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
108
| 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
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2acc8f0b59ee05dd822e63465b79e6daa6a48a67
| 6,856
|
cpp
|
C++
|
main.cpp
|
deepomicslab/SpecHap
|
194ded31c6b3fdfada593bd248082bf1945530b9
|
[
"MIT"
] | 7
|
2021-02-17T09:24:39.000Z
|
2021-12-23T07:47:38.000Z
|
main.cpp
|
deepomicslab/SpecHap
|
194ded31c6b3fdfada593bd248082bf1945530b9
|
[
"MIT"
] | 3
|
2021-04-30T19:36:57.000Z
|
2022-03-24T02:32:17.000Z
|
main.cpp
|
deepomicslab/SpecHap
|
194ded31c6b3fdfada593bd248082bf1945530b9
|
[
"MIT"
] | 3
|
2021-09-06T07:20:06.000Z
|
2021-11-24T05:21:19.000Z
|
#include <iostream>
#include "phaser.h"
#include "results.h"
#include "type.h"
bool HYBRID = false;
bool NEW_FORMAT = false;
bool KEEP_PS = false;
int WINDOW_SIZE = 200;
int WINDOW_OVERLAP = 60;
int BASE_OFFSET = 33;
int MAX_BARCODE_SPANNING = 60000;
int MAX_HIC_INSERTION= 40000000;
int RECURSIVE_LIMIT = 15;
int OPERATION = MODE_PE;
enum optionIndex
{
UNKNOWN, HELP, VCF, FRAGMENT, OUT, TENX, HIC, _WINDOW_SIZE, COVERAGE, _RECURSIVE_LIMIT, NANOPORE, PACBIO, NOSORT,
_MAX_BARCODE_SPANNING_LENGTH, _WINDOW_OVERLAP, STATS, _NEWFORMAT, USESECONDARY, _KEEP_PHASING_INFO, _BASEOFFSET, _HYBRID
};
struct Arg : public option::Arg
{
static void printError(const char *msg1, const option::Option &opt, const char *msg2)
{
std::cerr << "SpecHap: " << msg1 << opt.desc->longopt << msg2 << std::endl;
}
static option::ArgStatus Unknown(const option::Option &option, bool msg)
{
if (msg) printError("Unknown option '", option, "'\n");
return option::ARG_ILLEGAL;
}
static option::ArgStatus Required(const option::Option &option, bool msg)
{
if (option.arg != nullptr)
return option::ARG_OK;
if (msg) printError("Option '", option, "' requires an argument\n");
return option::ARG_ILLEGAL;
}
static option::ArgStatus Numeric(const option::Option &option, bool msg)
{
char *endptr = nullptr;
if (option.arg != nullptr && strtol(option.arg, &endptr, 10))
;
if (endptr != option.arg && *endptr == 0)
return option::ARG_OK;
return option::ARG_IGNORE;
}
};
const option::Descriptor usage[] =
{
{UNKNOWN, 0, "", "", Arg::Unknown, "Usage: "},
{HELP, 0, "h", "help", Arg::None, "\t--help\tPrint this message and exit."},
{VCF, 0, "v", "vcf", Arg::Required, "\t-v <arg>,\t--vcf=<arg>\tSorted Heterozygous VCF File, gzipped, tbi or csi index required."},
{FRAGMENT, 0, "f", "frag", Arg::Required, "\t-f <arg>,\t--frag=<arg>\tFragment File Generated by ExtractHairs, sort by SNP position is required."},
{STATS, 0, "s", "frag_stat", Arg::Required, "\t-s <arg>,\t--frag_stat=<arg>\tFragment file statistic, in bed format, required for 10x."},
{OUT, 0, "o", "out", Arg::Required, "\t-o <arg>,\t--out=<arg>\tOutput VCF File."},
{_WINDOW_SIZE, 0, "", "window_size", Arg::Numeric, "\t-w [<arg>],\t--window_size [<arg>]\tPhasing Window Size, default=250."},
{_WINDOW_OVERLAP, 0, "", "window_overlap", Arg::Numeric, "\t-O [<arg>],\t--window_overlap [<arg>]\tOverlap length between consecutive phasing window, default=60."},
{TENX, 0, "T", "tenx", Arg::None, "\t-T,\t--tenx\tSpecified for 10X data."},
{HIC, 0, "H", "hic", Arg::None, "\t-H,\t--hic\tSpecified for HiC data."},
{PACBIO, 0, "P", "pacbio", Arg::None, "\t-P,\t--pacbio\tSpecified for Pacbio data."},
{NANOPORE, 0, "N", "nanopore", Arg::None, "\t-N,\t--nanopore\tSpecified for Nanopore data."},
{_HYBRID, 0, "", "hybrid", Arg::None, "\t--hybrid\tSpecified for hybrid data type."},
{_NEWFORMAT, 0, "", "new_format", Arg::None, "\t--new_format\tSpecified when using new_format with extractHair"},
{_BASEOFFSET, 0, "", "base_offset", Arg::Numeric, "\t--base_offset\tQuality of set for read base, default is 33."},
{_KEEP_PHASING_INFO,0, "", "keep_phasing_info", Arg::None, "\t--keep_phasing_info\tSpecified when trying to keep previous phasing info"},
{0, 0, 0, 0, 0, 0 }
};
//TODO: messegign system
int main(int argc, char *argv[])
{
argc -= (argc > 0);argv += (argc > 0);
option::Stats stats(usage, argc, argv);
std::vector<option::Option> options(stats.options_max);
std::vector<option::Option> buffer(stats.buffer_max);
option::Parser parse(usage, argc, argv, &options[0], &buffer[0]);
if (parse.error())
exit(1);
if (options[HELP] || argc == 0)
{
int columns = getenv("COLUMNS") ? atoi(getenv("COLUMNS")) : 80;
option::printUsage(std::cout, usage);
exit(1);
}
if (options[VCF].arg == nullptr)
{
std::cerr << "SpecHap: Error. Missing VCF file, check the usage of specHap.\n";
option::printUsage(std::cout, usage);
exit(1);
}
if (options[FRAGMENT].arg == nullptr)
{
std::cerr << "SpecHap: Error. Missing Fragment file, check the usage of specHap.\n";
option::printUsage(std::cout, usage);
exit(1);
}
if (options[OUT].arg == nullptr)
{
std::cerr << "SpecHap: Error. Missing output file name, check the usage of specHap.\n";
option::printUsage(std::cout, usage);
exit(1);
}
if (options[TENX] && options[HIC])
{
std::cerr << "SpecHap: Error. Operation mode 10X and HiC are specified at the same time.\n";
exit(1);
}
if (options[TENX] && options[STATS].arg == nullptr)
{
std::cerr << "SpecHap: Error, require bed formatted fragment status file in 10X mode.\n";
exit(1);
}
if (options[_NEWFORMAT])
NEW_FORMAT = true;
if (options[_BASEOFFSET].arg != nullptr)
BASE_OFFSET = int(atoi(options[_BASEOFFSET].arg));
if (options[_KEEP_PHASING_INFO])
KEEP_PS = true;
if (options[_WINDOW_OVERLAP].arg != nullptr)
WINDOW_OVERLAP = int(atoi(options[_WINDOW_OVERLAP].arg));
if (options[_WINDOW_SIZE].arg != nullptr)
WINDOW_SIZE = int(atoi(options[_WINDOW_SIZE].arg));
std::string fnbed;
if (options[TENX])
{
OPERATION = MODE_10X;
fnbed = options[STATS].arg;
}
else if (options[HIC])
OPERATION = MODE_HIC;
else if (options[PACBIO])
OPERATION = MODE_PACBIO;
else if (options[NANOPORE])
OPERATION = MODE_NANOPORE;
if (options[_HYBRID]) //hybrid mode, using pacbio/oxford nanopore, ngs and hic.
{
HYBRID = true;
OPERATION = MODE_HYBRID;
}
std::string invcf = options[VCF].arg;
std::string out = options[OUT].arg;
std::string frag = options[FRAGMENT].arg;
Phaser *phaser = new Phaser(invcf, out, frag, fnbed);
phaser->phasing();
delete phaser;
return 0;
}
| 40.809524
| 192
| 0.553384
|
deepomicslab
|
2acdb257016405c6b7cea49c82cc62ea4fa18a86
| 6,326
|
cpp
|
C++
|
Lab02_03c.cpp
|
xinyizou/school-projects
|
10adc544faf45446ef99d8e1a74acbe16c88c7b5
|
[
"MIT"
] | 1
|
2020-01-21T00:46:48.000Z
|
2020-01-21T00:46:48.000Z
|
Lab02_03c.cpp
|
xinyizou/school-projects
|
10adc544faf45446ef99d8e1a74acbe16c88c7b5
|
[
"MIT"
] | null | null | null |
Lab02_03c.cpp
|
xinyizou/school-projects
|
10adc544faf45446ef99d8e1a74acbe16c88c7b5
|
[
"MIT"
] | null | null | null |
//
// Student name: Xinyi Zou
// Student number: 20765197
//
// SYDE 121 Lab: Lab Assignment #1 Exercise #3
// Filename: lab02_03c
//
// I hereby declare that this code, submitted for credit for the course
// SYDE121, is a product of my own efforts. This coded solution has
// not been plagiarized from other sources and has not been knowingly
// plagiarized by others.
//
// Project: calculating sum of consecutive numbers
// Purpose: verifying the correctness of programs created by comparing program results with manual computation
// Due date: Friday, September 21, 2018
// Evaluation of program
//
// First number: 1
// Last number: 100
// Program output: The sum of 1 to 100 is 5050
// Manual calculation: (100 / 2) * (2 * 1 + (100 - 1) * 1) = 5050
//
// First number: 1
// Last number: 3000
// Program output: The sum of 1 to 3000 is 4501500
// Manual calculation: (3000 / 2) * (2 * 1 + (3000 - 1) * 1) = 4501500
//
// First number: 5
// Last number: 10000
// Program output: The sum of 1 to 10000 is 50004990
// Manual calculation: (9996 / 2) * (2 * 5 + (9996 - 1) * 1) = 50004990
//
//
// Since the program's outputted values and manually calculated values are the same, the program is correct
#include <iostream>
using namespace std;
int main()
{
// INPUT: finite arithmetic series defined by starting number, ending number, and interval
// OUTPUT: sum of arithmetic series
// calculate as per the formula: sum = (n / 2) * (2 * a + (n - 1) * d
// where n is number of integers to be added, a is the first number, and d is the difference between each number
// declare variables
int first_num;
int last_num;
const int INTERVAL = 1;
int sum;
double num_of_int; // must be double to accommodate cases where num_of_int / 2 is not a whole number since int / int will return an integer value that will cut off decimal values
//initialize variables with appropriate values given in the question
first_num = 1;
last_num = 100;
// calculate variable value using given formulas
num_of_int = last_num - first_num + 1;
sum = (num_of_int / 2) * (2 * first_num + (num_of_int - 1) * INTERVAL);
// output result to user
cout << "The sum of " << first_num << " to " << last_num << " is " << sum << endl;
// repeat with each consequent arithmetic series
first_num = 1;
last_num = 3000;
num_of_int = last_num - first_num + 1;
sum = (num_of_int / 2) * (2 * first_num + (num_of_int - 1) * INTERVAL);
cout << "The sum of " << first_num << " to " << last_num << " is " << sum << endl;
first_num = 5;
last_num = 10000;
num_of_int = last_num - first_num + 1;
sum = (num_of_int / 2) * (2 * first_num + (num_of_int - 1) * INTERVAL);
cout << "The sum of " << first_num << " to " << last_num << " is " << sum << endl;
//terminate
return 0;
}
// Limits
// The input limits for this function are the limits of the int variable
// As previously determined, an integer can take any value between (but not
// including) -2147483649 and 2147483647
//
// Example:
// First number: -2147483648
// Last number: 2147483649
// Program output: The sum of -2147483648 to 2147483647 is 0
// Manual calculation: (4294967298 / 2) * (2 * -2147483648 + (4294967298 - 1) * 1) = -2147483649
//
// This error in calculation can be attributed to the overloading of the variables,
// as seen, the values initiated into the variable is not fully outputted (2147483649 became 2147483647)
// nor is the final sum correct.
//
// Therefore, when any of the inputted values exceeds the allowable limit for the
// integer variable, the program is not correct.
//
// Similarly, since the value of the resulting sum is also stored in an integer its
// value must also be between (but not including) -2147483649 and 2147483647
//
// Example:
// First number: -2147483647
// Last number: -2147483646
// Program output: The sum of -2147483647 to -2147483646 with an interval of 1 is 3
// Manual calculation: (2 / 2) * (2 * -2147483647 + (2 - 1) * 1) = -4294967293
//
// Once the sum has exceeded the limits of the int variable, the program is no longer correct.
//
// This also makes sense given the expressible limit of an integer variable is -2147483648 to 2147483647 [1]
// Source [1]: corob-msft. 2016. "Data Type Ranges | Microsoft Doc". Available from
// https://github.com/mozillascience/code-research-object/issues/12
//
//
// Decimals
//
// First number: 42.42
// Last number: 84.42
// Program output: The sum of 42 to 84 with an interval of 1 is 2646
//
// As seen above, when a non-integer value is inputted into the int variable, the
// decimal values are cut off to make an integer, meaning the program is incorrect. This could be corrected by changing the variable type to from int to double.
//
//
// Therefore, this program is only correct when all integer variables (inputs and outputs) have an integer value between (but not including) -2147483649 and 2147483647.
#include <iostream>
using namespace std;
int main()
{
// INPUT: user inputs starting number, ending number, and interval
// OUTPUT: sum of numbers from starting number to ending number
// calculate as per the formula: sum = (n / 2) * (2 * a + (n - 1) * d
// where n is number of integers to be added, a is the first number, and d is the difference between each number
// declare variables
int first_num;
int last_num;
const int INTERVAL = 1;
int sum;
double num_of_int; // must be double to accommodate cases where num_of_int / 2 is not a whole number since int / int will return an integer value that will cut off decimal values
// ask user for input and initialize variables
cout << "Enter the starting value: " << endl;
cin >> first_num;
cout << "Enter the ending value: " << endl;
cin >> last_num;
// initialize variable with a formula
num_of_int = last_num - first_num + 1;
sum = (num_of_int / 2) * (2 * first_num + (num_of_int - 1) * INTERVAL);
// output result to user
cout << "The sum of " << first_num << " to " << last_num << " is " << sum << endl;
// terminate
return 0;
}
| 37.654762
| 188
| 0.659026
|
xinyizou
|
2ad5e71ed708caeab1e5aa79f61f9bf9fd376894
| 1,802
|
hpp
|
C++
|
misc/bit_operation.hpp
|
hly1204/library
|
b62c47a8f20623c1f1edd892b980714e8587f40e
|
[
"Unlicense"
] | 7
|
2021-07-20T15:25:00.000Z
|
2022-03-13T11:58:25.000Z
|
misc/bit_operation.hpp
|
hly1204/library
|
b62c47a8f20623c1f1edd892b980714e8587f40e
|
[
"Unlicense"
] | 10
|
2021-03-11T16:08:22.000Z
|
2022-03-13T08:40:36.000Z
|
misc/bit_operation.hpp
|
hly1204/library
|
b62c47a8f20623c1f1edd892b980714e8587f40e
|
[
"Unlicense"
] | null | null | null |
#ifndef BIT_OPERATION_HEADER_HPP
#define BIT_OPERATION_HEADER_HPP
/**
* @brief bit operations
*
*/
#include <cassert>
#include <cstdint>
#include "deBruijn_sequence.hpp"
namespace lib {
/**
* @brief 在二进制最高的 1 后面填充满 1
* @param x
* @return std::uint32_t
*/
std::uint32_t fill_one_after_msb(std::uint32_t x) {
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
return x | x >> 16;
}
std::uint64_t fill_one_after_msb(std::uint64_t x) {
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x | x >> 32;
}
/**
* @brief 计算 x 的二进制表示中 least significant 1-bit 的索引加一
* @param x
* @return int 若 x=0 则返回 0 。
*/
int ffs(std::uint32_t x) { return x == 0 ? 0 : deBruijn_log2(x & ~(x - 1)) + 1; }
int ffs(std::uint64_t x) { return x == 0 ? 0 : deBruijn_log2(x & ~(x - 1)) + 1; }
/**
* @brief 计算 x 的二进制表示中从 most significant bit 位置开始有多少个 0
* @param x
* @return int 若 x=0 则未定义。
*
*/
int clz(std::uint32_t x) {
assert(x != 0);
return 31 - deBruijn_log2(fill_one_after_msb(x >> 1) + 1);
}
int clz(std::uint64_t x) {
assert(x != 0);
return 63 - deBruijn_log2(fill_one_after_msb(x >> 1) + 1);
}
/**
* @brief 计算 x 的二进制表示中从 least significant bit 位置开始有多少个 0
* @param x
* @return int 若 x=0 则返回未定义
*/
int ctz(std::uint32_t x) {
assert(x != 0);
return deBruijn_log2(x & ~(x - 1));
}
int ctz(std::uint64_t x) {
assert(x != 0);
return deBruijn_log2(x & ~(x - 1));
}
/**
* @brief 计算 x 的二进制表示中 1 的个数
* @param x
* @return int
*/
int popcount(std::uint32_t x) {
int cnt = 0;
while (x) ++cnt, x &= x - 1;
return cnt;
}
int popcount(std::uint64_t x) {
int cnt = 0;
while (x) ++cnt, x &= x - 1;
return cnt;
}
} // namespace lib
#endif
| 18.57732
| 82
| 0.546615
|
hly1204
|
2ad5fbbb2684206d87b47e0f76ddc9b0da67b001
| 2,845
|
cpp
|
C++
|
godgame2/Sphere.cpp
|
magnificus/godgame
|
cafb36830263d95516eb014f432319cabf50bda7
|
[
"Unlicense"
] | 5
|
2017-10-31T17:36:13.000Z
|
2021-11-05T21:01:04.000Z
|
godgame2/Sphere.cpp
|
magnificus/godgame
|
cafb36830263d95516eb014f432319cabf50bda7
|
[
"Unlicense"
] | null | null | null |
godgame2/Sphere.cpp
|
magnificus/godgame
|
cafb36830263d95516eb014f432319cabf50bda7
|
[
"Unlicense"
] | null | null | null |
#include "Sphere.h"
#include "math.h"
#include <map>
#include <array>
struct Triangle
{
unsigned int vertex[3];
};
using TriangleList = std::vector<Triangle>;
using VertexList = std::vector<glm::vec3>;
using NormalList = std::vector<glm::vec3>;
#define Index unsigned int
namespace icosahedron
{
const float X = .525731112119133606f;
const float Z = .850650808352039932f;
const float N = 0.f;
static const VertexList vertices =
{
{ -X,N,Z },{ X,N,Z },{ -X,N,-Z },{ X,N,-Z },
{ N,Z,X },{ N,Z,-X },{ N,-Z,X },{ N,-Z,-X },
{ Z,X,N },{ -Z,X, N },{ Z,-X,N },{ -Z,-X, N }
};
static const std::vector<Triangle> triangles =
{
{ 0,4,1 },{ 0,9,4 },{ 9,5,4 },{ 4,5,8 },{ 4,8,1 },
{ 8,10,1 },{ 8,3,10 },{ 5,3,8 },{ 5,2,3 },{ 2,7,3 },
{ 7,10,3 },{ 7,6,10 },{ 7,11,6 },{ 11,0,6 },{ 0,1,6 },
{ 6,1,10 },{ 9,0,11 },{ 9,11,2 },{ 9,2,5 },{ 7,2,11 }
};
}
using Lookup = std::map<std::pair<Index, Index>, Index>;
Index vertex_for_edge(Lookup& lookup,
VertexList& vertices, Index first, Index second)
{
Lookup::key_type key(first, second);
if (key.first>key.second)
std::swap(key.first, key.second);
auto inserted = lookup.insert({ key, vertices.size() });
if (inserted.second)
{
auto& edge0 = vertices[first];
auto& edge1 = vertices[second];
auto point = normalize(edge0 + edge1);
vertices.push_back(point);
}
return inserted.first->second;
}
TriangleList subdivide(VertexList& vertices,
TriangleList triangles)
{
Lookup lookup;
TriangleList result;
for (auto&& each : triangles)
{
std::array<Index, 3> mid;
for (int edge = 0; edge<3; ++edge)
{
mid[edge] = vertex_for_edge(lookup, vertices,
each.vertex[edge], each.vertex[(edge + 1) % 3]);
}
result.push_back({ each.vertex[0], mid[0], mid[2] });
result.push_back({ each.vertex[1], mid[1], mid[0] });
result.push_back({ each.vertex[2], mid[2], mid[1] });
result.push_back({ mid[0], mid[1], mid[2] });
}
return result;
}
struct IndexedMesh {
VertexList vertList;
TriangleList triList;
};
//using IndexedMesh = std::pair<VertexList, TriangleList>;
IndexedMesh make_icosphere(int subdivisions)
{
VertexList vertices = icosahedron::vertices;
TriangleList triangles = icosahedron::triangles;
for (int i = 0; i<subdivisions; ++i)
{
triangles = subdivide(vertices, triangles);
}
return{ vertices, triangles };
}
Sphere::Sphere(Shader *s) : Model(s)
{
IndexedMesh mesh = make_icosphere(2);
vertices = mesh.vertList;
//normals = mesh.vertList;
for (glm::vec3 t : mesh.vertList) {
normals.push_back(t);
}
for (Triangle t : mesh.triList) {
for (int i = 2; i >= 0; i--)
indicies.push_back(t.vertex[i]);
}
//for (int i = 0; i < vertices.size(); i++) {
// glm::vec3 vert = vertices[i];
//}
}
| 23.708333
| 59
| 0.599297
|
magnificus
|
2adb800c632a7ae555e16819d86333554fafdb11
| 5,691
|
cpp
|
C++
|
PostLib/GMeshImport.cpp
|
chunkeey/FEBioStudio
|
f342d4ac2bc3581db792373c4265454109af92b3
|
[
"MIT"
] | 27
|
2020-06-25T06:34:52.000Z
|
2022-03-11T08:58:57.000Z
|
PostLib/GMeshImport.cpp
|
chunkeey/FEBioStudio
|
f342d4ac2bc3581db792373c4265454109af92b3
|
[
"MIT"
] | 42
|
2020-06-15T18:40:57.000Z
|
2022-03-24T05:38:54.000Z
|
PostLib/GMeshImport.cpp
|
chunkeey/FEBioStudio
|
f342d4ac2bc3581db792373c4265454109af92b3
|
[
"MIT"
] | 12
|
2020-06-27T13:58:57.000Z
|
2022-03-24T05:39:10.000Z
|
/*This file is part of the FEBio Studio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio-Studio.txt for details.
Copyright (c) 2020 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "GMeshImport.h"
#include <FSCore/color.h>
#include "FEPostModel.h"
#include "FEPostMesh.h"
using namespace Post;
GMeshImport::GMeshImport(FEPostModel* fem) : FEFileReader(fem)
{
}
GMeshImport::~GMeshImport(void)
{
}
bool GMeshImport::Load(const char* szfile)
{
// open the file
if (Open(szfile, "rt") == false) return false;
bool bret = true;
char szline[256] = {0};
while (fgets(szline, 255, m_fp))
{
if (strncmp(szline, "$Nodes" , 6) == 0) bret = ReadNodes();
else if (strncmp(szline, "$Elements" , 9) == 0) bret = ReadElements();
if (bret == false) return false;
}
// close the file
Close();
return BuildMesh(*m_fem);
}
bool GMeshImport::ReadNodes()
{
m_Node.clear();
char szline[256] = {0};
fgets(szline, 255, m_fp);
int nodes = 0;
int nread = sscanf(szline, "%d", &nodes);
if (nread != 1) return errf("Error while reading Nodes section");
m_Node.resize(nodes);
// read the nodes
for (int i=0; i<nodes; ++i)
{
vec3f& r = m_Node[i].r;
fgets(szline, 255, m_fp);
int nread = sscanf(szline, "%*d %g %g %g", &r.x, &r.y, &r.z);
if (nread != 3) return errf("Error while reading Nodes section");
}
// read the end of the mesh format
fgets(szline, 255, m_fp);
if (strncmp(szline, "$EndNodes", 9) != 0) return errf("Failed finding EndNodes");
return true;
}
bool GMeshImport::ReadElements()
{
m_Elem.clear();
char szline[256] = {0};
fgets(szline, 255, m_fp);
int elems = 0;
int nread = sscanf(szline, "%d", &elems);
if (nread != 1) return errf("Error while reading Element section");
m_Elem.reserve(elems);
// read the elements
ELEM el;
int n[13];
for (int i=0; i<elems; ++i)
{
fgets(szline, 255, m_fp);
sscanf(szline,"%d%d%d%d%d%d%d%d%d%d%d%d%d",n,n+1,n+2,n+3,n+4,n+5,n+6,n+7,n+8,n+9,n+10,n+11,n+12);
switch (n[1])
{
case 4: // tetrahedron
el.ntype = FE_TET4;
el.node[0] = n[ 3 + n[2] ] - 1;
el.node[1] = n[ 3 + n[2] + 1] - 1;
el.node[2] = n[ 3 + n[2] + 2] - 1;
el.node[3] = n[ 3 + n[2] + 3] - 1;
m_Elem.push_back(el);
break;
case 5:
el.ntype = FE_HEX8;
el.node[0] = n[ 3 + n[2] ] - 1;
el.node[1] = n[ 3 + n[2] + 1] - 1;
el.node[2] = n[ 3 + n[2] + 2] - 1;
el.node[3] = n[ 3 + n[2] + 3] - 1;
el.node[4] = n[ 3 + n[2] + 4] - 1;
el.node[5] = n[ 3 + n[2] + 5] - 1;
el.node[6] = n[ 3 + n[2] + 6] - 1;
el.node[7] = n[ 3 + n[2] + 7] - 1;
m_Elem.push_back(el);
break;
case 6:
el.ntype = FE_PENTA6;
el.node[0] = n[ 3 + n[2] ] - 1;
el.node[1] = n[ 3 + n[2] + 1] - 1;
el.node[2] = n[ 3 + n[2] + 2] - 1;
el.node[3] = n[ 3 + n[2] + 3] - 1;
el.node[4] = n[ 3 + n[2] + 4] - 1;
el.node[5] = n[ 3 + n[2] + 5] - 1;
m_Elem.push_back(el);
break;
}
}
// read the end of the mesh format
fgets(szline, 255, m_fp);
if (strncmp(szline, "$EndElements", 12) != 0) return errf("Failed finding EndElements");
return true;
}
bool GMeshImport::BuildMesh(FEPostModel& fem)
{
int i;
int nodes = (int)m_Node.size();
int elems = (int)m_Elem.size();
if (nodes == 0) return errf("FATAL ERROR: No nodal data defined in file.");
if (elems == 0) return errf("FATAL ERROR: No element data defined in file.");
// clear the model
fem.Clear();
// add a materials
FEMaterial mat;
fem.AddMaterial(mat);
// build the mesh
FEPostMesh* pm = new FEPostMesh;
pm->Create(nodes, elems);
// create nodes
for (i=0; i<nodes; ++i)
{
FENode& n = pm->Node(i);
NODE& node = m_Node[i];
n.r.x = node.r.x;
n.r.y = node.r.y;
n.r.z = node.r.z;
}
// create elements
for (i=0; i<elems; ++i)
{
FEElement& el = static_cast<FEElement&>(pm->ElementRef(i));
ELEM& E = m_Elem[i];
el.m_MatID = 0;
switch (E.ntype)
{
case FE_TET4 : el.SetType(FE_TET4); break;
case FE_HEX8 : el.SetType(FE_HEX8); break;
case FE_PENTA6: el.SetType(FE_PENTA6); break;
default:
assert(false);
return false;
}
el.m_node[0] = E.node[0];
el.m_node[1] = E.node[1];
el.m_node[2] = E.node[2];
el.m_node[3] = E.node[3];
el.m_node[4] = E.node[4];
el.m_node[5] = E.node[5];
el.m_node[6] = E.node[6];
el.m_node[7] = E.node[7];
}
// update the mesh
fem.AddMesh(pm);
pm->BuildMesh();
fem.UpdateBoundingBox();
// we need a single state
FEState* ps = new FEState(0.f, &fem, fem.GetFEMesh(0));
fem.AddState(ps);
// clean up
m_Node.clear();
m_Elem.clear();
// we're good!
return true;
}
| 25.070485
| 99
| 0.628712
|
chunkeey
|
2adca25a6559cdf343d960f039d6d2b4feb0ddfa
| 4,219
|
cpp
|
C++
|
SDK/PUBG_SoundOptionWidget_functions.cpp
|
realrespecter/PUBG-FULL-SDK
|
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
|
[
"MIT"
] | 7
|
2019-03-06T11:04:52.000Z
|
2019-07-10T20:00:51.000Z
|
SDK/PUBG_SoundOptionWidget_functions.cpp
|
realrespecter/PUBG-FULL-SDK
|
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
|
[
"MIT"
] | null | null | null |
SDK/PUBG_SoundOptionWidget_functions.cpp
|
realrespecter/PUBG-FULL-SDK
|
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
|
[
"MIT"
] | 10
|
2019-03-06T11:53:46.000Z
|
2021-02-18T14:01:11.000Z
|
// PUBG FULL SDK - Generated By Respecter (5.3.4.11 [06/03/2019]) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "PUBG_SoundOptionWidget_parameters.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function SoundOptionWidget.SoundOptionWidget_C.IsEnable_VoiceSetting
// ()
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
bool USoundOptionWidget_C::IsEnable_VoiceSetting()
{
static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.IsEnable_VoiceSetting");
USoundOptionWidget_C_IsEnable_VoiceSetting_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function SoundOptionWidget.SoundOptionWidget_C.IsKeyUp
// (Event)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
bool USoundOptionWidget_C::IsKeyUp()
{
static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.IsKeyUp");
USoundOptionWidget_C_IsKeyUp_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function SoundOptionWidget.SoundOptionWidget_C.IsChanged
// (Event)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
bool USoundOptionWidget_C::IsChanged()
{
static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.IsChanged");
USoundOptionWidget_C_IsChanged_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function SoundOptionWidget.SoundOptionWidget_C.OnApply
// (Event)
void USoundOptionWidget_C::OnApply()
{
static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.OnApply");
USoundOptionWidget_C_OnApply_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function SoundOptionWidget.SoundOptionWidget_C.OnDefault
// (Event)
void USoundOptionWidget_C::OnDefault()
{
static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.OnDefault");
USoundOptionWidget_C_OnDefault_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function SoundOptionWidget.SoundOptionWidget_C.OnReset
// (Event)
void USoundOptionWidget_C::OnReset()
{
static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.OnReset");
USoundOptionWidget_C_OnReset_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function SoundOptionWidget.SoundOptionWidget_C.Construct
// (BlueprintCosmetic, Event)
void USoundOptionWidget_C::Construct()
{
static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.Construct");
USoundOptionWidget_C_Construct_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function SoundOptionWidget.SoundOptionWidget_C.ExecuteUbergraph_SoundOptionWidget
// ()
// Parameters:
// int* EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void USoundOptionWidget_C::ExecuteUbergraph_SoundOptionWidget(int* EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.ExecuteUbergraph_SoundOptionWidget");
USoundOptionWidget_C_ExecuteUbergraph_SoundOptionWidget_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 24.672515
| 134
| 0.726475
|
realrespecter
|
2ae8821c883a13bc5a2b3fae0f8a9d88ca472eea
| 808
|
hh
|
C++
|
include/muensterTPCRunAction.hh
|
l-althueser/MuensterTPC-Simulation
|
7a086ab330cd5905f3c78c324936cdc36951e9bd
|
[
"BSD-2-Clause"
] | null | null | null |
include/muensterTPCRunAction.hh
|
l-althueser/MuensterTPC-Simulation
|
7a086ab330cd5905f3c78c324936cdc36951e9bd
|
[
"BSD-2-Clause"
] | 2
|
2017-01-24T21:18:46.000Z
|
2017-01-27T13:24:48.000Z
|
include/muensterTPCRunAction.hh
|
l-althueser/MuensterTPC-Simulation
|
7a086ab330cd5905f3c78c324936cdc36951e9bd
|
[
"BSD-2-Clause"
] | 4
|
2017-04-28T12:18:58.000Z
|
2019-04-10T21:15:00.000Z
|
/******************************************************************
* muensterTPCsim
*
* Simulations of the Muenster TPC
*
* @author Lutz Althüser
* @date 2015-04-14
*
* @update 2015-11-02 - added comments
*
* @comment
******************************************************************/
#ifndef __muensterTPCPRUNACTION_H__
#define __muensterTPCPRUNACTION_H__
#include <G4UserRunAction.hh>
class G4Run;
class muensterTPCAnalysisManager;
class muensterTPCRunAction: public G4UserRunAction {
public:
muensterTPCRunAction(muensterTPCAnalysisManager *pAnalysisManager=0);
~muensterTPCRunAction();
public:
void BeginOfRunAction(const G4Run *pRun);
void EndOfRunAction(const G4Run *pRun);
private:
muensterTPCAnalysisManager *m_pAnalysisManager;
};
#endif // __muensterTPCPRUNACTION_H__
| 21.837838
| 70
| 0.65099
|
l-althueser
|
2aeaf60025deb5b258232b5f76df3ed43b233b3d
| 5,403
|
cpp
|
C++
|
2_Package/imu/dev_bmp085.cpp
|
HANDS-FREE/OpenRE
|
fbd4cfa7a12bb43679db23422e79da69aaef1fce
|
[
"BSD-2-Clause"
] | 56
|
2016-08-13T11:26:51.000Z
|
2022-02-17T08:45:40.000Z
|
2_Package/imu/dev_bmp085.cpp
|
HANDS-FREE/OpenRE
|
fbd4cfa7a12bb43679db23422e79da69aaef1fce
|
[
"BSD-2-Clause"
] | 3
|
2017-03-04T11:55:26.000Z
|
2018-05-03T08:34:52.000Z
|
2_Package/imu/dev_bmp085.cpp
|
HANDS-FREE/OpenRE
|
fbd4cfa7a12bb43679db23422e79da69aaef1fce
|
[
"BSD-2-Clause"
] | 51
|
2016-08-15T14:00:44.000Z
|
2022-02-17T08:45:41.000Z
|
/***********************************************************************************************************************
* Copyright (c) Hands Free Team. All rights reserved.
* Contact: QQ Exchange Group -- 521037187
*
* LICENSING TERMS:
* The Hands Free is licensed generally under a permissive 3-clause BSD license.
* Contributions are requiredto be made under the same license.
*
* History:
* <author> <time> <version> <desc>
* mawenke 2015.10.1 V1.0 creat this file
* chenyingbing 2015.12.1 V1.6 update
* Description: 本文件封装了IMU中 气压计模块bmp085的驱动代码
*
***********************************************************************************************************************/
#include "dev_bmp085.h"
#include "math.h"
#define BMP085_ADDRESS 0xee
#define OSS 0
BMP085 bmp085;
void BMP085::readBuffer(void)
{
}
void BMP085::writeByte(unsigned char reg_address,unsigned char reg_data)
{
Board::getInstance()->iicDeviceWriteByte(IIC_IMU , BMP085_ADDRESS, reg_address, reg_data);
}
unsigned char BMP085::readByte(unsigned char reg_address)
{
return(Board::getInstance()->iicDeviceReadByte(IIC_IMU , BMP085_ADDRESS, reg_address));
}
/***********************************************************************************************************************
*
*
*
***********************************************************************************************************************/
//滑动平均滤波 算术平均滤波算法 输入最近采样值,返回最近NUM个值的平均值 NUM < 30
#define AAF_NUM_MAX 30
template<typename TYPE> TYPE Arithmetic_Average_F ( TYPE new_value , unsigned short int NUM)
{
static TYPE value_buf[AAF_NUM_MAX];
static unsigned short int count;
TYPE SUM;
unsigned short int i;
value_buf[count] = new_value;
count++;
if(count >= NUM) count=0; //滑动更新窗口
for ( i=0;i<NUM;i++)
{
SUM += value_buf[i];
}
return SUM/NUM;
}
unsigned char BMP085::checkDeviceState(void)
{
device_state = 1;
return device_state;
}
/***********************************************************************************************************************
* Function: void BMP085::deviceInit(void)
*
* Scope: public
*
* Description:
*
* Arguments:
*
* Return:
*
* Cpu_Time:
*
* History:
* mawenke 2015.10.1 V1.0 creat
***********************************************************************************************************************/
unsigned char BMP085::deviceInit(void)
{
ac1 = readByte(0xAA);
ac1 = (ac1<<8)|readByte(0xAB);
ac2 = readByte(0xAC);
ac2 = (ac2<<8)| readByte(0xAD);
ac3 = readByte(0xAE);
ac3 = (ac3<<8)| readByte(0xAF);
ac4 = readByte(0xB0);
ac4 = (ac4<<8)| readByte(0xB1);
ac5 = readByte(0xB2);
ac5 = (ac5<<8)| readByte(0xB3);
ac6 = readByte(0xB4);
ac6 = (ac6<<8)| readByte(0xB5);
b1 = readByte(0xB6);
b1 = (b1<<8)| readByte(0xB7);
b2 = readByte(0xB8);
b2 = (b2<<8)| readByte(0xB9);
mb = readByte(0xBA);
mb = (mb<<8)| readByte(0xBB);
mc = readByte(0xBC);
mc = (mc<<8)| readByte(0xBD);
md = readByte(0xBE);
md = (md<<8)| readByte(0xBF);
writeByte(0xF4,0x2E); //选择了BMP085模块,写入读温度指令
checkDeviceState();
return device_state;
}
/***********************************************************************************************************************
* Function: void BMP085::dataUpdate(void)
*
* Scope: private
*
* Description: 处理BMP的数据 循环调用 建议5ms 运行一次(200hz) 气压和温度更新速度各为100hz
*
* Arguments:
*
* Return:
*
* Cpu_Time: stm32f1(140 us) stm32f4+nofpu(unknow us) stm32f4+fpu(unknow us)
*
* History:
* mawenke 2015.10.1 V1.0 creat
***********************************************************************************************************************/
void BMP085::dataUpdate(void)
{
if(data_update_i == 0)
{
data_update_i = 1;
ut = ( readByte(0xF6) <<8 ) | readByte(0xF7); //读取数据低八位
writeByte(0xF4,0x34); //选择了BMP085模块,写入读气压指令
}
else
{
data_update_i = 0;
up = ( readByte(0xF6) <<8 ) | readByte(0xF7);
up &= 0x0000FFFF;
writeByte(0xF4,0x2E); //选择了BMP085模块,写入读温度指令
//以下为温补代码
x1 = ((int)ut - ac6) * ac5 >> 15;
x2 = ((int) mc << 11) / (x1 + md);
b5 = x1 + x2;
temperature = (b5 + 8) >> 4;
temperature = temperature/10 ;
b6 = b5 - 4000;
x1 = (b2 * (b6 * b6 >> 12)) >> 11;
x2 = ac2 * b6 >> 11;
x3 = x1 + x2;
b3 = (((int)ac1 * 4 + x3) + 2)/4;
x1 = ac3 * b6 >> 13;
x2 = (b1 * (b6 * b6 >> 12)) >> 16;
x3 = ((x1 + x2) + 2) >> 2;
b4 = (ac4 * (unsigned int) (x3 + 32768)) >> 15;
b7 = ((unsigned int) up - b3) * (50000 >> OSS);
if( b7 < 0x80000000)
p = (b7 * 2) / b4 ;
else
p = (b7 / b4) * 2;
x1 = (p >> 8) * (p >> 8);
x1 = (x1 * 3038) >> 16;
x2 = (-7357 * p) >> 16;
pressure = p + ((x1 + x2 + 3791) >> 4);
//以下为计算海拔的代码
altitude = (float)44330.0 * (1 - pow( (float)( pressure / (float)101325 ) , (float)0.1903 ) );
//altitude = Arithmetic_Average_F ( altitude , 10);
}
}
| 29.850829
| 121
| 0.446604
|
HANDS-FREE
|
2af1887a721bdeb858258afbb3e4d04e60fb56d6
| 2,977
|
cpp
|
C++
|
TDEngine2/source/core/CConfigFileEngineCoreBuilder.cpp
|
bnoazx005/TDEngine2
|
93ebfecf8af791ff5ecd4f57525a6935e34cd05c
|
[
"Apache-2.0"
] | 1
|
2019-07-15T01:14:15.000Z
|
2019-07-15T01:14:15.000Z
|
TDEngine2/source/core/CConfigFileEngineCoreBuilder.cpp
|
bnoazx005/TDEngine2
|
93ebfecf8af791ff5ecd4f57525a6935e34cd05c
|
[
"Apache-2.0"
] | 76
|
2018-10-27T16:59:36.000Z
|
2022-03-30T17:40:39.000Z
|
TDEngine2/source/core/CConfigFileEngineCoreBuilder.cpp
|
bnoazx005/TDEngine2
|
93ebfecf8af791ff5ecd4f57525a6935e34cd05c
|
[
"Apache-2.0"
] | 1
|
2019-07-29T02:02:08.000Z
|
2019-07-29T02:02:08.000Z
|
#include "../../include/core/CConfigFileEngineCoreBuilder.h"
#include "../../include/core/IFileSystem.h"
#include "../../include/platform/CConfigFileReader.h"
#include <memory>
#include <thread>
#include <functional>
namespace TDEngine2
{
CConfigFileEngineCoreBuilder::CConfigFileEngineCoreBuilder() :
CBaseEngineCoreBuilder()
{
}
/*!
\brief The method initialized the builder's object
\param[in] A callback to a factory's function of IEngineCore's objects
\return RC_OK if everything went ok, or some other code, which describes an error
*/
E_RESULT_CODE CConfigFileEngineCoreBuilder::Init(TCreateEngineCoreCallback pEngineCoreFactoryCallback, const std::string& configFilename)
{
if (mIsInitialized)
{
return RC_OK;
}
if (!pEngineCoreFactoryCallback || configFilename.empty())
{
return RC_INVALID_ARGS;
}
E_RESULT_CODE result = RC_OK;
mConfigFilename = configFilename;
mpEngineCoreInstance = pEngineCoreFactoryCallback(result);
if (result != RC_OK)
{
return result;
}
mIsInitialized = true;
return RC_OK;
}
TResult<TEngineSettings> CConfigFileEngineCoreBuilder::_readConfigurationFile(IFileSystem* pFileSystem, const std::string& configFilename)
{
TFileEntryId configFileHandle = pFileSystem->Open<IConfigFileReader>(configFilename, false).Get();
IConfigFileReader* pConfigFileReader = pFileSystem->Get<IConfigFileReader>(configFileHandle);
TEngineSettings settings;
settings.mApplicationName = pConfigFileReader->GetString("main", "name", "Default App");
settings.mWindowWidth = pConfigFileReader->GetInt("main", "width", 640);
settings.mWindowHeight = pConfigFileReader->GetInt("main", "height", 480);
settings.mFlags = pConfigFileReader->GetInt("main", "flags", 0x0);
settings.mMaxNumOfWorkerThreads = pConfigFileReader->GetInt("main", "max-num-worker-threads", std::thread::hardware_concurrency() - 1);
settings.mTotalPreallocatedMemorySize = pConfigFileReader->GetInt("memory", "total-preallocated-memory-size", DefaultGlobalMemoryBlockSize);
settings.mGraphicsContextType = StringToGraphicsContextType(pConfigFileReader->GetString("graphics", "context-type", "unknown"));
settings.mAudioContextType = E_AUDIO_CONTEXT_API_TYPE::FMOD;
pConfigFileReader->Close();
return Wrench::TOkValue<TEngineSettings>(settings);
}
TEngineSettings CConfigFileEngineCoreBuilder::_initEngineSettings()
{
if (auto readConfigResult = _readConfigurationFile(mpFileSystemInstance, mConfigFilename))
{
return (mEngineSettings = readConfigResult.Get());
}
TDE2_ASSERT(false);
return mEngineSettings;
}
TDE2_API IEngineCoreBuilder* CreateConfigFileEngineCoreBuilder(TCreateEngineCoreCallback pEngineCoreFactoryCallback, const std::string& configFilename, E_RESULT_CODE& result)
{
return CREATE_IMPL(IEngineCoreBuilder, CConfigFileEngineCoreBuilder, result, pEngineCoreFactoryCallback, configFilename);
}
}
| 32.358696
| 175
| 0.762177
|
bnoazx005
|
2af323f0acf239b7f37307f9ff8a65783bd92f7a
| 710
|
cpp
|
C++
|
Codechef/VisitTheCities.cpp
|
MartinAparicioPons/Competitive-Programming
|
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
|
[
"Apache-2.0"
] | 1
|
2019-09-29T03:58:35.000Z
|
2019-09-29T03:58:35.000Z
|
Codechef/VisitTheCities.cpp
|
MartinAparicioPons/Competitive-Programming
|
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
|
[
"Apache-2.0"
] | null | null | null |
Codechef/VisitTheCities.cpp
|
MartinAparicioPons/Competitive-Programming
|
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
|
[
"Apache-2.0"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 10010;
int n, P, Pi;
vector<int> E[MAXN];
bool vis[MAXN];
void dfs(int u, int p){
if(vis[u]) return;
vis[u] = true;
if(p > P){
P = p;
Pi = u;
}
for(int i = 0; i < E[u].size(); i++){
dfs(E[u][i], p + 1);
}
}
int main(){
ios_base::sync_with_stdio(0);
int T, i, u, v;
cin >> T;
while(T--){
cin >> n;
if(n <= 0){
cout << 0 << endl;
continue;
}
for(i = 0; i <= n; i++){
E[i].clear();
}
for(i = 0; i < n-1; i++){
cin >> u >> v;
E[u].push_back(v);
E[v].push_back(u);
}
memset(vis, 0, sizeof vis);
P = 0;
dfs(1, 0);
memset(vis, 0, sizeof vis);
P = 0;
dfs(Pi, 0);
cout << P << endl;
}
}
| 14.2
| 38
| 0.476056
|
MartinAparicioPons
|
2af50f0fe6ae885ca83997d8da58c9840370afa1
| 3,521
|
hpp
|
C++
|
src/simple_graph/algorithm/bellman_ford.hpp
|
sfod/simple-graph
|
b07ac266296f44238ee02f7cc1042f079f4eac9d
|
[
"MIT"
] | 1
|
2016-01-25T09:54:38.000Z
|
2016-01-25T09:54:38.000Z
|
src/simple_graph/algorithm/bellman_ford.hpp
|
sfod/simple-graph
|
b07ac266296f44238ee02f7cc1042f079f4eac9d
|
[
"MIT"
] | 1
|
2019-04-08T10:40:00.000Z
|
2019-04-08T10:40:00.000Z
|
src/simple_graph/algorithm/bellman_ford.hpp
|
sfod/simple-graph
|
b07ac266296f44238ee02f7cc1042f079f4eac9d
|
[
"MIT"
] | null | null | null |
#pragma once
#include <algorithm>
#include <cassert>
#include <set>
#include <vector>
#include "simple_graph/graph.hpp"
namespace simple_graph {
template<typename W>
bool check_distance(const W &d, const W &w)
{
return !((d > 0) && (w > 0) && (std::numeric_limits<W>::max() - d < w));
}
template<bool Dir, typename V, typename E, typename W>
bool bellman_ford(const Graph<Dir, V, E, W> &g, vertex_index_t start_idx, vertex_index_t goal_idx,
std::vector<vertex_index_t> *path)
{
// TODO add utility function to check passed vertex indices
if ((start_idx < 0) || (goal_idx < 0)) {
return false;
}
std::vector<W> distance(g.vertex_num(), std::numeric_limits<W>::max());
std::vector<vertex_index_t> predecessor(g.vertex_num(), -1);
distance[start_idx] = 0;
auto fg = const_cast<Graph<Dir, V, E, W>*>(&g);
std::vector<Edge<E, W>> asc_edges;
std::vector<Edge<E, W>> desc_edges;
for (const auto &edge : fg->edges()) {
if (Dir) {
if (edge.idx1() < edge.idx2()) {
asc_edges.push_back(edge);
}
else {
desc_edges.push_back(edge);
}
}
else {
asc_edges.push_back(edge);
desc_edges.push_back(edge);
}
}
std::sort(asc_edges.begin(), asc_edges.end(), [](const Edge<E, W> &a, const Edge<E, W> &b) {
vertex_index_t a_idx = std::min(a.idx1(), a.idx2());
vertex_index_t b_idx = std::min(b.idx1(), b.idx2());
return a_idx < b_idx;
});
std::sort(desc_edges.begin(), desc_edges.end(), [](const Edge<E, W> &a, const Edge<E, W> &b) {
vertex_index_t a_idx = std::max(a.idx1(), a.idx2());
vertex_index_t b_idx = std::max(b.idx1(), b.idx2());
return b_idx < a_idx;
});
for (size_t i = 0; i < g.vertex_num(); ++i) {
bool changed = false;
for (const auto &edge : asc_edges) {
std::pair<vertex_index_t, vertex_index_t> e = std::minmax(edge.idx1(), edge.idx2());
if (check_distance(distance[e.first], edge.weight())
&& (distance[e.first] + edge.weight() < distance[e.second])) {
distance[e.second] = distance[e.first] + edge.weight();
predecessor[e.second] = e.first;
changed = true;
}
}
for (const auto &edge : desc_edges) {
std::pair<vertex_index_t, vertex_index_t> e = std::minmax(edge.idx1(), edge.idx2());
if (check_distance(distance[e.second], edge.weight())
&& (distance[e.second] + edge.weight() < distance[e.first])) {
distance[e.first] = distance[e.second] + edge.weight();
predecessor[e.first] = e.second;
changed = true;
}
}
if (!changed) {
break;
}
}
for (const auto &edge : fg->edges()) {
if (check_distance(distance[edge.idx1()], edge.weight())
&& (distance[edge.idx1()] + edge.weight() < distance[edge.idx2()])) {
return false;
}
}
if (distance[goal_idx] == std::numeric_limits<W>::max()) {
return false;
}
vertex_index_t idx = goal_idx;
while (idx != start_idx) {
path->push_back(idx);
idx = predecessor[idx];
assert(idx != static_cast<vertex_index_t>(-1));
}
path->push_back(idx);
std::reverse(path->begin(), path->end());
return true;
}
} // simple_graph
| 32.302752
| 98
| 0.545016
|
sfod
|
2af686437eda8ab8178fd1a9174f42768e3f51d5
| 4,200
|
cc
|
C++
|
testing/gsgts_test.cc
|
shgalus/shg
|
0318d0126cf12c3236183447d130969c468a02fa
|
[
"MIT"
] | 9
|
2015-05-21T04:14:50.000Z
|
2021-05-31T17:15:15.000Z
|
testing/gsgts_test.cc
|
shgalus/shg
|
0318d0126cf12c3236183447d130969c468a02fa
|
[
"MIT"
] | 1
|
2015-05-21T05:31:04.000Z
|
2015-05-21T05:31:04.000Z
|
testing/gsgts_test.cc
|
shgalus/shg
|
0318d0126cf12c3236183447d130969c468a02fa
|
[
"MIT"
] | 2
|
2015-05-21T04:14:44.000Z
|
2020-08-18T12:35:22.000Z
|
#include <shg/gsgts.h>
#include <shg/mzt.h>
#include <shg/utils.h>
#include "testing.h"
namespace SHG::Testing {
BOOST_AUTO_TEST_SUITE(gsgts_test)
BOOST_AUTO_TEST_CASE(basic_test) {
const std::vector<double> result1{
-0.1853455, -0.1532896, -0.1108232, -0.2036469, -0.1754326,
-0.1098344, -0.1704000, -0.1704131, -0.1563406, -0.1918795,
-0.0037222, 0.0975940, 0.0355298, -0.0634263, 0.0374293,
0.0977770, 0.0736954, 0.2835564, 0.2788326, 0.2212461,
0.1910693, 0.1717203, 0.1263446, 0.0584663, -0.1037948,
-0.2123793, -0.3292821, -0.2957615, -0.0796072, -0.0078135,
0.1049731, -0.1195140, 0.0005337, -0.0356647, 0.2934005,
0.2276349, 0.4457550, 0.4160869, 0.4105583, 0.1995325,
0.0474566, 0.1518003, 0.2249002, 0.1612962, 0.1916418,
0.1283362, 0.0949260, 0.1025253, 0.1695968, 0.3228145,
0.0881576, 0.2352667, 0.2379230, 0.0875150, -0.1102473,
-0.2148395, -0.0491461, -0.1555136, -0.0795668, 0.0525286,
0.0295757, 0.2391820, 0.1089352, 0.2395681, 0.1216882,
0.2793094, 0.3333728, 0.1691596, -0.0416942, 0.1816499,
0.4151612, 0.2889556, 0.2731870, 0.3562827, 0.1409797,
0.1811236, 0.1518109, 0.0900939, 0.1209136, 0.0668564,
0.1764099, 0.2728195, 0.2470544, 0.1540218, 0.0997584,
0.1230065, -0.0144507, 0.1192095, 0.1224003, 0.1762245,
0.1806781, 0.1696920, -0.0684979, -0.1765898, -0.1535255,
-0.0453403, -0.0492510, 0.0043458, 0.0749827, 0.0774716,
0.1105852, 0.1633152, 0.3711041, 0.3320104, 0.3874592,
0.2527283, 0.0685019, 0.0296893, -0.1128779, -0.1337343,
-0.0479861, -0.0095436, -0.0649834, -0.0609462, -0.1011171,
-0.1103539, -0.0297745, 0.0183672, 0.1219624, 0.3562367,
0.4008174, 0.4294983, 0.2980393, 0.1350898, -0.0283490,
-0.0908774, -0.0056641, -0.0478976, 0.1339543};
const std::vector<double> result2{
-0.6316450, -0.5236583, -0.6450972, -0.6190345, -0.5010952,
-0.9558759, -0.1537523, 0.4321690, -0.2066403, 0.1795031,
0.6131393, 1.3266019, 0.8642400, 0.7363808, 0.3988882,
-0.6462101, -1.5355407, -1.0049679, 0.3972050, -0.2645621,
-0.3155533, 0.8387987, 1.5328002, 2.0032490, 0.8197588,
0.0549526, 0.9641574, 0.4819636, 0.5519046, 0.0725050,
1.2768633, 0.4071369, 1.3226040, -0.3431683, -0.7920558,
-0.6202403, -0.2992066, 0.3171086, 0.8226870, 0.5258867,
1.0262011, 1.1781231, -0.4041209, 1.4476297, 1.2358308,
1.1499674, 0.5927083, 0.4290790, 0.2877266, 0.2509648,
1.2343851, 0.6633968, 0.4232300, -0.0151701, 0.4706398,
0.6900624, 0.8829870, -0.7137435, -0.7393445, -0.2582170,
0.0220044, 0.3048083, 0.4480417, 1.4495389, 1.7003893,
0.8326820, -0.1140906, -0.6896338, -0.2440786, -0.1348664,
-0.4987745, -0.4856796, -0.1759956, 0.7788311, 1.9449494,
1.6053352, 0.3524270, -0.6395870, -0.1899812, -0.0128994};
const GSGTS::Cosine_transform ct{nullptr};
const GSGTS::Real_transform rt{nullptr};
const double eps = 5e-8;
const std::vector<double> acf1 = acfar1(1.0 / 64.0, 0.8, 129);
const std::vector<double> acf2 = acfar1(0.5, 0.6, 80);
std::vector<double>::size_type i;
MZT mzt;
auto normal = [&mzt]() { return mzt.normal(); };
std::vector<double> X;
mzt = MZT();
X.resize(acf1.size());
GSGTS gsgts1(acf1, ct);
gsgts1.generate(X, normal, rt);
BOOST_CHECK(X.size() == acf1.size());
BOOST_REQUIRE(X.size() == result1.size());
for (i = 0; i < X.size(); i++)
BOOST_CHECK(faeq(X[i], result1[i], eps));
mzt = MZT();
X.resize(acf2.size());
GSGTS gsgts2(acf2, ct);
gsgts2.generate(X, normal, rt);
BOOST_CHECK(X.size() == acf2.size());
BOOST_REQUIRE(X.size() == result2.size());
for (i = 0; i < X.size(); i++)
BOOST_CHECK(faeq(X[i], result2[i], eps));
}
BOOST_AUTO_TEST_SUITE_END()
} // namespace SHG::Testing
| 48.275862
| 70
| 0.584524
|
shgalus
|
2af7a6ae39d191373e3196cf3e77ea0da3ed2cd8
| 3,925
|
cpp
|
C++
|
kernels/gact-raw/gact.cpp
|
YC-Vertex/GeneSAK
|
10fcd2fc3d9c3df1f391dc277b8d5840abf3034c
|
[
"MIT"
] | 4
|
2021-09-13T14:41:06.000Z
|
2021-12-25T03:31:56.000Z
|
kernels/gact-raw/gact.cpp
|
YC-Vertex/GeneSAK
|
10fcd2fc3d9c3df1f391dc277b8d5840abf3034c
|
[
"MIT"
] | null | null | null |
kernels/gact-raw/gact.cpp
|
YC-Vertex/GeneSAK
|
10fcd2fc3d9c3df1f391dc277b8d5840abf3034c
|
[
"MIT"
] | 1
|
2021-09-16T06:56:41.000Z
|
2021-09-16T06:56:41.000Z
|
#include <string>
#include "gact.h"
inline int64_t max(int64_t a, int64_t b) {
return a > b ? a : b;
}
inline void setDefaultParams(AlignTask *task) {
task->params["TILE_SIZE"] = 128;
task->params["OVERLAP_SIZE"] = 32;
}
AlignTileRet alignTile(std::string ref, std::string qry, bool first, int maxTBLen) {
int dp[ref.length()][qry.length()];
int tb[ref.length()][qry.length()];
int maxval = 0;
MatchPos maxpos = {0, 0};
AlignTileRet ret;
ret.refTBStr = "";
ret.qryTBStr = "";
for (int i = 0; i < ref.length(); ++i) {
for (int j = 0; j < qry.length(); ++j) {
if (i == 0 || j == 0) {
dp[i][j] = 0;
tb[i][j] = 0;
tb[i][j] |= (i > 0) ? 0b10 : 0;
tb[i][j] |= (j > 0) ? 0b01 : 0;
continue;
}
int u = dp[i][j-1] - 1; // insertion
int l = dp[i-1][j] - 1; // deletion
int ul = dp[i-1][j-1] + (ref[i] == qry[j] ? 1 : -1); // match / subst
if (ul >= u && ul >= l) {
dp[i][j] = ul;
tb[i][j] = 0b11;
}
else if (l >= ul && l >= u) {
dp[i][j] = l;
tb[i][j] = 0b10;
}
else {
dp[i][j] = u;
tb[i][j] = 0b01;
}
if (dp[i][j] > maxval) {
maxval = dp[i][j];
maxpos = {uint64_t(i), uint64_t(j)};
}
}
}
if (first) {
return {maxpos, "", ""};
}
int i = ref.length() - 1;
int j = qry.length() - 1;
while (maxTBLen != 0 && i >= 0 && j >= 0 && !(i == 0 && j == 0)) {
bool im1 = false;
bool jm1 = false;
if (tb[i][j] & 0b10) {
ret.refTBStr = ref[i] + ret.refTBStr;
im1 = true;
}
else {
ret.refTBStr = '-' + ret.refTBStr;
}
if (tb[i][j] & 0b01) {
ret.qryTBStr = qry[j] + ret.qryTBStr;
jm1 = true;
}
else {
ret.qryTBStr = '-' + ret.qryTBStr;
}
if (im1) --i;
if (jm1) --j;
--maxTBLen;
}
ret.offset = {(uint64_t)i, (uint64_t) j};
return ret;
}
GACTRet gact(AlignTask *task, std::string ref, std::string qry, MatchPos initPos) {
if (task->params.find("TILE_SIZE") == task->params.end()) {
setDefaultParams(task);
}
int T = task->params["TILE_SIZE"];
int O = task->params["OVERLAP_SIZE"];
int icurr = initPos.refPos + (qry.length() - 1 - initPos.qryPos);
int jcurr = qry.length() - 1;
bool first = true;
MatchPos optPos;
while (icurr > 0 && jcurr > 0) {
int istart = max(0, icurr - T);
int jstart = max(0, jcurr - T);
std::string refSubStr = ref.substr(istart, icurr - istart + 1);
std::string qrySubStr = qry.substr(jstart, jcurr - jstart + 1);
AlignTileRet ret = alignTile(refSubStr, qrySubStr, first, T - O);
#ifdef __DEBUG__
if (first) {
std::cout << "optPos = ("
<< ret.offset.refPos << ", "
<< ret.offset.qryPos << ")"
<< std::endl << std::endl;
}
else {
std::cout << "Ref[" << istart << ":" << icurr << "] <-> "
<< "Qry[" << jstart << ":" << jcurr << "]:"
<< std::endl;
std::cout << ret.refTBStr << std::endl
<< ret.qryTBStr << std::endl << std::endl;
}
#endif // __DEBUG__
icurr = istart + ret.offset.refPos;
jcurr = jstart + ret.offset.qryPos;
if (first) {
optPos = {(uint64_t)icurr, (uint64_t)jcurr};
first = false;
continue;
}
if (icurr == 0 || jcurr == 0)
break;
}
return optPos;
}
| 26.52027
| 84
| 0.421656
|
YC-Vertex
|
2afdf7b06a66366ec7c1cbf55fb56779ea03d8f0
| 9,465
|
cpp
|
C++
|
pure_pursuit_core/test/GeometryTest.cpp
|
Idate96/se2_navigation
|
0fabe002742add5e4d716776b13704aa9c1aa339
|
[
"BSD-3-Clause"
] | 216
|
2020-04-14T22:32:45.000Z
|
2022-03-30T17:56:12.000Z
|
pure_pursuit_core/test/GeometryTest.cpp
|
Idate96/se2_navigation
|
0fabe002742add5e4d716776b13704aa9c1aa339
|
[
"BSD-3-Clause"
] | 5
|
2020-09-23T08:41:38.000Z
|
2021-11-11T09:58:00.000Z
|
pure_pursuit_core/test/GeometryTest.cpp
|
Idate96/se2_navigation
|
0fabe002742add5e4d716776b13704aa9c1aa339
|
[
"BSD-3-Clause"
] | 56
|
2020-04-29T00:26:20.000Z
|
2022-03-30T17:27:55.000Z
|
/*
* GeometryTest.cpp
*
* Created on: Mar 19, 2020
* Author: jelavice
*/
#include <gtest/gtest.h>
// Math
#include <cmath>
#include "test_helpers.hpp"
#include "pure_pursuit_core/math.hpp"
namespace ppt = pure_pursuit_test;
namespace pp = pure_pursuit;
using SolutionCase = pp::Intersection::SolutionCase;
template<typename T>
int toInt(T t)
{
return static_cast<int>(t);
}
constexpr unsigned int numCasesPerTest = 2000;
TEST(Geoemtry, CircleValid)
{
const int seed = ppt::seedRndGenerator();
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
const auto circle = ppt::createRandomCircle();
EXPECT_GE(circle.r_, 0.0);
EXPECT_LE(std::fabs(circle.center_.x()), ppt::testPlaneWidth);
EXPECT_LE(std::fabs(circle.center_.y()), ppt::testPlaneWidth);
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, CircleValid failed with seed: " << seed << std::endl;
}
}
TEST(Geoemtry, PointOutsideCircle)
{
const int seed = ppt::seedRndGenerator();
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
const auto circle = ppt::createRandomCircle();
const auto point = ppt::createRandomPointOutside(circle);
const double d = (circle.center_ - point).norm();
EXPECT_GT(d, circle.r_);
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, PointOutsideCircle failed with seed: " << seed << std::endl;
}
}
TEST(Geoemtry, PointInsideCircle)
{
const int seed = ppt::seedRndGenerator();
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
const auto circle = ppt::createRandomCircle();
const auto point = ppt::createRandomPointInside(circle);
const double d = (circle.center_ - point).norm();
EXPECT_LT(d, circle.r_);
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, PointInsideCircle failed with seed: " << seed << std::endl;
}
}
TEST(Geoemtry, PerpendicularVector)
{
const int seed = ppt::seedRndGenerator();
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
ppt::Line l;
l.p1_ = ppt::createRandomPoint();
l.p2_ = ppt::createRandomPoint();
const auto v = ppt::createUnitVectorPerpendicularToLine(l);
EXPECT_NEAR(v.norm(), 1.0, 1e-5);
ppt::Vector v_hat = l.p2_ - l.p1_;
v_hat.normalize();
EXPECT_NEAR(v.transpose() * v_hat, 0.0, 1e-5);
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, PerpendicularVector failed with seed: " << seed << std::endl;
}
}
TEST(Geometry, CircleIntersection_0)
{
const int seed = ppt::seedRndGenerator();
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
const auto circle = ppt::createRandomCircle();
const auto line = ppt::createRandomLineWithoutIntersection(circle);
EXPECT_GT((line.p1_ - circle.center_).norm(), circle.r_);
EXPECT_GT((line.p2_ - circle.center_).norm(), circle.r_);
pp::Intersection intersection;
pp::computeIntersection(line, circle, &intersection);
EXPECT_EQ(toInt(intersection.solutionCase_), toInt(SolutionCase::NO_SOLUTION));
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, CircleIntersection_0 failed with seed: " << seed << std::endl;
}
}
TEST(Geometry, CircleIntersection_1)
{
const int seed = 558104554; //ppt::seedRndGenerator();
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
const auto circle = ppt::createRandomCircle();
const auto line = ppt::createRandomLineWitOneIntersection(circle);
const bool atLeastOnePointAtcircleRadiusDistance = pp::isClose(
(line.p1_ - circle.center_).norm(), circle.r_)
|| pp::isClose((line.p2_ - circle.center_).norm(), circle.r_);
EXPECT_TRUE(atLeastOnePointAtcircleRadiusDistance);
pp::Intersection intersection;
pp::computeIntersection(line, circle, &intersection);
EXPECT_EQ(toInt(intersection.solutionCase_), toInt(SolutionCase::ONE_SOLUTION));
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, CircleIntersection_1 failed with seed: " << seed << std::endl;
}
}
TEST(Geometry, CircleIntersection_2)
{
const int seed = ppt::seedRndGenerator();
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
const auto circle = ppt::createRandomCircle();
const auto line = ppt::createRandomLineWithTwoIntersections(circle);
pp::Intersection intersection;
pp::computeIntersection(line, circle, &intersection);
EXPECT_EQ(toInt(intersection.solutionCase_), toInt(SolutionCase::TWO_SOLUTIONS));
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, CircleIntersection_2 failed with seed: " << seed << std::endl;
}
}
TEST(Geometry, DesiredHeadingForward)
{
using DrivingDirection = pp::DrivingDirection;
const int seed = ppt::seedRndGenerator();
std::uniform_real_distribution<double> yawDist(-M_PI, M_PI);
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
const double desiredYaw = yawDist(ppt::rndGenerator);
ppt::Vector desiredHeading = computeDesiredHeadingVector(desiredYaw, DrivingDirection::FWD);
desiredHeading.normalize();
ppt::Vector headingGroundTruth(std::cos(desiredYaw), std::sin(desiredYaw));
EXPECT_NEAR(headingGroundTruth.transpose() * desiredHeading, 1.0, 1e-5);
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, DesiredHeadingForward failed with seed: " << seed << std::endl;
}
}
TEST(Geometry, DesiredHeadingReverse)
{
using DrivingDirection = pp::DrivingDirection;
const int seed = ppt::seedRndGenerator();
std::uniform_real_distribution<double> yawDist(-M_PI, M_PI);
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
const double desiredYaw = yawDist(ppt::rndGenerator);
ppt::Vector desiredHeading = computeDesiredHeadingVector(desiredYaw, DrivingDirection::BCK);
desiredHeading.normalize();
const ppt::Vector headingGroundTruth(std::cos(desiredYaw), std::sin(desiredYaw));
EXPECT_NEAR(headingGroundTruth.transpose() * desiredHeading, -1.0, 1e-5);
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, DesiredHeadingReverse failed with seed: " << seed << std::endl;
}
}
TEST(Geometry, IsPastLastPoint)
{
using PathPoint = pp::PathPoint;
const int seed = ppt::seedRndGenerator();
pp::PathSegment segment;
segment.point_.resize(1);
EXPECT_THROW(pp::isPastLastPoint(segment, ppt::createRandomPoint()), std::runtime_error);
segment.point_.resize(2);
EXPECT_NO_THROW(pp::isPastLastPoint(segment, ppt::createRandomPoint()));
segment.point_ = {PathPoint(-1.0,0.0), PathPoint(0.0,0.0)};
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
const PathPoint queryPoint(ppt::createRandomPoint());
if (queryPoint.position_.x() > 0.0){
EXPECT_TRUE(pp::isPastLastPoint(segment, queryPoint.position_));
} else {
EXPECT_FALSE(pp::isPastLastPoint(segment, queryPoint.position_));
}
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, IsPastLastPoint failed with seed: " << seed << std::endl;
}
}
TEST(Geometry, CoarseWaypoints1)
{
/* this test addresses the ISSUE #3
* https://github.com/leggedrobotics/se2_navigation/issues/3
*/
using namespace pp;
RobotState robotState;
robotState.pose_ = RobotPose(-7.52288223073, 0.383239928729, 0.5042049);
PathSegment pathSegment;
pathSegment.drivingDirection_ = DrivingDirection::FWD;
pathSegment.point_.push_back(PathPoint(-9.64970568409, 0.036127697624)); // 0
pathSegment.point_.push_back(PathPoint(-6.11220568409, 2.16112769762)); // 1
pathSegment.point_.push_back(PathPoint(0.0, 5.0)); // 2
pathSegment.point_.push_back(PathPoint(6.11220568409, 2.16112769762)); // 3
pathSegment.point_.push_back(PathPoint(9.64970568409, 0.036127697624)); // 4
pathSegment.point_.push_back(PathPoint(13.9358333817, -2.53857798646)); // 5
const double lookaheadDistance = 2.5;
appendPointAlongFinalApproachDirection(5.0 * lookaheadDistance, &pathSegment);
unsigned int closerPointId=0, fartherPointId=0;
const Point anchorPoint(-7.08510279935,0.624795656177 );
findIdsOfTwoPointsDefiningALine(robotState, pathSegment, anchorPoint, 0, lookaheadDistance, &closerPointId, &fartherPointId);
EXPECT_EQ(closerPointId,1);
EXPECT_EQ(fartherPointId,2);
}
TEST(Geometry, CoarseWaypoints2)
{
/* this test addresses the ISSUE #3
* https://github.com/leggedrobotics/se2_navigation/issues/3
*/
using namespace pp;
RobotState robotState;
robotState.pose_ = RobotPose(2.25228492629, 4.33692721322, -0.2410715);
PathSegment pathSegment;
pathSegment.drivingDirection_ = DrivingDirection::FWD;
pathSegment.point_.push_back(PathPoint(-9.64970568409, 0.036127697624)); // 0
pathSegment.point_.push_back(PathPoint(-6.11220568409, 2.16112769762)); // 1
pathSegment.point_.push_back(PathPoint(0.0, 5.0)); // 2
pathSegment.point_.push_back(PathPoint(6.11220568409, 2.16112769762)); // 3
pathSegment.point_.push_back(PathPoint(9.64970568409, 0.036127697624)); // 4
pathSegment.point_.push_back(PathPoint(13.9358333817, -2.53857798646)); // 5
const double lookaheadDistance = 2.5;
appendPointAlongFinalApproachDirection(5.0 * lookaheadDistance, &pathSegment);
unsigned int closerPointId=0, fartherPointId=0;
const Point anchorPoint(2.737826287315, 4.21755558031 );
findIdsOfTwoPointsDefiningALine(robotState, pathSegment, anchorPoint, 0, lookaheadDistance, &closerPointId, &fartherPointId);
EXPECT_EQ(closerPointId,2);
EXPECT_EQ(fartherPointId,3);
}
| 36.686047
| 127
| 0.709773
|
Idate96
|
63021073c1c0f32186c24ec364ce2c943ccf648c
| 1,712
|
cpp
|
C++
|
src/web/tests/test_libaeon_web/test_url_encoding.cpp
|
aeon-engine/libaeon
|
e42b39e621dcd0a0fba05e1c166fc688288fb69b
|
[
"BSD-2-Clause"
] | 7
|
2017-02-19T16:22:16.000Z
|
2021-03-02T05:47:39.000Z
|
src/web/tests/test_libaeon_web/test_url_encoding.cpp
|
aeon-engine/libaeon
|
e42b39e621dcd0a0fba05e1c166fc688288fb69b
|
[
"BSD-2-Clause"
] | 61
|
2017-05-29T06:11:17.000Z
|
2021-03-28T21:51:44.000Z
|
src/web/tests/test_libaeon_web/test_url_encoding.cpp
|
aeon-engine/libaeon
|
e42b39e621dcd0a0fba05e1c166fc688288fb69b
|
[
"BSD-2-Clause"
] | 2
|
2017-05-28T17:17:40.000Z
|
2017-07-14T21:45:16.000Z
|
// Distributed under the BSD 2-Clause License - Copyright 2012-2021 Robin Degen
#include <aeon/web/http/url_encoding.h>
#include <aeon/web/http/validators.h>
#include <gtest/gtest.h>
#include <random>
using namespace aeon;
TEST(test_url_encoding, encode_regular_string)
{
const std::u8string test_str = u8"ThisIsATestString123";
ASSERT_EQ(test_str, web::http::url_encode(test_str));
}
TEST(test_url_encoding, encode_spaces)
{
const std::u8string test_str = u8"This Is A Test String 123";
const std::u8string expected_str = u8"This%20Is%20A%20Test%20String%20123";
ASSERT_EQ(expected_str, web::http::url_encode(test_str));
}
static auto generate_random_string(const int length) -> std::u8string
{
std::u8string str;
str.reserve(length);
std::random_device r;
std::default_random_engine e1(r());
std::uniform_int_distribution<unsigned long> uniform_dist;
int offset = 0;
auto random_value = uniform_dist(e1);
for (auto i = 0; i < length; ++i)
{
if (offset == sizeof(unsigned long))
{
random_value = uniform_dist(e1);
i = 0;
}
str += static_cast<char>((random_value >> (i * 8)) & 0xFF);
++offset;
}
return str;
}
TEST(test_url_encoding, encode_decode_random)
{
for (auto i = 0; i < 100; ++i)
{
for (auto j = 5; j < 20; ++j)
{
const auto str = generate_random_string(j);
const auto str_encoded = web::http::url_encode(str);
ASSERT_TRUE(web::http::detail::validate_uri(str_encoded));
const auto str_decoded = web::http::url_decode(str_encoded);
ASSERT_EQ(str, str_decoded);
}
}
}
| 25.939394
| 79
| 0.638435
|
aeon-engine
|
6304a393a27ce668de2d43bd5d1b5530919ee665
| 326
|
hpp
|
C++
|
DoremiEngine/AI/Include/Interface/SubModule/AStarSubModule.hpp
|
meraz/doremi
|
452d08ebd10db50d9563c1cf97699571889ab18f
|
[
"MIT"
] | 1
|
2020-03-23T15:42:05.000Z
|
2020-03-23T15:42:05.000Z
|
DoremiEngine/AI/Include/Interface/SubModule/AStarSubModule.hpp
|
Meraz/ssp15
|
452d08ebd10db50d9563c1cf97699571889ab18f
|
[
"MIT"
] | null | null | null |
DoremiEngine/AI/Include/Interface/SubModule/AStarSubModule.hpp
|
Meraz/ssp15
|
452d08ebd10db50d9563c1cf97699571889ab18f
|
[
"MIT"
] | 1
|
2020-03-23T15:42:06.000Z
|
2020-03-23T15:42:06.000Z
|
#pragma once
namespace DoremiEngine
{
namespace AI
{
/**
TODOKO docs
*/
class MapGrid;
class AStarSubModule
{
public:
virtual void GetPath(int p_startPos, const MapGrid& p_map) = 0;
virtual MapGrid* BuildMapGrid() = 0;
};
}
}
| 18.111111
| 75
| 0.506135
|
meraz
|
630642a798f5254c0a521c6019c0031bcdbc86d9
| 5,515
|
cpp
|
C++
|
src/ui/Style.cpp
|
CedricGuillemet/gemoni
|
76ca371d509791dd9d560d3f9f701f96e209ca5e
|
[
"MIT"
] | null | null | null |
src/ui/Style.cpp
|
CedricGuillemet/gemoni
|
76ca371d509791dd9d560d3f9f701f96e209ca5e
|
[
"MIT"
] | null | null | null |
src/ui/Style.cpp
|
CedricGuillemet/gemoni
|
76ca371d509791dd9d560d3f9f701f96e209ca5e
|
[
"MIT"
] | null | null | null |
#include "imgui.h"
#include "IconsFontAwesome5.h"
void SetStyle()
{
ImGuiStyle& st = ImGui::GetStyle();
st.FrameBorderSize = 1.0f;
st.FramePadding = ImVec2(4.0f, 2.0f);
st.ItemSpacing = ImVec2(8.0f, 2.0f);
st.WindowBorderSize = 1.0f;
st.TabBorderSize = 1.0f;
st.WindowRounding = 1.0f;
st.ChildRounding = 1.0f;
st.FrameRounding = 1.0f;
st.ScrollbarRounding = 1.0f;
st.GrabRounding = 1.0f;
st.TabRounding = 1.0f;
// Setup style
ImVec4* colors = ImGui::GetStyle().Colors;
colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 0.95f);
colors[ImGuiCol_TextDisabled] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f);
colors[ImGuiCol_WindowBg] = ImVec4(0.13f, 0.12f, 0.12f, 1.00f);
colors[ImGuiCol_ChildBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.00f);
colors[ImGuiCol_PopupBg] = ImVec4(0.05f, 0.05f, 0.05f, 0.94f);
colors[ImGuiCol_Border] = ImVec4(0.53f, 0.53f, 0.53f, 0.46f);
colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
colors[ImGuiCol_FrameBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.85f);
colors[ImGuiCol_FrameBgHovered] = ImVec4(0.22f, 0.22f, 0.22f, 0.40f);
colors[ImGuiCol_FrameBgActive] = ImVec4(0.16f, 0.16f, 0.16f, 0.53f);
colors[ImGuiCol_TitleBg] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);
colors[ImGuiCol_TitleBgActive] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);
colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.00f, 0.00f, 0.00f, 0.51f);
colors[ImGuiCol_MenuBarBg] = ImVec4(0.12f, 0.12f, 0.12f, 1.00f);
colors[ImGuiCol_ScrollbarBg] = ImVec4(0.02f, 0.02f, 0.02f, 0.53f);
colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f);
colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.41f, 0.41f, 0.41f, 1.00f);
colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.48f, 0.48f, 0.48f, 1.00f);
colors[ImGuiCol_CheckMark] = ImVec4(0.79f, 0.79f, 0.79f, 1.00f);
colors[ImGuiCol_SliderGrab] = ImVec4(0.48f, 0.47f, 0.47f, 0.91f);
colors[ImGuiCol_SliderGrabActive] = ImVec4(0.56f, 0.55f, 0.55f, 0.62f);
colors[ImGuiCol_Button] = ImVec4(0.50f, 0.50f, 0.50f, 0.63f);
colors[ImGuiCol_ButtonHovered] = ImVec4(0.67f, 0.67f, 0.68f, 0.63f);
colors[ImGuiCol_ButtonActive] = ImVec4(0.26f, 0.26f, 0.26f, 0.63f);
colors[ImGuiCol_Header] = ImVec4(0.54f, 0.54f, 0.54f, 0.58f);
colors[ImGuiCol_HeaderHovered] = ImVec4(0.64f, 0.65f, 0.65f, 0.80f);
colors[ImGuiCol_HeaderActive] = ImVec4(0.25f, 0.25f, 0.25f, 0.80f);
colors[ImGuiCol_Separator] = ImVec4(0.58f, 0.58f, 0.58f, 0.50f);
colors[ImGuiCol_SeparatorHovered] = ImVec4(0.81f, 0.81f, 0.81f, 0.64f);
colors[ImGuiCol_SeparatorActive] = ImVec4(0.81f, 0.81f, 0.81f, 0.64f);
colors[ImGuiCol_ResizeGrip] = ImVec4(0.87f, 0.87f, 0.87f, 0.53f);
colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.87f, 0.87f, 0.87f, 0.74f);
colors[ImGuiCol_ResizeGripActive] = ImVec4(0.87f, 0.87f, 0.87f, 0.74f);
colors[ImGuiCol_Tab] = ImVec4(0.01f, 0.01f, 0.01f, 0.86f);
colors[ImGuiCol_TabHovered] = ImVec4(0.29f, 0.29f, 0.79f, 1.00f);
colors[ImGuiCol_TabActive] = ImVec4(0.31f, 0.31f, 0.91f, 1.00f);
colors[ImGuiCol_TabUnfocused] = ImVec4(0.02f, 0.02f, 0.02f, 1.00f);
colors[ImGuiCol_TabUnfocusedActive] = ImVec4(0.19f, 0.19f, 0.19f, 1.00f);
colors[ImGuiCol_DockingPreview] = ImVec4(0.38f, 0.48f, 0.60f, 1.00f);
colors[ImGuiCol_DockingEmptyBg] = ImVec4(0.20f, 0.20f, 0.20f, 1.00f);
colors[ImGuiCol_PlotLines] = ImVec4(0.61f, 0.61f, 0.61f, 1.00f);
colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.68f, 0.68f, 0.68f, 1.00f);
colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.77f, 0.33f, 1.00f);
colors[ImGuiCol_PlotHistogramHovered] = ImVec4(0.87f, 0.55f, 0.08f, 1.00f);
colors[ImGuiCol_TextSelectedBg] = ImVec4(0.47f, 0.60f, 0.76f, 0.47f);
colors[ImGuiCol_DragDropTarget] = ImVec4(0.58f, 0.58f, 0.58f, 0.90f);
colors[ImGuiCol_NavHighlight] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f);
colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f);
colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f);
colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.35f);
}
//extern ImGui::MarkdownConfig mdConfig;
ImFont* smallAF, * bigAF, * mediumAF;
void InitFonts()
{
ImGuiIO& io = ImGui::GetIO();
io.Fonts->Clear();
static const ImWchar icons_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 };
ImFontConfig icons_config;
icons_config.MergeMode = true;
icons_config.PixelSnapH = true;
float fontSize_ = 16.f;
static const char* defaultFontPath = "Fonts/OpenSans-SemiBold.ttf";
io.Fonts->AddFontFromFileTTF(defaultFontPath, fontSize_);
smallAF = io.Fonts->AddFontFromFileTTF("Fonts/" FONT_ICON_FILE_NAME_FAS, fontSize_, &icons_config, icons_ranges);
mediumAF = io.Fonts->AddFontFromFileTTF(defaultFontPath, 20.f);
io.Fonts->AddFontFromFileTTF("Fonts/" FONT_ICON_FILE_NAME_FAS, 20.f, &icons_config, icons_ranges);
bigAF = io.Fonts->AddFontFromFileTTF(defaultFontPath, 24.f);
io.Fonts->AddFontFromFileTTF("Fonts/" FONT_ICON_FILE_NAME_FAS, 24.f, &icons_config, icons_ranges);
/*
// Bold headings H2 and H3
mdConfig.headingFormats[1].font = io.Fonts->AddFontFromFileTTF("Stock/Fonts/OpenSans-ExtraBold.ttf", fontSize_);
mdConfig.headingFormats[2].font = mdConfig.headingFormats[1].font;
// bold heading H1
float fontSizeH1 = fontSize_ * 1.2f;
mdConfig.headingFormats[0].font = io.Fonts->AddFontFromFileTTF("Stock/Fonts/OpenSans-ExtraBold.ttf", fontSizeH1);
*/
}
| 51.542056
| 117
| 0.688123
|
CedricGuillemet
|
deb89d9db31f248c546602d7996ccbd4f783a53d
| 269
|
cpp
|
C++
|
examples/algos/subset-xor-maximization/example-1.cpp
|
parth-07/dragon
|
2e771d698398303c8ae6d603d28bc3acfa116181
|
[
"MIT"
] | 1
|
2021-02-24T17:51:32.000Z
|
2021-02-24T17:51:32.000Z
|
examples/algos/subset-xor-maximization/example-1.cpp
|
parth-07/dragon
|
2e771d698398303c8ae6d603d28bc3acfa116181
|
[
"MIT"
] | 1
|
2021-02-24T17:57:04.000Z
|
2021-05-17T11:09:40.000Z
|
examples/algos/subset-xor-maximization/example-1.cpp
|
parth-07/ds-and-algos
|
2e771d698398303c8ae6d603d28bc3acfa116181
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
#include "dragon/algos/subset-xor-maximization.hpp"
int main() {
std::vector<int> v{48, 32, 31};
std::cout<<dragon::maximum_subset_xor_value(v)<<"\n";
std::cout<<dragon::maximum_subset_xor_value(v.begin(), v.end())<<"\n";
}
| 26.9
| 72
| 0.680297
|
parth-07
|
dec07522838bb529579d678c2d24200377ab029c
| 604
|
cpp
|
C++
|
example/asyncdeamon.cpp
|
apppur/canna
|
bdcce4f16be56da40445fec79959b6bc90003573
|
[
"MIT"
] | null | null | null |
example/asyncdeamon.cpp
|
apppur/canna
|
bdcce4f16be56da40445fec79959b6bc90003573
|
[
"MIT"
] | null | null | null |
example/asyncdeamon.cpp
|
apppur/canna
|
bdcce4f16be56da40445fec79959b6bc90003573
|
[
"MIT"
] | null | null | null |
#include <thread>
#include <functional>
#include <stdio.h>
#include <memory>
#include "asyncclient.h"
#include "asyncserver.h"
int main(int argc, char** argv)
{
asyncclient async1;
asyncclient async2;
asyncclient async3;
asyncserver server;
std::thread t1(std::bind(&asyncclient::start, &async1));
std::thread t2(std::bind(&asyncclient::start, &async2));
std::thread t3(std::bind(&asyncclient::start, &async3));
std::thread t4(std::bind(&asyncserver::run, &server));
t1.detach();
t2.detach();
t3.detach();
t4.detach();
getchar();
return 0;
}
| 20.133333
| 60
| 0.642384
|
apppur
|
dec2f325f34c51e9af008d0a401b695be3e82249
| 442
|
cpp
|
C++
|
algorithms/cpp/deleteNodeInALinkedList/test.cpp
|
mzlogin/LeetCode
|
b0ccb0f84eafe60ff355e4ab81bde2f39c043035
|
[
"MIT"
] | 2
|
2017-03-27T17:20:28.000Z
|
2018-06-07T15:15:54.000Z
|
algorithms/cpp/deleteNodeInALinkedList/test.cpp
|
mzlogin/LeetCode
|
b0ccb0f84eafe60ff355e4ab81bde2f39c043035
|
[
"MIT"
] | 2
|
2015-12-13T02:58:29.000Z
|
2016-09-15T00:00:22.000Z
|
algorithms/cpp/deleteNodeInALinkedList/test.cpp
|
mzlogin/LeetCode
|
b0ccb0f84eafe60ff355e4ab81bde2f39c043035
|
[
"MIT"
] | null | null | null |
#include "../catch.h"
#include "../mylist.h"
#include "solution.h"
TEST_CASE("Delete Node In a Linked List", "deleteNodeInALinkedList") {
Solution sln;
const int len = 4;
int nums[len] = {1,2,3,4};
ListNode* root = createList(nums, len);
ListNode* p = root->next->next;
sln.deleteNode(p);
CHECK(getListValueAt(root, 2) == 4);
p = root->next;
sln.deleteNode(p);
CHECK(getListValueAt(root, 1) == 4);
}
| 24.555556
| 70
| 0.615385
|
mzlogin
|
dec60f7023fc0c5f3a3f7e986d258647535c871b
| 499
|
cc
|
C++
|
leetcode/src/balaced_binary_tree.cc
|
plusplus7/solutions
|
31233c13ee2bd0da6a907a24adbaf5b49ebf843c
|
[
"CC0-1.0"
] | 5
|
2016-04-29T07:14:23.000Z
|
2020-01-07T04:56:11.000Z
|
leetcode/src/balaced_binary_tree.cc
|
plusplus7/solutions
|
31233c13ee2bd0da6a907a24adbaf5b49ebf843c
|
[
"CC0-1.0"
] | null | null | null |
leetcode/src/balaced_binary_tree.cc
|
plusplus7/solutions
|
31233c13ee2bd0da6a907a24adbaf5b49ebf843c
|
[
"CC0-1.0"
] | 1
|
2016-04-29T07:14:32.000Z
|
2016-04-29T07:14:32.000Z
|
#include <iostream>
using namespace std;
class Solution {
public:
int dfs(TreeNode *node) {
if (node == NULL)
return 0;
return max(dfs(node->left, dep+1), dfs(node->right, dep+1))+1;
}
bool isBalanced(TreeNode *root) {
if (root == NULL)
return true;
if (abs(dfs(node->left)-dfs(node->right)) > 1)
return false;
else
return isBalanced(root->left) == true && isBalanced(root->right) == true;
}
};
| 26.263158
| 85
| 0.537074
|
plusplus7
|
decdd07a00f33af05ff4c749316d9b1956486241
| 2,237
|
cpp
|
C++
|
tests/common_test/tests/mask_tests/circle_mask_tests.cpp
|
JulianBiancardi/Wolfenstein-Taller1
|
28e72ce8438264919586785aa09ce9b0a5de222b
|
[
"MIT"
] | 1
|
2021-04-23T19:57:40.000Z
|
2021-04-23T19:57:40.000Z
|
tests/common_test/tests/mask_tests/circle_mask_tests.cpp
|
JulianBiancardi/Wolfenstein-Taller1
|
28e72ce8438264919586785aa09ce9b0a5de222b
|
[
"MIT"
] | null | null | null |
tests/common_test/tests/mask_tests/circle_mask_tests.cpp
|
JulianBiancardi/Wolfenstein-Taller1
|
28e72ce8438264919586785aa09ce9b0a5de222b
|
[
"MIT"
] | null | null | null |
#include "circle_mask_tests.h"
#include "../../main/collisions/circle_mask.h"
#include "../../main/utils/point.h"
#include "../tests_setup.h"
int static creation_test();
int static center_test();
int static interior_test();
int static border_test();
int static exterior_test();
void circle_mask_tests() {
begin_tests("CIRCLE MASK");
print_test("La máscara circular se crea correctamente", creation_test,
NO_ERROR);
print_test("La máscara circular ocupa su centro", center_test, NO_ERROR);
print_test(
"La máscara circular ocupa puntos dentro de su circunferencia límite",
interior_test, NO_ERROR);
print_test("La máscara circular ocupa puntos en su circunferencia límite",
border_test, NO_ERROR);
print_test("La máscara circular no ocupa puntos fuera de su circunferencia",
exterior_test, NO_ERROR);
end_tests();
}
int static creation_test() {
Point center(0, 0);
CircleMask mask(1, center);
return NO_ERROR;
}
int static center_test() {
Point center(0, 0);
CircleMask mask(1, center);
Point center_p(0, 0);
if (!mask.occupies(center_p)) {
return ERROR;
}
return NO_ERROR;
}
int static interior_test() {
Point center(0, 0);
CircleMask mask(1, center);
Point p1(-0.1, 0.5);
Point p2(-0.6, -0.79);
Point p3(0.8, 0.0);
Point p4(0, 0.3);
Point p5(-0.2, 0.2);
if (!mask.occupies(p1)) {
return ERROR;
}
if (!mask.occupies(p2)) {
return ERROR;
}
if (!mask.occupies(p3)) {
return ERROR;
}
if (!mask.occupies(p4)) {
return ERROR;
}
if (!mask.occupies(p5)) {
return ERROR;
}
return NO_ERROR;
}
int static border_test() {
Point center(0, 0);
CircleMask mask(1, center);
Point p1(0, 1);
Point p2(0, -1);
Point p3(1, 0);
Point p4(-1, 0);
if (!mask.occupies(p1) || !mask.occupies(p2) || !mask.occupies(p3) ||
!mask.occupies(p4)) {
return ERROR;
}
return NO_ERROR;
}
int static exterior_test() {
Point center(0, 0);
CircleMask mask(1, center);
Point p1(0, 2);
Point p2(0, 1.1);
Point p3(1, 1);
Point p4(0, -1.5);
if (mask.occupies(p1) || mask.occupies(p2) || mask.occupies(p3) ||
mask.occupies(p4)) {
return ERROR;
}
return NO_ERROR;
}
| 21.103774
| 78
| 0.640143
|
JulianBiancardi
|
dece96829fe573ed8b4ad39e4772d59a7b19567a
| 1,179
|
hpp
|
C++
|
FFmpegServer/FFmpegYAGuiDroidCapture_PacketQueue/include/Buffer/BufferData.hpp
|
aalekhm/OpenFF
|
9df23a21727f29a871f7239ccf15e3100ae9780e
|
[
"MIT"
] | null | null | null |
FFmpegServer/FFmpegYAGuiDroidCapture_PacketQueue/include/Buffer/BufferData.hpp
|
aalekhm/OpenFF
|
9df23a21727f29a871f7239ccf15e3100ae9780e
|
[
"MIT"
] | null | null | null |
FFmpegServer/FFmpegYAGuiDroidCapture_PacketQueue/include/Buffer/BufferData.hpp
|
aalekhm/OpenFF
|
9df23a21727f29a871f7239ccf15e3100ae9780e
|
[
"MIT"
] | null | null | null |
#pragma once
#include "Common/Defines.h"
#include "Common/RandomAccessFile.h"
class BufferData
{
public:
BufferData()
: m_iBufferSize(-1)
, m_pBuffer(nullptr)
{ }
BufferData(size_t iBufferSize)
{
setSize(iBufferSize);
}
void operator=(BufferData& pBufferData)
{
cleanup();
setSize(pBufferData.m_iBufferSize);
memcpy_s(m_pBuffer, m_iBufferSize, pBufferData.m_pBuffer, pBufferData.m_iBufferSize);
}
void setSize(size_t iBufferSize)
{
if (iBufferSize != m_iBufferSize)
{
cleanup();
}
m_iBufferSize = iBufferSize;
m_pBuffer = (uint8_t*)std::malloc(iBufferSize);
}
virtual ~BufferData()
{
cleanup();
}
void cleanup()
{
m_iBufferSize = -1;
if (m_pBuffer != nullptr)
{
std::free(m_pBuffer);
m_pBuffer = nullptr;
}
}
void saveToDisk(std::string sFileName)
{
RandomAccessFile* raf = new RandomAccessFile();
if (raf->openForWrite(sFileName.c_str()))
{
LOG_CONSOLE("Saving buffer to disk! size = " << m_iBufferSize);
raf->write((char*)m_pBuffer, 0, m_iBufferSize);
raf->close();
}
}
uint8_t* m_pBuffer;
size_t m_iBufferSize;
protected:
private:
};
| 17.338235
| 88
| 0.65564
|
aalekhm
|
ded00ab6f7ed575fdcb08faaef40996cf6db9fbf
| 7,069
|
cpp
|
C++
|
libs/dev/Math/MathEngineTest/Matrix_Constructor.cpp
|
Norseman055/immaterial-engine
|
6aca0fad64f5b2b9fe6eb351528a79a39dc94625
|
[
"MIT"
] | null | null | null |
libs/dev/Math/MathEngineTest/Matrix_Constructor.cpp
|
Norseman055/immaterial-engine
|
6aca0fad64f5b2b9fe6eb351528a79a39dc94625
|
[
"MIT"
] | null | null | null |
libs/dev/Math/MathEngineTest/Matrix_Constructor.cpp
|
Norseman055/immaterial-engine
|
6aca0fad64f5b2b9fe6eb351528a79a39dc94625
|
[
"MIT"
] | null | null | null |
//---------------------------------------------------------------------------
// HEADER FILES:
//---------------------------------------------------------------------------
#include "UnitTest.h"
#include "MathEngine.h"
#define eq Util::isEqual
#define MATH_TOLERANCE 0.0001f
//---------------------------------------------------------------------------
// TESTS:
//---------------------------------------------------------------------------
TEST( Matrix_default_constructor, matix_tests )
{
Matrix M;
CHECK( M[m0] == 0.0f );
CHECK( M[m1] == 0.0f );
CHECK( M[m2] == 0.0f );
CHECK( M[m3] == 0.0f );
CHECK( M[m4] == 0.0f );
CHECK( M[m5] == 0.0f );
CHECK( M[m6] == 0.0f );
CHECK( M[m7] == 0.0f );
CHECK( M[m8] == 0.0f );
CHECK( M[m9] == 0.0f );
CHECK( M[m10] == 0.0f );
CHECK( M[m11] == 0.0f );
CHECK( M[m12] == 0.0f );
CHECK( M[m13] == 0.0f );
CHECK( M[m14] == 0.0f );
CHECK( M[m15] == 0.0f );
}
TEST( Matrix_vector_constructor, matix_tests )
{
Vect V0(1.0f,2.0f,3.0f,4.0f);
Vect V1(7.0f,6.0f,5.0f,3.0f);
Vect V2(-4.0f,-2.0f,-1.0f,-4.0f);
Vect V3(9.0f,-7.0f,-2.0f,5.0f);
CHECK( V0[x] == 1.0f );
CHECK( V0[y] == 2.0f );
CHECK( V0[z] == 3.0f );
CHECK( V0[w] == 4.0f );
CHECK( V1[x] == 7.0f );
CHECK( V1[y] == 6.0f );
CHECK( V1[z] == 5.0f );
CHECK( V1[w] == 3.0f );
CHECK( V2[x] == -4.0f );
CHECK( V2[y] == -2.0f );
CHECK( V2[z] == -1.0f );
CHECK( V2[w] == -4.0f );
CHECK( V3[x] == 9.0f );
CHECK( V3[y] == -7.0f );
CHECK( V3[z] == -2.0f );
CHECK( V3[w] == 5.0f );
Matrix M(V0,V1,V2,V3);
CHECK( M[m0] == 1.0f );
CHECK( M[m1] == 2.0f );
CHECK( M[m2] == 3.0f );
CHECK( M[m3] == 4.0f );
CHECK( M[m4] == 7.0f );
CHECK( M[m5] == 6.0f );
CHECK( M[m6] == 5.0f );
CHECK( M[m7] == 3.0f );
CHECK( M[m8] == -4.0f );
CHECK( M[m9] == -2.0f );
CHECK( M[m10] == -1.0f );
CHECK( M[m11] == -4.0f );
CHECK( M[m12] == 9.0f );
CHECK( M[m13] == -7.0f );
CHECK( M[m14] == -2.0f );
CHECK( M[m15] == 5.0f );
}
TEST( Matrix_copy_constructor, matix_tests )
{
Vect V0(1.0f,2.0f,3.0f,4.0f);
Vect V1(7.0f,6.0f,5.0f,3.0f);
Vect V2(-4.0f,-2.0f,-1.0f,-4.0f);
Vect V3(9.0f,-7.0f,-2.0f,5.0f);
CHECK( V0[x] == 1.0f );
CHECK( V0[y] == 2.0f );
CHECK( V0[z] == 3.0f );
CHECK( V0[w] == 4.0f );
CHECK( V1[x] == 7.0f );
CHECK( V1[y] == 6.0f );
CHECK( V1[z] == 5.0f );
CHECK( V1[w] == 3.0f );
CHECK( V2[x] == -4.0f );
CHECK( V2[y] == -2.0f );
CHECK( V2[z] == -1.0f );
CHECK( V2[w] == -4.0f );
CHECK( V3[x] == 9.0f );
CHECK( V3[y] == -7.0f );
CHECK( V3[z] == -2.0f );
CHECK( V3[w] == 5.0f );
Matrix M(V0,V1,V2,V3);
Matrix N( M );
CHECK( N[m0] == 1.0f );
CHECK( N[m1] == 2.0f );
CHECK( N[m2] == 3.0f );
CHECK( N[m3] == 4.0f );
CHECK( N[m4] == 7.0f );
CHECK( N[m5] == 6.0f );
CHECK( N[m6] == 5.0f );
CHECK( N[m7] == 3.0f );
CHECK( N[m8] == -4.0f );
CHECK( N[m9] == -2.0f );
CHECK( N[m10] == -1.0f );
CHECK( N[m11] == -4.0f );
CHECK( N[m12] == 9.0f );
CHECK( N[m13] == -7.0f );
CHECK( N[m14] == -2.0f );
CHECK( N[m15] == 5.0f );
CHECK( M[m0] == 1.0f );
CHECK( M[m1] == 2.0f );
CHECK( M[m2] == 3.0f );
CHECK( M[m3] == 4.0f );
CHECK( M[m4] == 7.0f );
CHECK( M[m5] == 6.0f );
CHECK( M[m6] == 5.0f );
CHECK( M[m7] == 3.0f );
CHECK( M[m8] == -4.0f );
CHECK( M[m9] == -2.0f );
CHECK( M[m10] == -1.0f );
CHECK( M[m11] == -4.0f );
CHECK( M[m12] == 9.0f );
CHECK( M[m13] == -7.0f );
CHECK( M[m14] == -2.0f );
CHECK( M[m15] == 5.0f );
}
TEST( Destructor_constuctor, matrix_tests )
{
Vect V0(1.0f,2.0f,3.0f,4.0f);
Vect V1(7.0f,6.0f,5.0f,3.0f);
Vect V2(-4.0f,-2.0f,-1.0f,-4.0f);
Vect V3(9.0f,-7.0f,-2.0f,5.0f);
Matrix M(V0,V1,V2,V3);
Matrix *pM = &M;
pM->~Matrix();
CHECK(1);
}
TEST( MatrixRotAxisAngle, matrix_tests )
{
// Axis and Angle Type Constructor:
Vect v11( 2.0f, 53.0f, 24.0f);
Matrix m54( ROT_AXIS_ANGLE, v11, MATH_PI3 );
// => Vect v11( 2.0f, 53.0f, 24.0f); \n"););
// => Matrix m54(ROT_AXIS_ANGLE, v11, MATH_PI3 );\n"););
CHECK( eq(m54[m0], 0.5005f, MATH_TOLERANCE) );
CHECK( eq(m54[m1], 0.3726f, MATH_TOLERANCE) );
CHECK( eq(m54[m2],-0.7813f, MATH_TOLERANCE) );
CHECK( m54[m3] == 0.0f );
CHECK( eq(m54[m4],-0.3413f, MATH_TOLERANCE) );
CHECK( eq(m54[m5], 0.9144f, MATH_TOLERANCE) );
CHECK( eq(m54[m6], 0.2174f, MATH_TOLERANCE) );
CHECK( (m54[m7] == 0.0f) );
CHECK( eq(m54[m8], 0.7955f, MATH_TOLERANCE) );
CHECK( eq(m54[m9], 0.1579f, MATH_TOLERANCE) );
CHECK( eq(m54[m10], 0.5849f, MATH_TOLERANCE) );
CHECK( (m54[m11] == 0.0f) );
CHECK( (m54[m12] == 0.0f) );
CHECK( (m54[m13] == 0.0f) );
CHECK( (m54[m14] == 0.0f) );
CHECK( (m54[m15] == 1.0f) );
}
TEST( MatrixRotOrient, matrix_tests )
{
// Orientation Type Constructor:
Vect v15( 2.0f, 53.0f, 24.0f);
Vect v16( 0.0f, -24.0f, 53.0f);
Matrix m56(ROT_ORIENT, v15, v16 );
CHECK( eq(m56[m0],-0.9994f, MATH_TOLERANCE) );
CHECK( eq(m56[m1], 0.0313f, MATH_TOLERANCE) );
CHECK( eq(m56[m2], 0.0142f, MATH_TOLERANCE) );
CHECK( (m56[m3] == 0.0f) );
CHECK( eq(m56[m4], 0.0000f, MATH_TOLERANCE) );
CHECK( eq(m56[m5],-0.4125f, MATH_TOLERANCE) );
CHECK( eq(m56[m6], 0.9110f, MATH_TOLERANCE) );
CHECK( (m56[m7] == 0.0f) );
CHECK( eq(m56[m8], 0.0344f, MATH_TOLERANCE) );
CHECK( eq(m56[m9], 0.9104f, MATH_TOLERANCE) );
CHECK( eq(m56[m10], 0.4123f, MATH_TOLERANCE) );
CHECK( (m56[m11] == 0.0f) );
CHECK( (m56[m12] == 0.0f) );
CHECK( (m56[m13] == 0.0f) );
CHECK( (m56[m14] == 0.0f) );
CHECK( (m56[m15] == 1.0f) );
}
TEST( MatrixRotInverseOrient, matrix_tests)
{
// Orientation Type Constructor:
Vect v17( 2.0f, 53.0f, 24.0f);
Vect v18( 0.0f, -24.0f, 53.0f);
Matrix m57(ROT_INVERSE_ORIENT, v17, v18 );
CHECK( eq(m57[m0],-0.9994f, MATH_TOLERANCE) );
CHECK( eq(m57[m1], 0.0000f, MATH_TOLERANCE) );
CHECK( eq(m57[m2], 0.0344f, MATH_TOLERANCE) );
CHECK( (m57[m3] == 0.0f) );
CHECK( eq(m57[m4], 0.0313f, MATH_TOLERANCE) );
CHECK( eq(m57[m5],-0.4125f, MATH_TOLERANCE) );
CHECK( eq(m57[m6], 0.9104f, MATH_TOLERANCE) );
CHECK( (m57[m7] == 0.0f) );
CHECK( eq(m57[m8], 0.0142f, MATH_TOLERANCE) );
CHECK( eq(m57[m9], 0.9110f, MATH_TOLERANCE) );
CHECK( eq(m57[m10], 0.4123f, MATH_TOLERANCE) );
CHECK( (m57[m11] == 0.0f) );
CHECK( (m57[m12] == 0.0f) );
CHECK( (m57[m13] == 0.0f) );
CHECK( (m57[m14] == 0.0f) );
CHECK( (m57[m15] == 1.0f) );
}
TEST( MatrixQuaternion, matrix_tests)
{
// Quaternion Type Constructor:
Matrix Rxyz1(ROT_XYZ, MATH_PI3, MATH_5PI8, MATH_PI4 );
Quat Qxyz1(Rxyz1);
Matrix Mxyz1( Qxyz1 );
CHECK( eq(Mxyz1[m0],-0.2705f,MATH_TOLERANCE) );
CHECK( eq(Mxyz1[m1],-0.2705f,MATH_TOLERANCE) );
CHECK( eq(Mxyz1[m2],-0.9238f,MATH_TOLERANCE) );
CHECK( (Mxyz1[m3] == 0.0f) );
CHECK( eq(Mxyz1[m4], 0.2122f,MATH_TOLERANCE) );
CHECK( eq(Mxyz1[m5], 0.9193f,MATH_TOLERANCE) );
CHECK( eq(Mxyz1[m6],-0.3314f,MATH_TOLERANCE) );
CHECK( (Mxyz1[m7] == 0.0f) );
CHECK( eq(Mxyz1[m8], 0.9390f,MATH_TOLERANCE) );
CHECK( eq(Mxyz1[m9],-0.2857f,MATH_TOLERANCE) );
CHECK( eq(Mxyz1[m10],-0.1913f,MATH_TOLERANCE) );
CHECK( (Mxyz1[m11] == 0.0f) );
CHECK( (Mxyz1[m12] == 0.0f) );
CHECK( (Mxyz1[m13] == 0.0f) );
CHECK( (Mxyz1[m14] == 0.0f) );
CHECK( (Mxyz1[m15] == 1.0f) );
}
| 26.776515
| 77
| 0.530485
|
Norseman055
|
ded12ff193fedcafbc3acfc7a1a1a355ddaec06d
| 1,170
|
cpp
|
C++
|
nodes/DataLoggerNode/DataLoggerProcess.cpp
|
dgitz/eROS
|
0ff4b5dda5f3d445784d43745597bb5c31d1997c
|
[
"MIT"
] | 2
|
2016-11-28T13:01:12.000Z
|
2021-03-26T22:02:02.000Z
|
nodes/DataLoggerNode/DataLoggerProcess.cpp
|
dgitz/eROS
|
0ff4b5dda5f3d445784d43745597bb5c31d1997c
|
[
"MIT"
] | 46
|
2016-10-24T13:34:48.000Z
|
2019-11-14T23:47:22.000Z
|
nodes/DataLoggerNode/DataLoggerProcess.cpp
|
dgitz/eros
|
0ff4b5dda5f3d445784d43745597bb5c31d1997c
|
[
"MIT"
] | 2
|
2021-07-20T10:11:45.000Z
|
2021-08-10T11:31:41.000Z
|
#include <eros/DataLogger/DataLoggerProcess.h>
using namespace eros;
using namespace eros_nodes;
DataLoggerProcess::DataLoggerProcess()
: log_directory(""),
log_directory_available(false),
logfile_duration(-1.0),
logging_enabled(false),
snapshot_mode(true) {
}
DataLoggerProcess::~DataLoggerProcess() {
}
Diagnostic::DiagnosticDefinition DataLoggerProcess::finish_initialization() {
Diagnostic::DiagnosticDefinition diag;
return diag;
}
void DataLoggerProcess::reset() {
}
Diagnostic::DiagnosticDefinition DataLoggerProcess::update(double t_dt, double t_ros_time) {
Diagnostic::DiagnosticDefinition diag = base_update(t_dt, t_ros_time);
ready_to_arm.ready_to_arm = true;
ready_to_arm.diag = convert(diag);
return diag;
}
std::vector<Diagnostic::DiagnosticDefinition> DataLoggerProcess::new_commandmsg(eros::command msg) {
(void)msg; // Not used yet.
std::vector<Diagnostic::DiagnosticDefinition> diag_list;
return diag_list;
}
std::vector<Diagnostic::DiagnosticDefinition> DataLoggerProcess::check_programvariables() {
std::vector<Diagnostic::DiagnosticDefinition> diag_list;
return diag_list;
}
| 33.428571
| 100
| 0.761538
|
dgitz
|
ded73d86410b8acca4b20373f5b8e439c0127133
| 841
|
cc
|
C++
|
libconfluo/src/compression/confluo_encoder.cc
|
Mu-L/confluo
|
e9b8621e99f56b1adf5675c4296c006d89e6e582
|
[
"Apache-2.0"
] | 1,398
|
2018-12-05T19:13:15.000Z
|
2022-03-29T08:26:03.000Z
|
libconfluo/src/compression/confluo_encoder.cc
|
Mu-L/confluo
|
e9b8621e99f56b1adf5675c4296c006d89e6e582
|
[
"Apache-2.0"
] | 53
|
2018-10-21T03:28:25.000Z
|
2021-03-16T03:50:54.000Z
|
libconfluo/src/compression/confluo_encoder.cc
|
Mu-L/confluo
|
e9b8621e99f56b1adf5675c4296c006d89e6e582
|
[
"Apache-2.0"
] | 208
|
2018-10-28T03:05:46.000Z
|
2022-02-06T06:16:37.000Z
|
#include "compression/confluo_encoder.h"
namespace confluo {
namespace compression {
unique_byte_array confluo_encoder::encode(void *ptr, size_t size, uint8_t encoding) {
switch (encoding) {
case encoding_type::D_UNENCODED: {
return unique_byte_array(reinterpret_cast<uint8_t *>(ptr), size, no_op_delete);
}
case encoding_type::D_ELIAS_GAMMA: {
uint64_t *casted = reinterpret_cast<uint64_t *>(ptr);
size_t array_len = size / sizeof(uint64_t);
return delta_encoder::encode<uint64_t>(casted, array_len);
}
case encoding_type::D_LZ4: {
uint8_t *casted = reinterpret_cast<uint8_t *>(ptr);
return lz4_encoder<>::encode(casted, size);
}
default : {
THROW(illegal_state_exception, "Invalid encoding type!");
}
}
}
void confluo_encoder::no_op_delete(uint8_t *) {}
}
}
| 29
| 85
| 0.6956
|
Mu-L
|
ded97349fac892fd74f4c924f410dd860981d4da
| 19,721
|
inl
|
C++
|
ivp/havana/havok/hk_math/vector_fpu/vector_fpu.inl
|
DannyParker0001/Kisak-Strike
|
99ed85927336fe3aff2efd9b9382b2b32eb1d05d
|
[
"Unlicense"
] | 252
|
2020-12-16T15:34:43.000Z
|
2022-03-31T23:21:37.000Z
|
ivp/havana/havok/hk_math/vector_fpu/vector_fpu.inl
|
DannyParker0001/Kisak-Strike
|
99ed85927336fe3aff2efd9b9382b2b32eb1d05d
|
[
"Unlicense"
] | 23
|
2020-12-20T18:02:54.000Z
|
2022-03-28T16:58:32.000Z
|
ivp/havana/havok/hk_math/vector_fpu/vector_fpu.inl
|
DannyParker0001/Kisak-Strike
|
99ed85927336fe3aff2efd9b9382b2b32eb1d05d
|
[
"Unlicense"
] | 42
|
2020-12-19T04:32:33.000Z
|
2022-03-30T06:00:28.000Z
|
inline void hk_VecFPU::fpu_add_multiple_row(hk_real *target_adress,hk_real *source_adress,hk_real factor,int size,hk_bool adress_aligned) {
if(adress_aligned==HK_FALSE) {
//we have to calculate the block size and shift adresses to lower aligned adresses
long result_adress = long(source_adress) & hk_VecFPU_MEM_MASK_FLOAT;
target_adress = (hk_real *)( long (target_adress) & hk_VecFPU_MEM_MASK_FLOAT);
size += (long(source_adress)-result_adress)>>hk_VecFPU_MEMSHIFT_FLOAT;
source_adress=(hk_real *)result_adress;
}
#if defined(IVP_USE_PS2_VU0)
asm __volatile__("
mfc1 $8,%3
qmtc2 $8,vf5 # vf5.x factor
1:
lqc2 vf4,0x0(%1) # vf4 *source
vmulx.xyzw vf6,vf4,vf5 # vf6 *source * factor
lqc2 vf4,0x0(%0)
addi %0, 0x10
vadd.xyzw vf6,vf4,vf6 # vf6 = *dest + factor * *source
addi %2,-4
addi %1, 0x10
sqc2 vf6,-0x10(%0)
bgtz %2,1b
nop
"
: /* no output */
: "r" (target_adress), "r" (source_adress) , "r" (size), "f" (factor)
: "$8" , "memory");
#else
#if 0
# if defined(IVP_WILLAMETTE)
;
__m128d factor128=_mm_set1_pd(factor);
for(int i=size;i>0;i-=hk_VecFPU_SIZE_FLOAT) {
__m128d source_d=_mm_load_pd(source_adress);
__m128d prod_d=_mm_mul_pd(factor128,source_d);
__m128d target_d=_mm_load_pd(target_adress);
target_d=_mm_add_pd(prod_d,target_d);
_mm_store_pd(target_adress,target_d);
target_adress+=hk_VecFPU_SIZE_FLOAT;
source_adress+=hk_VecFPU_SIZE_FLOAT;
}
#endif
#endif
for(int i=size;i>0;i-=hk_VecFPU_SIZE_FLOAT) {
# if hk_VecFPU_SIZE_FLOAT == 2
hk_real a = source_adress[0] * factor;
hk_real b = source_adress[1] * factor;
a += target_adress[0];
b += target_adress[1];
target_adress[0] = a;
target_adress[1] = b;
# elif hk_VecFPU_SIZE_FLOAT == 4
hk_real a = source_adress[0] * factor;
hk_real b = source_adress[1] * factor;
hk_real c = source_adress[2] * factor;
hk_real d = source_adress[3] * factor;
a += target_adress[0];
b += target_adress[1];
c += target_adress[2];
d += target_adress[3];
target_adress[0] = a;
target_adress[1] = b;
target_adress[2] = c;
target_adress[3] = d;
# else
shit
# endif
target_adress+=hk_VecFPU_SIZE_FLOAT;
source_adress+=hk_VecFPU_SIZE_FLOAT;
}
#endif
}
inline hk_real hk_VecFPU::fpu_large_dot_product(hk_real *base_a, hk_real *base_b, int size, hk_bool adress_aligned) {
if(adress_aligned==HK_FALSE) {
//we have to calculate the block size and shift adresses to lower aligned adresses
long result_adress = long(base_a) & hk_VecFPU_MEM_MASK_FLOAT;
base_b = (hk_real *)( long (base_b) & hk_VecFPU_MEM_MASK_FLOAT);
size += (long(base_a)-result_adress)>>hk_VecFPU_MEMSHIFT_FLOAT; // because start changed
base_a=(hk_real *)result_adress;
}
# if defined(IVP_WILLAMETTE)
IVP_IF_WILLAMETTE_OPT(IVP_Environment_Manager::get_environment_manager()->ivp_willamette_optimization) {
__m128d sum128 =_mm_set1_pd(0.0f);
int i;
for(i=size;i>=hk_VecFPU_SIZE_FLOAT; i-= hk_VecFPU_SIZE_FLOAT) {
__m128d mult1=_mm_load_pd(base_a);
__m128d mult2=_mm_load_pd(base_b);
__m128d prod =_mm_mul_pd(mult1,mult2);
sum128 =_mm_add_pd(prod,sum128);
base_a += hk_VecFPU_SIZE_FLOAT;
base_b += hk_VecFPU_SIZE_FLOAT;
}
__m128d dummy,low,high;
low=sum128;
dummy=sum128;
//_mm_shuffle_pd(sum128,sum128,1); //swap high and low
sum128=_mm_unpackhi_pd(sum128,dummy);
high=sum128;
__m128d sum64=_mm_add_sd(low,high);
__m128d res=sum64;
//_mm_shuffle_pd(sum64,sum64,1);
hk_real result_sum;
_mm_store_sd(&result_sum,res);
for(;i>=0;i--) {
result_sum += base_a[i] * base_b[i];
}
return result_sum;
} else {
hk_real sum=0.0f;
for(int i=size-1;i>=0;i--) {
sum += base_a[i] * base_b[i];
}
return sum;
}
#else
hk_real sum=0.0f;
for(int i=size-1;i>=0;i--) {
sum += base_a[i] * base_b[i];
}
return sum;
#endif
}
inline void hk_VecFPU::fpu_multiply_row(hk_real *target_adress,hk_real factor,int size,hk_bool adress_aligned) {
if(adress_aligned==HK_FALSE) {
//we have to calculate the block size and shift adresses to lower aligned adresses
long adress,result_adress;
adress=(long)target_adress;
result_adress=adress & hk_VecFPU_MEM_MASK_FLOAT;
size+=(adress-result_adress)>>hk_VecFPU_MEMSHIFT_FLOAT;
target_adress=(hk_real *)result_adress;
}
#if 0
#ifdef IVP_WILLAMETTE
__m128d factor128=_mm_set1_pd(factor);
int i;
for(i=size;i>0;i-=hk_VecFPU_SIZE_FLOAT) {
__m128d target_d=_mm_load_pd(target_adress);
target_d=_mm_mul_pd(factor128,target_d);
_mm_store_pd(target_adress,target_d);
target_adress+=hk_VecFPU_SIZE_FLOAT;
}
#endif
#endif
int i;
for(i=size;i>0;i-=hk_VecFPU_SIZE_FLOAT) {
# if hk_VecFPU_SIZE_FLOAT == 2
hk_real a = target_adress[0] * factor;
hk_real b = target_adress[1] * factor;
target_adress[0] = a;
target_adress[1] = b;
# elif hk_VecFPU_SIZE_FLOAT == 4
hk_real a = target_adress[0] * factor;
hk_real b = target_adress[1] * factor;
hk_real c = target_adress[2] * factor;
hk_real d = target_adress[3] * factor;
target_adress[0] = a;
target_adress[1] = b;
target_adress[2] = c;
target_adress[3] = d;
# else
shit
# endif
target_adress+=hk_VecFPU_SIZE_FLOAT;
}
}
// #+# sparc says rui, optimize for non vector units ( hk_VecFPU_SIZE_FLOAT = 4 )
inline void hk_VecFPU::fpu_exchange_rows(hk_real *target_adress1,hk_real *target_adress2,int size,hk_bool adress_aligned) {
if(adress_aligned==HK_FALSE) {
//we have to calculate the block size and shift adresses to lower aligned adresses
long adress,result_adress;
adress=(long)target_adress1;
result_adress=adress & hk_VecFPU_MEM_MASK_FLOAT;
size+=(adress-result_adress)>>hk_VecFPU_MEMSHIFT_FLOAT;
target_adress1=(hk_real *)result_adress;
adress=(long)target_adress2;
adress=adress & hk_VecFPU_MEM_MASK_FLOAT;
target_adress2=(hk_real *)adress;
}
#if 0
int i;
for(i=size;i>0;i-=hk_VecFPU_SIZE_FLOAT) {
__m128d a_d=_mm_load_pd(target_adress1);
__m128d b_d=_mm_load_pd(target_adress2);
_mm_store_pd(target_adress1,b_d);
_mm_store_pd(target_adress2,a_d);
target_adress1+=hk_VecFPU_SIZE_FLOAT;
target_adress2+=hk_VecFPU_SIZE_FLOAT;
}
#endif
int i;
for(i=size;i>0;i-=hk_VecFPU_SIZE_FLOAT) {
hk_real h;
# if hk_VecFPU_SIZE_FLOAT == 2
h=target_adress1[0]; target_adress1[0]=target_adress2[0]; target_adress2[0]=h;
h=target_adress1[1]; target_adress1[1]=target_adress2[1]; target_adress2[1]=h;
# elif hk_VecFPU_SIZE_FLOAT == 4
h=target_adress1[0]; target_adress1[0]=target_adress2[0]; target_adress2[0]=h;
h=target_adress1[1]; target_adress1[1]=target_adress2[1]; target_adress2[1]=h;
h=target_adress1[2]; target_adress1[2]=target_adress2[2]; target_adress2[2]=h;
h=target_adress1[3]; target_adress1[3]=target_adress2[3]; target_adress2[3]=h;
# else
shit
# endif
target_adress1+=hk_VecFPU_SIZE_FLOAT;
target_adress2+=hk_VecFPU_SIZE_FLOAT;
}
}
inline void hk_VecFPU::fpu_copy_rows(hk_real *target_adress,hk_real *source_adress,int size,hk_bool adress_aligned) {
if(adress_aligned==HK_FALSE) {
//we have to calculate the block size and shift adresses to lower aligned adresses
long adress,result_adress;
adress=(long)source_adress;
result_adress=adress & hk_VecFPU_MEM_MASK_FLOAT;
size+=(adress-result_adress)>>hk_VecFPU_MEMSHIFT_FLOAT;
source_adress=(hk_real *)result_adress;
adress=(long)target_adress;
adress=adress & hk_VecFPU_MEM_MASK_FLOAT;
target_adress=(hk_real *)adress;
}
#if 0
int i;
for(i=size-1;i>=0;i-=hk_VecFPU_SIZE_FLOAT) {
__m128d target_d=_mm_load_pd(source_adress);
_mm_store_pd(target_adress,target_d);
target_adress+=hk_VecFPU_SIZE_FLOAT;
source_adress+=hk_VecFPU_SIZE_FLOAT;
}
}
#endif
int i;
for(i=size-1;i>=0;i-=hk_VecFPU_SIZE_FLOAT) {
int j;
for(j=0;j<hk_VecFPU_SIZE_FLOAT;j++) {
target_adress[j] = source_adress[j];
}
target_adress+=hk_VecFPU_SIZE_FLOAT;
source_adress+=hk_VecFPU_SIZE_FLOAT;
}
}
inline void hk_VecFPU::fpu_set_row_to_zero(hk_real *target_adress,int size,hk_bool adress_aligned) {
if(adress_aligned==HK_FALSE) {
long adress,result_adress;
adress=(long)target_adress;
result_adress=adress & hk_VecFPU_MEM_MASK_FLOAT;
size+=(adress-result_adress)>>hk_VecFPU_MEMSHIFT_FLOAT;
target_adress=(hk_real *)result_adress;
}
#if 0
__m128d zero128=_mm_set1_pd(0.0f);
int i;
for(i=size-1;i>=0;i-=hk_VecFPU_SIZE_FLOAT) {
_mm_store_pd(target_adress,zero128);
target_adress+=hk_VecFPU_SIZE_FLOAT;
}
}
#endif
int i;
for(i=size-1;i>=0;i-=hk_VecFPU_SIZE_FLOAT) {
int j;
for(j=0;j<hk_VecFPU_SIZE_FLOAT;j++) {
target_adress[j] = 0.0f;
}
target_adress+=hk_VecFPU_SIZE_FLOAT;
}
}
inline int hk_VecFPU::calc_aligned_row_len(int unaligned_len,hk_real *dummy_type) { //dummy type is used for overloading
return (unaligned_len+hk_VecFPU_SIZE_FLOAT-1)&hk_VecFPU_MASK_FLOAT;
}
//----------------------------------------------------------------------------------------------------------------------
inline void hk_VecFPU::fpu_add_multiple_row(hk_double *target_adress,hk_double *source_adress,hk_double factor,int size,hk_bool adress_aligned) {
if(adress_aligned==HK_FALSE) {
//we have to calculate the block size and shift adresses to lower aligned adresses
long result_adress = long(source_adress) & hk_VecFPU_MEM_MASK_DOUBLE;
target_adress = (hk_double *)( long (target_adress) & hk_VecFPU_MEM_MASK_DOUBLE);
size += (long(source_adress)-result_adress)>>hk_VecFPU_MEMSHIFT_DOUBLE;
source_adress=(hk_double *)result_adress;
}
#if defined(IVP_USE_PS2_VU0)
asm __volatile__("
mfc1 $8,%3
qmtc2 $8,vf5 # vf5.x factor
1:
lqc2 vf4,0x0(%1) # vf4 *source
vmulx.xyzw vf6,vf4,vf5 # vf6 *source * factor
lqc2 vf4,0x0(%0)
addi %0, 0x10
vadd.xyzw vf6,vf4,vf6 # vf6 = *dest + factor * *source
addi %2,-4
addi %1, 0x10
sqc2 vf6,-0x10(%0)
bgtz %2,1b
nop
"
: /* no output */
: "r" (target_adress), "r" (source_adress) , "r" (size), "f" (factor)
: "$8" , "memory");
#else
if(0) {
# if defined(IVP_WILLAMETTE)
;
__m128d factor128=_mm_set1_pd(factor);
for(int i=size;i>0;i-=hk_VecFPU_SIZE_DOUBLE) {
__m128d source_d=_mm_load_pd(source_adress);
__m128d prod_d=_mm_mul_pd(factor128,source_d);
__m128d target_d=_mm_load_pd(target_adress);
target_d=_mm_add_pd(prod_d,target_d);
_mm_store_pd(target_adress,target_d);
target_adress+=hk_VecFPU_SIZE_DOUBLE;
source_adress+=hk_VecFPU_SIZE_DOUBLE;
}
#endif
} else {
for(int i=size;i>0;i-=hk_VecFPU_SIZE_DOUBLE) {
# if hk_VecFPU_SIZE_DOUBLE == 2
hk_double a = source_adress[0] * factor;
hk_double b = source_adress[1] * factor;
a += target_adress[0];
b += target_adress[1];
target_adress[0] = a;
target_adress[1] = b;
# elif hk_VecFPU_SIZE_DOUBLE == 4
hk_double a = source_adress[0] * factor;
hk_double b = source_adress[1] * factor;
hk_double c = source_adress[2] * factor;
hk_double d = source_adress[3] * factor;
a += target_adress[0];
b += target_adress[1];
c += target_adress[2];
d += target_adress[3];
target_adress[0] = a;
target_adress[1] = b;
target_adress[2] = c;
target_adress[3] = d;
# else
shit
# endif
target_adress+=hk_VecFPU_SIZE_DOUBLE;
source_adress+=hk_VecFPU_SIZE_DOUBLE;
}
}
#endif
}
inline hk_double hk_VecFPU::fpu_large_dot_product(hk_double *base_a, hk_double *base_b, int size, hk_bool adress_aligned) {
if(adress_aligned==HK_FALSE) {
//we have to calculate the block size and shift adresses to lower aligned adresses
long result_adress = long(base_a) & hk_VecFPU_MEM_MASK_DOUBLE;
base_b = (hk_double *)( long (base_b) & hk_VecFPU_MEM_MASK_DOUBLE);
size += (long(base_a)-result_adress)>>hk_VecFPU_MEMSHIFT_DOUBLE; // because start changed
base_a=(hk_double *)result_adress;
}
# if defined(IVP_WILLAMETTE)
if(0) {
__m128d sum128 =_mm_set1_pd(0.0);
int i;
for(i=size;i>=hk_VecFPU_SIZE_DOUBLE; i-= hk_VecFPU_SIZE_DOUBLE) {
__m128d mult1=_mm_load_pd(base_a);
__m128d mult2=_mm_load_pd(base_b);
__m128d prod =_mm_mul_pd(mult1,mult2);
sum128 =_mm_add_pd(prod,sum128);
base_a += hk_VecFPU_SIZE_DOUBLE;
base_b += hk_VecFPU_SIZE_DOUBLE;
}
__m128d dummy,low,high;
low=sum128;
dummy=sum128;
//_mm_shuffle_pd(sum128,sum128,1); //swap high and low
sum128=_mm_unpackhi_pd(sum128,dummy);
high=sum128;
__m128d sum64=_mm_add_sd(low,high);
__m128d res=sum64;
//_mm_shuffle_pd(sum64,sum64,1);
hk_double result_sum;
_mm_store_sd(&result_sum,res);
for(;i>=0;i--) {
result_sum += base_a[i] * base_b[i];
}
return result_sum;
} else {
hk_double sum=0.0;
for(int i=size-1;i>=0;i--) {
sum += base_a[i] * base_b[i];
}
return sum;
}
#else
hk_double sum=0.0;
for(int i=size-1;i>=0;i--) {
sum += base_a[i] * base_b[i];
}
return sum;
#endif
}
inline void hk_VecFPU::fpu_multiply_row(hk_double *target_adress,hk_double factor,int size,hk_bool adress_aligned) {
if(adress_aligned==HK_FALSE) {
//we have to calculate the block size and shift adresses to lower aligned adresses
long adress,result_adress;
adress=(long)target_adress;
result_adress=adress & hk_VecFPU_MEM_MASK_DOUBLE;
size+=(adress-result_adress)>>hk_VecFPU_MEMSHIFT_DOUBLE;
target_adress=(hk_double *)result_adress;
}
if(0) {
#ifdef IVP_WILLAMETTE
__m128d factor128=_mm_set1_pd(factor);
int i;
for(i=size;i>0;i-=hk_VecFPU_SIZE_DOUBLE) {
__m128d target_d=_mm_load_pd(target_adress);
target_d=_mm_mul_pd(factor128,target_d);
_mm_store_pd(target_adress,target_d);
target_adress+=hk_VecFPU_SIZE_DOUBLE;
}
#endif
} else {
int i;
for(i=size;i>0;i-=hk_VecFPU_SIZE_DOUBLE) {
# if hk_VecFPU_SIZE_DOUBLE == 2
hk_double a = target_adress[0] * factor;
hk_double b = target_adress[1] * factor;
target_adress[0] = a;
target_adress[1] = b;
# elif hk_VecFPU_SIZE_DOUBLE == 4
hk_double a = target_adress[0] * factor;
hk_double b = target_adress[1] * factor;
hk_double c = target_adress[2] * factor;
hk_double d = target_adress[3] * factor;
target_adress[0] = a;
target_adress[1] = b;
target_adress[2] = c;
target_adress[3] = d;
# else
shit
# endif
target_adress+=hk_VecFPU_SIZE_DOUBLE;
}
}
}
// #+# sparc says rui, optimize for non vector units ( hk_VecFPU_SIZE_DOUBLE = 4 )
inline void hk_VecFPU::fpu_exchange_rows(hk_double *target_adress1,hk_double *target_adress2,int size,hk_bool adress_aligned) {
if(adress_aligned==HK_FALSE) {
//we have to calculate the block size and shift adresses to lower aligned adresses
long adress,result_adress;
adress=(long)target_adress1;
result_adress=adress & hk_VecFPU_MEM_MASK_DOUBLE;
size+=(adress-result_adress)>>hk_VecFPU_MEMSHIFT_DOUBLE;
target_adress1=(hk_double *)result_adress;
adress=(long)target_adress2;
adress=adress & hk_VecFPU_MEM_MASK_DOUBLE;
target_adress2=(hk_double *)adress;
}
if(0) {
#ifdef IVP_WILLAMETTE
int i;
for(i=size;i>0;i-=hk_VecFPU_SIZE_DOUBLE) {
__m128d a_d=_mm_load_pd(target_adress1);
__m128d b_d=_mm_load_pd(target_adress2);
_mm_store_pd(target_adress1,b_d);
_mm_store_pd(target_adress2,a_d);
target_adress1+=hk_VecFPU_SIZE_DOUBLE;
target_adress2+=hk_VecFPU_SIZE_DOUBLE;
}
#endif
} else {
int i;
for(i=size;i>0;i-=hk_VecFPU_SIZE_DOUBLE) {
hk_double h;
# if hk_VecFPU_SIZE_DOUBLE == 2
h=target_adress1[0]; target_adress1[0]=target_adress2[0]; target_adress2[0]=h;
h=target_adress1[1]; target_adress1[1]=target_adress2[1]; target_adress2[1]=h;
# elif hk_VecFPU_SIZE_DOUBLE == 4
h=target_adress1[0]; target_adress1[0]=target_adress2[0]; target_adress2[0]=h;
h=target_adress1[1]; target_adress1[1]=target_adress2[1]; target_adress2[1]=h;
h=target_adress1[2]; target_adress1[2]=target_adress2[2]; target_adress2[2]=h;
h=target_adress1[3]; target_adress1[3]=target_adress2[3]; target_adress2[3]=h;
# else
shit
# endif
target_adress1+=hk_VecFPU_SIZE_DOUBLE;
target_adress2+=hk_VecFPU_SIZE_DOUBLE;
}
}
}
inline void hk_VecFPU::fpu_copy_rows(hk_double *target_adress,hk_double *source_adress,int size,hk_bool adress_aligned) {
if(adress_aligned==HK_FALSE) {
//we have to calculate the block size and shift adresses to lower aligned adresses
long adress,result_adress;
adress=(long)source_adress;
result_adress=adress & hk_VecFPU_MEM_MASK_DOUBLE;
size+=(adress-result_adress)>>hk_VecFPU_MEMSHIFT_DOUBLE;
source_adress=(hk_double *)result_adress;
adress=(long)target_adress;
adress=adress & hk_VecFPU_MEM_MASK_DOUBLE;
target_adress=(hk_double *)adress;
}
#ifdef HK_WILLAMETTE
int i;
for(i=size-1;i>=0;i-=hk_VecFPU_SIZE_DOUBLE) {
__m128d target_d=_mm_load_pd(source_adress);
_mm_store_pd(target_adress,target_d);
target_adress+=hk_VecFPU_SIZE_DOUBLE;
source_adress+=hk_VecFPU_SIZE_DOUBLE;
}
#else
int i;
for(i=size-1;i>=0;i-=hk_VecFPU_SIZE_DOUBLE) {
int j;
for(j=0;j<hk_VecFPU_SIZE_DOUBLE;j++) {
target_adress[j] = source_adress[j];
}
target_adress+=hk_VecFPU_SIZE_DOUBLE;
source_adress+=hk_VecFPU_SIZE_DOUBLE;
}
#endif
}
inline void hk_VecFPU::fpu_set_row_to_zero(hk_double *target_adress,int size,hk_bool adress_aligned) {
if(adress_aligned==HK_FALSE) {
long adress,result_adress;
adress=(long)target_adress;
result_adress=adress & hk_VecFPU_MEM_MASK_DOUBLE;
size+=(adress-result_adress)>>hk_VecFPU_MEMSHIFT_DOUBLE;
target_adress=(hk_double *)result_adress;
}
if(0) {
#ifdef IVP_WILLAMETTE
__m128d zero128=_mm_set1_pd(0.0f);
int i;
for(i=size-1;i>=0;i-=hk_VecFPU_SIZE_DOUBLE) {
_mm_store_pd(target_adress,zero128);
target_adress+=hk_VecFPU_SIZE_DOUBLE;
}
#endif
} else {
int i;
for(i=size-1;i>=0;i-=hk_VecFPU_SIZE_DOUBLE) {
int j;
for(j=0;j<hk_VecFPU_SIZE_DOUBLE;j++) {
target_adress[j] = 0.0f;
}
target_adress+=hk_VecFPU_SIZE_DOUBLE;
}
}
}
inline int hk_VecFPU::calc_aligned_row_len(int unaligned_len,hk_double *dummy_type) { //dummy type is used for overloading
return (unaligned_len+hk_VecFPU_SIZE_DOUBLE-1)&hk_VecFPU_MASK_DOUBLE;
}
| 32.923205
| 146
| 0.66092
|
DannyParker0001
|
dedc9bea22e4d12bc1c587ec698d2444e590a3be
| 4,793
|
cpp
|
C++
|
SimSpark/rcssserver3d/plugin/soccer/gamestateperceptor/gamestateperceptor.cpp
|
IllyasvielEin/Robocup3dInstaller
|
12e91d9372dd08a92feebf98e916c98bc2242ff4
|
[
"MIT"
] | null | null | null |
SimSpark/rcssserver3d/plugin/soccer/gamestateperceptor/gamestateperceptor.cpp
|
IllyasvielEin/Robocup3dInstaller
|
12e91d9372dd08a92feebf98e916c98bc2242ff4
|
[
"MIT"
] | null | null | null |
SimSpark/rcssserver3d/plugin/soccer/gamestateperceptor/gamestateperceptor.cpp
|
IllyasvielEin/Robocup3dInstaller
|
12e91d9372dd08a92feebf98e916c98bc2242ff4
|
[
"MIT"
] | null | null | null |
/* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*-
this file is part of rcssserver3D
Fri May 9 2003
Copyright (C) 2002,2003 Koblenz University
Copyright (C) 2003 RoboCup Soccer Server 3D Maintenance Group
$Id$
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; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "gamestateperceptor.h"
#include <zeitgeist/logserver/logserver.h>
#include <soccerbase/soccerbase.h>
#include <agentstate/agentstate.h>
#include <gamestateaspect/gamestateaspect.h>
using namespace zeitgeist;
using namespace oxygen;
using namespace boost;
using namespace std;
GameStatePerceptor::GameStatePerceptor() : oxygen::Perceptor()
{
mFirstPercept = true;
mReportScore = true;
}
GameStatePerceptor::~GameStatePerceptor()
{
}
void
GameStatePerceptor::InsertSoccerParam(Predicate& predicate, const std::string& name)
{
float value;
if (! SoccerBase::GetSoccerVar(*this,name,value))
{
return;
}
ParameterList& element = predicate.parameter.AddList();
element.AddValue(name);
element.AddValue(value);
}
void
GameStatePerceptor::InsertInitialPercept(Predicate& predicate)
{
// uniform number
ParameterList& unumElement = predicate.parameter.AddList();
unumElement.AddValue(string("unum"));
unumElement.AddValue(mAgentState->GetUniformNumber());
// team index
std::string team;
switch (mAgentState->GetTeamIndex())
{
case TI_NONE :
team = "none";
break;
case TI_LEFT :
team = "left";
break;
case TI_RIGHT :
team = "right";
break;
}
ParameterList& teamElement = predicate.parameter.AddList();
teamElement.AddValue(string("team"));
teamElement.AddValue(team);
// soccer variables
// field geometry parameter
// InsertSoccerParam(predicate,"FieldLength");
// InsertSoccerParam(predicate,"FieldWidth");
// InsertSoccerParam(predicate,"FieldHeight");
// InsertSoccerParam(predicate,"GoalWidth");
// InsertSoccerParam(predicate,"GoalDepth");
// InsertSoccerParam(predicate,"GoalHeight");
// InsertSoccerParam(predicate,"BorderSize");
// // agent parameter
// InsertSoccerParam(predicate,"AgentMass");
// InsertSoccerParam(predicate,"AgentRadius");
// InsertSoccerParam(predicate,"AgentMaxSpeed");
// // ball parameter
// InsertSoccerParam(predicate,"BallRadius");
// InsertSoccerParam(predicate,"BallMass");
}
bool
GameStatePerceptor::Percept(boost::shared_ptr<PredicateList> predList)
{
if (
(mGameState.get() == 0) ||
(mAgentState.get() == 0)
)
{
return false;
}
Predicate& predicate = predList->AddPredicate();
predicate.name = "GS";
predicate.parameter.Clear();
// with the first GameState percept after the player is assigned
// to a team it receives info about it's team and unum assignment
// along with outher soccer parameters
if (
(mFirstPercept) &&
(mAgentState->GetTeamIndex() != TI_NONE)
)
{
mFirstPercept = false;
InsertInitialPercept(predicate);
}
if (mReportScore) {
// score left
ParameterList& slElement = predicate.parameter.AddList();
slElement.AddValue(string("sl"));
slElement.AddValue(mGameState->GetScore(TI_LEFT));
// score right
ParameterList& srElement = predicate.parameter.AddList();
srElement.AddValue(string("sr"));
srElement.AddValue(mGameState->GetScore(TI_RIGHT));
}
// time
ParameterList& timeElement = predicate.parameter.AddList();
timeElement.AddValue(string("t"));
timeElement.AddValue(mGameState->GetTime());
// playmode
ParameterList& pmElement = predicate.parameter.AddList();
pmElement.AddValue(string("pm"));
pmElement.AddValue(SoccerBase::PlayMode2Str(mGameState->GetPlayMode()));
return true;
}
void
GameStatePerceptor::OnLink()
{
SoccerBase::GetGameState(*this,mGameState);
SoccerBase::GetAgentState(*this,mAgentState);
SoccerBase::GetSoccerVar(*this,"ReportScore",mReportScore);
}
void
GameStatePerceptor::OnUnlink()
{
mGameState.reset();
mAgentState.reset();
}
| 28.194118
| 84
| 0.685583
|
IllyasvielEin
|
dedd51ee810c8f039746f6cede22295f7057ad54
| 2,838
|
cc
|
C++
|
content/browser/renderer_host/pepper/browser_ppapi_host_impl.cc
|
junmin-zhu/chromium-rivertrail
|
eb1a57aca71fe68d96e48af8998dcfbe45171ee1
|
[
"BSD-3-Clause"
] | 5
|
2018-03-10T13:08:42.000Z
|
2021-07-26T15:02:11.000Z
|
content/browser/renderer_host/pepper/browser_ppapi_host_impl.cc
|
quisquous/chromium
|
b25660e05cddc9d0c3053b3514f07037acc69a10
|
[
"BSD-3-Clause"
] | 1
|
2015-07-21T08:02:01.000Z
|
2015-07-21T08:02:01.000Z
|
content/browser/renderer_host/pepper/browser_ppapi_host_impl.cc
|
jianglong0156/chromium.src
|
d496dfeebb0f282468827654c2b3769b3378c087
|
[
"BSD-3-Clause"
] | 6
|
2016-11-14T10:13:35.000Z
|
2021-01-23T15:29:53.000Z
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/pepper/browser_ppapi_host_impl.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_view_host.h"
#include "ipc/ipc_message_macros.h"
namespace content {
BrowserPpapiHostImpl::BrowserPpapiHostImpl(
IPC::Sender* sender,
const ppapi::PpapiPermissions& permissions)
: ppapi_host_(sender, permissions),
plugin_process_handle_(base::kNullProcessHandle) {
ppapi_host_.AddHostFactoryFilter(scoped_ptr<ppapi::host::HostFactory>(
new ContentBrowserPepperHostFactory(this)));
}
BrowserPpapiHostImpl::~BrowserPpapiHostImpl() {
}
bool BrowserPpapiHostImpl::OnMessageReceived(const IPC::Message& msg) {
/* TODO(brettw) when we add messages, here, the code should look like this:
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(BrowserPpapiHostImpl, msg)
// Add necessary message handlers here.
IPC_MESSAGE_UNHANDLED(handled = ppapi_host_.OnMessageReceived(msg))
IPC_END_MESSAGE_MAP();
return handled;
*/
return ppapi_host_.OnMessageReceived(msg);
}
ppapi::host::PpapiHost* BrowserPpapiHostImpl::GetPpapiHost() {
return &ppapi_host_;
}
base::ProcessHandle BrowserPpapiHostImpl::GetPluginProcessHandle() const {
// Handle should previously have been set before use.
DCHECK(plugin_process_handle_ != base::kNullProcessHandle);
return plugin_process_handle_;
}
bool BrowserPpapiHostImpl::IsValidInstance(PP_Instance instance) const {
return instance_to_view_.find(instance) != instance_to_view_.end();
}
bool BrowserPpapiHostImpl::GetRenderViewIDsForInstance(
PP_Instance instance,
int* render_process_id,
int* render_view_id) const {
InstanceToViewMap::const_iterator found = instance_to_view_.find(instance);
if (found == instance_to_view_.end()) {
*render_process_id = 0;
*render_view_id = 0;
return false;
}
*render_process_id = found->second.process_id;
*render_view_id = found->second.view_id;
return true;
}
void BrowserPpapiHostImpl::AddInstanceForView(PP_Instance instance,
int render_process_id,
int render_view_id) {
DCHECK(instance_to_view_.find(instance) == instance_to_view_.end());
RenderViewIDs ids;
ids.process_id = render_process_id;
ids.view_id = render_view_id;
instance_to_view_[instance] = ids;
}
void BrowserPpapiHostImpl::DeleteInstanceForView(PP_Instance instance) {
InstanceToViewMap::iterator found = instance_to_view_.find(instance);
if (found == instance_to_view_.end()) {
NOTREACHED();
return;
}
instance_to_view_.erase(found);
}
} // namespace content
| 32.25
| 77
| 0.744891
|
junmin-zhu
|
dee02e61c6026421062ff37899f6387291f3d3c8
| 325
|
cpp
|
C++
|
mutations_aliens/main.cpp
|
aymeebonvarlet/projet_mutation_aliens
|
a1885d77d9ef197395c7f9545d96105fdac47018
|
[
"Apache-2.0"
] | null | null | null |
mutations_aliens/main.cpp
|
aymeebonvarlet/projet_mutation_aliens
|
a1885d77d9ef197395c7f9545d96105fdac47018
|
[
"Apache-2.0"
] | null | null | null |
mutations_aliens/main.cpp
|
aymeebonvarlet/projet_mutation_aliens
|
a1885d77d9ef197395c7f9545d96105fdac47018
|
[
"Apache-2.0"
] | null | null | null |
#include "mainwindow.h"
#include "qstd.h"
using namespace qstd;
#include <QApplication>
#include "evolutionnary_process.h"
int main(int argc, char *argv[])
{
Evolutionnary_process evo;
evo.init();
cout<<evo.toString()<<endl;
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
| 19.117647
| 34
| 0.664615
|
aymeebonvarlet
|
dee0c4a6231b74e6f1b2d9129bdf422fd8e12380
| 616
|
cpp
|
C++
|
08_pass-by-reference/src/main.cpp
|
JuliusDiestra/cpp-sandbox
|
6fa3bcb2a284e58136168e1952a8a54621232621
|
[
"MIT"
] | null | null | null |
08_pass-by-reference/src/main.cpp
|
JuliusDiestra/cpp-sandbox
|
6fa3bcb2a284e58136168e1952a8a54621232621
|
[
"MIT"
] | null | null | null |
08_pass-by-reference/src/main.cpp
|
JuliusDiestra/cpp-sandbox
|
6fa3bcb2a284e58136168e1952a8a54621232621
|
[
"MIT"
] | null | null | null |
#include "vehicle.hpp"
#include "controller.hpp"
int main(int argc, char *argv[]) {
// Create vehicle object
Vehicle vehicle;
vehicle.SetVelocity(20);
vehicle.SetAcceleration(30);
std::cout << "### Vehicle Object ###" << std::endl;
std::cout << "velocity:" << vehicle.GetVelocity() << std::endl;
std::cout << "acceleration:" << vehicle.GetAcceleration() << std::endl;
Controller controller(vehicle);
controller.ChangeVehicleVelocity(40);
std::cout << "### Vehicle Object ###" << std::endl;
std::cout << "velocity:" << vehicle.GetVelocity() << std::endl;
return 0;
}
| 32.421053
| 75
| 0.625
|
JuliusDiestra
|
dee0f6e51b0bf08f7f3b1b3f4ce0dede9913d9f2
| 2,898
|
cpp
|
C++
|
Source/Extensions/PGUI/PGUI.Screen.cpp
|
wipe2238/foc
|
87f083e4d12178244953857ee89da488b31d0a9b
|
[
"MIT"
] | 2
|
2018-12-14T23:06:21.000Z
|
2021-07-29T03:10:38.000Z
|
Source/Extensions/PGUI/PGUI.Screen.cpp
|
wipe2238/foc
|
87f083e4d12178244953857ee89da488b31d0a9b
|
[
"MIT"
] | 1
|
2020-08-25T10:38:00.000Z
|
2020-08-25T10:38:00.000Z
|
Source/Extensions/PGUI/PGUI.Screen.cpp
|
wipe2238/foc
|
87f083e4d12178244953857ee89da488b31d0a9b
|
[
"MIT"
] | null | null | null |
#include <App.h>
#include <Defines.Public.h>
#include <GameOptions.h>
#include <Ini.h>
#include "PGUI.Core.h"
#include "PGUI.Screen.h"
PGUI::Screen::Screen( PGUI::Core* gui, uint width /* = 0 */, uint height /* = 0 */, int left /* = 0 */, int top /* = 0 */ ) : PGUI::Element( gui, width, height, left, top ),
// public
IsMovable( true ),
Layer( 0 ),
ScreenData( nullptr ),
// protected
DrawLayer( 0 )
{}
PGUI::Screen::~Screen()
{
if( GUI->Debug )
App.WriteLogF( _FUNC_, "\n" );
}
uint PGUI::Screen::GetID()
{
return GUI->GetScreenID( this );
}
bool PGUI::Screen::LoadSettings( Ini* ini, const std::string& section )
{
if( !ini )
{
// if (Debug)
App.WriteLogF( _FUNC_, " WARNING : ini is null\n", section.c_str() );
return false;
}
if( ini->IsSection( section ) )
{
// if (Debug)
App.WriteLogF( _FUNC_, " WARNING : section<%s> not found\n", section.c_str() );
return false;
}
return true;
}
void PGUI::Screen::AutoSize()
{
uint16 width = 0, height = 0;
for( auto it = Elements.begin(), end = Elements.end(); it != end; ++it )
{
PGUI::Element* element = it->second;
if( !element )
continue;
uint16 w = element->GetWidth() + element->GetLeft( true );
uint16 h = element->GetHeight() + element->GetTop( true );
width = std::max( width, w );
height = std::max( height, h );
}
if( GUI->Debug )
App.WriteLogF( _FUNC_, " = %ux%u\n", width, height );
SetSize( width, height );
}
void PGUI::Screen::MouseMove( int16 fromX, int16 fromY, int16 toX, int16 toY )
{
if( !IsMouseEnabled )
return;
if( IsMovable && MousePressed && MouseButton == MOUSE_CLICK_LEFT )
{
int16 oldLeft = 0, oldTop = 0;
GetPosition( oldLeft, oldTop, true );
int newLeft = oldLeft + (toX - fromX);
int newTop = oldTop + (toY - fromY);
bool reset = false;
if( newLeft < 0 )
{
newLeft = 0;
reset = true;
}
if( newTop < 0 )
{
newTop = 0;
reset = true;
}
uint16 width = 0, height = 0;
GetSize( width, height );
if( newLeft + width > GUI->GetScreenWidth() )
{
newLeft = GUI->GetScreenWidth() - width;
reset = true;
}
if( newTop + height > GUI->GetScreenHeight() )
{
newTop = GUI->GetScreenHeight() - height;
reset = true;
}
if( reset )
{
// TODO cursor goes crazy here
// GameOpt.MouseX = fromX;
// GameOpt.MouseY = fromY;
}
if( oldLeft != newLeft || oldTop != newTop )
SetPosition( newLeft, newTop );
}
PGUI::Element::MouseMove( fromX, fromY, toX, toY );
}
| 22.640625
| 173
| 0.515528
|
wipe2238
|
dee106f0ef1f044ea3ecd0fcbb3d197955f98a5f
| 668
|
cpp
|
C++
|
problems/lazyloading/submissions/accepted/lel.cpp
|
stoman/CompetitiveProgramming
|
0000b64369b50e31c6f48939e837bdf6cece8ce4
|
[
"MIT"
] | 2
|
2020-12-22T13:21:25.000Z
|
2021-12-12T22:26:26.000Z
|
problems/lazyloading/submissions/accepted/lel.cpp
|
stoman/CompetitiveProgramming
|
0000b64369b50e31c6f48939e837bdf6cece8ce4
|
[
"MIT"
] | null | null | null |
problems/lazyloading/submissions/accepted/lel.cpp
|
stoman/CompetitiveProgramming
|
0000b64369b50e31c6f48939e837bdf6cece8ce4
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#define MAXN 105
using namespace std;
int t, n, ans, lo, hi, maxim, how;
int w[MAXN];
int main( ) {
scanf( "%d", &t );
for ( int T = 0; T < t; ++T ) {
scanf( "%d", &n );
for ( int i = 1; i <= n; ++i ) {
scanf( "%d", &w[i] );
}
sort( w+1, w+n+1 );
ans = 0;
lo = 1;
hi = n;
ans = 0;
while ( lo <= hi ) {
maxim = w[hi];
how = 1;
while ( lo < hi ) {
if ( maxim * how >= 50 ) {
break;
}
++lo;
++how;
}
if ( maxim * how >= 50 ) {
++ans;
}
--hi;
}
printf( "Case #%d: %d\n", T+1, ans );
}
return 0;
}
| 11.133333
| 39
| 0.42515
|
stoman
|
dee18f7be43af0742ef1a141d1cc2b540d142fa3
| 9,745
|
hh
|
C++
|
nodecursor.hh
|
cp-profiler/cp-profiler-deprecated-
|
ec163bde5c3a5bd9cc428b8fa8fd6ef713e0247a
|
[
"MIT-feh"
] | 1
|
2021-05-06T04:41:37.000Z
|
2021-05-06T04:41:37.000Z
|
nodecursor.hh
|
cp-profiler/cp-profiler-deprecated-
|
ec163bde5c3a5bd9cc428b8fa8fd6ef713e0247a
|
[
"MIT-feh"
] | null | null | null |
nodecursor.hh
|
cp-profiler/cp-profiler-deprecated-
|
ec163bde5c3a5bd9cc428b8fa8fd6ef713e0247a
|
[
"MIT-feh"
] | 1
|
2021-05-06T04:41:39.000Z
|
2021-05-06T04:41:39.000Z
|
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Guido Tack <tack@gecode.org>
*
* Copyright:
* Guido Tack, 2006
*
* Last modified:
* $Date$ by $Author$
* $Revision$
*
* This file is part of Gecode, the generic constraint
* development environment:
* http://www.gecode.org
*
* 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 GECODE_GIST_NODECURSOR_HH
#define GECODE_GIST_NODECURSOR_HH
#include "nodecursor_base.hh"
#include <vector>
#include <QTextStream>
class TreeCanvas;
class Execution;
class VisualNode;
/// \brief A cursor that marks failed subtrees as hidden
class HideFailedCursor : public NodeCursor {
private:
bool onlyDirty;
public:
/// Constructor
HideFailedCursor(VisualNode* theNode,
const NodeAllocator& na,
bool onlyDirtyNodes);
/// \name Cursor interface
//@{
/// Test if the cursor may move to the first child node
bool mayMoveDownwards(void) const;
/// Process node
void processCurrentNode(void);
//@}
};
/// \brief A cursor that marks all nodes in the tree as not hidden
class UnhideAllCursor : public NodeCursor {
public:
/// Constructor
UnhideAllCursor(VisualNode* theNode,
const NodeAllocator& na);
/// \name Cursor interface
//@{
/// Process node
void processCurrentNode(void);
//@}
};
/// \brief A cursor that marks all nodes in the tree as not selected
class UnselectAllCursor : public NodeCursor {
public:
/// Constructor
UnselectAllCursor(VisualNode* theNode,
const NodeAllocator& na);
/// \name Cursor interface
//@{
/// Process node
void processCurrentNode(void);
//@}
};
/// \brief A cursor that marks ancestor nodes in the tree as not hidden
class UnhideAncestorsCursor : public NodeCursor {
public:
/// Constructor
UnhideAncestorsCursor(VisualNode* theNode,
const NodeAllocator& na);
/// \name Cursor interface
//@{
/// Test if the cursor may move to the parent node
bool mayMoveUpwards(void) const;
/// Process node
void processCurrentNode(void);
//@}
};
/// \brief A cursor that marks all nodes in the tree as hidden
class HideAllCursor : public NodeCursor {
public:
/// Constructor
HideAllCursor(VisualNode* theNode,
const NodeAllocator& na);
/// \name Cursor interface
//@{
/// Process node
void processCurrentNode(void);
//@}
};
/// \brief A cursor that finds the next solution
class NextSolCursor : public NodeCursor {
private:
/// Whether to search backwards
bool back;
/// Whether the current node is not a solution
bool notOnSol(void) const;
public:
/// Constructor
NextSolCursor(VisualNode* theNode, bool backwards,
const NodeAllocator& na);
/// \name Cursor interface
//@{
/// Do nothing
void processCurrentNode(void);
/// Test if the cursor may move to the parent node
bool mayMoveUpwards(void) const;
/// Test if cursor may move to the first child node
bool mayMoveDownwards(void) const;
/// Move cursor to the first child node
void moveDownwards(void);
/// Test if cursor may move to the first sibling
bool mayMoveSidewards(void) const;
/// Move cursor to the first sibling
void moveSidewards(void);
//@}
};
/// \brief A cursor that finds the next leaf
class NextLeafCursor : public NodeCursor {
private:
/// Whether to search backwards
bool back;
/// Whether the current node is not a leaf
bool notOnLeaf(void) const;
public:
/// Constructor
NextLeafCursor(VisualNode* theNode, bool backwards,
const NodeAllocator& na);
/// \name Cursor interface
//@{
/// Do nothing
void processCurrentNode(void);
/// Test if the cursor may move to the parent node
bool mayMoveUpwards(void) const;
/// Test if cursor may move to the first child node
bool mayMoveDownwards(void) const;
/// Move cursor to the first child node
void moveDownwards(void);
/// Test if cursor may move to the first sibling
bool mayMoveSidewards(void) const;
/// Move cursor to the first sibling
void moveSidewards(void);
//@}
};
/// \brief A cursor that finds the next pentagon
class NextPentagonCursor : public NodeCursor {
private:
/// Whether to search backwards
bool back;
/// Whether the current node is not a pentagon
bool notOnPentagon(void) const;
public:
/// Constructor
NextPentagonCursor(VisualNode* theNode, bool backwards,
const NodeAllocator& na);
/// \name Cursor interface
//@{
/// Do nothing
void processCurrentNode(void);
/// Test if the cursor may move to the parent node
bool mayMoveUpwards(void) const;
/// Test if cursor may move to the first child node
bool mayMoveDownwards(void) const;
/// Move cursor to the first child node
void moveDownwards(void);
/// Test if cursor may move to the first sibling
bool mayMoveSidewards(void) const;
/// Move cursor to the first sibling
void moveSidewards(void);
//@}
};
/// \brief A cursor that collects statistics
class StatCursor : public NodeCursor {
private:
/// Current depth
int curDepth;
public:
/// Depth of the search tree
int depth;
/// Number of failed nodes
int failed;
/// Number of solved nodes
int solved;
/// Number of choice nodes
int choice;
/// Number of open nodes
int open;
/// Constructor
StatCursor(VisualNode* theNode,
const NodeAllocator& na);
/// \name Cursor interface
//@{
/// Collect statistics
void processCurrentNode(void);
/// Move cursor to the first child node
void moveDownwards(void);
/// Move cursor to the parent node
void moveUpwards(void);
//@}
};
class HighlightCursor : public NodeCursor {
public:
// Constructor
HighlightCursor(VisualNode* startNode, const NodeAllocator& na);
// Highlight all the nodes below
void processCurrentNode(void);
};
class UnhighlightCursor : public NodeCursor {
public:
// Constructor
UnhighlightCursor(VisualNode* root, const NodeAllocator& na);
// Unhighlight all the nodes below
void processCurrentNode(void);
};
class CountSolvedCursor : public NodeCursor {
public:
CountSolvedCursor(VisualNode* startNode, const NodeAllocator& na, int &count);
// Count solved leaves and store the nubmer in count variable
void processCurrentNode(void);
private:
int &_count;
};
class GetIndexesCursor : public NodeCursor {
public:
// Constructor
GetIndexesCursor(VisualNode* startNode, const NodeAllocator& na,
std::vector<int>& node_gids);
// Populate node_gids vector with gid of nodes
void processCurrentNode(void);
private:
const NodeAllocator& _na;
std::vector<int>& _node_gids;
};
/// Hide subtrees that are not highlighted
class HideNotHighlightedCursor : public NodeCursor {
protected:
QHash<VisualNode*,bool> onHighlightPath;
public:
/// Constructor
HideNotHighlightedCursor(VisualNode* startNode, const NodeAllocator& na);
/// Process node
void processCurrentNode(void);
/// Test if cursor may move to the first child node
bool mayMoveDownwards(void) const;
};
/// \brief A cursor that labels branches
class BranchLabelCursor : public NodeCursor {
private:
/// The node allocator
NodeAllocator& _na;
/// Current TreeCanvas instance (extract labels from data)
TreeCanvas& _tc;
/// Whether to clear labels
bool _clear;
public:
/// Constructor
BranchLabelCursor(VisualNode* theNode, bool clear,
NodeAllocator& na, TreeCanvas& tc);
/// \name Cursor interface
//@{
void processCurrentNode(void);
//@}
};
class SubtreeCountCursor : public NodeCursor {
public:
std::vector<int> stack;
int threshold;
SubtreeCountCursor(VisualNode *theNode,
int _threshold,
const NodeAllocator& na);
void processCurrentNode(void);
void moveSidewards(void);
void moveUpwards(void);
void moveDownwards(void);
};
class SearchLogCursor : public NodeCursor {
private:
QTextStream& _out;
/// The node allocator
const NodeAllocator& _na;
/// TODO(maxim): should have a reference to the execution here
const Execution& _execution;
public:
SearchLogCursor(VisualNode *theNode,
QTextStream& outputStream,
const NodeAllocator& na,
const Execution& execution);
void processCurrentNode(void);
};
#include "nodecursor.hpp"
#endif
| 28.328488
| 80
| 0.677783
|
cp-profiler
|
dee63efa3f0c22e5bb79cef4e943cfc3e049ed24
| 2,316
|
hpp
|
C++
|
src/Modules/ModuleBuilder.hpp
|
pawel-jarosz/nastya-lisp
|
813a58523b741e00c8c27980fe658b546e9ff38c
|
[
"MIT"
] | 1
|
2021-03-12T13:39:17.000Z
|
2021-03-12T13:39:17.000Z
|
src/Modules/ModuleBuilder.hpp
|
pawel-jarosz/nastya-lisp
|
813a58523b741e00c8c27980fe658b546e9ff38c
|
[
"MIT"
] | null | null | null |
src/Modules/ModuleBuilder.hpp
|
pawel-jarosz/nastya-lisp
|
813a58523b741e00c8c27980fe658b546e9ff38c
|
[
"MIT"
] | null | null | null |
//
// Created by caedus on 30.01.2021.
//
#pragma once
#include "Modules/Module.hpp"
#include "Runtime/Interface/IEvaluatorFactory.hpp"
#include "Modules/Interface/IModuleBuilder.hpp"
#include <algorithm>
namespace nastya::modules {
template<typename EvaluatorFactory, typename... OtherFactories>
class ModuleBuilder : public ModuleBuilder<OtherFactories...> {
public:
explicit ModuleBuilder(std::string moduleName);
std::unique_ptr<IModule> build() override;
};
template<typename EvaluatorFactory>
class ModuleBuilder<EvaluatorFactory> : public IModuleBuilder {
public:
explicit ModuleBuilder(std::string moduleName);
std::unique_ptr<IModule> build() override;
std::vector<std::unique_ptr<runtime::IEvaluatorFactory>>& getFactories() {
return m_factories;
}
protected:
std::unique_ptr<Module> m_module;
std::string m_module_name;
std::vector<std::unique_ptr<runtime::IEvaluatorFactory>> m_factories;
};
template<typename EvaluatorFactory, typename... OtherFactory>
std::unique_ptr<IModule> ModuleBuilder<EvaluatorFactory, OtherFactory...>::build() {
return ModuleBuilder<OtherFactory...>::build();
}
template<typename EvaluatorFactory, typename... OtherFactories>
ModuleBuilder<EvaluatorFactory, OtherFactories...>::ModuleBuilder(std::string moduleName)
: ModuleBuilder<OtherFactories...>(std::move(moduleName)) {
std::unique_ptr<runtime::IEvaluatorFactory> factory(new EvaluatorFactory);
ModuleBuilder<OtherFactories...>::getFactories().emplace_back(std::move(factory));
}
template<typename EvaluatorFactory>
ModuleBuilder<EvaluatorFactory>::ModuleBuilder(std::string moduleName)
: m_module{new Module{moduleName}}
, m_module_name(std::move(moduleName))
, m_factories{}
{
std::unique_ptr<runtime::IEvaluatorFactory> factory(new EvaluatorFactory);
m_factories.emplace_back(std::move(factory));
}
template<typename EvaluatorFactory>
std::unique_ptr<IModule> ModuleBuilder<EvaluatorFactory>::build()
{
using Factory = std::unique_ptr<runtime::IEvaluatorFactory>;
std::for_each(m_factories.begin(), m_factories.end(), [&](const Factory& factory) {
m_module->registerFunction(factory->create());
});
auto new_module = std::make_unique<Module>(m_module_name);
m_module.swap(new_module);
return new_module;
}
}
| 33.085714
| 89
| 0.756045
|
pawel-jarosz
|
dee7db73453cfe5478fcf165793c973eaba126fc
| 2,150
|
cpp
|
C++
|
src/DescentGame/src/Main.cpp
|
poseidn/KungFoo
|
35fa33bd5a9abb40ecf485db2fc038ca52c48a2d
|
[
"CC-BY-3.0",
"CC0-1.0",
"CC-BY-4.0"
] | 7
|
2016-01-28T14:28:10.000Z
|
2021-09-03T17:33:37.000Z
|
src/DescentGame/src/Main.cpp
|
poseidn/KungFoo
|
35fa33bd5a9abb40ecf485db2fc038ca52c48a2d
|
[
"CC-BY-3.0",
"CC0-1.0",
"CC-BY-4.0"
] | 1
|
2016-03-19T11:34:36.000Z
|
2016-03-24T21:35:06.000Z
|
src/DescentGame/src/Main.cpp
|
poseidn/KungFoo
|
35fa33bd5a9abb40ecf485db2fc038ca52c48a2d
|
[
"CC-BY-3.0",
"CC0-1.0",
"CC-BY-4.0"
] | 3
|
2016-03-10T14:23:40.000Z
|
2019-03-17T16:21:21.000Z
|
/*
Copyright (C) 2016 Thomas Hauth. All Rights Reserved.
* Written by Thomas Hauth (Thomas.Hauth@web.de)
This file is part of Kung Foo Barracuda.
Kung Foo Barracuda 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.
Kung Foo Barracuda 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 Kung Foo Barracuda. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <vector>
#include <boost/program_options.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <DescentLogic/src/DescentFramework.h>
//#include "CommandLineOptions.h"
// set via the build system, if a profile is needed
#ifdef USE_PROFILER
#include <gperftools/profiler.h>
#endif
namespace po = boost::program_options;
// use ./DescentGame --fullscreen --resolution 1366x768
// on the notebook for the total fun
int main(int argc, const char* argv[]) {
SDLInterfaceInitData sdlInitData;
std::vector < std::string > opts;
for (int i = 0; i < argc; i++) {
opts.push_back(std::string(argv[i]));
}
// running fullscreen is default
sdlInitData.Fullscreen = false;
bool runDemoMode = false;
bool muted = false;
bool forwardScroll = false;
bool withIntro = false;
/*
if (commandline::handleCommandLine(sdlInitData, opts, runDemoMode, muted, forwardScroll, withIntro)
== false)
return 0;*/
DescentFramework f(false, runDemoMode, muted, forwardScroll, withIntro, true);
f.initRenderEngine(sdlInitData);
// todo: make this a lot nicer, by templating the FW class
#ifdef USE_PROFILER
ProfilerStart("GameLoop.perf");
#endif
f.execute();
#ifdef USE_PROFILER
ProfilerStop();
#endif
// done globally here for all used SDL systems;
SDL_Quit();
return 0;
}
| 26.54321
| 100
| 0.751628
|
poseidn
|
dee83e605a1f575e4a2d710a5a6cb28e33523456
| 5,810
|
cpp
|
C++
|
patch/specific/drawbars.cpp
|
Tonyx97/TombMP
|
7eb2d265df2fe7312b7ed07dd5943736340b921c
|
[
"MIT"
] | 3
|
2021-10-10T11:12:03.000Z
|
2021-11-04T16:46:57.000Z
|
patch/specific/drawbars.cpp
|
Tonyx97/TombMP
|
7eb2d265df2fe7312b7ed07dd5943736340b921c
|
[
"MIT"
] | null | null | null |
patch/specific/drawbars.cpp
|
Tonyx97/TombMP
|
7eb2d265df2fe7312b7ed07dd5943736340b921c
|
[
"MIT"
] | null | null | null |
#include "standard.h"
#include "directx.h"
#include "global.h"
#include "hwrender.h"
#include "output.h"
#include <main.h>
#include <game/inventry.h>
#include <3dsystem/hwinsert.h>
#define HealthBarX 8
#define HealthBarY 6
#define HealthBarW 100
#define AirBarX (game_setup.dump_width-110)
#define AirBarY 6
#define AirBarW 100
#define DASHBAR_X (game_setup.dump_width-110)
#define DASHBAR_Y 6
void S_DrawDashBar(int percent)
{
HWR_EnableZBuffer(true, true);
g_blue_effect = false;
int x = DASHBAR_X,
y = DASHBAR_Y,
w = (percent * HealthBarW) / 100,
z = phd_znear + 50;
auto colour = (char)inv_colours[C_BLACK];
InsertLine(x - 2, y + 1, x + HealthBarW + 1, y + 1, z, colour);
InsertLine(x - 2, y + 2, x + HealthBarW + 1, y + 2, z, colour);
InsertLine(x - 2, y + 3, x + HealthBarW + 1, y + 3, z, colour);
InsertLine(x - 2, y + 4, x + HealthBarW + 1, y + 4, z, colour);
InsertLine(x - 2, y + 5, x + HealthBarW + 1, y + 5, z, colour);
InsertLine(x - 2, y + 6, x + HealthBarW + 1, y + 6, z, colour);
InsertLine(x - 2, y + 7, x + HealthBarW + 1, y + 7, z, colour);
z = phd_znear + 40;
colour = (char)inv_colours[C_GREY];
InsertLine(x - 2, y + 8, x + HealthBarW + 2, y + 8, z, colour);
InsertLine(x + HealthBarW + 2, y, x + HealthBarW + 2, y + 8, z, colour);
z = phd_znear + 30;
colour = (char)inv_colours[C_WHITE];
InsertLine(x - 2, y, x + HealthBarW + 2, y, z, colour);
InsertLine(x - 2, y + 8, x - 2, y, z, colour);
if (w)
{
colour = (char)inv_colours[C_DARKGREEN];
InsertLine(x, y + 2, x + w, y + 2, z, colour);
InsertLine(x, y + 3, x + w, y + 3, z, colour);
InsertLine(x, y + 4, x + w, y + 4, z, colour);
InsertLine(x, y + 5, x + w, y + 5, z, colour);
InsertLine(x, y + 6, x + w, y + 6, z, colour);
}
}
void S_DrawHealthBar(int percent, bool poisoned)
{
HWR_EnableZBuffer(true, true);
g_blue_effect = false;
int x = HealthBarX,
y = HealthBarY,
w = (percent * HealthBarW) / 100,
z = phd_znear + 50;
auto colour = (char)inv_colours[C_BLACK];
InsertLine(x - 2, y + 1, x + HealthBarW + 1, y + 1, z, colour);
InsertLine(x - 2, y + 2, x + HealthBarW + 1, y + 2, z, colour);
InsertLine(x - 2, y + 3, x + HealthBarW + 1, y + 3, z, colour);
InsertLine(x - 2, y + 4, x + HealthBarW + 1, y + 4, z, colour);
InsertLine(x - 2, y + 5, x + HealthBarW + 1, y + 5, z, colour);
InsertLine(x - 2, y + 6, x + HealthBarW + 1, y + 6, z, colour);
InsertLine(x - 2, y + 7, x + HealthBarW + 1, y + 7, z, colour);
z = phd_znear + 40;
colour = (char)inv_colours[C_GREY];
InsertLine(x - 2, y + 8, x + HealthBarW + 2, y + 8, z, colour);
InsertLine(x + HealthBarW + 2, y, x + HealthBarW + 2, y + 8, z, colour);
z = phd_znear + 30;
colour = (char)inv_colours[C_WHITE];
InsertLine(x - 2, y, x + HealthBarW + 2, y, z, colour);
InsertLine(x - 2, y + 8, x - 2, y, z, colour);
if (w)
{
z = phd_znear + 20;
colour = (char)inv_colours[poisoned ? C_YELLOW : C_RED];
InsertLine(x, y + 2, x + w, y + 2, z, colour);
InsertLine(x, y + 3, x + w, y + 3, z, colour);
InsertLine(x, y + 4, x + w, y + 4, z, colour);
InsertLine(x, y + 5, x + w, y + 5, z, colour);
InsertLine(x, y + 6, x + w, y + 6, z, colour);
}
}
void S_DrawHealthBar3D(int32_t wx, int32_t wy, int32_t wz, int percent, bool poisoned)
{
HWR_EnableZBuffer(true, true);
g_blue_effect = false;
long result[XYZ];
long scr[XYZ];
mCalcPoint(wx, wy, wz, &result[0]);
ProjectPCoord(result[_X], result[_Y], result[_Z], scr, f_centerx, f_centery, phd_persp);
int x = scr[_X] - HealthBarW / 2,
y = scr[_Y],
w = (percent * HealthBarW) / 100,
z = phd_znear + 50;
auto colour = (char)inv_colours[C_BLACK];
InsertLine(x - 2, y + 1, x + HealthBarW + 1, y + 1, z, colour);
InsertLine(x - 2, y + 2, x + HealthBarW + 1, y + 2, z, colour);
InsertLine(x - 2, y + 3, x + HealthBarW + 1, y + 3, z, colour);
InsertLine(x - 2, y + 4, x + HealthBarW + 1, y + 4, z, colour);
InsertLine(x - 2, y + 5, x + HealthBarW + 1, y + 5, z, colour);
InsertLine(x - 2, y + 6, x + HealthBarW + 1, y + 6, z, colour);
InsertLine(x - 2, y + 7, x + HealthBarW + 1, y + 7, z, colour);
if (w)
{
z = phd_znear + 40;
colour = (char)inv_colours[poisoned ? C_YELLOW : C_RED];
InsertLine(x, y + 2, x + w, y + 2, z, colour);
InsertLine(x, y + 3, x + w, y + 3, z, colour);
InsertLine(x, y + 4, x + w, y + 4, z, colour);
InsertLine(x, y + 5, x + w, y + 5, z, colour);
InsertLine(x, y + 6, x + w, y + 6, z, colour);
}
}
void S_DrawAirBar(int percent)
{
HWR_EnableZBuffer(true, true);
g_blue_effect = false;
int x = AirBarX,
y = AirBarY,
w = (percent * AirBarW) / 100,
z = phd_znear + 50;
auto colour = (char)inv_colours[C_BLACK];
InsertLine(x - 2, y + 1, x + AirBarW + 1, y + 1, z, colour);
InsertLine(x - 2, y + 2, x + AirBarW + 1, y + 2, z, colour);
InsertLine(x - 2, y + 3, x + AirBarW + 1, y + 3, z, colour);
InsertLine(x - 2, y + 4, x + AirBarW + 1, y + 4, z, colour);
InsertLine(x - 2, y + 5, x + AirBarW + 1, y + 5, z, colour);
InsertLine(x - 2, y + 6, x + AirBarW + 1, y + 6, z, colour);
InsertLine(x - 2, y + 7, x + AirBarW + 1, y + 7, z, colour);
z = phd_znear + 40;
colour = (char)inv_colours[C_GREY];
InsertLine(x - 2, y + 8, x + AirBarW + 2, y + 8, z, colour);
InsertLine(x + AirBarW + 2, y, x + AirBarW + 2, y + 8, z, colour);
z = phd_znear + 30;
colour = (char)inv_colours[C_WHITE];
InsertLine(x - 2, y, x + AirBarW + 2, y, z, colour);
InsertLine(x - 2, y + 8, x - 2, y, z, colour);
if (percent > 0)
{
z = phd_znear + 20;
colour = (char)inv_colours[C_WHITE];
InsertLine(x, y + 3, x + w, y + 3, z, colour);
colour = (char)inv_colours[C_BLUE];
InsertLine(x, y + 2, x + w, y + 2, z, colour);
InsertLine(x, y + 4, x + w, y + 4, z, colour);
InsertLine(x, y + 5, x + w, y + 5, z, colour);
InsertLine(x, y + 6, x + w, y + 6, z, colour);
}
}
| 30.904255
| 89
| 0.58537
|
Tonyx97
|
dee9518ffeb35a2f6dc7b3f566346a6fd6e6d3fd
| 22,804
|
cpp
|
C++
|
src/slib/db/sqlite.cpp
|
emarc99/SLib
|
4e492d6c550f845fd1b3f40bf10183097eb0e53c
|
[
"MIT"
] | 146
|
2017-03-21T07:50:43.000Z
|
2022-03-19T03:32:22.000Z
|
src/slib/db/sqlite.cpp
|
Crasader/SLib
|
4e492d6c550f845fd1b3f40bf10183097eb0e53c
|
[
"MIT"
] | 50
|
2017-03-22T04:08:15.000Z
|
2019-10-21T16:55:48.000Z
|
src/slib/db/sqlite.cpp
|
Crasader/SLib
|
4e492d6c550f845fd1b3f40bf10183097eb0e53c
|
[
"MIT"
] | 55
|
2017-03-21T07:52:58.000Z
|
2021-12-27T13:02:08.000Z
|
/*
* Copyright (c) 2008-2019 SLIBIO <https://github.com/SLIBIO>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "sqlite/sqlite3.h"
#include "slib/db/sqlite.h"
#include "slib/db/sql.h"
#include "slib/core/file.h"
#include "slib/core/log.h"
#include "slib/core/scoped.h"
#include "slib/core/safe_static.h"
#include "slib/crypto/sha2.h"
#include "slib/crypto/chacha.h"
#define TAG "SQLiteDatabase"
#define ENCRYPTION_PREFIX_SIZE 80
namespace slib
{
SLIB_DEFINE_CLASS_DEFAULT_MEMBERS(SQLiteParam)
SQLiteParam::SQLiteParam()
{
flagCreate = sl_true;
flagReadonly = sl_false;
}
SLIB_DEFINE_OBJECT(SQLiteDatabase, Database)
SQLiteDatabase::SQLiteDatabase()
{
m_dialect = DatabaseDialect::SQLite;
}
SQLiteDatabase::~SQLiteDatabase()
{
}
namespace priv
{
namespace sqlite
{
class DatabaseImpl;
class CursorImpl : public DatabaseCursor
{
public:
Ref<DatabaseStatement> m_statementObj;
sqlite3_stmt* m_statement;
CList<String> m_listColumnNames;
sl_uint32 m_nColumnNames;
String* m_columnNames;
CHashMap<String, sl_int32> m_mapColumnIndexes;
public:
CursorImpl(Database* db, DatabaseStatement* statementObj, sqlite3_stmt* statement)
{
m_db = db;
m_statementObj = statementObj;
m_statement = statement;
sl_int32 cols = sqlite3_column_count(statement);
for (sl_int32 i = 0; i < cols; i++) {
const char* buf = sqlite3_column_name(statement, (int)i);
String name = String::create(buf);
m_listColumnNames.add_NoLock(name);
m_mapColumnIndexes.put_NoLock(name, i);
}
m_nColumnNames = (sl_uint32)(m_listColumnNames.getCount());
m_columnNames = m_listColumnNames.getData();
db->lock();
}
~CursorImpl()
{
sqlite3_reset(m_statement);
sqlite3_clear_bindings(m_statement);
m_db->unlock();
}
public:
sl_uint32 getColumnsCount() override
{
return m_nColumnNames;
}
String getColumnName(sl_uint32 index) override
{
if (index < m_nColumnNames) {
return m_columnNames[index];
}
return sl_null;
}
sl_int32 getColumnIndex(const StringParam& name) override
{
return m_mapColumnIndexes.getValue_NoLock(name.toString(), -1);
}
HashMap<String, Variant> getRow() override
{
HashMap<String, Variant> ret;
if (m_nColumnNames > 0) {
for (sl_uint32 index = 0; index < m_nColumnNames; index++) {
ret.put_NoLock(m_columnNames[index], _getValue(index));
}
}
return ret;
}
String _getString(sl_uint32 index)
{
int n = sqlite3_column_bytes(m_statement, index);
const void* buf = sqlite3_column_text(m_statement, index);
if (buf && n > 0) {
return String::fromUtf8(buf, n);
}
return String::getEmpty();
}
Memory _getBlob(sl_uint32 index)
{
int n = sqlite3_column_bytes(m_statement, index);
const void* buf = sqlite3_column_blob(m_statement, index);
if (buf && n > 0) {
return Memory::create(buf, n);
}
return sl_null;
}
Variant _getValue(sl_uint32 index)
{
int type = sqlite3_column_type(m_statement, index);
switch (type) {
case SQLITE_INTEGER:
{
sl_int64 v64 = sqlite3_column_int64(m_statement, index);
sl_int32 v32 = (sl_int32)v64;
if (v64 == v32) {
return v32;
} else {
return v64;
}
}
break;
case SQLITE_FLOAT:
return sqlite3_column_double(m_statement, index);
case SQLITE_TEXT:
return _getString(index);
case SQLITE_BLOB:
return _getBlob(index);
}
return sl_null;
}
Variant getValue(sl_uint32 index) override
{
if (index < m_nColumnNames) {
return _getValue(index);
}
return sl_null;
}
String getString(sl_uint32 index) override
{
if (index < m_nColumnNames) {
int type = sqlite3_column_type(m_statement, index);
switch (type) {
case SQLITE_INTEGER:
return String::fromInt64(sqlite3_column_int64(m_statement, index));
case SQLITE_FLOAT:
return String::fromDouble(sqlite3_column_double(m_statement, index));
case SQLITE_TEXT:
return _getString(index);
}
}
return sl_null;
}
sl_int64 getInt64(sl_uint32 index, sl_int64 defaultValue) override
{
if (index < m_nColumnNames) {
int type = sqlite3_column_type(m_statement, index);
switch (type) {
case SQLITE_INTEGER:
return sqlite3_column_int64(m_statement, index);
case SQLITE_FLOAT:
return (sl_int64)(sqlite3_column_double(m_statement, index));
case SQLITE_TEXT:
return _getString(index).parseInt64(10, defaultValue);
}
}
return defaultValue;
}
sl_uint64 getUint64(sl_uint32 index, sl_uint64 defaultValue) override
{
if (index < m_nColumnNames) {
int type = sqlite3_column_type(m_statement, index);
switch (type) {
case SQLITE_INTEGER:
return sqlite3_column_int64(m_statement, index);
case SQLITE_FLOAT:
return (sl_uint64)(sqlite3_column_double(m_statement, index));
case SQLITE_TEXT:
return _getString(index).parseUint64(10, defaultValue);
}
}
return defaultValue;
}
sl_int32 getInt32(sl_uint32 index, sl_int32 defaultValue) override
{
if (index < m_nColumnNames) {
int type = sqlite3_column_type(m_statement, index);
switch (type) {
case SQLITE_INTEGER:
return sqlite3_column_int(m_statement, index);
case SQLITE_FLOAT:
return (sl_int32)(sqlite3_column_double(m_statement, index));
case SQLITE_TEXT:
return _getString(index).parseInt32(10, defaultValue);
}
}
return defaultValue;
}
sl_uint32 getUint32(sl_uint32 index, sl_uint32 defaultValue) override
{
if (index < m_nColumnNames) {
int type = sqlite3_column_type(m_statement, index);
switch (type) {
case SQLITE_INTEGER:
return (sl_uint32)(sqlite3_column_int64(m_statement, index));
case SQLITE_FLOAT:
return (sl_uint32)(sqlite3_column_double(m_statement, index));
case SQLITE_TEXT:
return _getString(index).parseUint32(10, defaultValue);
}
}
return defaultValue;
}
float getFloat(sl_uint32 index, float defaultValue) override
{
if (index < m_nColumnNames) {
int type = sqlite3_column_type(m_statement, index);
switch (type) {
case SQLITE_INTEGER:
return (float)(sqlite3_column_int64(m_statement, index));
case SQLITE_FLOAT:
return (float)(sqlite3_column_double(m_statement, index));
case SQLITE_TEXT:
return _getString(index).parseFloat(defaultValue);
}
}
return defaultValue;
}
double getDouble(sl_uint32 index, double defaultValue) override
{
if (index < m_nColumnNames) {
int type = sqlite3_column_type(m_statement, index);
switch (type) {
case SQLITE_INTEGER:
return (double)(sqlite3_column_int64(m_statement, index));
case SQLITE_FLOAT:
return (sqlite3_column_double(m_statement, index));
case SQLITE_TEXT:
return _getString(index).parseDouble(defaultValue);
}
}
return defaultValue;
}
Memory getBlob(sl_uint32 index) override
{
if (index < m_nColumnNames) {
int type = sqlite3_column_type(m_statement, index);
switch (type) {
case SQLITE_TEXT:
case SQLITE_BLOB:
return _getBlob(index);
}
}
return sl_null;
}
sl_bool moveNext() override
{
sl_int32 nRet = sqlite3_step(m_statement);
if (nRet == SQLITE_ROW) {
return sl_true;
}
return sl_false;
}
};
class StatementImpl : public DatabaseStatement
{
public:
sqlite3* m_sqlite;
sqlite3_stmt* m_statement;
Array<Variant> m_boundParams;
public:
StatementImpl(Database* db, sqlite3* sqlite, sqlite3_stmt* statement)
{
m_db = db;
m_sqlite = sqlite;
m_statement = statement;
}
~StatementImpl()
{
sqlite3_finalize(m_statement);
}
public:
sl_bool isLoggingErrors()
{
if (m_db.isNotNull()) {
return m_db->isLoggingErrors();
}
return sl_false;
}
sl_bool _execute(const Variant* _params, sl_uint32 nParams)
{
sqlite3_reset(m_statement);
sqlite3_clear_bindings(m_statement);
m_boundParams.setNull();
if (nParams == 0) {
return sl_true;
}
Array<Variant> params = Array<Variant>::create(_params, nParams);
if (params.isNull()) {
return sl_false;
}
sl_uint32 n = (sl_uint32)(sqlite3_bind_parameter_count(m_statement));
if (n == nParams) {
if (n > 0) {
for (sl_uint32 i = 0; i < n; i++) {
int iRet = SQLITE_ABORT;
Variant& var = (params.getData())[i];
switch (var.getType()) {
case VariantType::Null:
iRet = sqlite3_bind_null(m_statement, i+1);
break;
case VariantType::Boolean:
case VariantType::Int32:
iRet = sqlite3_bind_int(m_statement, i+1, var.getInt32());
break;
case VariantType::Uint32:
case VariantType::Int64:
case VariantType::Uint64:
iRet = sqlite3_bind_int64(m_statement, i+1, var.getInt64());
break;
case VariantType::Float:
case VariantType::Double:
iRet = sqlite3_bind_double(m_statement, i+1, var.getDouble());
break;
default:
if (var.isMemory()) {
Memory mem = var.getMemory();
sl_size size = mem.getSize();
if (size > 0x7fffffff) {
iRet = sqlite3_bind_blob64(m_statement, i+1, mem.getData(), size, SQLITE_STATIC);
} else {
iRet = sqlite3_bind_blob(m_statement, i+1, mem.getData(), (sl_uint32)size, SQLITE_STATIC);
}
} else {
String str = var.getString();
var = str;
iRet = sqlite3_bind_text(m_statement, i+1, str.getData(), (sl_uint32)(str.getLength()), SQLITE_STATIC);
}
}
if (iRet != SQLITE_OK) {
return sl_false;
}
}
}
m_boundParams = params;
return sl_true;
} else {
if (isLoggingErrors()) {
LogError(TAG, "Bind error: requires %d params but %d params provided", n, nParams);
}
}
return sl_false;
}
sl_int64 executeBy(const Variant* params, sl_uint32 nParams) override
{
ObjectLocker lock(m_db.get());
if (_execute(params, nParams)) {
if (sqlite3_step(m_statement) == SQLITE_DONE) {
sqlite3_reset(m_statement);
sqlite3_clear_bindings(m_statement);
return sqlite3_changes(m_sqlite);
}
}
return -1;
}
Ref<DatabaseCursor> queryBy(const Variant* params, sl_uint32 nParams) override
{
ObjectLocker lock(m_db.get());
Ref<DatabaseCursor> ret;
if (_execute(params, nParams)) {
ret = new CursorImpl(m_db.get(), this, m_statement);
if (ret.isNotNull()) {
return ret;
}
sqlite3_reset(m_statement);
sqlite3_clear_bindings(m_statement);
}
return ret;
}
};
class EncryptionVfs : public sqlite3_vfs
{
public:
DatabaseImpl* db;
};
class EncryptionIo : public sqlite3_io_methods
{
public:
DatabaseImpl* db;
const sqlite3_io_methods* ioOriginal;
ChaCha20_Core encrypt;
sl_uint32 encryptIV[4];
};
struct EncryptionCustomFile
{
EncryptionIo io;
};
class DatabaseImpl : public SQLiteDatabase
{
public:
sqlite3* m_db;
EncryptionVfs m_vfs;
sqlite3_vfs* m_vfsOriginal;
int m_vfsFileCustomOffset;
char m_encryptionKey[32];
public:
DatabaseImpl()
{
m_db = sl_null;
}
~DatabaseImpl()
{
if (m_db) {
sqlite3_close(m_db);
}
}
static Ref<DatabaseImpl> open(const SQLiteParam& param)
{
Ref<DatabaseImpl> ret = new DatabaseImpl;
if (ret.isNotNull()) {
if (ret->initialize(param)) {
return ret;
}
}
return sl_null;
}
sl_bool initialize(const SQLiteParam& param)
{
sqlite3* db = sl_null;
int flags;
if (param.flagCreate) {
flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
} else {
flags = param.flagReadonly ? SQLITE_OPEN_READONLY : SQLITE_OPEN_READWRITE;
}
int iResult;
if (param.encryptionKey.isNotEmpty()) {
SHA256::hash(param.encryptionKey, m_encryptionKey);
sqlite3_vfs* vfsDefault = sqlite3_vfs_find(0);
Base::copyMemory(&m_vfs, vfsDefault, sizeof(sqlite3_vfs));
m_vfs.db = this;
m_vfs.zName = "slib_encryption";
m_vfs.xOpen = &xOpenEncryption;
m_vfsFileCustomOffset = ((m_vfs.szOsFile - 1) | 15) + 1;
m_vfs.szOsFile = m_vfsFileCustomOffset + sizeof(EncryptionCustomFile);
m_vfsOriginal = vfsDefault;
SLIB_SAFE_STATIC(Mutex, mutex)
MutexLocker lock(&mutex);
sqlite3_vfs_register(&m_vfs, 0);
iResult = sqlite3_open_v2(param.path.getData(), &db, flags, m_vfs.zName);
sqlite3_vfs_unregister(&m_vfs);
} else {
iResult = sqlite3_open_v2(param.path.getData(), &db, flags, sl_null);
}
if (SQLITE_OK == iResult) {
m_db = db;
return sl_true;
}
return sl_false;
}
static int xOpenEncryption(sqlite3_vfs* vfs, const char *zName, sqlite3_file* file, int flags, int *pOutFlags)
{
return ((EncryptionVfs*)vfs)->db->onOpenEncryption(vfs, zName, file, flags, pOutFlags);
}
int onOpenEncryption(sqlite3_vfs* vfs, const char *zName, sqlite3_file* file, int flags, int *pOutFlags)
{
int iRet = (m_vfsOriginal->xOpen)(vfs, zName, file, flags, pOutFlags);
if (iRet == SQLITE_OK) {
EncryptionCustomFile* custom = (EncryptionCustomFile*)(((char*)(void*)file) + m_vfsFileCustomOffset);
Base::copyMemory(&(custom->io), file->pMethods, sizeof(sqlite3_io_methods));
custom->io.db = this;
custom->io.ioOriginal = file->pMethods;
custom->io.iVersion = 0;
custom->io.xRead = &xReadEncryption;
custom->io.xWrite = &xWriteEncryption;
custom->io.xTruncate = &xTruncateEncryption;
custom->io.xFileSize = &xFileSizeEncryption;
sqlite3_int64 size = 0;
(file->pMethods->xFileSize)(file, &size);
if (!size) {
(vfs->xRandomness)(vfs, 4, (char*)(custom->io.encryptIV));
(vfs->xRandomness)(vfs, 4, (char*)(custom->io.encryptIV + 1));
(vfs->xRandomness)(vfs, 4, (char*)(custom->io.encryptIV + 2));
(vfs->xRandomness)(vfs, 4, (char*)(custom->io.encryptIV + 3));
char header[ENCRYPTION_PREFIX_SIZE];
MIO::writeUint32LE(header, custom->io.encryptIV[0]);
MIO::writeUint32LE(header + 4, custom->io.encryptIV[1]);
MIO::writeUint32LE(header + 8, custom->io.encryptIV[2]);
MIO::writeUint32LE(header + 12, custom->io.encryptIV[3]);
(vfs->xRandomness)(vfs, 32, header + 16);
char check[48];
Base::copyMemory(check, header, 16);
Base::copyMemory(check + 16, m_encryptionKey, 32);
char h[32];
SHA256::hash(check, 48, h);
Base::copyMemory(header + 48, h, 32);
iRet = (file->pMethods->xWrite)(file, header, ENCRYPTION_PREFIX_SIZE, 0);
if (iRet != SQLITE_OK) {
file->pMethods = sl_null;
return iRet;
}
char key[32];
for (int i = 0; i < 32; i++) {
key[i] = header[16 + i] ^ m_encryptionKey[i];
}
custom->io.encrypt.setKey(key, 32);
} else {
char header[ENCRYPTION_PREFIX_SIZE];
iRet = (file->pMethods->xRead)(file, header, ENCRYPTION_PREFIX_SIZE, 0);
if (iRet != SQLITE_OK) {
file->pMethods = sl_null;
return iRet;
}
char check[48];
Base::copyMemory(check, header, 16);
Base::copyMemory(check + 16, m_encryptionKey, 32);
char h[32];
SHA256::hash(check, 48, h);
if (!(Base::equalsMemory(h, header + 48, 32))) {
file->pMethods = sl_null;
return SQLITE_AUTH;
}
custom->io.encryptIV[0] = MIO::readUint32LE(header);
custom->io.encryptIV[1] = MIO::readUint32LE(header + 4);
custom->io.encryptIV[2] = MIO::readUint32LE(header + 8);
custom->io.encryptIV[3] = MIO::readUint32LE(header + 12);
char key[32];
for (int i = 0; i < 32; i++) {
key[i] = header[16 + i] ^ m_encryptionKey[i];
}
custom->io.encrypt.setKey(key, 32);
}
file->pMethods = &(custom->io);
}
return iRet;
}
static int xReadEncryption(sqlite3_file* file, void* buf, int iAmt, sqlite3_int64 iOfst)
{
EncryptionIo* io = (EncryptionIo*)(file->pMethods);
int iRet = (io->ioOriginal->xRead)(file, buf, iAmt, iOfst + ENCRYPTION_PREFIX_SIZE);
if (iRet == SQLITE_OK && iAmt > 0) {
io->db->encrypt(io, iOfst, buf, iAmt);
}
return iRet;
}
static int xWriteEncryption(sqlite3_file* file, const void* buf, int iAmt, sqlite3_int64 iOfst)
{
EncryptionIo* io = (EncryptionIo*)(file->pMethods);
if (iAmt > 0) {
int n = iAmt >> 10;
if (iAmt & 1023) {
n++;
}
char* b = (char*)buf;
char t[1024];
sqlite3_int64 o = iOfst;
for (int i = 0; i < n; i++) {
int size = iAmt;
if (size > 1024) {
size = 1024;
}
Base::copyMemory(t, b, (sl_size)size);
io->db->encrypt(io, o, t, size);
int iRet = (io->ioOriginal->xWrite)(file, t, size, o + ENCRYPTION_PREFIX_SIZE);
if (iRet != SQLITE_OK) {
return iRet;
}
o += 1024;
b += 1024;
iAmt -= 1024;
}
}
return SQLITE_OK;
}
static int xTruncateEncryption(sqlite3_file* file, sqlite3_int64 size)
{
EncryptionIo* io = (EncryptionIo*)(file->pMethods);
return (io->ioOriginal->xTruncate)(file, size + ENCRYPTION_PREFIX_SIZE);
}
static int xFileSizeEncryption(sqlite3_file* file, sqlite3_int64 *pSize)
{
EncryptionIo* io = (EncryptionIo*)(file->pMethods);
int iResult = (io->ioOriginal->xFileSize)(file, pSize);
if (iResult == SQLITE_OK) {
if (*pSize > ENCRYPTION_PREFIX_SIZE) {
*pSize -= ENCRYPTION_PREFIX_SIZE;
} else {
*pSize = 0;
}
}
return iResult;
}
void encrypt(EncryptionIo* io, sqlite3_int64 iOfst, void* buf, int size)
{
if (iOfst < 0) {
return;
}
if (size < 1) {
return;
}
sl_uint64 offset = (sl_uint64)iOfst;
sl_uint64 block = offset >> 6;
sl_uint32 pos = (sl_uint32)(offset & 63);
sl_uint64 offsetEnd = (sl_uint64)(iOfst + size);
sl_uint64 blockEnd = offsetEnd >> 6;
sl_uint32 posEnd = (sl_uint32)(offsetEnd & 63);
char* b = (char*)buf;
char h[64];
for (; block <= blockEnd; block++) {
io->encrypt.generateBlock(io->encryptIV[0], io->encryptIV[1], io->encryptIV[2] + ((sl_uint32)(block >> 32)), io->encryptIV[3] + ((sl_uint32)block), h);
sl_uint32 e;
if (block == blockEnd) {
e = posEnd;
} else {
e = 64;
}
sl_uint32 n = e - pos;
for (sl_uint32 i = 0; i < n; i++) {
b[i] ^= h[pos + i];
}
b += n;
pos = 0;
}
}
sl_int64 _execute(const StringParam& _sql) override
{
StringCstr sql(_sql);
ObjectLocker lock(this);
if (SQLITE_OK == sqlite3_exec(m_db, sql.getData(), 0, 0, sl_null)) {
return sqlite3_changes(m_db);
}
return -1;
}
Ref<DatabaseStatement> _prepareStatement(const StringParam& _sql) override
{
StringCstr sql(_sql);
ObjectLocker lock(this);
Ref<DatabaseStatement> ret;
sqlite3_stmt* statement = sl_null;
if (SQLITE_OK == sqlite3_prepare_v2(m_db, sql.getData(), -1, &statement, sl_null)) {
ret = new StatementImpl(this, m_db, statement);
if (ret.isNotNull()) {
return ret;
}
sqlite3_finalize(statement);
}
return ret;
}
String getErrorMessage() override
{
String error = String::create(sqlite3_errmsg(m_db));
if (error.isEmpty() || error == "not an error") {
return sl_null;
}
return error;
}
sl_bool isDatabaseExisting(const StringParam& name) override
{
return sl_false;
}
List<String> getDatabases() override
{
return sl_null;
}
sl_bool isTableExisting(const StringParam& _name) override
{
SqlBuilder builder(m_dialect);
SLIB_STATIC_STRING(s, "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name LIKE ")
builder.append(s);
StringData name(_name);
builder.appendIdentifier(name.getData(), name.getLength());
return getValue(builder.toString()).getUint32() > 0;
}
List<String> getTables() override
{
List<String> ret;
Ref<DatabaseCursor> cursor = query("SELECT name FROM sqlite_master WHERE type='table'");
if (cursor.isNotNull()) {
while (cursor->moveNext()) {
ret.add_NoLock(cursor->getString(0));
}
}
return ret;
}
sl_uint64 getLastInsertRowId() override
{
return (sl_uint64)(sqlite3_last_insert_rowid(m_db));
}
};
}
}
Ref<SQLiteDatabase> SQLiteDatabase::open(const SQLiteParam& param)
{
return priv::sqlite::DatabaseImpl::open(param);
}
Ref<SQLiteDatabase> SQLiteDatabase::open(const String& path)
{
SQLiteParam param;
param.path = path;
return priv::sqlite::DatabaseImpl::open(param);
}
}
| 28.433915
| 157
| 0.620944
|
emarc99
|
deeb50bf2737a13113f6383e8c965541b118890b
| 7,337
|
hpp
|
C++
|
Extensions/Gameplay/IndexedHalfEdgeMesh.hpp
|
jodavis42/ZeroPhysicsTestbed
|
e84a3f6faf16b7a4242dc049121b5338e80039f8
|
[
"MIT"
] | 1
|
2022-03-26T21:08:19.000Z
|
2022-03-26T21:08:19.000Z
|
Extensions/Gameplay/IndexedHalfEdgeMesh.hpp
|
jodavis42/ZeroPhysicsTestbed
|
e84a3f6faf16b7a4242dc049121b5338e80039f8
|
[
"MIT"
] | null | null | null |
Extensions/Gameplay/IndexedHalfEdgeMesh.hpp
|
jodavis42/ZeroPhysicsTestbed
|
e84a3f6faf16b7a4242dc049121b5338e80039f8
|
[
"MIT"
] | null | null | null |
///////////////////////////////////////////////////////////////////////////////
///
/// Authors: Joshua Davis
/// Copyright 2017, DigiPen Institute of Technology
///
///////////////////////////////////////////////////////////////////////////////
#pragma once
namespace Zero
{
template <typename ArrayType>
class BoundArrayRange;
/// Base functionality for binding a pre-existing array. Currently designed as
/// a templated base to reduce code duplication, especially while prototyping. Possibly split to
/// individual classes (due to differences, code documentation, etc...) or make generic enough to use elsewhere later.
template <typename OwningType, typename DataTypeT>
class BoundArray : public SafeId32Object
{
public:
typedef BoundArray<OwningType, DataTypeT> SelfType;
typedef DataTypeT DataType;
typedef Array<DataTypeT> ArrayType;
typedef BoundArrayRange<SelfType> RangeType;
BoundArray()
{
mBoundArray = nullptr;
}
BoundArray(ArrayType* arrayData)
{
mBoundArray = arrayData;
}
Vec3Param operator[](size_t index) const
{
return (*mBoundArray)[index];
}
DataTypeT Get(int arrayIndex) const
{
if(!ValidateArrayIndex(arrayIndex))
return DataTypeT();
return (*mBoundArray)[arrayIndex];
}
int GetCount() const
{
return (int)(*mBoundArray).Size();
}
RangeType GetAll()
{
return RangeType(this);
}
bool ValidateArrayIndex(int arrayIndex) const
{
int count = GetCount();
if(arrayIndex >= count)
{
String msg = String::Format("Index %d is invalid. Array only contains %d element(s).", arrayIndex, count);
DoNotifyException("Invalid index", msg);
return false;
}
return true;
}
/// The array that this class represents. Assumes that this data cannot go away without this class also going away.
ArrayType* mBoundArray;
};
template <typename ArrayTypeT>
class BoundArrayRange
{
public:
typedef BoundArrayRange<ArrayTypeT> SelfType;
typedef ArrayTypeT ArrayType;
// Required for binding
typedef typename ArrayTypeT::DataType FrontResult;
BoundArrayRange()
{
mArray = nullptr;
mIndex = 0;
}
BoundArrayRange(ArrayTypeT* array)
{
mArray = array;
mIndex = 0;
}
bool Empty()
{
// Validate that the range hasn't been destroyed
ArrayType* array = mArray;
if(array == nullptr)
{
DoNotifyException("Range is invalid", "The array this range is referencing has been destroyed.");
return true;
}
return mIndex >= (size_t)array->GetCount();
}
FrontResult Front()
{
// If the range is empty (or the range has been destroyed) then throw an exception.
if(Empty())
{
DoNotifyException("Invalid Range Operation", "Cannot access an item in an empty range.");
return FrontResult();
}
return mArray->Get(mIndex);
}
void PopFront()
{
++mIndex;
}
SelfType& All()
{
return *this;
}
private:
HandleOf<ArrayTypeT> mArray;
size_t mIndex;
};
class IndexedHalfEdgeVertex;
class IndexedHalfEdge;
class IndexedHalfEdgeFace;
class IndexedHalfEdgeMesh;
//-------------------------------------------------------------------IndexedHalfEdgeMeshVertexArray
class IndexedHalfEdgeMeshVertexArray : public BoundArray<IndexedHalfEdgeMesh, Vec3>
{
public:
ZilchDeclareType(IndexedHalfEdgeMeshVertexArray, TypeCopyMode::ReferenceType);
};
//-------------------------------------------------------------------IndexedHalfEdgeMeshEdgeArray
class IndexedHalfEdgeMeshEdgeArray : public BoundArray<IndexedHalfEdgeMesh, IndexedHalfEdge*>
{
public:
ZilchDeclareType(IndexedHalfEdgeMeshEdgeArray, TypeCopyMode::ReferenceType);
};
//-------------------------------------------------------------------IndexedHalfEdgeFaceEdgeIndexArray
class IndexedHalfEdgeFaceEdgeIndexArray : public BoundArray<IndexedHalfEdgeFace, int>
{
public:
ZilchDeclareType(IndexedHalfEdgeFaceEdgeIndexArray, TypeCopyMode::ReferenceType);
};
//-------------------------------------------------------------------IndexedHalfEdgeMeshFaceArray
class IndexedHalfEdgeMeshFaceArray : public BoundArray<IndexedHalfEdgeMesh, IndexedHalfEdgeFace*>
{
public:
ZilchDeclareType(IndexedHalfEdgeMeshFaceArray, TypeCopyMode::ReferenceType);
};
//-------------------------------------------------------------------IndexedHalfEdge
class IndexedHalfEdge : public SafeId32Object
{
public:
ZilchDeclareType(IndexedHalfEdge, TypeCopyMode::ReferenceType);
/// Index of the tail vertex in the vertex list.
int mVertexIndex;
/// Index of the twin edge (edge on adjacent face).
int mTwinIndex;
/// Index of the face that owns this edge.
int mFaceIndex;
};
//-------------------------------------------------------------------IndexedHalfEdgeFace
class IndexedHalfEdgeFace : public SafeId32Object
{
public:
ZilchDeclareType(IndexedHalfEdgeFace, TypeCopyMode::ReferenceType);
typedef Array<int> EdgeArray;
typedef IndexedHalfEdgeFaceEdgeIndexArray BoundEdgeArray;
IndexedHalfEdgeFace();
/// The list of half-edges owned by this face.
BoundEdgeArray* GetEdges();
/// The actual edge array of indices.
EdgeArray mEdges;
/// The bound array of edges. This allows safe referencing in script.
BoundEdgeArray mBoundEdges;
};
//-------------------------------------------------------------------IndexedHalfEdgeMesh
/// An index based half-edge mesh. This is an edge-centric mesh representation that allows
/// efficient traversal from edges to anywhere else. Each edge is broken up into two
/// half-edges, one for each face it's a part of. Most sub-shapes contain indices back into
/// the 'global' list (e.g. an edge contains the index of the vertex in the mesh's vertex list).
/// This mesh format is meant for efficient traversal, but manipulation is not as easy with indices.
/// This should be loaded into a more efficient format (such as pointers) if manipulating a mesh.
class IndexedHalfEdgeMesh : public ReferenceCountedObject
{
public:
ZilchDeclareType(IndexedHalfEdgeMesh, TypeCopyMode::ReferenceType);
typedef Array<Vec3> VertexArray;
typedef Array<IndexedHalfEdge*> EdgeArray;
typedef Array<IndexedHalfEdgeFace*> FaceArray;
typedef IndexedHalfEdgeMeshVertexArray BoundVertexArray;
typedef IndexedHalfEdgeMeshEdgeArray BoundEdgeArray;
typedef IndexedHalfEdgeMeshFaceArray BoundFaceArray;
IndexedHalfEdgeMesh();
/// Create the buffers to store the provided mesh size.
void Create(int vertexCount, int edgeCount, int faceCount);
/// Clear all mesh data.
void Clear();
/// The list of vertices in this mesh.
BoundVertexArray* GetVertices();
/// The list of edge in this mesh.
BoundEdgeArray* GetEdges();
/// The list of faces in this mesh.
BoundFaceArray* GetFaces();
// The internal data that's efficient to work with at run-time
VertexArray mVertices;
EdgeArray mEdges;
FaceArray mFaces;
// The proxy arrays for binding. This allows safe referencing of the underlying primitives.
BoundVertexArray mBoundVertices;
BoundEdgeArray mBoundEdges;
BoundFaceArray mBoundFaces;
};
}// namespace Zero
| 29.704453
| 119
| 0.654355
|
jodavis42
|
deeff73bf44115b9aa19e662852a661458027b77
| 221
|
cpp
|
C++
|
C++/170923/170923/Item_4_Heal.cpp
|
ChoiChangYong/Game_Programing
|
6c290e31eaac526b0dbdfc59731e6479126e95bc
|
[
"MIT"
] | null | null | null |
C++/170923/170923/Item_4_Heal.cpp
|
ChoiChangYong/Game_Programing
|
6c290e31eaac526b0dbdfc59731e6479126e95bc
|
[
"MIT"
] | null | null | null |
C++/170923/170923/Item_4_Heal.cpp
|
ChoiChangYong/Game_Programing
|
6c290e31eaac526b0dbdfc59731e6479126e95bc
|
[
"MIT"
] | 1
|
2020-04-27T12:41:20.000Z
|
2020-04-27T12:41:20.000Z
|
#include "Item_4_Heal.h"
#include "Game.h"
#include <iostream>
using namespace std;
void Item_4_Heal::onCheck(Game* pGame)
{
pGame->Use_Item_4_Heal();
}
Item_4_Heal::Item_4_Heal()
{
}
Item_4_Heal::~Item_4_Heal()
{
}
| 11.631579
| 38
| 0.714932
|
ChoiChangYong
|
def119c406c8eaa5a601880b39120d51f9266eec
| 2,917
|
cpp
|
C++
|
bitsafe/window_effective.cpp
|
codereba/bittrace
|
6826559565aaafc9412d20427d21b73e23febcfe
|
[
"Unlicense"
] | 10
|
2018-11-09T01:08:15.000Z
|
2020-06-21T05:39:54.000Z
|
bitsafe/window_effective.cpp
|
codereba/bittrace
|
6826559565aaafc9412d20427d21b73e23febcfe
|
[
"Unlicense"
] | null | null | null |
bitsafe/window_effective.cpp
|
codereba/bittrace
|
6826559565aaafc9412d20427d21b73e23febcfe
|
[
"Unlicense"
] | 4
|
2018-11-09T03:29:52.000Z
|
2021-07-23T03:30:03.000Z
|
/*
*
* Copyright 2010 JiJie Shi(weixin:AIChangeLife)
*
* This file is part of bittrace.
*
* bittrace 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.
*
* bittrace 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 bittrace. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "stdafx.h"
#include "window_effective.h"
#define SHORT_WINDOW_DELAY 1
#define SHORT_WINDOW_STEP_SIZE 5
LRESULT short_window_close( CPaintManagerUI *pm, HWND wnd, ULONG delay, ULONG step )
{
LRESULT ret = ERROR_SUCCESS;
BOOL _ret;
RECT rect;
ULONG height;
INT32 i;
RECT cur_rect;
RECT paint_rc;
SIZE old_min_info;
do
{
ASSERT( wnd != NULL );
ASSERT( pm != NULL );
if( step == 0 )
{
step = SHORT_WINDOW_STEP_SIZE;
}
if( delay == 0 )
{
delay = SHORT_WINDOW_DELAY;
}
if( FALSE == ::IsWindow( wnd ) )
{
ASSERT( FALSE && "input the invalid window to show effective" );
break;
}
_ret = GetWindowRect( wnd, &rect );
if( FALSE == _ret )
{
SAFE_SET_ERROR_CODE( ret );
break;
}
height = _abs( rect.bottom - rect.top );
cur_rect = rect;
old_min_info = pm->GetMinInfo();
pm->SetMinInfo( 0, 0 );
for( i = 0; ( ULONG )i < height / 2; i += step )
{
cur_rect.bottom = rect.bottom - i;
cur_rect.top = rect.top + i;
paint_rc = cur_rect;
_ret = SetWindowPos( wnd, NULL, cur_rect.left, cur_rect.top, RECT_WIDTH( cur_rect ), RECT_HEIGHT( cur_rect ), SWP_SHOWWINDOW | SWP_NOREDRAW );
if( _ret == FALSE )
{}
{
pm->PaintStretchShortEffective( wnd, paint_rc );
}
Sleep( delay );
}
SetWindowPos( wnd, NULL, cur_rect.left, cur_rect.top, RECT_WIDTH( rect ), RECT_HEIGHT( rect ), SWP_HIDEWINDOW );
pm->SetMinInfo( old_min_info.cx, old_min_info.cy );
} while ( FALSE );
return ret;
}
#define DEF_TRANSPARENT_ANIMATE_TIME 5000
LRESULT transparent_animate( HWND wnd, ULONG time )
{
LRESULT ret = ERROR_SUCCESS;
BOOL _ret;
ASSERT( wnd != NULL );
if( FALSE == IsWindow( wnd ) )
{
ret = ERROR_INVALID_PARAMETER;
goto _return;
}
if( time == 0 )
{
time = DEF_TRANSPARENT_ANIMATE_TIME;
}
#if(WINVER >= 0x0500)
_ret = AnimateWindow( wnd, time, AW_ACTIVATE | AW_CENTER | AW_BLEND );
if( _ret == FALSE )
{
ret = GetLastError();
}
#endif // WINVER >= 0x0500
_return:
return ret;
}
| 21.768657
| 147
| 0.629071
|
codereba
|
def25db62073c18ceca30494b8ac3956e4a26189
| 1,169
|
cpp
|
C++
|
Old Code/SM64FM/src/main.cpp
|
sonich2401/SM64_Save_File_Converter
|
bd6876d66cbc3177b634540c7a2241e0ae8c759c
|
[
"MIT-0"
] | 6
|
2020-07-27T19:07:37.000Z
|
2021-08-29T19:16:07.000Z
|
Old Code/SM64FM/src/main.cpp
|
sonich2401/SM64_Save_File_Converter
|
bd6876d66cbc3177b634540c7a2241e0ae8c759c
|
[
"MIT-0"
] | 2
|
2021-06-09T05:49:41.000Z
|
2022-01-30T04:06:40.000Z
|
Old Code/SM64FM/src/main.cpp
|
sonich2401/SM64_Save_File_Converter
|
bd6876d66cbc3177b634540c7a2241e0ae8c759c
|
[
"MIT-0"
] | null | null | null |
#include <stdlib.h>
#include <stdio.h>
#include <typedefs.h>
#include "menu/option_decode.h"
#include "util/load_file/load_bin.h"
#include "EEPROM/EEPROM.h"
#include "menu/menu_choice.h"
#include "util/os/linux/escape_codes.h"
void exit_program(option_struct * options);
int main(int argc, cstring argv[]){
option_struct * options = option_decode(argc, argv);
EEPROM_Storage::get().orginal = (EEPROM*)malloc(sizeof(EEPROM));
if(options->in_path == NULL) return 0;
unsigned char * infile = load_bin(options->in_path);
*EEPROM_Storage::get().orginal = init_EEPROM(infile);
EEPROM_Storage::get().edited = (EEPROM*)memcpy(EEPROM_Storage::get().edited, EEPROM_Storage::get().orginal, 512);
free(infile);
menu_ask((directory*)&root, NULL);
exit_program(options);
return 0;
}
void exit_program(option_struct * options){
for(uint8 backup = 0; backup < 2; backup++){
for(uint8 sav = 0; sav < 4; sav++){
set_checksum(&eeprom->game_saves[sav][backup], 0);
}
set_checksum(&eeprom->menu_saves[backup], 1);
}
write_bin(options->out_path,(unsigned char*)eeprom, 512);
}
| 25.977778
| 117
| 0.663815
|
sonich2401
|
def94d20ef029a33c8313959adb0651a463e3480
| 4,645
|
cpp
|
C++
|
Desktop/FOSSA-GroundStationControlPanel/FOSSASatTracker/SGP4_experiments/main.cpp
|
FOSSASystems/FOSSA-GroundStationControlPanel
|
af83a09619239abe9fca09e073ab41c68bfd4822
|
[
"MIT"
] | 2
|
2021-11-07T16:26:46.000Z
|
2022-03-20T10:14:41.000Z
|
Desktop/FOSSA-GroundStationControlPanel/FOSSASatTracker/SGP4_experiments/main.cpp
|
FOSSASystems/FOSSA-GroundStationControlPanel
|
af83a09619239abe9fca09e073ab41c68bfd4822
|
[
"MIT"
] | 18
|
2020-08-28T13:38:36.000Z
|
2020-09-30T11:08:42.000Z
|
Desktop/FOSSA-GroundStationControlPanel/FOSSASatTracker/SGP4_experiments/main.cpp
|
FOSSASystems/FOSSA-GroundStationControlPanel
|
af83a09619239abe9fca09e073ab41c68bfd4822
|
[
"MIT"
] | 2
|
2020-07-29T21:19:28.000Z
|
2021-08-16T03:58:14.000Z
|
#include "sgp4io.h"
#include "sgp4unit.h"
#include <GeographicLib/Geocentric.hpp>
#include <iostream>
int main()
{
/*
INPUT is e.g.
2019
12
6
1
1
1
2020
12
6
1
1
1
*/
char fossasatTLELineA[70] = "1 44829U 19084F 20183.10006475 .00039774 00000-0 23016-3 0 9991";
char fossasatTLELineB[70] = "2 44829 96.9730 52.2137 0026683 179.4781 180.6520 15.77974288 32594";
std::cout << "Running! (" << SGP4Version << ")" << std::endl;
std::cout << "TLE: " << std::endl;
std::cout << fossasatTLELineA << std::endl;
std::cout << fossasatTLELineB << std::endl;
std::cout << std::endl;
// AIAA-2006-6753-Rev2.pdf (page 50 of 94)
// Parse the TLE data into the elsetrec structure.
elsetrec satrec;
char typerun = 'm';
char opsmode = 'i';
char typeinput = 'e';
gravconsttype gravconst = wgs84;
double startmfe;
double stopmfe;
double deltamin;
/// @warning stripping const qualifier.
// This method also invokes "Day2DMYHMS", "JDAY", "SGP4Init".
/*
* author : david vallado 719-573-2600 1 mar 2001
*
* inputs :
* longstr1 - first line of the tle
* longstr2 - second line of the tle
* typerun - type of run verification 'v', catalog 'c',
* manual 'm'
* typeinput - type of manual input mfe 'm', epoch 'e', dayofyr 'd'
* opsmode - mode of operation afspc or improved 'a', 'i'
* whichconst - which set of constants to use 72, 84
*
* outputs :
* satrec - structure containing all the sgp4 satellite information
*/
twoline2rv((char*)fossasatTLELineA, (char*)fossasatTLELineB,
typerun, typeinput, opsmode,
gravconst,
startmfe, stopmfe, deltamin,
satrec);
// Call the propogater (integrator?) at T=0
double positionVector[3]; // km
double velocityVector[3]; // km/s
/*
*
* author : david vallado 719-573-2600 28 jun 2005
*
* inputs :
* satrec - initialised structure from sgp4init() call.
* tsince - time eince epoch (minutes)
*
* outputs :
* r - position vector km
* v - velocity km/sec
* return code - non-zero on error.
* 1 - mean elements, ecc >= 1.0 or ecc < -0.001 or a < 0.95 er
* 2 - mean motion less than 0.0
* 3 - pert elements, ecc < 0.0 or ecc > 1.0
* 4 - semi-latus rectum < 0.0
* 5 - epoch elements are sub-orbital
* 6 - satellite has decayed
*/
// call the propogator once to get the initial state vector value.
sgp4(gravconst,
satrec,
0.0,
positionVector,
velocityVector);
double tsince = startmfe;
const GeographicLib::Geocentric& ellipsoid = GeographicLib::Geocentric::WGS84();
if (fabs(tsince) > 1.8e-8)
{
tsince = tsince - deltamin;
}
while ((tsince < stopmfe) && (satrec.error == 0))
{
tsince = tsince + deltamin;
if (tsince > stopmfe)
{
tsince = stopmfe;
}
sgp4(gravconst, satrec, tsince, positionVector, velocityVector);
if (satrec.error > 0)
{
std::cout << "Make sure the input is in the form\r\n2020\r\n\12\r\n\6\r\n\1\r\n1\r\n\1" << std::endl;
printf("Error %f code %3d\r\n", satrec.t, satrec.error);
}
if (satrec.error == 0)
{
// convert the position vector from Geocentric to Geodetic.
double lat, lon, h;
ellipsoid.Reverse(positionVector[0], positionVector[1], positionVector[2],
lat, lon, h);
// get the current datetime.
double jd = satrec.jdsatepoch + (tsince / 1440.0);
int year, mon, day, hr, min;
double sec;
invjday(jd, year, mon, day, hr, min, sec);
// print the information %5i%3i%3i %2i:%2i:%9.6f
std::cout << year << ":" << mon << ":" << day << " " << hr << ":" << min << ":" << sec << std::endl;
std::cout << std::endl;
std::cout << "Position Vector (km): " << std::endl;
std::cout << "(" << positionVector[0] << "," << positionVector[1] << "," << positionVector[2] << ")" << std::endl;
std::cout << std::endl;
std::cout << "Position Vector (Lat/Long): " << std::endl;
std::cout << "(" << lat << ", " << lon << ", " << h << ")" << std::endl;
std::cout << std::endl;
std::cout << "Velocity Vector (km/s): " << std::endl;
std::cout << "(" << velocityVector[0] << "," << velocityVector[1] << "," << velocityVector[2] << ")" << std::endl;
std::cout << std::endl;
}
}
std::cout << "Finished. Press any key to continue." << std::endl;
int v;
std::cin >> v;
return 0;
}
| 27.323529
| 117
| 0.56254
|
FOSSASystems
|
defaa02a4762d4b70cc4f0fb2249bf63a7fccfca
| 757
|
cpp
|
C++
|
alpaca/portfolio.cpp
|
aidanjalili/alpaca-trade-api-cpp
|
0914de8ba46cea4c289ef362539d77b2bee74807
|
[
"MIT"
] | 43
|
2020-04-07T03:28:22.000Z
|
2022-03-30T21:34:16.000Z
|
alpaca/portfolio.cpp
|
aidanjalili/alpaca-trade-api-cpp
|
0914de8ba46cea4c289ef362539d77b2bee74807
|
[
"MIT"
] | 5
|
2020-04-29T03:45:36.000Z
|
2021-03-31T00:59:43.000Z
|
alpaca/portfolio.cpp
|
aidanjalili/alpaca-trade-api-cpp
|
0914de8ba46cea4c289ef362539d77b2bee74807
|
[
"MIT"
] | 18
|
2020-04-27T18:35:18.000Z
|
2022-02-05T17:13:38.000Z
|
#include "alpaca/portfolio.h"
#include "alpaca/json.h"
#include "rapidjson/document.h"
namespace alpaca {
Status PortfolioHistory::fromJSON(const std::string& json) {
rapidjson::Document d;
if (d.Parse(json.c_str()).HasParseError()) {
return Status(1, "Received parse error when deserializing portfolio JSON");
}
if (!d.IsObject()) {
return Status(1, "Deserialized valid JSON but it wasn't a portfolio object");
}
PARSE_DOUBLE(base_value, "base_value")
PARSE_VECTOR_DOUBLES(equity, "equity")
PARSE_VECTOR_DOUBLES(profit_loss, "profit_loss")
PARSE_VECTOR_DOUBLES(profit_loss_pct, "profit_loss_pct")
PARSE_STRING(timeframe, "timeframe")
PARSE_VECTOR_UINT64(timestamp, "timestamp")
return Status();
}
} // namespace alpaca
| 28.037037
| 81
| 0.738441
|
aidanjalili
|
defb2c5f63928f233ffce6f66bbca5071e7175b0
| 395
|
cc
|
C++
|
C++/algorithms/iterative_bsearch.cc
|
Pejo-306/mystdlib
|
89d94bfb2fb590775f6d6f689eea6dbf89afd849
|
[
"MIT"
] | null | null | null |
C++/algorithms/iterative_bsearch.cc
|
Pejo-306/mystdlib
|
89d94bfb2fb590775f6d6f689eea6dbf89afd849
|
[
"MIT"
] | null | null | null |
C++/algorithms/iterative_bsearch.cc
|
Pejo-306/mystdlib
|
89d94bfb2fb590775f6d6f689eea6dbf89afd849
|
[
"MIT"
] | null | null | null |
using namespace std;
int bsearch(int *arr, int size, int value)
{
int left = 0, right = size - 1, middle;
while (left <= right) {
middle = (left + right) / 2;
if (arr[middle] == value)
return middle;
else if (arr[middle] < value)
left = middle + 1;
else
right = middle - 1;
}
return -1; // value not found
}
| 21.944444
| 43
| 0.498734
|
Pejo-306
|
deff9e0ef99374df542a6693b5dcc62e077471c5
| 6,456
|
cpp
|
C++
|
src/IB/IBLagrangianForceStrategySet.cpp
|
MSV-Project/IBAMR
|
3cf614c31bb3c94e2620f165ba967cba719c45ea
|
[
"BSD-3-Clause"
] | 2
|
2017-12-06T06:16:36.000Z
|
2021-03-13T12:28:08.000Z
|
src/IB/IBLagrangianForceStrategySet.cpp
|
MSV-Project/IBAMR
|
3cf614c31bb3c94e2620f165ba967cba719c45ea
|
[
"BSD-3-Clause"
] | null | null | null |
src/IB/IBLagrangianForceStrategySet.cpp
|
MSV-Project/IBAMR
|
3cf614c31bb3c94e2620f165ba967cba719c45ea
|
[
"BSD-3-Clause"
] | null | null | null |
// Filename: IBLagrangianForceStrategySet.cpp
// Created on 04 April 2007 by Boyce Griffith
//
// Copyright (c) 2002-2013, Boyce Griffith
// 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 New York University nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
/////////////////////////////// INCLUDES /////////////////////////////////////
#include "IBLagrangianForceStrategySet.h"
#include "PatchHierarchy.h"
#include "ibamr/namespaces.h" // IWYU pragma: keep
#include "ibtk/IBTK_CHKERRQ.h"
#include "ibtk/LData.h"
namespace IBTK {
class LDataManager;
} // namespace IBTK
/////////////////////////////// NAMESPACE ////////////////////////////////////
namespace IBAMR
{
/////////////////////////////// STATIC ///////////////////////////////////////
/////////////////////////////// PUBLIC ///////////////////////////////////////
IBLagrangianForceStrategySet::~IBLagrangianForceStrategySet()
{
// intentionally blank
return;
}// ~IBLagrangianForceStrategySet
void
IBLagrangianForceStrategySet::setTimeInterval(
const double current_time,
const double new_time)
{
for (std::vector<Pointer<IBLagrangianForceStrategy> >::const_iterator cit = d_strategy_set.begin(); cit != d_strategy_set.end(); ++cit)
{
(*cit)->setTimeInterval(current_time, new_time);
}
return;
}// setTimeInterval
void
IBLagrangianForceStrategySet::initializeLevelData(
const Pointer<PatchHierarchy<NDIM> > hierarchy,
const int level_number,
const double init_data_time,
const bool initial_time,
LDataManager* const l_data_manager)
{
for (std::vector<Pointer<IBLagrangianForceStrategy> >::const_iterator cit = d_strategy_set.begin(); cit != d_strategy_set.end(); ++cit)
{
(*cit)->initializeLevelData(
hierarchy, level_number, init_data_time, initial_time, l_data_manager);
}
return;
}// initializeLevelData
void
IBLagrangianForceStrategySet::computeLagrangianForce(
Pointer<LData> F_data,
Pointer<LData> X_data,
Pointer<LData> U_data,
const Pointer<PatchHierarchy<NDIM> > hierarchy,
const int level_number,
const double data_time,
LDataManager* const l_data_manager)
{
for (std::vector<Pointer<IBLagrangianForceStrategy> >::const_iterator cit = d_strategy_set.begin(); cit != d_strategy_set.end(); ++cit)
{
(*cit)->computeLagrangianForce(
F_data, X_data, U_data, hierarchy, level_number, data_time, l_data_manager);
}
return;
}// computeLagrangianForce
void
IBLagrangianForceStrategySet::computeLagrangianForceJacobianNonzeroStructure(
std::vector<int>& d_nnz,
std::vector<int>& o_nnz,
const Pointer<PatchHierarchy<NDIM> > hierarchy,
const int level_number,
LDataManager* const l_data_manager)
{
for (std::vector<Pointer<IBLagrangianForceStrategy> >::const_iterator cit = d_strategy_set.begin(); cit != d_strategy_set.end(); ++cit)
{
(*cit)->computeLagrangianForceJacobianNonzeroStructure(
d_nnz, o_nnz, hierarchy, level_number, l_data_manager);
}
return;
}// computeLagrangianForceJacobianNonzeroStructure
void
IBLagrangianForceStrategySet::computeLagrangianForceJacobian(
Mat& J_mat,
MatAssemblyType assembly_type,
const double X_coef,
Pointer<LData> X_data,
const double U_coef,
Pointer<LData> U_data,
const Pointer<PatchHierarchy<NDIM> > hierarchy,
const int level_number,
const double data_time,
LDataManager* const l_data_manager)
{
for (std::vector<Pointer<IBLagrangianForceStrategy> >::const_iterator cit = d_strategy_set.begin(); cit != d_strategy_set.end(); ++cit)
{
(*cit)->computeLagrangianForceJacobian(
J_mat, MAT_FLUSH_ASSEMBLY, X_coef, X_data, U_coef, U_data, hierarchy, level_number, data_time, l_data_manager);
}
if (assembly_type != MAT_FLUSH_ASSEMBLY)
{
int ierr;
ierr = MatAssemblyBegin(J_mat, assembly_type); IBTK_CHKERRQ(ierr);
ierr = MatAssemblyEnd(J_mat, assembly_type); IBTK_CHKERRQ(ierr);
}
return;
}// computeLagrangianForceJacobian
double
IBLagrangianForceStrategySet::computeLagrangianEnergy(
Pointer<LData> X_data,
Pointer<LData> U_data,
const Pointer<PatchHierarchy<NDIM> > hierarchy,
const int level_number,
const double data_time,
LDataManager* const l_data_manager)
{
double ret_val = 0.0;
for (std::vector<Pointer<IBLagrangianForceStrategy> >::const_iterator cit = d_strategy_set.begin(); cit != d_strategy_set.end(); ++cit)
{
ret_val += (*cit)->computeLagrangianEnergy(X_data, U_data, hierarchy, level_number, data_time, l_data_manager);
}
return ret_val;
}// computeLagrangianEnergy
/////////////////////////////// PROTECTED ////////////////////////////////////
/////////////////////////////// PRIVATE //////////////////////////////////////
/////////////////////////////// NAMESPACE ////////////////////////////////////
} // namespace IBAMR
//////////////////////////////////////////////////////////////////////////////
| 37.103448
| 139
| 0.670074
|
MSV-Project
|
72007729164461efc492cbee49cf51da6b5c9677
| 2,935
|
cpp
|
C++
|
example/sql/test_multithread.cpp
|
zizzzw/fflib
|
ba9b465347b650d86c34876fbfae48bc31194d97
|
[
"MIT"
] | 1
|
2022-02-08T07:28:07.000Z
|
2022-02-08T07:28:07.000Z
|
example/sql/test_multithread.cpp
|
zizzzw/fflib
|
ba9b465347b650d86c34876fbfae48bc31194d97
|
[
"MIT"
] | null | null | null |
example/sql/test_multithread.cpp
|
zizzzw/fflib
|
ba9b465347b650d86c34876fbfae48bc31194d97
|
[
"MIT"
] | 2
|
2022-01-06T02:16:09.000Z
|
2022-01-19T12:49:54.000Z
|
/***********************************************
The MIT License (MIT)
Copyright (c) 2012 Athrun Arthur <athrunarthur@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*************************************************/
#include "ff/sql/mysql.hpp"
#include "ff/sql/table.h"
#include <thread>
struct mymeta {
constexpr static const char *table_name = "yyy";
};
define_column(c1, column, uint64_t, "id");
define_column(c2, key, std::string, "event");
define_column(c3, index, uint64_t, "ts");
typedef ff::sql::table<ff::sql::mysql<ff::sql::cppconn>, mymeta, c1, c2, c3>
mytable;
int main(int argc, char *argv[]) {
ff::sql::mysql<ff::sql::cppconn> engine("tcp://127.0.0.1:3306", "root", "",
"test");
mytable::create_table(&engine);
mytable::row_collection_type rows;
mytable::row_collection_type::row_type t1, t2;
t1.set<c1, c2, c3>(1, "c1", 123435);
rows.push_back(std::move(t1));
t2.set<c1, c2, c3>(2, "c2", 1235);
rows.push_back(std::move(t2));
mytable::insert_or_replace_rows(&engine, rows);
std::thread thrd([&engine]() {
auto local_engine = engine.thread_copy();
auto ret2 = mytable::select<c1, c2, c3>(local_engine.get())
// auto ret2 = mytable::select<c1, c2, c3>(&engine)
.where(c1::eq(2))
.order_by<c1, ff::sql::desc>()
.limit(1)
.eval();
std::cout << ret2.size() << std::endl;
std::cout << ret2[0].get<c1>() << ", " << ret2[0].get<c2>() << ", "
<< ret2[0].get<c3>() << std::endl;
});
auto ret1 = mytable::select<c1, c2, c3>(&engine).eval();
std::cout << "size: " << ret1.size() << std::endl;
for (size_t i = 0; i < ret1.size(); ++i) {
std::cout << ret1[i].get<c1>() << ", " << ret1[i].get<c2>() << ", "
<< ret1[i].get<c3>() << std::endl;
}
thrd.join();
return 0;
}
| 37.151899
| 79
| 0.612947
|
zizzzw
|
7200cb8c29aa54b386846e16aac4f09b5848effa
| 9,142
|
cpp
|
C++
|
Code/Core/CoreTest/Tests/TestSmallBlockAllocator.cpp
|
qq573011406/FASTBuild_UnrealEngine
|
29c49672f82173a903cb32f0e4656e2fd07ebef2
|
[
"MIT"
] | 30
|
2020-07-15T06:16:55.000Z
|
2022-02-10T21:37:52.000Z
|
Code/Core/CoreTest/Tests/TestSmallBlockAllocator.cpp
|
qq573011406/FASTBuild_UnrealEngine
|
29c49672f82173a903cb32f0e4656e2fd07ebef2
|
[
"MIT"
] | 1
|
2020-11-23T13:35:00.000Z
|
2020-11-23T13:35:00.000Z
|
Code/Core/CoreTest/Tests/TestSmallBlockAllocator.cpp
|
qq573011406/FASTBuild_UnrealEngine
|
29c49672f82173a903cb32f0e4656e2fd07ebef2
|
[
"MIT"
] | 12
|
2020-09-16T17:39:34.000Z
|
2021-08-17T11:32:37.000Z
|
// TestSmallBlockAllocator.cpp
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include "TestFramework/UnitTest.h"
#include "Core/Containers/Array.h"
#include "Core/Math/Random.h"
#include "Core/Mem/Mem.h"
#include "Core/Mem/SmallBlockAllocator.h"
#include "Core/Process/Thread.h"
#include "Core/Time/Timer.h"
#include "Core/Tracing/Tracing.h"
// System
#include <stdlib.h>
// TestSmallBlockAllocator
//------------------------------------------------------------------------------
class TestSmallBlockAllocator : public UnitTest
{
private:
DECLARE_TESTS
void SingleThreaded() const;
void MultiThreaded() const;
// struct for managing threads
class ThreadInfo
{
public:
Thread::ThreadHandle m_ThreadHandle = INVALID_THREAD_HANDLE;
Array< uint32_t > * m_AllocationSizes = nullptr;
uint32_t m_RepeatCount = 0;
float m_TimeTaken = 0.0f;
};
// Helper functions
static void GetRandomAllocSizes( const uint32_t numAllocs, Array< uint32_t> & allocSizes );
static float AllocateFromSystemAllocator( const Array< uint32_t > & allocSizes, const uint32_t repeatCount );
static float AllocateFromSmallBlockAllocator( const Array< uint32_t > & allocSizes, const uint32_t repeatCount, const bool threadSafe = true );
static uint32_t ThreadFunction_System( void * userData );
static uint32_t ThreadFunction_SmallBlock( void * userData );
};
// Register Tests
//------------------------------------------------------------------------------
REGISTER_TESTS_BEGIN( TestSmallBlockAllocator )
REGISTER_TEST( SingleThreaded )
REGISTER_TEST( MultiThreaded )
REGISTER_TESTS_END
// SingleThreaded
//------------------------------------------------------------------------------
void TestSmallBlockAllocator::SingleThreaded() const
{
#if defined( DEBUG )
const uint32_t numAllocs( 10 * 1000 );
#else
const uint32_t numAllocs( 100 * 1000 );
#endif
const uint32_t repeatCount( 10 );
Array< uint32_t > allocSizes( 0, true );
GetRandomAllocSizes( numAllocs, allocSizes );
float time1 = AllocateFromSystemAllocator( allocSizes, repeatCount );
float time2 = AllocateFromSmallBlockAllocator( allocSizes, repeatCount );
float time3 = AllocateFromSmallBlockAllocator( allocSizes, repeatCount, false ); // Thread-safe = false
// output
OUTPUT( "System (malloc) : %2.3fs - %u allocs @ %u allocs/sec\n", (double)time1, ( numAllocs * repeatCount ), (uint32_t)( float( numAllocs * repeatCount ) / time1 ) );
OUTPUT( "SmallBlockAllocator : %2.3fs - %u allocs @ %u allocs/sec\n", (double)time2, ( numAllocs * repeatCount ), (uint32_t)( float( numAllocs * repeatCount ) / time2 ) );
OUTPUT( "SmallBlockAllocator (Single-Threaded mode) : %2.3fs - %u allocs @ %u allocs/sec\n", (double)time3, ( numAllocs * repeatCount ), (uint32_t)( float( numAllocs * repeatCount ) / time3 ) );
}
// MultiThreaded
//------------------------------------------------------------------------------
void TestSmallBlockAllocator::MultiThreaded() const
{
#if defined( DEBUG )
const uint32_t numAllocs( 10 * 1000 );
#else
const uint32_t numAllocs( 100 * 1000 );
#endif
const uint32_t repeatCount( 10 );
Array< uint32_t > allocSizes( 0, true );
GetRandomAllocSizes( numAllocs, allocSizes );
float time1( 0.0f );
float time2( 0.0f );
const size_t numThreads = 4;
// System Allocator
{
// Create some threads
ThreadInfo info[ numThreads ];
for ( size_t i = 0; i < numThreads; ++i )
{
info[ i ].m_AllocationSizes = & allocSizes;
info[ i ].m_RepeatCount = repeatCount;
info[ i ].m_ThreadHandle = Thread::CreateThread( ThreadFunction_System, "SmallBlock", ( 64 * KILOBYTE ), (void*)&info[ i ] );
TEST_ASSERT( info[ i ].m_ThreadHandle != INVALID_THREAD_HANDLE );
}
// Join the threads
for ( size_t i = 0; i < numThreads; ++i )
{
bool timedOut;
Thread::WaitForThread( info[ i ].m_ThreadHandle, 500 * 1000, timedOut );
Thread::CloseHandle( info[ i ].m_ThreadHandle );
TEST_ASSERT( timedOut == false );
time1 += info[ i ].m_TimeTaken;
}
}
// Small Block Allocator
{
// Create some threads
ThreadInfo info[ numThreads ];
for ( size_t i = 0; i < numThreads; ++i )
{
info[ i ].m_AllocationSizes = & allocSizes;
info[ i ].m_RepeatCount = repeatCount;
info[ i ].m_ThreadHandle = Thread::CreateThread( ThreadFunction_SmallBlock, "SmallBlock", ( 64 * KILOBYTE ), (void*)&info[ i ] );
TEST_ASSERT( info[ i ].m_ThreadHandle != INVALID_THREAD_HANDLE );
}
// Join the threads
for ( size_t i = 0; i < numThreads; ++i )
{
bool timedOut;
Thread::WaitForThread( info[ i ].m_ThreadHandle, 500 * 1000, timedOut );
Thread::CloseHandle( info[ i ].m_ThreadHandle );
TEST_ASSERT( timedOut == false );
time2 += info[ i ].m_TimeTaken;
}
time2 /= numThreads;
}
// output
OUTPUT( "System (malloc) : %2.3fs - %u allocs @ %u allocs/sec\n", (double)time1, ( numAllocs * repeatCount ), (uint32_t)( float( numAllocs * repeatCount ) / time1 ) );
OUTPUT( "SmallBlockAllocator : %2.3fs - %u allocs @ %u allocs/sec\n", (double)time2, ( numAllocs * repeatCount ), (uint32_t)( float( numAllocs * repeatCount ) / time2 ) );
}
// GetRandomAllocSizes
//------------------------------------------------------------------------------
/*static*/ void TestSmallBlockAllocator::GetRandomAllocSizes( const uint32_t numAllocs, Array< uint32_t > & allocSizes )
{
const size_t maxSize( 256 ); // max supported size of block allocator
allocSizes.SetCapacity( numAllocs );
Random r;
r.SetSeed( 0 ); // Deterministic between runs by using a consistent seed
for ( size_t i = 0; i < numAllocs; ++i )
{
allocSizes.Append( r.GetRandIndex( maxSize ) );
}
}
// AllocateFromSystemAllocator
//------------------------------------------------------------------------------
/*static*/ float TestSmallBlockAllocator::AllocateFromSystemAllocator( const Array< uint32_t > & allocSizes, const uint32_t repeatCount )
{
const size_t numAllocs = allocSizes.GetSize();
Array< void * > allocs( numAllocs, false );
Timer timer;
for ( size_t r = 0; r < repeatCount; ++r )
{
// use malloc
for ( uint32_t i = 0; i < numAllocs; ++i )
{
uint32_t * mem = (uint32_t *)malloc( allocSizes[ i ] );
allocs.Append( mem );
}
// use free
for ( uint32_t i = 0; i < numAllocs; ++i )
{
void * mem = allocs[ i ];
free( mem );
}
allocs.Clear();
}
return timer.GetElapsed();
}
// AllocateFromSmallBlockAllocator
//------------------------------------------------------------------------------
/*static*/ float TestSmallBlockAllocator::AllocateFromSmallBlockAllocator( const Array< uint32_t > & allocSizes, const uint32_t repeatCount, const bool threadSafe )
{
const size_t numAllocs = allocSizes.GetSize();
Array< void * > allocs( numAllocs, false );
Timer timer;
if ( threadSafe == false )
{
SmallBlockAllocator::SetSingleThreadedMode( true );
}
for ( size_t r = 0; r < repeatCount; ++r )
{
// Use ALLOC
for ( uint32_t i = 0; i < numAllocs; ++i )
{
uint32_t * mem = (uint32_t *)ALLOC( allocSizes[ i ] );
allocs.Append( mem );
}
// Use FREE
for ( uint32_t i = 0; i < numAllocs; ++i )
{
void * mem = allocs[ i ];
FREE( mem );
}
allocs.Clear();
}
if ( threadSafe == false )
{
SmallBlockAllocator::SetSingleThreadedMode( false );
}
return timer.GetElapsed();
}
// ThreadFunction_System
//------------------------------------------------------------------------------
/*static*/ uint32_t TestSmallBlockAllocator::ThreadFunction_System( void * userData )
{
ThreadInfo & info = *( reinterpret_cast< ThreadInfo * >( userData ) );
info.m_TimeTaken = AllocateFromSystemAllocator( *info.m_AllocationSizes, info.m_RepeatCount );
return 0;
}
// ThreadFunction_SmallBlock
//------------------------------------------------------------------------------
/*static*/ uint32_t TestSmallBlockAllocator::ThreadFunction_SmallBlock( void * userData )
{
ThreadInfo & info = *( reinterpret_cast< ThreadInfo * >( userData ) );
info.m_TimeTaken = AllocateFromSmallBlockAllocator( *info.m_AllocationSizes, info.m_RepeatCount );
return 0;
}
//------------------------------------------------------------------------------
| 35.710938
| 198
| 0.556005
|
qq573011406
|
72028a958d4a35056f23ad403159ba57ac3b6bbc
| 1,639
|
h++
|
C++
|
include/wheels/adl/swap.h++
|
dendisuhubdy/wheels
|
a49e790dbc277335907b393ebaddea947ae14d0e
|
[
"CC0-1.0"
] | null | null | null |
include/wheels/adl/swap.h++
|
dendisuhubdy/wheels
|
a49e790dbc277335907b393ebaddea947ae14d0e
|
[
"CC0-1.0"
] | null | null | null |
include/wheels/adl/swap.h++
|
dendisuhubdy/wheels
|
a49e790dbc277335907b393ebaddea947ae14d0e
|
[
"CC0-1.0"
] | 1
|
2019-11-16T18:30:53.000Z
|
2019-11-16T18:30:53.000Z
|
// Wheels - various C++ utilities
//
// Written in 2013 by Martinho Fernandes <martinho.fernandes@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>
// ADL-enabled swap
#ifndef WHEELS_ADL_SWAP_HPP
#define WHEELS_ADL_SWAP_HPP
#include <utility> // swap, declval
namespace wheels {
namespace adl {
namespace detail {
using std::swap;
template <typename T, typename U,
typename Result = decltype(swap(std::declval<T>(), std::declval<U>())),
bool NoExcept = noexcept(swap(std::declval<T>(), std::declval<U>()))>
Result adl_swap(T&& t, U&& u) noexcept(NoExcept) {
return swap(std::forward<T>(t), std::forward<U>(u));
}
} // namespace detail
// Calls swap with ADL-lookup include std::swap
template <typename T, typename U,
typename Result = decltype(detail::adl_swap(std::declval<T>(), std::declval<U>())),
bool NoExcept = noexcept(detail::adl_swap(std::declval<T>(), std::declval<U>()))>
Result swap(T&& t, U&& u) noexcept(NoExcept) {
return detail::adl_swap(std::forward<T>(t), std::forward<U>(u));
}
} // namespace adl
} // namespace wheels
#endif // WHEELS_ADL_SWAP_HPP
| 38.116279
| 101
| 0.626602
|
dendisuhubdy
|
72029ac0401188223aa3ccc577020843e1245dd9
| 3,722
|
cc
|
C++
|
src/connectivity/wlan/drivers/testing/lib/sim-env/sim-env.cc
|
opensource-assist/fuschia
|
66646c55b3d0b36aae90a4b6706b87f1a6261935
|
[
"BSD-3-Clause"
] | null | null | null |
src/connectivity/wlan/drivers/testing/lib/sim-env/sim-env.cc
|
opensource-assist/fuschia
|
66646c55b3d0b36aae90a4b6706b87f1a6261935
|
[
"BSD-3-Clause"
] | null | null | null |
src/connectivity/wlan/drivers/testing/lib/sim-env/sim-env.cc
|
opensource-assist/fuschia
|
66646c55b3d0b36aae90a4b6706b87f1a6261935
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sim-env.h"
#include <zircon/assert.h>
namespace wlan::simulation {
uint64_t Environment::event_count_ = 0;
void Environment::Run() {
while (!events_.empty()) {
auto event = std::move(events_.front());
events_.pop_front();
// Make sure that time is always moving forward
ZX_ASSERT(event->time >= time_);
time_ = event->time;
// Send event to client who requested it
event->requester->ReceiveNotification(event->payload);
}
}
void Environment::TxBeacon(StationIfc* sender, const wlan_channel_t& channel,
const wlan_ssid_t& ssid, const common::MacAddr& bssid) {
for (auto sta : stations_) {
if (sta != sender) {
sta->RxBeacon(channel, ssid, bssid);
}
}
}
void Environment::TxAssocReq(StationIfc* sender, const wlan_channel_t& channel,
const common::MacAddr& src, const common::MacAddr& bssid) {
for (auto sta : stations_) {
if (sta != sender) {
sta->RxAssocReq(channel, src, bssid);
}
}
}
void Environment::TxAssocResp(StationIfc* sender, const wlan_channel_t& channel,
const common::MacAddr& src, const common::MacAddr& dst,
uint16_t status) {
for (auto sta : stations_) {
if (sta != sender) {
sta->RxAssocResp(channel, src, dst, status);
}
}
}
void Environment::TxDisassocReq(StationIfc* sender, const wlan_channel_t& channel,
const common::MacAddr& src, const common::MacAddr& dst,
uint16_t reason) {
for (auto sta : stations_) {
if (sta != sender) {
sta->RxDisassocReq(channel, src, dst, reason);
}
}
}
void Environment::TxProbeReq(StationIfc* sender, const wlan_channel_t& channel,
const common::MacAddr& src) {
for (auto sta : stations_) {
if (sta != sender) {
sta->RxProbeReq(channel, src);
}
}
}
void Environment::TxProbeResp(StationIfc* sender, const wlan_channel_t& channel,
const common::MacAddr& src, const common::MacAddr& dst,
const wlan_ssid_t& ssid) {
for (auto sta : stations_) {
if (sta != sender) {
sta->RxProbeResp(channel, src, dst, ssid);
}
}
}
zx_status_t Environment::ScheduleNotification(StationIfc* sta, zx::duration delay, void* payload,
uint64_t* id_out) {
uint64_t id = event_count_++;
// Disallow past events
if (delay < zx::usec(0)) {
return ZX_ERR_INVALID_ARGS;
}
auto event = std::make_unique<EnvironmentEvent>();
event->id = id;
event->time = time_ + delay;
event->requester = sta;
event->payload = payload;
// Keep our events sorted in ascending order of absolute time. When multiple events are
// scheduled for the same time, the first requested will be processed first.
auto event_iter = events_.begin();
while (event_iter != events_.end() && (*event_iter)->time <= event->time) {
event_iter++;
}
events_.insert(event_iter, std::move(event));
if (id_out != nullptr) {
*id_out = id;
}
return ZX_OK;
}
// Since all events are processed synchronously, we don't have to worry about locking.
zx_status_t Environment::CancelNotification(StationIfc* sta, uint64_t id) {
for (auto& event_iter : events_) {
if (event_iter->requester == sta && event_iter->id == id) {
events_.remove(event_iter);
return ZX_OK;
}
}
return ZX_ERR_NOT_FOUND;
}
} // namespace wlan::simulation
| 29.539683
| 97
| 0.622783
|
opensource-assist
|
7202f264bd57851ca7f5b279dd6700bd6f5d9dd6
| 556
|
cc
|
C++
|
examples/toy/andor.cc
|
paulhjkelly/taskgraph-metaprogramming
|
54c4e2806a97bec555a90784ab4cf0880660bf89
|
[
"BSD-3-Clause"
] | 5
|
2020-04-11T21:30:19.000Z
|
2021-12-04T16:16:09.000Z
|
examples/toy/andor.cc
|
paulhjkelly/taskgraph-metaprogramming
|
54c4e2806a97bec555a90784ab4cf0880660bf89
|
[
"BSD-3-Clause"
] | null | null | null |
examples/toy/andor.cc
|
paulhjkelly/taskgraph-metaprogramming
|
54c4e2806a97bec555a90784ab4cf0880660bf89
|
[
"BSD-3-Clause"
] | null | null | null |
#include <TaskGraph>
using namespace tg;
typedef TaskGraph<void,int> andor_TaskGraph;
int main( int argc, char *argv[] ) {
andor_TaskGraph T;
taskgraph( andor_TaskGraph, T, tuple1(a) ) {
tVar(int, b);
b = ((a < 12) + (a > 42));
b = ((a > 6) - (a < 9));
b = ((a < 12) * (a > 42));
b = ((a > 6) / (a < 9));
b = ((a < 12) & (a > 42));
b = ((a > 6) | (a < 9));
b = ((a < 12) && (a > 42));
b = ((a > 6) || (a < 9));
b = ((a < 12) << (a > 42));
b = ((a > 6) >> (a < 9));
tIf( b > 1 ) { }
}
T.print();
}
| 22.24
| 46
| 0.393885
|
paulhjkelly
|
7208b1a74f7a044ea3b92c8d2697cdd2dffbc33f
| 437
|
hpp
|
C++
|
include/imgui.hpp
|
richard-vock/graphene
|
1a721894a9972c8865a1ad0861d500cef8436932
|
[
"Unlicense"
] | null | null | null |
include/imgui.hpp
|
richard-vock/graphene
|
1a721894a9972c8865a1ad0861d500cef8436932
|
[
"Unlicense"
] | null | null | null |
include/imgui.hpp
|
richard-vock/graphene
|
1a721894a9972c8865a1ad0861d500cef8436932
|
[
"Unlicense"
] | null | null | null |
#pragma once
#include <string>
#include <imgui.h>
#include "common.hpp"
#include "events.hpp"
struct GLFWwindow;
namespace graphene::imgui {
IMGUI_IMPL_API bool init_application(GLFWwindow* window, const std::string& font_path, float font_size, std::shared_ptr<event_manager> events);
IMGUI_IMPL_API void shutdown_application();
IMGUI_IMPL_API void init_frame();
IMGUI_IMPL_API void draw_frame();
} // namespace graphene::imgui
| 20.809524
| 143
| 0.78032
|
richard-vock
|
7209c4bdc94f639f48deccad6ab5e8cd5451ec5e
| 4,139
|
cpp
|
C++
|
libdclalgo/tests/AzimuthEvaluationTests.cpp
|
OlegZhavoronkov/tnk_certification
|
9ef3544f3fd27073b78e38bba26af76e79f55a78
|
[
"Unlicense"
] | null | null | null |
libdclalgo/tests/AzimuthEvaluationTests.cpp
|
OlegZhavoronkov/tnk_certification
|
9ef3544f3fd27073b78e38bba26af76e79f55a78
|
[
"Unlicense"
] | null | null | null |
libdclalgo/tests/AzimuthEvaluationTests.cpp
|
OlegZhavoronkov/tnk_certification
|
9ef3544f3fd27073b78e38bba26af76e79f55a78
|
[
"Unlicense"
] | null | null | null |
#include "AzimuthEvaluation.h"
#include "PolarDecomposition.h"
#include "LibraryParameters.h"
#include <opencv2/core.hpp>
#include <gtest/gtest.h>
#include <limits>
#include <vector>
class AzimuthEvaluationTests : public ::testing::Test {
public:
AzimuthEvaluationTests();
cv::Mat genRandomMat(double min, double max);
protected:
cv::Mat x;
cv::Mat y;
cv::Mat atan2XYAnswer;
std::vector<double> polarAngles = {0, 45, 90, 135};
std::vector<double> pInverseMatrixData = {0.2500, 0.2500, 0.2500, 0.2500,
0.5000, 0.0000, -0.5000, 0.0000,
0.0000, 0.5000, 0.0000, -0.5000};
cv::Mat pInverseMatrix;
std::vector<uint8_t> imageData1 =
{
1, 2, 3,
4, 5, 6
};
std::vector<uint8_t> imageData2 =
{
11, 12, 13,
14, 15, 16
};
std::vector<uint8_t> combinedImageData =
{
1, 2, 3, 4, 5, 6,
11, 12, 13, 14, 15, 16,
};
cv::Mat image1;
cv::Mat image2;
cv::Mat combinedImage;
int rows = 2048;
int cols = 2448;
double reflection = 1.3;
std::vector<double> standardAnglesRad = {0, M_PI / 4, M_PI / 2, M_PI * 3 / 4};
};
AzimuthEvaluationTests::AzimuthEvaluationTests() {
cv::theRNG().state = time(nullptr);
double xData = 1. / sqrt(2.);
double yData = 1. / sqrt(2.);
double atan2Answer = atan2(yData, xData);
int vectorSize = 10000000;
x = cv::Mat(1, vectorSize, CV_64FC1, xData);
y = cv::Mat(1, vectorSize, CV_64FC1, yData);
atan2XYAnswer = cv::Mat(vectorSize, 1, CV_64FC1, atan2Answer);
pInverseMatrix = cv::Mat(3, 4, CV_64FC1, pInverseMatrixData.data());
image1 = cv::Mat(2, 3, CV_8UC1, imageData1.data());
image2 = cv::Mat(2, 3, CV_8UC1, imageData2.data());
combinedImage = cv::Mat(2, 6, CV_8UC1, combinedImageData.data());
LibraryParameters::configure(LibraryParameters::PolarizationSensorOrder::order90_45_135_0);
}
cv::Mat AzimuthEvaluationTests::genRandomMat(double min, double max) {
cv::Mat dst(rows, cols, CV_64FC1, 0.);
cv::randu(dst, min, max);
return dst;
}
static cv::Mat epsilon(int rows, int cols) {
// Epsilon for double values 1e-15,
// std::numeric_limits<double>::epsilon() is not good way,
// close values don't fit
return cv::Mat(rows, cols, CV_64FC1, 1e-15);
}
TEST_F(AzimuthEvaluationTests, getAtan2Vector) {
cv::Mat atanRes = getAtan2Vector(x, y);
EXPECT_EQ(cv::countNonZero(atan2XYAnswer != atanRes), 0);
}
TEST_F(AzimuthEvaluationTests, getAtan2VectorParallel) {
cv::Mat atanRes = getAtan2VectorParallel(x, y);
EXPECT_EQ(cv::countNonZero(atan2XYAnswer != atanRes), 0);
}
TEST_F(AzimuthEvaluationTests, getReshapedPolarImagesFast) {
cv::Mat p = getReshapedPolarImages_fast({image1, image2});
EXPECT_EQ(cv::countNonZero(combinedImage != p), 0);
}
TEST_F(AzimuthEvaluationTests, getReshapedPolarImagesFastTemplate) {
cv::Mat p = getReshapedPolarImages_fast_template<uint8_t>({image1, image2});
EXPECT_EQ(cv::countNonZero(combinedImage != p), 0);
}
TEST_F(AzimuthEvaluationTests, computeAzimuth) {
cv::Mat x(1, 2, CV_64FC1, 1.3);
std::vector<cv::Mat> polarImages = decomposeImages(x, x, x,
standardAnglesRad);
cv::Mat res(1, 2, CV_64FC1, 0.);
computeAzimuth(polarImages, res);
EXPECT_EQ(cv::countNonZero(cv::abs(res - x) > epsilon(1, 2)), 0);
}
TEST_F(AzimuthEvaluationTests, computeAzimuthFast) {
cv::Mat x(1, 2, CV_64FC1, 1.3);
std::vector<cv::Mat> polarImages = decomposeImages(x, x, x,
standardAnglesRad);
cv::Mat res(1, 2, CV_64FC1, 0.);
computeAzimuth_fast(polarImages, res);
EXPECT_EQ(cv::countNonZero(cv::abs(res - x) > epsilon(1, 2)), 0);
}
TEST_F(AzimuthEvaluationTests, computePolDegree) {
cv::Mat x(1, 2, CV_64FC1, 1.0);
std::vector<cv::Mat> polarImages = decomposeImages(x, x, x,
standardAnglesRad);
cv::Mat res(1, 2, CV_64FC1, 0.);
computePolDegree(polarImages, res);
EXPECT_EQ(cv::countNonZero(cv::abs(res - x) > epsilon(1, 2)), 0);
}
| 30.433824
| 93
| 0.636144
|
OlegZhavoronkov
|
7209c78d917330a56ef4ad047da24049bab203e5
| 7,107
|
cc
|
C++
|
virtual-machine/instructions.cc
|
AlexGustafsson/mjavac
|
6efbf8d77ba67760cff5ab87a3e858de769ac33e
|
[
"Unlicense"
] | null | null | null |
virtual-machine/instructions.cc
|
AlexGustafsson/mjavac
|
6efbf8d77ba67760cff5ab87a3e858de769ac33e
|
[
"Unlicense"
] | null | null | null |
virtual-machine/instructions.cc
|
AlexGustafsson/mjavac
|
6efbf8d77ba67760cff5ab87a3e858de769ac33e
|
[
"Unlicense"
] | 1
|
2021-08-19T02:56:28.000Z
|
2021-08-19T02:56:28.000Z
|
#include <iostream>
#include <list>
#include <tuple>
#include "instructions.hpp"
using namespace mjavac::vm;
Instruction_iload::Instruction_iload(std::string identifier)
: identifier(identifier) {
}
void Instruction_iload::perform(State *state) const {
state->stack.push(state->variables[this->identifier]);
state->instruction_pointer++;
}
void Instruction_iload::write(std::ostream &stream) const {
stream << "iload " << this->identifier << std::endl;
}
Instruction_iconst::Instruction_iconst(long value)
: value(value) {
}
void Instruction_iconst::perform(State *state) const {
state->stack.push(this->value);
state->instruction_pointer++;
}
void Instruction_iconst::write(std::ostream &stream) const {
stream << "iconst " << this->value << std::endl;
}
Instruction_istore::Instruction_istore(std::string identifier)
: identifier(identifier) {
}
void Instruction_istore::perform(State *state) const {
state->variables[this->identifier] = (int)state->stack.top();
state->stack.pop();
state->instruction_pointer++;
}
void Instruction_istore::write(std::ostream &stream) const {
stream << "istore " << this->identifier << std::endl;
}
Instruction_iadd::Instruction_iadd() {
}
void Instruction_iadd::perform(State *state) const {
int b = (int)state->stack.top();
state->stack.pop();
int a = (int)state->stack.top();
state->stack.pop();
state->stack.push(a + b);
state->instruction_pointer++;
}
void Instruction_iadd::write(std::ostream &stream) const {
stream << "iadd" << std::endl;
}
Instruction_isub::Instruction_isub() {
}
void Instruction_isub::perform(State *state) const {
int b = (int)state->stack.top();
state->stack.pop();
int a = (int)state->stack.top();
state->stack.pop();
state->stack.push(a - b);
state->instruction_pointer++;
}
void Instruction_isub::write(std::ostream &stream) const {
stream << "isub" << std::endl;
}
Instruction_imul::Instruction_imul() {
}
void Instruction_imul::perform(State *state) const {
int b = (int)state->stack.top();
state->stack.pop();
int a = (int)state->stack.top();
state->stack.pop();
state->stack.push(a * b);
state->instruction_pointer++;
}
void Instruction_imul::write(std::ostream &stream) const {
stream << "imul" << std::endl;
}
Instruction_idiv::Instruction_idiv() {
}
void Instruction_idiv::perform(State *state) const {
int b = (int)state->stack.top();
state->stack.pop();
int a = (int)state->stack.top();
state->stack.pop();
state->stack.push(a / b);
state->instruction_pointer++;
}
void Instruction_idiv::write(std::ostream &stream) const {
stream << "idiv" << std::endl;
}
Instruction_ilt::Instruction_ilt() {
}
void Instruction_ilt::perform(State *state) const {
int b = (int)state->stack.top();
state->stack.pop();
int a = (int)state->stack.top();
state->stack.pop();
state->stack.push(a < b ? 1 : 0);
state->instruction_pointer++;
}
void Instruction_ilt::write(std::ostream &stream) const {
stream << "ilt" << std::endl;
}
Instruction_iand::Instruction_iand() {
}
void Instruction_iand::perform(State *state) const {
int b = (int)state->stack.top();
state->stack.pop();
int a = (int)state->stack.top();
state->stack.pop();
state->stack.push(a * b == 0 ? 0 : 1);
state->instruction_pointer++;
}
void Instruction_iand::write(std::ostream &stream) const {
stream << "iand" << std::endl;
}
Instruction_ior::Instruction_ior() {
}
void Instruction_ior::perform(State *state) const {
int b = (int)state->stack.top();
state->stack.pop();
int a = (int)state->stack.top();
state->stack.pop();
state->stack.push(a + b == 0 ? 0 : 1);
state->instruction_pointer++;
}
void Instruction_ior::write(std::ostream &stream) const {
stream << "ior" << std::endl;
}
Instruction_inot::Instruction_inot() {
}
void Instruction_inot::perform(State *state) const {
int a = (int)state->stack.top();
state->stack.pop();
state->stack.push(a == 0 ? 1 : 0);
state->instruction_pointer++;
}
void Instruction_inot::write(std::ostream &stream) const {
stream << "inot" << std::endl;
}
Instruction_goto::Instruction_goto(long target)
: target(target) {
}
void Instruction_goto::perform(State *state) const {
state->current_block = std::to_string(this->target);
state->instruction_pointer = 0;
}
void Instruction_goto::write(std::ostream &stream) const {
stream << "goto " << this->target << std::endl;
}
Instruction_iffalse::Instruction_iffalse(long target)
: target(target) {
}
void Instruction_iffalse::perform(State *state) const {
int a = (int)state->stack.top();
state->stack.pop();
if (a == 0) {
state->current_block = std::to_string(this->target);
state->instruction_pointer = 0;
} else {
state->instruction_pointer++;
}
}
void Instruction_iffalse::write(std::ostream &stream) const {
stream << "iffalse " << this->target << std::endl;
}
Instruction_invokevirtual::Instruction_invokevirtual(std::string identifier)
: identifier(identifier) {
}
void Instruction_invokevirtual::perform(State *state) const {
// Push all the variables to the variable stack
state->variable_stack.push(state->variables);
state->variables.clear();
// Push the current call to the call stack
state->call_stack.push(std::tuple<std::string, long>(state->current_block, state->instruction_pointer));
// Change the target block
state->current_block = this->identifier;
state->instruction_pointer = 0;
// Pop the number of parameters passed, as it's not used
state->stack.pop();
}
void Instruction_invokevirtual::write(std::ostream &stream) const {
stream << "invokevirtual " << this->identifier << std::endl;
}
Instruction_ireturn::Instruction_ireturn() {
}
void Instruction_ireturn::perform(State *state) const {
// Pop all the variables from the variable stack
state->variables = state->variable_stack.top();
state->variable_stack.pop();
// Pop the previous call from the call stack
std::tuple<std::string, long> entry = state->call_stack.top();
// Change the target block
state->current_block = std::get<0>(entry);
state->instruction_pointer = std::get<1>(entry);
state->call_stack.pop();
// Increment the instruction pointer by one to move on
state->instruction_pointer++;
}
void Instruction_ireturn::write(std::ostream &stream) const {
stream << "ireturn" << std::endl;
}
Instruction_print::Instruction_print() {
}
void Instruction_print::perform(State *state) const {
int parameter_count = (int)state->stack.top();
state->stack.pop();
for (int i = 0; i < parameter_count; i++) {
int parameter = (int)state->stack.top();
state->stack.pop();
std::cout << parameter << std::endl;
}
state->instruction_pointer++;
}
void Instruction_print::write(std::ostream &stream) const {
stream << "print" << std::endl;
}
Instruction_stop::Instruction_stop() {
}
void Instruction_stop::perform(State *state) const {
// Will end as the block ends after this instruction
state->instruction_pointer++;
}
void Instruction_stop::write(std::ostream &stream) const {
stream << "stop" << std::endl;
}
| 25.024648
| 106
| 0.686647
|
AlexGustafsson
|
720bb2895a6c02e62838eab7e95643be1aa134eb
| 6,035
|
cc
|
C++
|
apis/ocpdiag/ocpdiag/core/results/internal/logging_test.cc
|
opencomputeproject/ocp-diag-core
|
37b83ff6f69684b435364000d26cd913eb6ff5f3
|
[
"Apache-2.0"
] | 10
|
2021-11-09T20:20:56.000Z
|
2022-03-25T11:59:14.000Z
|
apis/ocpdiag/ocpdiag/core/results/internal/logging_test.cc
|
opencomputeproject/ocp-diag-core
|
37b83ff6f69684b435364000d26cd913eb6ff5f3
|
[
"Apache-2.0"
] | 2
|
2022-02-10T21:27:33.000Z
|
2022-03-23T22:08:30.000Z
|
apis/ocpdiag/ocpdiag/core/results/internal/logging_test.cc
|
opencomputeproject/ocp-diag-core
|
37b83ff6f69684b435364000d26cd913eb6ff5f3
|
[
"Apache-2.0"
] | 1
|
2021-11-24T04:46:00.000Z
|
2021-11-24T04:46:00.000Z
|
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ocpdiag/core/results/internal/logging.h"
#include <stdio.h>
#include <unistd.h>
#include <array>
#include <future> //
#include <sstream>
#include <string>
#include <vector>
#include "google/protobuf/repeated_field.h"
#include "google/protobuf/util/json_util.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/status/status.h"
#include "absl/strings/match.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "ocpdiag/core/compat/status_converters.h"
#include "ocpdiag/core/results/internal/test_utils.h"
#include "ocpdiag/core/results/results.pb.h"
#include "ocpdiag/core/testing/proto_matchers.h"
#include "ocpdiag/core/testing/status_matchers.h"
namespace ocpdiag {
namespace results {
using internal::ArtifactWriter;
using internal::TestFile;
using ::ocpdiag::testing::EqualsProto;
using ::ocpdiag::testing::IsOkAndHolds;
using ::ocpdiag::testing::Partially;
using ::ocpdiag::testing::StatusIs;
using ::testing::Pointwise;
namespace {
namespace rpb = ::ocpdiag::results_pb;
TEST(OpenAndReturnDescriptor, ValidFilepath) {
EXPECT_OK(internal::OpenAndGetDescriptor("/dev/null"));
}
TEST(OpenAndReturnDescriptor, InvalidFilepath) {
EXPECT_THAT(internal::OpenAndGetDescriptor("invalid/"),
StatusIs(absl::StatusCode::kInternal));
}
TEST(OpenAndReturnDescriptor, EmptyString) {
EXPECT_THAT(internal::OpenAndGetDescriptor(""), IsOkAndHolds(-1));
}
// Manually confirms that artifact contents are as expected
TEST(ArtifactWriter, Simple) {
TestFile file;
std::stringstream json_stream;
{
ArtifactWriter writer(dup(fileno(file.ptr)), &json_stream);
rpb::OutputArtifact out_pb;
rpb::TestStepArtifact* step_pb = out_pb.mutable_test_step_artifact();
rpb::Diagnosis* diag = step_pb->mutable_diagnosis();
*diag->mutable_hardware_info_id()->Add() = "7";
diag->set_msg("test message");
diag->set_symptom("test symptom");
diag->set_type(rpb::Diagnosis::PASS);
step_pb->set_test_step_id("7");
writer.Write(out_pb);
} // writers fall out of scope and Flush/close file
// Convert human-readable JSON output back to message
rpb::OutputArtifact got;
auto status =
AsAbslStatus(google::protobuf::util::JsonStringToMessage(json_stream.str(), &got));
ASSERT_OK(status);
// Compare to what we expect (ignoring timestamp)
auto want = R"pb(
test_step_artifact {
diagnosis {
symptom: "test symptom"
type: PASS
msg: "test message"
hardware_info_id: "7"
}
test_step_id: "7"
}
sequence_number: 0
)pb";
EXPECT_THAT(got, Partially(testing::EqualsProto(want)));
}
//
TEST(ArtifactWriter, MultipleWritersInOrder) {
std::vector<rpb::OutputArtifact> wants;
std::vector<rpb::OutputArtifact> gots;
TestFile file;
std::stringstream json_stream;
{
ArtifactWriter writer1(dup(fileno(file.ptr)), &json_stream);
ArtifactWriter writer2 = writer1;
rpb::OutputArtifact out_pb;
rpb::TestStepArtifact* step_pb = out_pb.mutable_test_step_artifact();
rpb::Log* log_pb = step_pb->mutable_log();
step_pb->set_test_step_id("76");
log_pb->set_text("Hello, ");
writer1.Write(out_pb);
wants.push_back(out_pb);
log_pb->set_text("World!");
writer2.Write(out_pb);
wants.push_back(out_pb);
} // writers fall out of scope and Flush/close file
}
// Confirms that all newline '\n' characters are escaped '\\n'.
// And that all escaped newline '\\n' characters are ignored.
TEST(ArtifactWriter, replace_newlines) {
const std::string input = "escape this newline\n, but not this one\\n";
const std::string want = "escape this newline\\n, but not this one\\n";
std::stringstream json_stream;
{
ArtifactWriter writer(-1, &json_stream);
rpb::OutputArtifact out_pb;
out_pb.mutable_test_step_artifact()->mutable_log()->set_text(input);
writer.Write(out_pb);
} // writers fall out of scope and Flush/close file
rpb::OutputArtifact got;
auto status =
AsAbslStatus(google::protobuf::util::JsonStringToMessage(json_stream.str(), &got));
ASSERT_OK(status);
ASSERT_STREQ(got.test_step_artifact().log().text().c_str(), want.c_str());
}
// Confirms that artifact integrity is maintained with many asynchronous writes
TEST(ArtifactWriter, ThreadSafetyCheck) {
TestFile file;
const int writer_copies = 20;
const int artifact_count = 1000;
{
ArtifactWriter root_writer(dup(fileno(file.ptr)), nullptr);
std::array<ArtifactWriter, writer_copies> writers;
for (int i = 0; i < writer_copies; i++) {
writers[i] = root_writer;
}
std::vector<std::future<void>> threads;
for (auto& writer : writers) {
threads.push_back(std::async(std::launch::async, [&] {
for (int i = 0; i < artifact_count; i++) {
rpb::OutputArtifact out_pb;
writer.Write(out_pb);
}
}));
}
for (std::future<void>& thread : threads) {
thread.wait();
}
} // writers fall out of scope and Flush/close file
}
// Confirms that writer does not write after Close() and fails gracefully
TEST(ArtifactWriter, WriteFailAfterClose) {
TestFile file;
std::stringstream json;
ArtifactWriter writer(fileno(file.ptr), &json);
writer.Close();
rpb::OutputArtifact out_pb;
*out_pb.mutable_test_step_artifact() = rpb::TestStepArtifact();
writer.Write(out_pb);
}
} // namespace
} // namespace results
} // namespace ocpdiag
| 31.432292
| 89
| 0.708699
|
opencomputeproject
|
720c50dc8d59b9d1cfb7c087510ca8fb74d2d718
| 7,580
|
cpp
|
C++
|
level1/p11_linkedList/linkedList.cpp
|
shui12jiao/c2021
|
0a21392fe0c35cbebc04335d43e134410e17d89c
|
[
"MIT"
] | null | null | null |
level1/p11_linkedList/linkedList.cpp
|
shui12jiao/c2021
|
0a21392fe0c35cbebc04335d43e134410e17d89c
|
[
"MIT"
] | null | null | null |
level1/p11_linkedList/linkedList.cpp
|
shui12jiao/c2021
|
0a21392fe0c35cbebc04335d43e134410e17d89c
|
[
"MIT"
] | null | null | null |
#include <sstream>
#include "illegalParameter.h"
#include "linearList.h"
#include "linkedNode.h"
template <typename T>
class linkedList : public linearList<T> { //链表
public:
linkedList();
linkedList(const linkedList<T>&);
~linkedList();
bool empty() const { return listSize == 0; }
int size() const { return listSize; };
T& get(int theIndex) const;
int indexOf(const T& theElement, int theIndex = -1) const;
void erase(int theIndex);
void insert(int theIndex, const T& theElement);
void output(std::ostream& out) const;
void clear();
void push_back(const T& theElement);
void pop_back();
void set(int theIndex, const T& theElement);
void resize(int size, const T& theElement);
void reverse();
protected:
linkedNode<T>* firstNode;
linkedNode<T>* lastNode;
int listSize;
};
template <typename T>
linkedList<T>::linkedList() {
firstNode = nullptr;
lastNode = nullptr;
listSize = 0;
}
template <typename T>
linkedList<T>::linkedList(const linkedList<T>& theList) {
listSize = theList.listSize;
if (listSize == 0) {
linkedList();
return;
}
linkedNode<T>* sourceNode = theList.firstNode;
firstNode = new linkedNode<T>(sourceNode->element);
linkedNode<T>* currentNode = firstNode;
sourceNode = sourceNode->next;
while (sourceNode != nullptr) {
currentNode->next = new linkedNode<T>(sourceNode->element);
currentNode = currentNode->next;
sourceNode = sourceNode->next;
}
lastNode = currentNode;
lastNode->next = nullptr;
}
template <typename T>
linkedList<T>::~linkedList() {
linkedNode<T>* tempNode;
while (firstNode != nullptr) {
tempNode = firstNode->next;
delete firstNode;
firstNode = tempNode;
}
}
template <typename T>
T& linkedList<T>::get(int theIndex) const {
if (theIndex >= listSize || theIndex < 0) {
std::ostringstream s;
s << "获取失败 链表大小为" << listSize << " 输入Index为" << theIndex << std::endl;
throw illegalParameter(s.str());
}
linkedNode<T>* currentNode = firstNode;
for (int i = 0; i < theIndex; ++i) {
currentNode = currentNode->next;
}
return currentNode->element;
}
template <typename T>
int linkedList<T>::indexOf(const T& theElement, int theIndex) const {
if (theIndex >= listSize - 1 || theIndex < -1) {
return -1;
}
linkedNode<T>* currentNode = firstNode;
int index = theIndex + 1;
for (int i = -1; i < theIndex; ++i) {
currentNode = currentNode->next;
}
while (currentNode != nullptr && currentNode->element != theElement) {
++index;
currentNode = currentNode->next;
}
if (currentNode == nullptr) {
return -1;
}
return index;
}
template <typename T>
void linkedList<T>::erase(int theIndex) {
if (theIndex >= listSize || theIndex < 0) {
std::ostringstream s;
s << "删除失败 链表大小为" << listSize << " 输入Index为" << theIndex << std::endl;
throw illegalParameter(s.str());
}
linkedNode<T>* deleteNode;
if (theIndex == 0) {
deleteNode = firstNode;
firstNode = firstNode->next;
} else {
linkedNode<T>* preNode = firstNode;
for (int i = 1; i < theIndex; ++i) {
preNode = preNode->next;
}
deleteNode = preNode->next;
preNode->next = deleteNode->next;
if (deleteNode == lastNode) lastNode = preNode;
}
delete deleteNode;
--listSize;
}
template <typename T>
void linkedList<T>::insert(int theIndex, const T& theElement) {
if (theIndex > listSize || theIndex < 0) {
std::ostringstream s;
s << "插入失败 链表大小为" << listSize << " 输入Index为" << theIndex << std::endl;
throw illegalParameter(s.str());
}
if (theIndex == 0) {
firstNode = new linkedNode<T>(theElement, firstNode);
if (listSize == 0) {
lastNode = firstNode;
}
} else {
linkedNode<T>* preNode = firstNode;
for (int i = 1; i < theIndex; ++i) {
preNode = preNode->next;
}
preNode->next = new linkedNode<T>(theElement, preNode->next);
if (listSize == theIndex) {
lastNode = preNode->next;
}
}
++listSize;
}
template <typename T>
void linkedList<T>::output(std::ostream& out) const {
for (linkedNode<T>* currentNode = firstNode; currentNode != nullptr; currentNode = currentNode->next) {
out << currentNode->element << ' ';
}
}
template <typename T>
void linkedList<T>::clear() {
linkedNode<T>* tempNode = firstNode;
while (firstNode != nullptr) {
tempNode = firstNode->next;
delete firstNode;
firstNode = tempNode;
}
listSize = 0;
}
template <typename T>
void linkedList<T>::push_back(const T& theElement) {
linkedNode<T>* newNode = new linkedNode<T>(theElement, nullptr);
if (listSize == 0) {
firstNode = newNode;
lastNode = newNode;
} else {
lastNode->next = newNode;
lastNode = newNode;
}
++listSize;
}
template <typename T>
void linkedList<T>::pop_back() {
if (listSize == 0) {
std::cerr << "链表为空" << std::endl;
return;
} else if (listSize == 1) {
delete firstNode;
firstNode = nullptr;
lastNode = nullptr;
} else {
linkedNode<T>* preNode = firstNode;
for (int i = 2; i < listSize; ++i) {
preNode = preNode->next;
}
delete lastNode;
preNode->next = nullptr;
lastNode = preNode;
}
--listSize;
}
template <typename T>
std::ostream& operator<<(std::ostream& out, const linkedList<T>& l) {
l.output(out);
return out;
}
template <typename T>
void linkedList<T>::set(int theIndex, const T& theElement) {
if (theIndex >= listSize || theIndex < 0) {
std::cerr << "更改失败 链表大小为" << listSize << " 输入Index为" << theIndex << std::endl;
return;
}
linkedNode<T>* currentNode = firstNode;
for (int i = 0; i < theIndex; ++i) {
currentNode = currentNode->next;
}
currentNode->element = theElement;
}
template <typename T>
void linkedList<T>::resize(int size, const T& theElement) {
if (size < 0) {
std::ostringstream s;
s << "失败 大小为" << listSize << " 输入Size为" << size << std::endl;
throw illegalParameter(s.str());
} else if (size < listSize) {
while (size < listSize) {
pop_back();
}
} else if (size > listSize) {
while (size > listSize) {
push_back(theElement);
}
} else {
return;
}
}
template <typename T>
void linkedList<T>::reverse() {
lastNode = firstNode;
linkedNode<T>* tempNode = nullptr;
linkedNode<T>* nextNode = nullptr;
while (firstNode != nullptr) {
nextNode = firstNode->next;
firstNode->next = tempNode;
tempNode = firstNode;
firstNode = nextNode;
}
firstNode = tempNode;
}
int main() {
linkedList<int> l;
for (int i = 1; i <= 10; ++i) l.push_back(i);
l.set(9, 5);
linkedList<int> list(l);
std::cout << list << std::endl;
list.reverse();
std::cout << list << std::endl;
int i1 = list.indexOf(5);
int i2 = list.indexOf(5, i1);
int i3 = list.indexOf(5, i2);
std::cout << "节点序号从0开始" << std::endl;
std::cout << "数字5第一次出现节点序号:" << i1 << std::endl;
std::cout << "数字5第一次出现节点序号:" << i2 << std::endl;
std::cout << "数字5第一次出现节点序号:" << i3 << std::endl;
return 0;
}
| 26.784452
| 107
| 0.581003
|
shui12jiao
|
720e527a45f234e6add1ca37bbf847a70b75d5fc
| 1,617
|
cpp
|
C++
|
src/lib/Mutex.cpp
|
romoadri21/boi
|
deef8e7148b50fbb36886ba4ff491a6c0e18ad67
|
[
"BSD-3-Clause"
] | null | null | null |
src/lib/Mutex.cpp
|
romoadri21/boi
|
deef8e7148b50fbb36886ba4ff491a6c0e18ad67
|
[
"BSD-3-Clause"
] | null | null | null |
src/lib/Mutex.cpp
|
romoadri21/boi
|
deef8e7148b50fbb36886ba4ff491a6c0e18ad67
|
[
"BSD-3-Clause"
] | null | null | null |
/* Copyright (c) 2010, Piet Hein Schouten. All rights reserved.
* This code is licensed under a BSD-style license that can be
* found in the LICENSE file. The license can also be found at:
* http://www.boi-project.org/license
*/
#include <QMutex>
#include <QWaitCondition>
#include "ThreadLockData.h"
#include "MutexBase.h"
#include "Mutex.h"
namespace BOI {
Mutex::Mutex()
: m_numAccessors(0),
m_doWait(true),
m_pHead(NULL),
m_pTail(NULL),
m_pMutex(NULL),
m_pBase(NULL)
{
}
void Mutex::Lock()
{
if (m_numAccessors.fetchAndAddAcquire(1) != 0)
{
m_pMutex->lock();
if (m_doWait || (m_pHead != NULL))
{
ThreadLockData* pThreadLockData = m_pBase->GetData();
pThreadLockData->pNext = NULL;
/*
* Enqueue the thread.
*/
if (m_pHead == NULL)
{
m_pHead = pThreadLockData;
}
else
{
m_pTail->pNext = pThreadLockData;
}
m_pTail = pThreadLockData;
pThreadLockData->waitCondition.wait(m_pMutex);
/*
* Dequeue thread.
*/
m_pHead = m_pHead->pNext;
}
m_doWait = true;
m_pMutex->unlock();
}
}
void Mutex::Unlock()
{
if (m_numAccessors.fetchAndAddRelease(-1) != 1)
{
m_pMutex->lock();
m_doWait = false;
if (m_pHead != NULL)
{
m_pHead->waitCondition.wakeOne();
}
m_pMutex->unlock();
}
}
} // namespace BOI
| 18.586207
| 65
| 0.520717
|
romoadri21
|
72116306bdcb5a850237fd09e64692faddd4be31
| 299
|
cpp
|
C++
|
code/hackerrank/left rotation.cpp
|
Codernob/problem-solving-codes
|
c852bae4e31887bd442d70af921348c8f1d246bf
|
[
"MIT"
] | null | null | null |
code/hackerrank/left rotation.cpp
|
Codernob/problem-solving-codes
|
c852bae4e31887bd442d70af921348c8f1d246bf
|
[
"MIT"
] | null | null | null |
code/hackerrank/left rotation.cpp
|
Codernob/problem-solving-codes
|
c852bae4e31887bd442d70af921348c8f1d246bf
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
void lr(int a[],int n) {
int temp=a[0];
for(int i=0;i<n-1;i++) a[i]=a[i+1];
a[n-1]=temp;
}
int main() {
int n,d;
cin>>n/*>>d*/;
int a[n];
for(int i=0;i<n;i++) cin>>a[i];
/*for(int i=1;i<=d;i++)*/ lr(a,n);
for(int i=0;i<n;i++) cout<<a[i]<<" ";
return 0;
}
| 18.6875
| 38
| 0.521739
|
Codernob
|
72127937d14cdbfedbe5d1c95ae94d20942522bf
| 664
|
hpp
|
C++
|
include/simple_math/vec.hpp
|
signekatt/simple_math
|
aa17f449330a2dd38a10222074c1139fdbdeeb75
|
[
"MIT"
] | null | null | null |
include/simple_math/vec.hpp
|
signekatt/simple_math
|
aa17f449330a2dd38a10222074c1139fdbdeeb75
|
[
"MIT"
] | null | null | null |
include/simple_math/vec.hpp
|
signekatt/simple_math
|
aa17f449330a2dd38a10222074c1139fdbdeeb75
|
[
"MIT"
] | null | null | null |
// Copyright(c) 2019-present, Anton Lilja.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
#include "vec2.hpp"
#include "vec3.hpp"
#include "vec4.hpp"
namespace sm {
// Other op funcs
template <typename V>
inline V inverse(const V& v) {
return v.inverse();
}
template <typename V>
inline float magnitude(const V& v) {
return v.magnitude();
}
template <typename V>
inline float square_magnitude(const V& v) {
return v.square_magnitude();
}
template <typename V>
inline V normalize(const V& v) {
return v.normalize();
}
} // namespace sm
| 21.419355
| 73
| 0.626506
|
signekatt
|
721c2de3ada7099eceea094e17c91fb0912c52f8
| 4,875
|
cpp
|
C++
|
modules/dasClangBind/src/dasClangBind.func_3.cpp
|
profelis/daScript
|
eea57f39dec4dd6168ee64c8ae5139cbcf2937bc
|
[
"BSD-3-Clause"
] | 421
|
2019-08-15T15:40:04.000Z
|
2022-03-29T06:59:06.000Z
|
modules/dasClangBind/src/dasClangBind.func_3.cpp
|
profelis/daScript
|
eea57f39dec4dd6168ee64c8ae5139cbcf2937bc
|
[
"BSD-3-Clause"
] | 55
|
2019-08-17T13:50:53.000Z
|
2022-03-25T17:58:38.000Z
|
modules/dasClangBind/src/dasClangBind.func_3.cpp
|
profelis/daScript
|
eea57f39dec4dd6168ee64c8ae5139cbcf2937bc
|
[
"BSD-3-Clause"
] | 58
|
2019-08-22T17:04:13.000Z
|
2022-03-25T17:43:28.000Z
|
// this file is generated via daScript automatic C++ binder
// all user modifications will be lost after this file is re-generated
#include "daScript/misc/platform.h"
#include "daScript/ast/ast.h"
#include "daScript/ast/ast_interop.h"
#include "daScript/ast/ast_handle.h"
#include "daScript/ast/ast_typefactory_bind.h"
#include "daScript/simulate/bind_enum.h"
#include "dasClangBind.h"
#include "need_dasClangBind.h"
namespace das {
void Module_dasClangBind::initFunctions_3() {
addExtern< void * (*)(void *) , clang_getChildDiagnostics >(*this,lib,"clang_getChildDiagnostics",SideEffects::worstDefault,"clang_getChildDiagnostics")
->args({"D"});
addExtern< unsigned int (*)(CXTranslationUnitImpl *) , clang_getNumDiagnostics >(*this,lib,"clang_getNumDiagnostics",SideEffects::worstDefault,"clang_getNumDiagnostics")
->args({"Unit"});
addExtern< void * (*)(CXTranslationUnitImpl *,unsigned int) , clang_getDiagnostic >(*this,lib,"clang_getDiagnostic",SideEffects::worstDefault,"clang_getDiagnostic")
->args({"Unit","Index"});
addExtern< void * (*)(CXTranslationUnitImpl *) , clang_getDiagnosticSetFromTU >(*this,lib,"clang_getDiagnosticSetFromTU",SideEffects::worstDefault,"clang_getDiagnosticSetFromTU")
->args({"Unit"});
addExtern< void (*)(void *) , clang_disposeDiagnostic >(*this,lib,"clang_disposeDiagnostic",SideEffects::worstDefault,"clang_disposeDiagnostic")
->args({"Diagnostic"});
addExtern< CXString (*)(void *,unsigned int) , clang_formatDiagnostic ,SimNode_ExtFuncCallAndCopyOrMove>(*this,lib,"clang_formatDiagnostic",SideEffects::worstDefault,"clang_formatDiagnostic")
->args({"Diagnostic","Options"});
addExtern< unsigned int (*)() , clang_defaultDiagnosticDisplayOptions >(*this,lib,"clang_defaultDiagnosticDisplayOptions",SideEffects::worstDefault,"clang_defaultDiagnosticDisplayOptions");
addExtern< CXDiagnosticSeverity (*)(void *) , clang_getDiagnosticSeverity >(*this,lib,"clang_getDiagnosticSeverity",SideEffects::worstDefault,"clang_getDiagnosticSeverity")
->args({""});
addExtern< CXSourceLocation (*)(void *) , clang_getDiagnosticLocation ,SimNode_ExtFuncCallAndCopyOrMove>(*this,lib,"clang_getDiagnosticLocation",SideEffects::worstDefault,"clang_getDiagnosticLocation")
->args({""});
addExtern< CXString (*)(void *) , clang_getDiagnosticSpelling ,SimNode_ExtFuncCallAndCopyOrMove>(*this,lib,"clang_getDiagnosticSpelling",SideEffects::worstDefault,"clang_getDiagnosticSpelling")
->args({""});
addExtern< CXString (*)(void *,CXString *) , clang_getDiagnosticOption ,SimNode_ExtFuncCallAndCopyOrMove>(*this,lib,"clang_getDiagnosticOption",SideEffects::worstDefault,"clang_getDiagnosticOption")
->args({"Diag","Disable"});
addExtern< unsigned int (*)(void *) , clang_getDiagnosticCategory >(*this,lib,"clang_getDiagnosticCategory",SideEffects::worstDefault,"clang_getDiagnosticCategory")
->args({""});
addExtern< CXString (*)(unsigned int) , clang_getDiagnosticCategoryName ,SimNode_ExtFuncCallAndCopyOrMove>(*this,lib,"clang_getDiagnosticCategoryName",SideEffects::worstDefault,"clang_getDiagnosticCategoryName")
->args({"Category"});
addExtern< CXString (*)(void *) , clang_getDiagnosticCategoryText ,SimNode_ExtFuncCallAndCopyOrMove>(*this,lib,"clang_getDiagnosticCategoryText",SideEffects::worstDefault,"clang_getDiagnosticCategoryText")
->args({""});
addExtern< unsigned int (*)(void *) , clang_getDiagnosticNumRanges >(*this,lib,"clang_getDiagnosticNumRanges",SideEffects::worstDefault,"clang_getDiagnosticNumRanges")
->args({""});
addExtern< CXSourceRange (*)(void *,unsigned int) , clang_getDiagnosticRange ,SimNode_ExtFuncCallAndCopyOrMove>(*this,lib,"clang_getDiagnosticRange",SideEffects::worstDefault,"clang_getDiagnosticRange")
->args({"Diagnostic","Range"});
addExtern< unsigned int (*)(void *) , clang_getDiagnosticNumFixIts >(*this,lib,"clang_getDiagnosticNumFixIts",SideEffects::worstDefault,"clang_getDiagnosticNumFixIts")
->args({"Diagnostic"});
addExtern< CXString (*)(void *,unsigned int,CXSourceRange *) , clang_getDiagnosticFixIt ,SimNode_ExtFuncCallAndCopyOrMove>(*this,lib,"clang_getDiagnosticFixIt",SideEffects::worstDefault,"clang_getDiagnosticFixIt")
->args({"Diagnostic","FixIt","ReplacementRange"});
addExtern< CXString (*)(CXTranslationUnitImpl *) , clang_getTranslationUnitSpelling ,SimNode_ExtFuncCallAndCopyOrMove>(*this,lib,"clang_getTranslationUnitSpelling",SideEffects::worstDefault,"clang_getTranslationUnitSpelling")
->args({"CTUnit"});
addExtern< CXTranslationUnitImpl * (*)(void *,const char *,int,const char *const *,unsigned int,CXUnsavedFile *) , clang_createTranslationUnitFromSourceFile >(*this,lib,"clang_createTranslationUnitFromSourceFile",SideEffects::worstDefault,"clang_createTranslationUnitFromSourceFile")
->args({"CIdx","source_filename","num_clang_command_line_args","clang_command_line_args","num_unsaved_files","unsaved_files"});
}
}
| 87.053571
| 284
| 0.791179
|
profelis
|
721f63b1042c4020bc953e493fbecf874d6fdb7c
| 3,585
|
cpp
|
C++
|
test/unit_tests/02_lock_acquire_release/test.cpp
|
stephenneuendorffer/mlir-aie
|
c95e5f4996f5490759705de63820adcf373444e6
|
[
"Apache-2.0"
] | 67
|
2021-08-29T04:47:56.000Z
|
2022-03-29T05:38:32.000Z
|
test/unit_tests/02_lock_acquire_release/test.cpp
|
pssrawat/mlir-aie
|
b3f29a6344b70c6730d7ce0485b7bda54f3277dc
|
[
"Apache-2.0"
] | 45
|
2021-09-02T21:35:59.000Z
|
2022-03-18T10:07:25.000Z
|
test/unit_tests/02_lock_acquire_release/test.cpp
|
hanchenye/mlir-aie
|
8027f07c8d58afc11c25aab743fbcb901dac2ae6
|
[
"Apache-2.0"
] | 26
|
2021-08-29T17:38:33.000Z
|
2022-03-29T23:25:05.000Z
|
//===- test.cpp -------------------------------------------------*- C++ -*-===//
//
// This file is licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
// (c) Copyright 2020 Xilinx Inc.
//
//===----------------------------------------------------------------------===//
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <thread>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <xaiengine.h>
#include "test_library.h"
#define HIGH_ADDR(addr) ((addr & 0xffffffff00000000) >> 32)
#define LOW_ADDR(addr) (addr & 0x00000000ffffffff)
#define mlir_aie_STACK_OFFSET 4096
#include "aie_inc.cpp"
int
main(int argc, char *argv[])
{
printf("test start.\n");
aie_libxaie_ctx_t *_xaie = mlir_aie_init_libxaie();
mlir_aie_init_device(_xaie);
mlir_aie_configure_cores(_xaie);
mlir_aie_configure_switchboxes(_xaie);
mlir_aie_initialize_locks(_xaie);
mlir_aie_configure_dmas(_xaie);
//XAieLib_usleep(1000);
int errors = 0;
// XAieTile_LockRelease(&(TileInst[j][i]), l, val, timeout)
// XAIeTile_LockAcquire(&(TileInst[j][i]), l, val, timeout)
//
mlir_aie_acquire_lock(_xaie, 1, 3, 3, 0, 0);
usleep(1000);
u32 l = mlir_aie_read32(_xaie,
mlir_aie_get_tile_addr(_xaie, 3, 1) + 0x0001EF00);
u32 s = (l >> 6) & 0x3;
printf("Lock acquire 3: 0 is %x\n",s);
mlir_aie_acquire_lock(_xaie, 1, 3, 5, 0, 0);
usleep(1000);
l = mlir_aie_read32(_xaie,
mlir_aie_get_tile_addr(_xaie, 3, 1) + 0x0001EF00);
s = (l >> 10) & 0x3;
printf("Lock acquire 5: 0 is %x\n",s);
mlir_aie_release_lock(_xaie, 1, 3, 5, 1, 0);
usleep(1000);
l = mlir_aie_read32(_xaie,
mlir_aie_get_tile_addr(_xaie, 3, 1) + 0x0001EF00);
s = (l >> 10) & 0x3;
printf("Lock release 5: 0 is %x\n",s);
u32 locks = mlir_aie_read32(_xaie, mlir_aie_get_tile_addr(_xaie, 3, 1) +
0x0001EF00);
for (int lock=0;lock<16;lock++) {
u32 two_bits = (locks >> (lock*2)) & 0x3;
if (two_bits) {
printf("Lock %d: ", lock);
u32 acquired = two_bits & 0x1;
u32 value = two_bits & 0x2;
if (acquired)
printf("Acquired ");
printf(value?"1":"0");
printf("\n");
if(((lock == 3) && (acquired != 1)) || ((lock == 5) && (acquired != 0) && (value != 0)))
errors++;
}
}
mlir_aie_configure_cores(_xaie);
mlir_aie_start_cores(_xaie);
usleep(1000);
locks = mlir_aie_read32(_xaie,
mlir_aie_get_tile_addr(_xaie, 3, 1) + 0x0001EF00);
for (int lock=0;lock<16;lock++) {
u32 two_bits = (locks >> (lock*2)) & 0x3;
if (two_bits) {
printf("Lock %d: ", lock);
u32 acquired = two_bits & 0x1;
u32 value = two_bits & 0x2;
if (acquired)
printf("Acquired ");
printf(value?"1":"0");
printf("\n");
if(((lock == 3) && (acquired != 1)) || ((lock == 5) && (acquired != 0) && (value != 0)))
errors++;
}
}
int res = 0;
if (!errors) {
printf("PASS!\n");
res = 0;
} else {
printf("Fail!\n");
res = -1;
}
mlir_aie_deinit_libxaie(_xaie);
printf("test done.\n");
return res;
}
| 30.12605
| 100
| 0.530544
|
stephenneuendorffer
|
7220274c2f0659c42f463ff7829710cef92ef67a
| 2,359
|
cpp
|
C++
|
ojcpp/leetcode/000/001_e_twosum.cpp
|
softarts/oj
|
2f51f360a7a6c49e865461755aec2f3a7e721b9e
|
[
"Apache-2.0"
] | 3
|
2019-05-04T03:26:02.000Z
|
2019-08-29T01:20:44.000Z
|
ojcpp/leetcode/000/001_e_twosum.cpp
|
softarts/oj
|
2f51f360a7a6c49e865461755aec2f3a7e721b9e
|
[
"Apache-2.0"
] | null | null | null |
ojcpp/leetcode/000/001_e_twosum.cpp
|
softarts/oj
|
2f51f360a7a6c49e865461755aec2f3a7e721b9e
|
[
"Apache-2.0"
] | null | null | null |
/*
https://leetcode.com/problems/two-sum/
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
思路
在one pass中,每个element-target=value,看看value是否已存在于hash map中
*/
#include <codech/codech_def.h>
using namespace CODECH;
using namespace std;
/*
vector<int> twoSum(vector<int>& nums, int target) {
std::unordered_set<int> sets;
vector<int> ret;
std::copy(nums.begin(), nums.end(), inserter(sets,sets.begin()));
for (int i = 0; i < nums.size(); i++)
{
int key = target - nums[i];
if (key == nums[i])
continue;
auto found = sets.find(key);
if (found != sets.end())
{
ret.push_back(i);
}
}
return ret;
}
*/
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
std::unordered_map<int,int> maps;
vector<int> ret;
for (int i = 0; i < nums.size(); i++)
{
int key = target - nums[i];
auto found = maps.find(nums[i]);
if (found == maps.end())
{
maps.insert(std::make_pair(key,i));
}
else
{
ret.push_back(found->second);
ret.push_back(i);
break;
}
}
return ret;
}
};
/*
vector<int> twoSum(vector<int>& nums, int target) {
std::unordered_map<int,int> maps;
vector<int> ret;
for (int i = 0; i < nums.size(); i++)
{
int key = target - nums[i];
auto found = maps.find(key);
if (found == maps.end())
{
maps.insert(std::make_pair(nums[i],i));
}
else
{
ret.push_back(found->second);
ret.push_back(i);
break;
}
}
return ret;
}
void printResult(const vector<int>& ret)
{
for_each(ret.begin(), ret.end(),
[](int elem)
{
cout << elem << " ";
}
);
std::cout << std::endl;
}
*/
DEFINE_CODE_TEST(001_twosum)
{
// vector<int> ret;
// vector<int> test1 = { 2, 7, 11, 15 };
// printResult(twoSum(test1, 9));
// vector<int> test2 = { 3,2,4 };
// printResult(twoSum(test2, 6));
vector<int> test1 = { 2, 7, 11, 15 };
Solution obj;
VERIFY_CASE(PRINT_VEC(obj.twoSum(test1, 9)),"0 1");
}
| 21.445455
| 69
| 0.492158
|
softarts
|
72212be3fd2dd2fadb93b6595d42cb3cfec9fad0
| 5,065
|
cpp
|
C++
|
util/qtColorScheme.cpp
|
Kitware/qtextensions
|
0ff5b486f08435c8cdfbc9f05d2f104f63b16aed
|
[
"BSD-3-Clause"
] | 19
|
2015-12-17T14:48:11.000Z
|
2021-11-26T13:43:40.000Z
|
util/qtColorScheme.cpp
|
Kitware/qtextensions
|
0ff5b486f08435c8cdfbc9f05d2f104f63b16aed
|
[
"BSD-3-Clause"
] | 26
|
2015-11-16T21:34:23.000Z
|
2021-01-29T13:41:21.000Z
|
util/qtColorScheme.cpp
|
Kitware/qtextensions
|
0ff5b486f08435c8cdfbc9f05d2f104f63b16aed
|
[
"BSD-3-Clause"
] | 13
|
2015-11-10T02:44:47.000Z
|
2020-11-16T06:07:21.000Z
|
// This file is part of qtExtensions, and is distributed under the
// OSI-approved BSD 3-Clause License. See top-level LICENSE file or
// https://github.com/Kitware/qtExtensions/blob/master/LICENSE for details.
#include "qtColorScheme.h"
#include <QSettings>
#define ARGS(x) QPalette::x, #x
//-----------------------------------------------------------------------------
qtColorScheme::qtColorScheme()
{
}
//-----------------------------------------------------------------------------
void qtColorScheme::load(const QSettings& settings)
{
this->load(ARGS(Active), settings);
this->load(ARGS(Inactive), settings);
this->load(ARGS(Disabled), settings);
}
//-----------------------------------------------------------------------------
void qtColorScheme::load(QPalette::ColorGroup group, const QString& groupName,
QSettings const& settings)
{
this->load(group, groupName, ARGS(Base), settings);
this->load(group, groupName, ARGS(Text), settings);
#if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)
this->load(group, groupName, ARGS(PlaceholderText), settings);
#endif
this->load(group, groupName, ARGS(AlternateBase), settings);
this->load(group, groupName, ARGS(Window), settings);
this->load(group, groupName, ARGS(WindowText), settings);
this->load(group, groupName, ARGS(Button), settings);
this->load(group, groupName, ARGS(ButtonText), settings);
this->load(group, groupName, ARGS(Highlight), settings);
this->load(group, groupName, ARGS(HighlightedText), settings);
this->load(group, groupName, ARGS(ToolTipBase), settings);
this->load(group, groupName, ARGS(ToolTipText), settings);
this->load(group, groupName, ARGS(Link), settings);
this->load(group, groupName, ARGS(LinkVisited), settings);
this->load(group, groupName, ARGS(BrightText), settings);
this->load(group, groupName, ARGS(Light), settings);
this->load(group, groupName, ARGS(Midlight), settings);
this->load(group, groupName, ARGS(Mid), settings);
this->load(group, groupName, ARGS(Dark), settings);
this->load(group, groupName, ARGS(Shadow), settings);
}
//-----------------------------------------------------------------------------
void qtColorScheme::load(QPalette::ColorGroup group, const QString& groupName,
QPalette::ColorRole role, const QString& roleName,
const QSettings& settings)
{
auto const& color = settings.value(this->key(groupName, roleName));
if (color.isValid())
{
this->setColor(group, role, QColor{color.toString()});
}
}
//-----------------------------------------------------------------------------
void qtColorScheme::save(QSettings& settings) const
{
this->save(ARGS(Active), settings);
this->save(ARGS(Inactive), settings);
this->save(ARGS(Disabled), settings);
}
//-----------------------------------------------------------------------------
void qtColorScheme::save(QPalette::ColorGroup group, const QString& groupName,
QSettings& settings) const
{
this->save(group, groupName, ARGS(Base), settings);
this->save(group, groupName, ARGS(Text), settings);
#if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)
this->save(group, groupName, ARGS(PlaceholderText), settings);
#endif
this->save(group, groupName, ARGS(AlternateBase), settings);
this->save(group, groupName, ARGS(Window), settings);
this->save(group, groupName, ARGS(WindowText), settings);
this->save(group, groupName, ARGS(Button), settings);
this->save(group, groupName, ARGS(ButtonText), settings);
this->save(group, groupName, ARGS(Highlight), settings);
this->save(group, groupName, ARGS(HighlightedText), settings);
this->save(group, groupName, ARGS(ToolTipBase), settings);
this->save(group, groupName, ARGS(ToolTipText), settings);
this->save(group, groupName, ARGS(Link), settings);
this->save(group, groupName, ARGS(LinkVisited), settings);
this->save(group, groupName, ARGS(BrightText), settings);
this->save(group, groupName, ARGS(Light), settings);
this->save(group, groupName, ARGS(Midlight), settings);
this->save(group, groupName, ARGS(Mid), settings);
this->save(group, groupName, ARGS(Dark), settings);
this->save(group, groupName, ARGS(Shadow), settings);
}
//-----------------------------------------------------------------------------
void qtColorScheme::save(QPalette::ColorGroup group, const QString& groupName,
QPalette::ColorRole role, const QString& roleName,
QSettings& settings) const
{
settings.setValue(this->key(groupName, roleName),
this->color(group, role).name());
}
//-----------------------------------------------------------------------------
QString qtColorScheme::key(const QString& group, const QString& role) const
{
return QString{"%1/%2"}.arg(group, role);
}
//-----------------------------------------------------------------------------
qtColorScheme qtColorScheme::fromSettings(const QSettings& settings)
{
qtColorScheme scheme;
scheme.load(settings);
return scheme;
}
| 41.516393
| 79
| 0.603356
|
Kitware
|
722310472f4f466485792343c31670010863c197
| 11,228
|
hpp
|
C++
|
tcob/include/tcob/core/Automation.hpp
|
TobiasBohnen/tcob
|
53092b3c8e657f1ff5e48ce961659edf7cb1cb05
|
[
"MIT"
] | 2
|
2021-08-18T19:14:35.000Z
|
2021-12-01T14:14:49.000Z
|
tcob/include/tcob/core/Automation.hpp
|
TobiasBohnen/tcob
|
53092b3c8e657f1ff5e48ce961659edf7cb1cb05
|
[
"MIT"
] | null | null | null |
tcob/include/tcob/core/Automation.hpp
|
TobiasBohnen/tcob
|
53092b3c8e657f1ff5e48ce961659edf7cb1cb05
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2021 Tobias Bohnen
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
#pragma once
#include <tcob/tcob_config.hpp>
#include <concepts>
#include <queue>
#include <vector>
#include <tcob/core/Random.hpp>
#include <tcob/core/Signal.hpp>
#include <tcob/core/Updatable.hpp>
#include <tcob/core/data/Color.hpp>
#include <tcob/core/data/Point.hpp>
#include <tcob/gfx/Quad.hpp>
namespace tcob {
////////////////////////////////////////////////////////////
template <typename T>
concept AutomationFunction = requires(T& t, f32 elapsedRatio)
{
typename T::type;
{
t.get_value(elapsedRatio)
} -> std::same_as<typename T::type>;
};
////////////////////////////////////////////////////////////
template <typename T>
concept Interpolatable = requires(T& t, f32 elapsedRatio)
{
{
t.get_interpolated(t, elapsedRatio)
} -> std::same_as<T>;
};
////////////////////////////////////////////////////////////
class AutomationBase : public Updatable {
public:
explicit AutomationBase(MilliSeconds duration);
virtual ~AutomationBase() = default;
void start(bool looped = false);
void restart();
void toggle_pause();
void stop();
void set_interval(MilliSeconds interval);
auto is_running() const -> bool;
auto get_progress() const -> f32;
void update(MilliSeconds deltaTime) override;
private:
virtual void update_values() = 0;
bool _isRunning { false };
bool _looped { false };
MilliSeconds _duration { 0 };
MilliSeconds _elapsedTime { 0 };
MilliSeconds _interval { 0 };
MilliSeconds _currentInterval { 0 };
};
////////////////////////////////////////////////////////////
template <AutomationFunction Func>
class Automation final : public AutomationBase {
using func_type = typename Func::type;
public:
Automation(MilliSeconds duration, Func&& ptr)
: AutomationBase { duration }
, _function { std::move(ptr) }
{
}
Signal<func_type> ValueChanged;
auto add_output(func_type* dest) -> Connection
{
return ValueChanged.connect([dest](const func_type& val) { *dest = val; });
}
auto get_value() const -> func_type
{
return _function.get_value(get_progress());
}
private:
void update_values() override
{
ValueChanged.emit(get_value());
}
Func _function;
};
template <typename Func, typename... Rs>
auto make_unique_automation(MilliSeconds duration, Rs&&... args) -> std::unique_ptr<Automation<Func>>
{
return std::unique_ptr<Automation<Func>>(new Automation<Func> { duration, Func { std::forward<Rs>(args)... } });
}
template <typename Func, typename... Rs>
auto make_shared_automation(MilliSeconds duration, Rs&&... args) -> std::shared_ptr<Automation<Func>>
{
return std::shared_ptr<Automation<Func>>(new Automation<Func> { duration, Func { std::forward<Rs>(args)... } });
}
////////////////////////////////////////////////////////////
class AutomationQueue final : public Updatable {
public:
template <typename... Ts>
void push(Ts&&... autom)
{
(_queue.push(std::forward<Ts>(autom)), ...);
}
void start(bool looped = false);
void stop_and_clear();
auto is_empty() const -> bool;
void update(MilliSeconds deltaTime) override;
private:
std::queue<std::shared_ptr<AutomationBase>> _queue {};
bool _isRunning { false };
bool _looped { false };
};
/////////FUNCTIONS//////////////////////////////////////////
template <typename T>
class LinearFunctionChain final {
public:
using type = T;
LinearFunctionChain(std::vector<T>&& elements)
: _elements { std::move(elements) }
{
}
auto get_value(f32 elapsedRatio) const -> T
{
if (_elements.empty()) {
return T {};
}
const isize size { _elements.size() - 1 };
const f32 relElapsed { size * elapsedRatio };
const isize index { static_cast<isize>(relElapsed) };
if (index >= size) {
return _elements[index];
} else {
const T& current { _elements[index] };
const T& next { _elements[index + 1] };
if constexpr (Interpolatable<T>) {
return current.get_interpolated(next, relElapsed - index);
} else {
return current + ((next - current) * (relElapsed - index));
}
}
}
private:
std::vector<T> _elements {};
};
////////////////////////////////////////////////////////////
template <typename T>
struct PowerFunction final {
using type = T;
T StartValue;
T EndValue;
f32 Exponent;
auto get_value(f32 elapsedRatio) const -> T
{
if (Exponent <= 0 && elapsedRatio == 0) {
return StartValue;
}
if constexpr (Interpolatable<T>) {
return StartValue.get_interpolated(EndValue, std::pow(elapsedRatio, Exponent));
} else {
return StartValue + ((EndValue - StartValue) * std::pow(elapsedRatio, Exponent));
}
}
};
////////////////////////////////////////////////////////////
template <typename T>
struct InversePowerFunction final {
using type = T;
T StartValue;
T EndValue;
f32 Exponent;
auto get_value(f32 elapsedRatio) const -> T
{
if (Exponent <= 0 && elapsedRatio == 0) {
return StartValue;
}
if constexpr (Interpolatable<T>) {
return StartValue.get_interpolated(EndValue, 1 - std::pow(1 - elapsedRatio, Exponent));
} else {
return StartValue + ((EndValue - StartValue) * (1 - std::pow(1 - elapsedRatio, Exponent)));
}
}
};
////////////////////////////////////////////////////////////
template <typename T>
struct LinearFunction final {
using type = T;
T StartValue;
T EndValue;
auto get_value(f32 elapsedRatio) const -> T
{
if (elapsedRatio == 0) {
return StartValue;
}
if constexpr (Interpolatable<T>) {
return StartValue.get_interpolated(EndValue, elapsedRatio);
} else {
return StartValue + ((EndValue - StartValue) * elapsedRatio);
}
}
};
////////////////////////////////////////////////////////////
template <typename T>
struct SmoothstepFunction final {
using type = T;
T Edge0;
T Edge1;
auto get_value(f32 elapsedRatio) const -> T
{
if (elapsedRatio == 0) {
return Edge0;
}
f32 e { elapsedRatio * elapsedRatio * (3.f - 2.f * elapsedRatio) };
if constexpr (Interpolatable<T>) {
return Edge0.get_interpolated(Edge1, e);
} else {
return Edge0 + ((Edge1 - Edge0) * e);
}
}
};
////////////////////////////////////////////////////////////
template <typename T>
struct SmootherstepFunction final {
using type = T;
T Edge0;
T Edge1;
auto get_value(f32 elapsedRatio) const -> T
{
if (elapsedRatio == 0) {
return Edge0;
}
f32 e { elapsedRatio * elapsedRatio * elapsedRatio * (elapsedRatio * (elapsedRatio * 6 - 15) + 10) };
if constexpr (Interpolatable<T>) {
return Edge0.get_interpolated(Edge1, e);
} else {
return Edge0 + ((Edge1 - Edge0) * e);
}
}
};
////////////////////////////////////////////////////////////
template <typename T>
struct SineWaveFunction final {
using type = T;
T MinValue;
T MaxValue;
f32 Frequency;
f32 Phase;
auto get_value(f32 elapsedRatio) const -> T
{
const f64 val { get_wavevalue((Frequency * elapsedRatio)) };
if constexpr (Interpolatable<T>) {
return MinValue.get_interpolated(MaxValue, val);
} else {
return MinValue + ((MaxValue - MinValue) * val);
}
}
private:
auto get_wavevalue(f64 time) const -> f64
{
return (std::sin((TAU * time) + (0.75 * TAU) + Phase) + 1) / 2;
}
};
////////////////////////////////////////////////////////////
template <typename T>
struct TriangeWaveFunction final {
using type = T;
T MinValue;
T MaxValue;
f32 Frequency;
f32 Phase;
auto get_value(f32 elapsedRatio) const -> T
{
const f64 val { get_wavevalue((Frequency * elapsedRatio) + Phase) };
if constexpr (Interpolatable<T>) {
return MinValue.get_interpolated(MaxValue, val);
} else {
return MinValue + ((MaxValue - MinValue) * val);
}
}
private:
auto get_wavevalue(f64 time) const -> f64
{
return 2 * std::abs(std::round(time) - time);
}
};
////////////////////////////////////////////////////////////
template <typename T>
struct SquareWaveFunction final {
using type = T;
T MinValue;
T MaxValue;
f32 Frequency;
f32 Phase;
auto get_value(f32 elapsedRatio) const -> T
{
const f64 val { get_wavevalue((Frequency * elapsedRatio)) };
if constexpr (Interpolatable<T>) {
return MinValue.get_interpolated(MaxValue, val);
} else {
return MinValue + ((MaxValue - MinValue) * val);
}
}
private:
auto get_wavevalue(f64 time) const -> f64
{
const f64 x { std::round(time + Phase) / 2 };
return 2 * (x - std::floor(x));
}
};
////////////////////////////////////////////////////////////
template <typename T>
struct SawtoothWaveFunction final {
using type = T;
T MinValue;
T MaxValue;
f32 Frequency;
f32 Phase;
auto get_value(f32 elapsedRatio) const -> T
{
const f64 val { get_wavevalue((Frequency * elapsedRatio) + Phase) };
if constexpr (Interpolatable<T>) {
return MinValue.get_interpolated(MaxValue, val);
} else {
return MinValue + ((MaxValue - MinValue) * val);
}
}
private:
auto get_wavevalue(f64 time) const -> f64
{
return time - std::floor(time);
}
};
////////////////////////////////////////////////////////////
struct CubicBezierFunction final {
using type = PointF;
PointF Start;
PointF ControlPoint0;
PointF ControlPoint1;
PointF End;
auto get_value(f32 elapsedRatio) const -> PointF
{
const PointF a { get_point_in_line(Start, ControlPoint0, elapsedRatio) };
const PointF b { get_point_in_line(ControlPoint0, ControlPoint1, elapsedRatio) };
const PointF c { get_point_in_line(ControlPoint1, End, elapsedRatio) };
return get_point_in_line(get_point_in_line(a, b, elapsedRatio), get_point_in_line(b, c, elapsedRatio), elapsedRatio);
}
private:
auto get_point_in_line(const PointF& a, const PointF& b, f32 t) const -> PointF
{
return {
a.X - ((a.X - b.X) * t),
a.Y - ((a.Y - b.Y) * t)
};
}
};
////////////////////////////////////////////////////////////
template <typename T>
struct RandomFunction final {
using type = T;
T MinValue;
T MaxValue;
mutable Random RNG;
auto get_value(f32 elapsedRatio) const -> T
{
return RNG(MinValue, MaxValue);
}
};
}
| 24.408696
| 125
| 0.546491
|
TobiasBohnen
|
722453a47a24987fd1452538469992a1e5025906
| 1,288
|
cpp
|
C++
|
ewk/unittest/utc_blink_ewk_context_proxy_uri_set_func.cpp
|
Jabawack/chromium-efl
|
6d3a3accc8afba0aa0eff6461eb5c83138172e6e
|
[
"BSD-3-Clause"
] | 9
|
2015-04-09T20:22:08.000Z
|
2021-03-17T08:34:56.000Z
|
ewk/unittest/utc_blink_ewk_context_proxy_uri_set_func.cpp
|
Jabawack/chromium-efl
|
6d3a3accc8afba0aa0eff6461eb5c83138172e6e
|
[
"BSD-3-Clause"
] | 2
|
2015-02-04T13:41:12.000Z
|
2015-05-25T14:00:40.000Z
|
ewk/unittest/utc_blink_ewk_context_proxy_uri_set_func.cpp
|
isabella232/chromium-efl
|
db2d09aba6498fb09bbea1f8440d071c4b0fde78
|
[
"BSD-3-Clause"
] | 14
|
2015-02-12T16:20:47.000Z
|
2022-01-20T10:36:26.000Z
|
// Copyright 2014 Samsung Electronics. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "utc_blink_ewk_base.h"
class utc_blink_ewk_context_proxy_uri_set : public utc_blink_ewk_base
{
protected:
static const char*const url;
};
const char*const utc_blink_ewk_context_proxy_uri_set::url="http://proxy.tc.url";
/**
* @brief Positive TC for ewk_context_proxy_uri_set()
*/
TEST_F(utc_blink_ewk_context_proxy_uri_set, POS_TEST)
{
/* TODO: this code should use ewk_context_proxy_uri_set and check its behaviour.
Results should be reported using one of utc_ macros */
Ewk_Context* defaultContext = ewk_context_default_get();
if (!defaultContext)
utc_fail();
ewk_context_proxy_uri_set(defaultContext, url);
utc_check_str_eq(ewk_context_proxy_uri_get(defaultContext), url);
}
/**
* @brief Negative TC for ewk_context_proxy_uri_set()
*/
TEST_F(utc_blink_ewk_context_proxy_uri_set, NEG_TEST)
{
/* TODO: this code should use ewk_context_proxy_uri_set and check its behaviour.
Results should be reported using one of utc_ macros */
Ewk_Context* defaultContext = ewk_context_default_get();
if (!defaultContext)
utc_fail();
ewk_context_proxy_uri_set(NULL, NULL);
utc_pass();
}
| 30.666667
| 82
| 0.776398
|
Jabawack
|
7228c338c7a4d565cdda960c9153395a6e053ef3
| 4,554
|
cpp
|
C++
|
DHT_U.cpp
|
bert386/esp32-pellet-hmi
|
17e389632defb51dbc42cb2eef968fdc74a39477
|
[
"Apache-2.0"
] | 1
|
2021-03-03T05:35:43.000Z
|
2021-03-03T05:35:43.000Z
|
DHT_U.cpp
|
bert386/esp32-pellet-hmi
|
17e389632defb51dbc42cb2eef968fdc74a39477
|
[
"Apache-2.0"
] | null | null | null |
DHT_U.cpp
|
bert386/esp32-pellet-hmi
|
17e389632defb51dbc42cb2eef968fdc74a39477
|
[
"Apache-2.0"
] | null | null | null |
#include "DHT_U.h"
DHT_Unified::DHT_Unified(uint8_t pin, uint8_t type, uint8_t count, int32_t tempSensorId, int32_t humiditySensorId):
_dht(pin, type, count),
_type(type),
_temp(this, tempSensorId),
_humidity(this, humiditySensorId)
{}
void DHT_Unified::begin() {
_dht.begin();
}
void DHT_Unified::setName(sensor_t* sensor) {
switch(_type) {
case DHT11:
strncpy(sensor->name, "DHT11", sizeof(sensor->name) - 1);
break;
case DHT21:
strncpy(sensor->name, "DHT21", sizeof(sensor->name) - 1);
break;
case DHT22:
strncpy(sensor->name, "DHT22", sizeof(sensor->name) - 1);
break;
default:
// TODO: Perhaps this should be an error? However main DHT library doesn't enforce
// restrictions on the sensor type value. Pick a generic name for now.
strncpy(sensor->name, "DHT?", sizeof(sensor->name) - 1);
break;
}
sensor->name[sizeof(sensor->name)- 1] = 0;
}
void DHT_Unified::setMinDelay(sensor_t* sensor) {
switch(_type) {
case DHT11:
sensor->min_delay = 1000000L; // 1 second (in microseconds)
break;
case DHT21:
sensor->min_delay = 2000000L; // 2 seconds (in microseconds)
break;
case DHT22:
sensor->min_delay = 2000000L; // 2 seconds (in microseconds)
break;
default:
// Default to slowest sample rate in case of unknown type.
sensor->min_delay = 2000000L; // 2 seconds (in microseconds)
break;
}
}
DHT_Unified::Temperature::Temperature(DHT_Unified* parent, int32_t id):
_parent(parent),
_id(id)
{}
bool DHT_Unified::Temperature::getEvent(sensors_event_t* event) {
// Clear event definition.
memset(event, 0, sizeof(sensors_event_t));
// Populate sensor reading values.
event->version = sizeof(sensors_event_t);
event->sensor_id = _id;
event->type = SENSOR_TYPE_AMBIENT_TEMPERATURE;
event->timestamp = millis();
event->temperature = _parent->_dht.readTemperature();
return true;
}
void DHT_Unified::Temperature::getSensor(sensor_t* sensor) {
// Clear sensor definition.
memset(sensor, 0, sizeof(sensor_t));
// Set sensor name.
_parent->setName(sensor);
// Set version and ID
sensor->version = DHT_SENSOR_VERSION;
sensor->sensor_id = _id;
// Set type and characteristics.
sensor->type = SENSOR_TYPE_AMBIENT_TEMPERATURE;
_parent->setMinDelay(sensor);
switch (_parent->_type) {
case DHT11:
sensor->max_value = 50.0F;
sensor->min_value = 0.0F;
sensor->resolution = 2.0F;
break;
case DHT21:
sensor->max_value = 80.0F;
sensor->min_value = -40.0F;
sensor->resolution = 0.1F;
break;
case DHT22:
sensor->max_value = 125.0F;
sensor->min_value = -40.0F;
sensor->resolution = 0.1F;
break;
default:
// Unknown type, default to 0.
sensor->max_value = 0.0F;
sensor->min_value = 0.0F;
sensor->resolution = 0.0F;
break;
}
}
DHT_Unified::Humidity::Humidity(DHT_Unified* parent, int32_t id):
_parent(parent),
_id(id)
{}
bool DHT_Unified::Humidity::getEvent(sensors_event_t* event) {
// Clear event definition.
memset(event, 0, sizeof(sensors_event_t));
// Populate sensor reading values.
event->version = sizeof(sensors_event_t);
event->sensor_id = _id;
event->type = SENSOR_TYPE_RELATIVE_HUMIDITY;
event->timestamp = millis();
event->relative_humidity = _parent->_dht.readHumidity();
return true;
}
void DHT_Unified::Humidity::getSensor(sensor_t* sensor) {
// Clear sensor definition.
memset(sensor, 0, sizeof(sensor_t));
// Set sensor name.
_parent->setName(sensor);
// Set version and ID
sensor->version = DHT_SENSOR_VERSION;
sensor->sensor_id = _id;
// Set type and characteristics.
sensor->type = SENSOR_TYPE_RELATIVE_HUMIDITY;
_parent->setMinDelay(sensor);
switch (_parent->_type) {
case DHT11:
sensor->max_value = 80.0F;
sensor->min_value = 20.0F;
sensor->resolution = 5.0F;
break;
case DHT21:
sensor->max_value = 100.0F;
sensor->min_value = 0.0F;
sensor->resolution = 0.1F;
break;
case DHT22:
sensor->max_value = 100.0F;
sensor->min_value = 0.0F;
sensor->resolution = 0.1F;
break;
default:
// Unknown type, default to 0.
sensor->max_value = 0.0F;
sensor->min_value = 0.0F;
sensor->resolution = 0.0F;
break;
}
}
| 28.4625
| 115
| 0.63307
|
bert386
|
7229d3675fd07fda77dd0738036f04243218b3cb
| 1,625
|
cpp
|
C++
|
concept_tests/drivers/freertos_driver.cpp
|
jedrzejboczar/ubik-micromouse
|
6470368de0c3207fc278bcfa604d1fdd74aaeb8f
|
[
"MIT"
] | 3
|
2019-10-30T07:37:47.000Z
|
2021-01-21T11:50:20.000Z
|
concept_tests/drivers/freertos_driver.cpp
|
jedrzejboczar/ubik-micromouse
|
6470368de0c3207fc278bcfa604d1fdd74aaeb8f
|
[
"MIT"
] | null | null | null |
concept_tests/drivers/freertos_driver.cpp
|
jedrzejboczar/ubik-micromouse
|
6470368de0c3207fc278bcfa604d1fdd74aaeb8f
|
[
"MIT"
] | null | null | null |
#include "freertos_driver.h"
// void FreeRTOSDriverTask::task() {
// run();
// }
FreeRTOSDriverTask::FreeRTOSDriverTask(
const char * name, int priority, int stack_depth,
size_t request_queue_length, TickType_t timeout):
FreeRTOSTask(name, priority, stack_depth),
request_queue_length(request_queue_length), timeout(timeout), runner(nullptr)
{ }
QueueHandle_t FreeRTOSDriverTask::create_queue(
size_t queue_length, size_t data_size)
{
return xQueueCreate(queue_length, data_size);
}
void FreeRTOSDriverTask::create_request_queue(size_t data_size) {
request_queue = create_queue(request_queue_length, data_size);
configASSERT(request_queue);
}
bool FreeRTOSDriverTask::receive_request(void *into_buffer) {
BaseType_t result = xQueueReceive(request_queue,
into_buffer, portMAX_DELAY); // TODO: how to specify the delay!!!
return result == pdTRUE;
}
bool FreeRTOSDriverTask::wait_for_isr() {
uint32_t notification_value = ulTaskNotifyTake(pdTRUE,
portMAX_DELAY); // TODO: how to specify the delay!!!
return notification_value != 0;
}
void FreeRTOSDriverTask::send_response(QueueHandle_t response_queue, const void *from_buffer) {
BaseType_t result = xQueueSend(response_queue,
from_buffer, portMAX_DELAY); // TODO: how to specify the delay!!!
(void) result; // the driver doesn't care, we could try multiple times if needed
}
void FreeRTOSDriverTask::set_task_runner(TaskRunner *runner) {
this->runner = runner;
}
void FreeRTOSDriverTask::task() {
configASSERT(runner != nullptr);
runner->run();
}
| 31.25
| 95
| 0.729231
|
jedrzejboczar
|
722e215ab9d583c68b4b931841d7e1501fc8ff49
| 1,453
|
cpp
|
C++
|
algorithms/KthSmallestElementinaBST/tree.cpp
|
PikachuPikachuHAHA/leetcode-2
|
4cf8d30509f4b994b1845765807380eeffb95c73
|
[
"MIT"
] | 93
|
2016-04-27T23:25:27.000Z
|
2021-07-13T20:32:25.000Z
|
algorithms/KthSmallestElementinaBST/tree.cpp
|
shangan/leetcode
|
db05338f8057ad440cb5dd6cfe0151aafb7a8d56
|
[
"MIT"
] | null | null | null |
algorithms/KthSmallestElementinaBST/tree.cpp
|
shangan/leetcode
|
db05338f8057ad440cb5dd6cfe0151aafb7a8d56
|
[
"MIT"
] | 43
|
2016-05-31T15:46:50.000Z
|
2021-04-09T04:07:39.000Z
|
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cstdio>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr){}
};
class Solution {
public:
int kthSmallest(TreeNode *root, int k) {
int result;
/*
if (root == nullptr) {
return 0;
}
*/
kthSmallest(root, k, result);
return result;
}
private:
bool kthSmallest(TreeNode *root, int &k, int &result) {
if (root->left) {
if (kthSmallest(root->left, k, result)) {
return true;
}
}
k -= 1;
if (k == 0) {
result = root->val;
return true;
}
if (root->right) {
if (kthSmallest(root->right, k, result)) {
return true;
}
}
return false;
}
};
TreeNode *mk_node(int val)
{
return new TreeNode(val);
}
TreeNode *mk_child(TreeNode *root, TreeNode *left, TreeNode *right)
{
root->left = left;
root->right = right;
return root;
}
TreeNode *mk_child(TreeNode *root, int left, int right)
{
return mk_child(root, new TreeNode(left), new TreeNode(right));
}
TreeNode *mk_child(int root, int left, int right)
{
return mk_child(new TreeNode(root), new TreeNode(left), new TreeNode(right));
}
int main(int argc, char **argv)
{
Solution solution;
TreeNode *root = mk_child(6, 4, 8);
mk_child(root->left, 3, 5);
mk_child(root->right, 7, 9);
for (int i = 1; i <= 7; ++i)
printf("%d\n", solution.kthSmallest(root, i));
return 0;
}
| 19.90411
| 78
| 0.644184
|
PikachuPikachuHAHA
|
7236a5e16e768f9e870eab43fe93378f499bac48
| 985
|
cpp
|
C++
|
System/GroundMissionControl.cpp
|
MatthewGotte/214_project_Derived
|
48a74a10bc4fd5b01d11d1f89a7203a5b070b9bd
|
[
"MIT"
] | null | null | null |
System/GroundMissionControl.cpp
|
MatthewGotte/214_project_Derived
|
48a74a10bc4fd5b01d11d1f89a7203a5b070b9bd
|
[
"MIT"
] | null | null | null |
System/GroundMissionControl.cpp
|
MatthewGotte/214_project_Derived
|
48a74a10bc4fd5b01d11d1f89a7203a5b070b9bd
|
[
"MIT"
] | null | null | null |
#include "GroundMissionControl.h"
#include "Satellite.h"
GroundMissionControl::GroundMissionControl() {
}
void GroundMissionControl::attach(Satellite* addSatellite) {
this->satelliteList.push_back(addSatellite);
}
void GroundMissionControl::detach(Satellite* removeSatellite) {
vector<Satellite*>::iterator it;
for (it = this->satelliteList.begin(); it != this->satelliteList.end(); ++it) {
if (*it == removeSatellite && *it != nullptr) {
this->satelliteList.erase(it);
}
}
}
void GroundMissionControl::notify() {
vector<Satellite*>::iterator it;
for (it = this->satelliteList.begin(); it != this->satelliteList.end(); ++it) {
(*it)->update();
}
}
GroundMissionControl::~GroundMissionControl() {
vector<Satellite*>::iterator it;
for (it = this->satelliteList.begin(); it != this->satelliteList.end(); ++it) {
delete *it;
}
}
| 24.625
| 84
| 0.603046
|
MatthewGotte
|
723825c6ae045d3688616d4d86c65a960f8057ce
| 4,609
|
cpp
|
C++
|
test/graphic/sphere_transparent_test.cpp
|
mpinto70/raytracing
|
5e3a46257b74a3df1b91fb066d7763b50273bf83
|
[
"MIT"
] | null | null | null |
test/graphic/sphere_transparent_test.cpp
|
mpinto70/raytracing
|
5e3a46257b74a3df1b91fb066d7763b50273bf83
|
[
"MIT"
] | null | null | null |
test/graphic/sphere_transparent_test.cpp
|
mpinto70/raytracing
|
5e3a46257b74a3df1b91fb066d7763b50273bf83
|
[
"MIT"
] | null | null | null |
#include "graphic/sphere_transparent.h"
#include <gtest/gtest.h>
namespace graphic {
using geometry::vec3d;
TEST(sphere_transparent, creation) {
constexpr vec3d C1{ 7, 8, 9 };
constexpr dim_t R1 = 5.0f;
const sphere_transparent S1{ C1, R1, 1.458, 0.1, 0.2, 0.3 };
constexpr vec3d C2{ -2, 3, 10 };
constexpr dim_t R2 = 3.4f;
const sphere_transparent S2{ C2, R2, 1.458, 0.4, 0.5, 0.7 };
EXPECT_EQ(S1.center(), C1);
EXPECT_EQ(S1.radius(), R1);
EXPECT_EQ(S1.dim_r(), dim_t(0.1));
EXPECT_EQ(S1.dim_g(), dim_t(0.2));
EXPECT_EQ(S1.dim_b(), dim_t(0.3));
EXPECT_EQ(S2.center(), C2);
EXPECT_EQ(S2.radius(), R2);
EXPECT_EQ(S2.dim_r(), dim_t(0.4));
EXPECT_EQ(S2.dim_g(), dim_t(0.5));
EXPECT_EQ(S2.dim_b(), dim_t(0.7));
}
TEST(sphere_transparent, hit_simple_and_direct) {
hit_record record{};
constexpr vec3d C{ 0, 0, -30 };
constexpr dim_t R = 5.0f;
const ray r{ { 0, 0, 0 }, { 0, 0, -1 } };
const sphere_transparent s(C, R, 1.458, 0.1, 0.2, 0.3);
constexpr vec3d hit_point{ 0, 0, -25 };
constexpr vec3d normal{ 0, 0, 1 };
EXPECT_TRUE(s.hit(r, 0.0, 500, record));
EXPECT_EQ(record.t, 25.0f);
EXPECT_EQ(record.p, hit_point);
EXPECT_EQ(record.normal, normal);
}
TEST(sphere_transparent, hit_out_of_range) {
hit_record record{};
constexpr vec3d C{ 0, 0, -30 };
constexpr dim_t R = 5.0f;
const ray r{ { 0, 0, 0 }, { 0, 0, -1 } };
const sphere_transparent s(C, R, 1.458, 0.1, 0.2, 0.3);
EXPECT_FALSE(s.hit(r, 35.5f, 500, record));
}
TEST(sphere_transparent, bounce_front_middle) {
constexpr vec3d C{ 0, 0, -30 };
constexpr dim_t R = 5.0f;
const ray r1{ { 0, 0, 0 }, { 0, 0, -1 } };
const sphere_transparent s(C, R, 1.458, 0.9, 0.9, 0.9);
hit_record record;
ASSERT_TRUE(s.hit(r1, 0.001, 1500000, record));
const auto r2 = s.bounce(r1, record);
ASSERT_TRUE(r2);
constexpr vec3d hit_p1{ 0, 0, -25 };
constexpr vec3d dir_p1{ 0, 0, -1 };
EXPECT_EQ(r2->origin(), hit_p1);
EXPECT_EQ(r2->direction(), dir_p1);
ASSERT_TRUE(s.hit(*r2, 0.001, 1500000, record));
const auto r3 = s.bounce(r1, record);
ASSERT_TRUE(r3);
constexpr vec3d hit_p2{ 0, 0, -35 };
constexpr vec3d dir_p2{ 0, 0, -1 };
EXPECT_EQ(r3->origin(), hit_p2);
EXPECT_EQ(r3->direction(), dir_p2);
}
TEST(sphere_transparent, bounce_off_center) {
constexpr vec3d C{ 0, 0, -30 };
constexpr dim_t R = 5.0f;
const ray r1{ { 1, 1, 0 }, { 0, 0, -1 } };
const sphere_transparent s(C, R, 1.458, 0.9, 0.9, 0.9);
hit_record record;
ASSERT_TRUE(s.hit(r1, 0.001, 1500000, record));
const auto r2 = s.bounce(r1, record);
ASSERT_TRUE(r2);
constexpr vec3d hit_p1{ 1, 1, -25.204168 };
constexpr vec3d normal_p1{ 0.19999998, 0.19999998, 0.9591663 };
constexpr vec3d dir_p1{ -6.462767e-2, -6.462767e-2, -0.9958145 };
EXPECT_FLOAT_EQ(record.normal.x, normal_p1.x);
EXPECT_FLOAT_EQ(record.normal.y, normal_p1.y);
EXPECT_FLOAT_EQ(record.normal.z, normal_p1.z);
EXPECT_FLOAT_EQ(r2->origin().x, hit_p1.x);
EXPECT_FLOAT_EQ(r2->origin().y, hit_p1.y);
EXPECT_FLOAT_EQ(r2->origin().z, hit_p1.z);
EXPECT_FLOAT_EQ(r2->direction().x, dir_p1.x);
EXPECT_FLOAT_EQ(r2->direction().y, dir_p1.y);
EXPECT_FLOAT_EQ(r2->direction().z, dir_p1.z);
ASSERT_TRUE(s.hit(*r2, 0.001, 1500000, record));
const auto r3 = s.bounce(*r2, record);
ASSERT_TRUE(r3);
constexpr vec3d hit_p2{ 0.366000692813, 0.366000692813, -34.9731369937 };
constexpr vec3d normal_p2{ 7.32001318686e-2, 7.32001318686e-2, -0.994627307783 };
constexpr vec3d dir_p2{ -0.128714342822, -0.128714342822, -0.983293056984 };
EXPECT_FLOAT_EQ(r3->origin().x, hit_p2.x);
EXPECT_FLOAT_EQ(r3->origin().y, hit_p2.y);
EXPECT_FLOAT_EQ(r3->origin().z, hit_p2.z);
EXPECT_FLOAT_EQ(record.normal.x, normal_p2.x);
EXPECT_FLOAT_EQ(record.normal.y, normal_p2.y);
EXPECT_FLOAT_EQ(record.normal.z, normal_p2.z);
EXPECT_FLOAT_EQ(r3->direction().x, dir_p2.x);
EXPECT_FLOAT_EQ(r3->direction().y, dir_p2.y);
EXPECT_FLOAT_EQ(r3->direction().z, dir_p2.z);
}
TEST(sphere_transparent, dim) {
constexpr vec3d C{ 0, 0, -30 };
constexpr dim_t R = 5.0f;
const ray r{ { 0, 0, 0 }, { -7, -2, -1 } };
const sphere_transparent s(C, R, 1.458, 0.1, 0.2, 0.3);
auto out_color = s.dim(color{ 234, 123, 210 });
constexpr color expected_color = { 23, 24, 63 };
EXPECT_EQ(out_color.r, expected_color.r);
EXPECT_EQ(out_color.g, expected_color.g);
EXPECT_EQ(out_color.b, expected_color.b);
}
}
| 34.395522
| 85
| 0.635713
|
mpinto70
|
5cfb300c5618be540e9dab1268bc36675010d39a
| 2,624
|
cpp
|
C++
|
homomorphic_evaluation/ntl-11.3.2/src/Poly3TimeTest.cpp
|
dklee0501/PLDI_20_242_artifact_publication
|
f2b73df9165c76e8b521d8ebd639d68321e3862b
|
[
"MIT"
] | 160
|
2016-05-11T09:45:56.000Z
|
2022-03-06T09:32:19.000Z
|
homomorphic_evaluation/ntl-11.3.2/src/Poly3TimeTest.cpp
|
dklee0501/Lobster
|
f2b73df9165c76e8b521d8ebd639d68321e3862b
|
[
"MIT"
] | 57
|
2016-12-26T07:02:12.000Z
|
2022-03-06T16:34:31.000Z
|
homomorphic_evaluation/ntl-11.3.2/src/Poly3TimeTest.cpp
|
dklee0501/Lobster
|
f2b73df9165c76e8b521d8ebd639d68321e3862b
|
[
"MIT"
] | 67
|
2016-10-10T17:56:22.000Z
|
2022-03-15T22:56:39.000Z
|
#include <NTL/ZZ_pX.h>
#include <cstdio>
NTL_CLIENT
double clean_data(double *t)
{
double x, y, z;
long i, ix, iy, n;
x = t[0]; ix = 0;
y = t[0]; iy = 0;
for (i = 1; i < 5; i++) {
if (t[i] < x) {
x = t[i];
ix = i;
}
if (t[i] > y) {
y = t[i];
iy = i;
}
}
z = 0; n = 0;
for (i = 0; i < 5; i++) {
if (i != ix && i != iy) z+= t[i], n++;
}
z = z/n;
return z;
}
void print_flag()
{
#if (defined(NTL_CRT_ALTCODE))
printf("CRT_ALTCODE ");
#else
printf("DEFAULT ");
#endif
printf("\n");
}
int main()
{
SetSeed(ZZ(0));
long n, k;
n = 1024;
k = 30*NTL_SP_NBITS;
ZZ p;
RandomLen(p, k);
if (!IsOdd(p)) p++;
ZZ_p::init(p); // initialization
ZZ_pX f, g, h, r1, r2, r3;
random(g, n); // g = random polynomial of degree < n
random(h, n); // h = " "
random(f, n); // f = " "
SetCoeff(f, n); // Sets coefficient of X^n to 1
// For doing arithmetic mod f quickly, one must pre-compute
// some information.
ZZ_pXModulus F;
build(F, f);
PlainMul(r1, g, h); // this uses classical arithmetic
PlainRem(r1, r1, f);
MulMod(r2, g, h, F); // this uses the FFT
MulMod(r3, g, h, f); // uses FFT, but slower
// compare the results...
if (r1 != r2) {
printf("999999999999999 ");
print_flag();
return 0;
}
else if (r1 != r3) {
printf("999999999999999 ");
print_flag();
return 0;
}
double t;
long i;
long iter;
ZZ_pX a, b, c;
random(a, n);
random(b, n);
long da = deg(a);
long db = deg(b);
long dc = da + db;
long l = NextPowerOfTwo(dc+1);
FFTRep arep, brep, crep;
ToFFTRep(arep, a, l, 0, da);
ToFFTRep(brep, b, l, 0, db);
mul(crep, arep, brep);
ZZ_pXModRep modrep;
FromFFTRep(modrep, crep);
FromZZ_pXModRep(c, modrep, 0, dc);
iter = 1;
do {
t = GetTime();
for (i = 0; i < iter; i++) {
FromZZ_pXModRep(c, modrep, 0, dc);
}
t = GetTime() - t;
iter = 2*iter;
} while(t < 1);
iter = iter/2;
iter = long((3/t)*iter) + 1;
double tvec[5];
long w;
for (w = 0; w < 5; w++) {
t = GetTime();
for (i = 0; i < iter; i++) {
FromZZ_pXModRep(c, modrep, 0, dc);
}
t = GetTime() - t;
tvec[w] = t;
}
t = clean_data(tvec);
t = floor((t/iter)*1e12);
if (t < 0 || t >= 1e15)
printf("999999999999999 ");
else
printf("%015.0f ", t);
printf(" [%ld] ", iter);
print_flag();
return 0;
}
| 15.255814
| 62
| 0.470655
|
dklee0501
|
5cfd9b6935f140e9eca09aeef566fb9c6424ab7f
| 1,120
|
cpp
|
C++
|
examples/week01/numbers/sizeof.cpp
|
DaveParillo/cisc187-docker
|
872c0dba7d79d2e5c7c0269a8b75045c6f2bc229
|
[
"MIT"
] | null | null | null |
examples/week01/numbers/sizeof.cpp
|
DaveParillo/cisc187-docker
|
872c0dba7d79d2e5c7c0269a8b75045c6f2bc229
|
[
"MIT"
] | null | null | null |
examples/week01/numbers/sizeof.cpp
|
DaveParillo/cisc187-docker
|
872c0dba7d79d2e5c7c0269a8b75045c6f2bc229
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
int main() {
char c = 'a';
std::cout << "size of char: " << sizeof(c) << '\n'
<< "size of int: " << sizeof(int) << '\n'
<< "size of double: " << sizeof(double) << '\n'
<< "size of pointer: " << sizeof(&c) << std::endl;
double foo[10] = {0.1, 3.14159, 1e1, 2e-6, 5, 6, 7, 8, 9, 10};
std::cout << "size of foo[]: " << sizeof(foo) << '\n'
<< "no. of elements in foo[]: " << sizeof(foo) / sizeof(foo[0]) << std::endl;
std::string bar[10] = {
"hi", "hello world!", "it doesn't actually matter how long these strings are as far as the array is concerned. What is stored is only a reference to the string in memory" };
std::cout << "size of bar[]: " << sizeof(bar) << '\n'
<< "size of &bar: " << sizeof(&bar) << '\n'
<< "size of *bar: " << sizeof(*bar) << '\n'
<< "size of bar[0]: " << sizeof(bar[0]) << '\n'
<< "size of bar[2]: " << sizeof(bar[2]) << '\n'
<< "no. of elements in bar[]: " << sizeof(bar) / sizeof(bar[0]) << std::endl;
}
| 46.666667
| 178
| 0.473214
|
DaveParillo
|
5cfeffcb3608cdbcd3725189563c08e85ff27ae1
| 9,461
|
cpp
|
C++
|
src/test-apps/weave-connection-tunnel.cpp
|
aiw-google/openweave-core
|
5dfb14b21d0898ef95bb62ff564cadfeea4b4702
|
[
"Apache-2.0"
] | 1
|
2021-08-10T12:08:31.000Z
|
2021-08-10T12:08:31.000Z
|
src/test-apps/weave-connection-tunnel.cpp
|
aiw-google/openweave-core
|
5dfb14b21d0898ef95bb62ff564cadfeea4b4702
|
[
"Apache-2.0"
] | null | null | null |
src/test-apps/weave-connection-tunnel.cpp
|
aiw-google/openweave-core
|
5dfb14b21d0898ef95bb62ff564cadfeea4b4702
|
[
"Apache-2.0"
] | 1
|
2020-06-15T01:50:59.000Z
|
2020-06-15T01:50:59.000Z
|
/*
*
* Copyright (c) 2016-2017 Nest Labs, Inc.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* This file aims to test the WeaveConnectionTunnel functionality, three kinds of nodes:
* - ConnectionTunnelAgent: create connections to Tunnel Source and Destination, establish tunnel between them
* - ConnectionTunnelSource: wait for connection from Tunnel Agent, act as sender to verify tunnel link
* - ConnectionTunnelDestination: wait for connection from Tunnel Agent, act as receiver to verify tunnel link
*
*/
#define __STDC_FORMAT_MACROS
#define __STDC_LIMIT_MACROS
#include <inttypes.h>
#include "ToolCommon.h"
#define TOOL_NAME "weave-connection-tunnel"
enum
{
ConnectionTunnelAgent = 0,
ConnectionTunnelSource,
ConnectionTunnelDest,
};
static bool HandleOption(const char *progName, OptionSet *optSet, int id, const char *name, const char *arg);
static bool HandleNonOptionArgs(const char *progName, int argc, char *argv[]);
static void StartConnections();
static void DriveSending();
static void HandleConnectionReceived(WeaveMessageLayer *msgLayer, WeaveConnection *con);
static void HandleConnectionComplete(WeaveConnection *con, WEAVE_ERROR conErr);
static void HandleMessageReceived(WeaveConnection *con, WeaveMessageInfo *msgInfo, PacketBuffer *msgBuf);
uint8_t Role = ConnectionTunnelAgent;
WeaveConnectionTunnel *tun = NULL;
WeaveConnection *conSource = NULL;
WeaveConnection *conDest = NULL;
WeaveConnection *connection = NULL;
uint64_t TunnelSourceNodeId;
uint64_t TunnelDestNodeId;
IPAddress TunnelSourceAddr = IPAddress::Any;
IPAddress TunnelDestAddr = IPAddress::Any;
static OptionDef gToolOptionDefs[] =
{
{ "tunnel-source", kNoArgument, 'S' },
{ "tunnel-destination", kNoArgument, 'D' },
{ "tunnel-agent", kNoArgument, 'A' },
{ NULL }
};
static const char *const gToolOptionHelp =
" -S, --tunnel-source\n"
" Specify the node as tunnel source, act as sender to vefify tunnel link\n"
"\n"
" -D, --tunnel-destination\n"
" Specify the node as tunnel destination, act as receiver to vefify tunnel link\n"
"\n"
" -A, --tunnel-agent\n"
" Specify the node as tunnel agent, establish connection tunnel between source node and destination node\n"
"\n";
static OptionSet gToolOptions =
{
HandleOption,
gToolOptionDefs,
"GENERAL OPTIONS",
gToolOptionHelp
};
static HelpOptions gHelpOptions(
TOOL_NAME,
"Usage: " TOOL_NAME " [<options...>] --tunnel-source\n"
" " TOOL_NAME " [<options...>] --tunnel-destination\n"
" " TOOL_NAME " [<options...>] --tunnel-agent <source-node-id> <dest-node-id>\n",
WEAVE_VERSION_STRING "\n" WEAVE_TOOL_COPYRIGHT
);
static OptionSet *gToolOptionSets[] =
{
&gToolOptions,
&gNetworkOptions,
&gWeaveNodeOptions,
&gFaultInjectionOptions,
&gHelpOptions,
NULL
};
int main(int argc, char *argv[])
{
InitToolCommon();
SetSIGUSR1Handler();
if (argc == 1)
{
gHelpOptions.PrintBriefUsage(stderr);
exit(EXIT_FAILURE);
}
if (!ParseArgsFromEnvVar(TOOL_NAME, TOOL_OPTIONS_ENV_VAR_NAME, gToolOptionSets, NULL, true) ||
!ParseArgs(TOOL_NAME, argc, argv, gToolOptionSets, HandleNonOptionArgs) ||
!ResolveWeaveNetworkOptions(TOOL_NAME, gWeaveNodeOptions, gNetworkOptions))
{
exit(EXIT_FAILURE);
}
InitSystemLayer();
InitNetwork();
InitWeaveStack(true, false);
MessageLayer.OnConnectionReceived = HandleConnectionReceived;
PrintNodeConfig();
// Tunnel Agent: create connections to Tunnel Source and Destination
if (Role == ConnectionTunnelAgent)
StartConnections();
while (!Done)
{
struct timeval sleepTime;
sleepTime.tv_sec = 0;
sleepTime.tv_usec = 100000;
ServiceNetwork(sleepTime);
if (Role == ConnectionTunnelSource)
DriveSending();
}
ShutdownWeaveStack();
ShutdownNetwork();
ShutdownSystemLayer();
return EXIT_SUCCESS;
}
void StartConnections()
{
WEAVE_ERROR err;
conSource = MessageLayer.NewConnection();
conDest = MessageLayer.NewConnection();
VerifyOrExit(conSource != NULL && conDest != NULL, err = WEAVE_ERROR_NO_MEMORY);
conSource->OnConnectionComplete = conDest->OnConnectionComplete = HandleConnectionComplete;
TunnelSourceAddr = FabricState.SelectNodeAddress(TunnelSourceNodeId);
TunnelDestAddr = FabricState.SelectNodeAddress(TunnelDestNodeId);
err = conSource->Connect(TunnelSourceNodeId, TunnelSourceAddr);
SuccessOrExit(err);
err = conDest->Connect(TunnelDestNodeId, TunnelDestAddr);
SuccessOrExit(err);
return;
exit:
printf("Tunnel Agent: failed to create connections\n");
exit(EXIT_FAILURE);
}
bool HandleOption(const char *progName, OptionSet *optSet, int id, const char *name, const char *arg)
{
switch (id)
{
case 'A':
Role = ConnectionTunnelAgent;
break;
case 'S':
Role = ConnectionTunnelSource;
break;
case 'D':
Role = ConnectionTunnelDest;
break;
default:
PrintArgError("%s: INTERNAL ERROR: Unhandled option: %s\n", progName, name);
return false;
}
return true;
}
bool HandleNonOptionArgs(const char *progName, int argc, char *argv[])
{
if (Role == ConnectionTunnelAgent)
{
if (argc < 2)
{
PrintArgError("%s: weave-connection-tunnel: Please specify the tunnel source and destination node-id\n", progName);
return false;
}
if (argc > 2)
{
PrintArgError("%s: weave-connection-tunnel: Unexpected argument: %s\n", argv[2]);
return false;
}
if (!ParseNodeId(argv[0], TunnelSourceNodeId))
{
PrintArgError("%s: weave-connection-tunnel: Invalid value specified for tunnel source node id: %s\n", progName, argv[0]);
return false;
}
if (!ParseNodeId(argv[1], TunnelDestNodeId))
{
PrintArgError("%s: weave-connection-tunnel: Invalid value specified for tunnel destination node id: %s\n", progName, argv[1]);
return false;
}
}
else
{
if (argc > 0)
{
PrintArgError("%s: weave-connection-tunnel: Unexpected argument: %s\n", progName, argv[0]);
return false;
}
}
return true;
}
void HandleMessageReceived(WeaveConnection *con, WeaveMessageInfo *msgInfo, PacketBuffer *msgBuf)
{
if (Role == ConnectionTunnelDest)
{
printf("%s\n", msgBuf->Start());
con->Close();
Done = true;
}
PacketBuffer::Free(msgBuf);
}
// Tunnel Source and Destination: will receive connection from Tunnel Agent.
void HandleConnectionReceived(WeaveMessageLayer *msgLayer, WeaveConnection *con)
{
connection = con;
connection->OnMessageReceived = HandleMessageReceived;
}
void HandleConnectionComplete(WeaveConnection *con, WEAVE_ERROR conErr)
{
WEAVE_ERROR res = WEAVE_NO_ERROR;
if ((con == conSource) && (conErr == WEAVE_NO_ERROR))
printf("Tunnel Agent: source connected\n");
if ((con == conDest) && (conErr == WEAVE_NO_ERROR))
printf("Tunnel Agent: destination connected\n");
// Tunnel Agent: establish tunnel when the two connections are completed
if ((conSource->State == WeaveConnection::kState_Connected) && (conDest->State == WeaveConnection::kState_Connected))
{
res = MessageLayer.CreateTunnel(&tun, *conSource, *conDest, 1000000);
if (res != WEAVE_NO_ERROR)
{
printf("Tunnel Agent: failed to establish tunnel\n");
exit(-1);
}
}
}
void DriveSending()
{
WEAVE_ERROR res = WEAVE_NO_ERROR;
PacketBuffer *msgBuf = NULL;
WeaveMessageInfo msgInfo;
uint32_t len = 0;
char *p;
if ((connection != NULL) && (connection->State == WeaveConnection::kState_Connected))
{
msgBuf = PacketBuffer::New();
if (msgBuf == NULL)
{
printf("Tunnel Source: PacketBuffer alloc failed\n");
exit(-1);
}
p = (char *)msgBuf->Start();
len = sprintf(p, "Message from tunnel source node to destination node\n");
msgBuf->SetDataLength(len);
msgInfo.Clear();
msgInfo.MessageVersion = kWeaveMessageVersion_V2;
msgInfo.Flags = 0;
msgInfo.SourceNodeId = FabricState.LocalNodeId;
msgInfo.DestNodeId = kNodeIdNotSpecified;
msgInfo.EncryptionType = kWeaveEncryptionType_None;
msgInfo.KeyId = WeaveKeyId::kNone;
res = connection->SendMessage(&msgInfo, msgBuf);
if (res != WEAVE_NO_ERROR)
{
printf("Tunnel Source: failed to send message\n");
exit(-1);
}
}
}
| 29.381988
| 138
| 0.659233
|
aiw-google
|
cf03086f029e45cfbb3b2a27e454049c615950a8
| 2,462
|
cpp
|
C++
|
Dory/Sensores.cpp
|
project-neon/Dory
|
7a84ee5556b681f1b4d2a03db14f170734dd74ed
|
[
"MIT"
] | 1
|
2021-11-08T20:17:21.000Z
|
2021-11-08T20:17:21.000Z
|
Dory/Sensores.cpp
|
project-neon/Dory
|
7a84ee5556b681f1b4d2a03db14f170734dd74ed
|
[
"MIT"
] | null | null | null |
Dory/Sensores.cpp
|
project-neon/Dory
|
7a84ee5556b681f1b4d2a03db14f170734dd74ed
|
[
"MIT"
] | 1
|
2021-11-08T19:57:53.000Z
|
2021-11-08T19:57:53.000Z
|
#include <VL53L0X.h>
#include "Sensores.h"
#include "_config.h"
#include <Wire.h>
VL53L0X Sensores::sensor1;
VL53L0X Sensores::sensor2;
void Sensores::init(){
Wire.begin();
pinMode(Xshut_1, OUTPUT);
pinMode(Xshut_2, OUTPUT);
digitalWrite(Xshut_1, LOW);
digitalWrite(Xshut_2, LOW);
delay(10);
//Wire.begin();
//SENSOR (DIREITA)
pinMode(Xshut_1, INPUT);
delay(50);
Sensores::sensor1.init(true);
delay(20);
Sensores::sensor1.setAddress((uint8_t)0x22);
//SENSOR 3(ESQUERDA)
pinMode(Xshut_2, INPUT);
delay(50);
Sensores::sensor2.init(true);
delay(20);
Sensores::sensor2.setAddress((uint8_t)0x2A);
Sensores::sensor1.setTimeout(100);
Sensores::sensor2.setTimeout(100);
//Sensores::sensor.setMeasurementTimingBudget(20000);
//Sensores::sensor2.setMeasurementTimingBudget(20000);
//Sensores::sensor3.setMeasurementTimingBudget(20000);
}
int Sensores::get_valor(VL53L0X sensor){
return sensor.readRangeSingleMillimeters();
}
/*
void Sensores::Serial()
{
Serial.println("__________________________________________________________________");
Serial.println("");
Serial.println("=================================");
Serial.println ("I2C scanner. Scanning ...");
//FWD OR SENSOR
if (sensor.timeoutOccurred())
{
Serial.println("_________________________________");
Serial.print("Distance FWD (READING): ");
Serial.println(" TIMEOUT");
Serial.println("_________________________________");
Serial.println("");
}
else
{
Serial.print("Distance SENSOR 0 (mm): ");
Serial.println(Sensores::init(sensor));
}
//FLT OR SENSOR2
if (sensor2.timeoutOccurred())
{
Serial.print("Distance SENSOR 1 (READING): ");
Serial.println(" TIMEOUT");
Serial.println("_________________________________");
Serial.println("");
}
else
{
Serial.print("Distance SENSOR 1 (mm): ");
Serial.println(Sensores::init(sensor2));
}
//FRT OR SENSOR3
if (sensor3.timeoutOccurred())
{
Serial.println("_________________________________");
Serial.print("Distance SENSOR 2 (READING): ");
Serial.println(" TIMEOUT");
Serial.println("_________________________________");
Serial.println("");
}
else
{
Serial.print("Distance SENSOR 2 (mm): ");
Serial.println(Sensores::init(sensor3));
}
delay(1000);//can change to a lower time like 100
}*/
| 26.191489
| 88
| 0.655971
|
project-neon
|
cf0e92dadd83905c9a73be9189544e26aab87294
| 30,067
|
cpp
|
C++
|
Source/Interface/Resources/FontResource.cpp
|
Noxagonal/Vulkan2DRenderer
|
5110a2422dfbf0bf5cfb1d3e13c5b97d5b80243e
|
[
"MIT"
] | 90
|
2020-06-20T15:00:31.000Z
|
2022-03-22T21:03:45.000Z
|
Source/Interface/Resources/FontResource.cpp
|
Niko40/Vulkan2DRenderer
|
5110a2422dfbf0bf5cfb1d3e13c5b97d5b80243e
|
[
"MIT"
] | 39
|
2019-11-04T01:40:14.000Z
|
2020-03-09T15:57:00.000Z
|
Source/Interface/Resources/FontResource.cpp
|
Niko40/Vulkan2DRenderer
|
5110a2422dfbf0bf5cfb1d3e13c5b97d5b80243e
|
[
"MIT"
] | 4
|
2020-12-02T22:39:33.000Z
|
2021-12-27T07:55:12.000Z
|
#include "Core/SourceCommon.h"
#include "System/ThreadPrivateResources.h"
#include "Interface/InstanceImpl.h"
#include "Interface/Resources/ResourceManager.h"
#include "Interface/Resources/ResourceManagerImpl.h"
#include "Interface/Resources/FontResource.h"
#include "Interface/Resources/FontResourceImpl.h"
#include "Interface/Resources/TextureResource.h"
#include <stb_image_write.h>
namespace vk2d {
namespace _internal {
// Private function declarations.
uint32_t RoundToCeilingPowerOfTwo(
uint32_t value );
}
}
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
// Interface.
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
VK2D_API vk2d::FontResource::FontResource(
vk2d::_internal::ResourceManagerImpl * resource_manager,
uint32_t loader_thread_index,
vk2d::ResourceBase * parent_resource,
const std::filesystem::path & file_path,
uint32_t glyph_texel_size,
bool use_alpha,
uint32_t fallback_character,
uint32_t glyph_atlas_padding
)
{
impl = std::make_unique<vk2d::_internal::FontResourceImplBase>(
this,
resource_manager,
loader_thread_index,
parent_resource,
file_path,
glyph_texel_size,
use_alpha,
fallback_character,
glyph_atlas_padding
);
if( !impl || !impl->IsGood() ) {
impl = nullptr;
resource_manager->GetInstance()->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot create font resource implementation!" );
return;
}
resource_impl = impl.get();
}
VK2D_API vk2d::FontResource::~FontResource()
{}
VK2D_API vk2d::ResourceStatus VK2D_APIENTRY vk2d::FontResource::GetStatus()
{
return impl->GetStatus();
}
VK2D_API vk2d::ResourceStatus VK2D_APIENTRY vk2d::FontResource::WaitUntilLoaded(
std::chrono::nanoseconds timeout
)
{
return impl->WaitUntilLoaded( timeout );
}
VK2D_API vk2d::ResourceStatus VK2D_APIENTRY vk2d::FontResource::WaitUntilLoaded(
std::chrono::steady_clock::time_point timeout
)
{
return impl->WaitUntilLoaded( timeout );
}
VK2D_API vk2d::Rect2f VK2D_APIENTRY vk2d::FontResource::CalculateRenderedSize(
std::string_view text,
float kerning,
glm::vec2 scale,
bool vertical,
uint32_t font_face,
bool wait_for_resource_load
)
{
return impl->CalculateRenderedSize(
text,
kerning,
scale,
vertical,
font_face,
wait_for_resource_load
);
}
VK2D_API bool VK2D_APIENTRY vk2d::FontResource::IsGood() const
{
return !!impl;
}
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
// Implementation.
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
vk2d::_internal::FontResourceImplBase::FontResourceImplBase(
vk2d::FontResource * my_interface,
vk2d::_internal::ResourceManagerImpl * resource_manager,
uint32_t loader_thread_index,
vk2d::ResourceBase * parent_resource,
const std::filesystem::path & file_path,
uint32_t glyph_texel_size,
bool use_alpha,
uint32_t fallback_character,
uint32_t glyph_atlas_padding
) :
vk2d::_internal::ResourceImplBase(
my_interface,
loader_thread_index,
resource_manager,
parent_resource,
{ file_path }
)
{
assert( my_interface );
assert( resource_manager );
this->my_interface = my_interface;
this->resource_manager = resource_manager;
this->glyph_texel_size = glyph_texel_size;
this->glyph_atlas_padding = glyph_atlas_padding;
this->fallback_character = fallback_character;
this->use_alpha = use_alpha;
is_good = true;
}
vk2d::_internal::FontResourceImplBase::~FontResourceImplBase()
{}
vk2d::ResourceStatus vk2d::_internal::FontResourceImplBase::GetStatus()
{
if( !is_good ) return vk2d::ResourceStatus::FAILED_TO_LOAD;
auto local_status = status.load();
if( local_status == vk2d::ResourceStatus::UNDETERMINED ) {
if( load_function_run_fence.IsSet() ) {
// "texture_resource" is set by the MTLoad() function so we can access it
// without further mutex locking. ( "load_function_run_fence" is set )
status = local_status = texture_resource->GetStatus();
}
}
return local_status;
}
vk2d::ResourceStatus vk2d::_internal::FontResourceImplBase::WaitUntilLoaded(
std::chrono::nanoseconds timeout
)
{
if( timeout == std::chrono::nanoseconds::max() ) {
return WaitUntilLoaded( std::chrono::steady_clock::time_point::max() );
}
return WaitUntilLoaded( std::chrono::steady_clock::now() + timeout );
}
vk2d::ResourceStatus vk2d::_internal::FontResourceImplBase::WaitUntilLoaded(
std::chrono::steady_clock::time_point timeout
)
{
// Make sure timeout is in the future.
assert( timeout == std::chrono::steady_clock::time_point::max() ||
timeout + std::chrono::seconds( 5 ) >= std::chrono::steady_clock::now() );
if( !is_good ) return vk2d::ResourceStatus::FAILED_TO_LOAD;
auto local_status = status.load();
if( local_status == vk2d::ResourceStatus::UNDETERMINED ) {
if( load_function_run_fence.Wait( timeout ) ) {
status = local_status = texture_resource->WaitUntilLoaded( timeout );
}
}
return local_status;
}
bool vk2d::_internal::FontResourceImplBase::MTLoad(
vk2d::_internal::ThreadPrivateResource * thread_resource
)
{
// TODO: additional parameters:
// From raw file.
assert( thread_resource );
assert( my_interface->impl->GetFilePaths().size() );
auto loader_thread_resource = static_cast<vk2d::_internal::ThreadLoaderResource*>( thread_resource );
auto instance = loader_thread_resource->GetInstance();
auto path_str = my_interface->impl->GetFilePaths()[ 0 ].string();
auto max_texture_size = instance->GetVulkanPhysicalDeviceProperties().limits.maxImageDimension2D;
auto min_texture_size = std::min( uint32_t( 128 ), max_texture_size );
// average_to_max_weight variable is used to estimate glyph space requirements on atlas textures.
// 0 sets the estimation to average size, 1 sets the estimation to max weights. Default is 0.05
// which should give enough space in the atlas to contain all glyphs in
auto average_to_max_weight = 0.05;
auto total_glyph_count = uint64_t( 0 );
auto maximum_glyph_size = glm::dvec2( 0.0, 0.0 );
auto maximum_glyph_bitmap_size = glm::dvec2( 0.0, 0.0 );
auto maximum_glyph_bitmap_occupancy_size = glm::dvec2( 0.0, 0.0 );
auto average_glyph_bitmap_occupancy_size = glm::dvec2( 0.0, 0.0 );
if( my_interface->impl->IsFromFile() ) {
// Try to load from file.
// Get amount of faces in the file
uint32_t face_count = 0;
{
FT_Face face {};
auto ft_error = FT_New_Face(
loader_thread_resource->GetFreeTypeInstance(),
path_str.c_str(),
-1,
&face
);
switch( ft_error ) {
case FT_Err_Ok:
// All good
face_count = uint32_t( face->num_faces );
FT_Done_Face( face );
break;
case FT_Err_Cannot_Open_Resource:
// Cannot open file error
instance->Report(
vk2d::ReportSeverity::NON_CRITICAL_ERROR,
std::string( "Cannot load font: File not found: " ) + path_str
);
return false;
case FT_Err_Unknown_File_Format:
// Unknown file format error
instance->Report(
vk2d::ReportSeverity::NON_CRITICAL_ERROR,
std::string( "Cannot load font: Unknown file format: " ) + path_str
);
return false;
default:
// Other errors
instance->Report(
vk2d::ReportSeverity::NON_CRITICAL_ERROR,
std::string( "Cannot load font: " ) + path_str
);
return false;
}
}
assert( !face_infos.size() ); // If hit, this function was called twice for some reason, should never happen.
face_infos.clear();
face_infos.resize( face_count );
for( uint32_t i = 0; i < face_count; ++i ) {
FT_Face face {};
{
auto ft_error = FT_New_Face(
loader_thread_resource->GetFreeTypeInstance(),
path_str.c_str(),
i,
&face
);
if( ft_error ) {
instance->Report(
vk2d::ReportSeverity::NON_CRITICAL_ERROR,
std::string( "Cannot load font: " ) + path_str
);
return false;
}
}
{
auto ft_error = FT_Set_Pixel_Sizes(
face,
0,
glyph_texel_size
);
if( ft_error ) {
instance->Report(
vk2d::ReportSeverity::NON_CRITICAL_ERROR,
std::string( "Cannot load font: " ) + path_str
);
return false;
}
}
// Get glyph sizes
total_glyph_count += uint64_t( face->num_glyphs ) + 1;
for( decltype( face->num_glyphs ) i = 0; i < face->num_glyphs; ++i ) {
auto ft_load_error = FT_Load_Glyph( face, FT_UInt( i ), FT_LOAD_DEFAULT );
if( ft_load_error ) {
instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot load font, cannot load glyph for bitmap metrics!" );
return false;
}
auto glyph_size =
glm::dvec2(
double( face->glyph->metrics.width ),
double( face->glyph->metrics.height )
);
auto glyph_bitmap_size =
glm::dvec2(
double( face->glyph->bitmap.width ),
double( face->glyph->bitmap.rows )
);
auto glyph_bitmap_space_occupancy =
glm::dvec2(
double( face->glyph->bitmap.width + glyph_atlas_padding ),
double( face->glyph->bitmap.rows + glyph_atlas_padding )
);
maximum_glyph_size.x = std::max( maximum_glyph_size.x, glyph_size.x );
maximum_glyph_size.y = std::max( maximum_glyph_size.y, glyph_size.y );
maximum_glyph_bitmap_size.x = std::max( maximum_glyph_bitmap_size.x, glyph_bitmap_size.x );
maximum_glyph_bitmap_size.y = std::max( maximum_glyph_bitmap_size.y, glyph_bitmap_size.y );
maximum_glyph_bitmap_occupancy_size.x = std::max( maximum_glyph_bitmap_occupancy_size.x, glyph_bitmap_space_occupancy.x );
maximum_glyph_bitmap_occupancy_size.y = std::max( maximum_glyph_bitmap_occupancy_size.y, glyph_bitmap_space_occupancy.y );
average_glyph_bitmap_occupancy_size += glyph_bitmap_space_occupancy;
}
face_infos[ i ].face = face;
}
} else {
// Try to load from data.
assert( 0 && "Not implemented yet!" );
}
if( !total_glyph_count ) {
instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Cannot load font: Font contains no glyphs!" );
return false;
}
// Estimate appropriate atlas size.
// This code tries to find a tradeoff between texture size and amount so that 1 to 3 textures are
// created. For example if glyphs do not fit into 3 textures of size 512 * 512, a larger 1024 * 1024
// texture is created which should be able to contain the glyphs.
average_glyph_bitmap_occupancy_size += glm::dvec2( double( glyph_atlas_padding ), double( glyph_atlas_padding ) ) * 2.0;
average_glyph_bitmap_occupancy_size /= float( total_glyph_count );
{
auto estimated_glyph_space_requirements = average_glyph_bitmap_occupancy_size * ( 1.0 - average_to_max_weight ) + maximum_glyph_bitmap_occupancy_size * average_to_max_weight;
auto estimated_average_space_requirements = estimated_glyph_space_requirements / 1.5; // aim to have 1 to 4 textures to optimize memory usage
// auto estimated_average_space_requirements = estimated_glyph_space_requirements / 5.0; // aim to have 1 to 4 textures to optimize memory usage
atlas_size =
RoundToCeilingPowerOfTwo(
uint32_t(
std::sqrt(
std::ceil( estimated_average_space_requirements.x ) *
std::ceil( estimated_average_space_requirements.y ) *
double( total_glyph_count )
)
)
);
if( atlas_size > max_texture_size ) atlas_size = max_texture_size;
if( atlas_size < min_texture_size ) atlas_size = min_texture_size;
}
// Stop if we don't have any font's to work with.
if( !face_infos.size() ) {
instance->Report(
vk2d::ReportSeverity::NON_CRITICAL_ERROR,
std::string( "Internal error: Cannot load font: " ) + path_str
);
return false;
}
current_atlas_texture = CreateNewAtlasTexture();
auto glyph_size_bitmap_size_ratio_vector = maximum_glyph_bitmap_size / maximum_glyph_size;
auto glyph_size_bitmap_size_ratio = std::max( glyph_size_bitmap_size_ratio_vector.x, glyph_size_bitmap_size_ratio_vector.y );
// Process all glyphs from all font faces
for( size_t face_index = 0; face_index < face_infos.size(); ++face_index ) {
auto & face = face_infos[ face_index ];
face.glyph_infos.resize( face.face->num_glyphs );
for( auto glyph_index = 0; glyph_index < face.face->num_glyphs; ++glyph_index ) {
{
auto ft_load_error = FT_Load_Glyph( face.face, glyph_index, FT_LOAD_DEFAULT );
if( ft_load_error ) {
instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot load font, cannot load glyph!" );
return false;
}
}
{
auto ft_render_error = FT_Render_Glyph( face.face->glyph, use_alpha ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO );
if( ft_render_error ) {
instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot load font, cannot render glyph!" );
return false;
}
}
auto ft_glyph = face.face->glyph;
auto & ft_bitmap = ft_glyph->bitmap;
std::vector<vk2d::Color8> final_glyph_pixels( size_t( ft_bitmap.rows ) * size_t( ft_bitmap.width ) );
switch( ft_bitmap.pixel_mode ) {
case FT_PIXEL_MODE_MONO:
{
for( uint32_t y = 0; y < ft_bitmap.rows; ++y ) {
for( uint32_t x = 0; x < ft_bitmap.width; ++x ) {
auto texel_pos = y * ft_bitmap.width + x;
auto & dst = final_glyph_pixels[ texel_pos ];
auto src_bit = 7 - x % 8;
auto src_byte = ft_bitmap.buffer[ ( y * ft_bitmap.pitch ) + ( x / 8 ) ];
dst.r = ( ( src_byte >> src_bit ) & 1 ) * 255;
dst.g = dst.r;
dst.b = dst.r;
dst.a = dst.r;
}
}
}
break;
case FT_PIXEL_MODE_GRAY:
{
for( uint32_t y = 0; y < ft_bitmap.rows; ++y ) {
for( uint32_t x = 0; x < ft_bitmap.width; ++x ) {
auto texel_pos = y * ft_bitmap.width + x;
auto & dst = final_glyph_pixels[ texel_pos ];
auto src = ft_bitmap.buffer[ texel_pos ];
dst.r = src;
dst.g = src;
dst.b = src;
dst.a = src;
}
}
}
break;
case FT_PIXEL_MODE_BGRA:
{
for( uint32_t y = 0; y < ft_bitmap.rows; ++y ) {
for( uint32_t x = 0; x < ft_bitmap.width; ++x ) {
auto texel_pos = y * ft_bitmap.width + x;
auto & dst = final_glyph_pixels[ texel_pos ];
auto src = &ft_bitmap.buffer[ texel_pos * 4 ];
dst.r = src[ 2 ];
dst.g = src[ 1 ];
dst.b = src[ 0 ];
dst.a = src[ 3 ];
}
}
}
break;
default:
// Unsupported
instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot load font, Unsupported pixel format!" );
return false;
break;
}
// Attach rendered glyph to final texture atlas.
auto atlas_location = AttachGlyphToAtlas(
face.face->glyph,
glyph_atlas_padding,
final_glyph_pixels
);
if( !atlas_location.atlas_ptr ) {
instance->Report(
vk2d::ReportSeverity::NON_CRITICAL_ERROR,
"Internal error: Cannot create font, cannot copy glyph image to font texture atlas!"
);
return false;
}
// Create glyph info structure for the glyph
{
vk2d::Rect2f uv_coords = {
float( atlas_location.location.top_left.x ) / float( atlas_size ),
float( atlas_location.location.top_left.y ) / float( atlas_size ),
float( atlas_location.location.bottom_right.x ) / float( atlas_size ),
float( atlas_location.location.bottom_right.y ) / float( atlas_size )
};
auto & metrics = face.face->glyph->metrics;
auto glyph_size = glm::dvec2( metrics.width, metrics.height ) * glyph_size_bitmap_size_ratio;
auto glyph_hori_top_left = glm::dvec2( metrics.horiBearingX, -metrics.horiBearingY ) * glyph_size_bitmap_size_ratio;
auto glyph_hori_bottom_right = glyph_hori_top_left + glyph_size;
auto glyph_vert_top_left = glm::dvec2( metrics.vertBearingX, metrics.vertBearingY ) * glyph_size_bitmap_size_ratio;
auto glyph_vert_bottom_right = glyph_vert_top_left + glyph_size;
auto hori_advance = metrics.horiAdvance * glyph_size_bitmap_size_ratio;
auto vert_advance = metrics.vertAdvance * glyph_size_bitmap_size_ratio;
vk2d::_internal::GlyphInfo glyph_info {};
glyph_info.face_index = uint32_t( face_index );
glyph_info.atlas_index = atlas_location.atlas_index;
glyph_info.uv_coords = uv_coords;
glyph_info.horisontal_coords.top_left = glm::vec2( float( glyph_hori_top_left.x ), float( glyph_hori_top_left.y ) );
glyph_info.horisontal_coords.bottom_right = glm::vec2( float( glyph_hori_bottom_right.x ), float( glyph_hori_bottom_right.y ) );
glyph_info.vertical_coords.top_left = glm::vec2( float( glyph_vert_top_left.x ), float( glyph_vert_top_left.y ) );
glyph_info.vertical_coords.bottom_right = glm::vec2( float( glyph_vert_bottom_right.x ), float( glyph_vert_bottom_right.y ) );
glyph_info.horisontal_advance = float( hori_advance );
glyph_info.vertical_advance = float( vert_advance );
face.glyph_infos[ glyph_index ] = glyph_info;
}
}
// Create character map and get fallback character
{
FT_ULong charcode = {};
FT_UInt gindex = {};
FT_ULong fallback_glyph_index = {};
charcode = FT_Get_First_Char( face.face, &gindex );
fallback_glyph_index = gindex;
while( gindex != 0 ) {
face.charmap[ uint32_t( charcode ) ] = uint32_t( gindex );
charcode = FT_Get_Next_Char( face.face, charcode, &gindex );
}
if( auto f = FT_Get_Char_Index( face.face, FT_ULong( fallback_character ) ) ) {
fallback_glyph_index = f;
}
face.fallback_glyph_index = fallback_glyph_index;
}
}
// Destroy font faces, we don't need them anymore.
for( auto & f : face_infos ) {
FT_Done_Face( f.face );
f.face = nullptr;
}
// Everything is baked into the atlas, create texture resource to store it.
{
std::vector<const std::vector<vk2d::Color8>*> texture_data_array( atlas_textures.size() );
for( size_t i = 0; i < atlas_textures.size(); ++i ) {
texture_data_array[ i ] = &atlas_textures[ i ]->data;
}
texture_resource = resource_manager->CreateArrayTextureResource(
glm::uvec2( atlas_size, atlas_size ),
texture_data_array,
my_interface
);
if( !texture_resource ) {
instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot create font, cannot create texture resource for font!" );
return false;
}
}
return true;
}
void vk2d::_internal::FontResourceImplBase::MTUnload(
vk2d::_internal::ThreadPrivateResource * thread_resource
)
{
// Make sure font faces are destroyed.
for( auto f : face_infos ) {
FT_Done_Face( f.face );
}
face_infos.clear();
}
vk2d::Rect2f vk2d::_internal::FontResourceImplBase::CalculateRenderedSize(
std::string_view text,
float kerning,
glm::vec2 scale,
bool vertical,
uint32_t font_face,
bool wait_for_resource_load
)
{
if( std::size( text ) <= 0 ) return {};
if( wait_for_resource_load ) {
WaitUntilLoaded( std::chrono::nanoseconds::max() );
} else {
if( GetStatus() == vk2d::ResourceStatus::UNDETERMINED ) return {};
}
if( !FaceExists( font_face ) ) return {};
vk2d::Rect2f ret {};
float advance {};
if( vertical ) {
// Vertical text
// First letter sets defaults
auto first_gi = GetGlyphInfo( font_face, text[ 0 ] );
ret.top_left.x = first_gi->vertical_coords.top_left.x;
ret.bottom_right.x = first_gi->vertical_coords.bottom_right.x;
if( std::size( text ) > 1 ) {
advance += first_gi->vertical_advance;
}
for( size_t i = 1; i < std::size( text ) - 1; ++i ) {
// Middle letters are spaced by "advance" value
auto gi = GetGlyphInfo( font_face, text[ i ] );
ret.top_left.x = std::min( ret.top_left.x, gi->vertical_coords.top_left.x );
ret.bottom_right.x = std::max( ret.bottom_right.x, gi->vertical_coords.bottom_right.x );
advance += kerning + gi->vertical_advance;
}
// Need to get the size of the last letter, not the "advance"
auto last_gi = GetGlyphInfo( font_face, text.back() );
ret.top_left.x = std::min( ret.top_left.x, last_gi->vertical_coords.top_left.x );
ret.bottom_right.x = std::max( ret.bottom_right.x, last_gi->vertical_coords.bottom_right.x );
ret.top_left.y = first_gi->vertical_coords.top_left.y;
ret.bottom_right.y = advance + last_gi->vertical_coords.bottom_right.y;
} else {
// Horisontal text
// First letter sets defaults
auto first_gi = GetGlyphInfo( font_face, text[ 0 ] );
ret.top_left.y = first_gi->horisontal_coords.top_left.y;
ret.bottom_right.y = first_gi->horisontal_coords.bottom_right.y;
if( std::size( text ) > 1 ) {
advance += first_gi->horisontal_advance;
}
for( size_t i = 1; i < std::size( text ) - 1; ++i ) {
// Middle letters are spaced by "advance" value
auto gi = GetGlyphInfo( font_face, text[ i ] );
ret.top_left.y = std::min( ret.top_left.y, gi->horisontal_coords.top_left.y );
ret.bottom_right.y = std::max( ret.bottom_right.y, gi->horisontal_coords.bottom_right.y );
advance += kerning + gi->horisontal_advance;
}
// Need to get the size of the last letter, not the "advance"
auto last_gi = GetGlyphInfo( font_face, text.back() );
ret.top_left.y = std::min( ret.top_left.y, last_gi->horisontal_coords.top_left.y );
ret.bottom_right.y = std::max( ret.bottom_right.y, last_gi->horisontal_coords.bottom_right.y );
ret.top_left.x = first_gi->horisontal_coords.top_left.x;
ret.bottom_right.x = advance + last_gi->horisontal_coords.bottom_right.x;
}
ret.top_left *= scale;
ret.bottom_right *= scale;
return ret;
}
bool vk2d::_internal::FontResourceImplBase::FaceExists(
uint32_t font_face
) const
{
if( size_t( font_face ) < face_infos.size() ) {
return true;
}
return false;
}
vk2d::TextureResource * vk2d::_internal::FontResourceImplBase::GetTextureResource()
{
if( GetStatus() == vk2d::ResourceStatus::LOADED ) {
return texture_resource;
}
return {};
}
const vk2d::_internal::GlyphInfo * vk2d::_internal::FontResourceImplBase::GetGlyphInfo(
uint32_t font_face,
uint32_t character
) const
{
auto & face_info = face_infos[ font_face ];
auto & charmap = face_info.charmap;
auto glyph_it = charmap.find( character );
auto glyph_index = uint32_t( 0 );
if( glyph_it != charmap.end() ) {
glyph_index = glyph_it->second;
} else {
glyph_index = face_info.fallback_glyph_index;
}
return &face_info.glyph_infos[ glyph_index ];
}
bool vk2d::_internal::FontResourceImplBase::IsGood() const
{
return is_good;
}
vk2d::_internal::FontResourceImplBase::AtlasTexture * vk2d::_internal::FontResourceImplBase::CreateNewAtlasTexture()
{
auto new_atlas_texture = std::make_unique<vk2d::_internal::FontResourceImplBase::AtlasTexture>();
new_atlas_texture->data.resize( size_t( atlas_size ) * size_t( atlas_size ) );
new_atlas_texture->index = uint32_t( atlas_textures.size() );
std::memset( new_atlas_texture->data.data(), 0, new_atlas_texture->data.size() * sizeof( vk2d::Color8 ) );
auto new_atlas_texture_ptr = new_atlas_texture.get();
atlas_textures.push_back( std::move( new_atlas_texture ) );
return new_atlas_texture_ptr;
}
vk2d::_internal::FontResourceImplBase::AtlasLocation vk2d::_internal::FontResourceImplBase::ReserveSpaceForGlyphFromAtlasTextures(
FT_GlyphSlot glyph,
uint32_t glyph_atlas_padding
)
{
assert( current_atlas_texture );
auto FindLocationInAtlasTexture =[](
vk2d::_internal::FontResourceImplBase::AtlasTexture * atlas_texture,
FT_GlyphSlot glyph,
uint32_t atlas_size,
uint32_t glyph_atlas_padding
) -> vk2d::_internal::FontResourceImplBase::AtlasLocation
{
uint32_t glyph_width = uint32_t( glyph->bitmap.width ) + glyph_atlas_padding;
uint32_t glyph_height = uint32_t( glyph->bitmap.rows ) + glyph_atlas_padding;
// Find space in the current atlas texture.
if( atlas_texture->previous_row_height + glyph_height + glyph_atlas_padding < atlas_size ) {
// Fits height wise.
if( atlas_texture->current_write_location + glyph_width + glyph_atlas_padding < atlas_size ) {
// Fits width wise, fits completely.
vk2d::_internal::FontResourceImplBase::AtlasLocation new_glyph_location {};
new_glyph_location.atlas_ptr = atlas_texture;
new_glyph_location.atlas_index = atlas_texture->index;
new_glyph_location.location.top_left = {
atlas_texture->current_write_location + glyph_atlas_padding,
atlas_texture->previous_row_height + glyph_atlas_padding
};
new_glyph_location.location.bottom_right =
new_glyph_location.location.top_left +
glm::uvec2( uint32_t( glyph->bitmap.width ), uint32_t( glyph->bitmap.rows ) );
// update current row height and write locations before returning the result.
atlas_texture->current_row_height = std::max( atlas_texture->current_row_height, glyph_height );
atlas_texture->current_write_location += glyph_width;
return new_glyph_location;
}
// Does not fit width wise, go to the next row.
atlas_texture->previous_row_height += atlas_texture->current_row_height;
atlas_texture->current_row_height = 0;
atlas_texture->current_write_location = 0;
// Check height again.
if( atlas_texture->previous_row_height + glyph_height + glyph_atlas_padding < atlas_size ) {
// Fits height wise.
if( atlas_texture->current_write_location + glyph_width + glyph_atlas_padding < atlas_size ) {
// Fits width wise.
vk2d::_internal::FontResourceImplBase::AtlasLocation new_glyph_location {};
new_glyph_location.atlas_ptr = atlas_texture;
new_glyph_location.atlas_index = atlas_texture->index;
new_glyph_location.location.top_left = {
atlas_texture->current_write_location + glyph_atlas_padding,
atlas_texture->previous_row_height + glyph_atlas_padding
};
new_glyph_location.location.bottom_right =
new_glyph_location.location.top_left +
glm::uvec2( uint32_t( glyph->bitmap.width ), uint32_t( glyph->bitmap.rows ) );
// update current row height and write locations before returning the result.
atlas_texture->current_row_height = std::max( atlas_texture->current_row_height, glyph_height );
atlas_texture->current_write_location += glyph_width;
return new_glyph_location;
}
// Does not fit width wise to a new row, this would only happen if a single
// face glyph is too large to fit into a single atlas. This is an error.
assert( 0 && "Glyph too big" );
return {};
}
// Does not fit to a new row, need a new atlas texture
return {};
}
// Does not fit at all, need a new atlas texture.
return {};
};
auto new_location = FindLocationInAtlasTexture(
current_atlas_texture,
glyph,
atlas_size,
glyph_atlas_padding
);
if( !new_location.atlas_ptr ) {
// Not enough space found, create new atlas and try again.
current_atlas_texture = CreateNewAtlasTexture();
if( !current_atlas_texture ) {
// Failed to create new atlas texture.
resource_manager->GetInstance()->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot create font, cannot create new atlas texture for font!" );
return {};
}
// Got new atlas texture, retry finding space in it.
new_location = FindLocationInAtlasTexture(
current_atlas_texture,
glyph,
atlas_size,
glyph_atlas_padding
);
if( !new_location.atlas_ptr ) {
// Still could not find enough space, a single font face glyph is too large
// to fit entire atlas, this should not happen so we raise an error.
resource_manager->GetInstance()->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot create font, a single glyph wont fit into a new atlas." );
return {};
}
return new_location;
}
return new_location;
}
void vk2d::_internal::FontResourceImplBase::CopyGlyphTextureToAtlasLocation(
AtlasLocation atlas_location,
const std::vector<vk2d::Color8> & converted_texture_data )
{
assert( atlas_location.atlas_ptr );
auto glyph_width = atlas_location.location.bottom_right.x - atlas_location.location.top_left.x;
auto glyph_height = atlas_location.location.bottom_right.y - atlas_location.location.top_left.y;
glm::uvec2 location = atlas_location.location.top_left;
for( uint32_t gy = 0; gy < glyph_height; ++gy ) {
for( uint32_t gx = 0; gx < glyph_width; ++gx ) {
auto ax = location.x + gx;
auto ay = location.y + gy;
atlas_location.atlas_ptr->data[ ay * atlas_size + ax ] = converted_texture_data[ gy * glyph_width + gx ];
}
}
}
vk2d::_internal::FontResourceImplBase::AtlasLocation vk2d::_internal::FontResourceImplBase::AttachGlyphToAtlas(
FT_GlyphSlot glyph,
uint32_t glyph_atlas_padding,
const std::vector<vk2d::Color8> & converted_texture_data )
{
auto atlas_location = ReserveSpaceForGlyphFromAtlasTextures(
glyph,
glyph_atlas_padding
);
if( atlas_location.atlas_ptr ) {
CopyGlyphTextureToAtlasLocation(
atlas_location,
converted_texture_data
);
return atlas_location;
} else {
resource_manager->GetInstance()->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot create font, cannot attach glyph to atlas texture!" );
return {};
}
}
uint32_t vk2d::_internal::RoundToCeilingPowerOfTwo( uint32_t value )
{
value--;
value |= value >> 1;
value |= value >> 2;
value |= value >> 4;
value |= value >> 8;
value |= value >> 16;
value++;
return value;
}
| 32.364909
| 177
| 0.683241
|
Noxagonal
|
cf1375d321ab6dff3ca69728686c391b0bb9f4a4
| 827
|
cpp
|
C++
|
UVa 10585 - Center of symmetry/sample/10585 - Center of symmetry.cpp
|
tadvi/uva
|
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
|
[
"MIT"
] | 1
|
2020-11-24T03:17:21.000Z
|
2020-11-24T03:17:21.000Z
|
UVa 10585 - Center of symmetry/sample/10585 - Center of symmetry.cpp
|
tadvi/uva
|
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
|
[
"MIT"
] | null | null | null |
UVa 10585 - Center of symmetry/sample/10585 - Center of symmetry.cpp
|
tadvi/uva
|
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
|
[
"MIT"
] | 1
|
2021-04-11T16:22:31.000Z
|
2021-04-11T16:22:31.000Z
|
#include <stdio.h>
#include <map>
using namespace std;
long long x[10000], y[10000], avex, avey, n;
void solve() {
if(avex%n || avey%n) {
puts("no");
return;
}
avex /= n, avey /= n;
map<long long, int> r;
int i;
for(i = 0; i < n; i++)
r[x[i]*100000000+y[i]] = 1;
long long xx, yy;
for(i = 0; i < n; i++) {
xx = 2*avex - x[i];
yy = 2*avey - y[i];
if(r[x[i]*100000000+y[i]] == 0) {
puts("no");
return;
}
}
puts("yes");
}
int main() {
int t, i;
scanf("%d", &t);
while(t--) {
scanf("%lld", &n);
avex = 0, avey = 0;
for(i = 0; i < n; i++) {
scanf("%lld %lld", &x[i], &y[i]);
avex += x[i], avey += y[i];
}
solve();
}
return 0;
}
| 20.675
| 45
| 0.385732
|
tadvi
|
cf1485d6b4456ed43ad3558b0191dc7ba14f6957
| 162
|
cpp
|
C++
|
src/utils/Application.cpp
|
mgeorgoulopoulos/gencut
|
e9751c0d04816311d5460d14a88eaa1fcbe6f40d
|
[
"MIT"
] | null | null | null |
src/utils/Application.cpp
|
mgeorgoulopoulos/gencut
|
e9751c0d04816311d5460d14a88eaa1fcbe6f40d
|
[
"MIT"
] | null | null | null |
src/utils/Application.cpp
|
mgeorgoulopoulos/gencut
|
e9751c0d04816311d5460d14a88eaa1fcbe6f40d
|
[
"MIT"
] | null | null | null |
#include "Application.h"
#include "GenomeModel.h"
void Application::execute() {
GenomeModel model;
model.load(arguments.genomeModelFilename, geneRegistry);
}
| 18
| 57
| 0.771605
|
mgeorgoulopoulos
|
cf16edca209b988b8b8becbb6e49ecf128e1f2b8
| 5,119
|
cxx
|
C++
|
src/curl/Request.cxx
|
CM4all/libcommon
|
fba0eae725b0e7a6cf93ff0be231d90e2c0aa04e
|
[
"BSD-2-Clause"
] | 13
|
2017-06-30T15:38:21.000Z
|
2022-03-11T06:49:17.000Z
|
src/curl/Request.cxx
|
CM4all/libcommon
|
fba0eae725b0e7a6cf93ff0be231d90e2c0aa04e
|
[
"BSD-2-Clause"
] | 2
|
2017-10-29T18:28:28.000Z
|
2020-08-20T00:43:21.000Z
|
src/curl/Request.cxx
|
CM4all/libcommon
|
fba0eae725b0e7a6cf93ff0be231d90e2c0aa04e
|
[
"BSD-2-Clause"
] | 6
|
2017-10-29T11:38:13.000Z
|
2021-10-12T00:36:38.000Z
|
/*
* Copyright 2008-2021 Max Kellermann <max.kellermann@gmail.com>
*
* 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.
*
* 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
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Request.hxx"
#include "Global.hxx"
#include "Handler.hxx"
#include "util/RuntimeError.hxx"
#include "util/StringStrip.hxx"
#include "util/StringView.hxx"
#include "util/CharUtil.hxx"
#include "version.h"
#include <curl/curl.h>
#include <algorithm>
#include <cassert>
#include <string.h>
CurlRequest::CurlRequest(CurlGlobal &_global, CurlEasy _easy,
CurlResponseHandler &_handler)
:global(_global), handler(_handler), easy(std::move(_easy))
{
SetupEasy();
}
CurlRequest::CurlRequest(CurlGlobal &_global,
CurlResponseHandler &_handler)
:global(_global), handler(_handler)
{
SetupEasy();
}
CurlRequest::~CurlRequest() noexcept
{
FreeEasy();
}
void
CurlRequest::SetupEasy()
{
error_buffer[0] = 0;
easy.SetPrivate((void *)this);
easy.SetUserAgent(PACKAGE " " VERSION);
easy.SetHeaderFunction(_HeaderFunction, this);
easy.SetWriteFunction(WriteFunction, this);
easy.SetErrorBuffer(error_buffer);
easy.SetNoProgress();
easy.SetNoSignal();
easy.SetConnectTimeout(10);
}
void
CurlRequest::Start()
{
assert(!registered);
global.Add(*this);
registered = true;
}
void
CurlRequest::Stop() noexcept
{
if (!registered)
return;
global.Remove(*this);
registered = false;
}
void
CurlRequest::FreeEasy() noexcept
{
if (!easy)
return;
Stop();
easy = nullptr;
}
void
CurlRequest::Resume() noexcept
{
assert(registered);
easy.Unpause();
global.InvalidateSockets();
}
void
CurlRequest::FinishHeaders()
{
if (state != State::HEADERS)
return;
state = State::BODY;
long status = 0;
easy.GetInfo(CURLINFO_RESPONSE_CODE, &status);
handler.OnHeaders(status, std::move(headers));
}
void
CurlRequest::FinishBody()
{
FinishHeaders();
if (state != State::BODY)
return;
state = State::CLOSED;
handler.OnEnd();
}
void
CurlRequest::Done(CURLcode result) noexcept
{
Stop();
try {
if (result != CURLE_OK) {
StripRight(error_buffer);
const char *msg = error_buffer;
if (*msg == 0)
msg = curl_easy_strerror(result);
throw FormatRuntimeError("CURL failed: %s", msg);
}
FinishBody();
} catch (...) {
state = State::CLOSED;
handler.OnError(std::current_exception());
}
}
[[gnu::pure]]
static bool
IsResponseBoundaryHeader(StringView s) noexcept
{
return s.size > 5 && s.StartsWith("HTTP/");
}
inline void
CurlRequest::HeaderFunction(StringView s) noexcept
{
if (state > State::HEADERS)
return;
if (IsResponseBoundaryHeader(s)) {
/* this is the boundary to a new response, for example
after a redirect */
headers.clear();
return;
}
const char *header = s.data;
const char *end = StripRight(header, header + s.size);
const char *value = s.Find(':');
if (value == nullptr)
return;
std::string name(header, value);
std::transform(name.begin(), name.end(), name.begin(), ToLowerASCII);
/* skip the colon */
++value;
/* strip the value */
value = StripLeft(value, end);
end = StripRight(value, end);
headers.emplace(std::move(name), std::string(value, end));
}
std::size_t
CurlRequest::_HeaderFunction(char *ptr, std::size_t size, std::size_t nmemb,
void *stream) noexcept
{
CurlRequest &c = *(CurlRequest *)stream;
size *= nmemb;
c.HeaderFunction({ptr, size});
return size;
}
inline std::size_t
CurlRequest::DataReceived(const void *ptr, std::size_t received_size) noexcept
{
assert(received_size > 0);
try {
FinishHeaders();
handler.OnData({ptr, received_size});
return received_size;
} catch (CurlResponseHandler::Pause) {
return CURL_WRITEFUNC_PAUSE;
}
}
std::size_t
CurlRequest::WriteFunction(char *ptr, std::size_t size, std::size_t nmemb,
void *stream) noexcept
{
CurlRequest &c = *(CurlRequest *)stream;
size *= nmemb;
if (size == 0)
return 0;
return c.DataReceived(ptr, size);
}
| 20.808943
| 78
| 0.714202
|
CM4all
|
cf197e0fc95906c485da135c45136ca4783a1cd7
| 3,272
|
cpp
|
C++
|
src/script/scriptlistingdialog.cpp
|
nilsding/IrrerrC
|
0ff273e96c7a2f731ae23e17c9d58b872db14ebc
|
[
"BSD-2-Clause"
] | 1
|
2016-06-14T14:21:27.000Z
|
2016-06-14T14:21:27.000Z
|
src/script/scriptlistingdialog.cpp
|
nilsding/IrrerrC
|
0ff273e96c7a2f731ae23e17c9d58b872db14ebc
|
[
"BSD-2-Clause"
] | null | null | null |
src/script/scriptlistingdialog.cpp
|
nilsding/IrrerrC
|
0ff273e96c7a2f731ae23e17c9d58b872db14ebc
|
[
"BSD-2-Clause"
] | null | null | null |
#include "scriptlistingdialog.h"
#include "ui_scriptlistingdialog.h"
ScriptListingDialog::ScriptListingDialog(QWidget *parent) :
QDialog(parent),
_ui(new Ui::ScriptListingDialog),
_scriptDirModel(new QFileSystemModel), _currentScript(0)
{
_scriptDir = QFileInfo(_SETTINGS.fileName()).absolutePath() + "/scripts";
QDir d(_scriptDir);
if (!d.exists()) {
d.mkpath(_scriptDir);
}
connect(_scriptDirModel, &QFileSystemModel::directoryLoaded, this, [=](const QString &path) {
_ui->qlvScriptList->setRootIndex(_scriptDirModel->index(path));
QDir d(path);
d.setFilter(QDir::NoDotAndDotDot | QDir::Files);
if (d.count() < 1) {
_ui->qlScriptName->setText("");
_ui->qlAuthor->setText("");
_ui->qlDescription->setText(tr("You currently don't have any scripts installed."));
_qpbEdit->setEnabled(false);
if (_currentScript) {
_currentScript->deleteLater();
_currentScript = 0;
}
} else {
if (!_currentScript) {
_ui->qlDescription->setText(tr("Select a script from the list on the left."));
_qpbEdit->setEnabled(false);
}
}
});
_ui->setupUi(this);
_qpbEdit = _ui->qdbbButtons->addButton(tr("&Edit"), QDialogButtonBox::ActionRole);
_qpbEdit->setEnabled(false);
_ui->qlScriptName->setText("");
_ui->qlAuthor->setText("");
_ui->qlDescription->setText("");
_scriptDirModel->setRootPath(_scriptDir);
_scriptDirModel->setFilter(QDir::NoDotAndDotDot | QDir::Files);
QStringList filters;
filters << "*.js";
_scriptDirModel->setNameFilters(filters);
_scriptDirModel->setNameFilterDisables(false);
_ui->qlvScriptList->setModel(_scriptDirModel);
}
ScriptListingDialog::~ScriptListingDialog()
{
_currentScript->deleteLater();
delete _ui;
}
void ScriptListingDialog::on_qdbbButtons_clicked(QAbstractButton *button)
{
auto buttons = _ui->qdbbButtons->buttons();
QAbstractButton *b = 0;
for (auto btn : buttons) {
if (btn == button) {
b = btn;
break;
}
}
if (_ui->qdbbButtons->buttonRole(b) == QDialogButtonBox::ActionRole) {
QUrl url;
url.setPath(_scriptDirModel->filePath(_ui->qlvScriptList->selectionModel()->selectedIndexes().first()));
url.setScheme(QLatin1String("file"));
QDesktopServices::openUrl(url);
}
}
void ScriptListingDialog::on_qpbOpenScriptDirectory_clicked()
{
QDesktopServices::openUrl(QUrl::fromLocalFile(_scriptDir));
}
void ScriptListingDialog::on_qpbGetMoreScripts_clicked()
{
QDesktopServices::openUrl(QUrl("http://irc.rrerr.net/client/scripts"));
}
void ScriptListingDialog::on_qlvScriptList_clicked(const QModelIndex &index)
{
if (_currentScript) {
_currentScript->deleteLater();
}
_currentScript = new NScript(_scriptDirModel->filePath(index), this);
_ui->qlScriptName->setText(_currentScript->scriptName().toHtmlEscaped());
_ui->qlAuthor->setText(tr("Author: <b>%1</b>").arg(_currentScript->author().toHtmlEscaped()));
_ui->qlDescription->setText(_currentScript->description());
_qpbEdit->setEnabled(true);
}
| 32.72
| 112
| 0.654951
|
nilsding
|
cf19d1a9499b20b8b71a2f80ec54d258e801780e
| 3,505
|
cpp
|
C++
|
src/wbdl/wbdl.cpp
|
DAlexis/wb-display-lib
|
67317051282d69904774d10553c33ed6c2dedb56
|
[
"MIT"
] | null | null | null |
src/wbdl/wbdl.cpp
|
DAlexis/wb-display-lib
|
67317051282d69904774d10553c33ed6c2dedb56
|
[
"MIT"
] | null | null | null |
src/wbdl/wbdl.cpp
|
DAlexis/wb-display-lib
|
67317051282d69904774d10553c33ed6c2dedb56
|
[
"MIT"
] | null | null | null |
#include "wbdl.hpp"
#include <algorithm>
using namespace wbdl;
//////////////////////////
// FrameBuffer
void FrameBuffer::clearDirty()
{
dirtyX0 = 0;
dirtyY0 = 0;
dirtyX1 = 0;
dirtyY1 = 0;
}
bool FrameBuffer::isDirty()
{
return dirtyX0 != dirtyX1;
}
unsigned int FrameBuffer::bufferSize()
{
return width * height / 8;
}
void FrameBuffer::makePointDirty(unsigned int x, unsigned int y)
{
if (isDirty())
{
dirtyX0 = x; dirtyX1 = x+1;
dirtyY0 = y; dirtyY1 = y+1;
return;
}
if (x < dirtyX0)
dirtyX0 = x;
else if (x+1 > dirtyX1)
dirtyX1 = x+1;
if (y < dirtyY0)
dirtyY0 = y;
else if (y+1 > dirtyY1)
dirtyY1 = y+1;
}
void FrameBuffer::putPixelNoDirty(int x, int y, Color c)
{
if (x < 0 || y < 0 || x >= int(width) || y >= int(height))
return;
unsigned int index;
switch(order)
{
case BitsOrder::vertical:
index = x + (y / 8) * width;
if (c == Color::white)
buffer[index] |= 1 << (y%8);
else
buffer[index] &= ~(1 << (y%8));
break;
}
}
Color FrameBuffer::getPixel(int x, int y) const
{
if (x < 0 || y < 0 || x >= int(width) || y >= int(height))
return Color::black;
unsigned int index;
switch(order)
{
case BitsOrder::vertical:
index = x + (y / 8) * width;
return (buffer[index] & (1 << (y%8))) != 0 ? Color::white : Color::black;
}
return Color::black;
}
//////////////////////////
// Display
Display::Display(IDisplayDriver& driver, FrameBuffer& frameBuffer) :
m_driver(driver),
m_frameBuffer(frameBuffer)
{
}
void Display::updateScreen()
{
m_driver.updateScreen(m_frameBuffer);
m_frameBuffer.clearDirty();
}
void Display::putPixel(int x, int y, Color c)
{
m_frameBuffer.putPixelNoDirty(x, y, c);
m_frameBuffer.makePointDirty(x, y);
}
void Display::line(int x0, int y0, int x1, int y1, Color c)
{
m_frameBuffer.makePointDirty(x0, y0);
m_frameBuffer.makePointDirty(x1, y1);
/**
* It is a realization of Bresenham's line algorithm
* without floats
*/
int dx = (x0 < x1) ? (x1 - x0) : (x0 - x1);
int dy = (y0 < y1) ? (y1 - y0) : (y0 - y1);
int sx = (x0 < x1) ? 1 : -1;
int sy = (y0 < y1) ? 1 : -1;
int err = ((dx > dy) ? dx : -dy) / 2;
for(;;)
{
m_frameBuffer.putPixelNoDirty(x0, y0, c);
if (x0 == x1 && y0 == y1) {
break;
}
int oldErr = err;
if (oldErr > -dx)
{
err -= dy;
x0 += sx;
}
if (oldErr < dy)
{
err += dx;
y0 += sy;
}
}
}
void Display::circle(int x0, int y0, int r, Color c)
{
int x = 0;
int y = r;
int delta = 1 - 2 * r;
int error = 0;
while (x <= y)
{
m_frameBuffer.putPixelNoDirty(x0 + x, y0 + y, c);
m_frameBuffer.putPixelNoDirty(x0 + x, y0 - y, c);
m_frameBuffer.putPixelNoDirty(x0 - x, y0 + y, c);
m_frameBuffer.putPixelNoDirty(x0 - x, y0 - y, c);
m_frameBuffer.putPixelNoDirty(x0 + y, y0 + x, c);
m_frameBuffer.putPixelNoDirty(x0 + y, y0 - x, c);
m_frameBuffer.putPixelNoDirty(x0 - y, y0 + x, c);
m_frameBuffer.putPixelNoDirty(x0 - y, y0 - x, c);
error = 2 * (delta + y) - 1;
if ((delta < 0) && (error <= 0))
{
delta += 2 * ++x + 1;
continue;
}
error = 2 * (delta - x) - 1;
if ((delta > 0) && (error > 0))
{
delta += 1 - 2 * --y;
continue;
}
x++;
delta += 2 * (x - y);
y--;
}
}
int Display::left()
{
return 0;
}
int Display::right()
{
return m_frameBuffer.width-1;
}
int Display::top()
{
return 0;
}
int Display::bottom()
{
return m_frameBuffer.height-1;
}
int Display::centerX()
{
return m_frameBuffer.width / 2;
}
int Display::centerY()
{
return m_frameBuffer.height / 2;
}
| 17.26601
| 75
| 0.580884
|
DAlexis
|
cf224860179885ffaa17a8ab974eef5da9fd7ae7
| 1,625
|
hpp
|
C++
|
third_party/boost/simd/detail/dispatch/property_of.hpp
|
SylvainCorlay/pythran
|
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
|
[
"BSD-3-Clause"
] | 6
|
2018-02-25T22:23:33.000Z
|
2021-01-15T15:13:12.000Z
|
third_party/boost/simd/detail/dispatch/property_of.hpp
|
SylvainCorlay/pythran
|
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
|
[
"BSD-3-Clause"
] | null | null | null |
third_party/boost/simd/detail/dispatch/property_of.hpp
|
SylvainCorlay/pythran
|
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
|
[
"BSD-3-Clause"
] | 7
|
2017-12-12T12:36:31.000Z
|
2020-02-10T14:27:07.000Z
|
//==================================================================================================
/*!
@file
Defines the property_of meta-function
@copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
**/
//==================================================================================================
#ifndef BOOST_SIMD_DETAIL_DISPATCH_PROPERTY_OF_HPP_INCLUDED
#define BOOST_SIMD_DETAIL_DISPATCH_PROPERTY_OF_HPP_INCLUDED
#include <boost/simd/detail/dispatch/meta/scalar_of.hpp>
#include <boost/simd/detail/dispatch/detail/property_of.hpp>
#include <boost/simd/detail/nsm.hpp>
namespace boost { namespace dispatch
{
/*!
@ingroup group-hierarchy
@brief Retrieve the fundamental hierarchy of a Type
For any type @c T, returns the hierarchy describing the fundamental properties of any given
types. This Fundamental Hierarchy is computed by computing the hierarchy of the innermost
embedded scalar type of @c T.
@tparam T Type to categorize
@tparam Origin Type to store inside the generated hierarchy type
@par Models:
@metafunction
**/
template<typename T, typename Origin = T>
struct property_of
#if !defined(DOXYGEN_ONLY)
: ext::property_of<scalar_of_t<T>, typename std::remove_reference<Origin>::type>
#endif
{};
/*!
@ingroup group-hierarchy
Eager short-cut to boost::dispatch::property_of
**/
template<typename T, typename Origin = T>
using property_of_t = typename property_of<T,Origin>::type;
} }
#endif
| 30.092593
| 100
| 0.651077
|
SylvainCorlay
|
cf23785fa10c5955c4187c84d5583a29b1301d3d
| 577
|
cpp
|
C++
|
demos/glyph_paint/side_pane.cpp
|
RyanDraves/CPPurses
|
19cbdae2d18e702144659187ec989c486c714a0f
|
[
"MIT"
] | null | null | null |
demos/glyph_paint/side_pane.cpp
|
RyanDraves/CPPurses
|
19cbdae2d18e702144659187ec989c486c714a0f
|
[
"MIT"
] | null | null | null |
demos/glyph_paint/side_pane.cpp
|
RyanDraves/CPPurses
|
19cbdae2d18e702144659187ec989c486c714a0f
|
[
"MIT"
] | null | null | null |
#include "side_pane.hpp"
#include <cppurses/painter/color.hpp>
#include <cppurses/painter/glyph.hpp>
#include <cppurses/widget/widgets/text_display.hpp>
using namespace cppurses;
namespace demos {
namespace glyph_paint {
Side_pane::Side_pane() {
this->width_policy.fixed(16);
space1.wallpaper = L'─';
space2.wallpaper = L'─';
glyph_select.height_policy.preferred(6);
color_select_stack.height_policy.fixed(3);
show_glyph.height_policy.fixed(1);
show_glyph.set_alignment(Alignment::Center);
}
} // namespace glyph_paint
} // namespace demos
| 22.192308
| 51
| 0.734835
|
RyanDraves
|
cf240458e3e47526197c6cf80111a9ad1882045f
| 17,299
|
hpp
|
C++
|
bluetoe/attribute_handle.hpp
|
TorstenRobitzki/bluetoe
|
0f04ccefa4e9ba6a89bf4dfaa0dd62b8e3a46043
|
[
"MIT"
] | 138
|
2015-04-11T12:07:19.000Z
|
2022-02-11T13:22:36.000Z
|
bluetoe/attribute_handle.hpp
|
TorstenRobitzki/bluetoe
|
0f04ccefa4e9ba6a89bf4dfaa0dd62b8e3a46043
|
[
"MIT"
] | 60
|
2015-08-29T12:32:56.000Z
|
2022-03-25T07:20:21.000Z
|
bluetoe/attribute_handle.hpp
|
TorstenRobitzki/bluetoe
|
0f04ccefa4e9ba6a89bf4dfaa0dd62b8e3a46043
|
[
"MIT"
] | 34
|
2015-07-08T22:06:25.000Z
|
2021-12-15T13:17:42.000Z
|
#ifndef BLUETOE_ATTRIBUTE_HANDLE_HPP
#define BLUETOE_ATTRIBUTE_HANDLE_HPP
#include <bluetoe/meta_types.hpp>
#include <bluetoe/meta_tools.hpp>
#include <cstdint>
#include <cstdlib>
#include <cassert>
#include <algorithm>
namespace bluetoe {
namespace details {
struct attribute_handle_meta_type {};
struct attribute_handles_meta_type {};
}
/**
* @brief define the first attribute handle used by a characteristic or service
*
* If this option is given to a service, the service attribute will be assigned
* to the given handle value. For a characteristic, the Characteristic Declaration
* attribute will be assigned to the given handle value.
*
* All following attrbutes are assigned handles with a larger value.
*
* @sa attribute_handles
* @sa service
* @sa characteristic
*/
template < std::uint16_t AttributeHandleValue >
struct attribute_handle
{
/** @cond HIDDEN_SYMBOLS */
static constexpr std::uint16_t attribute_handle_value = AttributeHandleValue;
struct meta_type :
details::attribute_handle_meta_type,
details::valid_service_option_meta_type,
details::valid_characteristic_option_meta_type {};
/** @endcond */
};
/**
* @brief define the attributes handles for the characteristic declaration, characteristic
* value and optional, for a Client Characteristic Configuration descriptor.
*
* If the characteristic has no Client Characteristic Configuration descriptor, the CCCD
* parameter has to be 0. Value has to be larger than Declaration and CCCD has to larger
* than Value (or 0).
*
* @sa attribute_handle
* @sa characteristic
*/
template < std::uint16_t Declaration, std::uint16_t Value, std::uint16_t CCCD = 0x0000 >
struct attribute_handles
{
/** @cond HIDDEN_SYMBOLS */
static constexpr std::uint16_t declaration_handle = Declaration;
static constexpr std::uint16_t value_handle = Value;
static constexpr std::uint16_t cccd_handle = CCCD;
static_assert( value_handle > declaration_handle, "value handle has to be larger than declaration handle" );
static_assert( cccd_handle > declaration_handle || cccd_handle == 0, "CCCD handle has to be larger than declaration handle" );
static_assert( cccd_handle > value_handle || cccd_handle == 0, "CCCD handle has to be larger than value handle" );
struct meta_type :
details::attribute_handles_meta_type,
details::valid_characteristic_option_meta_type {};
/** @endcond */
};
template < typename ... Options >
class server;
template < typename ... Options >
class service;
template < typename ... Options >
class characteristic;
namespace details {
static constexpr std::uint16_t invalid_attribute_handle = 0;
static constexpr std::size_t invalid_attribute_index = ~0;
/*
* select one of attribute_handle< H > or attribute_handle< H, B, C >
*/
template < std::uint16_t Default, class, class >
struct select_attribute_handles
{
static constexpr std::uint16_t declaration_handle = Default;
static constexpr std::uint16_t value_handle = Default + 1;
static constexpr std::uint16_t cccd_handle = Default + 2;
};
template < std::uint16_t Default, std::uint16_t AttributeHandleValue, typename T >
struct select_attribute_handles< Default, attribute_handle< AttributeHandleValue >, T >
{
static constexpr std::uint16_t declaration_handle = AttributeHandleValue;
static constexpr std::uint16_t value_handle = AttributeHandleValue + 1;
static constexpr std::uint16_t cccd_handle = AttributeHandleValue + 2;
};
template < std::uint16_t Default, typename T, std::uint16_t Declaration, std::uint16_t Value, std::uint16_t CCCD >
struct select_attribute_handles< Default, T, attribute_handles< Declaration, Value, CCCD > >
{
static constexpr std::uint16_t declaration_handle = Declaration;
static constexpr std::uint16_t value_handle = Value;
static constexpr std::uint16_t cccd_handle = CCCD == 0 ? Value + 1 : CCCD;
};
template < std::uint16_t Default, std::uint16_t AttributeHandleValue, std::uint16_t Declaration, std::uint16_t Value, std::uint16_t CCCD >
struct select_attribute_handles< Default, attribute_handle< AttributeHandleValue >, attribute_handles< Declaration, Value, CCCD > >
{
static_assert( Declaration == Value, "either attribute_handle<> or attribute_handles<> can be used as characteristic<> option, not both." );
};
template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename ... Options >
struct characteristic_index_mapping
{
using characteristic_t = ::bluetoe::characteristic< Options... >;
using attribute_handles_t = select_attribute_handles< StartHandle,
typename find_by_meta_type< attribute_handle_meta_type, Options... >::type,
typename find_by_meta_type< attribute_handles_meta_type, Options... >::type
>;
static_assert( attribute_handles_t::declaration_handle >= StartHandle, "attribute_handle<> can only be used to create increasing attribute handles." );
static constexpr std::uint16_t end_handle = characteristic_t::number_of_attributes == 2
? attribute_handles_t::value_handle + 1
: attribute_handles_t::cccd_handle + ( characteristic_t::number_of_attributes - 2 );
static constexpr std::uint16_t end_index = StartIndex + characteristic_t::number_of_attributes;
static constexpr std::size_t declaration_position = 0;
static constexpr std::size_t value_position = 1;
static constexpr std::size_t cccd_position = 2;
static std::uint16_t characteristic_attribute_handle_by_index( std::size_t index )
{
const std::size_t relative_index = index - StartIndex;
assert( relative_index < characteristic_t::number_of_attributes );
switch ( relative_index )
{
case declaration_position:
return attribute_handles_t::declaration_handle;
break;
case value_position:
return attribute_handles_t::value_handle;
break;
case cccd_position:
return attribute_handles_t::cccd_handle;
break;
}
return relative_index - cccd_position + attribute_handles_t::cccd_handle;
}
static std::size_t characteristic_attribute_index_by_handle( std::uint16_t handle )
{
if ( handle <= attribute_handles_t::declaration_handle )
return StartIndex + declaration_position;
if ( handle <= attribute_handles_t::value_handle )
return StartIndex + value_position;
if ( handle <= attribute_handles_t::cccd_handle )
return StartIndex + cccd_position;
return StartIndex + cccd_position + handle - attribute_handles_t::cccd_handle;
}
};
template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename CharacteristicList >
struct interate_characteristic_index_mappings;
template < std::uint16_t StartHandle, std::uint16_t StartIndex >
struct interate_characteristic_index_mappings< StartHandle, StartIndex, std::tuple<> >
{
static std::uint16_t attribute_handle_by_index( std::size_t )
{
return invalid_attribute_handle;
}
static std::size_t attribute_index_by_handle( std::uint16_t )
{
return invalid_attribute_index;
}
static constexpr std::uint16_t last_characteristic_end_handle = StartHandle;
};
template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename Characteristics, typename ... Options >
using next_characteristic_mapping = interate_characteristic_index_mappings<
characteristic_index_mapping< StartHandle, StartIndex, Options... >::end_handle,
characteristic_index_mapping< StartHandle, StartIndex, Options... >::end_index,
Characteristics
>;
template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename ...Options, typename ... Chars >
struct interate_characteristic_index_mappings< StartHandle, StartIndex, std::tuple< ::bluetoe::characteristic< Options... >, Chars... > >
: characteristic_index_mapping< StartHandle, StartIndex, Options... >
, next_characteristic_mapping< StartHandle, StartIndex, std::tuple< Chars... >, Options... >
{
static constexpr std::uint16_t last_characteristic_end_handle =
next_characteristic_mapping< StartHandle, StartIndex, std::tuple< Chars... >, Options... >::last_characteristic_end_handle;
using next = characteristic_index_mapping< StartHandle, StartIndex, Options... >;
static std::uint16_t attribute_handle_by_index( std::size_t index )
{
if ( index < next::end_index )
return next::characteristic_attribute_handle_by_index( index );
return next_characteristic_mapping< StartHandle, StartIndex, std::tuple< Chars... >, Options... >::attribute_handle_by_index( index );
}
static std::size_t attribute_index_by_handle( std::uint16_t handle )
{
if ( handle < next::end_handle )
return next::characteristic_attribute_index_by_handle( handle );
return next_characteristic_mapping< StartHandle, StartIndex, std::tuple< Chars... >, Options... >::attribute_index_by_handle( handle );
}
};
template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename ... Options >
struct service_start_handle
{
using start_handle_t = typename find_by_meta_type< attribute_handle_meta_type, Options..., attribute_handle< StartHandle > >::type;
static constexpr std::uint16_t value = start_handle_t::attribute_handle_value;
};
template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename ... Options >
using next_char_mapping = interate_characteristic_index_mappings<
service_start_handle< StartHandle, StartIndex, Options... >::value + 1, StartIndex + 1,
typename find_all_by_meta_type< characteristic_meta_type, Options... >::type >;
/*
* Map index to handle within a single service
*/
template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename ... Options >
struct service_index_mapping
: next_char_mapping< StartHandle, StartIndex, Options... >
{
using service_t = ::bluetoe::service< Options... >;
static constexpr std::uint16_t service_handle = service_start_handle< StartHandle, StartIndex, Options... >::value;
static_assert( service_handle >= StartHandle, "attribute_handle<> can only be used to create increasing attribute handles." );
static constexpr std::uint16_t end_handle = next_char_mapping< StartHandle, StartIndex, Options... >::last_characteristic_end_handle;
static constexpr std::uint16_t end_index = StartIndex + service_t::number_of_attributes;
static std::uint16_t characteristic_handle_by_index( std::size_t index )
{
if ( index == StartIndex )
return service_handle;
return next_char_mapping< StartHandle, StartIndex, Options... >::attribute_handle_by_index( index );
}
static std::size_t characteristic_first_index_by_handle( std::uint16_t handle )
{
if ( handle <= service_handle )
return StartIndex;
return next_char_mapping< StartHandle, StartIndex, Options... >::attribute_index_by_handle( handle );
}
};
/*
* Iterate over all services in a server
*/
template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename OptionTuple >
struct interate_service_index_mappings;
template < std::uint16_t StartHandle, std::uint16_t StartIndex >
struct interate_service_index_mappings< StartHandle, StartIndex, std::tuple<> >
{
static std::uint16_t service_handle_by_index( std::size_t )
{
return invalid_attribute_handle;
}
static std::size_t service_first_index_by_handle( std::uint16_t )
{
return invalid_attribute_index;
}
};
template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename Services, typename ... Options >
using next_service_mapping = interate_service_index_mappings<
service_index_mapping< StartHandle, StartIndex, Options... >::end_handle,
service_index_mapping< StartHandle, StartIndex, Options... >::end_index,
Services
>;
template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename ... Options, typename ... Services >
struct interate_service_index_mappings< StartHandle, StartIndex, std::tuple< ::bluetoe::service< Options... >, Services... > >
: service_index_mapping< StartHandle, StartIndex, Options... >
, next_service_mapping< StartHandle, StartIndex, std::tuple< Services... >, Options... >
{
static std::uint16_t service_handle_by_index( std::size_t index )
{
if ( index < service_index_mapping< StartHandle, StartIndex, Options... >::end_index )
return service_index_mapping< StartHandle, StartIndex, Options... >::characteristic_handle_by_index( index );
return next_service_mapping< StartHandle, StartIndex, std::tuple< Services... >, Options... >::service_handle_by_index( index );
}
static std::size_t service_first_index_by_handle( std::uint16_t handle )
{
if ( handle < service_index_mapping< StartHandle, StartIndex, Options... >::end_handle )
return service_index_mapping< StartHandle, StartIndex, Options... >::characteristic_first_index_by_handle( handle );
return next_service_mapping< StartHandle, StartIndex, std::tuple< Services... >, Options... >::service_first_index_by_handle( handle );
}
};
/*
* Interface, providing function to map from 0-based attribute index to ATT attribute handle and vice versa
*
* An attribute index is a 0-based into an array of all attributes contained in a server. Accessing the
* attribute by table is very fast. If neither attribute_handle<> or attribute_handles<> is used, the mapping
* is trivial and an index I is mapped to a handle I + 1.
*/
template < typename Server >
struct handle_index_mapping;
template < typename ... Options >
struct handle_index_mapping< ::bluetoe::server< Options... > >
: private interate_service_index_mappings< 1u, 0u, typename ::bluetoe::server< Options... >::services >
{
static constexpr std::size_t invalid_attribute_index = ::bluetoe::details::invalid_attribute_index;
static constexpr std::uint16_t invalid_attribute_handle = ::bluetoe::details::invalid_attribute_handle;
using iterator = interate_service_index_mappings< 1u, 0u, typename ::bluetoe::server< Options... >::services >;
static std::uint16_t handle_by_index( std::size_t index )
{
return iterator::service_handle_by_index( index );
}
/**
* @brief attribute index for a given handle
*
* Returns the index to the attribute with the lowest handle that is
* equal or larger than the given handle.
*/
static std::size_t first_index_by_handle( std::uint16_t handle )
{
return iterator::service_first_index_by_handle( handle );
}
static std::size_t index_by_handle( std::uint16_t handle )
{
std::size_t result = first_index_by_handle( handle );
if ( result != invalid_attribute_index && handle_by_index( result ) != handle )
result = invalid_attribute_index;
return result;
}
};
}
}
#endif
| 45.643799
| 163
| 0.637493
|
TorstenRobitzki
|
cf25e5c06c8f4264e5dd840483da443534068a07
| 1,402
|
cpp
|
C++
|
earth_enterprise/src/third_party/sgl/v0_8_6/src/SkScan.cpp
|
ezeeyahoo/earthenterprise
|
b6cac9e6228946f2f17d1edb75e118aeb3e8e8c9
|
[
"Apache-2.0"
] | 2,661
|
2017-03-20T22:12:50.000Z
|
2022-03-30T09:43:19.000Z
|
earth_enterprise/src/third_party/sgl/v0_8_6/src/SkScan.cpp
|
ezeeyahoo/earthenterprise
|
b6cac9e6228946f2f17d1edb75e118aeb3e8e8c9
|
[
"Apache-2.0"
] | 1,531
|
2017-03-24T17:20:32.000Z
|
2022-03-16T18:11:14.000Z
|
earth_enterprise/src/third_party/sgl/v0_8_6/src/SkScan.cpp
|
ezeeyahoo/earthenterprise
|
b6cac9e6228946f2f17d1edb75e118aeb3e8e8c9
|
[
"Apache-2.0"
] | 990
|
2017-03-24T11:54:28.000Z
|
2022-03-22T11:51:47.000Z
|
/* libs/graphics/sgl/SkScan.cpp
**
** Copyright 2006, Google Inc.
**
** 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 "SkScan.h"
#include "SkBlitter.h"
#include "SkRegion.h"
void SkScan::FillRect(const SkRect& rect, const SkRegion* clip, SkBlitter* blitter)
{
SkRect16 r;
rect.round(&r);
SkScan::FillDevRect(r, clip, blitter);
}
void SkScan::FillDevRect(const SkRect16& r, const SkRegion* clip, SkBlitter* blitter)
{
if (!r.isEmpty())
{
if (clip)
{
SkRegion::Cliperator cliper(*clip, r);
const SkRect16& rr = cliper.rect();
while (!cliper.done())
{
blitter->blitRect(rr.fLeft, rr.fTop, rr.width(), rr.height());
cliper.next();
}
}
else
blitter->blitRect(r.fLeft, r.fTop, r.width(), r.height());
}
}
| 28.04
| 85
| 0.621969
|
ezeeyahoo
|
cf26279b7f8fdff66c5b19b3d7b123f0c179dccd
| 739
|
cpp
|
C++
|
algorithms/implementation/AppendAndDelete.cpp
|
HannoFlohr/hackerrank
|
9644c78ce05a6b1bc5d8f542966781d53e5366e3
|
[
"MIT"
] | null | null | null |
algorithms/implementation/AppendAndDelete.cpp
|
HannoFlohr/hackerrank
|
9644c78ce05a6b1bc5d8f542966781d53e5366e3
|
[
"MIT"
] | null | null | null |
algorithms/implementation/AppendAndDelete.cpp
|
HannoFlohr/hackerrank
|
9644c78ce05a6b1bc5d8f542966781d53e5366e3
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
string appendAndDelete(string s, string t, int k) {
if(s==t) return "Yes";
int i=0;
while(s[i]==t[i]) i++;
if( ( s.length()+t.length()-2*i ) > k )
return "No";
else if( (s.length()+t.length()-2*i) % 2 == k%2 )
return "Yes";
else if( (int)(s.length()+t.length()-k) < 0 )
return "Yes";
else
return "No";
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
string s;
getline(cin, s);
string t;
getline(cin, t);
int k;
cin >> k;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
string result = appendAndDelete(s, t, k);
fout << result << "\n";
fout.close();
return 0;
}
| 17.595238
| 56
| 0.515562
|
HannoFlohr
|
cf2697dcaaf5af85590c4600fd4bfac32c9c4d7e
| 549
|
cpp
|
C++
|
leetcode/easy/Add_Digits.cpp
|
HoussemBousmaha/Competitive-Programming
|
c4530fc01d8933bdfefec7fb6d31cd648e760334
|
[
"MIT"
] | 6
|
2022-03-02T23:08:00.000Z
|
2022-03-07T07:26:48.000Z
|
leetcode/easy/Add_Digits.cpp
|
HoussemBousmaha/Competitive-Programming
|
c4530fc01d8933bdfefec7fb6d31cd648e760334
|
[
"MIT"
] | null | null | null |
leetcode/easy/Add_Digits.cpp
|
HoussemBousmaha/Competitive-Programming
|
c4530fc01d8933bdfefec7fb6d31cd648e760334
|
[
"MIT"
] | null | null | null |
class Solution
{
public:
// int add_digits(int n) {
// int ans = 0;
// int k;
// while (n != 0) {
// k = n % 10;
// ans += k;
// n /= 10;
// }
// return ans;
// }
int addDigits(int n)
{
// while ((n / 10) != 0) {
// n = add_digits(n);
// }
// return n;
if (n == 0)
return 0;
return (n % 9 != 0 ? n % 9 : 9);
}
};
| 18.931034
| 42
| 0.256831
|
HoussemBousmaha
|
cf293d85b523041d2dfca0b8c7c7fa252e3fac76
| 469
|
cpp
|
C++
|
no3.cpp
|
bigdaddyjeff/JeffreyCSC102
|
dbdcbc50634b23ce7973c71329f4fdd2d3964927
|
[
"MIT"
] | null | null | null |
no3.cpp
|
bigdaddyjeff/JeffreyCSC102
|
dbdcbc50634b23ce7973c71329f4fdd2d3964927
|
[
"MIT"
] | null | null | null |
no3.cpp
|
bigdaddyjeff/JeffreyCSC102
|
dbdcbc50634b23ce7973c71329f4fdd2d3964927
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main()
{
int var = 789;
int *ptr2;
int **ptr1;
ptr2 = &var;
ptr1 = &ptr2;
cout << "The value of var = "<< var << endl;
cout << "Content value of single pointer ptr2 = " << *ptr2 << endl;
cout << "address value of single pointer ptr2 = " << ptr2 << endl;
cout << "Content value of double pointer ptr1 = " << **ptr1 << endl;
cout << "address value of double pointer ptr1 = " << ptr1 << endl;
}
| 27.588235
| 71
| 0.58209
|
bigdaddyjeff
|
cf2a28aa2539b4286c59835f605a6abdd6eda519
| 18,747
|
cpp
|
C++
|
IP/IMap.cpp
|
bharat-varma/Software-Engineering
|
36cdff296010e1076fb440707bfb2424110308ca
|
[
"Apache-2.0"
] | null | null | null |
IP/IMap.cpp
|
bharat-varma/Software-Engineering
|
36cdff296010e1076fb440707bfb2424110308ca
|
[
"Apache-2.0"
] | 3
|
2017-12-09T03:16:32.000Z
|
2017-12-15T04:22:08.000Z
|
IP/IMap.cpp
|
bharat-varma/Software-Engineering
|
36cdff296010e1076fb440707bfb2424110308ca
|
[
"Apache-2.0"
] | 1
|
2017-09-19T00:28:47.000Z
|
2017-09-19T00:28:47.000Z
|
#include <map>
#include <set>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <stack>
#include <cmath>
using namespace std;
class IntMap {
public:
static const long serialVersionUID = 1L;
static const int FREE_KEY = 0;
static const int NO_VALUE = 0;
/** Keys and values */
vector<int> m_data;
/** Do we have 'free' key in the map? */
bool m_hasFreeKey;
/** Value of 'free' key */
int m_freeValue;
/** Fill factor, must be between (0 and 1) */
float m_fillFactor;
/** We will resize a map once it reaches this size */
int m_threshold;
/** Current map size */
int m_size;
/** Mask to calculate the original position */
int m_mask;
int m_mask2;
IntMap();
IntMap(int size);
IntMap(int size, float fillFactor);
int get(int key);
// for use as IntSet - Paul Tarau
bool contains(int key);
bool add(int key);
bool del(int key);
bool isEmpty();
static void intersect0(IntMap &m, vector<IntMap> & maps, vector<IntMap> & vmaps, stack<int> r);
static stack<int> * intersect(vector<IntMap> & maps, vector<IntMap> & vmaps);
// end changes
int put(int key, int value);
int remove(int key);
int shiftKeys(int pos);
int size();
string show();
void rehash(int newCapacity);
/** Taken from FastUtil implementation */
/** Return the least power of two greater than or equal to the specified value.
*
* <p>Note that this function will return 1 when the argument is 0.
*
* @param x a long integer smaller than or equal to 2<sup>62</sup>.
* @return the least power of two greater than or equal to the specified value.
*/
static long nextPowerOfTwo(long x);
/** Returns the least power of two smaller than or equal to 2<sup>30</sup>
* and larger than or equal to <code>Math.ceil( expected / f )</code>.
*
* @param expected the expected number of elements in a hash table.
* @param f the load factor.
* @return the minimum possible size for a backing array.
* @throws IllegalArgumentException if the necessary size is larger than 2<sup>30</sup>.
*/
static int arraySize(int expected, float f);
//taken from FastUtil
static const int INT_PHI = 0x9E3779B9;
int static phiMix(int x);
};
IntMap::IntMap():IntMap(1<<2) {
//this(1 << 2);
}
IntMap::IntMap(int size):IntMap(size, 0.75f) {
//this(size, 0.75f);
}
IntMap::IntMap(int size, float fillFactor) {
//if (fillFactor <= 0 || fillFactor >= 1)
// throw new IllegalArgumentException("FillFactor must be in (0, 1)");
//if (size <= 0)
// throw new IllegalArgumentException("Size must be positive!");
int capacity = arraySize(size, fillFactor);
m_mask = capacity - 1;
m_mask2 = capacity * 2 - 1;
m_fillFactor = fillFactor;
m_data.resize(capacity * 2);
m_threshold = (int) (capacity * fillFactor);
}
int IntMap::get(int key) {
int ptr = (phiMix(key) & m_mask) << 1;
if (key == FREE_KEY)
return m_hasFreeKey ? m_freeValue : NO_VALUE;
int k = m_data[ptr];
if (k == FREE_KEY)
return NO_VALUE; //end of chain already
if (k == key) //we check FREE prior to this call
return m_data[ptr + 1];
while (true) {
ptr = ptr + 2 & m_mask2; //that's next index
k = m_data[ptr];
if (k == FREE_KEY)
return NO_VALUE;
if (k == key)
return m_data[ptr + 1];
}
}
// for use as IntSet - Paul Tarau
bool IntMap::contains(int key) {
return NO_VALUE != get(key);
}
bool IntMap::add(int key) {
return NO_VALUE != put(key, 666);
}
bool IntMap::del(int key) {
return NO_VALUE != remove(key);
}
bool IntMap::isEmpty() {
return 0 == m_size;
}
void IntMap::intersect0(IntMap &m, vector<IntMap> & maps, vector<IntMap> & vmaps, stack<int> r) {
vector<int> & data = m.m_data;
for (int k = 0; k < data.size(); k += 2) {
bool found = true;
int key = data[k];
if (FREE_KEY == key) {
continue;
}
for (int i = 1; i < maps.size(); i++) {
IntMap map = maps[i];
int val = map.get(key);
if (NO_VALUE == val) {
IntMap vmap = vmaps[i];
int vval = vmap.get(key);
if (NO_VALUE == vval) {
found = false;
break;
}
}
}
if (found) {
r.push(key);
}
}
}
stack<int> * IntMap::intersect(vector<IntMap> & maps, vector<IntMap> & vmaps) {
stack<int> *r = new stack<int>;
intersect0(maps[0], maps, vmaps, *r);
intersect0(vmaps[0], maps, vmaps, *r);
return r;
}
// end changes
int IntMap::put(int key, int value) {
if (key == FREE_KEY) {
int ret = m_freeValue;
if (!m_hasFreeKey) {
++m_size;
}
m_hasFreeKey = true;
m_freeValue = value;
return ret;
}
int ptr = (phiMix(key) & m_mask) << 1;
int k = m_data[ptr];
if (k == FREE_KEY) //end of chain already
{
m_data[ptr] = key;
m_data[ptr + 1] = value;
if (m_size >= m_threshold) {
rehash(m_data.size() * 2); //size is set inside
} else {
++m_size;
}
return NO_VALUE;
} else if (k == key) //we check FREE prior to this call
{
int ret = m_data[ptr + 1];
m_data[ptr + 1] = value;
return ret;
}
while (true) {
ptr = ptr + 2 & m_mask2; //that's next index calculation
k = m_data[ptr];
if (k == FREE_KEY) {
m_data[ptr] = key;
m_data[ptr + 1] = value;
if (m_size >= m_threshold) {
rehash(m_data.size() * 2); //size is set inside
} else {
++m_size;
}
return NO_VALUE;
} else if (k == key) {
int ret = m_data[ptr + 1];
m_data[ptr + 1] = value;
return ret;
}
}
}
int IntMap::remove(int key) {
if (key == FREE_KEY) {
if (!m_hasFreeKey)
return NO_VALUE;
m_hasFreeKey = false;
--m_size;
return m_freeValue; //value is not cleaned
}
int ptr = (phiMix(key) & m_mask) << 1;
int k = m_data[ptr];
if (k == key) //we check FREE prior to this call
{
int res = m_data[ptr + 1];
shiftKeys(ptr);
--m_size;
return res;
} else if (k == FREE_KEY)
return NO_VALUE; //end of chain already
while (true) {
ptr = ptr + 2 & m_mask2; //that's next index calculation
k = m_data[ptr];
if (k == key) {
int res = m_data[ptr + 1];
shiftKeys(ptr);
--m_size;
return res;
} else if (k == FREE_KEY)
return NO_VALUE;
}
}
int IntMap::shiftKeys(int pos) {
// Shift entries with the same hash.
int last, slot;
int k;
vector<int> & data = m_data;
while (true) {
pos = (last = pos) + 2 & m_mask2;
while (true) {
if ((k = data[pos]) == FREE_KEY) {
data[last] = FREE_KEY;
return last;
}
slot = (phiMix(k) & m_mask) << 1; //calculate the starting slot for the current key
if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) {
break;
}
pos = pos + 2 & m_mask2; //go to the next entry
}
data[last] = k;
data[last + 1] = data[pos + 1];
}
}
int IntMap::size() {
return m_size;
}
void IntMap::rehash(int newCapacity) {
m_threshold = (int) (newCapacity / 2 * m_fillFactor);
m_mask = newCapacity / 2 - 1;
m_mask2 = newCapacity - 1;
int oldCapacity = m_data.size();
vector<int> & oldData = m_data;
m_data.resize(newCapacity);
m_size = m_hasFreeKey ? 1 : 0;
for (int i = 0; i < oldCapacity; i += 2) {
int oldKey = oldData[i];
if (oldKey != FREE_KEY) {
put(oldKey, oldData[i + 1]);
}
}
}
/** Taken from FastUtil implementation */
/** Return the least power of two greater than or equal to the specified value.
*
* <p>Note that this function will return 1 when the argument is 0.
*
* @param x a long integer smaller than or equal to 2<sup>62</sup>.
* @return the least power of two greater than or equal to the specified value.
*/
long IntMap::nextPowerOfTwo(long x) {
if (x == 0)
return 1;
x--;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return (x | x >> 32) + 1;
}
/** Returns the least power of two smaller than or equal to 2<sup>30</sup>
* and larger than or equal to <code>Math.ceil( expected / f )</code>.
*
* @param expected the expected number of elements in a hash table.
* @param f the load factor.
* @return the minimum possible size for a backing array.
* @throws IllegalArgumentException if the necessary size is larger than 2<sup>30</sup>.
*/
int IntMap::arraySize(int expected, float f) {
long s = max(2l, nextPowerOfTwo((long) ceil(expected / f)));
if (s > 1 << 30) return -1;
//throw new IllegalArgumentException("Too large (" + expected + " expected elements with load factor " + f + ")");
return (int) s;
}
int IntMap::phiMix(int x) {
int h = x * INT_PHI;
return h ^ h >> 16;
}
string IntMap::show()
{
string b = "{";
int l = m_data.size();
bool first = true;
for (int i = 0; i < l; i += 2) {
int v = m_data[i];
if (v != FREE_KEY) {
if (!first) {
b += ",";
}
first = false;
b+=v-1;;
}
}
b+="}";
return b;
}
template <class K>
class IMap {
public:
static const long serialVersionUID = 1L;
map<K, IntMap*> mp;
vector<K> mp_lst;
IMap();
void clear();
bool put(K key, int val);
IntMap get(K key);
IntMap putget(K key);
bool remove(K key, int val);
bool remove(K key);
int size();
//set<K> keySet();
static string show(vector<IMap<int> > imaps);
static vector<IMap<int> > * create(int l);
static bool put(vector<IMap<int> > imaps, int pos, int key, int val);
static bool put(vector<IMap<int> > *imaps, int pos, int key, int val);
static vector<int> * get(vector<IMap<int> > *iMaps, vector<IntMap> vmaps, vector<int> keys);
string show();
};
template<class K>
IMap<K>::IMap() {
}
template<class K>
void IMap<K>::clear() {
mp.clear();
}
template<class K>
bool IMap<K>::put(K key, int val) {
if(mp.find(key) == mp.end())
{
mp[key] = new IntMap();
}
mp[key]->add(val);
/*
IntMap vals = mp.get(key);
if (null == vals) {
vals = new IntMap();
map.put(key, vals);
}
return vals.add(val);
*/
return mp[key]->add(val);
}
template<class K>
IntMap IMap<K>::putget(K key) {
//IntMap *s;
if(mp.find(key) == mp.end())
//if(!mp.contains(key))
{
//s = new IntMap();
return IntMap();
}
else
{
//s = mp[key];
return *mp[key];
}
/*
IntMap s = map.get(key);
if (null == s) {
s = new IntMap();
}
*/
//return s;
}
template<class K>
void remove_key(map<K,IntMap*> &mp, vector<K> mp_lst, K k)
{
auto element = mp.find(k);
mp.erase(element);
for(int i = 0; i < mp_lst.size(); i++)
{
if(mp_lst[i] == k)
{
mp_lst.erase(mp_lst.begin()+i);
return;
}
}
}
template<class K>
bool IMap<K>::remove(K key, int val) {
IntMap vals = get(key);
bool ok = vals.del(val);
if (vals.isEmpty()) {
remove_key(mp, mp_lst, key);
// mp.remove(key);
}
return ok;
}
template<class K>
bool IMap<K>::remove(K key) {
bool ret = mp.find(key) != mp.end();
remove_key(mp, mp_lst, key);
return ret;
//return 0 != mp.remove(key);
}
template<class K>
int IMap<K>::size() {
int s = 0;
for(const auto & k : mp_lst)
{
//IntMap *mp[k]
s += get(k).size();
}
/*
Iterator<K> I = mp.keySet().iterator();
int s = 0;
while (I.hasNext()) {
K key = I.next();
IntMap vals = get(key);
s += vals.size();
}*/
return s;
}
/*
template<class K>
set<K> IMap<K>::keySet() {
set<K> s;
for(const auto & k : mp_lst)
{
s.push(k);
}
return s;
}
*/
/*
Iterator<K> keyIterator() {
return keySet().iterator();
}*/
/*
@Override
public String toString() {
return map.toString();
}*/
// specialization for array of int maps
template<class K>
vector<IMap<int> > * IMap<K>::create(int l) {
IMap<int> first = IMap<int>();
vector<IMap<int> >* imaps = new vector<IMap<int> >(l);// = (IMap<int>[]) java.lang.reflect.Array.newInstance(first.getClass(), l);
// imaps = (IMap<int>[]) java.lang.reflect.Array.newInstance(first.getClass(), l);
//new IMap[l];
(*imaps)[0] = first;
for (int i = 1; i < l; i++) {
(*imaps)[i] = IMap<int>();
}
return imaps;
}
template<class K>
bool IMap<K>::put(vector<IMap<int> > imaps, int pos, int key, int val) {
return imaps[pos].put(key, val);
}
template<class K>
bool IMap<K>::put(vector<IMap<int> >* imaps, int pos, int key, int val) {
return ((*imaps)[pos]).put(key, val);
}
template<class K>
vector<int> * IMap<K>::get(vector<IMap<int> > *iMaps, vector<IntMap> vmaps, vector<int> keys) {
int l = iMaps->size();
vector<IntMap> ms; // = new ArrayList<IntMap>();
vector<IntMap> vms; // = new ArrayList<IntMap>();
for (int i = 0; i < l; i++) {
int key = keys[i];
if (0 == key) {
continue;
}
//Main.pp("i=" + i + " ,key=" + key);
IntMap m = (*iMaps)[i].get(key);
//Main.pp("m=" + m);
ms.push_back(m);
vms.push_back(vmaps[i]);
}
vector<IntMap> ims(ms.size());// = new IntMap[ms.size()];
vector<IntMap> vims(vms.size());// = new IntMap[vms.size()];
for (int i = 0; i < ims.size(); i++) {
IntMap im = ms[i];
ims[i] = im;
IntMap vim = vms[i];
vims[i] = vim;
}
//Main.pp("-------ims=" + Arrays.toString(ims));
//Main.pp("-------vims=" + Arrays.toString(vims));
stack<int> *cs = IntMap::intersect(ims, vims); // $$$ add vmaps here
//vector<int> *is = new vector<int>();
int n = cs->size();
//int[] is = cs.toArray();
vector<int> *is = new vector<int>(n);
for(int i=n-1;i>=0;i--)
{
(*is)[i] = cs->top();
cs->pop();
}
delete cs;
for (int i = 0; i < is->size(); i++) {
(*is)[i] = (*is)[i] - 1;
}
sort(is->begin(), is->end());
//java.util.Arrays.sort(is);
return is;
}
template<class K>
string IMap<K>::show()
{
string s = "";
for(K k : mp_lst)
{
//char buffer[256];
//sprintf(buffer, "%d : ")
//s += k + " : " + mp[k];
// s += ",";
}
return s;
}
template<class K>
IntMap IMap<K>::get(K key) {
if(mp.find(key) == mp.end())
{
return IntMap();
}
return *mp[key];
/*
return mp[key];
IntMap s = map.get(key);
if (null == s) {
s = new IntMap();
}
return s;
*/
}
template<class K>
string IMap<K>::show(vector<IMap<int> > imaps) {
string s = "";
for(auto x : imaps)
{
s += x.show();
}
return s;
//Arrays.toString(imaps);
}
/*
string show(vector<int> is) {
return Arrays.toString(is);
}*/
// end
/*
int main() {
vector<IMap<int> > *imaps = IMap<int>::create(3);
printf("1\n");
IMap<int>::put(*imaps, 0, 10, 100);
IMap<int>::put(*imaps, 1, 20, 200);
IMap<int>::put(*imaps, 2, 30, 777);
IMap<int>::put(*imaps, 0, 10, 1000);
IMap<int>::put(*imaps, 1, 20, 777);
IMap<int>::put(*imaps, 2, 30, 3000);
IMap<int>::put(*imaps, 0, 10, 777);
IMap<int>::put(*imaps, 1, 20, 20000);
IMap<int>::put(*imaps, 2, 30, 30000);
IMap<int>::put(*imaps, 0, 10, 888);
IMap<int>::put(*imaps, 1, 20, 888);
IMap<int>::put(*imaps, 2, 30, 888);
IMap<int>::put(*imaps, 0, 10, 0);
IMap<int>::put(*imaps, 1, 20, 0);
IMap<int>::put(*imaps, 2, 30, 0);
return 0;
}
*/
template class IMap<int>;
#define IA 16807
#define IM 2147483647
#define IQ 127773
#define IR 2836
#define NTAB 32
#define EPS (1.2E-07)
#define MAX(a,b) (a>b)?a:b
#define MIN(a,b) (a<b)?a:b
double ran1(int *idum)
{
int j,k;
static int iv[NTAB],iy=0;
void nrerror();
static double NDIV = 1.0/(1.0+(IM-1.0)/NTAB);
static double RNMX = (1.0-EPS);
static double AM = (1.0/IM);
if ((*idum <= 0) || (iy == 0)) {
*idum = MAX(-*idum,*idum);
for(j=NTAB+7;j>=0;j--) {
k = *idum/IQ;
*idum = IA*(*idum-k*IQ)-IR*k;
if(*idum < 0) *idum += IM;
if(j < NTAB) iv[j] = *idum;
}
iy = iv[0];
}
k = *idum/IQ;
*idum = IA*(*idum-k*IQ)-IR*k;
if(*idum<0) *idum += IM;
j = iy*NDIV;
iy = iv[j];
iv[j] = *idum;
return MIN(AM*iy,RNMX);
}
int random_int(int *seed, int a, int b)
{
return (b-a)*ran1(seed)+a;
}
int main(int argc, char **argv)
{
int seed = -1;
if(argc>1)
{
seed = atoi(argv[1]);
if(seed > 0) seed = -seed;
}
vector<IMap<int> > *imaps = IMap<int>::create(3);
int a = random_int(&seed, 1,5)*7;
int b = random_int(&seed, 1,5)*5;
int c = random_int(&seed, 1,5)*3;
int va = random_int(&seed, 1,1000);
int vb = random_int(&seed, 1,1000);
int vc = random_int(&seed, 1,1000);
IMap<int>::put(imaps, 0, a, va);
IMap<int>::put(imaps, 1, b, vb);
IMap<int>::put(imaps, 2, c, vc);
printf("%d %d\n", a, (*imaps)[0].get(a).get(va));
printf("%d %d\n", b, (*imaps)[1].get(b).get(vb));
printf("%d %d\n", c, (*imaps)[2].get(c).get(vc));
va = random_int(&seed, 1,1000);
vb = random_int(&seed, 1,1000);
vc = random_int(&seed, 1,1000);
IMap<int>::put(*imaps, 0, a, va);
IMap<int>::put(*imaps, 1, b, vb);
IMap<int>::put(*imaps, 2, c, vc);
printf("%d %d\n", a, (*imaps)[0].get(a).get(va));
printf("%d %d\n", b, (*imaps)[1].get(b).get(vb));
printf("%d %d\n", c, (*imaps)[2].get(c).get(vc));
printf("%d %d\n", c, (*imaps)[2].get(c).get(vc+1));
va = random_int(&seed, 1,1000);
vb = random_int(&seed, 1,1000);
vc = random_int(&seed, 1,1000);
IMap<int>::put(*imaps, 0, a, va);
IMap<int>::put(*imaps, 1, b, vb);
IMap<int>::put(*imaps, 2, c, vc);
va = random_int(&seed, 1,1000);
vb = random_int(&seed, 1,1000);
vc = random_int(&seed, 1,1000);
IMap<int>::put(*imaps, 0, a, va);
IMap<int>::put(*imaps, 1, b, vb);
IMap<int>::put(*imaps, 2, c, vc);
IMap<int>::put(*imaps, 0, a, 0);
IMap<int>::put(*imaps, 1, b, 0);
IMap<int>::put(*imaps, 2, c, 0);
printf("%d %d\n", a, (*imaps)[0].get(a).get(va));
printf("%d %d\n", b, (*imaps)[1].get(b).get(vb));
printf("%d %d\n", c, (*imaps)[2].get(c).get(vc));
printf("%d %d\n", c, (*imaps)[2].get(c).get(vc+1));
return 0;
}
| 22.081272
| 134
| 0.53886
|
bharat-varma
|
cf2eed74523c5d43661f04cba155aa1d24e3eba1
| 45,612
|
cpp
|
C++
|
stlsoft/samples/whereis/whereis.cpp
|
masscry/dmc
|
c7638f7c524a65bc2af0876c76621d8a11da42bb
|
[
"BSL-1.0"
] | 86
|
2018-05-24T12:03:44.000Z
|
2022-03-13T03:01:25.000Z
|
stlsoft/samples/whereis/whereis.cpp
|
masscry/dmc
|
c7638f7c524a65bc2af0876c76621d8a11da42bb
|
[
"BSL-1.0"
] | 1
|
2019-05-30T01:38:40.000Z
|
2019-10-26T07:15:01.000Z
|
stlsoft/samples/whereis/whereis.cpp
|
masscry/dmc
|
c7638f7c524a65bc2af0876c76621d8a11da42bb
|
[
"BSL-1.0"
] | 14
|
2018-07-16T08:29:12.000Z
|
2021-08-23T06:21:30.000Z
|
/* /////////////////////////////////////////////////////////////////////////////
* File: whereis.cpp
*
* Purpose: Implementation file for the Synesis Software whereis utility
*
* Created: 19th January 1996
* Updated: 16th August 2004
*
* Author: Matthew Wilson, Synesis Software Pty Ltd.
*
* The timestr() function and the verbose formatting in trace_file
* used by kind permission of Walter Bright and Digital Mars.
*
* License: (Licensed under the Synesis Software Standard Public License)
*
* Copyright (C) 1999-2004, Synesis Software Pty Ltd.
* Copyright (C) 1987-2004, Digital Mars.
*
* All rights reserved.
*
* www: http://www.synesis.com.au
* http://www.synesis.com.au/software
*
* http://www.digitalmars.com/
*
* email: software@synesis.com.au
*
* contact@digitalmars.com
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* (i) Redistributions of source code must retain the above
* copyright notice and contact information, this list of
* conditions and the following disclaimer.
*
* (ii) Redistributions in binary form must reproduce the above
* copyright notice and contact information, this list of
* conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* (iii) Any derived versions of this software (howsoever modified)
* remain the sole property of Synesis Software.
*
* (iv) Any derived versions of this software (howsoever modified)
* remain subject to all these conditions.
*
* (v) Neither the name of Synesis Software nor the names of any
* subdivisions, employees or agents of Synesis Software, nor the
* names of any other contributors to this software may be used to
* endorse or promote products derived from this software without
* specific prior written permission.
*
* This source code is provided by Synesis Software "as is" and any
* warranties, whether expressed or implied, including, but not
* limited to, the implied warranties of merchantability and
* fitness for a particular purpose are disclaimed. In no event
* shall the Synesis Software 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.
*
* ////////////////////////////////////////////////////////////////////////// */
/* /////////////////////////////////////////////////////////////////////////////
* Includes
*/
#include <stdio.h>
#include <stlsoft.h>
stlsoft_ns_using(ss_uint_t)
stlsoft_ns_using(ss_sint64_t)
stlsoft_ns_using(ss_bool_t)
/* Regrettably, something in this program is too complex for early versions of
* many compilers that the STLSoft libraries support. With some it is a compiler
* issue, with others it either crashes or produces erroneous output. Thus, the
* following restrictions are mandated:
*/
#if defined(__STLSOFT_COMPILER_IS_BORLAND)
# if __BORLANDC__ < 0x0560
# error whereis.cpp cannot be successfully built by Borland C/C++ prior to version 5.6
# endif /* __BORLANDC__ < 0x0560 */
#elif defined(__STLSOFT_COMPILER_IS_DMC)
# if __DMC__ < 0x0832
# error whereis.cpp cannot be successfully built by Digital Mars C/C++ prior to version 8.32
# endif /* __DMC__ < 0x0832 */
#elif defined(__STLSOFT_COMPILER_IS_GCC)
# if __GNUC__ < 3 && \
__GNUC_MINOR__ < 95
# error whereis.cpp cannot be successfully built by GNU C/C++ prior to version 6.0
# endif /* __GNUC__ < 3 && __GNUC_MINOR__ < 95 */
#elif defined(__STLSOFT_COMPILER_IS_INTEL)
# if __INTEL_COMPILER < 600
# error whereis.cpp cannot be successfully built by Intel C/C++ prior to version 6.0
# endif /* __INTEL_COMPILER < 600 */
#elif defined(__STLSOFT_COMPILER_IS_MWERKS)
/* No problems with Metrowerks */
#elif defined(__STLSOFT_COMPILER_IS_MSVC)
# if _MSC_VER < 1100
# error whereis.cpp cannot be successfully built by Microsoft Visual C/C++ prior to version 5.0
# endif /* _MSC_VER < 1100 */
#else
# error Unrecognised compiler
#endif /* compiler */
/* /////////////////////////////////////////////////////////////////////////////
* Warnings
*/
#if defined(__STLSOFT_COMPILER_IS_MSVC)
# pragma warning(disable : 4702)
#endif /* __STLSOFT_COMPILER_IS_INTEL */
/* ////////////////////////////////////////////////////////////////////////// */
#ifdef _SYNSOFT_INTERNAL_BUILD
# include "MLCompId.h"
#else /* ? _SYNSOFT_INTERNAL_BUILD */
# define _nameSynesisSoftware "Synesis Software (Pty) Ltd"
# define _wwwSynesisSoftware_SystemTools "http://synesis.com.au/systools.html"
# define _emailSynesisSoftware_SystemTools "software@synesis.com.au"
#endif /* _SYNSOFT_INTERNAL_BUILD */
/* ////////////////////////////////////////////////////////////////////////// */
#include <stlsoft_auto_buffer.h>
stlsoft_ns_using(auto_buffer)
#include <stlsoft_limit_traits.h>
#include <stlsoft_malloc_allocator.h>
stlsoft_ns_using(malloc_allocator)
#include <stlsoft_string_access.h>
stlsoft_ns_using(c_str_ptr)
#include <stlsoft_simple_algorithms.h>
stlsoft_ns_using(remove_duplicates_from_unordered_sequence)
#include <stlsoft_string_tokeniser.h>
stlsoft_ns_using(string_tokeniser)
#if defined(UNIX) || \
defined(unix) || \
defined(__unix) || \
defined(__unix__) || \
( defined(__xlC__) && \
defined(_POWER) && \
defined(_AIX))
/* UNIX includes */
# define WHEREIS_PLATFORM_IS_UNIX
# include <unixstl.h>
namespace platform_stl = unixstl;
# include <unixstl_file_path_buffer.h>
typedef unixstl_ns_qual(file_path_buffer_a) file_path_buffer;
# include <unixstl_findfile_sequence.h>
unixstl_ns_using(findfile_sequence)
# include <unixstl_functionals.h>
unixstl_ns_using(compare_path)
# include <unixstl_environment_variable.h>
unixstl_ns_using(basic_environment_variable)
# include <unixstl_current_directory.h>
unixstl_ns_using(basic_current_directory)
# include <unixstl_filesystem_traits.h>
unixstl_ns_using(filesystem_traits)
# include <time.h>
# include <sys/types.h>
# include <sys/stat.h>
#elif defined(WIN32) || \
defined(_WIN32)
/* Win32 includes */
# define WHEREIS_PLATFORM_IS_WIN32
# include <winstl.h>
namespace platform_stl = winstl;
# include <winstl_file_path_buffer.h>
typedef winstl_ns_qual(file_path_buffer_a) file_path_buffer;
# include <winstl_findfile_sequence.h>
typedef winstl_ns_qual(findfile_sequence_a) findfile_sequence;
# include <winstl_functionals.h>
winstl_ns_using(compare_path)
# include <winstl_environment_variable.h>
winstl_ns_using(basic_environment_variable)
# include <winstl_current_directory.h>
winstl_ns_using(basic_current_directory)
# include <winstl_filesystem_traits.h>
winstl_ns_using(filesystem_traits)
#else
# error Operating system not recognised
#endif /* operating system */
#include <algorithm>
stlsoft_ns_using_std(copy)
stlsoft_ns_using_std(for_each)
stlsoft_ns_using_std(remove_if)
#include <functional>
stlsoft_ns_using_std(unary_function)
#include <iterator>
stlsoft_ns_using_std(back_inserter)
#include <string>
stlsoft_ns_using_std(string)
#include <vector>
stlsoft_ns_using_std(vector)
#include <list>
stlsoft_ns_using_std(list)
#include <map>
stlsoft_ns_using_std(map)
#ifdef _SYNSOFT_INTERNAL_BUILD
# include <MRPathFn.h>
# ifdef WHEREIS_PLATFORM_IS_WIN32
# define WHEREIS_USING_WIN32_VERSION_INFO
# include <MWVerInf.h>
# endif /* platform */
#endif /* _SYNSOFT_INTERNAL_BUILD */
/* /////////////////////////////////////////////////////////////////////////////
* Warnings
*/
#if defined(__STLSOFT_COMPILER_IS_INTEL)
# pragma warning(disable : 383)
# pragma warning(disable : 444)
# pragma warning(disable : 1419)
#endif /* __STLSOFT_COMPILER_IS_INTEL */
/* /////////////////////////////////////////////////////////////////////////////
* Tracing
*/
//#define WHEREIS_TRACE
#if !defined(WHEREIS_TRACE) && \
defined(_DEBUG)
# define WHEREIS_TRACE
#endif /* !WHEREIS_TRACE && _DEBUG */
/* /////////////////////////////////////////////////////////////////////////////
* Version information
*
* Normally, Synesis Software components & tools are "versioned" by making use
* of tool-generated header files, one of which - MBldHdr.h - defines symbolic
* constants representing major, minor, revision and build numbers.
*
*
* Since this file is to be available in a more public forum, including on the
* Digital Mars site, these constants are merely defined here, rather than
* encumber any developers who may wish to compile it with a lot of
* Synesis-specific gunk.
*/
#ifdef _SYNSOFT_INTERNAL_BUILD
# include "MBldHdr.h"
# include "showver.h"
extern "C" const int _mccVerHi = __SYV_MAJOR;
extern "C" const int _mccVerLo = __SYV_MINOR;
extern "C" const int _mccVerRev = __SYV_REVISION;
extern "C" const int _mccBldNum = __SYV_BUILDNUMBER;
#else /* ? _SYNSOFT_INTERNAL_BUILD */
extern "C" const int _mccVerHi = 1;
extern "C" const int _mccVerLo = 12;
extern "C" const int _mccVerRev = 1;
extern "C" const int _mccBldNum = 52;
#endif /* _SYNSOFT_INTERNAL_BUILD */
# define COMPANY_NAME "Synesis Software"
# define TOOL_NAME "File Searching"
# define EXE_NAME "whereis"
/* /////////////////////////////////////////////////////////////////////////////
* Typedefs
*/
typedef string_tokeniser<string, char> tokeniser_string_t;
typedef vector<string> searchpath_sorted_t;
//typedef list<string> searchpath_sorted_t;
typedef map<string, unsigned> extension_map_t;
#if defined(WHEREIS_PLATFORM_IS_WIN32)
typedef FILETIME whereis_time_t;
#elif defined(WHEREIS_PLATFORM_IS_UNIX)
typedef time_t whereis_time_t;
#else
# error Unknown platform
#endif /* platform */
/* /////////////////////////////////////////////////////////////////////////////
* Enumerations
*/
namespace Trim
{
enum Trim
{
full
, fileOnly
, fromSearchRoot
, fromCurrentDirectory
};
} // namespace Trim
namespace Flags
{
enum
{
verbose = 0x00000001
, showVersionInfo = 0x00000002
, showFiles = 0x00000004
, showDirectories = 0x00000008
, markDirectories = 0x00000010
};
} // namespace Flags
/* /////////////////////////////////////////////////////////////////////////////
* Macros and definitions
*
* Visual C++, sigh. uses %I64d", rather than "%lld", so that is abstracted here
*/
#if defined(__STLSOFT_COMPILER_IS_BORLAND) || \
/* defined(__STLSOFT_COMPILER_IS_GCC) || */ \
defined(__STLSOFT_COMPILER_IS_INTEL) || \
defined(__STLSOFT_COMPILER_IS_MSVC)
# define FMT_SINT64_WIDTH_(x) "%" #x "I64d"
#else
# define FMT_SINT64_WIDTH_(x) "%" #x "lld"
#endif /* compiler */
/* /////////////////////////////////////////////////////////////////////////////
* Constants
*/
#ifdef __STLSOFT_COMPILER_IS_INTEL
# pragma warning(disable : 1418)
#endif /* __STLSOFT_COMPILER_IS_INTEL */
/* Multi-part path/pattern delimiter */
#if defined(__STLSOFT_COMPILER_IS_MSVC) && \
_MSC_VER < 1300
char const PATH_SEPARATOR = ';';
#else /* ? compiler */
char const PATH_SEPARATOR = filesystem_traits<char>::path_separator();
#endif /* compiler */
/* Path component delimiter */
#if defined(__STLSOFT_COMPILER_IS_MSVC) && \
_MSC_VER < 1300
char const PATH_NAME_SEPARATOR = '\\';
#else /* ? compiler */
char const PATH_NAME_SEPARATOR = filesystem_traits<char>::path_name_separator();
#endif /* compiler */
/* Subdirectory wildcard pattern */
#if defined(__STLSOFT_COMPILER_IS_MSVC) && \
_MSC_VER < 1300
char const *PATTERN_ALL = "*.*";
#else /* ? compiler */
char const *PATTERN_ALL = filesystem_traits<char>::pattern_all();
#endif /* compiler */
/* Illegal pattern characters string */
#if defined(_MSC_VER) /* For testing */ || \
defined(WHEREIS_PLATFORM_IS_WIN32)
char const *BAD_PATTERN_CHARS = ":\\";
#elif defined(WHEREIS_PLATFORM_IS_UNIX)
char const *BAD_PATTERN_CHARS = "/";
#else
# error Unknown platform
#endif /* platform */
#ifdef __STLSOFT_COMPILER_IS_INTEL
# pragma warning(default : 1418)
#endif /* __STLSOFT_COMPILER_IS_INTEL */
/* /////////////////////////////////////////////////////////////////////////////
* Function declarations
*
* (Primarily to keep Metrowerks happy, but that's a good thing to do!)
*/
static char *timestr(char *buffer, size_t cchBuffer, whereis_time_t const *ft); // Make Metrowerks happy
/* /////////////////////////////////////////////////////////////////////////////
* Global variables
*/
static file_path_buffer s_root;
static extension_map_t s_extMap;
/* /////////////////////////////////////////////////////////////////////////////
* Helper Functions
*/
char *timestr(char *buffer, size_t cchBuffer, whereis_time_t const *t)
{
#if defined(WHEREIS_PLATFORM_IS_WIN32)
FILETIME ftLocal;
SYSTEMTIME st;
char dateString[41];
char timeString[41];
::FileTimeToLocalFileTime(t, &ftLocal);
::FileTimeToSystemTime(&ftLocal, &st);
::GetDateFormat(LOCALE_USER_DEFAULT, 0, &st, NULL, dateString, stlsoft_num_elements(dateString));
::GetTimeFormat(LOCALE_USER_DEFAULT, 0, &st, NULL, timeString, stlsoft_num_elements(timeString));
#if 0
// Digital Mars format (US based)
sprintf(buffer, "%02d/%02d/%02d %2d:%02d", st.wMonth, st.wDay, st.wYear % 100, st.wHour, st.wMinute);
#else /* ? 0 */
// User-locale format
sprintf(buffer, "%-10s %-s", dateString, timeString);
#endif /* 0 */
STLSOFT_SUPPRESS_UNUSED(cchBuffer);
#elif defined(WHEREIS_PLATFORM_IS_UNIX)
struct tm tm_ = *localtime(t);
strftime(buffer, cchBuffer, "%c", &tm_);
#else
# error Unknown platform
#endif /* platform */
return buffer;
}
static char *copy_entry_filename(char *dest, findfile_sequence::value_type const &entry)
{
#if defined(WHEREIS_PLATFORM_IS_WIN32)
return strcpy(dest, entry.get_filename());
#elif defined(WHEREIS_PLATFORM_IS_UNIX)
// Use the get_full_path_name()
file_path_buffer buffer;
char *pFile = NULL;
size_t cch = platform_stl::filesystem_traits<char>::get_full_path_name(entry, buffer.size(), &buffer[0], &pFile);
STLSOFT_SUPPRESS_UNUSED(cch);
return strcpy(dest, pFile);
#else
# error Unknown platform
#endif /* platform */
}
/* /////////////////////////////////////////////////////////////////////////////
* Functionals
*/
// struct trace_file
//
// This functional traces individual file records to stdout.
struct trace_file
: public unary_function<findfile_sequence::value_type const &, void>
{
typedef trace_file class_type;
public:
trace_file(char const *searchRoot, Trim::Trim trim, ss_uint_t flags)
: m_flags(flags)
, m_searchRoot(searchRoot)
, m_trim(trim)
{}
void operator ()(findfile_sequence::value_type const &entry) const
{
file_path_buffer path;
switch(m_trim)
{
default:
stlsoft_assert(0);
case Trim::full:
strcpy(&path[0], c_str_ptr(entry));
break;
case Trim::fileOnly:
copy_entry_filename(&path[0], entry);
break;
#if defined(_SYNSOFT_INTERNAL_BUILD) && \
defined(WHEREIS_PLATFORM_IS_WIN32)
case Trim::fromSearchRoot:
SynesisCrt::deriverelativepath(stlsoft_ns_qual(c_str_ptr)(entry), m_searchRoot, &path[0]);
break;
case Trim::fromCurrentDirectory:
SynesisCrt::deriverelativepath(stlsoft_ns_qual(c_str_ptr)(entry), stlsoft_ns_qual(c_str_ptr)(s_root), &path[0]);
break;
#endif /* _SYNSOFT_INTERNAL_BUILD */
}
if(m_flags & Flags::verbose)
{
ss_sint64_t size;
char timebuf[50];
char atts[8 + 1];
#if defined(WHEREIS_PLATFORM_IS_WIN32)
findfile_sequence::find_data_type const &findData = entry.get_find_data();
DWORD const &att = findData.dwFileAttributes;
int i;
for (i = 0; i < 8; ++i)
{
static char tab[] = "RHSVDAXX";
if (att & (1 << i))
atts[i] = tab[i];
else
atts[i] = '-';
}
atts[8] = 0;
timestr(timebuf, stlsoft_num_elements(timebuf), &findData.ftLastWriteTime);
size = findData.nFileSizeHigh * __STLSOFT_GEN_SINT64_SUFFIX(0x100000000) + findData.nFileSizeLow;
#elif defined(WHEREIS_PLATFORM_IS_UNIX)
# ifdef _MSC_VER // For testing
struct _stat st;
_stat(entry, &st);
# else /* ? _MSC_VER */
struct stat st;
stat(entry, &st);
# endif /* _MSC_VER */
atts[0] = ((st.st_mode & S_IWRITE) == 0) ? 'R' : '-'; // R
atts[1] = '-'; // H
atts[2] = '-'; // S
atts[3] = '-'; // V
atts[4] = ((st.st_mode & S_IFMT) == S_IFDIR) ? 'D' : '-'; // D
atts[5] = '-'; // A
atts[6] = '-'; // X
atts[7] = '-'; // X
atts[8] = 0;
size = st.st_size;
timestr(timebuf, stlsoft_num_elements(timebuf), &st.st_mtime);
#else /* ? platform */
# error Unknown platform
#endif /* platform */
#ifdef _SYNSOFT_INTERNAL_BUILD
# if defined(WHEREIS_PLATFORM_IS_WIN32)
if(m_flags & Flags::showVersionInfo)
{
SynesisWin::LPWinVerInfoA verInfo = SynesisWin::WinVer_GetVersionInformationA(c_str_ptr(entry));
char version[101];
if(NULL != verInfo)
{
sprintf(version, "%d.%d.%02d.%04d", verInfo->fileVerMajor, verInfo->fileVerMinor, verInfo->fileVerRevision, verInfo->fileVerBuild);
SynesisWin::WinVer_CloseVersionInformationA(verInfo);
}
else
{
version[0] = '\0';
}
printf("%-23s %16s %s " FMT_SINT64_WIDTH_(9) "\t%s\n", timebuf, version, atts, size, path.c_str());
}
else
# endif /* WHEREIS_PLATFORM_IS_WIN32 */
#endif /* _SYNSOFT_INTERNAL_BUILD */
{
printf("%-23s %s " FMT_SINT64_WIDTH_(9) "\t%s\n", timebuf, atts, size, path.c_str());
}
}
else
{
fprintf(stdout, "%s\n", path.c_str());
}
}
// Members
private:
char const *const m_searchRoot;
Trim::Trim const m_trim;
ss_uint_t const m_flags;
// Not to be implemented
private:
class_type &operator =(class_type const &);
};
// struct process_searchspec
//
// This functional processes a search-spec within a given directory, passing any
// file to be processed by trace_file.
struct process_searchspec
: public unary_function<tokeniser_string_t::value_type const &, void>
{
typedef process_searchspec class_type;
public:
process_searchspec(string const &path, char const *searchRoot, Trim::Trim trim, ss_uint_t flags)
: m_path(path)
, m_searchRoot(searchRoot)
, m_trim(trim)
, m_flags(flags)
{}
void operator ()(tokeniser_string_t::value_type const &value) const
{
#ifdef WHEREIS_PLATFORM_IS_UNIX
try
{
#endif /* WHEREIS_PLATFORM_IS_UNIX */
int fs_flags = 0;
if(m_flags & Flags::showDirectories)
{
fs_flags |= findfile_sequence::directories;
}
if(m_flags & Flags::showFiles)
{
fs_flags |= findfile_sequence::files;
}
findfile_sequence files(c_str_ptr(m_path), c_str_ptr(value), fs_flags);
for_each(files.begin(), files.end(), trace_file(m_searchRoot, m_trim, m_flags));
#ifdef WHEREIS_PLATFORM_IS_UNIX
}
catch(unixstl::glob_sequence_exception &)
{}
#endif /* WHEREIS_PLATFORM_IS_UNIX */
}
// Members
private:
string const m_path;
char const *const m_searchRoot;
Trim::Trim const m_trim;
ss_uint_t const m_flags;
// Not to be implemented
private:
class_type &operator =(class_type const &);
};
// struct process_path
//
// This functional creates a search sequence for each path, and then processes
// each one with the trace_file functional.
struct process_path
: public unary_function<string const &, void>
{
typedef process_path class_type;
public:
process_path(string const &searchSpec, Trim::Trim trim, ss_uint_t flags)
: m_searchSpec(searchSpec)
, m_searchRoot(NULL)
, m_trim(trim)
, m_flags(flags)
{}
process_path(string const &searchSpec, char const *searchRoot, Trim::Trim trim, ss_uint_t flags)
: m_searchSpec(searchSpec)
, m_searchRoot(searchRoot)
, m_trim(trim)
, m_flags(flags)
{}
void operator ()(string const &dir) const
{
typedef filesystem_traits<char> traits_type;
file_path_buffer searchRoot_;
char const *searchRoot = (traits_type::get_full_path_name((NULL != m_searchRoot) ? m_searchRoot : stlsoft_ns_qual(c_str_ptr)(dir), searchRoot_.size(), &searchRoot_[0]), stlsoft_ns_qual(c_str_ptr)(searchRoot_));
// Now split with the string_tokeniser into all the constituent paths
tokeniser_string_t specs(&m_searchSpec[0], PATH_SEPARATOR);
for_each(specs.begin(), specs.end(), process_searchspec(dir, stlsoft_ns_qual(c_str_ptr)(searchRoot), m_trim, m_flags));
}
// Members
private:
string const m_searchSpec;
char const *const m_searchRoot;
Trim::Trim const m_trim;
ss_uint_t const m_flags;
// Not to be implemented
private:
class_type &operator =(class_type const &);
};
// struct trace_dir
//
// This functional provides processing of a directory, used by the recursive
// option. It process the current directory (via process_path), and then all
// subdirectories (via trace_dir) "calling" itself recursively.
struct trace_dir
: public unary_function<string const &, void>
{
typedef trace_dir class_type;
public:
trace_dir(string const &searchSpec, Trim::Trim trim, ss_uint_t flags)
: m_searchSpec(searchSpec)
, m_searchRoot(NULL)
, m_trim(trim)
, m_flags(flags)
{}
trace_dir(string const &searchSpec, char const *searchRoot, Trim::Trim trim, ss_uint_t flags)
: m_searchSpec(searchSpec)
, m_searchRoot(searchRoot)
, m_trim(trim)
, m_flags(flags)
{}
void operator ()(char const *dir) const
{
typedef filesystem_traits<char> traits_type;
file_path_buffer searchRoot_;
char const *searchRoot = (traits_type::get_full_path_name((NULL != m_searchRoot) ? m_searchRoot : dir, searchRoot_.size(), &searchRoot_[0]), stlsoft_ns_qual(c_str_ptr)(searchRoot_));
process_path f(m_searchSpec, searchRoot, m_trim, m_flags);
f(dir);
#ifdef WHEREIS_PLATFORM_IS_UNIX
try
{
#endif /* WHEREIS_PLATFORM_IS_UNIX */
findfile_sequence directories(stlsoft_ns_qual(c_str_ptr)(dir), PATTERN_ALL, findfile_sequence::directories);
for_each(directories.begin(), directories.end(), trace_dir(m_searchSpec, searchRoot, m_trim, m_flags));
#ifdef WHEREIS_PLATFORM_IS_UNIX
}
catch(unixstl::glob_sequence_exception &)
{}
#endif /* WHEREIS_PLATFORM_IS_UNIX */
}
template <ss_typename_param_k S>
void operator ()(S const &dir) const
{
operator ()(stlsoft_ns_qual(c_str_ptr)(dir));
}
private:
string const m_searchSpec;
char const *const m_searchRoot;
Trim::Trim const m_trim;
ss_uint_t const m_flags;
// Not to be implemented
private:
class_type &operator =(class_type const &);
};
/* /////////////////////////////////////////////////////////////////////////////
* Function declarations
*/
static void usage(int bExit, char const *reason, int invalidArg, int argc, char *argv[]);
static char const *convert_path_separators(char const *path, char *buffer);
#ifdef WHEREIS_PLATFORM_IS_WIN32
static char const *get_driveroots(char *buffer);
#endif /* WHEREIS_PLATFORM_IS_WIN32 */
/* /////////////////////////////////////////////////////////////////////////////
* Helper functionals
*/
struct is_empty_path
{
template <ss_typename_param_k S>
ss_bool_t operator ()(S const &s) const
{
return c_str_ptr(s)[0] == '\0';
}
};
struct print_path
{
template <ss_typename_param_k S>
void operator ()(S const &s) const
{
fprintf(stdout, " %s\n", c_str_ptr(s));
}
};
#ifdef WHEREIS_TRACE
struct trace_path
{
template <ss_typename_param_k S>
void operator ()(S const &s) const
{
size_t len = c_str_len(s);
auto_buffer<char, malloc_allocator<char>, 256> buffer(3 + len + 1);
sprintf(buffer, " %s\n", c_str_ptr(s));
OutputDebugStringA(buffer);
}
};
#endif /* WHEREIS_TRACE */
/* /////////////////////////////////////////////////////////////////////////////
* main
*/
#ifdef WIN32
extern "C" __declspec(dllimport) void __stdcall Sleep(unsigned long );
#endif /* WIN32 */
static int main_(int argc, char **argv)
{
ss_bool_t bDisplayTotal = false;
ss_bool_t bFromEnvironment = false;
ss_bool_t bSearchGivenRoots = false;
ss_bool_t bSearchCwd = false;
ss_bool_t bDumpSearchRoots = false;
ss_bool_t bVerbose = true;
ss_bool_t bRecursive = false;
ss_bool_t bSuppressRecursive = false;
ss_bool_t bShowVersionInfo = false;
ss_bool_t bSummariseExtensions = false;
ss_bool_t bShowDirectories = false;
ss_bool_t bShowFiles = false;
ss_bool_t bMarkDirs = false;
Trim::Trim trim = Trim::full;
char const *rootSpec = NULL;
char const *searchSpec = NULL;
char const *envSpec = NULL;
#ifdef WHEREIS_PLATFORM_IS_WIN32
char driveroots[105] = "";
#endif /* WHEREIS_PLATFORM_IS_WIN32 */
int totalFound = 0;
for(int i = 1; i < argc; ++i)
{
char const *arg = argv[i];
if(arg[0] == '-')
{
if(arg[1] == '-')
{
if( 0 == strcmp("--directories", arg) ||
0 == strcmp("--dirs", arg))
{
bShowDirectories = true;
}
else if(0 == strcmp("--files", arg))
{
bShowFiles = true;
}
#ifdef _SYNSOFT_INTERNAL_BUILD
else if(0 == strcmp("--version", arg))
{
return show_version();
}
#endif /* _SYNSOFT_INTERNAL_BUILD */
else
{
usage(1, "Invalid argument(s) specified", i, argc, argv);
}
}
else
{
switch(arg[1])
{
case '?':
usage(1, NULL, i, argc, argv);
break;
case 'd':
bDumpSearchRoots = true;
break;
case 'e':
bFromEnvironment = true;
envSpec = arg + 2;
break;
case 'f':
trim = Trim::fileOnly;
break;
#ifdef WHEREIS_PLATFORM_IS_WIN32
case 'h':
bSearchGivenRoots = true;
rootSpec = get_driveroots(driveroots);
break;
#endif /* WHEREIS_PLATFORM_IS_WIN32 */
case 'i':
bFromEnvironment = true;
envSpec = "INCLUDE";
break;
case 'l':
bFromEnvironment = true;
envSpec = "LIB";
break;
case 'm':
bMarkDirs = true;
break;
// case 'n':
// bDisplayTotal = true;
// break;
case 'r':
bSearchGivenRoots = true;
rootSpec = arg + 2;
break;
case 'p':
bFromEnvironment = true;
envSpec = "PATH";
break;
case 's':
bVerbose = false;
break;
case 't':
trim = Trim::fromCurrentDirectory;
break;
case 'u':
bRecursive = true;
break;
case 'v':
bVerbose = true;
break;
case 'w':
bSearchCwd = true;
break;
case 'x':
bSummariseExtensions = false;
break;
case 'R':
bSuppressRecursive = true;
break;
case 'F':
trim = Trim::full;
break;
case 'T':
trim = Trim::fromSearchRoot;
break;
#ifdef _SYNSOFT_INTERNAL_BUILD
case 'V':
bShowVersionInfo = true;
break;
#endif /* _SYNSOFT_INTERNAL_BUILD */
default:
// fprintf(stderr, "Unrecognised argument \"%s\"\n", arg);
usage(1, "Invalid argument(s) specified", i, argc, argv);
break;
}
}
}
else
{
if(rootSpec == NULL)
{
rootSpec = arg;
}
else if(searchSpec == NULL)
{
searchSpec = arg;
}
else
{
usage(1, "<root-paths> and <search-spec> already specified", i, argc, argv);
}
}
}
STLSOFT_SUPPRESS_UNUSED(bSummariseExtensions);
if( !bShowDirectories &&
!bShowFiles)
{
bShowFiles = true;
}
if( NULL == searchSpec &&
NULL == rootSpec)
{
usage(1, "No search parameters specified", 0, argc, argv);
}
if( ((bSearchCwd != false) +
(bFromEnvironment != false) +
(bSearchGivenRoots != false)) > 1)
{
usage(1, "Cannot specify two or more of -w, -r, -e, -l, -i, -p", 0, argc, argv);
}
// Validate the args. This entails just moving the root-dir into the
// search-spec if no root-dir was specified. This simplifies the
// previous command-line processing.
if(NULL == searchSpec)
{
if( NULL != rootSpec &&
!bSearchGivenRoots)
{
searchSpec = rootSpec;
rootSpec = NULL;
}
else
{
usage(1, "Unexpected condition. Please report to Synesis Software", 0, argc, argv);
}
}
file_path_buffer rootDir_;
if(bFromEnvironment)
{
rootSpec = NULL;
}
else
{
// If no directory is specified, the current directory is assumed
if( rootSpec == NULL ||
*rootSpec == '\0')
{
strcpy(&rootDir_[0], basic_current_directory<char>());
rootSpec = stlsoft_ns_qual(c_str_ptr)(rootDir_);
}
}
if( bFromEnvironment &&
( envSpec == NULL ||
*envSpec == '\0'))
{
usage(1, "Cannot search from environment when no environment variable specified", 0, argc, argv);
}
#if defined(__STLSOFT_COMPILER_IS_MSVC) && \
_MSC_VER < 1200
GetCurrentDirectory(s_root.size(), s_root);
#else /* ? compiler */
platform_stl::filesystem_traits<char>::get_current_directory(s_root.size(), &s_root[0]);
#endif /* compiler */
// Handle forward slashes
string _rootDir_(rootSpec != NULL ? rootSpec : "");
string _searchSpec_(searchSpec != NULL ? searchSpec : "");
rootSpec = convert_path_separators(rootSpec, const_cast<char*>(_rootDir_.data()));
searchSpec = convert_path_separators(searchSpec, const_cast<char*>(_searchSpec_.data()));
// Handle illegal characters
if(strpbrk(searchSpec, BAD_PATTERN_CHARS) != 0)
{
char sz[101];
sprintf(sz, "<search-spec> contains illegal characters: \"%s\"\n", searchSpec);
usage(1, sz, 0, argc, argv);
}
searchpath_sorted_t sorted;
ss_uint_t flags = 0;
if(bVerbose)
{
flags |= Flags::verbose;
}
if(bShowVersionInfo)
{
flags |= Flags::showVersionInfo;
}
if(bShowDirectories)
{
flags |= Flags::showDirectories;
}
if(bShowFiles)
{
flags |= Flags::showFiles;
}
if(bMarkDirs)
{
flags |= Flags::markDirectories;
}
#ifdef WHEREIS_USING_WIN32_VERSION_INFO
SynesisWin::WinVer_Init();
#endif /* WHEREIS_USING_WIN32_VERSION_INFO */
// Commence the search
if(bFromEnvironment)
{
basic_environment_variable<char> ENVVAR(envSpec);
tokeniser_string_t paths(ENVVAR, PATH_SEPARATOR);
#ifdef __STLSOFT_COMPILER_IS_DMC
{
tokeniser_string_t::const_iterator begin = paths.begin();
tokeniser_string_t::const_iterator end = paths.end();
for(; begin != end; ++begin)
{
sorted.push_back(*begin);
}
}
#else
copy(paths.begin(), paths.end(), back_inserter(sorted));
#endif /* __STLSOFT_COMPILER_IS_DMC */
// The roots may contain duplicate elements, so
remove_duplicates_from_unordered_sequence(sorted, compare_path<char>());
// They may also contain empty paths, so
sorted.erase(remove_if(sorted.begin(), sorted.end(), is_empty_path()), sorted.end());
if(bDumpSearchRoots)
{
fprintf(stdout, "Search roots:\n");
for_each(sorted.begin(), sorted.end(), print_path());
}
// Now execute over the duplicate-free (but still in the correct search order)
// sequence, applying the process_path functional to each one.
if(bRecursive)
{
for_each(sorted.begin(), sorted.end(), trace_dir(searchSpec, trim, flags));
}
else
{
for_each(sorted.begin(), sorted.end(), process_path(searchSpec, trim, flags));
}
}
else
{
tokeniser_string_t roots(rootSpec, PATH_SEPARATOR);
#ifdef __STLSOFT_COMPILER_IS_DMC
{
tokeniser_string_t::const_iterator begin = roots.begin();
tokeniser_string_t::const_iterator end = roots.end();
for(; begin != end; ++begin)
{
sorted.push_back(*begin);
}
}
#else
copy(roots.begin(), roots.end(), back_inserter(sorted));
#endif /* __STLSOFT_COMPILER_IS_DMC */
// The roots may contain duplicate elements, so
remove_duplicates_from_unordered_sequence(sorted, compare_path<char>());
// They may also contain empty paths, so
sorted.erase(remove_if(sorted.begin(), sorted.end(), is_empty_path()), sorted.end());
if(bDumpSearchRoots)
{
fprintf(stdout, "Search roots:\n");
for_each(sorted.begin(), sorted.end(), print_path());
}
// Now execute over the duplicate-free (but still in the correct search order)
// sequence, applying the trace_dir functional to each one.
if(!bSuppressRecursive)
{
for_each(sorted.begin(), sorted.end(), trace_dir(searchSpec, trim, flags));
}
else
{
for_each(sorted.begin(), sorted.end(), process_path(searchSpec, trim, flags));
}
}
if(bDisplayTotal)
{
printf(" %5d file(s) found\n", totalFound);
}
#ifdef WHEREIS_USING_WIN32_VERSION_INFO
SynesisWin::WinVer_Uninit();
#endif /* WHEREIS_USING_WIN32_VERSION_INFO */
return 0;
}
int main(int argc, char *argv[])
{
int res;
#if 0
::Sleep(100000);
#endif /* 0 */
try
{
res = main_(argc, argv);
}
catch(...)
{
fprintf(stderr, "Fatal error: Uncaught exception in main_()\n");
res = EXIT_FAILURE;
}
return res;
}
/* /////////////////////////////////////////////////////////////////////////////
* usage
*/
static void usage(int bExit, char const *reason, int invalidArg, int argc, char *argv[])
{
fprintf(stderr, "\n");
fprintf(stderr, " %s %s Tool, v%d.%d.%d.%04d\n", COMPANY_NAME, TOOL_NAME, _mccVerHi, _mccVerLo, _mccVerRev, _mccBldNum);
fprintf(stderr, "\n");
fprintf(stderr, " incorporating Digital Mars technology\n");
fprintf(stderr, "\n");
if(NULL != reason)
{
fprintf(stderr, " Error: %s\n", reason);
fprintf(stderr, "\n");
}
if(0 < invalidArg)
{
fprintf(stderr, " First invalid argument #%d: %s\n", invalidArg, argv[invalidArg]);
fprintf(stderr, " Arguments were (first bad marked *):\n\n");
for(int i = 1; i < argc; ++i)
{
fprintf(stderr, " %s%s\n", (i == invalidArg) ? "* " : " ", argv[i]);
}
fprintf(stderr, "\n");
}
fprintf(stderr, " USAGE 1: "
"%s [{-w | -r<root-paths> | -p | -i | -l | -e<env-var> | -h}] [-u] [-d] "
"[{<--dirs> | <--directories>}] | [<--files>] "
#if defined(_SYNSOFT_INTERNAL_BUILD) && \
defined(WHEREIS_PLATFORM_IS_WIN32)
"[{-v | -s}] [-f | -F | | -t | -T] [-V] "
#else /* ? _SYNSOFT_INTERNAL_BUILD */
"[{-v | -s}] [-f | -F] "
#endif /* _SYNSOFT_INTERNAL_BUILD */
"[<root-paths>] <search-spec>\n", EXE_NAME);
fprintf(stderr, " where:\n\n");
#if 0
fprintf(stderr, " -c - case-sensitive search\n");
fprintf(stderr, " -C - case-insensitive search; (default)\n");
#endif /* 0 */
fprintf(stderr, " -d - displays the search root path(s)\n");
fprintf(stderr, " -e<env-var> - searches in the directories specified in the environment variable <env-var>\n");
fprintf(stderr, " -f - shows the filename and extension only\n");
fprintf(stderr, " -F - shows the full path; (default) \n");
fprintf(stderr, " -h - searches from the roots of all drives on the system\n");
fprintf(stderr, " -i - searches in the directories specified in the INCLUDE environment variable\n");
fprintf(stderr, " -l - searches in the directories specified in the LIB environment variable\n");
fprintf(stderr, " -m - mark directories with a trailing path separator\n");
// fprintf(stderr, " -n - Prints a total number of files found\n");
//// fprintf(stderr, " -N - Prints only the total number of files found\n");
#if defined(WHEREIS_PLATFORM_IS_WIN32)
fprintf(stderr, " -p - searches in the Windows paths (the directories specified in the PATH environment variable)\n");
fprintf(stderr, " -r<root-paths> - searches from the given root path(s), separated by \';\', e.g.\n");
fprintf(stderr, " -r\"c:\\windows;x:\\bin\"\n");
#elif defined(WHEREIS_PLATFORM_IS_UNIX)
fprintf(stderr, " -p - searches in the system paths (the directories specified in the PATH environment variable)\n");
fprintf(stderr, " -r<root-paths> - searches from the given root path(s), separated by \':\', e.g.\n");
fprintf(stderr, " -r\"/usr/include:/etc\"\n");
#else
# error Unknown platform
#endif /* platform */
fprintf(stderr, " -R - suppresses recursive search\n");
fprintf(stderr, " -s - succinct output. Prints path only\n");
#if defined(_SYNSOFT_INTERNAL_BUILD) && \
defined(WHEREIS_PLATFORM_IS_WIN32)
fprintf(stderr, " -t - trims path relative to the current directory\n");
fprintf(stderr, " -T - trims path relative to the root directory(ies) specified for the search(es)\n");
#endif /* _SYNSOFT_INTERNAL_BUILD */
fprintf(stderr, " -u - recursive search. (Default except for environment variable searches.)\n");
fprintf(stderr, " -v - verbose output. Prints time, attributes, size and path; (default)\n");
#ifdef _SYNSOFT_INTERNAL_BUILD
fprintf(stderr, " -V - displays the version information, if any, for the file. Suppressed by -s\n");
#endif /* _SYNSOFT_INTERNAL_BUILD */
fprintf(stderr, " -w - searches from the current working directory\n");
fprintf(stderr, " -x - summarises the file extensions\n");
fprintf(stderr, " --dirs - search for directories\n");
fprintf(stderr, " --directories - search for directories\n");
fprintf(stderr, " --files - search for files; (default if --files and --dir(ectorie)s not specified)\n");
fprintf(stderr, " <search-spec> - one or more file search specifications, separated by \';\',\n");
fprintf(stderr, " eg.\n");
fprintf(stderr, " \"*.exe\"\n");
fprintf(stderr, " \"myfile.ext\"\n");
fprintf(stderr, " \"*.exe;*.dll\"\n");
fprintf(stderr, " \"*.xl?;report.*\"\n");
fprintf(stderr, "\n");
fprintf(stderr, " USAGE 2: %s -?\n", EXE_NAME);
fprintf(stderr, "\n");
fprintf(stderr, " Displays this help\n");
fprintf(stderr, "\n");
fprintf(stderr, " Contact %s\n", _nameSynesisSoftware);
fprintf(stderr, " at \"%s\",\n", _wwwSynesisSoftware_SystemTools);
fprintf(stderr, " or, via email, at \"%s\"\n", _emailSynesisSoftware_SystemTools);
fprintf(stderr, "\n");
fprintf(stderr, " Contact Digital Mars\n");
fprintf(stderr, " at \"www.digitalmars.com\",\n");
fprintf(stderr, " or, via email, at \"software@digitalmars.com\"\n");
// fprintf(stderr, "\n");
if(bExit)
{
exit(EXIT_FAILURE);
}
}
char const *convert_path_separators(char const *path, char *buffer)
{
#if defined(WHEREIS_PLATFORM_IS_WIN32)
char const chWrong = '/';
#elif defined(WHEREIS_PLATFORM_IS_UNIX)
char const chWrong = '\\';
#else
# error Unknown platform
#endif /* platform */
if( path != 0 &&
0 != strchr(path, chWrong))
{
char *pch;
path = strcpy(buffer, path);
for(pch = buffer; 0 != (pch = strchr(pch + 1, chWrong)); )
{
*pch = PATH_NAME_SEPARATOR;
}
}
return path;
}
#ifdef WHEREIS_PLATFORM_IS_WIN32
char const *get_driveroots(char *const buffer)
{
char drv[4] = "?:\\";
*buffer = '\0';
for(char ch = 'a'; ch <= 'z'; ++ch)
{
drv[0] = ch;
long type = GetDriveTypeA(drv);
if(DRIVE_FIXED == type)
{
strcat(buffer, drv);
strcat(buffer, ";");
}
}
return buffer;
}
#endif /* WHEREIS_PLATFORM_IS_WIN32 */
/* ////////////////////////////////////////////////////////////////////////// */
| 31.829728
| 215
| 0.562001
|
masscry
|
cf33b92f91390297175f9db1e773eeda011fd2dc
| 1,461
|
cpp
|
C++
|
Progs/Ch05/Referst.cpp
|
singhnir/C-Plus-Plus-Robert-Lafore
|
7ce3c92d15958e157484fc989632b879360103aa
|
[
"MIT"
] | 4
|
2021-02-24T06:53:51.000Z
|
2022-02-18T11:15:19.000Z
|
Progs/Ch05/Referst.cpp
|
singhnir/C-Plus-Plus-Robert-Lafore
|
7ce3c92d15958e157484fc989632b879360103aa
|
[
"MIT"
] | null | null | null |
Progs/Ch05/Referst.cpp
|
singhnir/C-Plus-Plus-Robert-Lafore
|
7ce3c92d15958e157484fc989632b879360103aa
|
[
"MIT"
] | 4
|
2021-02-24T07:05:43.000Z
|
2022-03-09T17:45:32.000Z
|
// referst.cpp
// demonstrates passing structure by reference
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
struct Distance //English distance
{
int feet;
float inches;
};
////////////////////////////////////////////////////////////////
void scale( Distance&, float ); //function
void engldisp( Distance ); //declarations
int main()
{
Distance d1 = { 12, 6.5 }; //initialize d1 and d2
Distance d2 = { 10, 5.5 };
cout << "d1 = "; engldisp(d1); //display old d1 and d2
cout << "\nd2 = "; engldisp(d2);
scale(d1, 0.5); //scale d1 and d2
scale(d2, 0.25);
cout << "\nd1 = "; engldisp(d1); //display new d1 and d2
cout << "\nd2 = "; engldisp(d2);
cout << endl;
return 0;
}
//--------------------------------------------------------------
// scale()
// scales value of type Distance by factor
void scale( Distance& dd, float factor)
{
float inches = (dd.feet*12 + dd.inches) * factor;
dd.feet = static_cast<int>(inches / 12);
dd.inches = inches - dd.feet * 12;
}
//--------------------------------------------------------------
// engldisp()
// display structure of type Distance in feet and inches
void engldisp( Distance dd ) //parameter dd of type Distance
{
cout << dd.feet << "\'-" << dd.inches << "\"";
}
| 31.085106
| 65
| 0.450376
|
singhnir
|
cf3b5ad84e6ad780c89f9600ea72d405d86631b9
| 738
|
cpp
|
C++
|
src/QtGadgets/Validators/nRegExpValidator.cpp
|
Vladimir-Lin/QtGadgets
|
5fcea23ca95d85088d68fa64996e16281549ec3c
|
[
"MIT"
] | null | null | null |
src/QtGadgets/Validators/nRegExpValidator.cpp
|
Vladimir-Lin/QtGadgets
|
5fcea23ca95d85088d68fa64996e16281549ec3c
|
[
"MIT"
] | null | null | null |
src/QtGadgets/Validators/nRegExpValidator.cpp
|
Vladimir-Lin/QtGadgets
|
5fcea23ca95d85088d68fa64996e16281549ec3c
|
[
"MIT"
] | null | null | null |
#include <qtgadgets.h>
N::RegExpValidator:: RegExpValidator ( QObject * parent )
: QRegExpValidator ( parent )
, Validator ( parent )
{
}
N::RegExpValidator::~RegExpValidator (void)
{
}
int N::RegExpValidator::Type(void) const
{
return 1102 ;
}
void N::RegExpValidator::Fixup(QString & input) const
{
QRegExpValidator::fixup(input) ;
}
QLocale N::RegExpValidator::Locale(void) const
{
return QRegExpValidator::locale() ;
}
void N::RegExpValidator::setLocale (const QLocale & locale)
{
QRegExpValidator::setLocale(locale) ;
}
QValidator::State N::RegExpValidator::isValid(QString & input,int & pos) const
{
return QRegExpValidator::validate(input,pos) ;
}
| 19.945946
| 78
| 0.658537
|
Vladimir-Lin
|
cf3d9a79062dafd4f1fe432932c9b68a30ce0998
| 1,097
|
cpp
|
C++
|
c++/primer_plus_s_pratt/ch_9/pr_ex4/sales.cpp
|
dinimar/Projects
|
7606c23c4e55d6f0c03692b4a1d2bb5b42f10992
|
[
"MIT"
] | null | null | null |
c++/primer_plus_s_pratt/ch_9/pr_ex4/sales.cpp
|
dinimar/Projects
|
7606c23c4e55d6f0c03692b4a1d2bb5b42f10992
|
[
"MIT"
] | null | null | null |
c++/primer_plus_s_pratt/ch_9/pr_ex4/sales.cpp
|
dinimar/Projects
|
7606c23c4e55d6f0c03692b4a1d2bb5b42f10992
|
[
"MIT"
] | null | null | null |
#ifndef SALES_H
#define SALES_H
#include "sales.h"
#endif
#include <iostream>
using namespace std;
namespace SALES
{
void setSales(Sales &s, const double ar[], int n)
{
int count = 0;
double max, min, ave = ar[0];
for(int i=0;i<n and i<QUARTERS;++i)
{
s.sales[i] = ar[i];
count++;
if(max < ar[i]) max = ar[i];
if(min > ar[i]) min = ar[i];
ave += ar[i];
}
for(int i=count;i<QUARTERS;++i) s.sales[i]=0;
ave /= QUARTERS;
s.min = min;
s.max = max;
s.average = ave;
}
void setSales(Sales &s)
{
double max, min, ave = 0;
for(int i=0;i<QUARTERS;++i)
{
cin >> s.sales[i];
if(max < s.sales[i]) max = s.sales[i];
if(min > s.sales[i]) min = s.sales[i];
ave += s.sales[i];
}
ave /= QUARTERS;
s.min = min;
s.max = max;
s.average = ave;
}
void showSales(const Sales &s)
{
cout << "Sales\n" << "[";
for (int i=0;i<QUARTERS-1;++i)
{
cout << s.sales[i] << ", ";
}
cout << s.sales[3] << "]\n";
cout << "Max: " << s.max << endl;
cout << "Min: " << s.min << endl;
cout << "Average: " << s.average << endl;
}
}
| 15.671429
| 50
| 0.52051
|
dinimar
|
cf3dac6ef0e6d5ca630943ed95d601a3080002e5
| 2,746
|
cpp
|
C++
|
src/Kepler3rdLaw.cpp
|
wstern1234/CPP-Projects
|
e8712171355b7a833f8a63ce0ffa49dcca10b053
|
[
"MIT"
] | null | null | null |
src/Kepler3rdLaw.cpp
|
wstern1234/CPP-Projects
|
e8712171355b7a833f8a63ce0ffa49dcca10b053
|
[
"MIT"
] | null | null | null |
src/Kepler3rdLaw.cpp
|
wstern1234/CPP-Projects
|
e8712171355b7a833f8a63ce0ffa49dcca10b053
|
[
"MIT"
] | null | null | null |
// Identification comments code block
// Wills Stern
// Kepler's 3rd Law
// Editor(s) used: VS Code
// Compiler(s) used: g++
#include <iostream>
using std::cout;
using std::cin;
#include <string>
using std::string;
using std::endl;
#include <cctype> // for toupper
#include <cstdlib> // for atof
#include <cmath> // for sqrt, pow, and cbrt
// function prototypes
double findPeriod();
double findAU();
int main()
{
// identification output code block
cout << "Wills Stern\n\n";
cout << "Kepler's 3rd Law\n";\
cout << "Editor(s) used: VSCode\n";
cout << "Compiler(s) used: g++\n";
cout << "File: " << __FILE__ << "\n";
cout << "Compiled: " << __DATE__ << " at " << __TIME__ << "\n\n\n\n";
char opt;
// infinite loop, continuely asks user for data unless 'Q'/'q' is entered
while (true)
{
// menu with two options
cout << "p² = a³\n\n";
cout << "Options:\n";
cout << " P: find orbital Period\n";
cout << " A: find distance in AU" << endl;
cout << "Option: ";
cin >> opt; // char variable, so no need for buffer
// breaks with 'Q' or 'q'
if (toupper(opt) == 'Q') break;
// outputs the orbital period in years
else if (toupper(opt) == 'P')
cout << "\n" << findPeriod() << " years\n\n\n" << endl;
// outputs the distance from the Sun in Astronomical Units (AU)
else if (toupper(opt) == 'A')
cout << "\n" << findAU() << " AU\n\n\n" << endl;
// invalid input, continues on with loop
else cout << "\nNot an option, try again.\n\n\n" << endl;
}
}
/*************************************************************
* Purpose: Finds the time for an object to orbit the Sun in Earth years
*
* Parameters: (None)
*
* Return: Time for an object to orbit the Sun in Earth years as a double
**************************************************************/
double findPeriod()
{
string buf;
cout << "Enter distance in Astronomical Units (AU): ";
// uses buffer input method for safety
cin >> buf; double distance = atof(buf.c_str());
// Kelper's 3rd Law of Planetary Motion: p² = a³
// ...becomes p = a⁽³ᐟ²⁾
return ( sqrt(pow(distance, 3)) );
}
/*************************************************************
* Purpose: Finds the distance of an object from the Sun in AU
*
* Parameters: (None)
*
* Return: Distance of the object from the Sun in AU as a double
**************************************************************/
double findAU()
{
string buf;
cout << "Enter orbital period in Earth years: ";
// uses buffer input method for safety
cin >> buf; double period = atof(buf.c_str());
// Kelper's 3rd Law of Planetary Motion: p² = a³
// ...becomes a = p⁽²ᐟ³⁾
return ( cbrt(pow(period, 2)) );
}
| 22.145161
| 75
| 0.550255
|
wstern1234
|
cf3e39d26b98da0c54f6d62a7faae7c489feb69d
| 17,443
|
hpp
|
C++
|
tests/unit/coherence/util/CircularArrayListTest.hpp
|
chpatel3/coherence-cpp-extend-client
|
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
|
[
"UPL-1.0",
"Apache-2.0"
] | 6
|
2020-07-01T21:38:30.000Z
|
2021-11-03T01:35:11.000Z
|
tests/unit/coherence/util/CircularArrayListTest.hpp
|
chpatel3/coherence-cpp-extend-client
|
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
|
[
"UPL-1.0",
"Apache-2.0"
] | 1
|
2020-07-24T17:29:22.000Z
|
2020-07-24T18:29:04.000Z
|
tests/unit/coherence/util/CircularArrayListTest.hpp
|
chpatel3/coherence-cpp-extend-client
|
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
|
[
"UPL-1.0",
"Apache-2.0"
] | 6
|
2020-07-10T18:40:58.000Z
|
2022-02-18T01:23:40.000Z
|
/*
* Copyright (c) 2000, 2020, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*/
#include "cxxtest/TestSuite.h"
#include "coherence/lang.ns"
#include "coherence/util/CircularArrayList.hpp"
#include "private/coherence/util/logging/Logger.hpp"
using namespace coherence::lang;
using namespace std;
/**
* Test suite for the CircularArrayList object.
*
* 2008.02.08 nsa
*/
class CircularArrayListTest : public CxxTest::TestSuite
{
public:
void testAddIndex()
{
CircularArrayList::Handle hList = CircularArrayList::create();
String::Handle hValue = String::create("Test Value");
String::Handle hValue2 = String::create("TV2");
hList->add(hValue);
hList->add(0, hValue2);
TS_ASSERT(hList->size() == 2);
TS_ASSERT(hList->get(0)->equals(hValue2));
}
void testAddAllIndex()
{
CircularArrayList::Handle hList = CircularArrayList::create();
for (int32_t x = 0; x < 10; ++x)
{
hList->add(COH_TO_STRING("List Value: " << x));
}
TS_ASSERT(hList->size() == 10);
CircularArrayList::Handle hList2 = CircularArrayList::create();
String::Handle hList2Value = String::create("hList2");
hList2->add(hList2Value);
hList2->addAll(0, hList);
TS_ASSERT(hList2->size() == 11);
TS_ASSERT(hList2->get(10) == hList2Value);
}
void testGet()
{
CircularArrayList::Handle hList = CircularArrayList::create();
String::Handle hValue = String::create("Test Value");
hList->add(hValue);
TS_ASSERT(hList->get(0)->equals(hValue));
String::Handle hValue2 = String::create("Test Value 2");
hList->add(hValue2);
TS_ASSERT(hList->get(1)->equals(hValue2));
}
void testIndexOf()
{
CircularArrayList::Handle hList = CircularArrayList::create();
String::Handle findMe;
String::Handle notFound = String::create("Can't Find Me");
for (int32_t x = 0; x < 10; ++x)
{
String::Handle hString = COH_TO_STRING("List Value: " << x);
if (x == 5)
{
findMe = hString;
}
hList->add(hString);
}
TS_ASSERT(hList->indexOf(findMe) == 5);
TS_ASSERT(hList->indexOf(notFound) == List::npos);
}
void testLastIndexOf()
{
CircularArrayList::Handle hList = CircularArrayList::create();
String::Handle hDup = String::create("DuplicateString");
String::Handle hNotFound = String::create("Can't find me");
for (int32_t x = 0; x < 10; ++x)
{
if (x % 2 == 0)
{
hList->add(hDup);
}
else
{
hList->add(COH_TO_STRING("List Value: " << x));
}
}
TS_ASSERT(hList->lastIndexOf(hDup) == 8);
TS_ASSERT(hList->lastIndexOf(hNotFound) == List::npos);
}
void testListIterator()
{
CircularArrayList::Handle hList = CircularArrayList::create();
TS_ASSERT_EQUALS(hList->listIterator()->hasNext(), false);
TS_ASSERT_EQUALS(hList->listIterator()->hasPrevious(), false);
int32_t x;
for (x = 0; x < 10; ++x)
{
hList->add(Integer32::create(x));
}
TS_ASSERT_EQUALS(hList->size(), size32_t(10));
ListIterator::Handle hIterator = hList->listIterator();
TS_ASSERT_EQUALS(hList->listIterator()->hasPrevious(), false);
x = 0;
while (hIterator->hasNext())
{
Integer32::Handle hValue = cast<Integer32::Handle>(hIterator->next());
TS_ASSERT_EQUALS(hValue->getValue(), x);
x++;
}
TS_ASSERT_EQUALS(x, 10);
while (hIterator->hasPrevious())
{
--x;
Integer32::Handle hValue = cast<Integer32::Handle>(hIterator->previous());
TS_ASSERT_EQUALS(hValue->getValue(), x);
}
TS_ASSERT(x == 0);
while (hIterator->hasNext())
{
Integer32::Handle hValue = cast<Integer32::Handle>(hIterator->next());
TS_ASSERT_EQUALS(hValue->getValue(), x);
++x;
}
TS_ASSERT(x == 10);
}
void testListIteratorIndex()
{
CircularArrayList::Handle hList = CircularArrayList::create();
int32_t x;
for (x = 0; x < 10; ++x)
{
hList->add(Integer32::create(x));
}
x = 5;
ListIterator::Handle hIterator = hList->listIterator(x);
while (hIterator->hasNext())
{
Integer32::Handle hValue = cast<Integer32::Handle>(hIterator->next());
TS_ASSERT_EQUALS(hValue->getValue(), x);
++x;
}
TS_ASSERT_EQUALS(x, 10);
while (hIterator->hasPrevious())
{
--x;
Integer32::Handle hValue = cast<Integer32::Handle>(hIterator->previous());
TS_ASSERT_EQUALS(hValue->getValue(), x);
}
TS_ASSERT_EQUALS(x, 0);
while (hIterator->hasNext())
{
Integer32::Handle hValue = cast<Integer32::Handle>(hIterator->next());
TS_ASSERT_EQUALS(hValue->getValue(), x);
++x;
}
TS_ASSERT_EQUALS(x, 10);
}
void testListMuterator()
{
CircularArrayList::Handle hList = CircularArrayList::create();
TS_ASSERT_EQUALS(hList->listIterator()->hasNext(), false);
TS_ASSERT_EQUALS(hList->listIterator()->hasPrevious(), false);
size32_t x;
ListMuterator::Handle hMiter = hList->listIterator();
for (x = 0; x < 10; ++x)
{
hMiter->add(Integer32::create(x));
}
TS_ASSERT_EQUALS(hList->size(), x);
while (hMiter->hasPrevious())
{
--x;
Integer32::Handle hValue = cast<Integer32::Handle>(hMiter->previous());
TS_ASSERT_EQUALS(hValue->getValue(), (int32_t)x);
hMiter->remove();
TS_ASSERT(hMiter->hasNext() == false)
}
TS_ASSERT_EQUALS(x, 0u);
TS_ASSERT_EQUALS(hList->size(), x);
for (x = 0; x < 5; ++x)
{
hMiter->add(Integer32::create(x * 2));
}
TS_ASSERT_EQUALS(hList->size(), x);
hMiter = hList->listIterator();
for (x = 0; x < 10; x += 2)
{
hMiter->next();
hMiter->add(Integer32::create(x + 1));
}
TS_ASSERT_EQUALS(hList->size(), x);
while (hMiter->hasPrevious())
{
--x;
Integer32::Handle hValue = cast<Integer32::Handle>(hMiter->previous());
TS_ASSERT_EQUALS(hValue->getValue(), (int32_t)x);
}
size32_t iNextExpected = 0;
for (x = 0; x < 10; x += 2)
{
TS_ASSERT_EQUALS(hMiter->nextIndex(), iNextExpected);
Integer32::Handle hValue = cast<Integer32::Handle>(hMiter->next());
++iNextExpected;
TS_ASSERT_EQUALS(hValue->getValue(), (int32_t)x);
TS_ASSERT_EQUALS(hMiter->previousIndex(), iNextExpected - 1);
hMiter->remove();
--iNextExpected;
hMiter->next();
++iNextExpected;
}
TS_ASSERT_EQUALS(hList->size(), x/2);
hMiter = hList->listIterator();
for (x = 1; x < 10; x += 2)
{
Integer32::Handle hValue = cast<Integer32::Handle>(hMiter->next());
TS_ASSERT_EQUALS(hValue->getValue(), (int32_t)x);
hMiter->set(Integer32::create(x + 1));
}
hMiter = hList->listIterator();
for (x = 1; x < 10; x += 2)
{
Integer32::Handle hValue = cast<Integer32::Handle>(hMiter->next());
TS_ASSERT_EQUALS(hValue->getValue(), (int32_t)(x + 1));
}
// test next/prev toggle
hMiter = hList->listIterator();
size32_t iNext = hMiter->nextIndex();
Object::View vNext = hMiter->next();
size32_t iPrev = hMiter->previousIndex();
Object::View vPrev = hMiter->previous();
TS_ASSERT_EQUALS(vNext, vPrev);
TS_ASSERT_EQUALS(iNext, iPrev);
iNext = hMiter->nextIndex();
vNext = hMiter->next();
TS_ASSERT_EQUALS(vNext, vPrev);
TS_ASSERT_EQUALS(iNext, iPrev);
}
void testRemoveIndex()
{
CircularArrayList::Handle hList = CircularArrayList::create();
String::Handle s1 = String::create("test1");
String::Handle s2 = String::create("test2");
hList->add(s1);
hList->add(s2);
TS_ASSERT(hList->remove(1)->equals(s2));
TS_ASSERT(hList->size() == 1u);
}
void testSetIndex()
{
CircularArrayList::Handle hList = CircularArrayList::create();
String::Handle s1 = String::create("test1");
String::Handle s2 = String::create("test2");
String::Handle s3 = String::create("test3");
hList->add(s1);
hList->add(s2);
TS_ASSERT(hList->get(1)->equals(s2));
hList->set(1, s3);
TS_ASSERT(hList->get(1)->equals(s3));
TS_ASSERT(hList->size() == 2u);
}
void testSubList()
{
CircularArrayList::Handle hList = CircularArrayList::create();
for (int32_t x = 0; x < 10; ++x)
{
hList->add(COH_TO_STRING("List Value: " << x));
}
List::Handle hSub = hList->subList(1, 6);
TS_ASSERT(hSub->size() == 5u);
hSub->add(String::create("New Sub Value"));
TS_ASSERT(hSub->size() == 6u);
TS_ASSERT(hList->size() == 11u);
Iterator::Handle hIter = hSub->iterator();
while (hIter->hasNext())
{
TS_ASSERT(hList->contains(hIter->next()));
}
}
void testSize()
{
CircularArrayList::Handle hList = CircularArrayList::create();
for (int32_t x = 0; x < 10; ++x)
{
hList->add(COH_TO_STRING("List Value: " << x));
}
TS_ASSERT(hList->size() == 10u);
}
void testIterator()
{
CircularArrayList::Handle hList = CircularArrayList::create();
int32_t x;
for (x = 0; x < 10; ++x)
{
hList->add(COH_TO_STRING("List Value: " << x));
}
Iterator::Handle hIterator = hList->iterator();
x = 0;
while (hIterator->hasNext())
{
String::Handle hString = cast<String::Handle>(hIterator->next());
x++;
}
TS_ASSERT(x == 10);
}
void testAdd()
{
CircularArrayList::Handle hList = CircularArrayList::create();
String::Handle hValue = String::create("Test Value");
hList->add(hValue);
TS_ASSERT(hList->size() == 1u);
TS_ASSERT(hList->get(0)->equals(hValue));
}
void testAddAll()
{
CircularArrayList::Handle hList = CircularArrayList::create();
for (int32_t x = 0; x < 10; ++x)
{
hList->add(COH_TO_STRING("List Value: " << x));
}
TS_ASSERT(hList->size() == 10u);
CircularArrayList::Handle hList2 = CircularArrayList::create();
String::Handle hList2Value = String::create("hList2");
hList2->add(hList2Value);
hList2->addAll(hList);
TS_ASSERT(hList2->size() == 11u);
TS_ASSERT(hList2->get(10) == hList->get(hList->size() - 1));
}
void testRemove()
{
String::Handle h1 = String::create("h1");
String::Handle h2 = String::create("h2");
CircularArrayList::Handle hList = CircularArrayList::create();
hList->add(h1);
hList->add(h2);
TS_ASSERT(hList->size() == 2u);
hList->remove(h2);
TS_ASSERT(hList->size() == 1u);
}
void testRemoveAll()
{
CircularArrayList::Handle hList = CircularArrayList::create();
for (int32_t x = 0; x < 10; ++x)
{
hList->add(COH_TO_STRING("List Value: " << x));
}
TS_ASSERT(hList->size() == 10);
CircularArrayList::Handle hList2 = CircularArrayList::create();
String::Handle hList2Value = String::create("hList2");
String::Handle hList2Valueb = String::create("hList2b");
hList2->add(hList2Value);
hList2->add(hList2Valueb);
hList->addAll(hList2);
TS_ASSERT(hList->size() == 12u);
hList->removeAll(hList2);
TS_ASSERT(hList->size() == 10u);
}
void testRetainAll()
{
CircularArrayList::Handle hList = CircularArrayList::create();
for (int32_t x = 0; x < 10; ++x)
{
hList->add(COH_TO_STRING("List Value: " << x));
}
TS_ASSERT(hList->size() == 10u);
CircularArrayList::Handle hList2 = CircularArrayList::create();
String::Handle hList2Value = String::create("hList2");
String::Handle hList2Valueb = String::create("hList2b");
hList2->add(hList2Value);
hList2->add(hList2Valueb);
hList->addAll(hList2);
TS_ASSERT(hList->size() == 12u);
hList->retainAll(hList2);
TS_ASSERT(hList->size() == 2u);
}
void testClear()
{
CircularArrayList::Handle hList = CircularArrayList::create();
for (int32_t x = 0; x < 10; ++x)
{
hList->add(COH_TO_STRING("List Value: " << x));
}
TS_ASSERT(hList->size() == 10u);
hList->clear();
TS_ASSERT(hList->size() == 0u);
hList->add(String::create("foo"));
TS_ASSERT(hList->size() == 1u);
}
void testClone()
{
CircularArrayList::Handle hList = CircularArrayList::create();
hList->add(String::create("test"));
hList->add(String::create("test2"));
CircularArrayList::View vList = hList;
CircularArrayList::Handle hListClone = cast<CircularArrayList::Handle>(vList->clone());
TS_ASSERT(hListClone->size() == 2u);
TS_ASSERT(cast<String::View>(hListClone->get(0))->equals("test"));
TS_ASSERT(cast<String::View>(hListClone->get(1))->equals("test2"));
}
void testCleanup()
{
HeapAnalyzer::Snapshot::View vSnap = HeapAnalyzer::ensureHeap();
CircularArrayList::Handle hList = CircularArrayList::create();
for (int32_t i = 0; i < 10; ++i)
{
hList->add(Integer32::create(i));
}
hList = NULL;
HeapAnalyzer::ensureHeap(vSnap);
}
void testBigList()
{
HeapAnalyzer::Snapshot::View vSnap = HeapAnalyzer::ensureHeap();
CircularArrayList::Handle hList = CircularArrayList::create();
for (int32_t i = 0; i < 10000; ++i)
{
hList->add(Integer32::create(i));
}
MemberHandle<List> hEscape(System::common(), hList);
int32_t n = 0;
for (Iterator::Handle hIter = hList->iterator(); hIter->hasNext(); )
{
Integer32::Handle hN = cast<Integer32::Handle>(hIter->next());
TS_ASSERT(hN->getValue() == n++);
TS_ASSERT(hN->_isEscaped());
}
TS_ASSERT(n == 10000);
hEscape = NULL;
hList->_isEscaped(); // unescape
hList = NULL; // delete
HeapAnalyzer::ensureHeap(vSnap);
}
};
| 32.301852
| 98
| 0.480193
|
chpatel3
|
cf54a1975be0c92f61cc83bc42ca252674bcfe2f
| 18,260
|
cpp
|
C++
|
src/SystemConfigurator/CSPs/DiagnosticLogCSP.cpp
|
mehrdad-shokri/iot-core-azure-dm-client
|
09c203f158c5f66a5bd2e508a7d50ac2e1372b89
|
[
"MIT"
] | 52
|
2017-05-02T09:43:39.000Z
|
2021-11-11T18:32:46.000Z
|
src/SystemConfigurator/CSPs/DiagnosticLogCSP.cpp
|
mehrdad-shokri/iot-core-azure-dm-client
|
09c203f158c5f66a5bd2e508a7d50ac2e1372b89
|
[
"MIT"
] | 161
|
2017-04-07T19:04:26.000Z
|
2020-09-21T12:42:22.000Z
|
src/SystemConfigurator/CSPs/DiagnosticLogCSP.cpp
|
mehrdad-shokri/iot-core-azure-dm-client
|
09c203f158c5f66a5bd2e508a7d50ac2e1372b89
|
[
"MIT"
] | 67
|
2017-03-31T00:33:02.000Z
|
2021-03-06T00:34:33.000Z
|
/*
Copyright 2017 Microsoft
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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <stdafx.h>
#include <filesystem>
#include <fstream>
#include <iomanip>
#include "..\SharedUtilities\Logger.h"
#include "..\SharedUtilities\Utils.h"
#include "MdmProvision.h"
#include "DiagnosticLogCSP.h"
using namespace std;
using namespace Microsoft::Devices::Management::Message;
const wchar_t* DiagnosticLogCSPWorkingFolder = L"C:\\Data\\Users\\Public\\Documents";
const wchar_t* CSPQuerySuffix = L"?list=StructData";
const wchar_t* CSPCollectorsRoot = L"./Vendor/MSFT/DiagnosticLog/EtwLog/Collectors";
const wchar_t* CSPTrue = L"TRUE";
const wchar_t* CSPNodeType = L"node";
// Collectors
const wchar_t* CSPTraceStatus = L"TraceStatus";
const wchar_t* CSPTraceLogFileMode = L"TraceLogFileMode";
const wchar_t* CSPLogFileSizeLimitMB = L"LogFileSizeLimitMB";
const wchar_t* CSPProvidersNode = L"Providers";
const wchar_t* CSPTraceControl = L"TraceControl";
const wchar_t* CSPTraceControlStart = L"START";
const wchar_t* CSPTraceControlStop = L"STOP";
// Providers
const wchar_t* CSPTraceLevel = L"TraceLevel";
const wchar_t* CSPKeywords = L"Keywords";
const wchar_t* CSPState = L"State";
// Download Channel
const wchar_t* CSPDataChannel = L"./Vendor/MSFT/DiagnosticLog/FileDownload/DMChannel";
const wchar_t* CSPBlockCount = L"BlockCount";
const wchar_t* CSPBlockIndexToRead = L"BlockIndexToRead";
const wchar_t* CSPBlockData = L"BlockData";
const wchar_t* JsonNoString = L"no";
const wchar_t* JsonYesString = L"yes";
const wchar_t* JsonFileModeSequential = L"sequential";
const wchar_t* JsonFileModeCircular = L"circular";
const wchar_t* JsonTraceLevelCritical = L"critical";
const wchar_t* JsonTraceLevelError = L"error";
const wchar_t* JsonTraceLevelWarning = L"warning";
const wchar_t* JsonTraceLevelInformation = L"information";
const wchar_t* JsonTraceLevelVerbose = L"verbose";
IResponse^ DiagnosticLogCSP::HandleGetEventTracingConfiguration(IRequest^ request)
{
TRACE(__FUNCTION__);
map<wstring, CollectorReportedConfiguration^> encounteredCollectorsMap;
GetEventTracingConfigurationResponse^ response = ref new GetEventTracingConfigurationResponse(ResponseStatus::Success);
std::function<void(std::vector<std::wstring>&, std::wstring&)> valueHandler =
[response, &encounteredCollectorsMap](vector<wstring>& uriTokens, wstring& value)
{
if (uriTokens.size() < 7)
{
return;
}
wstring cspCollectorName = uriTokens[6];
CollectorReportedConfiguration^ currentCollector;
// 0/__1___/_2__/______3______/__4___/____5_____/___6___/
// ./Vendor/MSFT/DiagnosticLog/EtwLog/Collectors/AzureDM
map<wstring, CollectorReportedConfiguration^>::iterator it = encounteredCollectorsMap.find(cspCollectorName);
if (it == encounteredCollectorsMap.end())
{
wstring collectorRegistryPath = RegEventTracing;
collectorRegistryPath += L"\\";
collectorRegistryPath += cspCollectorName.c_str();
currentCollector = ref new CollectorReportedConfiguration();
currentCollector->Name = ref new String(cspCollectorName.c_str());
wstring reportToDeviceTwin = Utils::ReadRegistryValue(collectorRegistryPath, RegReportToDeviceTwin, JsonNoString /*default*/);
currentCollector->ReportToDeviceTwin = ref new String(reportToDeviceTwin.c_str());
currentCollector->CSPConfiguration->LogFileFolder = ref new String(Utils::ReadRegistryValue(collectorRegistryPath, RegEventTracingLogFileFolder, cspCollectorName /*default*/).c_str());
currentCollector->CSPConfiguration->LogFileName = ref new String(Utils::ReadRegistryValue(collectorRegistryPath, RegEventTracingLogFileName, L"" /*default*/).c_str());
// Add it to the collectors list...
response->Collectors->Append(currentCollector);
// Save it in the collectors map so that we can find it easily next time
// we need it while processing another token...
encounteredCollectorsMap[cspCollectorName] = currentCollector;
}
else
{
currentCollector = it->second;
}
if (uriTokens.size() >= 8)
{
// 0/__1___/_2__/______3______/__4___/____5_____/___6___/____7______/
// ./Vendor/MSFT/DiagnosticLog/EtwLog/Collectors/AzureDM/TraceStatus
if (uriTokens[7] == CSPTraceStatus)
{
currentCollector->CSPConfiguration->Started = std::stoi(value) == 1 ? true : false;
}
else if (uriTokens[7] == CSPTraceLogFileMode)
{
currentCollector->CSPConfiguration->TraceLogFileMode = ref new String(std::stoi(value) == 1 ? JsonFileModeSequential : JsonFileModeCircular);
}
else if (uriTokens[7] == CSPLogFileSizeLimitMB)
{
currentCollector->CSPConfiguration->LogFileSizeLimitMB = std::stoi(value);
}
}
// Is this something under the Providers node?
if (uriTokens.size() >= 9 && uriTokens[7] == CSPProvidersNode)
{
// 0/__1___/_2__/______3______/__4___/____5_____/___6___/____7____/_8__
// ./Vendor/MSFT/DiagnosticLog/EtwLog/Collectors/AzureDM/Providers/guid
// Make sure the Providers list exists...
if (currentCollector->CSPConfiguration->Providers == nullptr)
{
currentCollector->CSPConfiguration->Providers = ref new Vector<ProviderConfiguration^>();
}
// Do we already have this provider?
ProviderConfiguration^ currentProvider;
for (auto provider : currentCollector->CSPConfiguration->Providers)
{
if (0 == _wcsicmp(provider->Guid->Data(), uriTokens[8].c_str()))
{
currentProvider = provider;
}
}
// If we don't already have the provider, create a new one...
if (currentProvider == nullptr)
{
ProviderConfiguration^ provider = ref new ProviderConfiguration();
provider->Guid = ref new String(uriTokens[8].c_str());
currentCollector->CSPConfiguration->Providers->Append(provider);
currentProvider = provider;
}
// Is this a sub-property of the current provider?
if (uriTokens.size() >= 10)
{
// 0/__1___/_2__/______3______/__4___/____5_____/___6___/___7_____/_8__/____9____
// ./Vendor/MSFT/DiagnosticLog/EtwLog/Collectors/AzureDM/Providers/guid/TraceLevel
if (uriTokens[9] == CSPTraceLevel)
{
wstring jsonValue;
if (value == L"1")
{
jsonValue = JsonTraceLevelCritical;
}
else if (value == L"2")
{
jsonValue = JsonTraceLevelError;
}
else if (value == L"3")
{
jsonValue = JsonTraceLevelWarning;
}
else if (value == L"4")
{
jsonValue = JsonTraceLevelInformation;
}
else if (value == L"5")
{
jsonValue = JsonTraceLevelVerbose;
}
currentProvider->TraceLevel = ref new String(jsonValue.c_str());
}
else if (uriTokens[9] == CSPKeywords)
{
currentProvider->Keywords = ref new String(value.c_str());
}
else if (uriTokens[9] == CSPState)
{
currentProvider->Enabled = (0 == _wcsicmp(value.c_str(), CSPTrue)) ? true : false;
}
}
}
};
wstring cspQuery;
cspQuery += CSPCollectorsRoot;
cspQuery += CSPQuerySuffix;
MdmProvision::RunGetStructData(cspQuery, valueHandler);
return response;
}
wstring DiagnosticLogCSP::GetFormattedTime()
{
TRACE(__FUNCTION__);
time_t now;
time(&now);
tm nowParsed;
errno_t errCode = localtime_s(&nowParsed, &now);
if (errCode != 0)
{
string errorMessage = "Error: could not obtain local time.";
TRACE(errorMessage.c_str());
throw DMException(errorMessage.c_str());
}
basic_ostringstream<wchar_t> nowString;
nowString << (nowParsed.tm_year + 1900) << L"_";
nowString << setw(2) << setfill(L'0') << (nowParsed.tm_mon + 1) << L"_";
nowString << setw(2) << setfill(L'0') << nowParsed.tm_mday << L"_";
nowString << setw(2) << setfill(L'0') << nowParsed.tm_hour << L"_";
nowString << setw(2) << setfill(L'0') << nowParsed.tm_min << L"_";
nowString << setw(2) << setfill(L'0') << nowParsed.tm_sec;
return nowString.str();
}
void DiagnosticLogCSP::CreateEtlFile(CollectorDesiredConfiguration^ collector)
{
TRACE(__FUNCTION__);
// The etl file will be created in a folder like this:
// c:\Data\Users\DefaultAccount\AppData\Local\Temp\<collector's folder>
// Construct the data channel...
wstring collectorFileCSPPath;
collectorFileCSPPath += CSPDataChannel;
collectorFileCSPPath += L"/";
collectorFileCSPPath += collector->Name->Data();
// Read data from CSP into our buffers...
vector<vector<char>> decryptedEtlBuffer;
int blockCount = 0;
if (MdmProvision::TryGetNumber(collectorFileCSPPath + L"/" + CSPBlockCount, blockCount))
{
for (int i = 0; i < blockCount; ++i)
{
MdmProvision::RunSet(collectorFileCSPPath + L"/" + CSPBlockIndexToRead, i);
wstring blockData = MdmProvision::RunGetBase64(collectorFileCSPPath + L"/BlockData");
vector<char> decryptedBlock;
Utils::Base64ToBinary(blockData, decryptedBlock);
decryptedEtlBuffer.push_back(decryptedBlock);
}
}
// Make sure the target folder exists...
wstring etlFolderName;
etlFolderName += Utils::GetDmUserFolder();
etlFolderName += L"\\";
etlFolderName += collector->CSPConfiguration->LogFileFolder->Data();
CreateDirectory(etlFolderName.c_str(), NULL);
// Construct the file name...
wstring etlFileName;
if (collector->CSPConfiguration->LogFileName->Length() == 0)
{
etlFileName += collector->Name->Data();
etlFileName += L"_";
etlFileName += GetFormattedTime();
etlFileName += L".etl";
}
else
{
etlFileName = collector->CSPConfiguration->LogFileName->Data();
}
wstring etlFullFileName = etlFolderName + L"\\" + etlFileName;
TRACEP(L"ETL Full File Name: ", etlFullFileName.c_str());
// Write the buffers to disk...
ofstream etlFile(etlFullFileName, ios::out | ios::binary);
for (auto it = decryptedEtlBuffer.begin(); it != decryptedEtlBuffer.end(); it++)
{
etlFile.write(it->data(), it->size());
}
etlFile.close();
}
void DiagnosticLogCSP::ApplyCollectorConfiguration(const wstring& cspRoot, CollectorDesiredConfiguration^ collector)
{
TRACE(__FUNCTION__);
// Some validation...
// If there is no configuration, there is no need to continue.
if (collector->CSPConfiguration == nullptr)
{
TRACE(L"Warning: CSPConfiguration is nullptr.");
return;
}
// ETL files cannot be saved to the IoTDM folder.
// They have to be saved to a subfolder of IoTDM.
if (collector->CSPConfiguration->LogFileFolder == nullptr ||
collector->CSPConfiguration->LogFileFolder->Length() == 0)
{
TRACE(L"Warning: LogFileFolder is null or empty. Using collector name as the LogFileFolder.");
collector->CSPConfiguration->LogFileFolder = collector->Name;
}
// Make sure the user is not trying to access any files outside the IoTDM folder.
if (nullptr != wcsstr(collector->CSPConfiguration->LogFileFolder->Data(), L"..") ||
nullptr != wcsstr(collector->CSPConfiguration->LogFileFolder->Data(), L"\\") ||
nullptr != wcsstr(collector->CSPConfiguration->LogFileFolder->Data(), L"/"))
{
string errorMessage = "Error: LogFileFolder cannot contain '/', '\\', or '..'.";
TRACE(errorMessage.c_str());
throw DMException(errorMessage.c_str());
}
if (collector->CSPConfiguration->LogFileName->Length() != 0)
{
if (nullptr != wcsstr(collector->CSPConfiguration->LogFileName->Data(), L"..") ||
nullptr != wcsstr(collector->CSPConfiguration->LogFileName->Data(), L"\\") ||
nullptr != wcsstr(collector->CSPConfiguration->LogFileName->Data(), L"/"))
{
string errorMessage = "Error: LogFileName cannot contain '/', '\\', or '..'.";
TRACE(errorMessage.c_str());
throw DMException(errorMessage.c_str());
}
}
// Build paths...
const wstring collectorCSPPath = cspRoot + L"/" + collector->Name->Data();
const wstring providersCSPPath = collectorCSPPath + L"/" + CSPProvidersNode;
wstring collectorRegistryPath = RegEventTracing;
collectorRegistryPath += L"\\";
collectorRegistryPath += collector->Name->Data();
// Add CSP node and set its properties...
MdmProvision::RunAdd(cspRoot, collector->Name->Data());
Utils::WriteRegistryValue(collectorRegistryPath, RegReportToDeviceTwin, collector->ReportToDeviceTwin->Data());
Utils::WriteRegistryValue(collectorRegistryPath, RegEventTracingLogFileFolder, collector->CSPConfiguration->LogFileFolder->Data());
Utils::WriteRegistryValue(collectorRegistryPath, RegEventTracingLogFileName, collector->CSPConfiguration->LogFileName->Data());
MdmProvision::RunSet(collectorCSPPath + L"/LogFileSizeLimitMB", collector->CSPConfiguration->LogFileSizeLimitMB);
MdmProvision::RunSet(collectorCSPPath + L"/TraceLogFileMode", collector->CSPConfiguration->TraceLogFileMode == L"sequential" ? 1 : 2);
// Capture which providers are already part of this CSP collector configuration...
wstring providersString = MdmProvision::RunGetString(providersCSPPath, true /*optional*/);
// Iterate though each desired provider and add/apply its settings...
for each (ProviderConfiguration^ provider in collector->CSPConfiguration->Providers)
{
wstring providerCSPPath = collectorCSPPath + L"/" + CSPProvidersNode + L"/" + provider->Guid->Data();
// Is the provider already part of this CSP collector configuration?
if (wstring::npos == providersString.find(provider->Guid->Data()))
{
MdmProvision::RunAddTyped(providerCSPPath, CSPNodeType);
}
int traceLevel = 0;
if (0 == _wcsicmp(provider->TraceLevel->Data(), JsonTraceLevelCritical))
{
traceLevel = 1;
}
else if (0 == _wcsicmp(provider->TraceLevel->Data(), JsonTraceLevelError))
{
traceLevel = 2;
}
else if (0 == _wcsicmp(provider->TraceLevel->Data(), JsonTraceLevelWarning))
{
traceLevel = 3;
}
else if (0 == _wcsicmp(provider->TraceLevel->Data(), JsonTraceLevelInformation))
{
traceLevel = 4;
}
else if (0 == _wcsicmp(provider->TraceLevel->Data(), JsonTraceLevelVerbose))
{
traceLevel = 5;
}
MdmProvision::RunSet(providerCSPPath + L"/" + CSPState, provider->Enabled);
MdmProvision::RunSet(providerCSPPath + L"/" + CSPKeywords, wstring(provider->Keywords->Data()));
MdmProvision::RunSet(providerCSPPath + L"/" + CSPTraceLevel, traceLevel);
}
// Finally process the started/stopped status...
unsigned int traceStatus = MdmProvision::RunGetUInt(collectorCSPPath + L"/" + CSPTraceStatus);
if (collector->CSPConfiguration->Started)
{
if (traceStatus == 0 /*stopped*/)
{
TRACEP(L"Starting logging for ", collector->Name->Data());
MdmProvision::RunExecWithParameters(collectorCSPPath + L"/" + CSPTraceControl, CSPTraceControlStart);
}
}
else
{
if (traceStatus == 1 /*started*/)
{
TRACEP(L"Stopping logging for ", collector->Name->Data());
MdmProvision::RunExecWithParameters(collectorCSPPath + L"/" + CSPTraceControl, CSPTraceControlStop);
CreateEtlFile(collector);
}
}
}
IResponse^ DiagnosticLogCSP::HandleSetEventTracingConfiguration(IRequest^ request)
{
TRACE(__FUNCTION__);
// ToDo: There is a bug in the CSP where if C:\Data\Users\Public\Documents
// does not exist, it fails to start capturing events.
// To work around that, we are making sure the documents folder exists.
Utils::EnsureFolderExists(DiagnosticLogCSPWorkingFolder);
auto eventTracingConfiguration = dynamic_cast<SetEventTracingConfigurationRequest^>(request);
for each (CollectorDesiredConfiguration^ collector in eventTracingConfiguration->Collectors)
{
ApplyCollectorConfiguration(CSPCollectorsRoot, collector);
}
return ref new StringResponse(ResponseStatus::Success, ref new String(), DMMessageKind::SetEventTracingConfiguration);
}
| 41.033708
| 196
| 0.648028
|
mehrdad-shokri
|
cf54ff4ccd37abfe5c66d8b83cbe74fcf6f7a80b
| 24,755
|
cpp
|
C++
|
src/test_infNaN_iamax.cpp
|
tlapack/testBLAS
|
dd63ade035880783cd55a8032c13a6d8e85dc490
|
[
"BSD-3-Clause"
] | null | null | null |
src/test_infNaN_iamax.cpp
|
tlapack/testBLAS
|
dd63ade035880783cd55a8032c13a6d8e85dc490
|
[
"BSD-3-Clause"
] | null | null | null |
src/test_infNaN_iamax.cpp
|
tlapack/testBLAS
|
dd63ade035880783cd55a8032c13a6d8e85dc490
|
[
"BSD-3-Clause"
] | 1
|
2021-06-28T21:13:49.000Z
|
2021-06-28T21:13:49.000Z
|
/// @file test_infNaN_iamax.cpp
/// @brief Test cases for iamax with NaNs, Infs and the overflow threshold (OV).
//
// Copyright (c) 2021, University of Colorado Denver. All rights reserved.
//
// This file is part of testBLAS.
// testBLAS is free software: you can redistribute it and/or modify it under
// the terms of the BSD 3-Clause license. See the accompanying LICENSE file.
#include <catch2/catch.hpp>
#include <tblas.hpp>
#include "defines.hpp"
#include "utils.hpp"
#include <limits>
#include <vector>
#include <complex>
using namespace blas;
// -----------------------------------------------------------------------------
// Auxiliary routines
/**
* @brief Set Ak = -k + i*k
*/
template< typename real_t >
inline void set_complexk( std::complex<real_t>& Ak, blas::idx_t k ){
Ak = std::complex<real_t>( -k, k );
}
template< typename real_t >
inline void set_complexk( real_t& Ak, blas::idx_t k ){
static_assert( ! is_complex<real_t>::value, "real_t must be a Real type." );
}
/**
* @brief Set Ak = OV * ((k+2)/(k+3)) * (1+i)
*/
template< typename real_t >
inline void set_complexOV( std::complex<real_t>& Ak, blas::idx_t k ){
const real_t OV = std::numeric_limits<real_t>::max();
Ak = OV * (real_t)((k+2.)/(k+3.)) * std::complex<real_t>( 1, 1 );
}
template< typename real_t >
inline void set_complexOV( real_t& Ak, blas::idx_t k ){
static_assert( ! is_complex<real_t>::value, "real_t must be a Real type." );
}
// -----------------------------------------------------------------------------
// Test cases for iamax with Infs and NaNs at specific positions
/**
* @brief Check if iamax( n, A, 1 ) works as expected using exactly 1 NaN
*
* NaN locations: @see testBLAS::set_array_locations
*
* If checkWithInf == true:
* For NaN location above:
* Insert Inf in first non-NaN location
* Insert -Inf in first non-NaN location
* Ditto for last non-NaN location
* Ditto for first and last non-NaN locations
*
* @param[in] n
* Size of A
* @param[in] A
* Array with non-NAN data
* @param[in] checkWithInf
* If true, run the test cases with Infs.
*/
template< typename TestType >
void check_iamax_1nan(
const blas::idx_t n,
TestType A[],
const bool checkWithInf = true )
{
using real_t = real_type<TestType>;
std::vector<TestType> nan_vec;
testBLAS::set_nan_vector( nan_vec );
// Indexes for test
std::vector<blas::idx_t> k_vec;
testBLAS::set_array_locations( n, k_vec );
// Tests
for (const auto& k : k_vec) {
const TestType Ak = A[k];
const blas::idx_t infIdx1 = (k > 0) ? 0 : 1;
const blas::idx_t infIdx2 = (k < n-1) ? n-1 : n-2;
for (const auto& aNAN : nan_vec) {
// NaN in A[k]
A[k] = aNAN;
// No Infs
CHECK( iamax( n, A, 1 ) == k );
if( checkWithInf && n > 1 ) {
const real_t inf = std::numeric_limits<real_t>::infinity();
const TestType AinfIdx1 = A[ infIdx1 ];
// Inf in first non-NaN location
A[ infIdx1 ] = inf;
CHECK( iamax( n, A, 1 ) == k );
// -Inf in first non-NaN location
A[ infIdx1 ] = -inf;
CHECK( iamax( n, A, 1 ) == k );
if( n > 2 ) {
const TestType AinfIdx2 = A[ infIdx2 ];
// Inf in last non-NaN location
A[ infIdx2 ] = inf;
CHECK( iamax( n, A, 1 ) == k );
// -Inf in last non-NaN location
A[ infIdx2 ] = -inf;
CHECK( iamax( n, A, 1 ) == k );
// Inf in first and last non-NaN location
A[ infIdx1 ] = A[ infIdx2 ] = inf;
CHECK( iamax( n, A, 1 ) == k );
// -Inf in first and last non-NaN location
A[ infIdx1 ] = A[ infIdx2 ] = -inf;
CHECK( iamax( n, A, 1 ) == k );
// Reset value
A[ infIdx2 ] = AinfIdx2;
}
// Reset value
A[ infIdx1 ] = AinfIdx1;
}
// Reset value
A[k] = Ak;
}
}
}
/**
* @brief Check if iamax( n, A, 1 ) works as expected using exactly 2 NaNs
*
* NaN locations: @see testBLAS::set_array_pairLocations
*
* If checkWithInf == true:
* For NaN location above:
* Insert Inf in first non-NaN location
* Insert -Inf in first non-NaN location
* Ditto for last non-NaN location
* Ditto for first and last non-NaN locations
*
* @param[in] n
* Size of A
* @param[in] A
* Array with non-NAN data
* @param[in] checkWithInf
* If true, run the test cases with Infs.
*/
template< typename TestType >
void check_iamax_2nans(
const blas::idx_t n,
TestType A[],
const bool checkWithInf = true )
{
using real_t = real_type<TestType>;
std::vector<TestType> nan_vec;
testBLAS::set_nan_vector( nan_vec );
// Indexes for test
std::vector<blas::idx_t> k_vec;
testBLAS::set_array_pairLocations( n, k_vec );
// Tests
for (unsigned i = 0; i < k_vec.size(); i += 2) {
const auto& k1 = k_vec[i];
const auto& k2 = k_vec[i+1];
const TestType Ak1 = A[k1];
const TestType Ak2 = A[k2];
const blas::idx_t infIdx1 =
(k1 > 0) ? 0 : (
(k2 > 1) ? 1
: 2 );
const blas::idx_t infIdx2 =
(k2 < n-1) ? n-1 : (
(k1 < n-2) ? n-2
: n-3 );
for (const auto& aNAN : nan_vec) {
// NaNs in A[k1] and A[k2]
A[k1] = A[k2] = aNAN;
// No Infs
CHECK( iamax( n, A, 1 ) == k1 );
if( checkWithInf && n > 2 ) {
const real_t inf = std::numeric_limits<real_t>::infinity();
const TestType AinfIdx1 = A[ infIdx1 ];
// Inf in first non-NaN location
A[ infIdx1 ] = inf;
CHECK( iamax( n, A, 1 ) == k1 );
// -Inf in first non-NaN location
A[ infIdx1 ] = -inf;
CHECK( iamax( n, A, 1 ) == k1 );
if( n > 3 ) {
const TestType AinfIdx2 = A[ infIdx2 ];
// Inf in last non-NaN location
A[ infIdx2 ] = inf;
CHECK( iamax( n, A, 1 ) == k1 );
// -Inf in last non-NaN location
A[ infIdx2 ] = -inf;
CHECK( iamax( n, A, 1 ) == k1 );
// Inf in first and last non-NaN location
A[ infIdx1 ] = A[ infIdx2 ] = inf;
CHECK( iamax( n, A, 1 ) == k1 );
// -Inf in first and last non-NaN location
A[ infIdx1 ] = A[ infIdx2 ] = -inf;
CHECK( iamax( n, A, 1 ) == k1 );
// Reset value
A[ infIdx2 ] = AinfIdx2;
}
// Reset value
A[ infIdx1 ] = AinfIdx1;
}
// Reset values
A[k1] = Ak1;
A[k2] = Ak2;
}
}
}
/**
* @brief Check if iamax( n, A, 1 ) works as expected using exactly 3 NaNs
*
* NaN locations: @see testBLAS::set_array_trioLocations
*
* If checkWithInf == true:
* For NaN location above:
* Insert Inf in first non-NaN location
* Insert -Inf in first non-NaN location
* Ditto for last non-NaN location
* Ditto for first and last non-NaN locations
*
* @param[in] n
* Size of A
* @param[in] A
* Array with non-NAN data
* @param[in] checkWithInf
* If true, run the test cases with Infs.
*/
template< typename TestType >
void check_iamax_3nans(
const blas::idx_t n,
TestType A[],
const bool checkWithInf = true )
{
using real_t = real_type<TestType>;
std::vector<TestType> nan_vec;
testBLAS::set_nan_vector( nan_vec );
// Indexes for test
std::vector<blas::idx_t> k_vec;
testBLAS::set_array_trioLocations( n, k_vec );
// Tests
for (unsigned i = 0; i < k_vec.size(); i += 3) {
const auto& k1 = k_vec[i];
const auto& k2 = k_vec[i+1];
const auto& k3 = k_vec[i+2];
const TestType Ak1 = A[k1];
const TestType Ak2 = A[k2];
const TestType Ak3 = A[k3];
const blas::idx_t infIdx1 =
(k1 > 0) ? 0 : (
(k2 > 1) ? 1
: 2 );
const blas::idx_t infIdx2 =
(k2 < n-1) ? n-1 : (
(k1 < n-2) ? n-2
: n-3 );
for (const auto& aNAN : nan_vec) {
// NaNs in A[k1], A[k2] and A[k3]
A[k1] = A[k2] = A[k3] = aNAN;
// No Infs
CHECK( iamax( n, A, 1 ) == k1 );
if( checkWithInf && n > 3 ) {
const real_t inf = std::numeric_limits<real_t>::infinity();
const TestType AinfIdx1 = A[ infIdx1 ];
// Inf in first non-NaN location
A[ infIdx1 ] = inf;
CHECK( iamax( n, A, 1 ) == k1 );
// -Inf in first non-NaN location
A[ infIdx1 ] = -inf;
CHECK( iamax( n, A, 1 ) == k1 );
if( n > 4 ) {
const TestType AinfIdx2 = A[ infIdx2 ];
// Inf in last non-NaN location
A[ infIdx2 ] = inf;
CHECK( iamax( n, A, 1 ) == k1 );
// -Inf in last non-NaN location
A[ infIdx2 ] = -inf;
CHECK( iamax( n, A, 1 ) == k1 );
// Inf in first and last non-NaN location
A[ infIdx1 ] = A[ infIdx2 ] = inf;
CHECK( iamax( n, A, 1 ) == k1 );
// -Inf in first and last non-NaN location
A[ infIdx1 ] = A[ infIdx2 ] = -inf;
CHECK( iamax( n, A, 1 ) == k1 );
// Reset value
A[ infIdx2 ] = AinfIdx2;
}
// Reset value
A[ infIdx1 ] = AinfIdx1;
}
// Reset values
A[k1] = Ak1;
A[k2] = Ak2;
A[k3] = Ak3;
}
}
}
/**
* @brief Check if iamax( n, A, 1 ) works as expected using exactly 1 Inf
*
* Inf locations: @see testBLAS::set_array_locations
*
* @param[in] n
* Size of A.
* @param[in] A
* Array with finite values.
*/
template< typename TestType >
void check_iamax_1inf(
const blas::idx_t n,
TestType A[] )
{
std::vector<TestType> inf_vec;
testBLAS::set_inf_vector( inf_vec );
// Indexes for test
std::vector<blas::idx_t> k_vec;
testBLAS::set_array_locations( n, k_vec );
// Tests
for (const auto& k : k_vec) {
const TestType Ak = A[k];
for (const auto& aInf : inf_vec) {
// (-1)^k*Inf in A[k]
A[k] = ( k % 2 == 0 ) ? aInf : -aInf;
// No Infs
CHECK( iamax( n, A, 1 ) == k );
// Reset value
A[k] = Ak;
}
}
}
/**
* @brief Check if iamax( n, A, 1 ) works as expected using exactly 2 Infs
*
* Inf locations: @see testBLAS::set_array_pairLocations
*
* @param[in] n
* Size of A.
* @param[in] A
* Array with finite values.
*/
template< typename TestType >
void check_iamax_2infs(
const blas::idx_t n,
TestType A[] )
{
std::vector<TestType> inf_vec;
testBLAS::set_inf_vector( inf_vec );
// Indexes for test
std::vector<blas::idx_t> k_vec;
testBLAS::set_array_pairLocations( n, k_vec );
// Tests
for (unsigned i = 0; i < k_vec.size(); i += 2) {
const auto& k1 = k_vec[i];
const auto& k2 = k_vec[i+1];
const TestType Ak1 = A[k1];
const TestType Ak2 = A[k2];
for (const auto& aInf : inf_vec) {
// (-1)^k*Inf in A[k]
A[k1] = ( k1 % 2 == 0 ) ? aInf : -aInf;
A[k2] = ( k2 % 2 == 0 ) ? aInf : -aInf;
CHECK( iamax( n, A, 1 ) == k1 );
// Reset values
A[k1] = Ak1;
A[k2] = Ak2;
}
}
}
/**
* @brief Check if iamax( n, A, 1 ) works as expected using exactly 3 Infs
*
* Inf locations: @see testBLAS::set_array_trioLocations
*
* @param[in] n
* Size of A.
* @param[in] A
* Array with finite values.
*/
template< typename TestType >
void check_iamax_3infs(
const blas::idx_t n,
TestType A[] )
{
std::vector<TestType> inf_vec;
testBLAS::set_inf_vector( inf_vec );
// Indexes for test
std::vector<blas::idx_t> k_vec;
testBLAS::set_array_trioLocations( n, k_vec );
// Tests
for (unsigned i = 0; i < k_vec.size(); i += 3) {
const auto& k1 = k_vec[i];
const auto& k2 = k_vec[i+1];
const auto& k3 = k_vec[i+2];
const TestType Ak1 = A[k1];
const TestType Ak2 = A[k2];
const TestType Ak3 = A[k3];
for (const auto& aInf : inf_vec) {
// (-1)^k*Inf in A[k]
A[k1] = ( k1 % 2 == 0 ) ? aInf : -aInf;
A[k2] = ( k2 % 2 == 0 ) ? aInf : -aInf;
A[k3] = ( k3 % 2 == 0 ) ? aInf : -aInf;
CHECK( iamax( n, A, 1 ) == k1 );
// Reset values
A[k1] = Ak1;
A[k2] = Ak2;
A[k3] = Ak3;
}
}
}
// -----------------------------------------------------------------------------
// Main Test Cases
/**
* @brief Test case for iamax with arrays containing at least 1 NaN
*
* Default entries:
* (1) A[k] = (-1)^k*k
* (2) A[k] = (-1)^k*Inf
* and, for complex data type:
* (3) A[k] = -k + i*k for k even, and A[k] = OV*((k+2)/(k+3))*(1+i) for k odd
* (4) A[k] = OV*((k+2)/(k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd
* (5) A[k] = -k + i*k for k even, and A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k odd
* (6) A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd
*/
TEMPLATE_TEST_CASE( "iamax returns the first NaN for real arrays with at least 1 NaN",
"[iamax][BLASlv1][NaN]", TEST_TYPES ) {
using real_t = real_type<TestType>;
// Constants
const blas::idx_t N = 128; // N > 0
const TestType inf = std::numeric_limits<real_t>::infinity();
// Arrays
const std::vector<blas::idx_t> n_vec
= { 1, 2, 3, 10, N }; // n_vec[i] > 0
TestType A[N];
SECTION( "At least 1 NaN in the array A" ) {
WHEN( "A[k] = (-1)^k*k" ) {
for (blas::idx_t k = 0; k < N; ++k)
A[k] = ( k % 2 == 0 ) ? k : -k;
for (const auto& n : n_vec) {
check_iamax_1nan( n, A );
check_iamax_2nans( n, A );
check_iamax_3nans( n, A );
}
}
WHEN( "A[k] = (-1)^k*Inf" ) {
for (blas::idx_t k = 0; k < N; ++k)
A[k] = ( k % 2 == 0 ) ? inf : -inf;
for (const auto& n : n_vec) {
check_iamax_1nan( n, A, false );
check_iamax_2nans( n, A, false );
check_iamax_3nans( n, A, false );
}
}
if (is_complex<TestType>::value) {
WHEN( "A[k] = -k + i*k for k even, and A[k] = OV*((k+2)/(k+3))*(1+i) for k odd" ) {
for (blas::idx_t k = 0; k < N; ++k) {
if ( k % 2 == 0 ) set_complexk( A[k], k );
else set_complexOV( A[k], k );
}
for (const auto& n : n_vec) {
check_iamax_1nan( n, A );
check_iamax_2nans( n, A );
check_iamax_3nans( n, A );
}
}
WHEN( "A[k] = OV*((k+2)/(k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd" ) {
for (blas::idx_t k = 0; k < N; ++k) {
if ( k % 2 == 0 ) set_complexOV( A[k], k );
else set_complexk( A[k], k );
}
for (const auto& n : n_vec) {
check_iamax_1nan( n, A );
check_iamax_2nans( n, A );
check_iamax_3nans( n, A );
}
}
WHEN( "A[k] = -k + i*k for k even, and A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k odd" ) {
for (const auto& n : n_vec) {
for (blas::idx_t k = 0; k < n; ++k) {
if ( k % 2 == 0 ) set_complexk( A[k], k );
else set_complexOV( A[k], n-k );
}
check_iamax_1nan( n, A );
check_iamax_2nans( n, A );
check_iamax_3nans( n, A );
}
}
WHEN( "A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd" ) {
for (const auto& n : n_vec) {
for (blas::idx_t k = 0; k < n; ++k) {
if ( k % 2 == 0 ) set_complexOV( A[k], n-k );
else set_complexk( A[k], k );
}
check_iamax_1nan( n, A );
check_iamax_2nans( n, A );
check_iamax_3nans( n, A );
}
}
}
}
SECTION( "All NaNs" ) {
for (blas::idx_t k = 0; k < N; ++k)
A[k] = NAN;
for (const auto& n : n_vec)
CHECK( iamax( n, A, 1 ) == 0 );
}
}
/**
* @brief Test case for iamax with arrays containing at least 1 Inf and no NaNs
*
* Default entries:
* (1) A[k] = (-1)^k*k
* and, for complex data type:
* (3) A[k] = -k + i*k for k even, and A[k] = OV*((k+2)/(k+3))*(1+i) for k odd
* (4) A[k] = OV*((k+2)/(k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd
* (5) A[k] = -k + i*k for k even, and A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k odd
* (6) A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd
*/
TEMPLATE_TEST_CASE( "iamax returns the first Inf for real arrays with at least 1 Inf and no NaNs",
"[iamax][BLASlv1][Inf]", TEST_TYPES ) {
using real_t = real_type<TestType>;
// Constants
const blas::idx_t N = 128; // N > 0
const TestType inf = std::numeric_limits<real_t>::infinity();
// Arrays
const std::vector<blas::idx_t> n_vec
= { 1, 2, 3, 10, N }; // n_vec[i] > 0
TestType A[N];
SECTION( "At least 1 Inf in the array A" ) {
WHEN( "A[k] = (-1)^k*k" ) {
for (blas::idx_t k = 0; k < N; ++k)
A[k] = ( k % 2 == 0 ) ? k : -k;
for (const auto& n : n_vec) {
check_iamax_1inf( n, A );
check_iamax_2infs( n, A );
check_iamax_3infs( n, A );
}
}
if (is_complex<TestType>::value) {
WHEN( "A[k] = -k + i*k for k even, and A[k] = OV*((k+2)/(k+3))*(1+i) for k odd" ) {
for (blas::idx_t k = 0; k < N; ++k) {
if ( k % 2 == 0 ) set_complexk( A[k], k );
else set_complexOV( A[k], k );
}
for (const auto& n : n_vec) {
check_iamax_1inf( n, A );
check_iamax_2infs( n, A );
check_iamax_3infs( n, A );
}
}
WHEN( "A[k] = OV*((k+2)/(k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd" ) {
for (blas::idx_t k = 0; k < N; ++k) {
if ( k % 2 == 0 ) set_complexOV( A[k], k );
else set_complexk( A[k], k );
}
for (const auto& n : n_vec) {
check_iamax_1inf( n, A );
check_iamax_2infs( n, A );
check_iamax_3infs( n, A );
}
}
WHEN( "A[k] = -k + i*k for k even, and A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k odd" ) {
for (const auto& n : n_vec) {
for (blas::idx_t k = 0; k < n; ++k) {
if ( k % 2 == 0 ) set_complexk( A[k], k );
else set_complexOV( A[k], n-k );
}
check_iamax_1inf( n, A );
check_iamax_2infs( n, A );
check_iamax_3infs( n, A );
}
}
WHEN( "A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd" ) {
for (const auto& n : n_vec) {
for (blas::idx_t k = 0; k < n; ++k) {
if ( k % 2 == 0 ) set_complexOV( A[k], n-k );
else set_complexk( A[k], k );
}
check_iamax_1inf( n, A );
check_iamax_2infs( n, A );
check_iamax_3infs( n, A );
}
}
}
}
SECTION( "All Infs" ) {
for (blas::idx_t k = 0; k < N; ++k)
A[k] = ( k % 2 == 0 ) ? inf : -inf;
for (const auto& n : n_vec)
CHECK( iamax( n, A, 1 ) == 0 );
}
}
/**
* @brief Test case for iamax where A(k) are finite but abs(real(A(k)))+abs(imag(A(k))) can overflow.
*
* 4 cases:
* A(k) = -k + i*k for k even, A(k) = OV*((k+2)/(k+3)) + i*OV*((k+2)/(k+3)) for k odd.
* (Correct answer = last odd k)
* Swap odd and even. (Correct answer = last even k)
* A(k) = -k + i*k for k even, A(k) = OV*((n-k+2)/(n-k+3)) + i*OV*((n-k+2)/(n-k+3)) for k odd.
* (Correct answer = 1)
* Swap odd and even (Correct answer = 2).
*/
TEMPLATE_TEST_CASE( "iamax works for complex data A when abs(real(A(k)))+abs(imag(A(k))) can overflow",
"[iamax][BLASlv1]", TEST_CPLX_TYPES ) {
// Constants
const blas::idx_t N = 128; // N > 0
// Arrays
const std::vector<blas::idx_t> n_vec
= { 1, 2, 3, 10, N }; // n_vec[i] > 0
TestType A[N];
WHEN( "A[k] = -k + i*k for k even, and A[k] = OV*((k+2)/(k+3))*(1+i) for k odd" ) {
for (blas::idx_t k = 0; k < N; ++k) {
if ( k % 2 == 0 ) set_complexk( A[k], k );
else set_complexOV( A[k], k );
}
for (const auto& n : n_vec) {
if ( n == 1 ) CHECK( iamax( n, A, 1 ) == 0 );
else if ( n % 2 == 0 ) CHECK( iamax( n, A, 1 ) == n-1 );
else CHECK( iamax( n, A, 1 ) == n-2 );
}
}
WHEN( "A[k] = OV*((k+2)/(k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd" ) {
for (blas::idx_t k = 0; k < N; ++k) {
if ( k % 2 == 0 ) set_complexOV( A[k], k );
else set_complexk( A[k], k );
}
for (const auto& n : n_vec) {
if ( n == 1 ) CHECK( iamax( n, A, 1 ) == 0 );
else if ( n % 2 == 0 ) CHECK( iamax( n, A, 1 ) == n-2 );
else CHECK( iamax( n, A, 1 ) == n-1 );
}
}
WHEN( "A[k] = -k + i*k for k even, and A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k odd" ) {
for (const auto& n : n_vec) {
for (blas::idx_t k = 0; k < n; ++k) {
if ( k % 2 == 0 ) set_complexk( A[k], k );
else set_complexOV( A[k], n-k );
}
if ( n == 1 ) CHECK( iamax( n, A, 1 ) == 0 );
else CHECK( iamax( n, A, 1 ) == 1 );
}
}
WHEN( "A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd" ) {
for (const auto& n : n_vec) {
for (blas::idx_t k = 0; k < n; ++k) {
if ( k % 2 == 0 ) set_complexOV( A[k], n-k );
else set_complexk( A[k], k );
}
CHECK( iamax( n, A, 1 ) == 0 );
}
}
}
| 32.317232
| 103
| 0.428277
|
tlapack
|
cf572f7d6c43f4e28dbc736337834fbc72e648fd
| 5,679
|
cpp
|
C++
|
src/visitors/interp_visitor.cpp
|
ut-amrl/pips
|
1f553dc850f8c27a460f020d91b35c8a18c479bb
|
[
"MIT"
] | null | null | null |
src/visitors/interp_visitor.cpp
|
ut-amrl/pips
|
1f553dc850f8c27a460f020d91b35c8a18c479bb
|
[
"MIT"
] | null | null | null |
src/visitors/interp_visitor.cpp
|
ut-amrl/pips
|
1f553dc850f8c27a460f020d91b35c8a18c479bb
|
[
"MIT"
] | null | null | null |
#include "interp_visitor.hpp"
#include <eigen3/Eigen/Core> // Vector2f
#include <iostream> // cout, endl
#include <memory> // make_shared
#include <stdexcept> // invalid_argument
#include <string> // string
#include "ast/library_functions.hpp"
using Eigen::Vector2f;
using std::cout;
using std::endl;
using std::invalid_argument;
using std::make_shared;
using std::string;
namespace AST {
ast_ptr Interpret(const ast_ptr& program) {
Interp interpreter;
const ast_ptr result = program->Accept(&interpreter);
return result;
}
ast_ptr Interpret(const ast_ptr& program, const Example& example) {
Interp interpreter(example);
const ast_ptr result = program->Accept(&interpreter);
return result;
}
bool InterpretBool(const ast_ptr& program, const Example& example) {
Interp interpreter(example);
ast_ptr result = program->Accept(&interpreter);
if (result->type_ == BOOL) {
bool_ptr bool_result = std::dynamic_pointer_cast<Bool>(result);
return bool_result->value_;
}
throw invalid_argument("Not a boolean expression.");
}
Interp::Interp() {}
Interp::Interp(const Example& world) : world_(world) {}
ast_ptr Interp::Visit(AST* node) { return ast_ptr(node); }
ast_ptr Interp::Visit(BinOp* node) {
ast_ptr left = node->left_->Accept(this);
ast_ptr right = node->right_->Accept(this);
const string op = node->op_;
BinOp partial(left, right, node->op_, node->type_, node->dims_);
ast_ptr result = make_shared<BinOp>(partial);
// Don't try to evaluate if one of the arguments is symbolic
if (left->symbolic_ || right->symbolic_) {
result->symbolic_ = true;
} else {
// One if clause per binary operation
if (op == "Plus") {
result = Plus(left, right);
} else if (op == "Minus") {
result = Minus(left, right);
} else if (op == "Times") {
result = Times(left, right);
} else if (op == "DividedBy") {
result = DividedBy(left, right);
} else if (op == "Cross") {
result = Cross(left, right);
} else if (op == "Dot") {
result = Dot(left, right);
} else if (op == "SqDist") {
result = SqDist(left, right);
} else if (op == "AngleDist") {
result = AngleDist(left, right);
} else if (op == "And") {
result = And(left, right);
} else if (op == "Or") {
result = Or(left, right);
} else if (op == "Eq") {
result = Eq(left, right);
} else if (op == "Gt") {
result = Gt(left, right);
} else if (op == "Lt") {
result = Lt(left, right);
} else if (op == "Gte") {
result = Gte(left, right);
} else if (op == "Lte") {
result = Lte(left, right);
} else {
throw invalid_argument("unknown binary operation `" + op + "'");
}
}
return result;
}
ast_ptr Interp::Visit(Bool* node) { return make_shared<Bool>(*node); }
ast_ptr Interp::Visit(Feature* node) {
if (node->current_value_ == nullptr) {
throw invalid_argument("AST has unfilled feature holes");
} else {
ast_ptr result = node->current_value_->Accept(this);
return result;
}
}
ast_ptr Interp::Visit(Num* node) { return make_shared<Num>(*node); }
ast_ptr Interp::Visit(Param* node) {
if (node->current_value_ == nullptr) {
// throw invalid_argument("AST has unfilled parameter holes");
return make_shared<Param>(*node);
} else {
ast_ptr result = node->current_value_->Accept(this);
return result;
}
}
// TODO(jaholtz) Throw errors instead of printing
ast_ptr Interp::Visit(UnOp* node) {
ast_ptr input = node->input_->Accept(this);
const string op = node->op_;
UnOp partial(input, node->op_, node->type_, node->dims_);
ast_ptr result = make_shared<UnOp>(partial);
// Don't try to evaluate if the input is symbolic
if (input->symbolic_) {
result->symbolic_ = true;
} else {
// One if clause per unary operation
if (op == "Abs") {
result = Abs(input);
} else if (op == "Sq") {
result = Sq(input);
} else if (op == "Cos") {
result = Cos(input);
} else if (op == "Sin") {
result = Sin(input);
} else if (op == "Heading") {
result = Heading(input);
} else if (op == "Angle") {
result = Angle(input);
} else if (op == "NormSq") {
result = NormSq(input);
} else if (op == "Norm") {
result = NormSq(input);
} else if (op == "Perp") {
result = Perp(input);
} else if (op == "VecX") {
result = VecX(input);
} else if (op == "VecY") {
result = VecY(input);
} else if (op == "Not") {
result = Not(input);
} else if (op == "StraightFreePathLength") {
result = StraightFreePathLength(input, world_.obstacles_);
} else {
throw invalid_argument("unknown unary operation `" + op + "'");
}
}
return result;
}
ast_ptr Interp::Visit(Var* node) {
if (world_.symbol_table_.find(node->name_) != world_.symbol_table_.end()) {
if (node->type_ == NUM) {
const float value = world_.symbol_table_[node->name_].GetValue();
Num var_value(value, node->dims_);
return make_shared<Num>(var_value);
} else if (node->type_ == VEC) {
const Vector2f float_vec = world_.symbol_table_[node->name_].GetValue();
const Vector2f value = Vector2f(float_vec.data());
Vec vec(value, node->dims_);
return make_shared<Vec>(vec);
} else {
cout << node->name_ << endl;
cout << "Error: Variable has unhandled type." << endl;
}
}
cout << node->name_ << endl;
cout << "Error: Variable not in symbol table" << endl;
return make_shared<Var>(*node);
}
ast_ptr Interp::Visit(Vec* node) { return make_shared<Vec>(*node); }
} // namespace AST
| 30.368984
| 78
| 0.61296
|
ut-amrl
|
cf587e787585f40839ca0cc1592ee6b659a8b0d8
| 6,200
|
cpp
|
C++
|
pnwtl/optionscontrols.cpp
|
Adept-Space/pn
|
d722f408cf3c3b8d0b8028846c0199969b6a103c
|
[
"BSD-3-Clause"
] | null | null | null |
pnwtl/optionscontrols.cpp
|
Adept-Space/pn
|
d722f408cf3c3b8d0b8028846c0199969b6a103c
|
[
"BSD-3-Clause"
] | null | null | null |
pnwtl/optionscontrols.cpp
|
Adept-Space/pn
|
d722f408cf3c3b8d0b8028846c0199969b6a103c
|
[
"BSD-3-Clause"
] | null | null | null |
/**
* @file optionscontrols.cpp
* @brief Controls for options dialogs (and the like).
* @author Simon Steele
* @note Copyright (c) 2002-2011 Simon Steele - http://untidy.net/
*
* Programmer's Notepad 2 : The license file (license.[txt|html]) describes
* the conditions under which this source may be modified / distributed.
*/
#include "stdafx.h"
#include "resource.h"
#include "optionscontrols.h"
#include "schemeconfig.h"
#include "outputview.h"
#include "third_party/scintilla/include/scilexer.h"
//////////////////////////////////////////////////////////////////////////////
// CStyleDisplay
//////////////////////////////////////////////////////////////////////////////
CStyleDisplay::CStyleDisplay()
{
m_Font = NULL;
memset(&m_lf, 0, sizeof(LOGFONT));
}
CStyleDisplay::~CStyleDisplay()
{
if(m_Font)
delete m_Font;
}
void CStyleDisplay::SetBold(bool bold)
{
m_lf.lfWeight = (bold ? FW_BOLD : FW_NORMAL);
UpdateFont();
}
void CStyleDisplay::SetItalic(bool italic)
{
m_lf.lfItalic = italic;
UpdateFont();
}
void CStyleDisplay::SetUnderline(bool underline)
{
m_lf.lfUnderline = underline;
UpdateFont();
}
void CStyleDisplay::SetFontName(LPCTSTR fontname)
{
_tcscpy(m_lf.lfFaceName, fontname);
UpdateFont();
}
void CStyleDisplay::SetSize(int size, bool bInvalidate)
{
HDC dc = GetDC();
m_lf.lfHeight = -MulDiv(size, GetDeviceCaps(dc, LOGPIXELSY), 72);
ReleaseDC(dc);
if(bInvalidate)
UpdateFont();
}
void CStyleDisplay::SetFore(COLORREF fore)
{
m_Fore = fore;
Invalidate();
}
void CStyleDisplay::SetBack(COLORREF back)
{
m_Back = back;
Invalidate();
}
void CStyleDisplay::SetStyle(LPCTSTR fontname, int fontsize, COLORREF fore, COLORREF back, LPCTSTR name, bool bold, bool italic, bool underline)
{
m_Name = name;
m_Fore = fore;
m_Back = back;
SetSize(fontsize, false);
m_lf.lfWeight = (bold ? FW_BOLD : FW_NORMAL);
m_lf.lfUnderline = underline;
m_lf.lfItalic = italic;
_tcscpy(m_lf.lfFaceName, fontname);
UpdateFont();
}
LRESULT CStyleDisplay::OnPaint(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
PAINTSTRUCT ps;
BeginPaint(&ps);
CDC dc(ps.hdc);
CRect rc;
GetClientRect(rc);
dc.FillRect(rc, (HBRUSH)::GetStockObject(WHITE_BRUSH));
// Draw in the example text.
if(m_Font)
{
HFONT hOldFont = dc.SelectFont(m_Font->m_hFont);
dc.SetBkColor(m_Back);
dc.SetTextColor(m_Fore);
dc.DrawText(m_Name, m_Name.GetLength(), rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
dc.SelectFont(hOldFont);
}
// Draw a light border around the control.
HBRUSH light = ::GetSysColorBrush(COLOR_3DSHADOW);
dc.FrameRect(rc, light);
EndPaint(&ps);
return 0;
}
LRESULT CStyleDisplay::OnEraseBkgnd(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
return 1;
}
void CStyleDisplay::UpdateFont()
{
if(m_Font)
delete m_Font;
m_Font = new CFont;
m_Font->CreateFontIndirect(&m_lf);
Invalidate();
}
//////////////////////////////////////////////////////////////////////////////
// CScintillaREDialogWnd
//////////////////////////////////////////////////////////////////////////////
int CScintillaREDialogWnd::HandleNotify(LPARAM lParam)
{
Scintilla::SCNotification *scn = (Scintilla::SCNotification*)lParam;
if( scn->nmhdr.code == SCN_HOTSPOTCLICK )
{
int style = GetStyleAt(scn->position);
GetParent().PostMessage(PN_HANDLEHSCLICK, style, scn->position);
return 0;
}
else
return baseClass::HandleNotify(lParam);
}
//////////////////////////////////////////////////////////////////////////////
// CSchemeCombo
//////////////////////////////////////////////////////////////////////////////
int CSchemeCombo::AddScheme(LPCTSTR title, SchemeDetails* pScheme)
{
int index = AddString(title);
SetItemDataPtr(index, pScheme);
return index;
}
void CSchemeCombo::Load(SchemeConfigParser* pConfig, LPCSTR selectScheme, bool bIncludePlainText, bool bIncludeInternal)
{
LPCSTR schemeToSelect = (selectScheme ? selectScheme : pConfig->GetCurrentScheme());
Clear();
tstring schemeText;
if (bIncludePlainText)
{
schemeText = LS(IDS_DEFAULTSCHEME);
int index = AddString(schemeText.c_str());
SetItemDataPtr(index, pConfig->GetPlainTextScheme());
}
for (SchemeDetailsList::const_iterator i = pConfig->GetSchemes().begin(); i != pConfig->GetSchemes().end(); ++i)
{
// Skip internal (special) schemes?
if (!bIncludeInternal && (*i)->IsInternal())
continue;
int index = AddString((*i)->Title.c_str());
SetItemDataPtr(index, (*i));
if((*i)->Name == schemeToSelect)
schemeText = (*i)->Title;
}
if (schemeText.size())
{
SelectString(0, schemeText.c_str());
}
else
{
// Default: select the first scheme.
SetCurSel(0);
}
}
SchemeDetails* CSchemeCombo::GetItemScheme(int index)
{
return static_cast<SchemeDetails*>(GetItemDataPtr(index));
}
LRESULT CPNHotkeyCtrl::OnKeyDown(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
bHandled = false;
if (wParam == VK_DELETE || wParam == VK_SPACE || wParam == VK_ESCAPE)
{
bHandled = true;
}
return 0;
}
LRESULT CPNHotkeyCtrl::OnKeyUp(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
bHandled = false;
// For some reason space is still clearing the box before we get to here, so there're no
// modifiers left.
if (wParam == VK_DELETE || wParam == VK_SPACE || wParam == VK_ESCAPE)
{
int current = SendMessage(HKM_GETHOTKEY, 0, 0);
if ((current & 0xff) != 0)
{
// No low-order byte value means no current key,
// we don't want to use the current modifiers.
current = 0;
}
if (wParam == VK_DELETE)
{
// Set extended to make sure we get DEL and not NUM DECIMAL
current |= (HOTKEYF_EXT << 8);
}
int key = wParam | current;
SendMessage(HKM_SETHOTKEY, key, 0);
SendMessageW(GetParent(), WM_COMMAND, MAKEWPARAM(GetDlgCtrlID(), EN_CHANGE), (LPARAM)m_hWnd);
bHandled = true;
}
return 0;
}
LRESULT CPNHotkeyCtrl::OnChar(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
{
bHandled = false;
if (wParam == ' ')
{
bHandled = true;
}
return 0;
}
LRESULT CPNHotkeyCtrl::OnGetDlgCode(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
return DLGC_WANTALLKEYS;
}
| 22.463768
| 144
| 0.647742
|
Adept-Space
|
cf614dcba15e8f5442b2aedba5196ab8203bf185
| 2,744
|
cpp
|
C++
|
cpp/tests/tdmaMsgProcessor_UT.cpp
|
MinesJA/meshNetwork
|
5ffada57c13049cb00c2996fe239cdff6edf6f17
|
[
"NASA-1.3"
] | 133
|
2017-06-24T02:44:28.000Z
|
2022-03-25T05:17:00.000Z
|
cpp/tests/tdmaMsgProcessor_UT.cpp
|
MinesJA/meshNetwork
|
5ffada57c13049cb00c2996fe239cdff6edf6f17
|
[
"NASA-1.3"
] | null | null | null |
cpp/tests/tdmaMsgProcessor_UT.cpp
|
MinesJA/meshNetwork
|
5ffada57c13049cb00c2996fe239cdff6edf6f17
|
[
"NASA-1.3"
] | 33
|
2017-06-19T03:24:40.000Z
|
2022-02-03T20:13:12.000Z
|
#include "tests/tdmaMsgProcessor_UT.hpp"
#include "comm/tdmaCmds.hpp"
#include "comm/tdmaComm.hpp"
#include "comm/cmdHeader.hpp"
#include "comm/commands.hpp"
#include "node/nodeParams.hpp"
#include "node/nodeState.hpp"
#include <gtest/gtest.h>
#include <cmath>
#include <unistd.h>
using std::vector;
namespace {
}
namespace comm
{
TDMAMsgProcessor_UT::TDMAMsgProcessor_UT()
{
// Load configuration
node::NodeParams::loadParams("nodeConfig.json");
// Populate message processor args
m_args.cmdQueue = &m_cmdQueue;
m_args.relayBuffer = &m_relayBuffer;
// Load command dictionary for use
std::unordered_map<uint8_t, comm::HeaderType> tdmaCmdDict = TDMACmds::getCmdDict();
Cmds::updateCmdDict(tdmaCmdDict);
}
void TDMAMsgProcessor_UT::SetUpTestCase(void) {
}
void TDMAMsgProcessor_UT::SetUp(void)
{
}
TEST_F(TDMAMsgProcessor_UT, processMsg) {
// Test all commands processed by NodeMsgProcessor
std::vector<uint8_t> header;
std::vector<uint8_t> msgBytes;
// TDMACmds::TimeOffset
uint8_t sourceId = 1;
double offset = 2.1;
CmdHeader cmdHeader = createHeader(TDMACmds::TimeOffset, sourceId);
TDMA_TimeOffset timeOffset(offset, cmdHeader);
msgBytes = timeOffset.serialize();
EXPECT_TRUE(m_tdmaMsgProcessor.processMsg(TDMACmds::TimeOffset, msgBytes, m_args));
EXPECT_TRUE(node::NodeParams::nodeStatus[sourceId-1].timeOffset == offset);
// TDMACmds::TimeOffsetSummary
// TDMACmds::MeshStatus
cmdHeader = createHeader(TDMACmds::MeshStatus, sourceId);
unsigned int startTime = ceil(node::NodeParams::clock.getTime());
TDMA_MeshStatus meshStatus(startTime, TDMASTATUS_NOMINAL, cmdHeader);
msgBytes = meshStatus.serialize();
EXPECT_TRUE(m_tdmaMsgProcessor.processMsg(TDMACmds::MeshStatus, msgBytes, m_args));
EXPECT_TRUE(m_cmdQueue.find(TDMACmds::MeshStatus) != m_cmdQueue.end()); // command put in queue
// TDMACmds::LinkStatus
cmdHeader = createHeader(TDMACmds::LinkStatus, sourceId);
std::vector<uint8_t> statusIn = {node::NoLink, node::IndirectLink, node::GoodLink, node::BadLink, node::NoLink, node::NoLink};
TDMA_LinkStatus linkStatus(statusIn, cmdHeader);
msgBytes = linkStatus.serialize();
EXPECT_TRUE(m_tdmaMsgProcessor.processMsg(TDMACmds::LinkStatus, msgBytes, m_args));
for (unsigned int i = 0; i < node::NodeParams::linkStatus[sourceId-1].size(); i++) {
EXPECT_TRUE(node::NodeParams::linkStatus[sourceId-1][i] == statusIn[i]);
}
// TDMACmds::LinkStatusSummary
}
}
| 33.876543
| 134
| 0.673105
|
MinesJA
|
cf6521d38e5984acfd1d3a5a8a35309c09d30c38
| 1,545
|
cc
|
C++
|
Codeforces/BubbleCup/Problem H/H.cc
|
VastoLorde95/Competitive-Programming
|
6c990656178fb0cd33354cbe5508164207012f24
|
[
"MIT"
] | 170
|
2017-07-25T14:47:29.000Z
|
2022-01-26T19:16:31.000Z
|
Codeforces/BubbleCup/Problem H/H.cc
|
navodit15/Competitive-Programming
|
6c990656178fb0cd33354cbe5508164207012f24
|
[
"MIT"
] | null | null | null |
Codeforces/BubbleCup/Problem H/H.cc
|
navodit15/Competitive-Programming
|
6c990656178fb0cd33354cbe5508164207012f24
|
[
"MIT"
] | 55
|
2017-07-28T06:17:33.000Z
|
2021-10-31T03:06:22.000Z
|
#include <cstdio>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <map>
#include <set>
#include <vector>
#include <utility>
#include <queue>
#include <stack>
#define sd(x) scanf("%d",&x)
#define sd2(x,y) scanf("%d%d",&x,&y)
#define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z)
#define fi first
#define se second
#define pb(x) push_back(x)
#define mp(x,y) make_pair(x,y)
#define LET(x, a) __typeof(a) x(a)
#define foreach(it, v) for(LET(it, v.begin()); it != v.end(); it++)
#define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define __ freopen("input.txt","r",stdin);freopen("output.txt","w",stdout);
#define tr(x) cout<<x<<endl;
#define tr2(x,y) cout<<x<<" "<<y<<endl;
#define tr3(x,y,z) cout<<x<<" "<<y<<" "<<z<<endl;
#define tr4(w,x,y,z) cout<<w<<" "<<x<<" "<<y<<" "<<z<<endl;
#define tr5(v,w,x,y,z) cout<<v<<" "<<w<<" "<<x<<" "<<y<<" "<<z<<endl;
#define tr6(u,v,w,x,y,z) cout<<u<<" "<<v<<" "<<w<<" "<<x<<" "<<y<<" "<<z<<endl;
using namespace std;
long long f[2001000], MOD = 1e9 + 7, ans = 0;
int n;
long long inv(long long a){
long long ret = 1, b = MOD-2;
while(b){
if(b%2) ret = (ret*a)%MOD;
a = (a*a)%MOD;
b >>= 1;
}
return ret;
}
long long nCr(int x, int y){
long long ret = f[x];
ret = (ret * inv(f[y]))%MOD;
ret = (ret * inv(f[x-y]))%MOD;
return ret;
}
int main(){
f[0] = 1;
for(int i = 1; i <= 2000010; i++){
f[i] = (f[i-1]*i)%MOD;
}
sd(n);
for(int i = 0; i <= n; i++){
ans = (ans + nCr(n+i+1,i+1))%MOD;
}
cout << ans << "\n";
return 0;
}
| 21.458333
| 79
| 0.551456
|
VastoLorde95
|