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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c13b20b4c5f957ca9facceae8d1b9ec3b149b080 | 225 | inl | C++ | node_modules/lzz-gyp/lzz-source/gram_Visitor.inl | SuperDizor/dizornator | 9f57dbb3f6af80283b4d977612c95190a3d47900 | [
"ISC"
] | 3 | 2019-09-18T16:44:33.000Z | 2021-03-29T13:45:27.000Z | node_modules/lzz-gyp/lzz-source/gram_Visitor.inl | SuperDizor/dizornator | 9f57dbb3f6af80283b4d977612c95190a3d47900 | [
"ISC"
] | null | null | null | node_modules/lzz-gyp/lzz-source/gram_Visitor.inl | SuperDizor/dizornator | 9f57dbb3f6af80283b4d977612c95190a3d47900 | [
"ISC"
] | 2 | 2019-03-29T01:06:38.000Z | 2019-09-18T16:44:34.000Z | // gram_Visitor.inl
//
#ifdef LZZ_ENABLE_INLINE
#define LZZ_INLINE inline
#else
#define LZZ_INLINE
#endif
namespace gram
{
LZZ_INLINE Visitor::Visitor (bool slippery)
: m_slippery (slippery)
{}
}
#undef LZZ_INLINE
| 14.0625 | 45 | 0.737778 | SuperDizor |
c13dc984026548a60265e21d62c2b5e041f979b1 | 1,462 | cpp | C++ | NULL Engine/Source/Component.cpp | BarcinoLechiguino/NULL_Engine | f2abecb44bee45b7cbf2d5b53609d79d38ecc5a3 | [
"MIT"
] | 4 | 2020-11-29T12:28:31.000Z | 2021-06-08T17:32:56.000Z | NULL Engine/Source/Component.cpp | BarcinoLechiguino/NULL_Engine | f2abecb44bee45b7cbf2d5b53609d79d38ecc5a3 | [
"MIT"
] | null | null | null | NULL Engine/Source/Component.cpp | BarcinoLechiguino/NULL_Engine | f2abecb44bee45b7cbf2d5b53609d79d38ecc5a3 | [
"MIT"
] | 4 | 2020-11-01T17:06:32.000Z | 2021-01-09T16:58:50.000Z | #include "Log.h"
#include "Random.h"
#include "VariableTypedefs.h"
#include "GameObject.h"
#include "Component.h"
Component::Component(GameObject* owner, COMPONENT_TYPE type, bool is_active) :
id (Random::LCG::GetRandomUint()),
type (type),
owner (owner),
is_active (is_active)
{
}
Component::~Component()
{
}
bool Component::Update()
{
return true;
}
bool Component::CleanUp()
{
return true;
}
bool Component::SaveState(ParsonNode& root) const
{
return true;
}
bool Component::LoadState(ParsonNode& root)
{
return true;
}
// --- COMPONENT METHODS ---
const char* Component::GetNameFromType() const
{
switch (type)
{
case COMPONENT_TYPE::NONE: { return "NONE"; } break;
case COMPONENT_TYPE::TRANSFORM: { return "Transform"; } break;
case COMPONENT_TYPE::MESH: { return "Mesh"; } break;
case COMPONENT_TYPE::MATERIAL: { return "Material"; } break;
case COMPONENT_TYPE::LIGHT: { return "Light"; } break;
case COMPONENT_TYPE::CAMERA: { return "Camera"; } break;
case COMPONENT_TYPE::ANIMATOR: { return "Animator"; } break;
case COMPONENT_TYPE::ANIMATION: { return "Animation"; } break;
}
return "NONE";
}
uint32 Component::GetID() const
{
return id;
}
void Component::ResetID()
{
id = Random::LCG::GetRandomUint();
}
bool Component::IsActive() const
{
return is_active;
}
void Component::SetIsActive(const bool& set_to)
{
is_active = set_to;
}
GameObject* Component::GetOwner() const
{
return owner;
} | 17.404762 | 78 | 0.69015 | BarcinoLechiguino |
c13f1e8d75ce1246fa6245f3e4182839b7fbacd3 | 1,036 | cpp | C++ | p1070Mooncake.cpp | yangyueren/PAT | 950d820ec9174c5e2d74adafeb2abde4acdc635f | [
"MIT"
] | 1 | 2020-02-01T08:20:26.000Z | 2020-02-01T08:20:26.000Z | p1070Mooncake.cpp | yangyueren/PAT | 950d820ec9174c5e2d74adafeb2abde4acdc635f | [
"MIT"
] | null | null | null | p1070Mooncake.cpp | yangyueren/PAT | 950d820ec9174c5e2d74adafeb2abde4acdc635f | [
"MIT"
] | null | null | null | //
// Created by yryang on 2019/9/15.
//
#include "iostream"
#include "string.h"
#include "string"
#include "stdlib.h"
#include "stdio.h"
#include "map"
#include "vector"
#include "set"
#include "math.h"
#include "queue"
#include "algorithm"
#include "unordered_map"
using namespace std;
struct node{
double ton;
double totalpri;
double pri;
}nodes[10005];
double total;
double price=0;
double now=0;
int N;
int cmp(node a, node b){
return a.pri > b.pri;
}
int main(){
cin >> N >> total;
for (int i = 0; i < N; ++i) {
cin >> nodes[i].ton;
}
for (int j = 0; j < N; ++j) {
cin >> nodes[j].totalpri;
nodes[j].pri = nodes[j].totalpri / nodes[j].ton;
}
sort(nodes, nodes+N, cmp);
for (int k = 0; k < N; ++k) {
if(now + nodes[k].ton >= total){
price += (total-now)*nodes[k].pri;
break;
}else{
price += nodes[k].totalpri;
now += nodes[k].ton;
}
}
printf("%.2lf\n", price);
return 0;
} | 18.175439 | 56 | 0.533784 | yangyueren |
c13f9629a2b7f0e10d6fc6bf1220fe71c39b143a | 895 | cpp | C++ | problem 1-50/21. Merge Two Sorted Lists.cpp | just-essential/LeetCode-Cpp | 3ec49434d257defd28bfe4784ecd0ff2f9077a31 | [
"MIT"
] | null | null | null | problem 1-50/21. Merge Two Sorted Lists.cpp | just-essential/LeetCode-Cpp | 3ec49434d257defd28bfe4784ecd0ff2f9077a31 | [
"MIT"
] | null | null | null | problem 1-50/21. Merge Two Sorted Lists.cpp | just-essential/LeetCode-Cpp | 3ec49434d257defd28bfe4784ecd0ff2f9077a31 | [
"MIT"
] | null | null | null | /*
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
*/
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode head(0), *l3 = &head;
while (l1 && l2) {
if (l1->val < l2->val) {
l3->next = l1;
l1 = l1->next;
} else {
l3->next = l2;
l2 = l2->next;
}
l3 = l3->next;
}
if (l1) {
l3->next = l1;
} else {
l3->next = l2;
}
return head.next;
}
void test() {
assert(listNodeToString(mergeTwoLists(stringToListNode("[1,2,4]"), stringToListNode("[1,3,4]"))) ==
"[1, 1, 2, 3, 4, 4]");
}
}; | 24.861111 | 141 | 0.459218 | just-essential |
c14077941b88c9b876d337ff86d2d1d967257037 | 16,838 | cpp | C++ | 3rdparty/pytorch/torch/csrc/jit/script/parser.cpp | WoodoLee/TorchCraft | 999f68aab9e7d50ed3ae138297226dc95fefc458 | [
"MIT"
] | null | null | null | 3rdparty/pytorch/torch/csrc/jit/script/parser.cpp | WoodoLee/TorchCraft | 999f68aab9e7d50ed3ae138297226dc95fefc458 | [
"MIT"
] | null | null | null | 3rdparty/pytorch/torch/csrc/jit/script/parser.cpp | WoodoLee/TorchCraft | 999f68aab9e7d50ed3ae138297226dc95fefc458 | [
"MIT"
] | null | null | null | #include <c10/util/Optional.h>
#include <torch/csrc/jit/script/lexer.h>
#include <torch/csrc/jit/script/parse_string_literal.h>
#include <torch/csrc/jit/script/parser.h>
#include <torch/csrc/jit/script/tree.h>
#include <torch/csrc/jit/script/tree_views.h>
namespace torch {
namespace jit {
namespace script {
Decl mergeTypesFromTypeComment(
const Decl& decl,
const Decl& type_annotation_decl,
bool is_method) {
auto expected_num_annotations = decl.params().size();
if (is_method) {
// `self` argument
expected_num_annotations -= 1;
}
if (expected_num_annotations != type_annotation_decl.params().size()) {
throw ErrorReport(type_annotation_decl.range())
<< "Number of type annotations ("
<< type_annotation_decl.params().size()
<< ") did not match the number of "
<< "function parameters (" << expected_num_annotations << ")";
}
auto old = decl.params();
auto _new = type_annotation_decl.params();
// Merge signature idents and ranges with annotation types
std::vector<Param> new_params;
size_t i = is_method ? 1 : 0;
size_t j = 0;
if (is_method) {
new_params.push_back(old[0]);
}
for (; i < decl.params().size(); ++i, ++j) {
new_params.emplace_back(old[i].withType(_new[j].type()));
}
return Decl::create(
decl.range(),
List<Param>::create(decl.range(), new_params),
type_annotation_decl.return_type());
}
struct ParserImpl {
explicit ParserImpl(const std::string& str)
: L(str), shared(sharedParserData()) {}
Ident parseIdent() {
auto t = L.expect(TK_IDENT);
// whenever we parse something that has a TreeView type we always
// use its create method so that the accessors and the constructor
// of the Compound tree are in the same place.
return Ident::create(t.range, t.text());
}
TreeRef createApply(const Expr& expr) {
TreeList attributes;
auto range = L.cur().range;
TreeList inputs;
parseOperatorArguments(inputs, attributes);
return Apply::create(
range,
expr,
List<Expr>(makeList(range, std::move(inputs))),
List<Attribute>(makeList(range, std::move(attributes))));
}
static bool followsTuple(int kind) {
switch (kind) {
case TK_PLUS_EQ:
case TK_MINUS_EQ:
case TK_TIMES_EQ:
case TK_DIV_EQ:
case TK_NEWLINE:
case '=':
case ')':
return true;
default:
return false;
}
}
// exp | expr, | expr, expr, ...
Expr parseExpOrExpTuple() {
auto prefix = parseExp();
if (L.cur().kind == ',') {
std::vector<Expr> exprs = {prefix};
while (L.nextIf(',')) {
if (followsTuple(L.cur().kind))
break;
exprs.push_back(parseExp());
}
auto list = List<Expr>::create(prefix.range(), exprs);
prefix = TupleLiteral::create(list.range(), list);
}
return prefix;
}
// things like a 1.0 or a(4) that are not unary/binary expressions
// and have higher precedence than all of them
TreeRef parseBaseExp() {
TreeRef prefix;
switch (L.cur().kind) {
case TK_NUMBER: {
prefix = parseConst();
} break;
case TK_TRUE:
case TK_FALSE:
case TK_NONE: {
auto k = L.cur().kind;
auto r = L.cur().range;
prefix = c(k, r, {});
L.next();
} break;
case '(': {
L.next();
if (L.nextIf(')')) {
/// here we have the empty tuple case
std::vector<Expr> vecExpr;
List<Expr> listExpr = List<Expr>::create(L.cur().range, vecExpr);
prefix = TupleLiteral::create(L.cur().range, listExpr);
break;
}
prefix = parseExpOrExpTuple();
L.expect(')');
} break;
case '[': {
auto list = parseList('[', ',', ']', &ParserImpl::parseExp);
prefix = ListLiteral::create(list.range(), List<Expr>(list));
} break;
case TK_STRINGLITERAL: {
prefix = parseConcatenatedStringLiterals();
} break;
default: {
Ident name = parseIdent();
prefix = Var::create(name.range(), name);
} break;
}
while (true) {
if (L.nextIf('.')) {
const auto name = parseIdent();
prefix = Select::create(name.range(), Expr(prefix), Ident(name));
} else if (L.cur().kind == '(') {
prefix = createApply(Expr(prefix));
} else if (L.cur().kind == '[') {
prefix = parseSubscript(prefix);
} else {
break;
}
}
return prefix;
}
TreeRef parseAssignmentOp() {
auto r = L.cur().range;
switch (L.cur().kind) {
case TK_PLUS_EQ:
case TK_MINUS_EQ:
case TK_TIMES_EQ:
case TK_DIV_EQ: {
int modifier = L.next().text()[0];
return c(modifier, r, {});
} break;
default: {
L.expect('=');
return c('=', r, {}); // no reduction
} break;
}
}
TreeRef parseTrinary(
TreeRef true_branch,
const SourceRange& range,
int binary_prec) {
auto cond = parseExp();
L.expect(TK_ELSE);
auto false_branch = parseExp(binary_prec);
return c(TK_IF_EXPR, range, {cond, std::move(true_branch), false_branch});
}
// parse the longest expression whose binary operators have
// precedence strictly greater than 'precedence'
// precedence == 0 will parse _all_ expressions
// this is the core loop of 'top-down precedence parsing'
Expr parseExp() {
return parseExp(0);
}
Expr parseExp(int precedence) {
TreeRef prefix = nullptr;
int unary_prec;
if (shared.isUnary(L.cur().kind, &unary_prec)) {
auto kind = L.cur().kind;
auto pos = L.cur().range;
L.next();
auto unary_kind =
kind == '*' ? TK_STARRED : kind == '-' ? TK_UNARY_MINUS : kind;
auto subexp = parseExp(unary_prec);
// fold '-' into constant numbers, so that attributes can accept
// things like -1
if (unary_kind == TK_UNARY_MINUS && subexp.kind() == TK_CONST) {
prefix = Const::create(subexp.range(), "-" + Const(subexp).text());
} else {
prefix = c(unary_kind, pos, {subexp});
}
} else {
prefix = parseBaseExp();
}
int binary_prec;
while (shared.isBinary(L.cur().kind, &binary_prec)) {
if (binary_prec <= precedence) // not allowed to parse something which is
// not greater than 'precedence'
break;
int kind = L.cur().kind;
auto pos = L.cur().range;
L.next();
if (shared.isRightAssociative(kind))
binary_prec--;
// special case for trinary operator
if (kind == TK_IF) {
prefix = parseTrinary(prefix, pos, binary_prec);
continue;
}
prefix = c(kind, pos, {prefix, parseExp(binary_prec)});
}
return Expr(prefix);
}
template <typename T>
List<T> parseList(int begin, int sep, int end, T (ParserImpl::*parse)()) {
auto r = L.cur().range;
if (begin != TK_NOTHING)
L.expect(begin);
std::vector<T> elements;
if (L.cur().kind != end) {
do {
elements.push_back((this->*parse)());
} while (L.nextIf(sep));
}
if (end != TK_NOTHING)
L.expect(end);
return List<T>::create(r, elements);
}
Const parseConst() {
auto range = L.cur().range;
auto t = L.expect(TK_NUMBER);
return Const::create(t.range, t.text());
}
StringLiteral parseConcatenatedStringLiterals() {
auto range = L.cur().range;
std::stringstream ss;
while (L.cur().kind == TK_STRINGLITERAL) {
auto literal_range = L.cur().range;
ss << parseStringLiteral(literal_range, L.next().text());
}
return StringLiteral::create(range, ss.str());
}
Expr parseAttributeValue() {
return parseExp();
}
void parseOperatorArguments(TreeList& inputs, TreeList& attributes) {
L.expect('(');
if (L.cur().kind != ')') {
do {
if (L.cur().kind == TK_IDENT && L.lookahead().kind == '=') {
auto ident = parseIdent();
L.expect('=');
auto v = parseAttributeValue();
attributes.push_back(
Attribute::create(ident.range(), Ident(ident), v));
} else {
inputs.push_back(parseExp());
}
} while (L.nextIf(','));
}
L.expect(')');
}
// Parse expr's of the form [a:], [:b], [a:b], [:]
Expr parseSubscriptExp() {
TreeRef first, second;
auto range = L.cur().range;
if (L.cur().kind != ':') {
first = parseExp();
}
if (L.nextIf(':')) {
if (L.cur().kind != ',' && L.cur().kind != ']') {
second = parseExp();
}
auto maybe_first = first ? Maybe<Expr>::create(range, Expr(first))
: Maybe<Expr>::create(range);
auto maybe_second = second ? Maybe<Expr>::create(range, Expr(second))
: Maybe<Expr>::create(range);
return SliceExpr::create(range, maybe_first, maybe_second);
} else {
return Expr(first);
}
}
TreeRef parseSubscript(const TreeRef& value) {
const auto range = L.cur().range;
auto subscript_exprs =
parseList('[', ',', ']', &ParserImpl::parseSubscriptExp);
return Subscript::create(range, Expr(value), subscript_exprs);
}
TreeRef parseParam() {
auto ident = parseIdent();
TreeRef type;
if (L.nextIf(':')) {
type = parseExp();
} else {
type = Var::create(L.cur().range, Ident::create(L.cur().range, "Tensor"));
}
TreeRef def;
if (L.nextIf('=')) {
def = Maybe<Expr>::create(L.cur().range, parseExp());
} else {
def = Maybe<Expr>::create(L.cur().range);
}
return Param::create(
type->range(), Ident(ident), Expr(type), Maybe<Expr>(def));
}
Param parseBareTypeAnnotation() {
auto type = parseExp();
return Param::create(
type.range(),
Ident::create(type.range(), ""),
type,
Maybe<Expr>::create(type.range()));
}
Decl parseTypeComment() {
auto range = L.cur().range;
L.expect(TK_TYPE_COMMENT);
auto param_types =
parseList('(', ',', ')', &ParserImpl::parseBareTypeAnnotation);
TreeRef return_type;
if (L.nextIf(TK_ARROW)) {
auto return_type_range = L.cur().range;
return_type = Maybe<Expr>::create(return_type_range, parseExp());
} else {
return_type = Maybe<Expr>::create(L.cur().range);
}
return Decl::create(range, param_types, Maybe<Expr>(return_type));
}
// 'first' has already been parsed since expressions can exist
// alone on a line:
// first[,other,lhs] = rhs
TreeRef parseAssign(const Expr& lhs) {
auto op = parseAssignmentOp();
auto rhs = parseExpOrExpTuple();
L.expect(TK_NEWLINE);
if (op->kind() == '=') {
return Assign::create(lhs.range(), lhs, Expr(rhs));
} else {
// this is an augmented assignment
if (lhs.kind() == TK_TUPLE_LITERAL) {
throw ErrorReport(lhs.range())
<< " augmented assignment can only have one LHS expression";
}
return AugAssign::create(lhs.range(), lhs, AugAssignKind(op), Expr(rhs));
}
}
TreeRef parseStmt() {
switch (L.cur().kind) {
case TK_IF:
return parseIf();
case TK_WHILE:
return parseWhile();
case TK_FOR:
return parseFor();
case TK_GLOBAL: {
auto range = L.next().range;
auto idents =
parseList(TK_NOTHING, ',', TK_NOTHING, &ParserImpl::parseIdent);
L.expect(TK_NEWLINE);
return Global::create(range, idents);
}
case TK_RETURN: {
auto range = L.next().range;
Expr value = L.cur().kind != TK_NEWLINE ? parseExpOrExpTuple()
: Expr(c(TK_NONE, range, {}));
L.expect(TK_NEWLINE);
return Return::create(range, value);
}
case TK_RAISE: {
auto range = L.next().range;
auto expr = parseExp();
L.expect(TK_NEWLINE);
return Raise::create(range, expr);
}
case TK_ASSERT: {
auto range = L.next().range;
auto cond = parseExp();
Maybe<Expr> maybe_first = Maybe<Expr>::create(range);
if (L.nextIf(',')) {
auto msg = parseExp();
maybe_first = Maybe<Expr>::create(range, Expr(msg));
}
L.expect(TK_NEWLINE);
return Assert::create(range, cond, maybe_first);
}
case TK_PASS: {
auto range = L.next().range;
L.expect(TK_NEWLINE);
return Pass::create(range);
}
case TK_DEF: {
return parseFunction(/*is_method=*/false);
}
default: {
auto lhs = parseExpOrExpTuple();
if (L.cur().kind != TK_NEWLINE) {
return parseAssign(lhs);
} else {
L.expect(TK_NEWLINE);
return ExprStmt::create(lhs.range(), lhs);
}
}
}
}
TreeRef parseOptionalIdentList() {
TreeRef list = nullptr;
if (L.cur().kind == '(') {
list = parseList('(', ',', ')', &ParserImpl::parseIdent);
} else {
list = c(TK_LIST, L.cur().range, {});
}
return list;
}
TreeRef parseIf(bool expect_if = true) {
auto r = L.cur().range;
if (expect_if)
L.expect(TK_IF);
auto cond = parseExp();
L.expect(':');
auto true_branch = parseStatements();
auto false_branch = makeList(L.cur().range, {});
if (L.nextIf(TK_ELSE)) {
L.expect(':');
false_branch = parseStatements();
} else if (L.nextIf(TK_ELIF)) {
// NB: this needs to be a separate statement, since the call to parseIf
// mutates the lexer state, and thus causes a heap-use-after-free in
// compilers which evaluate argument expressions LTR
auto range = L.cur().range;
false_branch = makeList(range, {parseIf(false)});
}
return If::create(
r, Expr(cond), List<Stmt>(true_branch), List<Stmt>(false_branch));
}
TreeRef parseWhile() {
auto r = L.cur().range;
L.expect(TK_WHILE);
auto cond = parseExp();
L.expect(':');
auto body = parseStatements();
return While::create(r, Expr(cond), List<Stmt>(body));
}
TreeRef parseFor() {
auto r = L.cur().range;
L.expect(TK_FOR);
auto targets =
parseList(TK_NOTHING, ',', TK_NOTHING, &ParserImpl::parseExp);
L.expect(TK_IN);
auto itrs = parseList(TK_NOTHING, ',', TK_NOTHING, &ParserImpl::parseExp);
L.expect(':');
auto body = parseStatements();
return For::create(r, targets, itrs, body);
}
TreeRef parseStatements(bool expect_indent = true) {
auto r = L.cur().range;
if (expect_indent) {
L.expect(TK_INDENT);
}
TreeList stmts;
do {
stmts.push_back(parseStmt());
} while (!L.nextIf(TK_DEDENT));
return c(TK_LIST, r, std::move(stmts));
}
Maybe<Expr> parseReturnAnnotation() {
if (L.nextIf(TK_ARROW)) {
// Exactly one expression for return type annotation
auto return_type_range = L.cur().range;
return Maybe<Expr>::create(return_type_range, parseExp());
} else {
return Maybe<Expr>::create(L.cur().range);
}
}
Decl parseDecl() {
auto paramlist = parseList('(', ',', ')', &ParserImpl::parseParam);
// Parse return type annotation
TreeRef return_type;
Maybe<Expr> return_annotation = parseReturnAnnotation();
L.expect(':');
return Decl::create(
paramlist.range(), List<Param>(paramlist), return_annotation);
}
TreeRef parseFunction(bool is_method) {
L.expect(TK_DEF);
auto name = parseIdent();
auto decl = parseDecl();
// Handle type annotations specified in a type comment as the first line of
// the function.
L.expect(TK_INDENT);
if (L.cur().kind == TK_TYPE_COMMENT) {
auto type_annotation_decl = Decl(parseTypeComment());
L.expect(TK_NEWLINE);
decl = mergeTypesFromTypeComment(decl, type_annotation_decl, is_method);
}
auto stmts_list = parseStatements(false);
return Def::create(
name.range(), Ident(name), Decl(decl), List<Stmt>(stmts_list));
}
Lexer& lexer() {
return L;
}
private:
// short helpers to create nodes
TreeRef c(int kind, const SourceRange& range, TreeList&& trees) {
return Compound::create(kind, range, std::move(trees));
}
TreeRef makeList(const SourceRange& range, TreeList&& trees) {
return c(TK_LIST, range, std::move(trees));
}
Lexer L;
SharedParserData& shared;
};
Parser::Parser(const std::string& src) : pImpl(new ParserImpl(src)) {}
Parser::~Parser() = default;
TreeRef Parser::parseFunction(bool is_method) {
return pImpl->parseFunction(is_method);
}
Lexer& Parser::lexer() {
return pImpl->lexer();
}
Decl Parser::parseTypeComment() {
return pImpl->parseTypeComment();
}
} // namespace script
} // namespace jit
} // namespace torch
| 29.907638 | 80 | 0.585521 | WoodoLee |
c144cb12e732cd551f7b2ac52de2cfd43aa4245a | 2,361 | hpp | C++ | PSME/common/agent-framework/include/agent-framework/module/enum/network.hpp | opencomputeproject/HWMgmt-DeviceMgr-PSME | 2a00188aab6f4bef3776987f0842ef8a8ea972ac | [
"Apache-2.0"
] | 5 | 2021-10-07T15:36:37.000Z | 2022-03-01T07:21:49.000Z | PSME/common/agent-framework/include/agent-framework/module/enum/network.hpp | opencomputeproject/HWMgmt-DeviceMgr-PSME | 2a00188aab6f4bef3776987f0842ef8a8ea972ac | [
"Apache-2.0"
] | null | null | null | PSME/common/agent-framework/include/agent-framework/module/enum/network.hpp | opencomputeproject/HWMgmt-DeviceMgr-PSME | 2a00188aab6f4bef3776987f0842ef8a8ea972ac | [
"Apache-2.0"
] | 1 | 2022-03-01T07:21:51.000Z | 2022-03-01T07:21:51.000Z | /*!
* @copyright
* Copyright (c) 2015-2017 Intel Corporation
*
* @copyright
* 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
*
* @copyright
* http://www.apache.org/licenses/LICENSE-2.0
*
* @copyright
* 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 network.hpp
* @brief string enums for model classes, see enum_builder.hpp for more info
* */
#pragma once
#include "enum_builder.hpp"
namespace agent_framework {
namespace model {
namespace enums {
/*!
* @brief ENUM SwitchTechnology for Switch class member
*
* */
ENUM(SwitchTechnology, uint32_t, Ethernet, PCIe);
/*!
* @brief ENUM Switch role in the network
* */
ENUM(SwitchRole, uint32_t, TOR, EOR, Drawer, Unknown);
/*!
* @brief ENUM PortType for Switch Port class member
*
* */
ENUM(PortType, uint32_t, Upstream, Downstream, MeshPort, Unknown);
/*!
* @brief ENUM PortClass for Switch Port class member
*
* */
ENUM(PortClass, uint32_t, Physical, Logical, Reserved);
/*!
* @brief ENUM PortMode for Switch Port class member
*
* */
ENUM(PortMode, uint32_t,
Unknown, LinkAggregationStatic, LinkAggregationDynamic);
/*!
* @brief ENUM LinkTechnology for Switch Port class member
*
* */
ENUM(LinkTechnology, uint32_t, Ethernet, PCIe, Unknown);
/*!
* @brief ENUM OperationalState for Switch Port class member
*
* */
ENUM(OperationalState, uint32_t, Up, Down, Unknown);
/*!
* @brief ENUM AdministrativeState for Switch Port class member
*
* */
ENUM(AdministrativeState, uint32_t, Up, Down);
/*!
* @brief ENUM NetworkServiceName for Manager class Network Service subclass
* member
* */
ENUM(NetworkServiceName, uint32_t, HTTP, HTTPS, SNMP, VirtualMedia, Telnet,
SSDP, IPMI, SSH, KVMIP);
/*!
* @brief ENUM AclAction for Acl rule
* */
ENUM(AclAction, uint32_t, Permit, Deny, Forward, Mirror);
/*!
* @brief ENUM AclMirrorType for Acl mirror rule
* */
ENUM(AclMirrorType, uint32_t, Egress, Ingress, Bidirectional, Redirect);
}
}
}
| 23.376238 | 76 | 0.711139 | opencomputeproject |
c146e2d8b34e78abf481531b645867f682d0c62f | 4,653 | cpp | C++ | simulator/src/monitor.cpp | CMU-SAFARI/DAMOV | ed39a0642f22d551bed6ab6baaf91c89cc8a3855 | [
"MIT"
] | 17 | 2021-07-10T13:22:26.000Z | 2022-02-09T20:11:39.000Z | simulator/src/monitor.cpp | CMU-SAFARI/DAMOV | ed39a0642f22d551bed6ab6baaf91c89cc8a3855 | [
"MIT"
] | 4 | 2021-08-18T14:07:24.000Z | 2022-01-24T16:38:06.000Z | simulator/src/monitor.cpp | CMU-SAFARI/DAMOV | ed39a0642f22d551bed6ab6baaf91c89cc8a3855 | [
"MIT"
] | 2 | 2021-08-03T10:56:16.000Z | 2022-01-31T12:10:56.000Z | /** $lic$
* Copyright (C) 2012-2015 by Massachusetts Institute of Technology
* Copyright (C) 2010-2013 by The Board of Trustees of Stanford University
*
* This file is part of zsim.
*
* zsim 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.
*
* If you use this software in your research, we request that you reference
* the zsim paper ("ZSim: Fast and Accurate Microarchitectural Simulation of
* Thousand-Core Systems", Sanchez and Kozyrakis, ISCA-40, June 2013) as the
* source of the simulator in any publications that use this software, and that
* you send us a citation of your work.
*
* zsim is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "partitioner.h"
// UMon
UMonMonitor::UMonMonitor(uint32_t _numLines, uint32_t _umonLines, uint32_t _umonBuckets, uint32_t _numPartitions, uint32_t _buckets)
: PartitionMonitor(_buckets)
, missCache(nullptr)
, missCacheValid(false)
, monitors(_numPartitions, nullptr) {
assert(_numPartitions > 0);
missCache = gm_calloc<uint32_t>(_buckets * _numPartitions);
for (auto& monitor : monitors) {
monitor = new UMon(_numLines, _umonLines, _umonBuckets);
}
}
UMonMonitor::~UMonMonitor() {
for (auto monitor : monitors) {
delete monitor;
}
gm_free(missCache);
monitors.clear();
}
void UMonMonitor::access(uint32_t partition, Address lineAddr) {
assert(partition < monitors.size());
monitors[partition]->access(lineAddr);
// check optimization assumption -- we shouldn't cache all misses
// if they are getting accessed while they are updated! -nzb
assert(!missCacheValid);
missCacheValid = false;
}
uint32_t UMonMonitor::getNumAccesses(uint32_t partition) const {
assert(partition < monitors.size());
auto monitor = monitors[partition];
return monitor->getNumAccesses();
}
uint32_t UMonMonitor::get(uint32_t partition, uint32_t bucket) const {
assert(partition < monitors.size());
if (!missCacheValid) {
getMissCurves();
missCacheValid = true;
}
return missCache[partition*buckets+bucket];
}
void UMonMonitor::getMissCurves() const {
for (uint32_t partition = 0; partition < getNumPartitions(); partition++) {
getMissCurve(&missCache[partition*buckets], partition);
}
}
void UMonMonitor::getMissCurve(uint32_t* misses, uint32_t partition) const {
assert(partition < monitors.size());
auto monitor = monitors[partition];
uint32_t umonBuckets = monitor->getBuckets();
uint64_t umonMisses[ umonBuckets ];
monitor->getMisses(umonMisses);
// Upsample or downsample
// We have an odd number of elements; the last one is the one that
// should not be aliased, as it is the one without buckets
if (umonBuckets >= buckets) {
uint32_t downsampleRatio = umonBuckets/buckets;
assert(umonBuckets % buckets == 0);
//info("Downsampling (or keeping sampling), ratio %d", downsampleRatio);
for (uint32_t j = 0; j < buckets; j++) {
misses[j] = umonMisses[j*downsampleRatio];
}
misses[buckets] = umonMisses[umonBuckets];
} else {
uint32_t upsampleRatio = buckets/umonBuckets;
assert(buckets % umonBuckets == 0);
//info("Upsampling , ratio %d", upsampleRatio);
for (uint32_t j = 0; j < umonBuckets; j++) {
misses[upsampleRatio*j] = umonMisses[j];
double m0 = umonMisses[j];
double m1 = umonMisses[j+1];
for (uint32_t k = 1; k < upsampleRatio; k++) {
double frac = ((double)k)/((double)upsampleRatio);
double m = m0*(1-frac) + m1*(frac);
misses[upsampleRatio*j + k] = (uint64_t)m;
}
misses[buckets] = umonMisses[umonBuckets];
}
}
/*info("Miss utility curves %d:", partition);
for (uint32_t j = 0; j <= buckets; j++) info(" misses[%d] = %ld", j, misses[j]);
for (uint32_t j = 0; j <= umonBuckets; j++) info(" umonMisses[%d] = %ld", j, umonMisses[j]);
*/
}
void UMonMonitor::reset() {
for (auto monitor : monitors) {
monitor->startNextInterval();
}
missCacheValid = false;
}
| 34.213235 | 132 | 0.660434 | CMU-SAFARI |
c14a9437c1fa8ad7de2a867bc432c5242a18810b | 13,023 | cpp | C++ | 3rdparty/FlyCube/src/Apps/CoreDxrTriangle/main.cpp | CU-Production/FlyCube-Demos | 2763720818499bc9244eb4b16e60e647a5c88827 | [
"MIT"
] | 8 | 2021-03-17T19:25:12.000Z | 2022-02-05T02:08:21.000Z | 3rdparty/FlyCube/src/Apps/CoreDxrTriangle/main.cpp | THISISAGOODNAME/SSSR | ea4b6350b2da3d5656c7aa8c87f9965144369d22 | [
"MIT"
] | null | null | null | 3rdparty/FlyCube/src/Apps/CoreDxrTriangle/main.cpp | THISISAGOODNAME/SSSR | ea4b6350b2da3d5656c7aa8c87f9965144369d22 | [
"MIT"
] | 2 | 2021-09-22T14:39:51.000Z | 2021-11-08T09:47:38.000Z | #include <AppBox/AppBox.h>
#include <AppBox/ArgsParser.h>
#include <Instance/Instance.h>
#include <stdexcept>
#include <glm/gtx/transform.hpp>
#include <Utilities/Common.h>
int main(int argc, char* argv[])
{
Settings settings = ParseArgs(argc, argv);
AppBox app("CoreDxrTriangle", settings);
AppRect rect = app.GetAppRect();
std::shared_ptr<Instance> instance = CreateInstance(settings.api_type);
std::shared_ptr<Adapter> adapter = std::move(instance->EnumerateAdapters()[settings.required_gpu_index]);
app.SetGpuName(adapter->GetName());
std::shared_ptr<Device> device = adapter->CreateDevice();
if (!device->IsDxrSupported())
throw std::runtime_error("Ray Tracing is not supported");
std::shared_ptr<CommandQueue> command_queue = device->GetCommandQueue(CommandListType::kGraphics);
std::shared_ptr<CommandQueue> upload_command_queue = device->GetCommandQueue(CommandListType::kGraphics);
constexpr uint32_t frame_count = 3;
std::shared_ptr<Swapchain> swapchain = device->CreateSwapchain(app.GetNativeWindow(), rect.width, rect.height, frame_count, settings.vsync);
uint64_t fence_value = 0;
std::shared_ptr<Fence> fence = device->CreateFence(fence_value);
std::vector<uint32_t> index_data = { 0, 1, 2 };
std::shared_ptr<Resource> index_buffer = device->CreateBuffer(BindFlag::kIndexBuffer | BindFlag::kCopyDest, sizeof(uint32_t) * index_data.size());
index_buffer->CommitMemory(MemoryType::kDefault);
index_buffer->SetName("index_buffer");
std::vector<glm::vec3> vertex_data = { glm::vec3(-0.5, -0.5, 0.0), glm::vec3(0.0, 0.5, 0.0), glm::vec3(0.5, -0.5, 0.0) };
std::shared_ptr<Resource> vertex_buffer = device->CreateBuffer(BindFlag::kVertexBuffer | BindFlag::kCopyDest, sizeof(vertex_data.front()) * vertex_data.size());
vertex_buffer->CommitMemory(MemoryType::kDefault);
vertex_buffer->SetName("vertex_buffer");
std::shared_ptr<Resource> upload_buffer = device->CreateBuffer(BindFlag::kCopySource, index_buffer->GetWidth() + vertex_buffer->GetWidth());
upload_buffer->CommitMemory(MemoryType::kUpload);
upload_buffer->SetName("upload_buffer");
upload_buffer->UpdateUploadBuffer(0, index_data.data(), sizeof(index_data.front()) * index_data.size());
upload_buffer->UpdateUploadBuffer(index_buffer->GetWidth(), vertex_data.data(), sizeof(vertex_data.front()) * vertex_data.size());
std::shared_ptr<CommandList> upload_command_list = device->CreateCommandList(CommandListType::kGraphics);
upload_command_list->CopyBuffer(upload_buffer, index_buffer, { { 0, 0, index_buffer->GetWidth() } });
upload_command_list->CopyBuffer(upload_buffer, vertex_buffer, { { index_buffer->GetWidth(), 0, vertex_buffer->GetWidth() } });
upload_command_list->ResourceBarrier({ { index_buffer, ResourceState::kCopyDest, ResourceState::kNonPixelShaderResource } });
upload_command_list->ResourceBarrier({ { vertex_buffer, ResourceState::kCopyDest, ResourceState::kNonPixelShaderResource } });
RaytracingGeometryDesc raytracing_geometry_desc = {
{ vertex_buffer, gli::format::FORMAT_RGB32_SFLOAT_PACK32, 3 },
{ index_buffer, gli::format::FORMAT_R32_UINT_PACK32, 3 },
RaytracingGeometryFlags::kOpaque
};
const uint32_t bottom_count = 2;
auto blas_prebuild_info = device->GetBLASPrebuildInfo({ raytracing_geometry_desc }, BuildAccelerationStructureFlags::kAllowCompaction);
auto tlas_prebuild_info = device->GetTLASPrebuildInfo(bottom_count, BuildAccelerationStructureFlags::kNone);
uint64_t acceleration_structures_size = Align(blas_prebuild_info.acceleration_structure_size, kAccelerationStructureAlignment) + tlas_prebuild_info.acceleration_structure_size;
std::shared_ptr<Resource> acceleration_structures_memory = device->CreateBuffer(BindFlag::kAccelerationStructure, acceleration_structures_size);
acceleration_structures_memory->CommitMemory(MemoryType::kDefault);
acceleration_structures_memory->SetName("acceleration_structures_memory");
std::shared_ptr<Resource> bottom = device->CreateAccelerationStructure(
AccelerationStructureType::kBottomLevel,
acceleration_structures_memory,
0
);
auto scratch = device->CreateBuffer(BindFlag::kRayTracing, std::max(blas_prebuild_info.build_scratch_data_size, tlas_prebuild_info.build_scratch_data_size));
scratch->CommitMemory(MemoryType::kDefault);
scratch->SetName("scratch");
auto blas_compacted_size_buffer = device->CreateBuffer(BindFlag::kCopyDest, sizeof(uint64_t));
blas_compacted_size_buffer->CommitMemory(MemoryType::kReadback);
blas_compacted_size_buffer->SetName("blas_compacted_size_buffer");
auto query_heap = device->CreateQueryHeap(QueryHeapType::kAccelerationStructureCompactedSize, 1);
upload_command_list->BuildBottomLevelAS({}, bottom, scratch, 0, { raytracing_geometry_desc }, BuildAccelerationStructureFlags::kAllowCompaction);
upload_command_list->UAVResourceBarrier(bottom);
upload_command_list->WriteAccelerationStructuresProperties({ bottom }, query_heap, 0);
upload_command_list->ResolveQueryData(query_heap, 0, 1, blas_compacted_size_buffer, 0);
upload_command_list->Close();
upload_command_queue->ExecuteCommandLists({ upload_command_list });
upload_command_queue->Signal(fence, ++fence_value);
fence->Wait(fence_value);
uint64_t blas_compacted_size = *reinterpret_cast<uint64_t*>(blas_compacted_size_buffer->Map());
blas_compacted_size_buffer->Unmap();
upload_command_list->Reset();
upload_command_list->CopyAccelerationStructure(bottom, bottom, CopyAccelerationStructureMode::kCompact);
std::vector<std::pair<std::shared_ptr<Resource>, glm::mat4x4>> geometry = {
{ bottom, glm::transpose(glm::translate(glm::vec3(-0.5f, 0.0f, 0.0f))) },
{ bottom, glm::transpose(glm::translate(glm::vec3(0.5f, 0.0f, 0.0f))) },
};
assert(geometry.size() == bottom_count);
std::vector<RaytracingGeometryInstance> instances;
for (const auto& mesh : geometry)
{
RaytracingGeometryInstance& instance = instances.emplace_back();
memcpy(&instance.transform, &mesh.second, sizeof(instance.transform));
instance.instance_offset = static_cast<uint32_t>(instances.size() - 1);
instance.instance_mask = 0xff;
instance.acceleration_structure_handle = mesh.first->GetAccelerationStructureHandle();
}
std::shared_ptr<Resource> top = device->CreateAccelerationStructure(
AccelerationStructureType::kTopLevel,
acceleration_structures_memory,
Align(blas_compacted_size, kAccelerationStructureAlignment)
);
auto instance_data = device->CreateBuffer(BindFlag::kRayTracing, instances.size() * sizeof(instances.back()));
instance_data->CommitMemory(MemoryType::kUpload);
instance_data->SetName("instance_data");
instance_data->UpdateUploadBuffer(0, instances.data(), instances.size() * sizeof(instances.back()));
upload_command_list->BuildTopLevelAS({}, top, scratch, 0, instance_data, 0, instances.size(), BuildAccelerationStructureFlags::kNone);
upload_command_list->UAVResourceBarrier(top);
std::shared_ptr<Resource> uav = device->CreateTexture(TextureType::k2D, BindFlag::kUnorderedAccess | BindFlag::kCopySource, swapchain->GetFormat(), 1, rect.width, rect.height, 1, 1);
uav->CommitMemory(MemoryType::kDefault);
uav->SetName("uav");
upload_command_list->ResourceBarrier({ { uav, uav->GetInitialState(), ResourceState::kUnorderedAccess } });
upload_command_list->Close();
upload_command_queue->ExecuteCommandLists({ upload_command_list });
upload_command_queue->Signal(fence, ++fence_value);
command_queue->Wait(fence, fence_value);
ViewDesc top_view_desc = {};
top_view_desc.view_type = ViewType::kAccelerationStructure;
std::shared_ptr<View> top_view = device->CreateView(top, top_view_desc);
ViewDesc uav_view_desc = {};
uav_view_desc.view_type = ViewType::kRWTexture;
uav_view_desc.dimension = ViewDimension::kTexture2D;
std::shared_ptr<View> uav_view = device->CreateView(uav, uav_view_desc);
std::shared_ptr<Shader> library = device->CompileShader({ ASSETS_PATH"shaders/CoreDxrTriangle/RayTracing.hlsl", "", ShaderType::kLibrary, "6_3" });
std::shared_ptr<Shader> library_hit = device->CompileShader({ ASSETS_PATH"shaders/CoreDxrTriangle/RayTracingHit.hlsl", "", ShaderType::kLibrary, "6_3" });
std::shared_ptr<Shader> library_callable = device->CompileShader({ ASSETS_PATH"shaders/CoreDxrTriangle/RayTracingCallable.hlsl", "", ShaderType::kLibrary, "6_3" });
std::shared_ptr<Program> program = device->CreateProgram({ library, library_hit, library_callable });
BindKey geometry_key = library->GetBindKey("geometry");
BindKey result_key = library->GetBindKey("result");
std::shared_ptr<BindingSetLayout> layout = device->CreateBindingSetLayout({ geometry_key, result_key });
std::shared_ptr<BindingSet> binding_set = device->CreateBindingSet(layout);
binding_set->WriteBindings({
{ geometry_key, top_view },
{ result_key, uav_view }
});
std::vector<RayTracingShaderGroup> groups;
groups.push_back({ RayTracingShaderGroupType::kGeneral, library->GetId("ray_gen") });
groups.push_back({ RayTracingShaderGroupType::kGeneral, library->GetId("miss") });
groups.push_back({ RayTracingShaderGroupType::kTrianglesHitGroup, 0, library_hit->GetId("closest_red") });
groups.push_back({ RayTracingShaderGroupType::kTrianglesHitGroup, 0, library_hit->GetId("closest_green") });
groups.push_back({ RayTracingShaderGroupType::kGeneral, library_callable->GetId("callable") });
std::shared_ptr<Pipeline> pipeline = device->CreateRayTracingPipeline({ program, layout, groups });
std::shared_ptr<Resource> shader_table = device->CreateBuffer(BindFlag::kShaderTable, device->GetShaderTableAlignment() * groups.size());
shader_table->CommitMemory(MemoryType::kUpload);
shader_table->SetName("shader_table");
decltype(auto) shader_handles = pipeline->GetRayTracingShaderGroupHandles(0, groups.size());
for (size_t i = 0; i < groups.size(); ++i)
{
shader_table->UpdateUploadBuffer(i * device->GetShaderTableAlignment(), shader_handles.data() + i * device->GetShaderGroupHandleSize(), device->GetShaderGroupHandleSize());
}
RayTracingShaderTables shader_tables = {};
shader_tables.raygen = { shader_table, 0 * device->GetShaderTableAlignment(), device->GetShaderTableAlignment(), device->GetShaderTableAlignment() };
shader_tables.miss = { shader_table, 1 * device->GetShaderTableAlignment(), device->GetShaderTableAlignment(), device->GetShaderTableAlignment() };
shader_tables.hit = { shader_table, 2 * device->GetShaderTableAlignment(), 2 * device->GetShaderTableAlignment(), device->GetShaderTableAlignment() };
shader_tables.callable = { shader_table, 4 * device->GetShaderTableAlignment(), device->GetShaderTableAlignment(), device->GetShaderTableAlignment() };
std::array<uint64_t, frame_count> fence_values = {};
std::vector<std::shared_ptr<CommandList>> command_lists;
for (uint32_t i = 0; i < frame_count; ++i)
{
std::shared_ptr<Resource> back_buffer = swapchain->GetBackBuffer(i);
ViewDesc back_buffer_view_desc = {};
back_buffer_view_desc.view_type = ViewType::kRenderTarget;
back_buffer_view_desc.dimension = ViewDimension::kTexture2D;
std::shared_ptr<View> back_buffer_view = device->CreateView(back_buffer, back_buffer_view_desc);
command_lists.emplace_back(device->CreateCommandList(CommandListType::kGraphics));
std::shared_ptr<CommandList> command_list = command_lists[i];
command_list->BindPipeline(pipeline);
command_list->BindBindingSet(binding_set);
command_list->DispatchRays(shader_tables, rect.width, rect.height, 1);
command_list->ResourceBarrier({ { back_buffer, ResourceState::kPresent, ResourceState::kCopyDest } });
command_list->ResourceBarrier({ { uav, ResourceState::kUnorderedAccess, ResourceState::kCopySource } });
command_list->CopyTexture(uav, back_buffer, { { rect.width, rect.height, 1 } });
command_list->ResourceBarrier({ { uav, ResourceState::kCopySource, ResourceState::kUnorderedAccess } });
command_list->ResourceBarrier({ { back_buffer, ResourceState::kCopyDest, ResourceState::kPresent } });
command_list->Close();
}
while (!app.PollEvents())
{
uint32_t frame_index = swapchain->NextImage(fence, ++fence_value);
command_queue->Wait(fence, fence_value);
fence->Wait(fence_values[frame_index]);
command_queue->ExecuteCommandLists({ command_lists[frame_index] });
command_queue->Signal(fence, fence_values[frame_index] = ++fence_value);
swapchain->Present(fence, fence_values[frame_index]);
}
command_queue->Signal(fence, ++fence_value);
fence->Wait(fence_value);
return 0;
}
| 61.140845 | 186 | 0.744222 | CU-Production |
c14ea670d80601a960264ee8bca5a1cbd59b206b | 67,124 | cpp | C++ | common/BaseDatapath.cpp | httsai/NTHU_Aladdin | 4140fcdade512b89647608b9b724690c5d3b2ba4 | [
"BSL-1.0"
] | null | null | null | common/BaseDatapath.cpp | httsai/NTHU_Aladdin | 4140fcdade512b89647608b9b724690c5d3b2ba4 | [
"BSL-1.0"
] | null | null | null | common/BaseDatapath.cpp | httsai/NTHU_Aladdin | 4140fcdade512b89647608b9b724690c5d3b2ba4 | [
"BSL-1.0"
] | null | null | null | #include <sstream>
#include <boost/tokenizer.hpp>
#include "opcode_func.h"
#include "BaseDatapath.h"
BaseDatapath::BaseDatapath(std::string bench, string trace_file, string config_file, float cycle_t)
{
benchName = (char*) bench.c_str();
cycleTime = cycle_t;
DDDG *dddg;
dddg = new DDDG(this, trace_file);
/*Build Initial DDDG*/
if (dddg->build_initial_dddg())
{
std::cerr << "-------------------------------" << std::endl;
std::cerr << " Aladdin Ends.. " << std::endl;
std::cerr << "-------------------------------" << std::endl;
exit(0);
}
delete dddg;
std::cerr << "-------------------------------" << std::endl;
std::cerr << " Initializing BaseDatapath " << std::endl;
std::cerr << "-------------------------------" << std::endl;
numTotalNodes = microop.size();
BGL_FORALL_VERTICES(v, graph_, Graph)
nameToVertex[get(boost::vertex_index, graph_, v)] = v;
vertexToName = get(boost::vertex_index, graph_);
std::vector<std::string> dynamic_methodid(numTotalNodes, "");
initDynamicMethodID(dynamic_methodid);
for (auto dynamic_func_it = dynamic_methodid.begin(), E = dynamic_methodid.end();
dynamic_func_it != E; dynamic_func_it++)
{
char func_id[256];
int count;
sscanf((*dynamic_func_it).c_str(), "%[^-]-%d\n", func_id, &count);
if (functionNames.find(func_id) == functionNames.end())
functionNames.insert(func_id);
}
parse_config(bench, config_file);
num_cycles = 0;
}
BaseDatapath::~BaseDatapath() {}
void BaseDatapath::addDddgEdge(unsigned int from, unsigned int to, uint8_t parid)
{
if (from != to)
add_edge(from, to, EdgeProperty(parid), graph_);
}
//optimizationFunctions
void BaseDatapath::setGlobalGraph()
{
std::cerr << "=============================================" << std::endl;
std::cerr << " Optimizing... " << benchName << std::endl;
std::cerr << "=============================================" << std::endl;
finalIsolated.assign(numTotalNodes, 1);
}
void BaseDatapath::memoryAmbiguation()
{
std::cerr << "-------------------------------" << std::endl;
std::cerr << " Memory Ambiguation " << std::endl;
std::cerr << "-------------------------------" << std::endl;
std::unordered_multimap<std::string, std::string> pair_per_load;
std::unordered_set<std::string> paired_store;
std::unordered_map<std::string, bool> store_load_pair;
std::vector<std::string> instid(numTotalNodes, "");
std::vector<std::string> dynamic_methodid(numTotalNodes, "");
std::vector<std::string> prev_basic_block(numTotalNodes, "");
initInstID(instid);
initDynamicMethodID(dynamic_methodid);
initPrevBasicBlock(prev_basic_block);
std::vector< Vertex > topo_nodes;
boost::topological_sort(graph_, std::back_inserter(topo_nodes));
//nodes with no incoming edges to first
for (auto vi = topo_nodes.rbegin(); vi != topo_nodes.rend(); ++vi)
{
unsigned node_id = vertexToName[*vi];
int node_microop = microop.at(node_id);
if (!is_store_op(node_microop))
continue;
//iterate its children to find a load op
out_edge_iter out_edge_it, out_edge_end;
for (tie(out_edge_it, out_edge_end) = out_edges(*vi, graph_); out_edge_it != out_edge_end; ++out_edge_it)
{
int child_id = vertexToName[target(*out_edge_it, graph_)];
int child_microop = microop.at(child_id);
if (!is_load_op(child_microop))
continue;
std::string node_dynamic_methodid = dynamic_methodid.at(node_id);
std::string load_dynamic_methodid = dynamic_methodid.at(child_id);
if (node_dynamic_methodid.compare(load_dynamic_methodid) != 0)
continue;
std::string store_unique_id (node_dynamic_methodid + "-" + instid.at(node_id) + "-" + prev_basic_block.at(node_id));
std::string load_unique_id (load_dynamic_methodid+ "-" + instid.at(child_id) + "-" + prev_basic_block.at(child_id));
if (store_load_pair.find(store_unique_id + "-" + load_unique_id ) != store_load_pair.end())
continue;
//add to the pair
store_load_pair[store_unique_id + "-" + load_unique_id] = 1;
paired_store.insert(store_unique_id);
auto load_range = pair_per_load.equal_range(load_unique_id);
bool found_store = 0;
for (auto store_it = load_range.first; store_it != load_range.second; store_it++)
{
if (store_unique_id.compare(store_it->second) == 0)
{
found_store = 1;
break;
}
}
if (!found_store)
{
pair_per_load.insert(make_pair(load_unique_id,store_unique_id));
}
}
}
if (store_load_pair.size() == 0)
return;
std::vector<newEdge> to_add_edges;
std::unordered_map<std::string, unsigned> last_store;
for (unsigned node_id = 0; node_id < numTotalNodes; node_id++)
{
int node_microop = microop.at(node_id);
if (!is_memory_op(node_microop))
continue;
std::string unique_id (dynamic_methodid.at(node_id) + "-" + instid.at(node_id) + "-" + prev_basic_block.at(node_id));
if (is_store_op(node_microop))
{
auto store_it = paired_store.find(unique_id);
if (store_it == paired_store.end())
continue;
last_store[unique_id] = node_id;
}
else
{
assert(is_load_op(node_microop));
auto load_range = pair_per_load.equal_range(unique_id);
if (std::distance(load_range.first, load_range.second) == 1)
continue;
for (auto load_store_it = load_range.first; load_store_it != load_range.second; ++load_store_it)
{
assert(paired_store.find(load_store_it->second) != paired_store.end());
auto prev_store_it = last_store.find(load_store_it->second);
if (prev_store_it == last_store.end())
continue;
unsigned prev_store_id = prev_store_it->second;
if (!doesEdgeExist(prev_store_id, node_id))
{
to_add_edges.push_back({prev_store_id, node_id, -1});
dynamicMemoryOps.insert(load_store_it->second + "-" + prev_basic_block.at(prev_store_id));
dynamicMemoryOps.insert(load_store_it->first + "-" + prev_basic_block.at(node_id));
}
}
}
}
updateGraphWithNewEdges(to_add_edges);
}
/*
* Read: graph_, microop
* Modify: graph_
*/
void BaseDatapath::removePhiNodes()
{
std::cerr << "-------------------------------" << std::endl;
std::cerr << " Remove PHI and BitCast Nodes " << std::endl;
std::cerr << "-------------------------------" << std::endl;
EdgeNameMap edge_to_parid = get(boost::edge_name, graph_);
std::set<Edge> to_remove_edges;
std::vector<newEdge> to_add_edges;
vertex_iter vi, vi_end;
int removed_phi = 0;
for (tie(vi, vi_end) = vertices(graph_); vi != vi_end; ++vi)
{
unsigned node_id = vertexToName[*vi];
int node_microop = microop.at(node_id);
if (node_microop != LLVM_IR_PHI && node_microop != LLVM_IR_BitCast)
continue;
//find its children
std::vector< pair<unsigned, int> > phi_child;
out_edge_iter out_edge_it, out_edge_end;
for (tie(out_edge_it, out_edge_end) = out_edges(*vi, graph_);
out_edge_it != out_edge_end; ++out_edge_it)
{
to_remove_edges.insert(*out_edge_it);
phi_child.push_back(make_pair(vertexToName[target(*out_edge_it, graph_)],
edge_to_parid[*out_edge_it]));
}
if (phi_child.size() == 0)
continue;
//find its parents
in_edge_iter in_edge_it, in_edge_end;
for (tie(in_edge_it, in_edge_end) = in_edges(*vi, graph_);
in_edge_it != in_edge_end; ++in_edge_it)
{
unsigned parent_id = vertexToName[source(*in_edge_it, graph_)];
to_remove_edges.insert(*in_edge_it);
for (auto child_it = phi_child.begin(), chil_E = phi_child.end();
child_it != chil_E; ++child_it)
to_add_edges.push_back({parent_id, child_it->first, child_it->second});
}
std::vector<pair<unsigned, int> >().swap(phi_child);
removed_phi++;
}
updateGraphWithIsolatedEdges(to_remove_edges);
updateGraphWithNewEdges(to_add_edges);
cleanLeafNodes();
}
/*
* Read: lineNum.gz, flattenConfig, microop
* Modify: graph_
*/
void BaseDatapath::loopFlatten()
{
std::unordered_set<int> flatten_config;
if (!readFlattenConfig(flatten_config))
return;
std::cerr << "-------------------------------" << std::endl;
std::cerr << " Loop Flatten " << std::endl;
std::cerr << "-------------------------------" << std::endl;
std::vector<int> lineNum(numTotalNodes, -1);
initLineNum(lineNum);
std::vector<unsigned> to_remove_nodes;
for(unsigned node_id = 0; node_id < numTotalNodes; node_id++)
{
int node_linenum = lineNum.at(node_id);
auto it = flatten_config.find(node_linenum);
if (it == flatten_config.end())
continue;
if (is_compute_op(microop.at(node_id)))
microop.at(node_id) = LLVM_IR_Move;
else if (is_branch_op(microop.at(node_id)))
to_remove_nodes.push_back(node_id);
}
updateGraphWithIsolatedNodes(to_remove_nodes);
cleanLeafNodes();
}
void BaseDatapath::cleanLeafNodes()
{
EdgeNameMap edge_to_parid = get(boost::edge_name, graph_);
/*track the number of children each node has*/
std::vector<int> num_of_children(numTotalNodes, 0);
std::vector<unsigned> to_remove_nodes;
std::vector< Vertex > topo_nodes;
boost::topological_sort(graph_, std::back_inserter(topo_nodes));
//bottom nodes first
for (auto vi = topo_nodes.begin(); vi != topo_nodes.end(); ++vi)
{
Vertex node_vertex = *vi;
if (boost::degree(node_vertex, graph_) == 0)
continue;
unsigned node_id = vertexToName[node_vertex];
int node_microop = microop.at(node_id);
if (num_of_children.at(node_id) == boost::out_degree(node_vertex, graph_)
&& node_microop != LLVM_IR_SilentStore
&& node_microop != LLVM_IR_Store
&& node_microop != LLVM_IR_Ret
&& !is_branch_op(node_microop))
{
to_remove_nodes.push_back(node_id);
//iterate its parents
in_edge_iter in_edge_it, in_edge_end;
for (tie(in_edge_it, in_edge_end) = in_edges(node_vertex, graph_); in_edge_it != in_edge_end; ++in_edge_it)
{
int parent_id = vertexToName[source(*in_edge_it, graph_)];
num_of_children.at(parent_id)++;
}
}
else if (is_branch_op(node_microop))
{
//iterate its parents
in_edge_iter in_edge_it, in_edge_end;
for (tie(in_edge_it, in_edge_end) = in_edges(node_vertex, graph_); in_edge_it != in_edge_end; ++in_edge_it)
{
if (edge_to_parid[*in_edge_it] == CONTROL_EDGE)
{
int parent_id = vertexToName[source(*in_edge_it, graph_)];
num_of_children.at(parent_id)++;
}
}
}
}
updateGraphWithIsolatedNodes(to_remove_nodes);
}
/*
* Read: graph_, instid, microop
* Modify: microop
*/
void BaseDatapath::removeInductionDependence()
{
//set graph
std::cerr << "-------------------------------" << std::endl;
std::cerr << " Remove Induction Dependence " << std::endl;
std::cerr << "-------------------------------" << std::endl;
std::vector<std::string> instid(numTotalNodes, "");
initInstID(instid);
std::vector< Vertex > topo_nodes;
boost::topological_sort(graph_, std::back_inserter(topo_nodes));
//nodes with no incoming edges to first
for (auto vi = topo_nodes.rbegin(); vi != topo_nodes.rend(); ++vi)
{
unsigned node_id = vertexToName[*vi];
std::string node_instid = instid.at(node_id);
if (node_instid.find("indvars") == std::string::npos)
continue;
if (microop.at(node_id) == LLVM_IR_Add )
microop.at(node_id) = LLVM_IR_IndexAdd;
}
}
//called in the end of the whole flow
void BaseDatapath::dumpStats()
{
clearGraph();
dumpGraph();
writeMicroop(microop);
writeFinalLevel();
writeGlobalIsolated();
}
void BaseDatapath::loopPipelining()
{
if (!readPipeliningConfig())
{
std::cerr << "Loop Pipelining is not ON." << std::endl;
return ;
}
std::unordered_map<int, int > unrolling_config;
if (!readUnrollingConfig(unrolling_config))
{
std::cerr << "Loop Unrolling is not defined. " << std::endl;
std::cerr << "Loop pipelining is only applied to unrolled loops." << std::endl;
return ;
}
if (loopBound.size() <= 2)
return;
std::cerr << "-------------------------------" << std::endl;
std::cerr << " Loop Pipelining " << std::endl;
std::cerr << "-------------------------------" << std::endl;
EdgeNameMap edge_to_parid = get(boost::edge_name, graph_);
vertex_iter vi, vi_end;
std::set<Edge> to_remove_edges;
std::vector<newEdge> to_add_edges;
//After loop unrolling, we define strict control dependences between basic block,
//where all the instructions in the following basic block depend on the prev branch instruction
//To support loop pipelining, which allows the next iteration
//starting without waiting until the prev iteration finish, we move the control dependences
//between last branch node in the prev basic block and instructions in the next basic block
//to first non isolated instruction in the prev basic block and instructions in the next basic block...
std::map<unsigned, unsigned> first_non_isolated_node;
auto bound_it = loopBound.begin();
unsigned node_id = *bound_it;
//skip first region
bound_it++;
while ( (unsigned)node_id < numTotalNodes)
{
assert(is_branch_op(microop.at(*bound_it)));
while (node_id < *bound_it && (unsigned) node_id < numTotalNodes)
{
if (nameToVertex.find(node_id) == nameToVertex.end()
|| boost::degree(nameToVertex[node_id], graph_) == 0
|| is_branch_op(microop.at(node_id)) ) {
node_id++;
continue;
}
else {
first_non_isolated_node[*bound_it] = node_id;
node_id = *bound_it;
break;
}
}
if (first_non_isolated_node.find(*bound_it) == first_non_isolated_node.end())
first_non_isolated_node[*bound_it] = *bound_it;
bound_it++;
if (bound_it == loopBound.end() - 1 )
break;
}
int prev_branch = -1;
int prev_first = -1;
for(auto first_it = first_non_isolated_node.begin(), E = first_non_isolated_node.end(); first_it != E; ++first_it)
{
unsigned br_node = first_it->first;
unsigned first_id = first_it->second;
if (is_call_op(microop.at(br_node))) {
prev_branch = -1;
continue;
}
if (prev_branch != -1)
{
//adding dependence between prev_first and first_id
if (!doesEdgeExist(prev_first, first_id))
to_add_edges.push_back({(unsigned)prev_first, first_id, CONTROL_EDGE});
//adding dependence between first_id and prev_branch's children
out_edge_iter out_edge_it, out_edge_end;
for (tie(out_edge_it, out_edge_end) = out_edges(nameToVertex[prev_branch], graph_); out_edge_it != out_edge_end; ++out_edge_it)
{
Vertex child_vertex = target(*out_edge_it, graph_);
unsigned child_id = vertexToName[child_vertex];
if (child_id <= first_id
|| edge_to_parid[*out_edge_it] != CONTROL_EDGE)
continue;
if (!doesEdgeExist(first_id, child_id))
to_add_edges.push_back({first_id, child_id, 1});
}
}
//update first_id's parents, dependence become strict control dependence
in_edge_iter in_edge_it, in_edge_end;
for (tie(in_edge_it, in_edge_end) = in_edges(nameToVertex[first_id], graph_); in_edge_it != in_edge_end; ++in_edge_it)
{
Vertex parent_vertex = source(*in_edge_it, graph_);
unsigned parent_id = vertexToName[parent_vertex];
if (is_branch_op(microop.at(parent_id)))
continue;
to_remove_edges.insert(*in_edge_it);
to_add_edges.push_back({parent_id, first_id, CONTROL_EDGE});
}
//remove control dependence between br node to its children
out_edge_iter out_edge_it, out_edge_end;
for (tie(out_edge_it, out_edge_end) = out_edges(nameToVertex[br_node], graph_); out_edge_it != out_edge_end; ++out_edge_it) {
if (is_call_op(microop.at(vertexToName[target(*out_edge_it, graph_)])))
continue;
if (edge_to_parid[*out_edge_it] != CONTROL_EDGE)
continue;
to_remove_edges.insert(*out_edge_it);
}
prev_branch = br_node;
prev_first = first_id;
}
updateGraphWithIsolatedEdges(to_remove_edges);
updateGraphWithNewEdges(to_add_edges);
cleanLeafNodes();
}
/*
* Read: graph_, lineNum.gz, unrollingConfig, microop
* Modify: graph_
* Write: loop_bound
*/
void BaseDatapath::loopUnrolling()
{
std::unordered_map<int, int > unrolling_config;
readUnrollingConfig(unrolling_config);
std::cerr << "-------------------------------" << std::endl;
std::cerr << " Loop Unrolling " << std::endl;
std::cerr << "-------------------------------" << std::endl;
std::vector<unsigned> to_remove_nodes;
std::unordered_map<std::string, unsigned> inst_dynamic_counts;
std::vector<unsigned> nodes_between;
std::vector<newEdge> to_add_edges;
std::vector<int> lineNum(numTotalNodes, -1);
initLineNum(lineNum);
bool first = false;
int iter_counts = 0;
int prev_branch = -1;
for(unsigned node_id = 0; node_id < numTotalNodes; node_id++)
{
if (nameToVertex.find(node_id) == nameToVertex.end())
continue;
Vertex node_vertex = nameToVertex[node_id];
if (boost::degree(node_vertex, graph_) == 0
&& !is_call_op(microop.at(node_id)))
continue;
if (!first)
{
first = true;
loopBound.push_back(node_id);
prev_branch = node_id;
}
assert(prev_branch != -1);
if (prev_branch != node_id &&
!(is_dma_op(microop.at(prev_branch)) && is_dma_op(microop.at(node_id))) ) {
to_add_edges.push_back({(unsigned)prev_branch, node_id, CONTROL_EDGE});
}
if (!is_branch_op(microop.at(node_id)))
nodes_between.push_back(node_id);
else
{
//for the case that the first non-isolated node is also a call node;
if (is_call_op(microop.at(node_id)) && *loopBound.rbegin() != node_id)
{
loopBound.push_back(node_id);
prev_branch = node_id;
}
int node_linenum = lineNum.at(node_id);
auto unroll_it = unrolling_config.find(node_linenum);
//not unrolling branch
if (unroll_it == unrolling_config.end())
{
if (!is_call_op(microop.at(node_id))) {
nodes_between.push_back(node_id);
continue;
}
// Enforce dependences between branch nodes, including call nodes
// Except for the case that both two branches are DMA operations.
// (Two DMA operations can go in parallel.)
if (!doesEdgeExist(prev_branch, node_id) &&
!( is_dma_op(microop.at(prev_branch)) &&
is_dma_op(microop.at(node_id)) ) )
to_add_edges.push_back({(unsigned)prev_branch, node_id, CONTROL_EDGE});
for (auto prev_node_it = nodes_between.begin(), E = nodes_between.end();
prev_node_it != E; prev_node_it++)
{
if (!doesEdgeExist(*prev_node_it, node_id) &&
!( is_dma_op(microop.at(*prev_node_it)) &&
is_dma_op(microop.at(node_id)) ) ) {
to_add_edges.push_back({*prev_node_it, node_id, CONTROL_EDGE});
}
}
nodes_between.clear();
nodes_between.push_back(node_id);
prev_branch = node_id;
}
else
{
int factor = unroll_it->second;
int node_microop = microop.at(node_id);
char unique_inst_id[256];
sprintf(unique_inst_id, "%d-%d", node_microop, node_linenum);
auto it = inst_dynamic_counts.find(unique_inst_id);
if (it == inst_dynamic_counts.end())
{
inst_dynamic_counts[unique_inst_id] = 1;
it = inst_dynamic_counts.find(unique_inst_id);
}
else
it->second++;
if (it->second % factor == 0)
{
loopBound.push_back(node_id);
iter_counts++;
for (auto prev_node_it = nodes_between.begin(), E = nodes_between.end();
prev_node_it != E; prev_node_it++)
{
if (!doesEdgeExist(*prev_node_it, node_id)) {
to_add_edges.push_back({*prev_node_it, node_id, CONTROL_EDGE});
}
}
nodes_between.clear();
nodes_between.push_back(node_id);
prev_branch = node_id;
}
else
to_remove_nodes.push_back(node_id);
}
}
}
loopBound.push_back(numTotalNodes);
if (iter_counts == 0 && unrolling_config.size() != 0 )
{
std::cerr << "-------------------------------" << std::endl;
std::cerr << "Loop Unrolling Factor is Larger than the Loop Trip Count."
<< std::endl;
std::cerr << "Loop Unrolling is NOT applied. Please choose a smaller "
<< "unrolling factor." << std::endl;
std::cerr << "-------------------------------" << std::endl;
}
updateGraphWithNewEdges(to_add_edges);
updateGraphWithIsolatedNodes(to_remove_nodes);
cleanLeafNodes();
}
/*
* Read: loop_bound, flattenConfig, graph, actualAddress, microop
* Modify: graph_
*/
void BaseDatapath::removeSharedLoads()
{
std::unordered_set<int> flatten_config;
if (!readFlattenConfig(flatten_config)&& loopBound.size() <= 2)
return;
std::cerr << "-------------------------------" << std::endl;
std::cerr << " Load Buffer " << std::endl;
std::cerr << "-------------------------------" << std::endl;
EdgeNameMap edge_to_parid = get(boost::edge_name, graph_);
std::unordered_map<unsigned, long long int> address;
initAddress(address);
vertex_iter vi, vi_end;
std::set<Edge> to_remove_edges;
std::vector<newEdge> to_add_edges;
int shared_loads = 0;
auto bound_it = loopBound.begin();
unsigned node_id = 0;
while ( (unsigned)node_id < numTotalNodes)
{
std::unordered_map<unsigned, unsigned> address_loaded;
while (node_id < *bound_it && (unsigned) node_id < numTotalNodes)
{
if (nameToVertex.find(node_id) == nameToVertex.end())
{
node_id++;
continue;
}
if (boost::degree(nameToVertex[node_id], graph_) == 0)
{
node_id++;
continue;
}
int node_microop = microop.at(node_id);
long long int node_address = address[node_id];
auto addr_it = address_loaded.find(node_address);
if (is_store_op(node_microop) && addr_it != address_loaded.end())
address_loaded.erase(addr_it);
else if (is_load_op(node_microop))
{
if (addr_it == address_loaded.end())
address_loaded[node_address] = node_id;
else
{
shared_loads++;
microop.at(node_id) = LLVM_IR_Move;
unsigned prev_load = addr_it->second;
//iterate through its children
Vertex load_node = nameToVertex[node_id];
out_edge_iter out_edge_it, out_edge_end;
for (tie(out_edge_it, out_edge_end) = out_edges(load_node, graph_); out_edge_it != out_edge_end; ++out_edge_it)
{
Edge curr_edge = *out_edge_it;
Vertex child_vertex = target(curr_edge, graph_);
unsigned child_id = vertexToName[child_vertex];
Vertex prev_load_vertex = nameToVertex[prev_load];
if (!doesEdgeExistVertex(prev_load_vertex, child_vertex))
to_add_edges.push_back({prev_load, child_id, edge_to_parid[curr_edge]});
to_remove_edges.insert(*out_edge_it);
}
in_edge_iter in_edge_it, in_edge_end;
for (tie(in_edge_it, in_edge_end) = in_edges(load_node, graph_); in_edge_it != in_edge_end; ++in_edge_it)
to_remove_edges.insert(*in_edge_it);
}
}
node_id++;
}
bound_it++;
if (bound_it == loopBound.end() )
break;
}
updateGraphWithIsolatedEdges(to_remove_edges);
updateGraphWithNewEdges(to_add_edges);
cleanLeafNodes();
}
/*
* Read: loopBound, flattenConfig, graph_, instid, dynamicMethodID,
* prevBasicBlock
* Modify: graph_
*/
void BaseDatapath::storeBuffer()
{
if (loopBound.size() <= 2)
return;
std::cerr << "-------------------------------" << std::endl;
std::cerr << " Store Buffer " << std::endl;
std::cerr << "-------------------------------" << std::endl;
EdgeNameMap edge_to_parid = get(boost::edge_name, graph_);
std::vector<std::string> instid(numTotalNodes, "");
std::vector<std::string> dynamic_methodid(numTotalNodes, "");
std::vector<std::string> prev_basic_block(numTotalNodes, "");
initInstID(instid);
initDynamicMethodID(dynamic_methodid);
initPrevBasicBlock(prev_basic_block);
std::vector<newEdge> to_add_edges;
std::vector<unsigned> to_remove_nodes;
auto bound_it = loopBound.begin();
unsigned node_id = 0;
while (node_id < numTotalNodes)
{
while (node_id < *bound_it && node_id < numTotalNodes)
{
if (nameToVertex.find(node_id) == nameToVertex.end()
|| boost::degree(nameToVertex[node_id], graph_) == 0)
{
++node_id;
continue;
}
if (is_store_op(microop.at(node_id)))
{
//remove this store
std::string store_unique_id (dynamic_methodid.at(node_id) + "-" + instid.at(node_id) + "-" + prev_basic_block.at(node_id));
//dynamic stores, cannot disambiguated in the static time, cannot remove
if (dynamicMemoryOps.find(store_unique_id) != dynamicMemoryOps.end()) {
++node_id;
continue;
}
Vertex node = nameToVertex[node_id];
out_edge_iter out_edge_it, out_edge_end;
std::vector<Vertex> store_child;
for (tie(out_edge_it, out_edge_end) = out_edges(node, graph_);
out_edge_it != out_edge_end; ++out_edge_it)
{
Vertex child_vertex = target(*out_edge_it, graph_);
int child_id = vertexToName[child_vertex];
if (is_load_op(microop.at(child_id)))
{
std::string load_unique_id (dynamic_methodid.at(child_id) + "-"
+ instid.at(child_id) + "-" + prev_basic_block.at(child_id));
if (dynamicMemoryOps.find(load_unique_id) != dynamicMemoryOps.end()
|| child_id >= (unsigned)*bound_it )
continue;
else
store_child.push_back(child_vertex);
}
}
if (store_child.size() > 0)
{
bool parent_found = false;
Vertex store_parent;
in_edge_iter in_edge_it, in_edge_end;
for (tie(in_edge_it, in_edge_end) = in_edges(node, graph_);
in_edge_it != in_edge_end; ++in_edge_it)
{
//parent node that generates value
if (edge_to_parid[*in_edge_it] == 1)
{
parent_found = true;
store_parent = source(*in_edge_it, graph_);
break;
}
}
if (parent_found)
{
for (auto load_it = store_child.begin(), E = store_child.end();
load_it != E; ++load_it)
{
Vertex load_node = *load_it;
to_remove_nodes.push_back(vertexToName[load_node]);
out_edge_iter out_edge_it, out_edge_end;
for (tie(out_edge_it, out_edge_end) = out_edges(load_node, graph_);
out_edge_it != out_edge_end; ++out_edge_it)
to_add_edges.push_back({(unsigned)vertexToName[store_parent],
(unsigned)vertexToName[target(*out_edge_it, graph_)],
edge_to_parid[*out_edge_it]});
}
}
}
}
++node_id;
}
++bound_it;
if (bound_it == loopBound.end() )
break;
}
updateGraphWithNewEdges(to_add_edges);
updateGraphWithIsolatedNodes(to_remove_nodes);
cleanLeafNodes();
}
/*
* Read: loopBound, flattenConfig, graph_, address, instid, dynamicMethodID,
* prevBasicBlock
* Modify: graph_
*/
void BaseDatapath::removeRepeatedStores()
{
std::unordered_set<int> flatten_config;
if (!readFlattenConfig(flatten_config)&& loopBound.size() <= 2)
return;
std::cerr << "-------------------------------" << std::endl;
std::cerr << " Remove Repeated Store " << std::endl;
std::cerr << "-------------------------------" << std::endl;
std::unordered_map<unsigned, long long int> address;
initAddress(address);
std::vector<std::string> instid(numTotalNodes, "");
std::vector<std::string> dynamic_methodid(numTotalNodes, "");
std::vector<std::string> prev_basic_block(numTotalNodes, "");
initInstID(instid);
initDynamicMethodID(dynamic_methodid);
initPrevBasicBlock(prev_basic_block);
int shared_stores = 0;
int node_id = numTotalNodes - 1;
auto bound_it = loopBound.end();
bound_it--;
bound_it--;
while (node_id >=0 ) {
unordered_map<unsigned, int> address_store_map;
while (node_id >= *bound_it && node_id >= 0) {
if (nameToVertex.find(node_id) == nameToVertex.end()
|| boost::degree(nameToVertex[node_id], graph_) == 0
|| !is_store_op(microop.at(node_id))) {
--node_id;
continue;
}
long long int node_address = address[node_id];
auto addr_it = address_store_map.find(node_address);
if (addr_it == address_store_map.end())
address_store_map[node_address] = node_id;
else {
//remove this store
std::string store_unique_id (dynamic_methodid.at(node_id) + "-" + instid.at(node_id) + "-" + prev_basic_block.at(node_id));
//dynamic stores, cannot disambiguated in the run time, cannot remove
if (dynamicMemoryOps.find(store_unique_id) == dynamicMemoryOps.end()
&& boost::out_degree(nameToVertex[node_id], graph_)== 0) {
microop.at(node_id) = LLVM_IR_SilentStore;
shared_stores++;
}
}
--node_id;
}
if (--bound_it == loopBound.begin())
break;
}
cleanLeafNodes();
}
/*
* Read: loopBound, flattenConfig, graph_, microop
* Modify: graph_
*/
void BaseDatapath::treeHeightReduction()
{
if (loopBound.size() <= 2)
return;
std::cerr << "-------------------------------" << std::endl;
std::cerr << " Tree Height Reduction " << std::endl;
std::cerr << "-------------------------------" << std::endl;
EdgeNameMap edge_to_parid = get(boost::edge_name, graph_);
std::vector<bool> updated(numTotalNodes, 0);
std::vector<int> bound_region(numTotalNodes, 0);
int region_id = 0;
unsigned node_id = 0;
auto bound_it = loopBound.begin();
while (node_id < *bound_it)
{
bound_region.at(node_id) = region_id;
node_id++;
if (node_id == *bound_it)
{
region_id++;
bound_it++;
if (bound_it == loopBound.end())
break;
}
}
std::set<Edge> to_remove_edges;
std::vector<newEdge> to_add_edges;
//nodes with no outgoing edges to first (bottom nodes first)
for(int node_id = numTotalNodes -1; node_id >= 0; node_id--)
{
if (nameToVertex.find(node_id) == nameToVertex.end()
|| boost::degree(nameToVertex[node_id], graph_) == 0
|| updated.at(node_id)
|| !is_associative(microop.at(node_id)) )
continue;
updated.at(node_id) = 1;
int node_region = bound_region.at(node_id);
std::list<unsigned> nodes;
std::vector<Edge> tmp_remove_edges;
std::vector<pair<int, bool> > leaves;
std::vector<int> associative_chain;
associative_chain.push_back(node_id);
int chain_id = 0;
while (chain_id < associative_chain.size())
{
int chain_node_id = associative_chain.at(chain_id);
int chain_node_microop = microop.at(chain_node_id);
if (is_associative(chain_node_microop))
{
updated.at(chain_node_id) = 1;
int num_of_chain_parents = 0;
in_edge_iter in_edge_it, in_edge_end;
for (tie(in_edge_it, in_edge_end) = in_edges(nameToVertex[chain_node_id] , graph_); in_edge_it != in_edge_end; ++in_edge_it)
{
int parent_id = vertexToName[source(*in_edge_it, graph_)];
if (is_branch_op(microop.at(parent_id)))
continue;
num_of_chain_parents++;
}
if (num_of_chain_parents == 2)
{
nodes.push_front(chain_node_id);
for (tie(in_edge_it, in_edge_end) = in_edges(nameToVertex[chain_node_id] , graph_); in_edge_it != in_edge_end; ++in_edge_it)
{
Vertex parent_node = source(*in_edge_it, graph_);
int parent_id = vertexToName[parent_node];
assert(parent_id < chain_node_id);
int parent_region = bound_region.at(parent_id);
int parent_microop = microop.at(parent_id);
if (is_branch_op(parent_microop))
continue;
Edge curr_edge = *in_edge_it;
tmp_remove_edges.push_back(curr_edge);
if (parent_region == node_region)
{
updated.at(parent_id) = 1;
if (!is_associative(parent_microop))
leaves.push_back(make_pair(parent_id, 0));
else
{
out_edge_iter out_edge_it, out_edge_end;
int num_of_children = 0;
for (tie(out_edge_it, out_edge_end) = out_edges(parent_node, graph_); out_edge_it != out_edge_end; ++out_edge_it) {
if (edge_to_parid[*out_edge_it] != CONTROL_EDGE)
num_of_children++;
}
if (num_of_children == 1)
associative_chain.push_back(parent_id);
else
leaves.push_back(make_pair(parent_id, 0));
}
}
else
leaves.push_back(make_pair(parent_id, 1));
}
}
else
leaves.push_back(make_pair(chain_node_id, 0));
}
else
leaves.push_back(make_pair(chain_node_id, 0));
chain_id++;
}
//build the tree
if (nodes.size() < 3)
continue;
for(auto it = tmp_remove_edges.begin(), E = tmp_remove_edges.end(); it != E; it++)
to_remove_edges.insert(*it);
std::map<unsigned, unsigned> rank_map;
auto leaf_it = leaves.begin();
while (leaf_it != leaves.end())
{
if (leaf_it->second == 0)
rank_map[leaf_it->first] = 0;
else
rank_map[leaf_it->first] = numTotalNodes;
++leaf_it;
}
//reconstruct the rest of the balanced tree
auto node_it = nodes.begin();
while (node_it != nodes.end())
{
unsigned node1, node2;
if (rank_map.size() == 2)
{
node1 = rank_map.begin()->first;
node2 = (++rank_map.begin())->first;
}
else
findMinRankNodes(node1, node2, rank_map);
assert((node1 != numTotalNodes) && (node2 != numTotalNodes));
to_add_edges.push_back({node1, *node_it, 1});
to_add_edges.push_back({node2, *node_it, 1});
//place the new node in the map, remove the two old nodes
rank_map[*node_it] = max(rank_map[node1], rank_map[node2]) + 1;
rank_map.erase(node1);
rank_map.erase(node2);
++node_it;
}
}
updateGraphWithIsolatedEdges(to_remove_edges);
updateGraphWithNewEdges(to_add_edges);
cleanLeafNodes();
}
void BaseDatapath::findMinRankNodes(unsigned &node1, unsigned &node2, std::map<unsigned, unsigned> &rank_map)
{
unsigned min_rank = numTotalNodes;
for (auto it = rank_map.begin(); it != rank_map.end(); ++it)
{
int node_rank = it->second;
if (node_rank < min_rank)
{
node1 = it->first;
min_rank = node_rank;
}
}
min_rank = numTotalNodes;
for (auto it = rank_map.begin(); it != rank_map.end(); ++it)
{
int node_rank = it->second;
if ((it->first != node1) && (node_rank < min_rank))
{
node2 = it->first;
min_rank = node_rank;
}
}
}
void BaseDatapath::updateGraphWithNewEdges(std::vector<newEdge> &to_add_edges)
{
for(auto it = to_add_edges.begin(); it != to_add_edges.end(); ++it)
{
if (it->from != it->to && !doesEdgeExist(it->from, it->to))
get(boost::edge_name, graph_)[add_edge(it->from, it->to, graph_).first] = it->parid;
}
}
void BaseDatapath::updateGraphWithIsolatedNodes(std::vector<unsigned> &to_remove_nodes)
{
for(auto it = to_remove_nodes.begin(); it != to_remove_nodes.end(); ++it)
clear_vertex(nameToVertex[*it], graph_);
}
void BaseDatapath::updateGraphWithIsolatedEdges(std::set<Edge> &to_remove_edges)
{
for (auto it = to_remove_edges.begin(), E = to_remove_edges.end(); it!=E; ++it)
remove_edge(*it, graph_);
}
/*
* Write per cycle activity to bench_stats. The format is:
* cycle_num,num-of-muls,num-of-adds,num-of-bitwise-ops,num-of-reg-reads,num-of-reg-writes
* If it is called from ScratchpadDatapath, it also outputs per cycle memory
* activity for each partitioned array.
*/
void BaseDatapath::writePerCycleActivity()
{
std::string bn(benchName);
activity_map mul_activity, add_activity, bit_activity;
activity_map ld_activity, st_activity;
max_activity_map max_mul_per_function;
max_activity_map max_add_per_function;
max_activity_map max_bit_per_function;
std::vector<std::string> comp_partition_names;
std::vector<std::string> mem_partition_names;
registers.getRegisterNames(comp_partition_names);
getMemoryBlocks(mem_partition_names);
initPerCycleActivity(comp_partition_names, mem_partition_names,
ld_activity, st_activity,
mul_activity, add_activity, bit_activity,
max_mul_per_function, max_add_per_function,
max_bit_per_function,
num_cycles);
updatePerCycleActivity(ld_activity, st_activity,
mul_activity, add_activity, bit_activity,
max_mul_per_function, max_add_per_function,
max_bit_per_function);
outputPerCycleActivity(comp_partition_names, mem_partition_names,
ld_activity, st_activity,
mul_activity, add_activity, bit_activity,
max_mul_per_function, max_add_per_function,
max_bit_per_function);
}
void BaseDatapath::initPerCycleActivity(
std::vector<std::string> &comp_partition_names,
std::vector<std::string> &mem_partition_names,
activity_map &ld_activity, activity_map &st_activity,
activity_map &mul_activity, activity_map &add_activity,
activity_map &bit_activity,
max_activity_map &max_mul_per_function,
max_activity_map &max_add_per_function,
max_activity_map &max_bit_per_function,
int num_cycles)
{
for (auto it = comp_partition_names.begin(); it != comp_partition_names.end() ; ++it)
{
ld_activity.insert({*it, make_vector(num_cycles)});
st_activity.insert({*it, make_vector(num_cycles)});
}
for (auto it = mem_partition_names.begin(); it != mem_partition_names.end() ; ++it)
{
ld_activity.insert({*it, make_vector(num_cycles)});
st_activity.insert({*it, make_vector(num_cycles)});
}
for (auto it = functionNames.begin(); it != functionNames.end() ; ++it)
{
mul_activity.insert({*it, make_vector(num_cycles)});
add_activity.insert({*it, make_vector(num_cycles)});
bit_activity.insert({*it, make_vector(num_cycles)});
max_mul_per_function.insert({*it, 0});
max_add_per_function.insert({*it, 0});
max_bit_per_function.insert({*it, 0});
}
}
void BaseDatapath::updatePerCycleActivity(
activity_map &ld_activity, activity_map &st_activity,
activity_map &mul_activity, activity_map &add_activity,
activity_map &bit_activity,
max_activity_map &max_mul_per_function,
max_activity_map &max_add_per_function,
max_activity_map &max_bit_per_function)
{
/*We use two ways to count the number of functional units in accelerators: one
* assumes that functional units can be reused in the same region; the other
* assumes no reuse of functional units. The advantage of reusing is that it
* elimates the cost of duplicating functional units which can lead to high
* leakage power and area. However, additional wires and muxes may need to be
* added for reusing.
* In the current model, we assume that multipliers can be reused, since the
* leakage power and area of multipliers are relatively significant, and no
* reuse for adders. This way of modeling is consistent with our observation
* of accelerators generated with Vivado.*/
std::vector<std::string> dynamic_methodid(numTotalNodes, "");
initDynamicMethodID(dynamic_methodid);
int num_adds_so_far = 0, num_bits_so_far = 0;
auto bound_it = loopBound.begin();
for(unsigned node_id = 0; node_id < numTotalNodes; ++node_id)
{
char func_id[256];
int count;
sscanf(dynamic_methodid.at(node_id).c_str(), "%[^-]-%d\n", func_id, &count);
if (node_id == *bound_it) {
if (max_add_per_function[func_id] < num_adds_so_far)
max_add_per_function[func_id] = num_adds_so_far;
if (max_bit_per_function[func_id] < num_bits_so_far)
max_bit_per_function[func_id] = num_bits_so_far;
num_adds_so_far = 0;
num_bits_so_far = 0;
bound_it++;
}
if (finalIsolated.at(node_id))
continue;
int node_level = newLevel.at(node_id);
int node_microop = microop.at(node_id);
if (is_mul_op(node_microop))
mul_activity[func_id].at(node_level) +=1;
else if (is_add_op(node_microop)) {
add_activity[func_id].at(node_level) +=1;
num_adds_so_far +=1;
}
else if (is_bit_op(node_microop)) {
bit_activity[func_id].at(node_level) +=1;
num_bits_so_far +=1;
}
else if (is_load_op(node_microop)) {
std::string base_addr = baseAddress[node_id].first;
if (ld_activity.find(base_addr) != ld_activity.end())
ld_activity[base_addr].at(node_level) += 1;
}
else if (is_store_op(node_microop)) {
std::string base_addr = baseAddress[node_id].first;
if (st_activity.find(base_addr) != st_activity.end())
st_activity[base_addr].at(node_level) += 1;
}
}
for (auto it = functionNames.begin(); it != functionNames.end() ; ++it)
max_mul_per_function[*it] = *(std::max_element(mul_activity[*it].begin(),
mul_activity[*it].end()));
}
void BaseDatapath::outputPerCycleActivity(
std::vector<std::string> &comp_partition_names,
std::vector<std::string> &mem_partition_names,
activity_map &ld_activity, activity_map &st_activity,
activity_map &mul_activity, activity_map &add_activity,
activity_map &bit_activity,
max_activity_map &max_mul_per_function,
max_activity_map &max_add_per_function,
max_activity_map &max_bit_per_function)
{
ofstream stats, power_stats;
std::string bn(benchName);
std::string file_name = bn + "_stats";
stats.open(file_name.c_str());
file_name += "_power";
power_stats.open(file_name.c_str());
stats << "cycles," << num_cycles << "," << numTotalNodes << std::endl;
power_stats << "cycles," << num_cycles << "," << numTotalNodes << std::endl;
stats << num_cycles << "," ;
power_stats << num_cycles << "," ;
/*Start writing the second line*/
for (auto it = functionNames.begin(); it != functionNames.end() ; ++it)
{
stats << *it << "-mul," << *it << "-add," << *it << "-bit,";
power_stats << *it << "-mul," << *it << "-add," << *it << "-bit,";
}
stats << "reg,";
power_stats << "reg,";
for (auto it = mem_partition_names.begin();
it != mem_partition_names.end() ; ++it) {
stats << *it << "-read," << *it << "-write,";
}
stats << std::endl;
power_stats << std::endl;
/*Finish writing the second line*/
/*Caculating the number of FUs and leakage power*/
int max_reg_read = 0, max_reg_write = 0;
for (unsigned level_id = 0; ((int) level_id) < num_cycles; ++level_id)
{
if (max_reg_read < regStats.at(level_id).reads )
max_reg_read = regStats.at(level_id).reads ;
if (max_reg_write < regStats.at(level_id).writes )
max_reg_write = regStats.at(level_id).writes ;
}
int max_reg = max_reg_read + max_reg_write;
int max_add = 0, max_bit = 0, max_mul = 0;
for (auto it = functionNames.begin(); it != functionNames.end() ; ++it)
{
max_bit += max_bit_per_function[*it];
max_add += max_add_per_function[*it];
max_mul += max_mul_per_function[*it];
}
float add_leakage_power = ADD_leak_power * max_add;
float mul_leakage_power = MUL_leak_power * max_mul;
float reg_leakage_power = registers.getTotalLeakagePower()
+ REG_leak_power * 32 * max_reg;
float fu_leakage_power = mul_leakage_power
+ add_leakage_power
+ reg_leakage_power;
/*Finish caculating the number of FUs and leakage power*/
float fu_dynamic_energy = 0;
/*Start writing per cycle activity */
for (unsigned curr_level = 0; ((int)curr_level) < num_cycles ; ++curr_level)
{
stats << curr_level << "," ;
power_stats << curr_level << ",";
//For FUs
for (auto it = functionNames.begin(); it != functionNames.end() ; ++it)
{
float curr_mul_dynamic_power = (MUL_switch_power + MUL_int_power)
* mul_activity[*it].at(curr_level);
float curr_add_dynamic_power = (ADD_switch_power + ADD_int_power)
* add_activity[*it].at(curr_level);
fu_dynamic_energy += ( curr_mul_dynamic_power + curr_add_dynamic_power )
* cycleTime;
stats << mul_activity[*it].at(curr_level) << ","
<< add_activity[*it].at(curr_level) << ","
<< bit_activity[*it].at(curr_level) << ",";
power_stats << curr_mul_dynamic_power + mul_leakage_power << ","
<< curr_add_dynamic_power + add_leakage_power << ","
<< "0," ;
}
//For regs
int curr_reg_reads = regStats.at(curr_level).reads;
int curr_reg_writes = regStats.at(curr_level).writes;
float curr_reg_dynamic_energy = (REG_int_power + REG_sw_power)
*(curr_reg_reads + curr_reg_writes)
* 32 * cycleTime;
for (auto it = comp_partition_names.begin();
it != comp_partition_names.end() ; ++it)
{
curr_reg_reads += ld_activity.at(*it).at(curr_level);
curr_reg_writes += st_activity.at(*it).at(curr_level);
curr_reg_dynamic_energy += registers.getReadEnergy(*it)
* ld_activity.at(*it).at(curr_level)
+ registers.getWriteEnergy(*it)
* st_activity.at(*it).at(curr_level);
}
fu_dynamic_energy += curr_reg_dynamic_energy;
stats << curr_reg_reads << "," << curr_reg_writes << "," ;
power_stats << curr_reg_dynamic_energy / cycleTime + reg_leakage_power;
for (auto it = mem_partition_names.begin();
it != mem_partition_names.end() ; ++it)
stats << ld_activity.at(*it).at(curr_level) << ","
<< st_activity.at(*it).at(curr_level) << ",";
stats << std::endl;
power_stats << std::endl;
}
stats.close();
power_stats.close();
float avg_mem_power =0, avg_mem_dynamic_power = 0, mem_leakage_power = 0;
getAverageMemPower(num_cycles, &avg_mem_power,
&avg_mem_dynamic_power, &mem_leakage_power);
float avg_fu_dynamic_power = fu_dynamic_energy / (cycleTime * num_cycles);
float avg_fu_power = avg_fu_dynamic_power + fu_leakage_power;
float avg_power = avg_fu_power + avg_mem_power;
float mem_area = getTotalMemArea();
unsigned mem_size = getTotalMemSize();
float fu_area = registers.getTotalArea()
+ ADD_area * max_add
+ MUL_area * max_mul
+ REG_area * 32 * max_reg;
float total_area = mem_area + fu_area;
//Summary output:
//Cycle, Avg Power, Avg FU Power, Avg MEM Power, Total Area, FU Area, MEM Area
std::cerr << "===============================" << std::endl;
std::cerr << " Aladdin Results " << std::endl;
std::cerr << "===============================" << std::endl;
std::cerr << "Running : " << benchName << std::endl;
std::cerr << "Cycle : " << num_cycles << " cycles" << std::endl;
std::cerr << "Avg Power: " << avg_power << " mW" << std::endl;
std::cerr << "Avg FU Power: " << avg_fu_power << " mW" << std::endl;
std::cerr << "Avg FU Dynamic Power: " << avg_fu_dynamic_power << " mW" << std::endl;
std::cerr << "Avg FU leakage Power: " << fu_leakage_power << " mW" << std::endl;
std::cerr << "Avg SRAM Power: " << avg_mem_power << " mW" << std::endl;
std::cerr << "Avg SRAM Dynamic Power: " << avg_mem_dynamic_power << " mW" << std::endl;
std::cerr << "Avg SRAM Leakage Power: " << mem_leakage_power << " mW" << std::endl;
std::cerr << "Total Area: " << total_area << " uM^2" << std::endl;
std::cerr << "FU Area: " << fu_area << " uM^2" << std::endl;
std::cerr << "SRAM Area: " << mem_area << " uM^2" << std::endl;
std::cerr << "SRAM size: " << mem_size / 1024 << " KB" << std::endl;
std::cerr << "Num of Multipliers (32-bit): " << max_mul << std::endl;
std::cerr << "Num of Adders (32-bit): " << max_add << std::endl;
std::cerr << "===============================" << std::endl;
std::cerr << " Aladdin Results " << std::endl;
std::cerr << "===============================" << std::endl;
ofstream summary;
file_name = bn + "_summary";
summary.open(file_name.c_str());
summary << "===============================" << std::endl;
summary << " Aladdin Results " << std::endl;
summary << "===============================" << std::endl;
summary << "Running : " << benchName << std::endl;
summary << "Cycle : " << num_cycles << " cycles" << std::endl;
summary << "Avg Power: " << avg_power << " mW" << std::endl;
summary << "Avg FU Power: " << avg_fu_power << " mW" << std::endl;
summary << "Avg FU Dynamic Power: " << avg_fu_dynamic_power << " mW" << std::endl;
summary << "Avg FU leakage Power: " << fu_leakage_power << " mW" << std::endl;
summary << "Avg SRAM Power: " << avg_mem_power << " mW" << std::endl;
summary << "Avg SRAM Dynamic Power: " << avg_mem_dynamic_power << " mW" << std::endl;
summary << "Avg SRAM Leakage Power: " << mem_leakage_power << " mW" << std::endl;
summary << "Total Area: " << total_area << " uM^2" << std::endl;
summary << "FU Area: " << fu_area << " uM^2" << std::endl;
summary << "SRAM Area: " << mem_area << " uM^2" << std::endl;
summary << "SRAM size: " << mem_size << " B" << std::endl;
summary << "Num of Multipliers (32-bit): " << max_mul << std::endl;
summary << "Num of Adders (32-bit): " << max_add << std::endl;
summary << "===============================" << std::endl;
summary << " Aladdin Results " << std::endl;
summary << "===============================" << std::endl;
summary.close();
}
void BaseDatapath::writeGlobalIsolated()
{
std::string file_name(benchName);
file_name += "_isolated.gz";
write_gzip_bool_file(file_name, finalIsolated.size(), finalIsolated);
}
void BaseDatapath::writeBaseAddress()
{
ostringstream file_name;
file_name << benchName << "_baseAddr.gz";
gzFile gzip_file;
gzip_file = gzopen(file_name.str().c_str(), "w");
for (auto it = baseAddress.begin(), E = baseAddress.end(); it != E; ++it)
gzprintf(gzip_file, "node:%u,part:%s,base:%lld\n", it->first, it->second.first.c_str(), it->second.second);
gzclose(gzip_file);
}
void BaseDatapath::writeFinalLevel()
{
std::string file_name(benchName);
file_name += "_level.gz";
write_gzip_file(file_name, newLevel.size(), newLevel);
}
void BaseDatapath::writeMicroop(std::vector<int> µop)
{
std::string file_name(benchName);
file_name += "_microop.gz";
write_gzip_file(file_name, microop.size(), microop);
}
void BaseDatapath::initPrevBasicBlock(std::vector<std::string> &prevBasicBlock)
{
std::string file_name(benchName);
file_name += "_prevBasicBlock.gz";
read_gzip_string_file(file_name, prevBasicBlock.size(), prevBasicBlock);
}
void BaseDatapath::initDynamicMethodID(std::vector<std::string> &methodid)
{
std::string file_name(benchName);
file_name += "_dynamic_funcid.gz";
read_gzip_string_file(file_name, methodid.size(), methodid);
}
void BaseDatapath::initMethodID(std::vector<int> &methodid)
{
std::string file_name(benchName);
file_name += "_methodid.gz";
read_gzip_file(file_name, methodid.size(), methodid);
}
void BaseDatapath::initInstID(std::vector<std::string> &instid)
{
std::string file_name(benchName);
file_name += "_instid.gz";
read_gzip_string_file(file_name, instid.size(), instid);
}
void BaseDatapath::initAddress(std::unordered_map<unsigned, long long int> &address)
{
std::string file_name(benchName);
file_name += "_memaddr.gz";
gzFile gzip_file;
gzip_file = gzopen(file_name.c_str(), "r");
while (!gzeof(gzip_file))
{
char buffer[256];
if (gzgets(gzip_file, buffer, 256) == NULL)
break;
unsigned node_id, size;
long long int addr;
sscanf(buffer, "%d,%lld,%d\n", &node_id, &addr, &size);
address[node_id] = addr;
}
gzclose(gzip_file);
}
void BaseDatapath::initAddressAndSize(std::unordered_map<unsigned, pair<long long int, unsigned> > &address)
{
std::string file_name(benchName);
file_name += "_memaddr.gz";
gzFile gzip_file;
gzip_file = gzopen(file_name.c_str(), "r");
while (!gzeof(gzip_file))
{
char buffer[256];
if (gzgets(gzip_file, buffer, 256) == NULL)
break;
unsigned node_id, size;
long long int addr;
sscanf(buffer, "%d,%lld,%d\n", &node_id, &addr, &size);
address[node_id] = make_pair(addr, size);
}
gzclose(gzip_file);
}
void BaseDatapath::initLineNum(std::vector<int> &line_num)
{
ostringstream file_name;
file_name << benchName << "_linenum.gz";
read_gzip_file(file_name.str(), line_num.size(), line_num);
}
void BaseDatapath::initGetElementPtr(std::unordered_map<unsigned, pair<std::string, long long int> > &get_element_ptr)
{
ostringstream file_name;
file_name << benchName << "_getElementPtr.gz";
gzFile gzip_file;
gzip_file = gzopen(file_name.str().c_str(), "r");
while (!gzeof(gzip_file))
{
char buffer[256];
if (gzgets(gzip_file, buffer, 256) == NULL)
break;
unsigned node_id;
long long int address;
char label[256];
sscanf(buffer, "%d,%[^,],%lld\n", &node_id, label, &address);
get_element_ptr[node_id] = make_pair(label, address);
}
gzclose(gzip_file);
}
//stepFunctions
//multiple function, each function is a separate graph
void BaseDatapath::setGraphForStepping()
{
std::cerr << "=============================================" << std::endl;
std::cerr << " Scheduling... " << benchName << std::endl;
std::cerr << "=============================================" << std::endl;
newLevel.assign(numTotalNodes, 0);
edgeToParid = get(boost::edge_name, graph_);
numTotalEdges = boost::num_edges(graph_);
numParents.assign(numTotalNodes, 0);
latestParents.assign(numTotalNodes, 0);
executedNodes = 0;
totalConnectedNodes = 0;
for (unsigned node_id = 0; node_id < numTotalNodes; node_id++)
{
Vertex node = nameToVertex[node_id];
if (boost::degree(node, graph_) != 0 || is_dma_op(microop.at(node_id)))
{
finalIsolated.at(node_id) = 0;
numParents.at(node_id) = boost::in_degree(node, graph_);
totalConnectedNodes++;
}
}
executingQueue.clear();
readyToExecuteQueue.clear();
initExecutingQueue();
}
void BaseDatapath::dumpGraph()
{
std::string bn(benchName);
std::ofstream out(bn + "_graph.dot");
write_graphviz(out, graph_);
}
int BaseDatapath::clearGraph()
{
std::vector< Vertex > topo_nodes;
boost::topological_sort(graph_, std::back_inserter(topo_nodes));
//bottom nodes first
std::vector<int> earliest_child(numTotalNodes, num_cycles);
for (auto vi = topo_nodes.begin(); vi != topo_nodes.end(); ++vi)
{
unsigned node_id = vertexToName[*vi];
if (finalIsolated.at(node_id))
continue;
unsigned node_microop = microop.at(node_id);
if (!is_memory_op(node_microop) && ! is_branch_op(node_microop))
if ((earliest_child.at(node_id) - 1 ) > newLevel.at(node_id))
newLevel.at(node_id) = earliest_child.at(node_id) - 1;
in_edge_iter in_i, in_end;
for (tie(in_i, in_end) = in_edges(*vi , graph_); in_i != in_end; ++in_i)
{
int parent_id = vertexToName[source(*in_i, graph_)];
if (earliest_child.at(parent_id) > newLevel.at(node_id))
earliest_child.at(parent_id) = newLevel.at(node_id);
}
}
updateRegStats();
return num_cycles;
}
void BaseDatapath::updateRegStats()
{
regStats.assign(num_cycles, {0, 0, 0});
for(unsigned node_id = 0; node_id < numTotalNodes; node_id++)
{
if (finalIsolated.at(node_id))
continue;
if (is_control_op(microop.at(node_id)) ||
is_index_op(microop.at(node_id)))
continue;
int node_level = newLevel.at(node_id);
int max_children_level = node_level;
Vertex node = nameToVertex[node_id];
out_edge_iter out_edge_it, out_edge_end;
std::set<int> children_levels;
for (tie(out_edge_it, out_edge_end) = out_edges(node, graph_); out_edge_it != out_edge_end; ++out_edge_it)
{
int child_id = vertexToName[target(*out_edge_it, graph_)];
int child_microop = microop.at(child_id);
if (is_control_op(child_microop))
continue;
if (is_load_op(child_microop))
continue;
int child_level = newLevel.at(child_id);
if (child_level > max_children_level)
max_children_level = child_level;
if (child_level > node_level && child_level != num_cycles - 1)
children_levels.insert(child_level);
}
for (auto it = children_levels.begin(); it != children_levels.end(); it++)
regStats.at(*it).reads++;
if (max_children_level > node_level && node_level != 0 )
regStats.at(node_level).writes++;
}
}
void BaseDatapath::copyToExecutingQueue()
{
auto it = readyToExecuteQueue.begin();
while (it != readyToExecuteQueue.end())
{
executingQueue.push_back(*it);
it = readyToExecuteQueue.erase(it);
}
}
bool BaseDatapath::step()
{
stepExecutingQueue();
copyToExecutingQueue();
num_cycles++;
if (executedNodes == totalConnectedNodes)
return 1;
return 0;
}
// Marks a node as completed and advances the executing queue iterator.
void BaseDatapath::markNodeCompleted(
std::vector<unsigned>::iterator& executingQueuePos,
int& advance_to)
{
unsigned node_id = *executingQueuePos;
executedNodes++;
newLevel.at(node_id) = num_cycles;
executingQueue.erase(executingQueuePos);
updateChildren(node_id);
executingQueuePos = executingQueue.begin();
std::advance(executingQueuePos, advance_to);
}
void BaseDatapath::updateChildren(unsigned node_id)
{
Vertex node = nameToVertex[node_id];
out_edge_iter out_edge_it, out_edge_end;
for (tie(out_edge_it, out_edge_end) = out_edges(node, graph_); out_edge_it != out_edge_end; ++out_edge_it)
{
unsigned child_id = vertexToName[target(*out_edge_it, graph_)];
int edge_parid = edgeToParid[*out_edge_it];
if (numParents[child_id] > 0)
{
numParents[child_id]--;
if (numParents[child_id] == 0)
{
unsigned child_microop = microop.at(child_id);
if ( (node_latency(child_microop) == 0 || node_latency(microop.at(node_id))== 0)
&& edge_parid != CONTROL_EDGE )
executingQueue.push_back(child_id);
else
readyToExecuteQueue.push_back(child_id);
numParents[child_id] = -1;
}
}
}
}
void BaseDatapath::initExecutingQueue()
{
for(unsigned i = 0; i < numTotalNodes; i++)
{
if (numParents[i] == 0 && finalIsolated[i] != 1)
executingQueue.push_back(i);
}
}
int BaseDatapath::shortestDistanceBetweenNodes(unsigned int from, unsigned int to)
{
std::list<pair<unsigned int, unsigned int> > queue;
queue.push_back({from, 0});
while(queue.size() != 0)
{
unsigned int curr_node = queue.front().first;
unsigned int curr_dist = queue.front().second;
out_edge_iter out_edge_it, out_edge_end;
for (tie(out_edge_it, out_edge_end) = out_edges(nameToVertex[curr_node], graph_); out_edge_it != out_edge_end; ++out_edge_it)
{
if (get(boost::edge_name, graph_, *out_edge_it) != CONTROL_EDGE)
{
int child_id = vertexToName[target(*out_edge_it, graph_)];
if (child_id == to)
return curr_dist + 1;
queue.push_back({child_id, curr_dist + 1});
}
}
queue.pop_front();
}
return -1;
}
//readConfigs
bool BaseDatapath::readPipeliningConfig()
{
ifstream config_file;
std::string file_name(benchName);
file_name += "_pipelining_config";
config_file.open(file_name.c_str());
if (!config_file.is_open())
return 0;
std::string wholeline;
getline(config_file, wholeline);
if (wholeline.size() == 0)
return 0;
bool flag = atoi(wholeline.c_str());
return flag;
}
bool BaseDatapath::readUnrollingConfig(std::unordered_map<int, int > &unrolling_config)
{
ifstream config_file;
std::string file_name(benchName);
file_name += "_unrolling_config";
config_file.open(file_name.c_str());
if (!config_file.is_open())
return 0;
while(!config_file.eof())
{
std::string wholeline;
getline(config_file, wholeline);
if (wholeline.size() == 0)
break;
char func[256];
int line_num, factor;
sscanf(wholeline.c_str(), "%[^,],%d,%d\n", func, &line_num, &factor);
unrolling_config[line_num] =factor;
}
config_file.close();
return 1;
}
bool BaseDatapath::readFlattenConfig(std::unordered_set<int> &flatten_config)
{
ifstream config_file;
std::string file_name(benchName);
file_name += "_flatten_config";
config_file.open(file_name.c_str());
if (!config_file.is_open())
return 0;
while(!config_file.eof())
{
std::string wholeline;
getline(config_file, wholeline);
if (wholeline.size() == 0)
break;
char func[256];
int line_num;
sscanf(wholeline.c_str(), "%[^,],%d\n", func, &line_num);
flatten_config.insert(line_num);
}
config_file.close();
return 1;
}
bool BaseDatapath::readCompletePartitionConfig(std::unordered_map<std::string, unsigned> &config)
{
std::string comp_partition_file(benchName);
comp_partition_file += "_complete_partition_config";
if (!fileExists(comp_partition_file))
return 0;
ifstream config_file;
config_file.open(comp_partition_file);
std::string wholeline;
while(!config_file.eof())
{
getline(config_file, wholeline);
if (wholeline.size() == 0)
break;
unsigned size;
char type[256];
char base_addr[256];
sscanf(wholeline.c_str(), "%[^,],%[^,],%d\n", type, base_addr, &size);
config[base_addr] = size;
}
config_file.close();
return 1;
}
bool BaseDatapath::readPartitionConfig(std::unordered_map<std::string, partitionEntry> & partition_config)
{
ifstream config_file;
std::string file_name(benchName);
file_name += "_partition_config";
if (!fileExists(file_name))
return 0;
config_file.open(file_name.c_str());
std::string wholeline;
while (!config_file.eof())
{
getline(config_file, wholeline);
if (wholeline.size() == 0) break;
unsigned size, p_factor, wordsize;
char type[256];
char base_addr[256];
sscanf(wholeline.c_str(), "%[^,],%[^,],%d,%d,%d\n", type, base_addr, &size, &wordsize, &p_factor);
std::string p_type(type);
partition_config[base_addr] = {p_type, size, wordsize, p_factor};
}
config_file.close();
return 1;
}
void BaseDatapath::parse_config(std::string bench, std::string config_file_name)
{
ifstream config_file;
config_file.open(config_file_name);
std::string wholeline;
std::vector<std::string> flatten_config;
std::vector<std::string> unrolling_config;
std::vector<std::string> partition_config;
std::vector<std::string> comp_partition_config;
std::vector<std::string> pipelining_config;
while(!config_file.eof())
{
wholeline.clear();
getline(config_file, wholeline);
if (wholeline.size() == 0)
break;
string type, rest_line;
int pos_end_tag = wholeline.find(",");
if (pos_end_tag == -1)
break;
type = wholeline.substr(0, pos_end_tag);
rest_line = wholeline.substr(pos_end_tag + 1);
if (!type.compare("flatten"))
flatten_config.push_back(rest_line);
else if (!type.compare("unrolling"))
unrolling_config.push_back(rest_line);
else if (!type.compare("partition"))
if (wholeline.find("complete") == std::string::npos)
partition_config.push_back(rest_line);
else
comp_partition_config.push_back(rest_line);
else if (!type.compare("pipelining"))
pipelining_config.push_back(rest_line);
else
{
cerr << "what else? " << wholeline << endl;
exit(0);
}
}
config_file.close();
if (flatten_config.size() != 0)
{
string file_name(bench);
file_name += "_flatten_config";
ofstream output;
output.open(file_name);
for (unsigned i = 0; i < flatten_config.size(); ++i)
output << flatten_config.at(i) << endl;
output.close();
}
if (unrolling_config.size() != 0)
{
string file_name(bench);
file_name += "_unrolling_config";
ofstream output;
output.open(file_name);
for (unsigned i = 0; i < unrolling_config.size(); ++i)
output << unrolling_config.at(i) << endl;
output.close();
}
if (pipelining_config.size() != 0)
{
string pipelining(bench);
pipelining += "_pipelining_config";
ofstream pipe_config;
pipe_config.open(pipelining);
for (unsigned i = 0; i < pipelining_config.size(); ++i)
pipe_config << pipelining_config.at(i) << endl;
pipe_config.close();
}
if (partition_config.size() != 0)
{
string partition(bench);
partition += "_partition_config";
ofstream part_config;
part_config.open(partition);
for (unsigned i = 0; i < partition_config.size(); ++i)
part_config << partition_config.at(i) << endl;
part_config.close();
}
if (comp_partition_config.size() != 0)
{
string complete_partition(bench);
complete_partition += "_complete_partition_config";
ofstream comp_config;
comp_config.open(complete_partition);
for (unsigned i = 0; i < comp_partition_config.size(); ++i)
comp_config << comp_partition_config.at(i) << endl;
comp_config.close();
}
}
/* Tokenizes an input string and returns a vector. */
void BaseDatapath::tokenizeString(std::string input,
std::vector<int>& tokenized_list)
{
using namespace boost;
tokenizer<> tok(input);
for(tokenizer<>::iterator beg = tok.begin(); beg != tok.end(); ++beg)
{
int value;
istringstream(*beg) >> value;
tokenized_list.push_back(value);
}
}
| 34.671488 | 134 | 0.632218 | httsai |
c154237eb5944bd5697f2a8970747486a6764d80 | 595 | cpp | C++ | Programmers/C++/땅따먹기.cpp | sungmen/Solve_Algorithms | 64b3f96a9ce91a91d7eafbd3c27688b0a6dffdeb | [
"MIT"
] | 1 | 2020-07-08T23:16:19.000Z | 2020-07-08T23:16:19.000Z | Programmers/C++/땅따먹기.cpp | sungmen/Solve_Algorithms | 64b3f96a9ce91a91d7eafbd3c27688b0a6dffdeb | [
"MIT"
] | 1 | 2020-05-16T03:12:24.000Z | 2020-05-16T03:14:42.000Z | Programmers/C++/땅따먹기.cpp | sungmen/Solve_Algorithms | 64b3f96a9ce91a91d7eafbd3c27688b0a6dffdeb | [
"MIT"
] | 2 | 2020-05-16T03:25:16.000Z | 2021-02-10T16:51:25.000Z | #include <bits/stdc++.h>
using namespace std;
int solution(vector<vector<int> > land) {
ios_base::sync_with_stdio(false);
for (int i = 1; i < land.size(); i++) {
land[i][0] += max(land[i-1][1], max(land[i-1][2], land[i-1][3]));
land[i][1] += max(land[i-1][0], max(land[i-1][2], land[i-1][3]));
land[i][2] += max(land[i-1][0], max(land[i-1][1], land[i-1][3]));
land[i][3] += max(land[i-1][1], max(land[i-1][2], land[i-1][0]));
}
return max(max(land[land.size()-1][0], land[land.size()-1][1]), max(land[land.size()-1][2], land[land.size()-1][3]));
} | 49.583333 | 121 | 0.52437 | sungmen |
c154c8c082fd784e72327c947fa41f216c04e8bb | 8,153 | hpp | C++ | GPU_version/vio/include/vio/nlls_solver_impl.hpp | Pilot-Labs-Dev/vio_svo | 8274e4269b383e9816fca5c3102b51cd4d1b95ae | [
"MIT"
] | 2 | 2022-03-17T01:12:10.000Z | 2022-03-24T03:17:24.000Z | GPU_version/vio/include/vio/nlls_solver_impl.hpp | Pilot-Labs-Dev/vio_svo | 8274e4269b383e9816fca5c3102b51cd4d1b95ae | [
"MIT"
] | null | null | null | GPU_version/vio/include/vio/nlls_solver_impl.hpp | Pilot-Labs-Dev/vio_svo | 8274e4269b383e9816fca5c3102b51cd4d1b95ae | [
"MIT"
] | 1 | 2022-03-12T11:42:01.000Z | 2022-03-12T11:42:01.000Z | /*
* Abstract Nonlinear Least-Squares Solver Class
*
* nlls_solver.h
*
* Created on: Nov 5, 2012
* Author: cforster
*/
#ifndef LM_SOLVER_IMPL_HPP_
#define LM_SOLVER_IMPL_HPP_
#include <stdexcept>
template <int D, typename T>
void vk::NLLSSolver<D, T>::optimize(ModelType& model)
{
if(method_ == GaussNewton)
optimizeGaussNewton();
else if(method_ == LevenbergMarquardt)
optimizeLevenbergMarquardt(model);
}
template <int D, typename T>
void vk::NLLSSolver<D, T>::optimizeGaussNewton()
{
// Compute weight scale
if(use_weights_)
computeResiduals(false, true);
// perform iterative estimation
for (iter_ = 0; iter_<n_iter_; ++iter_)
{
rho_ = 0;
n_meas_ = 0;
double new_chi2 = computeResiduals(true, false);
// solve the linear system
if(!solve())
{
// matrix was singular and could not be computed
if(verbose_)std::cerr << "Matrix is close to singular! Stop Optimizing." << std::endl;
stop_ = true;
}
// check if error increased since last optimization
if((iter_ > 0 && new_chi2 > chi2_) || stop_)
{
if(verbose_)
{
std::cerr << "It. " << iter_
<< "\t Failure"
<< "\t new_chi2 = " << new_chi2
<< "\t Error increased. Stop optimizing.\n";
}
break;
}
// update the model
update();
chi2_ = new_chi2;
if(verbose_)
{
std::cerr << "It. " << iter_
<< "\t Success"
<< "\t new_chi2 = " << new_chi2
<< "\t x_norm = " << vk::norm_max(x_)<<'\n';
}
// stop when converged, i.e. update step too small
if(vk::norm_max(x_)<=eps_)
break;
}
}
template <int D, typename T>
void vk::NLLSSolver<D, T>::optimizeLevenbergMarquardt(ModelType& model)
{
// Compute weight scale
if(use_weights_)
computeResiduals(model, false, true);
// compute the initial error
chi2_ = computeResiduals(model, true, false);
if(verbose_)
cout << "init chi2 = " << chi2_
<< "\t n_meas = " << n_meas_
<< endl;
// TODO: compute initial lambda
// Hartley and Zisserman: "A typical init value of lambda is 10^-3 times the
// average of the diagonal elements of J'J"
// Compute Initial Lambda
if(mu_ < 0)
{
double H_max_diag = 0;
double tau = 1e-4;
for(size_t j=0; j<D; ++j)
H_max_diag = max(H_max_diag, fabs(H_(j,j)));
mu_ = tau*H_max_diag;
}
// perform iterative estimation
for (iter_ = 0; iter_<n_iter_; ++iter_)
{
rho_ = 0;
startIteration();
bool sign=false;
// try to compute and update, if it fails, try with increased mu
n_trials_ = 0;
do
{
// init variables
ModelType new_model;
double new_chi2 = -1;
H_.setZero();
//H_ = mu_ * Matrix<double,D,D>::Identity(D,D);
Jres_.setZero();
// compute initial error
n_meas_ = 0;
computeResiduals(model, true, false);
// add damping term:
H_ += (H_.diagonal()*mu_).asDiagonal();
// add prior
if(have_prior_)
applyPrior(model);
// solve the linear system
if(solve())
{
// update the model
update(model, new_model);
// compute error with new model and compare to old error
n_meas_ = 0;
new_chi2 = computeResiduals(new_model, true, false);
rho_ = chi2_-new_chi2;
}
else
{
// matrix was singular and could not be computed
cout << "Matrix is close to singular!" << endl;
cout << "H = " << H_ << endl;
cout << "Jres = " << Jres_ << endl;
rho_ = -1;
}
if(rho_>0)
{
// update decrased the error -> success
model = new_model;
chi2_ = new_chi2;
stop_ = vk::norm_max(x_)<=eps_ ? true : false;
mu_ *= max(1./3., min(1.-pow(2*rho_-1,3), 2./3.));
nu_ = 2.;
if(verbose_)
{
cout << "It. " << iter_
<< "\t Trial " << n_trials_
<< "\t Success"
<< "\t n_meas = " << n_meas_
<< "\t new_chi2 = " << new_chi2
<< "\t mu = " << mu_
<< "\t nu = " << nu_
<< "\t x_norm = " << vk::norm_max(x_)
<< endl;
}
}
else
{
if(sign){
if(verbose_)
{
cout << "It. " << iter_
<< "\t Trial " << n_trials_
<< "\t Failure"
<< "\t n_meas = " << n_meas_
<< "\t new_chi2 = " << new_chi2
<< "\t mu = " << mu_
<< "\t nu = " << nu_
<< "\t x_norm = " << vk::norm_max(x_)
<< endl;
}
mu_ /= nu_;
nu_ /= 2.;
++n_trials_;
if (n_trials_ >= n_trials_max_)
stop_ = true;
sign=false;
}else{
if(verbose_)
{
cout << "It. " << iter_
<< "\t Trial " << n_trials_
<< "\t Failure"
<< "\t n_meas = " << n_meas_
<< "\t new_chi2 = " << new_chi2
<< "\t mu = " << mu_
<< "\t nu = " << nu_
<< "\t x_norm = " << vk::norm_max(x_)
<< endl;
}
mu_ *= nu_;
nu_ *= 2.;
++n_trials_;
if (n_trials_ >= n_trials_max_)
stop_ = true;
sign=true;
}
}
finishTrial();
} while(!(rho_>0 || stop_));
if (stop_)
break;
finishIteration();
}
}
template <int D, typename T>
void vk::NLLSSolver<D, T>::setRobustCostFunction(
ScaleEstimatorType scale_estimator,
WeightFunctionType weight_function)
{
switch(scale_estimator)
{
case TDistScale:
if(verbose_)
printf("Using TDistribution Scale Estimator\n");
scale_estimator_.reset(new robust_cost::TDistributionScaleEstimator());
use_weights_=true;
break;
case MADScale:
if(verbose_)
printf("Using MAD Scale Estimator\n");
scale_estimator_.reset(new robust_cost::MADScaleEstimator());
use_weights_=true;
break;
case NormalScale:
if(verbose_)
printf("Using Normal Scale Estimator\n");
scale_estimator_.reset(new robust_cost::NormalDistributionScaleEstimator());
use_weights_=true;
break;
default:
if(verbose_)
printf("Using Unit Scale Estimator\n");
scale_estimator_.reset(new robust_cost::UnitScaleEstimator());
use_weights_=false;
}
switch(weight_function)
{
case TDistWeight:
if(verbose_)
printf("Using TDistribution Weight Function\n");
weight_function_.reset(new robust_cost::TDistributionWeightFunction());
break;
case TukeyWeight:
if(verbose_)
printf("Using Tukey Weight Function\n");
weight_function_.reset(new robust_cost::TukeyWeightFunction());
break;
case HuberWeight:
if(verbose_)
printf("Using Huber Weight Function\n");
weight_function_.reset(new robust_cost::HuberWeightFunction());
break;
default:
if(verbose_)
printf("Using Unit Weight Function\n");
weight_function_.reset(new robust_cost::UnitWeightFunction());
}
}
template <int D, typename T>
void vk::NLLSSolver<D, T>::setPrior(
const T& prior,
const Matrix<double, D, D>& Information)
{
have_prior_ = true;
prior_ = prior;
I_prior_ = Information;
}
template <int D, typename T>
void vk::NLLSSolver<D, T>::reset()
{
have_prior_ = false;
chi2_ = 1e10;
mu_ = mu_init_;
nu_ = nu_init_;
n_meas_ = 0;
n_iter_ = n_iter_init_;
iter_ = 0;
stop_ = false;
}
template <int D, typename T>
inline const double& vk::NLLSSolver<D, T>::getChi2() const
{
return chi2_;
}
template <int D, typename T>
inline const vk::Matrix<double, D, D>& vk::NLLSSolver<D, T>::getInformationMatrix() const
{
return H_;
}
#endif /* LM_SOLVER_IMPL_HPP_ */
| 25.800633 | 92 | 0.535018 | Pilot-Labs-Dev |
c155a838b36e948a213f7fab326cccc63469505c | 432 | hpp | C++ | engine/generators/include/RoadGenerator.hpp | sidav/shadow-of-the-wyrm | 747afdeebed885b1a4f7ab42f04f9f756afd3e52 | [
"MIT"
] | 1 | 2020-05-24T22:44:03.000Z | 2020-05-24T22:44:03.000Z | engine/generators/include/RoadGenerator.hpp | cleancoindev/shadow-of-the-wyrm | 51b23e98285ecb8336324bfd41ebf00f67b30389 | [
"MIT"
] | null | null | null | engine/generators/include/RoadGenerator.hpp | cleancoindev/shadow-of-the-wyrm | 51b23e98285ecb8336324bfd41ebf00f67b30389 | [
"MIT"
] | null | null | null | #pragma once
#include "Map.hpp"
#include "Directions.hpp"
#define DEFAULT_ROAD_WIDTH 3
class RoadGenerator
{
public:
RoadGenerator(const int width=DEFAULT_ROAD_WIDTH);
RoadGenerator(const CardinalDirection direction, const int width=DEFAULT_ROAD_WIDTH);
virtual MapPtr generate(MapPtr map);
protected:
void generate_road(MapPtr map);
const int ROAD_WIDTH;
const CardinalDirection ROAD_DIRECTION;
};
| 20.571429 | 89 | 0.763889 | sidav |
c15a93fcca153424e4d9df95f44a1869f71cfe48 | 4,279 | cpp | C++ | plugins/resource_context/src/systems/BufferResourceCache.cpp | fuchstraumer/Caelestis | 9c4b76288220681bb245d84e5d7bf8c7f69b2716 | [
"MIT"
] | 5 | 2018-08-16T00:55:33.000Z | 2020-06-19T14:30:17.000Z | plugins/resource_context/src/systems/BufferResourceCache.cpp | fuchstraumer/Caelestis | 9c4b76288220681bb245d84e5d7bf8c7f69b2716 | [
"MIT"
] | null | null | null | plugins/resource_context/src/systems/BufferResourceCache.cpp | fuchstraumer/Caelestis | 9c4b76288220681bb245d84e5d7bf8c7f69b2716 | [
"MIT"
] | null | null | null | #include "systems/BufferResourceCache.hpp"
#include "core/ShaderResource.hpp"
#include "resource/Buffer.hpp"
namespace vpsk {
BufferResourceCache::BufferResourceCache(const vpr::Device* dvc) : device(dvc) { }
BufferResourceCache::~BufferResourceCache() {}
void BufferResourceCache::AddResources(const std::vector<const st::ShaderResource*>& resources) {
createResources(resources);
}
void BufferResourceCache::AddResource(const st::ShaderResource* resource) {
if (!HasResource(resource->ParentGroupName(), resource->Name())) {
createResource(resource);
}
}
vpr::Buffer* BufferResourceCache::at(const std::string& group, const std::string& name) {
return buffers.at(group).at(name).get();
}
vpr::Buffer* BufferResourceCache::find(const std::string& group, const std::string& name) noexcept {
auto group_iter = buffers.find(group);
if (group_iter != buffers.end()) {
auto rsrc_iter = group_iter->second.find(name);
if (rsrc_iter != group_iter->second.end()) {
return rsrc_iter->second.get();
}
else {
return nullptr;
}
}
else {
return nullptr;
}
}
bool BufferResourceCache::HasResource(const std::string& group, const std::string& name) const noexcept {
if (buffers.count(group) == 0) {
return false;
}
else if (buffers.at(group).count(name) != 0) {
return true;
}
else {
return false;
}
}
void BufferResourceCache::createTexelBuffer(const st::ShaderResource* texel_buffer, bool storage) {
auto& group = buffers[texel_buffer->ParentGroupName()];
auto buffer = std::make_unique<vpr::Buffer>(device);
auto flags = storage ? VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT : VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT;
buffer->CreateBuffer(flags, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, texel_buffer->MemoryRequired());
buffer->CreateView(texel_buffer->Format(), buffer->Size(), 0);
group.emplace(texel_buffer->Name(), std::move(buffer));
}
void BufferResourceCache::createUniformBuffer(const st::ShaderResource* uniform_buffer) {
auto& group = buffers[uniform_buffer->ParentGroupName()];
auto buffer = std::make_unique<vpr::Buffer>(device);
auto flags = VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
buffer->CreateBuffer(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, flags, uniform_buffer->MemoryRequired());
group.emplace(uniform_buffer->Name(), std::move(buffer));
}
void BufferResourceCache::createStorageBuffer(const st::ShaderResource* storage_buffer) {
auto& group = buffers[storage_buffer->ParentGroupName()];
auto buffer = std::make_unique<vpr::Buffer>(device);
buffer->CreateBuffer(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, storage_buffer->MemoryRequired());
group.emplace(storage_buffer->Name(), std::move(buffer));
}
void BufferResourceCache::createResources(const std::vector<const st::ShaderResource*>& resources) {
for (const auto& rsrc : resources) {
if (!HasResource(rsrc->ParentGroupName(), rsrc->Name())) {
createResource(rsrc);
}
}
}
void BufferResourceCache::createResource(const st::ShaderResource* rsrc) {
switch (rsrc->DescriptorType()) {
case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
createTexelBuffer(rsrc, false);
break;
case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
createTexelBuffer(rsrc, true);
break;
case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
createUniformBuffer(rsrc);
break;
case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
createStorageBuffer(rsrc);
break;
case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
createUniformBuffer(rsrc);
break;
case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
createStorageBuffer(rsrc);
break;
default:
break;
}
}
}
| 38.205357 | 136 | 0.646179 | fuchstraumer |
c15c5910de26010cd8cdfeda4e8f0660489a6aeb | 424 | cpp | C++ | Assignment2/IDivable.cpp | JJhuk/C-Unmanaged-Programming | 3c78a5be69e4cfd9b8cb33604d5f009b5d34c2fb | [
"MIT"
] | 1 | 2020-04-20T04:33:29.000Z | 2020-04-20T04:33:29.000Z | Assignment2/IDivable.cpp | JJhuk/C-Unmanaged-Programming | 3c78a5be69e4cfd9b8cb33604d5f009b5d34c2fb | [
"MIT"
] | null | null | null | Assignment2/IDivable.cpp | JJhuk/C-Unmanaged-Programming | 3c78a5be69e4cfd9b8cb33604d5f009b5d34c2fb | [
"MIT"
] | null | null | null | #pragma once
#include "Person.h"
namespace assignment2
{
class Vehicle
{
public:
Vehicle(unsigned int maxPassengersCount);
~Vehicle();
virtual unsigned int GetMaxSpeed() const = 0;
bool AddPassenger(const Person* person);
bool RemovePassenger(unsigned int i);
const Person* GetPassenger(unsigned int i) const;
unsigned int GetPassengersCount() const;
unsigned int GetMaxPassengersCount() const;
};
}
| 19.272727 | 51 | 0.742925 | JJhuk |
c15d575b85f1cfb33f82e192833cf99ecbc34955 | 822 | cpp | C++ | shadow/renderer/camera.cpp | thesamhurwitz/shadow | 437033ea54f1e1e28280c6d1d45e762aa850eaaa | [
"MIT"
] | null | null | null | shadow/renderer/camera.cpp | thesamhurwitz/shadow | 437033ea54f1e1e28280c6d1d45e762aa850eaaa | [
"MIT"
] | null | null | null | shadow/renderer/camera.cpp | thesamhurwitz/shadow | 437033ea54f1e1e28280c6d1d45e762aa850eaaa | [
"MIT"
] | null | null | null | #include "camera.h"
#include <glm/gtc/matrix_transform.hpp>
namespace Shadow {
Camera::Camera(float left, float right, float bottom, float top)
: mProjectionMatrix(glm::ortho(left, right, bottom, top, -1.0f, 1.0f)),
mViewMatrix(1.0f),
mPosition(0.0f)
{
mViewProjectionMatrix = mProjectionMatrix * mViewMatrix;
}
void Camera::SetProjection(float left, float right, float bottom, float top) {
mProjectionMatrix = glm::ortho(left, right, bottom, top, -1.0f, 1.0f);
Recalculate();
}
void Camera::Recalculate() {
glm::mat4 transform = glm::translate(glm::mat4(1.0f), mPosition) *
glm::rotate(glm::mat4(1.0f), glm::radians(mRotation), glm::vec3(0, 0, 1));
mViewMatrix = glm::inverse(transform);
mViewProjectionMatrix = mProjectionMatrix * mViewMatrix;
}
} | 29.357143 | 100 | 0.670316 | thesamhurwitz |
c15dd93bf0661dfebf5efaeca1497419a5a0a0bc | 3,690 | cpp | C++ | scps/Schrodinger1DItem.cpp | gapost/MISfit | 882653365d2ae3b3173c763df3fc9b02724d91c2 | [
"MIT"
] | null | null | null | scps/Schrodinger1DItem.cpp | gapost/MISfit | 882653365d2ae3b3173c763df3fc9b02724d91c2 | [
"MIT"
] | null | null | null | scps/Schrodinger1DItem.cpp | gapost/MISfit | 882653365d2ae3b3173c763df3fc9b02724d91c2 | [
"MIT"
] | null | null | null | // Schrodinger1DItem.cpp: implementation of the CSchrodinger1DItem class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Schrodinger1DItem.h"
#include "Schrodinger1D.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
void CSchrodinger1DItem::Assign(CSchrodinger1D* pS, int& i)
{
iequ = i;
x = &(pS->x[iequ]);
h = &(pS->h[iequ]);
L = &(pS->L[iequ]);
v = &(pS->v[iequ]);
q = &(pS->q[iequ]);
dq = &(pS->dq[iequ]);
d = &(pS->T.d(iequ));
s = 0;
if (iequ) s = &(pS->T.s(iequ));
d1 = &(pS->d1[iequ]);
E = pS->E;
Z = pS->Z;
W1 = pS->W1;
W2 = pS->W2;
ne = &(pS->ne);
i += get_m();
}
void CSchrodingerBC::MakeMatrix()
{
double M1,M2,dE1,dE2;
if (Prev) {
M1 = ((CSchrodinger1DLayer*)Prev)->Mz;
dE1 = ((CSchrodinger1DLayer*)Prev)->dE;
}
if (Next) {
M2 = ((CSchrodinger1DLayer*)Next)->Mz;
dE2 = ((CSchrodinger1DLayer*)Next)->dE;
}
switch (btype)
{
case box:
if (s) {
*s = -1/M1/(*L)/(*(L-1))/(*(h-1));
*d1 = 2/M1/(*h)/(*(h-1)) + dE1 + 1e100;
} else {
*d1 = 2/M2/(*(h+1))/(*h) + dE2 + 1e100;
}
break;
case transmit:
if (s) {
*s = -1/M1/(*L)/(*(L-1))/(*(h-1));
*d1 = 1/M1/(*h)/(*h) + dE1;
} else {
*d1 = 1/M2/(*h)/(*h) + dE2;
}
break;
case cont:
int i=0;
s[i] = -1/M1/L[i]/L[i-1]/h[i-1];
d1[i] = 1/L[i]/L[i]*(1/M2/h[i] + 1/M1/h[i-1]) + dE2;
break;
}
}
void CSchrodingerBC::CalcQ()
{
double M, absM;
if (Prev) {
M = ((CSchrodinger1DLayer*)Prev)->Md;
}
if (Next) {
M = ((CSchrodinger1DLayer*)Next)->Md;
}
absM = fabs(M);
int k;
switch (btype)
{
case box:
break;
case transmit:
for(k=0; k<*ne; k++) {
double z = Z[k][iequ];
*q -= M*z*W1[k];
*dq += absM*z*W2[k];
}
break;
case cont:
for(k=0; k<*ne; k++) {
double z = Z[k][iequ];
*q -= M*z*W1[k];
*dq += absM*z*W2[k];
}
break;
}
}
double CSchrodingerBC::get_Md()
{
double M;
if (Prev) {
M = ((CSchrodinger1DLayer*)Prev)->Md;
}
if (Next) {
M = ((CSchrodinger1DLayer*)Next)->Md;
}
return M;
}
void CSchrodinger1DLayer::MakeMatrix()
{
int m = get_m();
for(int i=0; i<m; i++) {
s[i] = -1/Mz/L[i]/L[i-1]/h[i-1];
d1[i] = 2/Mz/h[i]/h[i-1] + dE;
}
}
void CSchrodinger1DLayer::CalcQ()
{
double absMd = fabs(Md);
int m = get_m();
for(int i =0; i<m; i++) {
for(int k=0; k<*ne; k++) {
double z = Z[k][iequ+i];
q[i] -= Md*z*W1[k];
dq[i] += absMd*z*W2[k];
}
}
}
void CSchrodinger1DLayer::CalcBounds(double& lbound, double& ubound, double eps)
{
int sign = 1;
if (Md<0) sign=-1;
double qriterion = sign*(log(sign*Md) - log(eps));
int m = get_m();
if (sign==1) {
double vmin = *(v-1);
for(int i = 0; i<=m; i++) if (v[i]<vmin) vmin = v[i];
vmin += dE;
if (lbound==0. && ubound==0.) { lbound=vmin; ubound=qriterion; }
else {
if (vmin < lbound) lbound = vmin;
if (qriterion > ubound) ubound = qriterion;
}
} else {
double vmax = *(v-1);
for(int i = 0; i<=m; i++) if (v[i]>vmax) vmax = v[i];
vmax += dE;
if (lbound==0. && ubound==0.) { lbound=qriterion; ubound=vmax; }
else {
if (vmax > ubound) ubound = vmax;
if (qriterion < lbound) lbound = qriterion;
}
}
}
void CSchrodinger1DLayer::Dump(ostream& s)
{
int m = get_m();
for(int i = -1; i<m; i++) {
s << x[i] << "\t";
s << (v[i]+dE)/beta << "\t";
s << fabs(q[i]/beta*N0) << "\t";
s << dq[i]/beta*N0 << "\n";
}
}
| 19.52381 | 81 | 0.463144 | gapost |
c15e3c19bb65075988046d812a4a968f4b958c1a | 3,490 | cpp | C++ | RadeonGPUAnalyzerGUI/src/rgUnsavedItemsDialog.cpp | alphonsetai/RGA | 76cd5f36b40bd5e3de40bfb3e79c410aa4c132c9 | [
"MIT"
] | null | null | null | RadeonGPUAnalyzerGUI/src/rgUnsavedItemsDialog.cpp | alphonsetai/RGA | 76cd5f36b40bd5e3de40bfb3e79c410aa4c132c9 | [
"MIT"
] | null | null | null | RadeonGPUAnalyzerGUI/src/rgUnsavedItemsDialog.cpp | alphonsetai/RGA | 76cd5f36b40bd5e3de40bfb3e79c410aa4c132c9 | [
"MIT"
] | null | null | null | // C++.
#include <cassert>
// Qt.
#include <QWidget>
#include <QDialog>
#include <QSignalMapper>
#include <QPainter>
// Local.
#include <RadeonGPUAnalyzerGUI/include/qt/rgUnsavedItemsDialog.h>
#include <RadeonGPUAnalyzerGUI/include/rgUtils.h>
#include <RadeonGPUAnalyzerGUI/include/rgDefinitions.h>
rgUnsavedItemsDialog::rgUnsavedItemsDialog(QWidget *parent)
: QDialog(parent)
{
// Setup the UI.
ui.setupUi(this);
// Disable the help button in the titlebar.
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
// Connect the signals.
ConnectSignals();
// Create item delegate for the list widget.
m_pItemDelegate = new rgUnsavedFileItemDelegate();
bool isDelegateValid = (m_pItemDelegate != nullptr);
assert(isDelegateValid);
if (isDelegateValid)
{
// Set custom delegate for the list widget.
ui.fileListWidget->setItemDelegate(m_pItemDelegate);
}
// Disable selection of items.
ui.fileListWidget->setSelectionMode(QAbstractItemView::NoSelection);
}
rgUnsavedItemsDialog::~rgUnsavedItemsDialog()
{
if (m_pItemDelegate != nullptr)
{
delete m_pItemDelegate;
}
}
void rgUnsavedItemsDialog::ConnectSignals()
{
// Create a signal mapper to map the button clicks to the done(int) slot
// with appropriate result values.
QSignalMapper* pButtonSignalMapper = new QSignalMapper(this);
// Yes button.
bool isConnected = connect(ui.yesPushButton, SIGNAL(clicked()), pButtonSignalMapper, SLOT(map()));
assert(isConnected);
pButtonSignalMapper->setMapping(ui.yesPushButton, UnsavedFileDialogResult::Yes);
// No button.
isConnected = connect(ui.noPushButton, SIGNAL(clicked()), pButtonSignalMapper, SLOT(map()));
assert(isConnected);
pButtonSignalMapper->setMapping(ui.noPushButton, UnsavedFileDialogResult::No);
// Cancel button.
isConnected = connect(ui.cancelPushButton, SIGNAL(clicked()), pButtonSignalMapper, SLOT(map()));
assert(isConnected);
pButtonSignalMapper->setMapping(ui.cancelPushButton, UnsavedFileDialogResult::Cancel);
// Signal mapper.
isConnected = connect(pButtonSignalMapper, SIGNAL(mapped(int)), this, SLOT(done(int)));
assert(isConnected);
}
void rgUnsavedItemsDialog::AddFile(QString filename)
{
ui.fileListWidget->addItem(filename);
}
void rgUnsavedItemsDialog::AddFiles(QStringList filenames)
{
foreach(const QString& filename, filenames)
{
AddFile(filename);
}
}
void rgUnsavedFileItemDelegate::drawDisplay(QPainter* pPainter, const QStyleOptionViewItem& option, const QRect &rect, const QString& text) const
{
bool isPainterValid = (pPainter != nullptr);
assert(isPainterValid);
if (isPainterValid)
{
// Truncate string so it fits within rect.
QString truncatedString = rgUtils::TruncateString(text.toStdString(), gs_TEXT_TRUNCATE_LENGTH_FRONT,
gs_TEXT_TRUNCATE_LENGTH_BACK, rect.width(), pPainter->font(), rgUtils::EXPAND_BACK).c_str();
// Draw text within rect.
pPainter->drawText(rect, Qt::AlignVCenter, truncatedString);
}
}
QSize rgUnsavedFileItemDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
{
// Use standard size hint implementation, but with a fixed width of 0 (width will be determined by view width).
QSize adjustedHint = QItemDelegate::sizeHint(option, index);
adjustedHint.setWidth(0);
return adjustedHint;
}
| 30.347826 | 145 | 0.723209 | alphonsetai |
c15e9c69a07d80945aac87092984b1923f41acb4 | 686 | cpp | C++ | calculator/IdGenerator.cpp | fmidev/smartmet-library-calculator | 19366ff5af4d3a456d1841c3c3cb598eb900d86a | [
"MIT"
] | null | null | null | calculator/IdGenerator.cpp | fmidev/smartmet-library-calculator | 19366ff5af4d3a456d1841c3c3cb598eb900d86a | [
"MIT"
] | null | null | null | calculator/IdGenerator.cpp | fmidev/smartmet-library-calculator | 19366ff5af4d3a456d1841c3c3cb598eb900d86a | [
"MIT"
] | null | null | null | // ======================================================================
/*!
* \file
* \brief Interface of class TextGen::IdGenerator
*/
// ======================================================================
#include "IdGenerator.h"
#include <boost/atomic.hpp>
namespace TextGen
{
// ----------------------------------------------------------------------
/*!
* \brief Return a new ID
*
* \return The generated ID
*/
// ----------------------------------------------------------------------
long IdGenerator::generate()
{
static boost::atomic<long> id;
return ++id;
}
} // namespace TextGen
// ======================================================================
| 22.129032 | 73 | 0.300292 | fmidev |
c15f4c9e92fef839991a274dfa983a9c8f42bd7f | 11,565 | cc | C++ | components/digital_asset_links/digital_asset_links_handler.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | components/digital_asset_links/digital_asset_links_handler.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | components/digital_asset_links/digital_asset_links_handler.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/digital_asset_links/digital_asset_links_handler.h"
#include <vector>
#include "base/bind.h"
#include "base/json/json_reader.h"
#include "base/logging.h"
#include "base/strings/stringprintf.h"
#include "base/values.h"
#include "content/public/browser/web_contents.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_status_code.h"
#include "net/http/http_util.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/cpp/simple_url_loader.h"
#include "services/network/public/mojom/url_response_head.mojom.h"
#include "third_party/blink/public/mojom/devtools/console_message.mojom.h"
#include "url/origin.h"
namespace {
// In some cases we get a network change while fetching the digital asset
// links file. See https://crbug.com/987329.
const int kNumNetworkRetries = 1;
// Location on a website where the asset links file can be found, see
// https://developers.google.com/digital-asset-links/v1/getting-started.
const char kAssetLinksAbsolutePath[] = ".well-known/assetlinks.json";
GURL GetUrlForAssetLinks(const url::Origin& origin) {
return origin.GetURL().Resolve(kAssetLinksAbsolutePath);
}
// An example, well formed asset links file for reference:
// [{
// "relation": ["delegate_permission/common.handle_all_urls"],
// "target": {
// "namespace": "android_app",
// "package_name": "com.peter.trustedpetersactivity",
// "sha256_cert_fingerprints": [
// "FA:2A:03: ... :9D"
// ]
// }
// }, {
// "relation": ["delegate_permission/common.handle_all_urls"],
// "target": {
// "namespace": "android_app",
// "package_name": "com.example.firstapp",
// "sha256_cert_fingerprints": [
// "64:2F:D4: ... :C1"
// ]
// }
// }]
bool StatementHasMatchingRelationship(const base::Value& statement,
const std::string& target_relation) {
const base::Value* relations =
statement.FindKeyOfType("relation", base::Value::Type::LIST);
if (!relations)
return false;
for (const auto& relation : relations->GetList()) {
if (relation.is_string() && relation.GetString() == target_relation)
return true;
}
return false;
}
bool StatementHasMatchingTargetValue(
const base::Value& statement,
const std::string& target_key,
const std::set<std::string>& target_value) {
const base::Value* package = statement.FindPathOfType(
{"target", target_key}, base::Value::Type::STRING);
return package &&
target_value.find(package->GetString()) != target_value.end();
}
bool StatementHasMatchingFingerprint(const base::Value& statement,
const std::string& target_fingerprint) {
const base::Value* fingerprints = statement.FindPathOfType(
{"target", "sha256_cert_fingerprints"}, base::Value::Type::LIST);
if (!fingerprints)
return false;
for (const auto& fingerprint : fingerprints->GetList()) {
if (fingerprint.is_string() &&
fingerprint.GetString() == target_fingerprint) {
return true;
}
}
return false;
}
// Shows a warning message in the DevTools console.
void AddMessageToConsole(content::WebContents* web_contents,
const std::string& message) {
if (web_contents) {
web_contents->GetMainFrame()->AddMessageToConsole(
blink::mojom::ConsoleMessageLevel::kWarning, message);
return;
}
// Fallback to LOG.
LOG(WARNING) << message;
}
} // namespace
namespace digital_asset_links {
const char kDigitalAssetLinksCheckResponseKeyLinked[] = "linked";
DigitalAssetLinksHandler::DigitalAssetLinksHandler(
scoped_refptr<network::SharedURLLoaderFactory> factory,
content::WebContents* web_contents)
: shared_url_loader_factory_(std::move(factory)) {
if (web_contents) {
web_contents_ = web_contents->GetWeakPtr();
}
}
DigitalAssetLinksHandler::~DigitalAssetLinksHandler() = default;
void DigitalAssetLinksHandler::OnURLLoadComplete(
std::string relationship,
absl::optional<std::string> fingerprint,
std::map<std::string, std::set<std::string>> target_values,
std::unique_ptr<std::string> response_body) {
int response_code = -1;
if (url_loader_->ResponseInfo() && url_loader_->ResponseInfo()->headers)
response_code = url_loader_->ResponseInfo()->headers->response_code();
if (!response_body || response_code != net::HTTP_OK) {
int net_error = url_loader_->NetError();
if (net_error == net::ERR_INTERNET_DISCONNECTED ||
net_error == net::ERR_NAME_NOT_RESOLVED) {
AddMessageToConsole(web_contents_.get(),
"Digital Asset Links connection failed.");
std::move(callback_).Run(RelationshipCheckResult::kNoConnection);
return;
}
AddMessageToConsole(
web_contents_.get(),
base::StringPrintf(
"Digital Asset Links endpoint responded with code %d.",
response_code));
std::move(callback_).Run(RelationshipCheckResult::kFailure);
return;
}
data_decoder::DataDecoder::ParseJsonIsolated(
*response_body,
base::BindOnce(&DigitalAssetLinksHandler::OnJSONParseResult,
weak_ptr_factory_.GetWeakPtr(), std::move(relationship),
std::move(fingerprint), std::move(target_values)));
url_loader_.reset(nullptr);
}
void DigitalAssetLinksHandler::OnJSONParseResult(
std::string relationship,
absl::optional<std::string> fingerprint,
std::map<std::string, std::set<std::string>> target_values,
data_decoder::DataDecoder::ValueOrError result) {
if (!result.value) {
AddMessageToConsole(
web_contents_.get(),
"Digital Asset Links response parsing failed with message: " +
*result.error);
std::move(callback_).Run(RelationshipCheckResult::kFailure);
return;
}
auto& statement_list = *result.value;
if (!statement_list.is_list()) {
std::move(callback_).Run(RelationshipCheckResult::kFailure);
AddMessageToConsole(web_contents_.get(), "Statement List is not a list.");
return;
}
// We only output individual statement failures if none match.
std::vector<std::string> failures;
for (const auto& statement : statement_list.GetList()) {
if (!statement.is_dict()) {
failures.push_back("Statement is not a dictionary.");
continue;
}
if (!StatementHasMatchingRelationship(statement, relationship)) {
failures.push_back("Statement failure matching relationship.");
continue;
}
if (fingerprint &&
!StatementHasMatchingFingerprint(statement, *fingerprint)) {
failures.push_back("Statement failure matching fingerprint.");
continue;
}
bool failed_target_check = false;
for (const auto& key_value : target_values) {
if (!StatementHasMatchingTargetValue(statement, key_value.first,
key_value.second)) {
failures.push_back("Statement failure matching " + key_value.first +
".");
failed_target_check = true;
break;
}
}
if (failed_target_check)
continue;
std::move(callback_).Run(RelationshipCheckResult::kSuccess);
return;
}
for (const auto& failure_reason : failures)
AddMessageToConsole(web_contents_.get(), failure_reason);
std::move(callback_).Run(RelationshipCheckResult::kFailure);
}
bool DigitalAssetLinksHandler::CheckDigitalAssetLinkRelationshipForAndroidApp(
const std::string& web_domain,
const std::string& relationship,
const std::string& fingerprint,
const std::string& package,
RelationshipCheckResultCallback callback) {
// TODO(rayankans): Should we also check the namespace here?
return CheckDigitalAssetLinkRelationship(
web_domain, relationship, fingerprint, {{"package_name", {package}}},
std::move(callback));
}
bool DigitalAssetLinksHandler::CheckDigitalAssetLinkRelationshipForWebApk(
const std::string& web_domain,
const std::string& manifest_url,
RelationshipCheckResultCallback callback) {
return CheckDigitalAssetLinkRelationship(
web_domain, "delegate_permission/common.query_webapk", absl::nullopt,
{{"namespace", {"web"}}, {"site", {manifest_url}}}, std::move(callback));
}
bool DigitalAssetLinksHandler::CheckDigitalAssetLinkRelationship(
const std::string& web_domain,
const std::string& relationship,
const absl::optional<std::string>& fingerprint,
const std::map<std::string, std::set<std::string>>& target_values,
RelationshipCheckResultCallback callback) {
// TODO(peconn): Propagate the use of url::Origin backwards to clients.
GURL request_url = GetUrlForAssetLinks(url::Origin::Create(GURL(web_domain)));
if (!request_url.is_valid())
return false;
// Resetting both the callback and SimpleURLLoader here to ensure
// that any previous requests will never get a
// OnURLLoadComplete. This effectively cancels any checks that was
// done over this handler.
callback_ = std::move(callback);
net::NetworkTrafficAnnotationTag traffic_annotation =
net::DefineNetworkTrafficAnnotation("digital_asset_links", R"(
semantics {
sender: "Digital Asset Links Handler"
description:
"Digital Asset Links APIs allows any caller to check pre declared"
"relationships between two assets which can be either web domains"
"or native applications. This requests checks for a specific "
"relationship declared by a web site with an Android application"
trigger:
"When the related application makes a claim to have the queried"
"relationship with the web domain"
data: "None"
destination: WEBSITE
}
policy {
cookies_allowed: YES
cookies_store: "user"
setting: "Not user controlled. But the verification is a trusted API"
"that doesn't use user data"
policy_exception_justification:
"Not implemented, considered not useful as no content is being "
"uploaded; this request merely downloads the resources on the web."
})");
auto request = std::make_unique<network::ResourceRequest>();
request->url = request_url;
// Exclude credentials (specifically client certs) from the request.
request->credentials_mode =
network::mojom::CredentialsMode::kOmitBug_775438_Workaround;
url_loader_ =
network::SimpleURLLoader::Create(std::move(request), traffic_annotation);
url_loader_->SetRetryOptions(
kNumNetworkRetries,
network::SimpleURLLoader::RetryMode::RETRY_ON_NETWORK_CHANGE);
url_loader_->SetTimeoutDuration(timeout_duration_);
url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
shared_url_loader_factory_.get(),
base::BindOnce(&DigitalAssetLinksHandler::OnURLLoadComplete,
weak_ptr_factory_.GetWeakPtr(), relationship, fingerprint,
target_values));
return true;
}
void DigitalAssetLinksHandler::SetTimeoutDuration(
base::TimeDelta timeout_duration) {
timeout_duration_ = timeout_duration;
}
} // namespace digital_asset_links
| 35.151976 | 80 | 0.694596 | zealoussnow |
c1601b8758430a450bffd6a48fd8840b9effcf39 | 1,564 | cpp | C++ | aws-cpp-sdk-sagemaker/source/model/OfflineStoreStatus.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-sagemaker/source/model/OfflineStoreStatus.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-sagemaker/source/model/OfflineStoreStatus.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/sagemaker/model/OfflineStoreStatus.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace SageMaker
{
namespace Model
{
OfflineStoreStatus::OfflineStoreStatus() :
m_status(OfflineStoreStatusValue::NOT_SET),
m_statusHasBeenSet(false),
m_blockedReasonHasBeenSet(false)
{
}
OfflineStoreStatus::OfflineStoreStatus(JsonView jsonValue) :
m_status(OfflineStoreStatusValue::NOT_SET),
m_statusHasBeenSet(false),
m_blockedReasonHasBeenSet(false)
{
*this = jsonValue;
}
OfflineStoreStatus& OfflineStoreStatus::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("Status"))
{
m_status = OfflineStoreStatusValueMapper::GetOfflineStoreStatusValueForName(jsonValue.GetString("Status"));
m_statusHasBeenSet = true;
}
if(jsonValue.ValueExists("BlockedReason"))
{
m_blockedReason = jsonValue.GetString("BlockedReason");
m_blockedReasonHasBeenSet = true;
}
return *this;
}
JsonValue OfflineStoreStatus::Jsonize() const
{
JsonValue payload;
if(m_statusHasBeenSet)
{
payload.WithString("Status", OfflineStoreStatusValueMapper::GetNameForOfflineStoreStatusValue(m_status));
}
if(m_blockedReasonHasBeenSet)
{
payload.WithString("BlockedReason", m_blockedReason);
}
return payload;
}
} // namespace Model
} // namespace SageMaker
} // namespace Aws
| 20.578947 | 111 | 0.751279 | perfectrecall |
c16288695b71e20cbd42e56b2dd3c4785ceb17d8 | 562 | hpp | C++ | libs/renderer/include/sge/renderer/texture/volume_shared_ptr.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | libs/renderer/include/sge/renderer/texture/volume_shared_ptr.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | libs/renderer/include/sge/renderer/texture/volume_shared_ptr.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_RENDERER_TEXTURE_VOLUME_SHARED_PTR_HPP_INCLUDED
#define SGE_RENDERER_TEXTURE_VOLUME_SHARED_PTR_HPP_INCLUDED
#include <sge/renderer/texture/volume_fwd.hpp>
#include <fcppt/shared_ptr_impl.hpp>
namespace sge
{
namespace renderer
{
namespace texture
{
typedef fcppt::shared_ptr<texture::volume> volume_shared_ptr;
}
}
}
#endif
| 21.615385 | 61 | 0.770463 | cpreh |
c1633a5b5840f93790dd65fa5c759adb8a7d65ee | 1,875 | cpp | C++ | src/component/extra/fps.cpp | pepng-CU/pepng | 6030798b6936a6f85655d5e5d1ca638be282de92 | [
"MIT"
] | 2 | 2021-04-28T20:51:25.000Z | 2021-04-28T20:51:38.000Z | src/component/extra/fps.cpp | pepng-CU/pepng | 6030798b6936a6f85655d5e5d1ca638be282de92 | [
"MIT"
] | null | null | null | src/component/extra/fps.cpp | pepng-CU/pepng | 6030798b6936a6f85655d5e5d1ca638be282de92 | [
"MIT"
] | null | null | null | #include "fps.hpp"
#include <sstream>
#include "../../io/io.hpp"
#include "../transform.hpp"
FPS::FPS(float panSpeed, float rotationSpeed) :
Component("FPS"),
__pan_speed(panSpeed),
__rotation_speed(rotationSpeed)
{}
FPS::FPS(const FPS& fps) :
Component(fps),
__pan_speed(fps.__pan_speed),
__rotation_speed(fps.__rotation_speed)
{}
std::shared_ptr<FPS> FPS::make_fps(float panSpeed, float rotationSpeed) {
std::shared_ptr<FPS> fps(new FPS(panSpeed, rotationSpeed));
return fps;
}
std::shared_ptr<FPS> pepng::make_fps(float panSpeed, float rotationSpeed) {
return FPS::make_fps(panSpeed, rotationSpeed);
}
FPS* FPS::clone_implementation() {
return new FPS(*this);
}
void FPS::update(std::shared_ptr<WithComponents> parent) {
if(!this->_is_active) {
return;
}
auto transform = parent->get_component<Transform>();
if (transform == nullptr) {
std::stringstream ss;
ss << *parent << " has an FPS but no Transform.";
std::cout << ss.str() << std::endl;
std::runtime_error(ss.str());
}
auto input = Input::get();
auto mouseDelta = glm::vec2(input->axis("mouseX"), input->axis("mouseY"));
if (input->button("pan")) {
transform->position += transform->up() * mouseDelta.y * this->__pan_speed + transform->right() * mouseDelta.x * this->__pan_speed;
}
auto rotation = glm::vec3(mouseDelta.y, mouseDelta.x, 0.0f);
if(input->button("rotate") && glm::length(rotation) > 0.25f) {
transform->delta_rotate(rotation * this->__rotation_speed);
}
transform->position -= transform->forward() * input->axis("zoom") * this->__pan_speed;
}
#ifdef IMGUI
void FPS::imgui() {
Component::imgui();
ImGui::InputFloat("Pan Speed", &this->__pan_speed);
ImGui::InputFloat("Rotation Speed", &this->__rotation_speed);
}
#endif | 25.337838 | 138 | 0.6464 | pepng-CU |
c1639a7bba7ab0bf6112e0444e986527b4cc9e8b | 2,547 | hpp | C++ | include/wire/util/concatenate.hpp | zmij/wire | 9981eb9ea182fc49ef7243eed26b9d37be70a395 | [
"Artistic-2.0"
] | 5 | 2016-04-07T19:49:39.000Z | 2021-08-03T05:24:11.000Z | include/wire/util/concatenate.hpp | zmij/wire | 9981eb9ea182fc49ef7243eed26b9d37be70a395 | [
"Artistic-2.0"
] | null | null | null | include/wire/util/concatenate.hpp | zmij/wire | 9981eb9ea182fc49ef7243eed26b9d37be70a395 | [
"Artistic-2.0"
] | 1 | 2020-12-27T11:47:31.000Z | 2020-12-27T11:47:31.000Z | /*
* stream_feeder.hpp
*
* Created on: Jan 27, 2016
* Author: zmij
*/
#ifndef WIRE_UTIL_CONCATENATE_HPP_
#define WIRE_UTIL_CONCATENATE_HPP_
#include <sstream>
#include <string>
#include <typeinfo>
namespace wire {
namespace util {
namespace detail {
struct __io_meta_function_helper {
template <typename T> __io_meta_function_helper(T const&);
};
::std::false_type
operator << (::std::ostream const&, __io_meta_function_helper const&);
template <typename T>
struct has_output_operator {
private:
static ::std::false_type test(::std::false_type);
static ::std::true_type test(::std::ostream&);
static ::std::ostream& os;
static T const& val;
public:
static constexpr bool value = ::std::is_same<
decltype( test( os << val) ), ::std::true_type >::type::value;
};
template < typename T, bool >
struct output_impl {
static void
output(::std::ostream& os, T const& arg)
{
os << arg;
}
};
template < typename T >
struct output_impl<T, false> {
static void
output(::std::ostream& os, T const&)
{
os << typeid(T).name();
}
};
template < typename T >
void
concatenate( ::std::ostream& os, T const& arg)
{
using output = output_impl<T, has_output_operator<T>::value>;
output::output(os, arg);
}
template < typename T, typename ... Y >
void
concatenate( ::std::ostream& os, T const& arg, Y const& ... args )
{
using output = output_impl<T, has_output_operator<T>::value>;
output::output(os, arg);
concatenate(os, args ...);
}
template < typename T >
void
delim_concatenate( ::std::ostream& os, ::std::string const& delim, T const& arg)
{
using output = output_impl<T, has_output_operator<T>::value>;
output::output(os, arg);
}
template < typename T, typename ... Y >
void
delim_concatenate( ::std::ostream& os, ::std::string const& delim, T const& arg, Y const& ... args )
{
using output = output_impl<T, has_output_operator<T>::value>;
output::output(os, arg);
os << delim;
delim_concatenate(os, delim, args ...);
}
} // namespace detail
template < typename ... T >
::std::string
concatenate( T const& ... args)
{
::std::ostringstream os;
detail::concatenate(os, args ...);
return os.str();
}
template < typename ... T >
::std::string
delim_concatenate(::std::string const& delim, T const& ... args)
{
::std::ostringstream os;
detail::delim_concatenate(os, delim, args ...);
return os.str();
}
} // namespace util
} // namespace wire
#endif /* WIRE_UTIL_CONCATENATE_HPP_ */
| 22.147826 | 100 | 0.647428 | zmij |
c1690ab82760c5260d9e570a4abf35d3f5e766f6 | 1,517 | cc | C++ | src/qtui/qtui.cc | Acidburn0zzz/audacious-plugins | 6fa3edfb44750602c8dcd2f2b1517c4a8261ba28 | [
"BSD-3-Clause"
] | null | null | null | src/qtui/qtui.cc | Acidburn0zzz/audacious-plugins | 6fa3edfb44750602c8dcd2f2b1517c4a8261ba28 | [
"BSD-3-Clause"
] | null | null | null | src/qtui/qtui.cc | Acidburn0zzz/audacious-plugins | 6fa3edfb44750602c8dcd2f2b1517c4a8261ba28 | [
"BSD-3-Clause"
] | null | null | null | /*
* qtui.cc
* Copyright 2014 Michał Lipski
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions, and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions, and the following disclaimer in the documentation
* provided with the distribution.
*
* This software is provided "as is" and without any warranty, express or
* implied. In no event shall the authors be liable for any damages arising from
* the use of this software.
*/
#include <QApplication>
#include <libaudcore/i18n.h>
#include <libaudcore/plugin.h>
#include <libaudcore/plugins.h>
#include "main_window.h"
static MainWindow * window;
static bool_t init ()
{
return true;
}
static void cleanup ()
{
}
static void run ()
{
int dummy_argc = 0;
QApplication qapp (dummy_argc, 0);
window = new MainWindow;
window->show ();
qapp.exec ();
delete window;
}
static void show (bool_t show)
{
}
static void quit ()
{
qApp->quit();
}
#define AUD_PLUGIN_NAME N_("Qt Interface")
#define AUD_PLUGIN_INIT init
#define AUD_PLUGIN_CLEANUP cleanup
#define AUD_IFACE_RUN run
#define AUD_IFACE_SHOW show
#define AUD_IFACE_QUIT quit
#define AUD_DECLARE_IFACE
#include <libaudcore/plugin-declare.h>
| 20.780822 | 80 | 0.715887 | Acidburn0zzz |
c16976c86bb4c6c946d5ae75bca57bd100ff3431 | 244 | hpp | C++ | Projects/krkr2_on_VC/kirikiri2/src/core/environ/win32/VS2005/my_vcl/FileCtrl.hpp | CATION-M/X-moe | 2bac3bb45ff21e50921aac8422f2e00839f546e5 | [
"MIT"
] | 2 | 2020-02-25T15:18:53.000Z | 2020-08-24T13:30:34.000Z | Projects/krkr2_on_VC/kirikiri2/src/core/environ/win32/VS2005/my_vcl/FileCtrl.hpp | CATION-M/X-moe | 2bac3bb45ff21e50921aac8422f2e00839f546e5 | [
"MIT"
] | null | null | null | Projects/krkr2_on_VC/kirikiri2/src/core/environ/win32/VS2005/my_vcl/FileCtrl.hpp | CATION-M/X-moe | 2bac3bb45ff21e50921aac8422f2e00839f546e5 | [
"MIT"
] | 1 | 2019-11-25T05:29:30.000Z | 2019-11-25T05:29:30.000Z | #pragma once
#include "vcl_base.h"
#include "Buttons.hpp"
#include "Classes.hpp"
#include "Controls.hpp"
#include "Forms.hpp"
#include "Graphics.hpp"
#include "Menus.hpp"
#include "Messages.hpp"
#include "StdCtrls.hpp"
#include "SysUtils.hpp"
| 18.769231 | 23 | 0.737705 | CATION-M |
c16a57f313d112c14818c4934d202e8dd34fd05f | 4,118 | cpp | C++ | components/scene_graph/sources/core/sg_particle_emitter.cpp | untgames/funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 7 | 2016-03-30T17:00:39.000Z | 2017-03-27T16:04:04.000Z | components/scene_graph/sources/core/sg_particle_emitter.cpp | untgames/Funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 4 | 2017-11-21T11:25:49.000Z | 2018-09-20T17:59:27.000Z | components/scene_graph/sources/core/sg_particle_emitter.cpp | untgames/Funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 4 | 2016-11-29T15:18:40.000Z | 2017-03-27T16:04:08.000Z | #include "shared.h"
using namespace scene_graph;
/*
ParticleEmitter implementation
*/
typedef xtl::signal<void (ParticleEmitter& sender, ParticleEmitterEvent event)> ParticleEmitterSignal;
struct ParticleEmitter::Impl: public xtl::instance_counter<ParticleEmitter>
{
stl::string particle_system_id; //particle system identifier (as loaded in media::ParticleSystemLibrary)
xtl::auto_connection particles_parent_destroy_connection; //particles parent node's destroy connection
ParticleEmitterSignal signals [ParticleEmitterEvent_Num]; //signals
Node* particles_parent; //particles are emitted in coordinate space of this node
scene_graph::SpriteMode sprite_mode; //sprite mode
bool is_playing; //is emitter emits particles now
Impl (const char* in_particle_system_id, Node* in_particles_parent, scene_graph::SpriteMode in_sprite_mode)
: particles_parent (in_particles_parent)
, sprite_mode (in_sprite_mode)
, is_playing (true)
{
if (!in_particle_system_id)
throw xtl::make_null_argument_exception ("scene_graph::ParticleEmitter::Impl::Impl", "particle_system_id");
particle_system_id = in_particle_system_id;
particles_parent_destroy_connection = particles_parent->RegisterEventHandler (NodeEvent_BeforeDestroy, xtl::bind (&ParticleEmitter::Impl::OnBaseNodeDestroy, this));
}
void OnBaseNodeDestroy ()
{
particles_parent = 0;
}
///Notify about event
void Notify (ParticleEmitter& emitter, ParticleEmitterEvent event)
{
//ignore if we have no handlers for this event
if (!signals [event])
return;
//call event handlers
try
{
signals [event] (emitter, event);
}
catch (...)
{
//suppress all exceptions
}
}
};
/*
Constructor / destructor
*/
ParticleEmitter::ParticleEmitter (const char* particle_system_id, Node::Pointer particles_parent, scene_graph::SpriteMode sprite_mode)
: impl (new Impl (particle_system_id, particles_parent ? particles_parent.get () : this, sprite_mode))
{}
ParticleEmitter::~ParticleEmitter ()
{
delete impl;
}
/*
Emitter creation
*/
ParticleEmitter::Pointer ParticleEmitter::Create (const char* particle_system_id, Node::Pointer particles_parent, scene_graph::SpriteMode sprite_mode)
{
return Pointer (new ParticleEmitter (particle_system_id, particles_parent, sprite_mode), false);
}
/*
Particle system identifier (as loaded in media::ParticleSystemLibrary)
*/
const char* ParticleEmitter::ParticleSystemId () const
{
return impl->particle_system_id.c_str ();
}
/*
Particles are emitted in coordinate space of this node
*/
Node::Pointer ParticleEmitter::ParticlesParent () const
{
return impl->particles_parent;
}
/*
Sprite mode
*/
scene_graph::SpriteMode ParticleEmitter::SpriteMode () const
{
return impl->sprite_mode;
}
/*
Control simualtion process
*/
void ParticleEmitter::Play ()
{
if (impl->is_playing)
return;
impl->is_playing = true;
impl->Notify (*this, ParticleEmitterEvent_OnPlay);
}
bool ParticleEmitter::IsPlaying () const
{
return impl->is_playing;
}
void ParticleEmitter::Pause ()
{
if (!impl->is_playing)
return;
impl->is_playing = false;
impl->Notify (*this, ParticleEmitterEvent_OnPause);
}
/*
Registration for ParticleEmitter events
*/
xtl::connection ParticleEmitter::RegisterEventHandler (ParticleEmitterEvent event, const EventHandler& handler) const
{
if (event < 0 || event >= ParticleEmitterEvent_Num)
throw xtl::make_argument_exception ("scene_graph::ParticleEmitter::Event", "event", event);
return impl->signals [event].connect (handler);
}
/*
Method which is called when this node is visited
*/
void ParticleEmitter::AcceptCore (Visitor& visitor)
{
if (!TryAccept (*this, visitor))
VisualModel::AcceptCore (visitor);
}
| 25.899371 | 169 | 0.685041 | untgames |
c16c56082492b65f4c46d10a81aef1e7318a0828 | 204 | cpp | C++ | ai/mean-max/test/test2.cpp | jonasnic/codingame | f1a7fe8007b9ca63bdf30cd72f4d6ac41a5ac721 | [
"MIT"
] | 30 | 2016-04-30T01:56:05.000Z | 2022-03-09T22:19:12.000Z | ai/mean-max/test/test2.cpp | jonasnic/codingame | f1a7fe8007b9ca63bdf30cd72f4d6ac41a5ac721 | [
"MIT"
] | 1 | 2021-05-19T19:36:45.000Z | 2021-05-19T19:36:45.000Z | ai/mean-max/test/test2.cpp | jonasnic/codingame | f1a7fe8007b9ca63bdf30cd72f4d6ac41a5ac721 | [
"MIT"
] | 17 | 2020-01-28T13:54:06.000Z | 2022-03-26T09:49:27.000Z | #include <iostream>
#include "../../src/referee.cpp"
using namespace std;
int main() {
Referee referee;
referee.readGameInfo();
Referee refereeCopy(referee);
cout << refereeCopy.toString();
}
| 15.692308 | 33 | 0.686275 | jonasnic |
c16d16e2804cffc8f8b85b880046d455eec7ef4c | 1,110 | cpp | C++ | hackerrank/practice/data_structures/trees/swap_nodes_algo.cpp | Loks-/competitions | 3bb231ba9dd62447048832f45b09141454a51926 | [
"MIT"
] | 4 | 2018-06-05T14:15:52.000Z | 2022-02-08T05:14:23.000Z | hackerrank/practice/data_structures/trees/swap_nodes_algo.cpp | Loks-/competitions | 3bb231ba9dd62447048832f45b09141454a51926 | [
"MIT"
] | null | null | null | hackerrank/practice/data_structures/trees/swap_nodes_algo.cpp | Loks-/competitions | 3bb231ba9dd62447048832f45b09141454a51926 | [
"MIT"
] | 1 | 2018-10-21T11:01:35.000Z | 2018-10-21T11:01:35.000Z | // https://www.hackerrank.com/challenges/swap-nodes-algo
#include "common/stl/base.h"
#include <functional>
int main_swap_nodes_algo() {
unsigned N;
cin >> N;
vector<int> vl(N + 1, -1), vr(N + 1, -1), vd(N + 1, -1);
vector<bool> vh(N + 1, true);
for (unsigned i = 1; i <= N; ++i) {
int l, r;
cin >> l >> r;
vl[i] = l;
vr[i] = r;
if (l != -1) vh[l] = false;
if (r != -1) vh[r] = false;
}
unsigned h = 0;
for (unsigned i = 1; i < N; ++i) {
if (vh[i]) {
h = i;
break;
}
}
std::function<void(int, int)> InitD = [&](int c, int cd) -> void {
if (c != -1) {
vd[c] = cd;
InitD(vl[c], cd + 1);
InitD(vr[c], cd + 1);
}
};
std::function<void(int)> Print = [&](int c) -> void {
if (c != -1) {
Print(vl[c]);
cout << c << " ";
Print(vr[c]);
}
};
InitD(h, 1);
unsigned T;
cin >> T;
for (unsigned iT = 0; iT < T; ++iT) {
int d;
cin >> d;
for (unsigned i = 1; i <= N; ++i) {
if ((vd[i] % d) == 0) swap(vl[i], vr[i]);
}
Print(h);
cout << endl;
}
return 0;
}
| 19.137931 | 68 | 0.435135 | Loks- |
c16dc9367f81c8ff11ae5bed4efdf9351fc6c171 | 2,176 | cpp | C++ | src/handler/media_mux.cpp | anjisuan783/media_server | 443fdbda8a778c7302020ea16f4fb25cd3fd8dae | [
"MIT"
] | 9 | 2022-01-07T03:10:45.000Z | 2022-03-31T03:29:02.000Z | src/handler/media_mux.cpp | anjisuan783/media_server | 443fdbda8a778c7302020ea16f4fb25cd3fd8dae | [
"MIT"
] | 16 | 2021-12-17T08:32:57.000Z | 2022-03-10T06:16:14.000Z | src/handler/media_mux.cpp | anjisuan783/media_lib | c09c7d48f495a803df79e39cf837bbcb1320ceb8 | [
"MIT"
] | 1 | 2022-02-21T15:47:21.000Z | 2022-02-21T15:47:21.000Z | //
// Copyright (c) 2021- anjisuan783
//
// SPDX-License-Identifier: MIT
//
#include "handler/media_mux.h"
#include "common/media_kernel_error.h"
#include "utils/json.h"
#include "connection/http_conn.h"
#include "http/http_stack.h"
#include "http/h/http_message.h"
#include "connection/h/media_conn_mgr.h"
#include "rtmp/media_req.h"
#include "handler/media_live_handler.h"
#include "handler/media_rtc_handler.h"
#include "handler/media_file_handler.h"
namespace ma {
MediaHttpServeMux::MediaHttpServeMux()
: rtc_sevice_{new MediaHttpRtcServeMux},
flv_sevice_{new MediaFlvPlayHandler},
file_sevice_{new MediaFileHandler} {
g_conn_mgr_.signal_destroy_conn_.connect(this, &MediaHttpServeMux::conn_destroy);
}
MediaHttpServeMux::~MediaHttpServeMux() = default;
srs_error_t MediaHttpServeMux::init() {
return rtc_sevice_->init();
}
srs_error_t MediaHttpServeMux::serve_http(
std::shared_ptr<IHttpResponseWriter> writer,
std::shared_ptr<ISrsHttpMessage> msg) {
std::string path = msg->path();
if (path == RTC_PUBLISH_PREFIX || path == RTC_PALY_PREFIX) {
return rtc_sevice_->serve_http(std::move(writer), std::move(msg));
}
if (path == HTTP_TEST) {
return file_sevice_->serve_http(std::move(writer), std::move(msg));
}
return flv_sevice_->serve_http(std::move(writer), std::move(msg));
}
srs_error_t MediaHttpServeMux::mount_service(
std::shared_ptr<MediaSource> s, std::shared_ptr<MediaRequest> r) {
srs_error_t err = srs_success;
if ((err = rtc_sevice_->mount_service(s, r)) != srs_success) {
return srs_error_wrap(err, "rtc mount service");
}
return flv_sevice_->mount_service(std::move(s), std::move(r));
}
void MediaHttpServeMux::unmount_service(
std::shared_ptr<MediaSource> s, std::shared_ptr<MediaRequest> r) {
rtc_sevice_->unmount_service(s, r);
flv_sevice_->unmount_service(std::move(s), std::move(r));
}
void MediaHttpServeMux::conn_destroy(std::shared_ptr<IMediaConnection> conn) {
flv_sevice_->conn_destroy(conn);
file_sevice_->conn_destroy(conn);
}
std::unique_ptr<IMediaHttpHandler> ServerHandlerFactor::Create() {
return std::make_unique<MediaHttpServeMux>();
}
}
| 27.897436 | 83 | 0.737592 | anjisuan783 |
c1718e41050f137965ec0de32d9a4ca17db3d949 | 12,031 | cpp | C++ | escriptcore/src/WrappedArray.cpp | markendr/esys-escript.github.io | 0023eab09cd71f830ab098cb3a468e6139191e8d | [
"Apache-2.0"
] | null | null | null | escriptcore/src/WrappedArray.cpp | markendr/esys-escript.github.io | 0023eab09cd71f830ab098cb3a468e6139191e8d | [
"Apache-2.0"
] | null | null | null | escriptcore/src/WrappedArray.cpp | markendr/esys-escript.github.io | 0023eab09cd71f830ab098cb3a468e6139191e8d | [
"Apache-2.0"
] | null | null | null |
/*****************************************************************************
*
* Copyright (c) 2003-2020 by The University of Queensland
* http://www.uq.edu.au
*
* Primary Business: Queensland, Australia
* Licensed under the Apache License, version 2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Development until 2012 by Earth Systems Science Computational Center (ESSCC)
* Development 2012-2013 by School of Earth Sciences
* Development from 2014-2017 by Centre for Geoscience Computing (GeoComp)
* Development from 2019 by School of Earth and Environmental Sciences
**
*****************************************************************************/
#include "Data.h"
#include "WrappedArray.h"
#include "DataException.h"
#if ESYS_HAVE_NUMPY_H
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/ndarrayobject.h>
#endif
#include <iostream>
#include <boost/python/tuple.hpp>
using namespace escript;
using namespace boost::python;
using DataTypes::cplx_t;
using DataTypes::real_t;
namespace
{
void checkFeatures(const boost::python::object& obj)
{
using namespace std;
boost::python::object o2;
try
{
/*int len=*/ extract<int>(obj.attr("__len__")());
}
catch (...)
{
PyErr_Clear();
throw DataException("Object passed to WrappedArray must support __len__");
}
try
{
o2=obj.attr("__getitem__");
}
catch (...)
{
PyErr_Clear();
throw DataException("Object passed to WrappedArray must support __getitem__");
}
}
// This should not be called on anything which does
// not have a __len__
bool checkForComplex(const boost::python::object& obj)
{
try
{
int len=extract<int>(obj.attr("__len__")());
for (int i=0;i<len;++i)
{
const boost::python::object t=obj[i];
bool haslen=false;
try
{
extract<int>(t.attr("__len__")());
haslen=true;
}
catch(...)
{
PyErr_Clear();
}
// If it has a length, we dig down
// if not, we test for complex
if (haslen)
{
if (checkForComplex(t))
{
return true;
}
}
else
{
extract<DataTypes::real_t> er(t);
if (!er.check())
{
// unfortunately, if this was a numpy object, that check my fail
// even if it should succeed (eg numpy.int64 on python3)
// instead, we will try to call __float__ and see what happens
try
{
t.attr("__float__")();
return false; // if this check succeeds it isn't complex
}
catch (...)
{
PyErr_Clear();
// at this point, we have no apparent way to get a real out so
// we assume it must be complex
return true;
}
}
}
}
return false;
}
catch(...)
{
PyErr_Clear();
return false;
}
return false;
}
void getObjShape(const boost::python::object& obj, DataTypes::ShapeType& s)
{
int len=0;
try
{
len=extract<int>(obj.attr("__len__")());
}
catch(...)
{
PyErr_Clear(); // tell python the error isn't there anymore
return;
}
if (len<1)
{
throw DataException("Array filter - no empty components in arrays please.");
}
s.push_back(len);
if (s.size()>ESCRIPT_MAX_DATA_RANK)
{
throw DataException("Array filter - Maximum rank exceeded in array");
}
getObjShape(obj[0],s);
}
}
WrappedArray::WrappedArray(const boost::python::object& obj_in)
:obj(obj_in),converted(false),iscomplex(false),scalar_r(nan("")),scalar_c(nan(""))
{
dat_r=0;
dat_c=0;
// First we check for scalars
try
{
extract<DataTypes::cplx_t> ec(obj_in);
extract<real_t> er(obj_in);
if (er.check()) // check for real_t first because complex will fail this
{
scalar_r=er();
}
else
{
scalar_c=ec();
iscomplex=true;
}
rank=0;
return;
}
catch (...)
{ // so we clear the failure
PyErr_Clear();
}
try
{
const boost::python::object obj_in_t=obj_in[make_tuple()];
extract<DataTypes::cplx_t> ec(obj_in_t);
extract<real_t> er(obj_in_t);
if (er.check())
{
scalar_r=er();
}
else
{
scalar_c=ec();
iscomplex=true;
}
rank=0;
return;
}
catch (...)
{ // so we clear the failure
PyErr_Clear();
}
scalar_c=0;
scalar_r=0;
checkFeatures(obj_in);
getObjShape(obj,shape);
rank=shape.size();
iscomplex=checkForComplex(obj_in);
#if ESYS_HAVE_NUMPY_H
// if obj is a numpy array it is much faster to copy the array through the
// __array_struct__ interface instead of extracting single values from the
// components via getElt(). For this to work we check below that
// (1) this is a valid PyArrayInterface instance
// (2) the data is stored as a contiguous C array
// (3) the data type is suitable (correct type and byte size)
try
{
object o = (extract<object>(obj.attr("__array_struct__")));
#ifdef ESPYTHON3
if (PyCapsule_CheckExact(o.ptr()))
#else
if (PyCObject_Check(o.ptr()))
#endif
{
PyObject* cobj=(PyObject*)o.ptr();
#ifdef ESPYTHON3
const char* name = PyCapsule_GetName(cobj);
PyArrayInterface* arr=(PyArrayInterface*)PyCapsule_GetPointer(cobj, name);
#else
PyArrayInterface* arr=(PyArrayInterface*)PyCObject_AsVoidPtr(cobj);
#endif
#ifndef NPY_1_7_API_VERSION
#define NPY_ARRAY_IN_ARRAY NPY_IN_ARRAY
#define NPY_ARRAY_NOTSWAPPED NPY_NOTSWAPPED
#endif
if (arr->two==2 && arr->flags&NPY_ARRAY_IN_ARRAY && arr->flags&NPY_ARRAY_NOTSWAPPED)
{
std::vector<int> strides;
// convert #bytes to #elements
for (int i=0; i<arr->nd; i++)
{
strides.push_back(arr->strides[i]/arr->itemsize);
}
if (arr->typekind == 'f')
{
if (arr->itemsize==sizeof(real_t))
{
convertNumpyArray<real_t>((const real_t*)arr->data, strides);
}
else if (arr->itemsize==sizeof(float))
{
convertNumpyArray<float>((const float*)arr->data, strides);
}
}
else if (arr->typekind == 'i')
{
if (arr->itemsize==sizeof(int))
{
convertNumpyArray<int>((const int*)arr->data, strides);
}
else if (arr->itemsize==sizeof(long))
{
convertNumpyArray<long>((const long*)arr->data, strides);
}
}
else if (arr->typekind == 'u')
{
if (arr->itemsize==sizeof(unsigned))
{
convertNumpyArray<unsigned>((const unsigned*)arr->data, strides);
}
else if (arr->itemsize==sizeof(unsigned long))
{
convertNumpyArray<unsigned long>((const unsigned long*)arr->data, strides);
}
}
else if (arr->typekind == 'c')
{
if (arr->itemsize==sizeof(cplx_t))
{
convertNumpyArrayC<DataTypes::cplx_t>((const cplx_t*)arr->data, strides);
iscomplex=true;
}
// not accomodating other types of complex values
}
}
}
} catch (...)
{
PyErr_Clear();
}
#endif
}
template<typename T>
void WrappedArray::convertNumpyArrayC(const T* array, const std::vector<int>& strides) const
{
// this method is only called by the constructor above which does the
// necessary checks and initialisations
int size=DataTypes::noValues(shape);
dat_c=new cplx_t[size];
switch (rank)
{
case 1:
#pragma omp parallel for
for (int i=0;i<shape[0];i++)
{
dat_c[i]=array[i*strides[0]];
}
break;
case 2:
#pragma omp parallel for
for (int i=0;i<shape[0];i++)
{
for (int j=0;j<shape[1];j++)
{
dat_c[DataTypes::getRelIndex(shape,i,j)]=array[i*strides[0]+j*strides[1]];
}
}
break;
case 3:
#pragma omp parallel for
for (int i=0;i<shape[0];i++)
{
for (int j=0;j<shape[1];j++)
{
for (int k=0;k<shape[2];k++)
{
dat_c[DataTypes::getRelIndex(shape,i,j,k)]=array[i*strides[0]+j*strides[1]+k*strides[2]];
}
}
}
break;
case 4:
#pragma omp parallel for
for (int i=0;i<shape[0];i++)
{
for (int j=0;j<shape[1];j++)
{
for (int k=0;k<shape[2];k++)
{
for (int m=0;m<shape[3];m++)
{
dat_c[DataTypes::getRelIndex(shape,i,j,k,m)]=array[i*strides[0]+j*strides[1]+k*strides[2]+m*strides[3]];
}
}
}
}
break;
}
}
template<typename T>
void WrappedArray::convertNumpyArray(const T* array, const std::vector<int>& strides) const
{
// this method is only called by the constructor above which does the
// necessary checks and initialisations
int size=DataTypes::noValues(shape);
dat_r=new real_t[size];
switch (rank)
{
case 1:
#pragma omp parallel for
for (int i=0;i<shape[0];i++)
{
dat_r[i]=array[i*strides[0]];
}
break;
case 2:
#pragma omp parallel for
for (int i=0;i<shape[0];i++)
{
for (int j=0;j<shape[1];j++)
{
dat_r[DataTypes::getRelIndex(shape,i,j)]=array[i*strides[0]+j*strides[1]];
}
}
break;
case 3:
#pragma omp parallel for
for (int i=0;i<shape[0];i++)
{
for (int j=0;j<shape[1];j++)
{
for (int k=0;k<shape[2];k++)
{
dat_r[DataTypes::getRelIndex(shape,i,j,k)]=array[i*strides[0]+j*strides[1]+k*strides[2]];
}
}
}
break;
case 4:
#pragma omp parallel for
for (int i=0;i<shape[0];i++)
{
for (int j=0;j<shape[1];j++)
{
for (int k=0;k<shape[2];k++)
{
for (int m=0;m<shape[3];m++)
{
dat_r[DataTypes::getRelIndex(shape,i,j,k,m)]=array[i*strides[0]+j*strides[1]+k*strides[2]+m*strides[3]];
}
}
}
}
break;
}
}
void WrappedArray::convertArrayR() const
{
if ((converted) || (rank<=0) || (rank>4)) // checking illegal rank here to avoid memory issues later
{ // yes the failure is silent here but not doing the copy
return; // will just cause an error to be raised later
}
int size=DataTypes::noValues(shape);
real_t* tdat=new real_t[size];
switch (rank)
{
case 1: for (int i=0;i<shape[0];i++)
{
tdat[i]=getElt(i);
}
break;
case 2: for (int i=0;i<shape[0];i++)
{
for (int j=0;j<shape[1];j++)
{
tdat[DataTypes::getRelIndex(shape,i,j)]=getElt(i,j);
}
}
break;
case 3: for (int i=0;i<shape[0];i++)
{
for (int j=0;j<shape[1];j++)
{
for (int k=0;k<shape[2];k++)
{
tdat[DataTypes::getRelIndex(shape,i,j,k)]=getElt(i,j,k);
}
}
}
break;
case 4: for (int i=0;i<shape[0];i++)
{
for (int j=0;j<shape[1];j++)
{
for (int k=0;k<shape[2];k++)
{
for (int m=0;m<shape[3];m++)
{
tdat[DataTypes::getRelIndex(shape,i,j,k,m)]=getElt(i,j,k,m);
}
}
}
}
break;
default:
; // do nothing
// can't happen. We've already checked the bounds above
}
dat_r=tdat;
converted=true;
}
void WrappedArray::convertArrayC() const
{
if ((converted) || (rank<=0) || (rank>4)) // checking illegal rank here to avoid memory issues later
{ // yes the failure is silent here but not doing the copy
return; // will just cause an error to be raised later
}
int size=DataTypes::noValues(shape);
cplx_t* tdat=new cplx_t[size];
switch (rank)
{
case 1: for (int i=0;i<shape[0];i++)
{
tdat[i]=getElt(i);
}
break;
case 2: for (int i=0;i<shape[0];i++)
{
for (int j=0;j<shape[1];j++)
{
tdat[DataTypes::getRelIndex(shape,i,j)]=getElt(i,j);
}
}
break;
case 3: for (int i=0;i<shape[0];i++)
{
for (int j=0;j<shape[1];j++)
{
for (int k=0;k<shape[2];k++)
{
tdat[DataTypes::getRelIndex(shape,i,j,k)]=getElt(i,j,k);
}
}
}
break;
case 4: for (int i=0;i<shape[0];i++)
{
for (int j=0;j<shape[1];j++)
{
for (int k=0;k<shape[2];k++)
{
for (int m=0;m<shape[3];m++)
{
tdat[DataTypes::getRelIndex(shape,i,j,k,m)]=getElt(i,j,k,m);
}
}
}
}
break;
default:
; // do nothing
// can't happen. We've already checked the bounds above
}
dat_c=tdat;
converted=true;
}
void WrappedArray::convertArray() const
{
if (iscomplex)
{
convertArrayC();
}
else
{
convertArrayR();
}
}
WrappedArray::~WrappedArray()
{
if (dat_r!=0)
{
delete[] dat_r;
}
if (dat_c!=0)
{
delete[] dat_c;
}
}
| 21.638489 | 111 | 0.591306 | markendr |
c174b800b5a2517e76055a9369c8b9f60be4a046 | 2,945 | cpp | C++ | mesh_processing/VertexWeights.cpp | rms80/libgeometry | e60ec7d34968573a9cda3f3bf56d2d4717385dc9 | [
"BSL-1.0"
] | 23 | 2015-08-13T07:36:00.000Z | 2022-01-24T19:00:04.000Z | mesh_processing/VertexWeights.cpp | rms80/libgeometry | e60ec7d34968573a9cda3f3bf56d2d4717385dc9 | [
"BSL-1.0"
] | null | null | null | mesh_processing/VertexWeights.cpp | rms80/libgeometry | e60ec7d34968573a9cda3f3bf56d2d4717385dc9 | [
"BSL-1.0"
] | 6 | 2015-07-06T21:37:31.000Z | 2020-07-01T04:07:50.000Z | // Copyright Ryan Schmidt 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See copy at http://www.boost.org/LICENSE_1_0.txt)
#include "VertexWeights.h"
#include "VectorUtil.h"
#include "rmsdebug.h"
using namespace rms;
void VertexWeights::Uniform( VFTriangleMesh & mesh, IMesh::VertexID vID,
std::vector<IMesh::VertexID> & vNeighbourhood,
std::vector<float> & vWeights, bool bNormalize )
{
size_t nNbrs = vNeighbourhood.size();
vWeights.resize(nNbrs);
for ( unsigned int k = 0; k < nNbrs; ++k )
vWeights[k] = 1.0f;
if ( bNormalize ) {
float fWeightSum = (float)nNbrs;
for ( unsigned int k = 0; k < nNbrs; ++k )
vWeights[k] /= fWeightSum;
}
}
void VertexWeights::InverseDistance( VFTriangleMesh & mesh, IMesh::VertexID vID,
std::vector<IMesh::VertexID> & vNeighbourhood,
std::vector<float> & vWeights, float fPow, float fEps, bool bNormalize )
{
Wml::Vector3f vVtx, vNbr;
mesh.GetVertex(vID, vVtx);
float fWeightSum = 0.0f;
size_t nNbrs = vNeighbourhood.size();
vWeights.resize(nNbrs);
for ( unsigned int k = 0; k < nNbrs; ++k ) {
mesh.GetVertex( vNeighbourhood[k], vNbr );
float fDist = (vNbr - vVtx).Length();
vWeights[k] = 1.0f / (fEps + pow(fDist,fPow));
fWeightSum += vWeights[k];
}
if ( bNormalize ) {
float fWeightSum = (float)nNbrs;
for ( unsigned int k = 0; k < nNbrs; ++k )
vWeights[k] /= fWeightSum;
}
}
//! assumes one-ring is ordered
void VertexWeights::Cotangent( VFTriangleMesh & mesh, IMesh::VertexID vID,
std::vector<IMesh::VertexID> & vOneRing,
std::vector<float> & vWeights, bool bNormalize )
{
Wml::Vector3f vVtx, vOpp, vPrev, vNext;
size_t nNbrs = vOneRing.size();
mesh.GetVertex(vID, vVtx);
mesh.GetVertex(vOneRing[0], vOpp);
mesh.GetVertex(vOneRing[nNbrs-1], vPrev);
vWeights.resize(nNbrs);
float fWeightSum = 0.0f;
for ( unsigned int k = 0; k < nNbrs; ++k ) {
IMesh::VertexID nNext = vOneRing[(k+1)%nNbrs];
mesh.GetVertex(nNext, vNext);
Wml::Vector3f a1(vVtx - vPrev); a1.Normalize();
Wml::Vector3f a2(vOpp - vPrev); a2.Normalize();
float fADot = a1.Dot(a2);
double fAlpha = acos( rms::Clamp(fADot, -1.0f, 1.0f) );
Wml::Vector3f b1(vVtx - vNext); b1.Normalize();
Wml::Vector3f b2(vOpp - vNext); b2.Normalize();
float fBDot = b1.Dot(b2);
double fBeta = acos( rms::Clamp(fBDot, -1.0f, 1.0f) );
vWeights[k] = (float)( 1/tan(fAlpha) + 1/tan(fBeta) );
if ( ! _finite(vWeights[k]) )
_RMSInfo("MeshUtils::CotangentWeights():: non-finite weight at vertex %d [%d/%d] alpha d/a: %f/%f beta d/a: %f/%f\n", vOneRing[k], k, nNbrs, fADot,fAlpha, fBDot, fBeta);
fWeightSum += vWeights[k];
vPrev = vOpp;
vOpp = vNext;
}
if ( bNormalize ) {
for ( unsigned int k = 0; k < nNbrs; ++k )
vWeights[k] /= fWeightSum;
}
}
| 28.872549 | 177 | 0.619694 | rms80 |
c17829c4cf2dfb4d15e419de03804ec968cd60e6 | 4,542 | cpp | C++ | jsk_recognition_utils/src/geo/cylinder.cpp | ShunjiroOsada/jsk_visualization_package | f5305ccb79b41a2efc994a535cb316e7467961de | [
"MIT"
] | 5 | 2016-07-18T02:20:30.000Z | 2022-01-23T13:12:20.000Z | jsk_recognition_utils/src/geo/cylinder.cpp | ShunjiroOsada/jsk_visualization_package | f5305ccb79b41a2efc994a535cb316e7467961de | [
"MIT"
] | null | null | null | jsk_recognition_utils/src/geo/cylinder.cpp | ShunjiroOsada/jsk_visualization_package | f5305ccb79b41a2efc994a535cb316e7467961de | [
"MIT"
] | 7 | 2015-11-01T13:40:30.000Z | 2020-02-21T12:59:18.000Z | // -*- mode: c++ -*-
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2014, JSK Lab
* 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/o2r other materials provided
* with the distribution.
* * Neither the name of the JSK Lab nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#define BOOST_PARAMETER_MAX_ARITY 7
#include "jsk_recognition_utils/geo/cylinder.h"
#include "jsk_recognition_utils/geo_util.h"
namespace jsk_recognition_utils
{
Cylinder::Cylinder(Eigen::Vector3f point, Eigen::Vector3f direction, double radius):
point_(point), direction_(direction), radius_(radius)
{
}
void Cylinder::filterPointCloud(const pcl::PointCloud<pcl::PointXYZ>& cloud,
const double threshold,
pcl::PointIndices& output)
{
Line line(direction_, point_);
output.indices.clear();
for (size_t i = 0; i < cloud.points.size(); i++) {
Eigen::Vector3f p = cloud.points[i].getVector3fMap();
double d = line.distanceToPoint(p);
if (d < radius_ + threshold && d > radius_ - threshold) {
output.indices.push_back(i);
}
}
}
void Cylinder::estimateCenterAndHeight(const pcl::PointCloud<pcl::PointXYZ>& cloud,
const pcl::PointIndices& indices,
Eigen::Vector3f& center,
double& height)
{
Line line(direction_, point_);
Vertices points;
for (size_t i = 0; i < indices.indices.size(); i++) {
int point_index = indices.indices[i];
points.push_back(cloud.points[point_index].getVector3fMap());
}
PointPair min_max = line.findEndPoints(points);
Eigen::Vector3f min_point = min_max.get<0>();
Eigen::Vector3f max_point = min_max.get<1>();
Eigen::Vector3f min_point_projected, max_point_projected;
line.foot(min_point, min_point_projected);
line.foot(max_point, max_point_projected);
height = (min_point_projected - max_point_projected).norm();
center = (min_point_projected + max_point_projected) / 2.0;
}
void Cylinder::toMarker(visualization_msgs::Marker& marker,
const Eigen::Vector3f& center,
const Eigen::Vector3f& uz,
const double height)
{
marker.type = visualization_msgs::Marker::CYLINDER;
marker.pose.position.x = center[0];
marker.pose.position.y = center[1];
marker.pose.position.z = center[2];
Eigen::Vector3f orig_z(0, 0, 1);
Eigen::Quaternionf q;
q.setFromTwoVectors(orig_z, uz);
marker.pose.orientation.x = q.x();
marker.pose.orientation.y = q.y();
marker.pose.orientation.z = q.z();
marker.pose.orientation.w = q.w();
marker.scale.x = radius_ * 2;
marker.scale.y = radius_ * 2;
marker.scale.z = height;
marker.color.a = 1.0;
marker.color.g = 1.0;
marker.color.b = 1.0;
}
Eigen::Vector3f Cylinder::getDirection()
{
return direction_;
}
}
| 39.495652 | 86 | 0.643329 | ShunjiroOsada |
c178fc54bf3d7ce82998eb41a6ab8a68b9b7f669 | 454 | hpp | C++ | src/Client/EnviadoresCliente/EnviadorCredenciales.hpp | brunograssano/SuperMarioBros-Honguitos | f945e434bc317a6d8c8d682b1042d8a385929156 | [
"MIT"
] | 4 | 2021-02-21T17:12:46.000Z | 2021-02-25T20:36:27.000Z | src/Client/EnviadoresCliente/EnviadorCredenciales.hpp | brunograssano/SuperMarioBros-Honguitos | f945e434bc317a6d8c8d682b1042d8a385929156 | [
"MIT"
] | null | null | null | src/Client/EnviadoresCliente/EnviadorCredenciales.hpp | brunograssano/SuperMarioBros-Honguitos | f945e434bc317a6d8c8d682b1042d8a385929156 | [
"MIT"
] | 2 | 2021-02-20T19:49:33.000Z | 2021-02-25T20:35:22.000Z | #ifndef SRC_CLIENT_ENVIADORESCLIENTE_ENVIADORCREDENCIALES_HPP_
#define SRC_CLIENT_ENVIADORESCLIENTE_ENVIADORCREDENCIALES_HPP_
#include "src/Utils/Enviador.hpp"
class EnviadorCredenciales:public Enviador{
public:
explicit EnviadorCredenciales(Socket* socket);
void enviar()override;
void dejarInformacion(void* informacion)override;
private:
credencial_t credenciales;
};
#endif /* SRC_CLIENT_ENVIADORESCLIENTE_ENVIADORCREDENCIALES_HPP_ */
| 25.222222 | 67 | 0.84141 | brunograssano |
c17a07f579626e88d8c3f8149000b9873dfb35aa | 3,994 | cpp | C++ | code/src/GeminiClient.cpp | Blackmane/gemini | 4c7091aec06826bf2ff440c858a18c9e05730d59 | [
"MIT"
] | null | null | null | code/src/GeminiClient.cpp | Blackmane/gemini | 4c7091aec06826bf2ff440c858a18c9e05730d59 | [
"MIT"
] | null | null | null | code/src/GeminiClient.cpp | Blackmane/gemini | 4c7091aec06826bf2ff440c858a18c9e05730d59 | [
"MIT"
] | null | null | null | /**
* @file GeminiClient.cpp
* @brief implementation
*
* @author Niccolò Pieretti
* @date 02 Apr 2021
*
****************************************************************************
*
* _ _ o __ __ __ _ o _ ,_ _
* / |/ | | / / / \_|/ \_| |/ / | |/
* | |_/|_/\__/\___/\__/ |__/ |_/|__/ |_/|__/
* /|
* \|
****************************************************************************/
#include "GeminiClient.hpp"
#include "Exception.hpp"
#include "Protocol.hpp"
#include "TslSocket.hpp"
#include "Utils.hpp"
#include <iostream>
#include <errno.h>
#include <netdb.h>
#include <openssl/err.h>
#include <resolv.h>
#include <string.h>
#include <unistd.h>
// ~~~~~ ~~~~~ ~~~~~
// Implementation
// ~~~~~ ~~~~~ ~~~~~
std::unique_ptr<gemini::Response>
gemini::GeminiClient::getResponse(std::string request,
std::unique_ptr<Socket> connection) {
// Send request
auto sendRes = connection->send(request);
if (sendRes <= 0) {
throw connection_error("Error in send request");
}
// Read <STATUS><SPACE>
const auto statusSize =
response::HEADER_STATUS_SIZE + response::HEADER_SPACE_SIZE;
char statusBuffer[statusSize + 1];
auto statusRes = connection->read(statusBuffer, statusSize);
if ((size_t)statusRes < statusSize) {
throw protocol_response_error("Empty response");
}
if (!(response::isHeaderStatusFirstValid(statusBuffer[0]) &&
response::isHeaderStatusSecondValid(statusBuffer[1]))) {
throw protocol_response_error("Invalid status --- response");
}
if (statusBuffer[2] != ' ') {
throw protocol_response_error("Invalid status response");
}
std::unique_ptr<Response> response(new Response);
response->statusCodeFirst = statusBuffer[0] - '0';
response->statusCodeSecond = statusBuffer[1] - '0';
// Read <META><CR><FL>
const auto metaSize = response::HEADER_META_SIZE + 2;
char metaBuffer[metaSize + 1];
auto metaRes = connection->read(metaBuffer, metaSize);
// Check header termination
if (metaRes < 2) {
throw protocol_response_error("Empty header");
}
// Assure metaBuffer terminates
metaBuffer[metaRes > metaSize ? metaSize : metaRes] = '\0';
// Find terminators
auto pos = strstr(metaBuffer, "\r\n");
if (pos == nullptr) {
throw protocol_response_error("Invalid header termination");
}
if ((size_t)(pos - metaBuffer) > response::HEADER_META_SIZE) {
throw protocol_response_error("Invalid meta size");
}
// Save meta
response->meta = std::string(metaBuffer, pos);
// Read <BODY>
if (response->statusCodeFirst == response::HEADER_STATUS_FIRST::SUCCESS) {
const auto bodyChunkSize = response::BODY_CHUNK_SIZE;
char bodyBuffer[bodyChunkSize + 1];
// Copy previous part
if (pos + 2 < metaBuffer + metaRes) {
response->body += std::string(pos + 2, metaBuffer + metaRes);
}
auto bodyRes = connection->read(bodyBuffer, bodyChunkSize);
while (bodyRes > 0) {
// Set string terminator
bodyBuffer[(size_t)bodyRes > bodyChunkSize ? bodyChunkSize : bodyRes] =
'\0';
response->body += std::string(bodyBuffer);
bodyRes = connection->read(bodyBuffer, bodyChunkSize);
}
}
return response;
}
std::unique_ptr<gemini::Response>
gemini::GeminiClient::request(const std::string url, const std::string port) {
// Check url
if (url.length() > request::URL_MAX_SIZE) {
throw std::invalid_argument("Invalid url length: expected max " +
std::to_string(request::URL_MAX_SIZE));
}
// Open socket
const std::string hostname = getHostnameFromUrl(url);
std::unique_ptr<Socket> socket =
std::unique_ptr<Socket>(new TslSocket(hostname, port));
// Build request: <URL><CR><LF>
std::string request(url + gemini::CR + gemini::LF);
return getResponse(request, std::move(socket));
}
| 31.698413 | 78 | 0.604407 | Blackmane |
c17ccb994cf70cce6b7413301df3b7cf91582208 | 2,343 | cpp | C++ | uppdev/stdapp/stdappSplash.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | 2 | 2016-04-07T07:54:26.000Z | 2020-04-14T12:37:34.000Z | uppdev/stdapp/stdappSplash.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | null | null | null | uppdev/stdapp/stdappSplash.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | null | null | null | #include <stdapp/stdappSplash.hpp>
#define IMAGECLASS UPP_LogoImg
#define IMAGEFILE <stdapp/UPP_Logo_033.iml>
#include <Draw/iml_source.h>
Splash::Splash(const int language, const int ms)
{
SetLanguage(language);
SetRect(GetWorkArea().CenterRect(MakeSplash(*this, widgets) + 2));
SetFrame(BlackFrame());
PopUp(NULL, false, false, true);
SetTimeCallback(ms, THISBACK(CloseSplash));
}
Size Splash::MakeSplash(Ctrl& parent, Array<Ctrl>& widgets)
{
Image logo = UPP_LogoImg::AppLogo();
Size logo_size = logo.GetSize();
Size rect_size;
rect_size.cx = max(SPLASH_RECT_CX, logo_size.cx);
rect_size.cy = max(SPLASH_RECT_CY, logo_size.cy);
parent.Add(widgets.Create<StaticRect>().Color(SPLASH_PAPER_COLOR).SizePos());
ImageCtrl& image = widgets.Create<ImageCtrl>();
image.SetImage(logo);
image.LeftPos(0, logo_size.cx).VSizePos();
parent.Add(image);
Label& label_1 = widgets.Create<Label>();
label_1.SetFont(SPLASH_FONT_1(SPLASH_FONT_SIZE_1).Bold());
label_1.SetInk(SPLASH_INK_COLOR_1);
label_1 = APP_TITLE;
label_1.SetAlign(ALIGN_CENTER);
label_1.RightPos(0, rect_size.cx - logo_size.cx).TopPos(rect_size.cy * 1 / 9, 20);
parent.Add(label_1);
Label& label_2 = widgets.Create<Label>();
label_2.SetFont(SPLASH_FONT_2(SPLASH_FONT_SIZE_2).Bold());
label_2.SetInk(SPLASH_INK_COLOR_2);
label_2 = APP_VERSION;
label_2.SetAlign(ALIGN_CENTER);
label_2.RightPos(0, rect_size.cx - logo_size.cx).TopPos(rect_size.cy * 3 / 9, 20);
parent.Add(label_2);
Label& label_3 = widgets.Create<Label>();
label_3.SetFont(SPLASH_FONT_3(SPLASH_FONT_SIZE_3).Italic());
label_3.SetInk(SPLASH_INK_COLOR_3);
label_3 = APP_SUBTITLE;
label_3.SetAlign(ALIGN_CENTER);
label_3.RightPos(0, rect_size.cx - logo_size.cx).TopPos(rect_size.cy * 5 / 9, 20);
parent.Add(label_3);
Label& label_4 = widgets.Create<Label>();
label_4.SetFont(SPLASH_FONT_4(SPLASH_FONT_SIZE_4));
label_4.SetInk(SPLASH_INK_COLOR_4);
label_4 = APP_COPYRIGHT;
label_4.SetAlign(ALIGN_CENTER);
label_4.RightPos(0, rect_size.cx - logo_size.cx).TopPos(rect_size.cy * 7 / 9, 20);
parent.Add(label_4);
return rect_size;
}
void Splash::CloseSplash()
{
Close();
}
| 33 | 87 | 0.685446 | dreamsxin |
c17fc0d94a34616853aac134528108d402eb6364 | 2,154 | hpp | C++ | libelement/src/object_model/declarations/declaration.hpp | ultraleap/Element | 6fe9ab800a9152482e719a7dc17d296bad464eb6 | [
"Apache-2.0"
] | 12 | 2019-12-17T18:27:04.000Z | 2021-06-04T08:46:05.000Z | libelement/src/object_model/declarations/declaration.hpp | ultraleap/Element | 6fe9ab800a9152482e719a7dc17d296bad464eb6 | [
"Apache-2.0"
] | 12 | 2020-10-27T14:30:37.000Z | 2022-01-05T16:50:53.000Z | libelement/src/object_model/declarations/declaration.hpp | ultraleap/Element | 6fe9ab800a9152482e719a7dc17d296bad464eb6 | [
"Apache-2.0"
] | 6 | 2020-01-10T23:45:48.000Z | 2021-07-01T22:58:01.000Z | #pragma once
//SELF
#include "object_model/object_internal.hpp"
#include "object_model/scope.hpp"
#include "object_model/call_stack.hpp"
namespace element
{
static const std::string intrinsic_qualifier = "intrinsic";
static const std::string namespace_qualifier = "namespace";
static const std::string constraint_qualifier = "constraint";
static const std::string struct_qualifier = "struct";
static const std::string function_qualifier; //empty string
static const std::string return_keyword = "return";
static const std::string unidentifier = "_";
class declaration : public object
{
public:
explicit declaration(identifier name, const scope* parent);
[[nodiscard]] std::string get_name() const final;
[[nodiscard]] std::string get_qualified_name() const;
[[nodiscard]] bool has_inputs() const { return !inputs.empty(); }
[[nodiscard]] bool has_constraint() const { return false; } //TODO: JM - nonsense, this needs to be a constraint::something OR constraint::any
[[nodiscard]] bool has_scope() const;
[[nodiscard]] bool virtual is_intrinsic() const = 0;
[[nodiscard]] virtual bool is_variadic() const { return false; }
[[nodiscard]] const std::vector<port>& get_inputs() const override { return inputs; }
[[nodiscard]] const scope* get_scope() const override { return our_scope.get(); }
[[nodiscard]] const port& get_output() const override { return output; }
[[nodiscard]] virtual bool serializable(const compilation_context& context) const { return false; }
[[nodiscard]] virtual bool deserializable(const compilation_context& context) const { return false; }
[[nodiscard]] virtual object_const_shared_ptr generate_placeholder(const compilation_context& context, std::size_t& placeholder_index, std::size_t boundary_scope) const;
[[nodiscard]] virtual std::string location() const;
std::string qualifier;
identifier name;
std::vector<port> inputs;
std::unique_ptr<scope> our_scope;
port output;
protected:
//the wrapper is used to return declarations within the object model
std::shared_ptr<const declaration_wrapper> wrapper;
};
} // namespace element | 43.08 | 173 | 0.736769 | ultraleap |
c181b5a07187c900d3ad3a1b4baf132f13cfa7b0 | 61,082 | hpp | C++ | hpx/hpx_fwd.hpp | andreasbuhr/hpx | 4366a90aacbd3e95428a94ab24a1646a67459cc2 | [
"BSL-1.0"
] | null | null | null | hpx/hpx_fwd.hpp | andreasbuhr/hpx | 4366a90aacbd3e95428a94ab24a1646a67459cc2 | [
"BSL-1.0"
] | null | null | null | hpx/hpx_fwd.hpp | andreasbuhr/hpx | 4366a90aacbd3e95428a94ab24a1646a67459cc2 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2007-2013 Hartmut Kaiser
// Copyright (c) 2011 Bryce Lelbach
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
/// \file hpx_fwd.hpp
#if !defined(HPX_HPX_FWD_MAR_24_2008_1119AM)
#define HPX_HPX_FWD_MAR_24_2008_1119AM
#include <hpx/config.hpp>
#include <cstdlib>
#include <vector>
#include <boost/config.hpp>
#include <boost/version.hpp>
#if BOOST_VERSION < 104200
// Please update your Boost installation (see www.boost.org for details).
#error HPX cannot be compiled with a Boost version earlier than V1.42.
#endif
#if defined(BOOST_WINDOWS)
#include <winsock2.h>
#include <windows.h>
#endif
#include <boost/shared_ptr.hpp>
#include <boost/intrusive_ptr.hpp>
#include <boost/cstdint.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/detail/scoped_enum_emulation.hpp>
#include <boost/system/error_code.hpp>
#include <hpx/config/function.hpp>
#include <hpx/traits.hpp>
#include <hpx/lcos/local/once_fwd.hpp>
#include <hpx/util/unused.hpp>
#include <hpx/util/move.hpp>
#include <hpx/util/remove_reference.hpp>
#include <hpx/util/coroutine/coroutine.hpp>
#include <hpx/runtime/threads/detail/tagged_thread_state.hpp>
/// \namespace hpx
///
/// The namespace \a hpx is the main namespace of the HPX library. All classes
/// functions and variables are defined inside this namespace.
namespace hpx
{
/// \cond NOINTERNAL
class error_code;
HPX_EXCEPTION_EXPORT extern error_code throws;
/// \namespace applier
///
/// The namespace \a applier contains all definitions needed for the
/// class \a hpx#applier#applier and its related functionality. This
/// namespace is part of the HPX core module.
namespace applier
{
class HPX_API_EXPORT applier;
/// The function \a get_applier returns a reference to the (thread
/// specific) applier instance.
HPX_API_EXPORT applier& get_applier();
HPX_API_EXPORT applier* get_applier_ptr();
}
namespace agas
{
struct HPX_API_EXPORT addressing_service;
enum service_mode
{
service_mode_invalid = -1,
service_mode_bootstrap = 0,
service_mode_hosted = 1
};
}
/// \namespace naming
///
/// The namespace \a naming contains all definitions needed for the AGAS
/// (Active Global Address Space) service.
namespace naming
{
typedef agas::addressing_service resolver_client;
struct HPX_API_EXPORT gid_type;
struct HPX_API_EXPORT id_type;
struct HPX_API_EXPORT address;
class HPX_API_EXPORT locality;
HPX_API_EXPORT resolver_client& get_agas_client();
}
///////////////////////////////////////////////////////////////////////////
/// \namespace parcelset
namespace parcelset
{
enum connection_type
{
connection_unknown = -1,
connection_tcpip = 0,
connection_shmem = 1,
connection_portals4 = 2,
connection_ibverbs = 3,
connection_mpi = 4,
connection_last
};
class HPX_API_EXPORT parcel;
class HPX_API_EXPORT parcelport;
class HPX_API_EXPORT parcelhandler;
namespace server
{
class parcelport_queue;
}
struct parcelhandler_queue_base;
namespace policies
{
struct global_parcelhandler_queue;
typedef global_parcelhandler_queue parcelhandler_queue;
struct message_handler;
}
HPX_API_EXPORT std::string get_connection_type_name(connection_type);
HPX_API_EXPORT connection_type get_connection_type_from_name(std::string const&);
HPX_API_EXPORT policies::message_handler* get_message_handler(
parcelhandler* ph, char const* name, char const* type, std::size_t num,
std::size_t interval, naming::locality const& l, connection_type t,
error_code& ec = throws);
HPX_API_EXPORT void do_background_work();
}
/// \namespace threads
///
/// The namespace \a threadmanager contains all the definitions required
/// for the scheduling, execution and general management of \a
/// hpx#threadmanager#thread's.
namespace threads
{
namespace policies
{
struct scheduler_base;
#if defined(HPX_GLOBAL_SCHEDULER)
class HPX_EXPORT global_queue_scheduler;
#endif
#if defined(HPX_STATIC_PRIORITY_SCHEDULER)
template <typename Mutex = boost::mutex>
class HPX_API_EXPORT static_priority_queue_scheduler;
#endif
#if defined(HPX_ABP_SCHEDULER)
struct HPX_EXPORT abp_queue_scheduler;
#endif
#if defined(HPX_ABP_PRIORITY_SCHEDULER)
class HPX_EXPORT abp_priority_queue_scheduler;
#endif
template <typename Mutex = boost::mutex>
class HPX_EXPORT local_queue_scheduler;
template <typename Mutex = boost::mutex>
class HPX_EXPORT local_priority_queue_scheduler;
#if defined(HPX_HIERARCHY_SCHEDULER)
class HPX_EXPORT hierarchy_scheduler;
#endif
#if defined(HPX_PERIODIC_PRIORITY_SCHEDULER)
class HPX_EXPORT periodic_priority_scheduler;
#endif
class HPX_EXPORT callback_notifier;
// define the default scheduler to use
typedef local_priority_queue_scheduler<> queue_scheduler;
}
struct HPX_EXPORT threadmanager_base;
class HPX_EXPORT thread_data;
template <
typename SchedulingPolicy,
typename NotificationPolicy = threads::policies::callback_notifier>
class HPX_EXPORT threadmanager_impl;
/// \enum thread_state_enum
///
/// The \a thread_state_enum enumerator encodes the current state of a
/// \a thread instance
enum thread_state_enum
{
unknown = 0,
active = 1, /*!< thread is currently active (running,
has resources) */
pending = 2, /*!< thread is pending (ready to run, but
no hardware resource available) */
suspended = 3, /*!< thread has been suspended (waiting for
synchronization event, but still
known and under control of the
threadmanager) */
depleted = 4, /*!< thread has been depleted (deeply
suspended, it is not known to the
thread manager) */
terminated = 5, /*!< thread has been stopped an may be
garbage collected */
staged = 6 /*!< this is not a real thread state, but
allows to reference staged task descriptions,
which eventually will be converted into
thread objects */
};
/// \ cond NODETAIL
/// Please note that if you change the value of threads::terminated
/// above, you will need to adjust do_call(dummy<1> = 1) in
/// util/coroutine/detail/coroutine_impl.hpp as well.
/// \ endcond
/// \enum thread_priority
enum thread_priority
{
thread_priority_unknown = -1,
thread_priority_default = 0, ///< use default priority
thread_priority_low = 1, ///< low thread priority
thread_priority_normal = 2, ///< normal thread priority (default)
thread_priority_critical = 3 ///< high thread priority
};
typedef threads::detail::tagged_thread_state<thread_state_enum> thread_state;
HPX_API_EXPORT char const* get_thread_state_name(thread_state_enum state);
HPX_API_EXPORT char const* get_thread_priority_name(thread_priority priority);
/// \enum thread_state_ex_enum
///
/// The \a thread_state_ex_enum enumerator encodes the reason why a
/// thread is being restarted
enum thread_state_ex_enum
{
wait_unknown = -1,
wait_signaled = 0, ///< The thread has been signaled
wait_timeout = 1, ///< The thread has been reactivated after a timeout
wait_terminate = 2, ///< The thread needs to be terminated
wait_abort = 3 ///< The thread needs to be aborted
};
typedef threads::detail::tagged_thread_state<thread_state_ex_enum> thread_state_ex;
typedef thread_state_enum thread_function_type(thread_state_ex_enum);
/// \enum thread_stacksize
enum thread_stacksize
{
thread_stacksize_small = 1, ///< use small stack size
thread_stacksize_medium = 2, ///< use medium sized stack size
thread_stacksize_large = 3, ///< use large stack size
thread_stacksize_huge = 4, ///< use very large stack size
thread_stacksize_nostack = 5, ///< this thread does not suspend (does not need a stack)
thread_stacksize_default = thread_stacksize_small, ///< use default stack size
thread_stacksize_minimal = thread_stacksize_small, ///< use minimally possible stack size
thread_stacksize_maximal = thread_stacksize_huge, ///< use maximally possible stack size
};
///////////////////////////////////////////////////////////////////////
/// \ cond NODETAIL
namespace detail
{
template <typename CoroutineImpl> struct coroutine_allocator;
}
/// \ endcond
typedef util::coroutines::coroutine<
thread_function_type, detail::coroutine_allocator> coroutine_type;
typedef coroutine_type::thread_id_type thread_id_type;
typedef coroutine_type::self thread_self;
///////////////////////////////////////////////////////////////////////
/// \ cond NODETAIL
thread_id_type const invalid_thread_id =
reinterpret_cast<thread_id_type>(-1);
/// \ endcond
/// The function \a get_self returns a reference to the (OS thread
/// specific) self reference to the current PX thread.
HPX_API_EXPORT thread_self& get_self();
/// The function \a get_self_ptr returns a pointer to the (OS thread
/// specific) self reference to the current PX thread.
HPX_API_EXPORT thread_self* get_self_ptr();
/// The function \a get_ctx_ptr returns a pointer to the internal data
/// associated with each coroutine.
HPX_API_EXPORT thread_self::impl_type* get_ctx_ptr();
/// The function \a get_self_ptr_checked returns a pointer to the (OS
/// thread specific) self reference to the current HPX thread.
HPX_API_EXPORT thread_self* get_self_ptr_checked(error_code& ec = throws);
/// The function \a get_self_id returns the HPX thread id of the current
/// thread (or zero if the current thread is not a PX thread).
HPX_API_EXPORT thread_id_type get_self_id();
/// The function \a get_parent_id returns the HPX thread id of the
/// current's thread parent (or zero if the current thread is not a
/// PX thread).
///
/// \note This function will return a meaningful value only if the
/// code was compiled with HPX_THREAD_MAINTAIN_PARENT_REFERENCE
/// being defined.
HPX_API_EXPORT thread_id_type get_parent_id();
/// The function \a get_parent_phase returns the HPX phase of the
/// current's thread parent (or zero if the current thread is not a
/// PX thread).
///
/// \note This function will return a meaningful value only if the
/// code was compiled with HPX_THREAD_MAINTAIN_PARENT_REFERENCE
/// being defined.
HPX_API_EXPORT std::size_t get_parent_phase();
/// The function \a get_parent_locality_id returns the id of the locality of
/// the current's thread parent (or zero if the current thread is not a
/// PX thread).
///
/// \note This function will return a meaningful value only if the
/// code was compiled with HPX_THREAD_MAINTAIN_PARENT_REFERENCE
/// being defined.
HPX_API_EXPORT boost::uint32_t get_parent_locality_id();
/// The function \a get_self_component_id returns the lva of the
/// component the current thread is acting on
///
/// \note This function will return a meaningful value only if the
/// code was compiled with HPX_THREAD_MAINTAIN_TARGET_ADDRESS
/// being defined.
HPX_API_EXPORT boost::uint64_t get_self_component_id();
/// The function \a get_thread_manager returns a reference to the
/// current thread manager.
HPX_API_EXPORT threadmanager_base& get_thread_manager();
/// The function \a get_thread_count returns the number of currently
/// known threads.
///
/// \note If state == unknown this function will not only return the
/// number of currently existing threads, but will add the number
/// of registered task descriptions (which have not been
/// converted into threads yet).
HPX_API_EXPORT boost::int64_t get_thread_count(
thread_state_enum state = unknown);
/// \copydoc get_thread_count(thread_state_enum state)
HPX_API_EXPORT boost::int64_t get_thread_count(
thread_priority priority, thread_state_enum state = unknown);
}
/// \namespace actions
///
/// The namespace \a actions contains all definitions needed for the
/// class \a hpx#action_manager#action_manager and its related
/// functionality. This namespace is part of the HPX core module.
namespace actions
{
struct HPX_API_EXPORT base_action;
typedef boost::shared_ptr<base_action> action_type;
class HPX_API_EXPORT continuation;
typedef boost::shared_ptr<continuation> continuation_type;
class HPX_API_EXPORT action_manager;
template <typename Component, typename Result,
typename Arguments, typename Derived>
struct action;
}
class HPX_API_EXPORT runtime;
class HPX_API_EXPORT thread;
/// A HPX runtime can be executed in two different modes: console mode
/// and worker mode.
enum runtime_mode
{
runtime_mode_invalid = -1,
runtime_mode_console = 0, ///< The runtime is the console locality
runtime_mode_worker = 1, ///< The runtime is a worker locality
runtime_mode_connect = 2, ///< The runtime is a worker locality
///< connecting late
runtime_mode_default = 3, ///< The runtime mode will be determined
///< based on the command line arguments
runtime_mode_last
};
/// Get the readable string representing the name of the given runtime_mode
/// constant.
HPX_API_EXPORT char const* get_runtime_mode_name(runtime_mode state);
HPX_API_EXPORT runtime_mode get_runtime_mode_from_name(std::string const& mode);
///////////////////////////////////////////////////////////////////////////
/// Retrieve the string value of a configuration entry as given by \p key.
HPX_API_EXPORT std::string get_config_entry(std::string const& key,
std::string const& dflt);
/// Retrieve the integer value of a configuration entry as given by \p key.
HPX_API_EXPORT std::string get_config_entry(std::string const& key,
std::size_t dflt);
///////////////////////////////////////////////////////////////////////////
template <
typename SchedulingPolicy,
typename NotificationPolicy = threads::policies::callback_notifier>
class HPX_API_EXPORT runtime_impl;
/// The function \a get_runtime returns a reference to the (thread
/// specific) runtime instance.
HPX_API_EXPORT runtime& get_runtime();
HPX_API_EXPORT runtime* get_runtime_ptr();
/// The function \a get_locality returns a reference to the locality
HPX_API_EXPORT naming::locality const& get_locality();
/// The function \a get_runtime_instance_number returns a unique number
/// associated with the runtime instance the current thread is running in.
HPX_API_EXPORT std::size_t get_runtime_instance_number();
HPX_API_EXPORT void report_error(std::size_t num_thread
, boost::exception_ptr const& e);
HPX_API_EXPORT void report_error(boost::exception_ptr const& e);
/// Register a function to be called during system shutdown
HPX_API_EXPORT bool register_on_exit(HPX_STD_FUNCTION<void()> const&);
enum logging_destination
{
destination_hpx = 0,
destination_timing = 1,
destination_agas = 2,
destination_app = 3
};
/// \namespace components
namespace components
{
enum factory_state_enum
{
factory_enabled = 0,
factory_disabled = 1,
factory_check = 2
};
/// \ cond NODETAIL
namespace detail
{
struct this_type {};
struct fixed_component_tag {};
struct simple_component_tag {};
struct managed_component_tag {};
}
/// \ endcond
///////////////////////////////////////////////////////////////////////
typedef boost::int32_t component_type;
enum component_enum_type
{
component_invalid = -1,
// Runtime support component (provides system services such as
// component creation, etc). One per locality.
component_runtime_support = 0,
// Pseudo-component for direct access to local virtual memory.
component_memory = 1,
// Generic memory blocks.
component_memory_block = 2,
// Base component for LCOs that do not produce a value.
component_base_lco = 3,
// Base component for LCOs that do produce values.
component_base_lco_with_value = 4,
// Synchronization barrier LCO.
component_barrier = ((5 << 16) | component_base_lco),
// An LCO representing a value which may not have been computed yet.
component_promise = ((6 << 16) | component_base_lco_with_value),
// AGAS locality services.
component_agas_locality_namespace = 7,
// AGAS primary address resolution services.
component_agas_primary_namespace = 8,
// AGAS global type system.
component_agas_component_namespace = 9,
// AGAS symbolic naming services.
component_agas_symbol_namespace = 10,
#if defined(HPX_HAVE_SODIUM)
// root CA, subordinate CA
component_root_certificate_authority = 11,
component_subordinate_certificate_authority = 12,
#endif
component_last,
component_first_dynamic = component_last,
// Force this enum type to be at least 32 bits.
component_upper_bound = 0x7fffffffL //-V112
};
///////////////////////////////////////////////////////////////////////
template <typename Component = detail::this_type>
class fixed_component_base;
template <typename Component>
class fixed_component;
template <typename Component = detail::this_type>
class abstract_simple_component_base;
template <typename Component = detail::this_type>
class simple_component_base;
template <typename Component>
class simple_component;
template <typename Component, typename Derived = detail::this_type>
class abstract_managed_component_base;
template <typename Component, typename Wrapper = detail::this_type,
typename CtorPolicy = traits::construct_without_back_ptr,
typename DtorPolicy = traits::managed_object_controls_lifetime>
class managed_component_base;
template <typename Component, typename Derived = detail::this_type>
class managed_component;
struct HPX_API_EXPORT component_factory_base;
template <typename Component>
struct component_factory;
class runtime_support;
class memory;
class memory_block;
namespace stubs
{
struct runtime_support;
struct memory;
struct memory_block;
}
namespace server
{
class HPX_API_EXPORT runtime_support;
class HPX_API_EXPORT memory;
class HPX_API_EXPORT memory_block;
}
HPX_EXPORT void console_logging(logging_destination dest,
std::size_t level, std::string const& msg);
HPX_EXPORT void cleanup_logging();
HPX_EXPORT void activate_logging();
}
HPX_EXPORT components::server::runtime_support* get_runtime_support_ptr();
/// \namespace lcos
namespace lcos
{
class base_lco;
template <typename Result, typename RemoteResult = Result>
class base_lco_with_value;
template <typename Result,
typename RemoteResult =
typename traits::promise_remote_result<Result>::type>
class promise;
template <typename Action,
typename Result = typename traits::promise_local_result<
typename Action::result_type>::type,
typename DirectExecute = typename Action::direct_execution>
class packaged_action;
template <typename Action,
typename Result = typename traits::promise_local_result<
typename Action::result_type>::type,
typename DirectExecute = typename Action::direct_execution>
class deferred_packaged_task;
template <typename Result>
class future;
template <typename ValueType>
struct object_semaphore;
namespace stubs
{
template <typename ValueType>
struct object_semaphore;
}
namespace server
{
template <typename ValueType>
struct object_semaphore;
}
}
/// \namespace util
namespace util
{
struct binary_filter;
class HPX_EXPORT section;
class HPX_EXPORT runtime_configuration;
class HPX_EXPORT io_service_pool;
/// \brief Expand INI variables in a string
HPX_API_EXPORT std::string expand(std::string const& expand);
/// \brief Expand INI variables in a string
HPX_API_EXPORT void expand(std::string& expand);
}
namespace performance_counters
{
struct counter_info;
}
///////////////////////////////////////////////////////////////////////////
// Launch policy for \a hpx::async
BOOST_SCOPED_ENUM_START(launch)
{
async = 0x01,
deferred = 0x02,
task = 0x04, // see N3632
sync = 0x08,
all = 0x0f // async | deferred | task | sync
};
BOOST_SCOPED_ENUM_END
inline bool
operator&(BOOST_SCOPED_ENUM(launch) lhs, BOOST_SCOPED_ENUM(launch) rhs)
{
return static_cast<int>(lhs) & static_cast<int>(rhs) ? true : false;
}
///////////////////////////////////////////////////////////////////////////
/// \brief Return the number of OS-threads running in the runtime instance
/// the current HPX-thread is associated with.
HPX_API_EXPORT std::size_t get_os_thread_count();
///////////////////////////////////////////////////////////////////////////
HPX_API_EXPORT bool is_scheduler_numa_sensitive();
///////////////////////////////////////////////////////////////////////////
HPX_API_EXPORT util::runtime_configuration const& get_config();
///////////////////////////////////////////////////////////////////////////
HPX_API_EXPORT hpx::util::io_service_pool* get_thread_pool(char const* name);
///////////////////////////////////////////////////////////////////////////
// Pulling important types into the main namespace
using naming::id_type;
using lcos::future;
using lcos::promise;
/// \endcond
}
namespace hpx
{
///////////////////////////////////////////////////////////////////////////
/// \brief Return the global id representing this locality
///
/// The function \a find_here() can be used to retrieve the global id
/// usable to refer to the current locality.
///
/// \param ec [in,out] this represents the error status on exit, if this
/// is pre-initialized to \a hpx#throws the function will throw
/// on error instead.
///
/// \note Generally, the id of a locality can be used for instance to
/// create new instances of components and to invoke plain actions
/// (global functions).
///
/// \returns The global id representing the locality this function has
/// been called on.
///
/// \note As long as \a ec is not pre-initialized to \a hpx::throws this
/// function doesn't throw but returns the result code using the
/// parameter \a ec. Otherwise it throws an instance of
/// hpx::exception.
///
/// \note This function will return meaningful results only if called
/// from an HPX-thread. It will return \a hpx::naming::invalid_id
/// otherwise.
///
/// \see \a hpx::find_all_localities(), \a hpx::find_locality()
HPX_API_EXPORT naming::id_type find_here(error_code& ec = throws);
///////////////////////////////////////////////////////////////////////////
/// \brief Return the global id representing the root locality
///
/// The function \a find_root_locality() can be used to retrieve the global
/// id usable to refer to the root locality. The root locality is the
/// locality where the main AGAS service is hosted.
///
/// \param ec [in,out] this represents the error status on exit, if this
/// is pre-initialized to \a hpx#throws the function will throw
/// on error instead.
///
/// \note Generally, the id of a locality can be used for instance to
/// create new instances of components and to invoke plain actions
/// (global functions).
///
/// \returns The global id representing the root locality for this
/// application.
///
/// \note As long as \a ec is not pre-initialized to \a hpx::throws this
/// function doesn't throw but returns the result code using the
/// parameter \a ec. Otherwise it throws an instance of
/// hpx::exception.
///
/// \note This function will return meaningful results only if called
/// from an HPX-thread. It will return \a hpx::naming::invalid_id
/// otherwise.
///
/// \see \a hpx::find_all_localities(), \a hpx::find_locality()
HPX_API_EXPORT naming::id_type find_root_locality(error_code& ec = throws);
///////////////////////////////////////////////////////////////////////////
/// \brief Return the list of global ids representing all localities
/// available to this application.
///
/// The function \a find_all_localities() can be used to retrieve the
/// global ids of all localities currently available to this application.
///
/// \param ec [in,out] this represents the error status on exit, if this
/// is pre-initialized to \a hpx#throws the function will throw
/// on error instead.
///
/// \note Generally, the id of a locality can be used for instance to
/// create new instances of components and to invoke plain actions
/// (global functions).
///
/// \returns The global ids representing the localities currently
/// available to this application.
///
/// \note As long as \a ec is not pre-initialized to \a hpx::throws this
/// function doesn't throw but returns the result code using the
/// parameter \a ec. Otherwise it throws an instance of
/// hpx::exception.
///
/// \note This function will return meaningful results only if called
/// from an HPX-thread. It will return an empty vector otherwise.
///
/// \see \a hpx::find_here(), \a hpx::find_locality()
HPX_API_EXPORT std::vector<naming::id_type> find_all_localities(
error_code& ec = throws);
///////////////////////////////////////////////////////////////////////////
/// \brief Return the list of global ids representing all localities
/// available to this application which support the given component
/// type.
///
/// The function \a find_all_localities() can be used to retrieve the
/// global ids of all localities currently available to this application
/// which support the creation of instances of the given component type.
///
/// \note Generally, the id of a locality can be used for instance to
/// create new instances of components and to invoke plain actions
/// (global functions).
///
/// \param type [in] The type of the components for which the function should
/// return the available localities.
/// \param ec [in,out] this represents the error status on exit, if this
/// is pre-initialized to \a hpx#throws the function will throw
/// on error instead.
///
/// \returns The global ids representing the localities currently
/// available to this application which support the creation of
/// instances of the given component type. If no localities
/// supporting the given component type are currently available,
/// this function will return an empty vector.
///
/// \note As long as \a ec is not pre-initialized to \a hpx::throws this
/// function doesn't throw but returns the result code using the
/// parameter \a ec. Otherwise it throws an instance of
/// hpx::exception.
///
/// \note This function will return meaningful results only if called
/// from an HPX-thread. It will return an empty vector otherwise.
///
/// \see \a hpx::find_here(), \a hpx::find_locality()
HPX_API_EXPORT std::vector<naming::id_type> find_all_localities(
components::component_type type, error_code& ec = throws);
/// \brief Return the list of locality ids of remote localities supporting
/// the given component type. By default this function will return
/// the list of all remote localities (all but the current locality).
///
/// The function \a find_remote_localities() can be used to retrieve the
/// global ids of all remote localities currently available to this
/// application (i.e. all localities except the current one).
///
/// \param ec [in,out] this represents the error status on exit, if this
/// is pre-initialized to \a hpx#throws the function will throw
/// on error instead.
///
/// \note Generally, the id of a locality can be used for instance to
/// create new instances of components and to invoke plain actions
/// (global functions).
///
/// \returns The global ids representing the remote localities currently
/// available to this application.
///
/// \note As long as \a ec is not pre-initialized to \a hpx::throws this
/// function doesn't throw but returns the result code using the
/// parameter \a ec. Otherwise it throws an instance of
/// hpx::exception.
///
/// \note This function will return meaningful results only if called
/// from an HPX-thread. It will return an empty vector otherwise.
///
/// \see \a hpx::find_here(), \a hpx::find_locality()
HPX_API_EXPORT std::vector<naming::id_type> find_remote_localities(
error_code& ec = throws);
/// \brief Return the list of locality ids of remote localities supporting
/// the given component type. By default this function will return
/// the list of all remote localities (all but the current locality).
///
/// The function \a find_remote_localities() can be used to retrieve the
/// global ids of all remote localities currently available to this
/// application (i.e. all localities except the current one) which
/// support the creation of instances of the given component type.
///
/// \param type [in] The type of the components for which the function should
/// return the available remote localities.
/// \param ec [in,out] this represents the error status on exit, if this
/// is pre-initialized to \a hpx#throws the function will throw
/// on error instead.
///
/// \note Generally, the id of a locality can be used for instance to
/// create new instances of components and to invoke plain actions
/// (global functions).
///
/// \returns The global ids representing the remote localities currently
/// available to this application.
///
/// \note As long as \a ec is not pre-initialized to \a hpx::throws this
/// function doesn't throw but returns the result code using the
/// parameter \a ec. Otherwise it throws an instance of
/// hpx::exception.
///
/// \note This function will return meaningful results only if called
/// from an HPX-thread. It will return an empty vector otherwise.
///
/// \see \a hpx::find_here(), \a hpx::find_locality()
HPX_API_EXPORT std::vector<naming::id_type> find_remote_localities(
components::component_type type, error_code& ec = throws);
///////////////////////////////////////////////////////////////////////////
/// \brief Return the global id representing an arbitrary locality which
/// supports the given component type.
///
/// The function \a find_locality() can be used to retrieve the
/// global id of an arbitrary locality currently available to this
/// application which supports the creation of instances of the given
/// component type.
///
/// \note Generally, the id of a locality can be used for instance to
/// create new instances of components and to invoke plain actions
/// (global functions).
///
/// \param type [in] The type of the components for which the function should
/// return any available locality.
/// \param ec [in,out] this represents the error status on exit, if this
/// is pre-initialized to \a hpx#throws the function will throw
/// on error instead.
///
/// \returns The global id representing an arbitrary locality currently
/// available to this application which supports the creation of
/// instances of the given component type. If no locality
/// supporting the given component type is currently available,
/// this function will return \a hpx::naming::invalid_id.
///
/// \note As long as \a ec is not pre-initialized to \a hpx::throws this
/// function doesn't throw but returns the result code using the
/// parameter \a ec. Otherwise it throws an instance of
/// hpx::exception.
///
/// \note This function will return meaningful results only if called
/// from an HPX-thread. It will return \a hpx::naming::invalid_id
/// otherwise.
///
/// \see \a hpx::find_here(), \a hpx::find_all_localities()
HPX_API_EXPORT naming::id_type find_locality(components::component_type type,
error_code& ec = throws);
///////////////////////////////////////////////////////////////////////////
/// \brief Return the number of localities which are currently registered
/// for the running application.
///
/// The function \a get_num_localities returns the number of localities
/// currently connected to the console.
///
/// \note This function will return meaningful results only if called
/// from an HPX-thread. It will return 0 otherwise.
///
/// \note As long as \a ec is not pre-initialized to \a hpx::throws this
/// function doesn't throw but returns the result code using the
/// parameter \a ec. Otherwise it throws an instance of
/// hpx::exception.
///
/// \see \a hpx::find_all_localities_sync, \a hpx::get_num_localities
HPX_API_EXPORT boost::uint32_t get_num_localities_sync(error_code& ec = throws);
/// \brief Return the number of localities which were registered at startup
/// for the running application.
///
/// The function \a get_initial_num_localities returns the number of localities
/// which were connected to the console at application startup.
///
/// \note As long as \a ec is not pre-initialized to \a hpx::throws this
/// function doesn't throw but returns the result code using the
/// parameter \a ec. Otherwise it throws an instance of
/// hpx::exception.
///
/// \see \a hpx::find_all_localities, \a hpx::get_num_localities
HPX_API_EXPORT boost::uint32_t get_initial_num_localities();
///////////////////////////////////////////////////////////////////////////
/// \brief Asynchronously return the number of localities which are
/// currently registered for the running application.
///
/// The function \a get_num_localities asynchronously returns the
/// number of localities currently connected to the console. The returned
/// future represents the actual result.
///
/// \note This function will return meaningful results only if called
/// from an HPX-thread. It will return 0 otherwise.
///
/// \see \a hpx::find_all_localities, \a hpx::get_num_localities
HPX_API_EXPORT lcos::future<boost::uint32_t> get_num_localities();
/// \brief Return the number of localities which are currently registered
/// for the running application.
///
/// The function \a get_num_localities returns the number of localities
/// currently connected to the console which support the creation of the
/// given component type.
///
/// \param t The component type for which the number of connected
/// localities should be retrieved.
/// \param ec [in,out] this represents the error status on exit, if this
/// is pre-initialized to \a hpx#throws the function will throw
/// on error instead.
///
/// \note This function will return meaningful results only if called
/// from an HPX-thread. It will return 0 otherwise.
///
/// \note As long as \a ec is not pre-initialized to \a hpx::throws this
/// function doesn't throw but returns the result code using the
/// parameter \a ec. Otherwise it throws an instance of
/// hpx::exception.
///
/// \see \a hpx::find_all_localities, \a hpx::get_num_localities
HPX_API_EXPORT boost::uint32_t get_num_localities_sync(
components::component_type t, error_code& ec = throws);
/// \brief Asynchronously return the number of localities which are
/// currently registered for the running application.
///
/// The function \a get_num_localities asynchronously returns the
/// number of localities currently connected to the console which support
/// the creation of the given component type. The returned future represents
/// the actual result.
///
/// \param t The component type for which the number of connected
/// localities should be retrieved.
///
/// \note This function will return meaningful results only if called
/// from an HPX-thread. It will return 0 otherwise.
///
/// \see \a hpx::find_all_localities, \a hpx::get_num_localities
HPX_API_EXPORT lcos::future<boost::uint32_t> get_num_localities(
components::component_type t);
///////////////////////////////////////////////////////////////////////////
/// The type of a function which is registered to be executed as a
/// startup or pre-startup function.
typedef HPX_STD_FUNCTION<void()> startup_function_type;
///////////////////////////////////////////////////////////////////////////
/// \brief Add a function to be executed by a HPX thread before hpx_main
/// but guaranteed before any startup function is executed (system-wide).
///
/// Any of the functions registered with \a register_pre_startup_function
/// are guaranteed to be executed by an HPX thread before any of the
/// registered startup functions are executed (see
/// \a hpx::register_startup_function()).
///
/// \param f [in] The function to be registered to run by an HPX thread as
/// a pre-startup function.
///
/// \note If this function is called while the pre-startup functions are
/// being executed or after that point, it will raise a invalid_status
/// exception.
///
/// This function is one of the few API functions which can be called
/// before the runtime system has been fully initialized. It will
/// automatically stage the provided startup function to the runtime
/// system during its initialization (if necessary).
///
/// \see \a hpx::register_startup_function()
HPX_API_EXPORT void register_pre_startup_function(startup_function_type const& f);
///////////////////////////////////////////////////////////////////////////
/// \brief Add a function to be executed by a HPX thread before hpx_main
/// but guaranteed after any pre-startup function is executed (system-wide).
///
/// Any of the functions registered with \a register_startup_function
/// are guaranteed to be executed by an HPX thread after any of the
/// registered pre-startup functions are executed (see:
/// \a hpx::register_pre_startup_function()), but before \a hpx_main is
/// being called.
///
/// \param f [in] The function to be registered to run by an HPX thread as
/// a startup function.
///
/// \note If this function is called while the startup functions are
/// being executed or after that point, it will raise a invalid_status
/// exception.
///
/// This function is one of the few API functions which can be called
/// before the runtime system has been fully initialized. It will
/// automatically stage the provided startup function to the runtime
/// system during its initialization (if necessary).
///
/// \see \a hpx::register_pre_startup_function()
HPX_API_EXPORT void register_startup_function(startup_function_type const& f);
/// The type of a function which is registered to be executed as a
/// shutdown or pre-shutdown function.
typedef HPX_STD_FUNCTION<void()> shutdown_function_type;
/// \brief Add a function to be executed by a HPX thread during
/// \a hpx::finalize() but guaranteed before any shutdown function is
/// executed (system-wide)
///
/// Any of the functions registered with \a register_pre_shutdown_function
/// are guaranteed to be executed by an HPX thread during the execution of
/// \a hpx::finalize() before any of the registered shutdown functions are
/// executed (see: \a hpx::register_shutdown_function()).
///
/// \param f [in] The function to be registered to run by an HPX thread as
/// a pre-shutdown function.
///
/// \note If this function is called before the runtime system is
/// initialized, or while the pre-shutdown functions are
/// being executed, or after that point, it will raise a invalid_status
/// exception.
///
/// \see \a hpx::register_shutdown_function()
HPX_API_EXPORT void register_pre_shutdown_function(shutdown_function_type const& f);
/// \brief Add a function to be executed by a HPX thread during
/// \a hpx::finalize() but guaranteed after any pre-shutdown function is
/// executed (system-wide)
///
/// Any of the functions registered with \a register_shutdown_function
/// are guaranteed to be executed by an HPX thread during the execution of
/// \a hpx::finalize() after any of the registered pre-shutdown functions
/// are executed (see: \a hpx::register_pre_shutdown_function()).
///
/// \param f [in] The function to be registered to run by an HPX thread as
/// a shutdown function.
///
/// \note If this function is called before the runtime system is
/// initialized, or while the shutdown functions are
/// being executed, or after that point, it will raise a invalid_status
/// exception.
///
/// \see \a hpx::register_pre_shutdown_function()
HPX_API_EXPORT void register_shutdown_function(shutdown_function_type const& f);
///////////////////////////////////////////////////////////////////////////
/// \brief Return the number of the current OS-thread running in the
/// runtime instance the current HPX-thread is executed with.
///
/// This function returns the zero based index of the OS-thread which
/// executes the current HPX-thread.
///
/// \note The returned value is zero based and it's maximum value is
/// smaller than the overall number of OS-threads executed (as
/// returned by \a get_os_thread_count().
///
/// \note This function needs to be executed on a HPX-thread. It will
/// fail otherwise (it will return -1).
HPX_API_EXPORT std::size_t get_worker_thread_num();
///////////////////////////////////////////////////////////////////////////
/// \brief Return the number of the locality this function is being called
/// from.
///
/// This function returns the id of the current locality.
///
/// \param ec [in,out] this represents the error status on exit, if this
/// is pre-initialized to \a hpx#throws the function will throw
/// on error instead.
///
/// \note The returned value is zero based and it's maximum value is
/// smaller than the overall number of localities the current
/// application is running on (as returned by
/// \a get_num_localities()).
///
/// \note As long as \a ec is not pre-initialized to \a hpx::throws this
/// function doesn't throw but returns the result code using the
/// parameter \a ec. Otherwise it throws an instance of
/// hpx::exception.
///
/// \note This function needs to be executed on a HPX-thread. It will
/// fail otherwise (it will return -1).
HPX_API_EXPORT boost::uint32_t get_locality_id(error_code& ec = throws);
///////////////////////////////////////////////////////////////////////////
/// \brief Test whether the runtime system is currently running.
///
/// This function returns whether the runtime system is currently running
/// or not, e.g. whether the current state of the runtime system is
/// \a hpx::runtime::running
///
/// \note This function needs to be executed on a HPX-thread. It will
/// return false otherwise.
HPX_API_EXPORT bool is_running();
///////////////////////////////////////////////////////////////////////////
/// \brief Return the name of the calling thread.
///
/// This function returns the name of the calling thread. This name uniquely
/// identifies the thread in the context of HPX. If the function is called
/// while no HPX runtime system is active, the result will be "<unknown>".
HPX_API_EXPORT std::string get_thread_name();
///////////////////////////////////////////////////////////////////////////
/// \brief Return the number of worker OS- threads used to execute HPX
/// threads
///
/// This function returns the number of OS-threads used to execute HPX
/// threads. If the function is called while no HPX runtime system is active,
/// it will return zero.
HPX_API_EXPORT std::size_t get_num_worker_threads();
///////////////////////////////////////////////////////////////////////////
/// \brief Return the system uptime measure on the thread executing this call.
///
/// This function returns the system uptime measured in nanoseconds for the
/// thread executing this call. If the function is called while no HPX
/// runtime system is active, it will return zero.
HPX_API_EXPORT boost::uint64_t get_system_uptime();
///////////////////////////////////////////////////////////////////////////
/// \brief Return the id of the locality where the object referenced by the
/// given id is currently located on
///
/// The function hpx::get_colocation_id() returns the id of the locality
/// where the given object is currently located.
///
/// \param id [in] The id of the object to locate.
/// \param ec [in,out] this represents the error status on exit, if this
/// is pre-initialized to \a hpx#throws the function will throw
/// on error instead.
///
/// \note As long as \a ec is not pre-initialized to \a hpx::throws this
/// function doesn't throw but returns the result code using the
/// parameter \a ec. Otherwise it throws an instance of
/// hpx::exception.
///
/// \see \a hpx::get_colocation_id()
HPX_API_EXPORT naming::id_type get_colocation_id_sync(
naming::id_type const& id, error_code& ec = throws);
/// \brief Asynchronously return the id of the locality where the object
/// referenced by the given id is currently located on
///
/// \see \a hpx::get_colocation_id_sync()
HPX_API_EXPORT lcos::future<naming::id_type> get_colocation_id(
naming::id_type const& id);
///////////////////////////////////////////////////////////////////////////
/// \brief Return the name of the referenced locality.
///
/// This function returns a future referring to the name for the locality
/// of the given id.
///
/// \param id [in] The global id of the locality for which the name should
/// be retrievd
///
/// \returns This function returns the name for the locality of the given
/// id. The name is retrieved from the underlying networking layer
/// and may be different for different parcelports.
///
HPX_API_EXPORT future<std::string> get_locality_name(
naming::id_type const& id);
///////////////////////////////////////////////////////////////////////////
/// \brief Trigger the LCO referenced by the given id
///
/// \param id [in] this represents the id of the LCO which should be
/// triggered.
HPX_API_EXPORT void trigger_lco_event(naming::id_type const& id);
/// \brief Set the result value for the LCO referenced by the given id
///
/// \param id [in] this represents the id of the LCO which should
/// receive the given value.
/// \param t [in] this is the value which should be sent to the LCO.
template <typename T>
void set_lco_value(naming::id_type const& id, BOOST_FWD_REF(T) t);
/// \brief Set the error state for the LCO referenced by the given id
///
/// \param id [in] this represents the id of the LCO which should
/// eceive the error value.
/// \param e [in] this is the error value which should be sent to
/// the LCO.
HPX_API_EXPORT void set_lco_error(naming::id_type const& id,
boost::exception_ptr const& e);
/// \copydoc hpx::set_lco_error(naming::id_type const& id, boost::exception_ptr const& e)
HPX_API_EXPORT void set_lco_error(naming::id_type const& id,
BOOST_RV_REF(boost::exception_ptr) e);
///////////////////////////////////////////////////////////////////////////
/// \brief Start all active performance counters, optionally naming the
/// section of code
///
/// \param ec [in,out] this represents the error status on exit, if this
/// is pre-initialized to \a hpx#throws the function will throw
/// on error instead.
///
/// \note As long as \a ec is not pre-initialized to \a hpx::throws this
/// function doesn't throw but returns the result code using the
/// parameter \a ec. Otherwise it throws an instance of
/// hpx::exception.
///
/// \note The active counters are those which have been specified on
/// the command line while executing the application (see command
/// line option \--hpx:print-counter)
HPX_API_EXPORT void start_active_counters(error_code& ec = throws);
/// \brief Resets all active performance counters.
///
/// \param ec [in,out] this represents the error status on exit, if this
/// is pre-initialized to \a hpx#throws the function will throw
/// on error instead.
///
/// \note As long as \a ec is not pre-initialized to \a hpx::throws this
/// function doesn't throw but returns the result code using the
/// parameter \a ec. Otherwise it throws an instance of
/// hpx::exception.
///
/// \note The active counters are those which have been specified on
/// the command line while executing the application (see command
/// line option \--hpx:print-counter)
HPX_API_EXPORT void reset_active_counters(error_code& ec = throws);
/// \brief Stop all active performance counters.
///
/// \param ec [in,out] this represents the error status on exit, if this
/// is pre-initialized to \a hpx#throws the function will throw
/// on error instead.
///
/// \note As long as \a ec is not pre-initialized to \a hpx::throws this
/// function doesn't throw but returns the result code using the
/// parameter \a ec. Otherwise it throws an instance of
/// hpx::exception.
///
/// \note The active counters are those which have been specified on
/// the command line while executing the application (see command
/// line option \--hpx:print-counter)
HPX_API_EXPORT void stop_active_counters(error_code& ec = throws);
/// \brief Evaluate and output all active performance counters, optionally
/// naming the point in code marked by this function.
///
/// \param reset [in] this is an optional flag allowing to reset
/// the counter value after it has been evaluated.
/// \param description [in] this is an optional value naming the point in
/// the code marked by the call to this function.
/// \param ec [in,out] this represents the error status on exit, if this
/// is pre-initialized to \a hpx#throws the function will throw
/// on error instead.
///
/// \note As long as \a ec is not pre-initialized to \a hpx::throws this
/// function doesn't throw but returns the result code using the
/// parameter \a ec. Otherwise it throws an instance of
/// hpx::exception.
///
/// \note The output generated by this function is redirected to the
/// destination specified by the corresponding command line
/// options (see \--hpx:print-counter-destination).
///
/// \note The active counters are those which have been specified on
/// the command line while executing the application (see command
/// line option \--hpx:print-counter)
HPX_API_EXPORT void evaluate_active_counters(bool reset = false,
char const* description = 0, error_code& ec = throws);
///////////////////////////////////////////////////////////////////////////
/// \brief Create an instance of a message handler plugin
///
/// The function hpx::create_message_handler() creates an instance of a
/// message handler plugin based on the parameters specified.
///
/// \param message_handler_type
/// \param action
/// \param pp
/// \param num_messages
/// \param interval
/// \param ec [in,out] this represents the error status on exit, if this
/// is pre-initialized to \a hpx#throws the function will throw
/// on error instead.
///
/// \note As long as \a ec is not pre-initialized to \a hpx::throws this
/// function doesn't throw but returns the result code using the
/// parameter \a ec. Otherwise it throws an instance of
/// hpx::exception.
HPX_API_EXPORT parcelset::policies::message_handler* create_message_handler(
char const* message_handler_type, char const* action,
parcelset::parcelport* pp, std::size_t num_messages,
std::size_t interval, error_code& ec = throws);
///////////////////////////////////////////////////////////////////////////
/// \brief Create an instance of a binary filter plugin
///
/// \param ec [in,out] this represents the error status on exit, if this
/// is pre-initialized to \a hpx#throws the function will throw
/// on error instead.
///
/// \note As long as \a ec is not pre-initialized to \a hpx::throws this
/// function doesn't throw but returns the result code using the
/// parameter \a ec. Otherwise it throws an instance of
/// hpx::exception.
HPX_API_EXPORT util::binary_filter* create_binary_filter(
char const* binary_filter_type, bool compress,
util::binary_filter* next_filter = 0, error_code& ec = throws);
#if defined(HPX_HAVE_SODIUM)
namespace components { namespace security
{
class certificate;
class certificate_signing_request;
class parcel_suffix;
class hash;
template <typename T> class signed_type;
typedef signed_type<certificate> signed_certificate;
typedef signed_type<certificate_signing_request>
signed_certificate_signing_request;
typedef signed_type<parcel_suffix> signed_parcel_suffix;
}}
#if defined(HPX_HAVE_SECURITY)
/// \brief Return the certificate for this locality
///
/// \returns This function returns the signed certificate for this locality.
HPX_API_EXPORT components::security::signed_certificate const&
get_locality_certificate(error_code& ec = throws);
/// \brief Return the certificate for the given locality
///
/// \param id The id representing the locality for which to retrieve
/// the signed certificate.
///
/// \returns This function returns the signed certificate for the locality
/// identified by the parameter \a id.
HPX_API_EXPORT components::security::signed_certificate const&
get_locality_certificate(boost::uint32_t locality_id, error_code& ec = throws);
/// \brief Add the given certificate to the certificate store of this locality.
///
/// \param cert The certificate to add to the certificate store of this
/// locality
HPX_API_EXPORT void add_locality_certificate(
components::security::signed_certificate const& cert,
error_code& ec = throws);
#endif
#endif
}
#include <hpx/lcos/async_fwd.hpp>
#endif
| 43.167491 | 105 | 0.606447 | andreasbuhr |
c181d6aba3a40cbc3958e0b7b480daf7ef966266 | 2,158 | cpp | C++ | NodesKLevelFar.cpp | aak-301/data-structure | 13d63e408a0001ceb06e2937ab8fcc3f176db78d | [
"Apache-2.0"
] | null | null | null | NodesKLevelFar.cpp | aak-301/data-structure | 13d63e408a0001ceb06e2937ab8fcc3f176db78d | [
"Apache-2.0"
] | null | null | null | NodesKLevelFar.cpp | aak-301/data-structure | 13d63e408a0001ceb06e2937ab8fcc3f176db78d | [
"Apache-2.0"
] | null | null | null | // https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/submissions/
#include<iostream>
#include<vector>
using namespace std;
struct TreeNode{
int val;
struct TreeNode *left, *right;
TreeNode(int x){
val = x;
left=NULL;
right=NULL;
}
};
bool findUntil(TreeNode* root, TreeNode* target,vector<TreeNode* >& v){
if(root == NULL) return false;
if(root->val == target->val) {
v.push_back(root);
return true;
}
bool b = findUntil(root->left,target,v);
if(b){
v.push_back(root);
return true;
}
bool c = findUntil(root->right,target,v);
if(c){
v.push_back(root);
return true;
}
return false;
}
vector<TreeNode*> findNode(TreeNode* root, TreeNode* target){
vector<TreeNode* > v;
findUntil(root, target, v);
return v;
}
void GetNodes(TreeNode* root,int k, TreeNode* p, vector<int>& store){
if(root==NULL || root==p || k<0) return;
if(k==0){
store.push_back(root->val);
}
GetNodes(root->left, k-1, p, store);
GetNodes(root->right, k-1, p, store);
}
vector<int> distanceK(TreeNode* root, TreeNode* target, int k) {
vector<TreeNode* > v = findNode(root, target);
int n = v.size();
vector<int> store;
for(int i=0;i<n;i++){
GetNodes(v[i],k-i, i==0?NULL:v[i-1], store);
}
return store;
}
int main(){
/*
3
/ \
5 1
/ \ / \
6 2 0 8
/ \
7 4
*/
struct TreeNode* root = new TreeNode(3);
root->left = new TreeNode(5);
root->right = new TreeNode(1);
root->left->left = new TreeNode(6);
root->left->right = new TreeNode(2);
root->right->left = new TreeNode(0);
root->right->right = new TreeNode(8);
root->left->right->left = new TreeNode(7);
root->left->right->right = new TreeNode(4);
vector<int> v = distanceK(root, root->left->right->right,2);
for(int e : v) cout<<e<<" ";
} | 28.025974 | 82 | 0.517609 | aak-301 |
c182d6effc1e8cac25e61efd8ea0c169dfbca65e | 8,529 | cpp | C++ | Source/World/Item.cpp | Andres6936/TinyRogue | 9198347fd5080ac1d6cf21f0da6266202594cf54 | [
"MIT"
] | 10 | 2017-12-04T14:15:53.000Z | 2021-07-28T06:17:56.000Z | Source/World/Item.cpp | Andres6936/TinyRogue | 9198347fd5080ac1d6cf21f0da6266202594cf54 | [
"MIT"
] | null | null | null | Source/World/Item.cpp | Andres6936/TinyRogue | 9198347fd5080ac1d6cf21f0da6266202594cf54 | [
"MIT"
] | 1 | 2018-01-21T16:15:39.000Z | 2018-01-21T16:15:39.000Z | #include "Item.hpp"
#include "ActorPlayer.hpp" // REMOVE:
#include "../Graphics/Color.hpp"
#include "../Utility/Rng.hpp"
#include "../Utility/Utility.hpp"
// Items
#include "Items/Potion.hpp"
#include "Items/Scroll.hpp"
#include "Items/Weapon.hpp"
#include "Items/Armor.hpp"
#include "Items/Ring.hpp"
#include "Items/Stick.hpp"
#include <sstream>
#include <cassert>
namespace
{
/* extern.c */
std::vector<Item::Info> things =
{
{ L"potion", 26, L'!' },
{ L"sroll", 36, L'?' },
{ L"food", 16, L'%' },
{ L"weapon", 7, L')' },
{ L"armor", 7, L'[' },
{ L"ring", 4, L'=' },
{ L"stick", 4, L'/' },
{ L"gold", 0, L'*' },
{ L"amulet", 0, L'"' },
};
const std::wstring fruit = L"slime-mold";
}
int Item::Group = 2;
Item::Item(ItemType type)
: Entity(things[static_cast<int>(type)].worth) // glyph
, type(type)
{
setColor(Color::Yellow);
}
std::wstring Item::getAName() const
{
std::wostringstream oss;
switch (type)
{
case ItemType::Food:
if (which == 1)
{
if (count == 1)
oss << (isVowel(fruit) ? L"an " : L"a ") << fruit;
else
oss << count << L" " << fruit << L"s";
}
else
{
if (count == 1)
oss << L"some food";
else
oss << count << L" rations of food";
}
break;
case ItemType::Gold:
oss << count << L" gold pieces";
break;
case ItemType::Amulet:
oss << L"the Amulet of Yendor";
break;
}
return oss.str();
}
ItemType Item::getType() const
{
return type;
}
bool Item::hasFlag(Flags flag) const
{
return flags & flag;
}
void Item::addFlag(Flags flag)
{
flags |= flag;
}
void Item::removeFlag(Flags flag)
{
flags &= ~flag;
}
void Item::setCount(int count)
{
this->count = count;
}
int Item::getCount() const
{
return count;
}
void Item::addCount(int count)
{
assert(count > 0);
this->count += count;
}
void Item::reduceCount(int count)
{
assert(count > 0);
this->count -= count;
}
int Item::getWhich() const
{
return which;
}
int Item::getGroup() const
{
return group;
}
int Item::getLaunch() const
{
return -1;
}
std::string Item::getDamage() const
{
return "";
}
std::string Item::getDamageThrown() const
{
return "";
}
int Item::getHitPlus() const
{
return 0;
}
int Item::getDamagePlus() const
{
return 0;
}
int Item::getArmor() const
{
return 0;
}
int Item::getRingPower() const
{
return 0;
}
bool Item::isSame(ItemType type, int which) const
{
return this->type == type && this->which == which;
}
bool Item::isSame(Item& item) const
{
return type == item.type && which == item.which;
}
bool Item::use(Actor& actor)
{
if (type == ItemType::Food)
{
eat(actor);
playSound(SoundID::Eat);
}
return true;
}
void Item::enchant()
{
// Do nothing by default
}
void Item::degrade()
{
// Do nothing by default
}
int Item::ringEat() const
{
return 0;
}
void Item::eat(Actor& actor)
{
// HACK: Avoid dynamic_cast
dynamic_cast<ActorPlayer&>(actor).eatFood();
if (which == 1)
message(L"my, that was a yummy " + fruit + L".", Color::White);
else
{
if (randomInt(100) > 70)
{
message(actor.chooseStr(L"bummer", L"yuk") + L", this food tastes awful.", Color::White);
actor.gainExp(1);
}
else
message(actor.chooseStr(L"oh, wow", L"yum") + L", that tasted good.", Color::White);
}
--count;
}
void Item::identify()
{
addFlag(Item::IsKnow);
}
bool Item::isIdentified() const
{
switch (type)
{
case ItemType::Weapon:
case ItemType::Armor:
case ItemType::Ring:
case ItemType::Stick:
return hasFlag(Item::IsKnow);
}
return true;
}
bool Item::isMagic() const
{
/* potion.c */
// is_magic: Returns true if an object radiates magic
switch (type)
{
case ItemType::Potion:
case ItemType::Scroll:
case ItemType::Stick: // TODO: empty staff or wand?
case ItemType::Ring:
case ItemType::Amulet:
return true;
case ItemType::Weapon:
return getHitPlus() > 0 || getDamagePlus() > 0;
case ItemType::Armor:
return hasFlag(Item::IsProtected) || getArmor() < 0;
}
return false;
}
bool Item::dropCheck(Actor& actor) const
{
/* things.c */
// dropcheck: Do special checks for dropping or unweilding|unwearing|unringing
for (int i = 0; i < Actor::MaxSlot; ++i)
{
auto slot = static_cast<Actor::Slot>(i);
if (actor.getEquipment(slot) == this)
{
if (hasFlag(Item::IsCursed))
{
Item* item = actor.getEquipment(slot);
// message(L"you can't. It appears to be cursed.", Color::White);
message(L"you can't. Your " + item->getName() + L" appears to be cursed.", Color::White);
return false;
}
else
actor.setEquipment(slot, nullptr); // unequip
break;
}
}
return true;
}
void Item::repaint()
{
setChar(things[static_cast<int>(type)].worth);
setColor(Color::Yellow);
}
void Item::initItems(Rng& rng)
{
Potion::initColors(rng);
Scroll::initNames(rng);
Stick::initMaterials(rng);
Ring::initStones(rng);
// Group = 2;
}
Item::Ptr Item::detachOne()
{
assert(count > 1);
count -= 1;
// Potion, scroll, food
auto item = createItem(type, which);
item->count = 1;
item->flags = flags;
return item;
}
Item::Ptr Item::createItem(ItemType type, int which)
{
Item::Ptr item = nullptr;
switch (type)
{
case ItemType::Potion:
item = std::make_unique<Potion>(type);
item->which = which;
break;
case ItemType::Scroll:
item = std::make_unique<Scroll>(type);
item->which = which;
break;
case ItemType::Food:
item = std::make_unique<Item>(type);
item->which = which;
break;
case ItemType::Weapon:
item = Weapon::createWeapon(which);
break;
case ItemType::Armor:
item = Armor::createArmor(which);
break;
case ItemType::Ring:
item = Ring::createRing(which);
break;
case ItemType::Stick:
item = Stick::createStick(which);
break;
}
return item;
}
Item::Ptr Item::createItem(Rng& rng, int& noFood)
{
/* things.c */
// new_thing: Return a new thing
auto type = noFood > 3 ? ItemType::Food : static_cast<ItemType>(pickOne(rng, things));
Item::Ptr item = nullptr;
switch (type)
{
case ItemType::Potion:
item = std::make_unique<Potion>(type);
item->which = Potion::pickOne(rng);
break;
case ItemType::Scroll:
item = std::make_unique<Scroll>(type);
item->which = Scroll::pickOne(rng);
break;
case ItemType::Food:
noFood = 0;
item = std::make_unique<Item>(type);
item->which = rng.getInt(10) > 0 ? 0 : 1;
break;
case ItemType::Weapon:
{
int r = rng.getInt(100);
int hitPlus = 0;
if (r < 20) // 10 > 20 (10% > 20%)
hitPlus -= rng.getInt(3) + 1;
else if (r < 35) // 15 > 35 (5% > 15%)
hitPlus += rng.getInt(3) + 1;
item = Weapon::createWeapon(Weapon::pickOne(rng), hitPlus);
}
break;
case ItemType::Armor:
{
int r = rng.getInt(100);
int ac = 0;
if (r < 25) // 20 > 25 (20% > 25%)
ac += rng.getInt(3) + 1;
else if (r < 43) // 28 > 43 (8% > 18%)
ac -= rng.getInt(3) + 1;
item = Armor::createArmor(Armor::pickOne(rng), ac);
}
break;
case ItemType::Ring:
{
int power = 0;
int which = Ring::pickOne(rng);
switch (which)
{
case Ring::Protect:
case Ring::AddStrength:
case Ring::AddHit:
case Ring::AddDamage:
if ((power = rng.getInt(3)) == 0)
power = -1;
break;
case Ring::Aggravate:
case Ring::Teleport:
power = -1;
break;
}
item = Ring::createRing(which, power);
}
break;
case ItemType::Stick:
item = Stick::createStick(Stick::pickOne(rng));
break;
}
return item;
}
Item::Ptr Item::createGold(int value)
{
auto item = std::make_unique<Item>(ItemType::Gold);
item->count = value;
item->addFlag(Item::IsMany);
item->group = 1; // GOLDGRP 1
return item;
}
std::wstring Item::getFruit()
{
return fruit;
}
wchar_t Item::getRandomChar()
{
// TODO: Add stairs
return things[randomInt(things.size())].worth;
}
int Item::pickOne(Rng& rng, std::vector<Info>& items)
{
int totalProb = 0;
for (const auto& item : items)
totalProb += item.prob;
int i = rng.getInt(totalProb); // 100
for (std::size_t j = 0; j < items.size(); ++j)
{
i -= items[j].prob;
if (i < 0)
return j;
}
return -1; // error
}
| 17.126506 | 95 | 0.584594 | Andres6936 |
c183d7754048099fca5672cd8a54e37c7aedb5a0 | 505 | cpp | C++ | main.cpp | sandsmark/epubreader | 1bc70119a6074d14fb9e5ff219097e058ef96442 | [
"BSD-3-Clause"
] | 19 | 2016-11-27T03:48:13.000Z | 2021-12-17T01:51:14.000Z | main.cpp | sandsmark/epubreader | 1bc70119a6074d14fb9e5ff219097e058ef96442 | [
"BSD-3-Clause"
] | 4 | 2017-03-22T16:31:53.000Z | 2022-01-25T01:43:42.000Z | main.cpp | sandsmark/epubreader | 1bc70119a6074d14fb9e5ff219097e058ef96442 | [
"BSD-3-Clause"
] | 5 | 2017-03-21T17:53:58.000Z | 2021-04-01T08:43:11.000Z | #include "widget.h"
#include <QApplication>
#include <QDebug>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
a.setQuitOnLastWindowClosed(true);
Widget *w = new Widget;
w->setAttribute(Qt::WA_DeleteOnClose);
if (argc > 1) {
if (!w->loadFile(argv[1])) {
qWarning() << "Failed to load" << argv[1];
return 1;
}
} else {
if (!w->loadFile()) {
return 1;
}
}
w->show();
return a.exec();
}
| 19.423077 | 54 | 0.512871 | sandsmark |
c184149a9d38d0b872508529e4b4edbe5bcbc60e | 1,277 | cc | C++ | paddle/fluid/platform/device/ipu/ipu_info.cc | zmxdream/Paddle | 04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c | [
"Apache-2.0"
] | 2 | 2021-11-12T11:31:12.000Z | 2021-12-05T10:30:28.000Z | paddle/fluid/platform/device/ipu/ipu_info.cc | zmxdream/Paddle | 04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c | [
"Apache-2.0"
] | 1 | 2021-11-01T06:28:16.000Z | 2021-11-01T06:28:16.000Z | paddle/fluid/platform/device/ipu/ipu_info.cc | zmxdream/Paddle | 04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c | [
"Apache-2.0"
] | 5 | 2021-12-10T11:20:06.000Z | 2022-02-18T05:18:12.000Z | /* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "paddle/fluid/platform/device/ipu/ipu_info.h"
#include "paddle/fluid/platform/device/ipu/ipu_backend.h"
namespace paddle {
namespace platform {
//! Get a list of device ids from environment variable or use all.
std::vector<int> GetSelectedIPUDevices() {
std::shared_ptr<platform::ipu::IpuBackend> ipu_backend =
platform::ipu::IpuBackend::GetInstance();
return ipu_backend->GetDeviceIds();
}
//! Get the total number of IPU devices in system.
int GetIPUDeviceCount() {
std::shared_ptr<platform::ipu::IpuBackend> ipu_backend =
platform::ipu::IpuBackend::GetInstance();
return ipu_backend->GetNumDevices();
}
} // namespace platform
} // namespace paddle
| 38.69697 | 72 | 0.762725 | zmxdream |
c1845d8cbb1d6e4ba2ed377596564af0620ae37d | 905 | cpp | C++ | migration_enclave/untrusted/TcpServer.cpp | SSGAalto/sgx-migration | 4dd8c4d9d9ffac1155a3161e9a0321b0f4a4377a | [
"Apache-2.0"
] | 14 | 2018-11-28T13:45:03.000Z | 2022-02-10T02:22:49.000Z | migration_enclave/untrusted/TcpServer.cpp | SSGAalto/sgx-migration | 4dd8c4d9d9ffac1155a3161e9a0321b0f4a4377a | [
"Apache-2.0"
] | 4 | 2020-02-26T07:41:18.000Z | 2021-06-15T09:58:45.000Z | migration_enclave/untrusted/TcpServer.cpp | SSGAalto/sgx-migration | 4dd8c4d9d9ffac1155a3161e9a0321b0f4a4377a | [
"Apache-2.0"
] | 6 | 2018-11-28T13:54:39.000Z | 2021-01-20T14:41:54.000Z | /*
* TcpServer.cpp
*
* Created on: Aug 22, 2017
*/
#include "TcpServer.h"
namespace network{
TcpServer::TcpServer(boost::asio::io_service& io_service, unsigned short port,
std::function<int(TcpConnection *conn, message_t *msg)> callback)
: acceptor_(io_service, tcp::endpoint(tcp::v4(), port)),
callback(callback) {
start_accept();
}
void TcpServer::start_accept() {
TcpConnection::ptr new_connection = TcpConnection::create(acceptor_.get_io_service());
acceptor_.async_accept(new_connection->socket(),
boost::bind(&TcpServer::handle_accept, this, new_connection,
boost::asio::placeholders::error));
}
void TcpServer::handle_accept(TcpConnection::ptr new_connection, const boost::system::error_code& error) {
if (!error) {
new_connection->receive_msg(callback);
}
start_accept();
}
} // namespace
| 22.625 | 106 | 0.669613 | SSGAalto |
c1862f98a059c6beab92ef353f27e694106bef60 | 997 | cpp | C++ | codeforces/1430/1430D/main.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 8 | 2020-12-23T07:54:53.000Z | 2021-11-23T02:46:35.000Z | codeforces/1430/1430D/main.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 1 | 2020-11-07T13:22:29.000Z | 2020-12-20T12:54:00.000Z | codeforces/1430/1430D/main.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 1 | 2021-01-16T03:40:10.000Z | 2021-01-16T03:40:10.000Z | #include <bits/stdc++.h>
using namespace std;
int solve(int N, string const& S) {
map<int, int> count;
vector<int> next(N, -1);
for (int i = 0; i < N; ++i) {
int j;
for (j = i + 1; j < N; ++j) {
if (S[i] != S[j]) break;
}
if (j > i + 1) {
count[i] = j - i;
}
next[i] = j;
i = j - 1;
}
int ans = 0;
for (int i = 0; i < N;) {
++ans;
if (count.empty()) {
i = next[i];
if (i < N) i = next[i];
} else {
auto it = count.begin();
--it->second;
if (it->second == 1 || it->first < next[i]) count.erase(it);
i = next[i];
}
}
return ans;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int T, N;
string S;
cin >> T;
for (int tt = 0; tt < T; ++tt) {
cin >> N >> S;
cout << solve(N, S) << endl;
}
return 0;
} | 19.54902 | 72 | 0.377131 | xirc |
c1865d0df63483a4e1ed41a9f9d8eb601daa4d43 | 1,461 | hpp | C++ | engine/include/Engine/SpriteBounds.hpp | Alexthehuman3/ASGE | a9cf473a3117f4b67a2dbe8fac00b1a2a4fd6e44 | [
"MIT"
] | 8 | 2020-04-26T11:48:29.000Z | 2022-02-23T15:13:50.000Z | engine/include/Engine/SpriteBounds.hpp | Alexthehuman3/ASGE | a9cf473a3117f4b67a2dbe8fac00b1a2a4fd6e44 | [
"MIT"
] | null | null | null | engine/include/Engine/SpriteBounds.hpp | Alexthehuman3/ASGE | a9cf473a3117f4b67a2dbe8fac00b1a2a4fd6e44 | [
"MIT"
] | 1 | 2021-05-13T16:37:24.000Z | 2021-05-13T16:37:24.000Z | // Copyright (c) 2021 James Huxtable. All rights reserved.
//
// This work is licensed under the terms of the MIT license.
//
// 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.
/**
* @file
* @brief Struct @ref ASGE::SpriteBounds
*/
#ifndef ASGE_SPRITEBOUNDS_HPP
#define ASGE_SPRITEBOUNDS_HPP
#include "Point2D.hpp"
namespace ASGE
{
/**
* @brief Four vertices defining a sprites bound.
*
* Used to conveniently store 4 points together. These 4 points
* typically define the for vertices defining the bounding rectangle
* of a sprite. Note:There is no guarantee that the bounds stored here
* are axis-aligned or ordered.
*/
struct SpriteBounds
{
Point2D v1 = { 0, 0 }; /**< The first vertex position. */
Point2D v2 = { 0, 0 }; /**< The second vertex position */
Point2D v3 = { 0, 0 }; /**< The third vertex position. */
Point2D v4 = { 0, 0 }; /**< The fourth vertex position. */
};
using TextBounds = SpriteBounds;
} // namespace ASGE
#endif // ASGE_SPRITEBOUNDS_HPP
| 33.204545 | 81 | 0.698152 | Alexthehuman3 |
c18782859e92c0451ee2ec694d9b240aedca574b | 3,083 | cpp | C++ | winp/winp/test/hook_test.cpp | benbraide/winp2 | f2687fe00b8cbda10f3e8d169c0c3823cf8e6c5f | [
"MIT"
] | null | null | null | winp/winp/test/hook_test.cpp | benbraide/winp2 | f2687fe00b8cbda10f3e8d169c0c3823cf8e6c5f | [
"MIT"
] | null | null | null | winp/winp/test/hook_test.cpp | benbraide/winp2 | f2687fe00b8cbda10f3e8d169c0c3823cf8e6c5f | [
"MIT"
] | null | null | null | #include "hook_test.h"
void winp::test::hook::run(int cmd_show){
winp::window::object ws;
ws.set_caption(L"Test Window");
ws.set_position(30, 30);
ws.set_size(1500, 800);
ws.create();
ws.show(cmd_show);
ws.get_grid([](winp::grid::object &grd){
grd.add_object([](winp::grid::row &row){
row.add_object([](winp::grid::column &col){
col.add_object([&](control::push_button &btn){
btn.set_text(L"Top-Left Aligned");
btn.insert_hook<ui::placement_hook>(ui::placement_hook::alignment_type::top_left);
});
col.add_object([&](control::push_button &btn){
btn.set_text(L"Top-Center Aligned");
btn.insert_hook<ui::placement_hook>(ui::placement_hook::alignment_type::top_center);
});
col.add_object([&](control::push_button &btn){
btn.set_text(L"Top-Right Aligned");
btn.insert_hook<ui::placement_hook>(ui::placement_hook::alignment_type::top_right);
});
col.add_object([&](control::push_button &btn){
btn.set_text(L"Center-Right Aligned");
btn.insert_hook<ui::placement_hook>(ui::placement_hook::alignment_type::center_right);
});
col.add_object([&](control::push_button &btn){
btn.set_text(L"Center Aligned");
btn.insert_hook<ui::placement_hook>(ui::placement_hook::alignment_type::center);
});
col.add_object([&](control::push_button &btn){
btn.set_text(L"Center-Left Aligned");
btn.insert_hook<ui::placement_hook>(ui::placement_hook::alignment_type::center_left);
});
col.add_object([&](control::push_button &btn){
btn.set_text(L"Bottom-Left Aligned");
btn.insert_hook<ui::placement_hook>(ui::placement_hook::alignment_type::bottom_left);
});
col.add_object([&](control::push_button &btn){
btn.set_text(L"Bottom-Center Aligned");
btn.insert_hook<ui::placement_hook>(ui::placement_hook::alignment_type::bottom_center);
});
col.add_object([&](control::push_button &btn){
btn.set_text(L"Bottom-Right Aligned");
btn.insert_hook<ui::placement_hook>(ui::placement_hook::alignment_type::bottom_right);
});
col.add_object([&](control::push_button &btn){
btn.set_text(L"Drag-Hooked");
btn.set_position(200, 90);
btn.insert_hook<ui::drag_hook>();
});
col.add_object([&](control::push_button &btn){
btn.set_text(L"Sibling Aligned");
btn.insert_hook<ui::sibling_placement_hook>(ui::sibling_placement_hook::sibling_type::previous, ui::sibling_placement_hook::alignment_type::center_right, POINT{ 5, 0 });
});
});
row.add_object([](winp::grid::column &col){
col.add_object([](winp::window::object &cw){
cw.set_caption(L"Children Contain Window");
cw.insert_hook<ui::children_contain_hook>(SIZE{ 30, 30 });
cw.set_position(30, 30);
cw.set_size(900, 500);
cw.create();
cw.show();
cw.add_object([](winp::window::object &ccw){
ccw.set_caption(L"Contained Child Window");
ccw.set_position(30, 30);
ccw.set_size(450, 250);
ccw.create();
ccw.show();
});
});
});
});
});
app::object::run();
}
| 32.797872 | 174 | 0.662018 | benbraide |
c187b2ab8bcc19a64601b02337c4528c929d6911 | 5,731 | cpp | C++ | Project4/src/ofApp.cpp | WenheLI/advanced_creative_code_19 | 1480c6ff8b7f5f53cc0f3ff8677138e70cff5269 | [
"MIT"
] | null | null | null | Project4/src/ofApp.cpp | WenheLI/advanced_creative_code_19 | 1480c6ff8b7f5f53cc0f3ff8677138e70cff5269 | [
"MIT"
] | null | null | null | Project4/src/ofApp.cpp | WenheLI/advanced_creative_code_19 | 1480c6ff8b7f5f53cc0f3ff8677138e70cff5269 | [
"MIT"
] | null | null | null | #include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofSetFrameRate(60);
for (int i = 0; i < 5; i++) {
auto b = make_shared<Ball>();
b->init();
balls.push_back(b);
}
phase = 0;
int bufferSize = 512;
volume = 0.6f;
pan =0.5f;
ofSoundStreamSettings settings;
settings.setOutListener(this);
settings.sampleRate = sampleRate;
settings.numOutputChannels = 2;
settings.numInputChannels = 0;
settings.bufferSize = bufferSize;
soundStream.setup(settings);
lAudio.assign(bufferSize, 0.0);
rAudio.assign(bufferSize, 0.0);
}
//--------------------------------------------------------------
void ofApp::update(){
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++)
if (i != j) balls[i]->update(balls[j]);
}
}
//--------------------------------------------------------------
void ofApp::draw(){
ofBackground(34, 34, 34);
ofSetColor(225);
ofDrawBitmapString("press 's' to unpause the audio\npress 'e' to pause the audio", 31, 92);
ofNoFill();
// draw the left channel:
ofPushStyle();
ofPushMatrix();
ofTranslate(32, 150, 0);
ofSetColor(225);
ofDrawBitmapString("Left Channel", 4, 18);
ofSetLineWidth(1);
ofDrawRectangle(0, 0, 450, 200);
ofSetColor(245, 58, 135);
ofSetLineWidth(1.5);
ofBeginShape();
for (unsigned int i = 0; i < lAudio.size(); i++){
float l = ofMap(i, 0, lAudio.size(), 0, 450, true);
ofVertex(l, 100 -lAudio[i]*180.0f);
}
ofEndShape(false);
ofPopMatrix();
ofPopStyle();
// draw the right channel:
ofPushStyle();
ofPushMatrix();
ofTranslate(500, 150, 0);
ofSetColor(225);
ofDrawBitmapString("Right Channel", 4, 18);
ofSetLineWidth(1);
ofDrawRectangle(0, 0, 450, 200);
ofSetColor(245, 58, 135);
ofSetLineWidth(1.5);
ofBeginShape();
for (unsigned int i = 0; i < rAudio.size(); i++){
float l = ofMap(i, 0, rAudio.size(), 0, 450, true);
ofVertex(l, 100 -rAudio[i]*180.0f);
}
ofEndShape(false);
ofPopMatrix();
ofPopStyle();
for (int i = 0; i < 5; i++) balls[i]->draw();
}
void ofApp::audioOut(ofSoundBuffer &outBuffer){
float leftScale = 1 - pan;
float rightScale = pan;
while (phase > TWO_PI){
phase -= TWO_PI;
}
for(int i = 0; i < outBuffer.size(); i += 2) {
auto cooin = generateSample(phase, balls[0]);
float sample = cooin * (ofMap(balls[0]->vel.length(), 0, 10, 0, .8)+.2); // generating a sine wave sample
float x = balls[0]->pos.x;
float w = ofGetWidth();
float rightOffset = ofMap(x - w/2.0, -w/2.0 , w/2.0, -1, 1);
rightOffset = (-1 * abs(rightOffset)) + 1;
float leftOffset = 1 - abs(rightOffset);
rAudio[i]= sample * volume*leftOffset;
lAudio[i]= sample * volume*rightOffset;
outBuffer[i] = sample * volume*rightOffset; // writing/drawing to the left channel
outBuffer[i+1] = sample * volume*leftOffset; // writing/drawing to the right channel
//memorize this equation! phaseOffset = freq / sampleRate
float phaseOffset = ((float)2000 / ofMap(balls[0]->preAcc.length(), 0, 80/balls[0]->r, 60, 2500));
phase += phaseOffset;
}
}
float ofApp::generateSample(float phase, shared_ptr<Ball> ball){
auto waveType = waveTypeGenerator(ball->pos);
switch (waveType) {
case 1://sine
return sin(phase*TWO_PI);
break;
case 2://square
return sin(phase*TWO_PI) > 0 ? .5 : -.5;
case 3://sawtooth
return fmod(phase,TWO_PI);
case 4://triangle
return abs(sin(phase*TWO_PI));
default:
break;
}
}
int ofApp::waveTypeGenerator(ofVec2f ballPos){
if (ballPos.x >= 0 && ballPos.x < ofGetWidth()/2){
if (ballPos.y >= 0 && ballPos.y < ofGetHeight()/2){
return 1;
} else {
return 2;
}
} else {
if (ballPos.y >= 0 && ballPos.y < ofGetHeight()/2){
return 3;
} else {
return 4;
}
}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
if( key == 's' ){
soundStream.start();
}
if( key == 'e' ){
soundStream.stop();
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| 24.283898 | 113 | 0.462746 | WenheLI |
c1885c143429dafe1bc1a5ac7666e2d7aba77ab9 | 1,556 | cc | C++ | cc/test/fake_external_begin_frame_source.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5 | 2015-04-30T00:13:21.000Z | 2019-07-10T02:17:24.000Z | cc/test/fake_external_begin_frame_source.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | cc/test/fake_external_begin_frame_source.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2015-03-27T11:15:39.000Z | 2016-08-17T14:19:56.000Z | // Copyright 2014 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 "cc/test/fake_external_begin_frame_source.h"
#include "base/location.h"
#include "base/message_loop/message_loop.h"
#include "base/time/time.h"
#include "cc/test/begin_frame_args_test.h"
namespace cc {
FakeExternalBeginFrameSource::FakeExternalBeginFrameSource(double refresh_rate)
: milliseconds_per_frame_(1000.0 / refresh_rate),
is_ready_(false),
weak_ptr_factory_(this) {
DetachFromThread();
}
FakeExternalBeginFrameSource::~FakeExternalBeginFrameSource() {
DCHECK(CalledOnValidThread());
}
void FakeExternalBeginFrameSource::SetClientReady() {
DCHECK(CalledOnValidThread());
is_ready_ = true;
}
void FakeExternalBeginFrameSource::OnNeedsBeginFramesChange(
bool needs_begin_frames) {
DCHECK(CalledOnValidThread());
if (needs_begin_frames) {
PostTestOnBeginFrame();
}
}
void FakeExternalBeginFrameSource::TestOnBeginFrame() {
DCHECK(CalledOnValidThread());
CallOnBeginFrame(CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE));
if (NeedsBeginFrames()) {
PostTestOnBeginFrame();
}
}
void FakeExternalBeginFrameSource::PostTestOnBeginFrame() {
base::MessageLoop::current()->PostDelayedTask(
FROM_HERE, base::Bind(&FakeExternalBeginFrameSource::TestOnBeginFrame,
weak_ptr_factory_.GetWeakPtr()),
base::TimeDelta::FromMilliseconds(milliseconds_per_frame_));
}
} // namespace cc
| 28.290909 | 79 | 0.760283 | kjthegod |
c18ed2a631202bf3c99791fc194a9bbd53ad84ae | 684 | cpp | C++ | 1 Mathematics/gcd.cpp | AdityaVSM/algorithms | 0ab0147a1e3905cf3096576a89cbce13de2673ed | [
"MIT"
] | null | null | null | 1 Mathematics/gcd.cpp | AdityaVSM/algorithms | 0ab0147a1e3905cf3096576a89cbce13de2673ed | [
"MIT"
] | null | null | null | 1 Mathematics/gcd.cpp | AdityaVSM/algorithms | 0ab0147a1e3905cf3096576a89cbce13de2673ed | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int gcd1(int a, int b){ //worst cse:O(min(a,b))
int small = std::min(a,b);
while(small > 0){
if(a%small == 0 && b%small == 0){
break;
}
small--;
}
return small;
}
//Euclid algo
int gcd2(int a, int b){
while(a != b){
if(a>b)
a -= b;
else
b -= a;
}
return a;
}
//optimized Euclid aligo
int gcd3(int a, int b){ //Best approach O(log(min(a,b)))
if(b == 0)
return a;
return gcd3(b,a%b);
}
int main(){
cout<<gcd1(4,6)<<endl;
cout<<gcd2(4,6)<<endl;
cout<<gcd3(4,6)<<endl;
return 0;
} | 19 | 60 | 0.457602 | AdityaVSM |
c1901445cf21033fb7a2bab6fdc196dbaa46cd42 | 6,059 | cpp | C++ | core/src/db/snapshot/Operations.cpp | zhang19941219/milvus | afac02ca2f1cab7bd98afb8fe6981d602b7a9a9b | [
"Apache-2.0"
] | null | null | null | core/src/db/snapshot/Operations.cpp | zhang19941219/milvus | afac02ca2f1cab7bd98afb8fe6981d602b7a9a9b | [
"Apache-2.0"
] | null | null | null | core/src/db/snapshot/Operations.cpp | zhang19941219/milvus | afac02ca2f1cab7bd98afb8fe6981d602b7a9a9b | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2019-2020 Zilliz. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations under the License.
#include "db/snapshot/Operations.h"
#include <chrono>
#include <sstream>
#include "db/snapshot/OperationExecutor.h"
#include "db/snapshot/Snapshots.h"
namespace milvus {
namespace engine {
namespace snapshot {
static ID_TYPE UID = 1;
std::ostream&
operator<<(std::ostream& out, const Operations& operation) {
out << operation.ToString();
return out;
}
Operations::Operations(const OperationContext& context, ScopedSnapshotT prev_ss, const OperationsType& type)
: context_(context),
prev_ss_(prev_ss),
uid_(UID++),
status_(SS_OPERATION_PENDING, "Operation Pending"),
type_(type) {
}
Operations::Operations(const OperationContext& context, ID_TYPE collection_id, ID_TYPE commit_id,
const OperationsType& type)
: context_(context), uid_(UID++), status_(SS_OPERATION_PENDING, "Operation Pending"), type_(type) {
auto status = Snapshots::GetInstance().GetSnapshot(prev_ss_, collection_id, commit_id);
if (!status.ok())
prev_ss_ = ScopedSnapshotT();
}
std::string
Operations::SuccessString() const {
return status_.ToString();
}
std::string
Operations::FailureString() const {
return status_.ToString();
}
std::string
Operations::GetRepr() const {
std::stringstream ss;
ss << "<" << GetName() << ":" << GetID() << ">";
return ss.str();
}
std::string
Operations::ToString() const {
std::stringstream ss;
ss << GetRepr();
ss << (done_ ? " | DONE" : " | PENDING");
if (done_) {
if (status_.ok()) {
ss << " | " << SuccessString();
} else {
ss << " | " << FailureString();
}
}
return ss.str();
}
ID_TYPE
Operations::GetID() const {
return uid_;
}
Status
Operations::operator()(Store& store) {
auto status = PreCheck();
if (!status.ok())
return status;
return ApplyToStore(store);
}
void
Operations::SetStatus(const Status& status) {
status_ = status;
}
Status
Operations::WaitToFinish() {
std::unique_lock<std::mutex> lock(finish_mtx_);
finish_cond_.wait(lock, [this] { return done_; });
return status_;
}
void
Operations::Done() {
std::unique_lock<std::mutex> lock(finish_mtx_);
done_ = true;
if (GetType() == OperationsType::W_Compound) {
std::cout << ToString() << std::endl;
}
finish_cond_.notify_all();
}
Status
Operations::PreCheck() {
return Status::OK();
}
Status
Operations::Push(bool sync) {
auto status = PreCheck();
if (!status.ok())
return status;
return OperationExecutor::GetInstance().Submit(shared_from_this(), sync);
}
Status
Operations::DoCheckStale(ScopedSnapshotT& latest_snapshot) const {
return Status::OK();
}
Status
Operations::CheckStale(const CheckStaleFunc& checker) const {
decltype(prev_ss_) latest_ss;
auto status = Snapshots::GetInstance().GetSnapshotNoLoad(latest_ss, prev_ss_->GetCollection()->GetID());
if (!status.ok())
return status;
if (prev_ss_->GetID() != latest_ss->GetID()) {
if (checker) {
status = checker(latest_ss);
} else {
status = DoCheckStale(latest_ss);
}
}
return status;
}
Status
Operations::DoneRequired() const {
Status status;
if (!done_) {
status = Status(SS_CONSTRAINT_CHECK_ERROR, "Operation is expected to be done");
}
return status;
}
Status
Operations::IDSNotEmptyRequried() const {
Status status;
if (ids_.size() == 0)
status = Status(SS_CONSTRAINT_CHECK_ERROR, "No Snapshot is available");
return status;
}
Status
Operations::PrevSnapshotRequried() const {
Status status;
if (!prev_ss_) {
status = Status(SS_CONSTRAINT_CHECK_ERROR, "Prev snapshot is requried");
}
return status;
}
Status
Operations::GetSnapshot(ScopedSnapshotT& ss) const {
auto status = PrevSnapshotRequried();
if (!status.ok())
return status;
status = DoneRequired();
if (!status.ok())
return status;
status = IDSNotEmptyRequried();
if (!status.ok())
return status;
status = Snapshots::GetInstance().GetSnapshot(ss, prev_ss_->GetCollectionId(), ids_.back());
return status;
}
Status
Operations::ApplyToStore(Store& store) {
if (GetType() == OperationsType::W_Compound) {
std::cout << ToString() << std::endl;
}
if (done_) {
Done();
return status_;
}
auto status = OnExecute(store);
SetStatus(status);
Done();
return status_;
}
Status
Operations::OnExecute(Store& store) {
auto status = PreExecute(store);
if (!status.ok()) {
return status;
}
status = DoExecute(store);
if (!status.ok()) {
return status;
}
return PostExecute(store);
}
Status
Operations::PreExecute(Store& store) {
return Status::OK();
}
Status
Operations::DoExecute(Store& store) {
return Status::OK();
}
Status
Operations::PostExecute(Store& store) {
return store.DoCommitOperation(*this);
}
Status
Operations::RollBack() {
// TODO: Implement here
// Spwarn a rollback operation or re-use this operation
return Status::OK();
}
Status
Operations::ApplyRollBack(Store& store) {
// TODO: Implement rollback to remove all resources in steps_
return Status::OK();
}
Operations::~Operations() {
// TODO: Prefer to submit a rollback operation if status is not ok
}
} // namespace snapshot
} // namespace engine
} // namespace milvus
| 24.139442 | 113 | 0.653738 | zhang19941219 |
c1914370cd26ac29d17d65ca214cdbda79fd6eea | 5,723 | cpp | C++ | algorithms/kernel/neural_networks/layers/pooling1d_layer/backward/pooling1d_layer_backward.cpp | rayrapetyan/daal | 41cc748dc50097b1064e40395a4da7ce6f836244 | [
"Apache-2.0"
] | null | null | null | algorithms/kernel/neural_networks/layers/pooling1d_layer/backward/pooling1d_layer_backward.cpp | rayrapetyan/daal | 41cc748dc50097b1064e40395a4da7ce6f836244 | [
"Apache-2.0"
] | null | null | null | algorithms/kernel/neural_networks/layers/pooling1d_layer/backward/pooling1d_layer_backward.cpp | rayrapetyan/daal | 41cc748dc50097b1064e40395a4da7ce6f836244 | [
"Apache-2.0"
] | null | null | null | /* file: pooling1d_layer_backward.cpp */
/*******************************************************************************
* Copyright 2014-2018 Intel Corporation
* All Rights Reserved.
*
* If this software was obtained under the Intel Simplified Software License,
* the following terms apply:
*
* The source code, information and material ("Material") contained herein is
* owned by Intel Corporation or its suppliers or licensors, and title to such
* Material remains with Intel Corporation or its suppliers or licensors. The
* Material contains proprietary information of Intel or its suppliers and
* licensors. The Material is protected by worldwide copyright laws and treaty
* provisions. No part of the Material may be used, copied, reproduced,
* modified, published, uploaded, posted, transmitted, distributed or disclosed
* in any way without Intel's prior express written permission. No license under
* any patent, copyright or other intellectual property rights in the Material
* is granted to or conferred upon you, either expressly, by implication,
* inducement, estoppel or otherwise. Any license under such intellectual
* property rights must be express and approved by Intel in writing.
*
* Unless otherwise agreed by Intel in writing, you may not remove or alter this
* notice or any other notice embedded in Materials by Intel or Intel's
* suppliers or licensors in any way.
*
*
* If this software was obtained under the Apache License, Version 2.0 (the
* "License"), the following terms apply:
*
* 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.
*******************************************************************************/
/*
//++
// Implementation of pooling1d calculation algorithm and types methods.
//--
*/
#include "pooling1d_layer_backward_types.h"
#include "pooling1d_layer_types.h"
#include "daal_strings.h"
using namespace daal::services;
namespace daal
{
namespace algorithms
{
namespace neural_networks
{
namespace layers
{
namespace pooling1d
{
namespace backward
{
namespace interface1
{
/** Default constructor */
Input::Input() {}
Input::Input(const Input& other) : super(other) {}
/**
* Return the collection with gradient size
* \return The collection with gradient size
*/
services::Collection<size_t> Input::getGradientSize() const
{
services::Collection<size_t> dims;
data_management::NumericTablePtr inputDims = getAuxInputDimensions();
if(!data_management::checkNumericTable(inputDims.get(), auxInputDimensionsStr())) { return dims; }
data_management::BlockDescriptor<int> block;
inputDims->getBlockOfRows(0, 1, data_management::readOnly, block);
int *inputDimsArray = block.getBlockPtr();
for(size_t i = 0; i < inputDims->getNumberOfColumns(); i++)
{
dims.push_back((size_t) inputDimsArray[i]);
}
inputDims->releaseBlockOfRows(block);
return dims;
}
services::Collection<size_t> Input::getInputGradientSize(const pooling1d::Parameter *parameter) const
{
const Parameter *param = static_cast<const Parameter *>(parameter);
services::Collection<size_t> inputDims = getGradientSize();
inputDims[param->index.size[0]] =
computeInputDimension(inputDims[param->index.size[0]], param->kernelSize.size[0], param->padding.size[0], param->stride.size[0]);
return inputDims;
}
size_t Input::computeInputDimension(size_t maskDim, size_t kernelSize, size_t padding, size_t stride) const
{
size_t inputDim = (maskDim + 2 * padding - kernelSize + stride) / stride;
return inputDim;
}
/** Default constructor */
Result::Result() {}
/**
* Checks the result of the backward 1D pooling layer
* \param[in] input %Input object for the layer
* \param[in] parameter %Parameter of the layer
* \param[in] method Computation method
*/
services::Status Result::check(const daal::algorithms::Input *input, const daal::algorithms::Parameter *parameter, int method) const
{
const Parameter *param = static_cast<const Parameter *>(parameter);
if (!param->propagateGradient) { return services::Status(); }
services::Status s;
DAAL_CHECK_STATUS(s, layers::backward::Result::check(input, parameter, method));
const Input *algInput = static_cast<const Input *>(input);
//get expected gradient dimensions
services::Collection<size_t> gradientDims = algInput->getGradientSize();
DAAL_CHECK_STATUS(s, data_management::checkTensor(get(layers::backward::gradient).get(), gradientStr(), &gradientDims));
DAAL_CHECK_EX(param->stride.size[0] != 0, services::ErrorIncorrectParameter, services::ParameterName, stridesStr());
size_t index = param->index.size[0];
DAAL_CHECK_EX(index <= gradientDims.size() - 1, services::ErrorIncorrectParameter, services::ParameterName,
indicesStr());
DAAL_CHECK_EX((param->kernelSize.size[0] != 0 &&
param->kernelSize.size[0] <= gradientDims[index] + 2 * param->padding.size[0]), services::ErrorIncorrectParameter, services::ParameterName,
kernelSizesStr());
return s;
}
}// namespace interface1
}// namespace backward
}// namespace pooling1d
}// namespace layers
}// namespace neural_networks
}// namespace algorithms
}// namespace daal
| 38.153333 | 158 | 0.706098 | rayrapetyan |
c1920641d9f469968a5478ece13f1c1ddcd4f8c0 | 2,415 | cpp | C++ | src/heap.cpp | tenglvjun/Algorithm | 463873ae0dbbbf774ad427e98bf0c71147b1fb5c | [
"MIT"
] | null | null | null | src/heap.cpp | tenglvjun/Algorithm | 463873ae0dbbbf774ad427e98bf0c71147b1fb5c | [
"MIT"
] | null | null | null | src/heap.cpp | tenglvjun/Algorithm | 463873ae0dbbbf774ad427e98bf0c71147b1fb5c | [
"MIT"
] | null | null | null | #include "heap.h"
#include "macro.h"
#include <assert.h>
#include <cmath>
#include "tools.h"
Heap::Heap(bool maxHeapify /* = true */)
: ContinueContainer(), m_isMaxHeapify(maxHeapify)
{
}
Heap::Heap(int *data, int len, bool maxHeapify /* = true */)
: ContinueContainer(data, len), m_isMaxHeapify(maxHeapify)
{
Heapify();
}
Heap::~Heap()
{
}
void Heap::PushBack(const int v)
{
ContinueContainer::PushBack(v);
TrackUp(m_len - 1);
}
int Heap::PopFront()
{
Swap(m_data, 0, (m_len - 1));
int value = ContinueContainer::Erase(m_len - 1);
TrackDown(0);
return value;
}
void Heap::Sort()
{
int len = m_len;
int *buf = new int[len];
int idx = 0;
while (m_len > 0)
{
buf[idx++] = PopFront();
}
Resize(buf, len);
}
void Heap::Heapify()
{
int height = (int)log2(m_len);
for (int i = height - 1; i >= 0; i--)
{
for (int j = pow(2, i); j < pow(2, i + 1); j++)
{
TrackDown(j - 1);
}
}
}
void Heap::TrackDown(const int node)
{
int left = node * 2 + 1;
int right = node * 2 + 2;
if (left >= m_len)
{
return;
}
int sid;
int value;
if (m_isMaxHeapify)
{
value = m_data[node] < m_data[left] ? m_data[left] : m_data[node];
if (right < m_len)
{
value = value < m_data[right] ? m_data[right] : value;
}
}
else
{
value = m_data[node] > m_data[left] ? m_data[left] : m_data[node];
if (right < m_len)
{
value = value > m_data[right] ? m_data[right] : value;
}
}
if (value == m_data[node])
{
return;
}
if (value == m_data[left])
{
Swap(m_data, node, left);
TrackDown(left);
}
if ((right < m_len) && (value == m_data[right]))
{
Swap(m_data, node, right);
TrackDown(right);
}
}
void Heap::TrackUp(const int node)
{
if (0 == node)
{
return;
}
int parent = (node - 1) / 2;
if (m_isMaxHeapify)
{
if (m_data[parent] < m_data[node])
{
Swap(m_data, parent, node);
TrackDown(parent);
TrackUp(parent);
}
}
else
{
if (m_data[parent] > m_data[node])
{
Swap(m_data, parent, node);
TrackDown(parent);
TrackUp(parent);
}
}
} | 17.888889 | 74 | 0.496066 | tenglvjun |
c192da0b8712aa41516af77289357418d3410ac2 | 944 | cc | C++ | below2.1/whatdoesthefoxsay.cc | danzel-py/Kattis-Problem-Archive | bce1929d654b1bceb104f96d68c74349273dd1ff | [
"Apache-2.0"
] | null | null | null | below2.1/whatdoesthefoxsay.cc | danzel-py/Kattis-Problem-Archive | bce1929d654b1bceb104f96d68c74349273dd1ff | [
"Apache-2.0"
] | null | null | null | below2.1/whatdoesthefoxsay.cc | danzel-py/Kattis-Problem-Archive | bce1929d654b1bceb104f96d68c74349273dd1ff | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <regex>
#include <sstream>
#include <map>
using namespace std;
int main()
{
int n;
cin >> n;
cin.ignore(11000, '\n');
string str, strdict, animal, goes, sound;
regex e("[A-Za-z]+");
for (int i = 0; i < n; i++)
{
map<string, int> maptoanimal;
getline(cin, str);
while (true)
{
getline(cin, strdict);
if (strdict == "what does the fox say?")
{
break;
}
stringstream ss(strdict);
ss >> animal >> goes >> sound;
maptoanimal[sound] = 1;
}
for (sregex_iterator i = sregex_iterator(str.begin(), str.end(), e); i != sregex_iterator(); ++i)
{
smatch m = *i;
string a = m.str();
if(maptoanimal[a]==0){
cout<<a<<' ';
}
}
cout<<'\n';
}
return 0;
} | 21.953488 | 105 | 0.439619 | danzel-py |
c19ce513d2df9cc41bf5e08315e929eeb353e771 | 693 | cpp | C++ | 3_OOP/LyThuyet-T6/Bai-3/Xe.cpp | SummerSad/HCMUS-Lectures | b376e144e2601a73684e2ff437ab5c94a943909c | [
"MIT"
] | 8 | 2020-05-11T09:48:40.000Z | 2022-03-28T13:43:27.000Z | 3_OOP/LyThuyet-T6/Bai-3/Xe.cpp | SummerSad/HCMUS-Lectures | b376e144e2601a73684e2ff437ab5c94a943909c | [
"MIT"
] | null | null | null | 3_OOP/LyThuyet-T6/Bai-3/Xe.cpp | SummerSad/HCMUS-Lectures | b376e144e2601a73684e2ff437ab5c94a943909c | [
"MIT"
] | 4 | 2021-04-13T04:01:50.000Z | 2021-12-10T01:12:15.000Z | #include "Xe.h"
// Xe
Xe::Xe(double tocdoXang0Tai, double tocdoXangHH)
{
m_xang = 0;
m_duong = 0;
m_hang = 0;
m_tocdoXang0Tai = tocdoXang0Tai;
m_tocdoXangHH = tocdoXangHH;
m_xangTieuThu = m_tocdoXang0Tai * m_duong + m_tocdoXangHH * m_hang;
}
void Xe::themHang(double hang)
{
m_hang += hang;
m_xangTieuThu += m_tocdoXangHH * hang;
}
void Xe::botHang(double hang)
{
hang = hang <= m_hang ? hang : m_hang;
themHang(-hang);
}
void Xe::themXang(double xang)
{
m_xang += xang;
}
void Xe::chay(double duong)
{
m_duong += duong;
m_xangTieuThu += m_tocdoXang0Tai * duong;
m_xang -= m_xangTieuThu;
}
bool Xe::hetXang()
{
return m_xang <= 0;
}
double Xe::xang()
{
return m_xang;
}
| 14.744681 | 68 | 0.681097 | SummerSad |
c1a2643ada253d12752ac95c546898830176b297 | 9,925 | cpp | C++ | test/when_all_tests.cpp | toomuchsalt/cppcoro | 552e67e7381166747fe8ec5dc3f71637daf765b8 | [
"MIT"
] | 13 | 2020-09-30T17:03:18.000Z | 2022-02-21T11:42:12.000Z | test/when_all_tests.cpp | arthurzam/cppcoro | a736b873c599175f551b7bbdedc8365eacdd1334 | [
"MIT"
] | null | null | null | test/when_all_tests.cpp | arthurzam/cppcoro | a736b873c599175f551b7bbdedc8365eacdd1334 | [
"MIT"
] | 5 | 2020-10-10T14:22:58.000Z | 2021-02-10T01:58:40.000Z | ///////////////////////////////////////////////////////////////////////////////
// Copyright (c) Lewis Baker
// Licenced under MIT license. See LICENSE.txt for details.
///////////////////////////////////////////////////////////////////////////////
#include <cppcoro/when_all.hpp>
#include <cppcoro/config.hpp>
#include <cppcoro/async_manual_reset_event.hpp>
#include <cppcoro/async_mutex.hpp>
#include <cppcoro/fmap.hpp>
#include <cppcoro/shared_task.hpp>
#include <cppcoro/sync_wait.hpp>
#include <cppcoro/task.hpp>
#include "counted.hpp"
#include <functional>
#include <string>
#include <vector>
#include <ostream>
#include "doctest/cppcoro_doctest.h"
TEST_SUITE_BEGIN("when_all");
namespace
{
template<template<typename T> class TASK, typename T>
TASK<T> when_event_set_return(cppcoro::async_manual_reset_event& event, T value)
{
co_await event;
co_return std::move(value);
}
}
TEST_CASE("when_all() with no args completes immediately")
{
[[maybe_unused]] std::tuple<> result = cppcoro::sync_wait(cppcoro::when_all());
}
TEST_CASE("when_all() with one arg")
{
bool started = false;
bool finished = false;
auto f = [&](cppcoro::async_manual_reset_event& event) -> cppcoro::task<std::string>
{
started = true;
co_await event;
finished = true;
co_return "foo";
};
cppcoro::async_manual_reset_event event;
auto whenAllTask = cppcoro::when_all(f(event));
CHECK(!started);
cppcoro::sync_wait(cppcoro::when_all_ready(
[&]() -> cppcoro::task<>
{
auto[s] = co_await whenAllTask;
CHECK(s == "foo");
}(),
[&]() -> cppcoro::task<>
{
CHECK(started);
CHECK(!finished);
event.set();
CHECK(finished);
co_return;
}()));
}
TEST_CASE("when_all() with awaitables")
{
cppcoro::sync_wait([]() -> cppcoro::task<>
{
auto makeTask = [](int x) -> cppcoro::task<int>
{
co_return x;
};
cppcoro::async_manual_reset_event event;
event.set();
cppcoro::async_mutex mutex;
auto[eventResult, mutexLock, number] = co_await cppcoro::when_all(
std::ref(event),
mutex.scoped_lock_async(),
makeTask(123) | cppcoro::fmap([](int x) { return x + 1; }));
(void)eventResult;
(void)mutexLock;
CHECK(number == 124);
CHECK(!mutex.try_lock());
}());
}
TEST_CASE("when_all() with all task types")
{
counted::reset_counts();
auto run = [](cppcoro::async_manual_reset_event& event) -> cppcoro::task<>
{
using namespace std::string_literals;
auto[a, b] = co_await cppcoro::when_all(
when_event_set_return<cppcoro::task>(event, "foo"s),
when_event_set_return<cppcoro::shared_task>(event, counted{}));
CHECK(a == "foo");
CHECK(b.id == 0);
// GCC 10.1 fails this check: at this point there are 3 objects alive
// * One will be destructed later
// * One object is completely leaked
#if CPPCORO_COMPILER_GCC && CPPCORO_COMPILER_GCC <= 10'02'00
WARN("GCC <= 10.02 is known to produce memory leaks !!!");
#else
CHECK(counted::active_count() == 1);
#endif
};
cppcoro::async_manual_reset_event event;
cppcoro::sync_wait(cppcoro::when_all_ready(
run(event),
[&]() -> cppcoro::task<>
{
event.set();
co_return;
}()));
}
TEST_CASE("when_all() throws if any task throws")
{
struct X {};
struct Y {};
int startedCount = 0;
auto makeTask = [&](int value) -> cppcoro::task<int>
{
++startedCount;
if (value == 0) throw X{};
else if (value == 1) throw Y{};
else co_return value;
};
cppcoro::sync_wait([&]() -> cppcoro::task<>
{
try
{
// This could either throw X or Y exception.
// The exact exception that is thrown is not defined if multiple tasks throw an exception.
// TODO: Consider throwing some kind of aggregate_exception that collects all of the exceptions together.
(void)co_await cppcoro::when_all(makeTask(0), makeTask(1), makeTask(2));
}
catch (const X&)
{
}
catch (const Y&)
{
}
}());
}
TEST_CASE("when_all() with task<void>")
{
int voidTaskCount = 0;
auto makeVoidTask = [&]() -> cppcoro::task<>
{
++voidTaskCount;
co_return;
};
auto makeIntTask = [](int x) -> cppcoro::task<int>
{
co_return x;
};
// Single void task in when_all()
auto[x] = cppcoro::sync_wait(cppcoro::when_all(makeVoidTask()));
(void)x;
CHECK(voidTaskCount == 1);
// Multiple void tasks in when_all()
auto[a, b] = cppcoro::sync_wait(cppcoro::when_all(
makeVoidTask(),
makeVoidTask()));
(void)a;
(void)b;
CHECK(voidTaskCount == 3);
// Mixing void and non-void tasks in when_all()
auto[v1, i, v2] = cppcoro::sync_wait(cppcoro::when_all(
makeVoidTask(),
makeIntTask(123),
makeVoidTask()));
(void)v1;
(void)v2;
CHECK(voidTaskCount == 5);
CHECK(i == 123);
}
TEST_CASE("when_all() with vector<task<>>")
{
int startedCount = 0;
auto makeTask = [&](cppcoro::async_manual_reset_event& event) -> cppcoro::task<>
{
++startedCount;
co_await event;
};
cppcoro::async_manual_reset_event event1;
cppcoro::async_manual_reset_event event2;
bool finished = false;
auto run = [&]() -> cppcoro::task<>
{
std::vector<cppcoro::task<>> tasks;
tasks.push_back(makeTask(event1));
tasks.push_back(makeTask(event2));
tasks.push_back(makeTask(event1));
auto allTask = cppcoro::when_all(std::move(tasks));
CHECK(startedCount == 0);
co_await allTask;
finished = true;
};
cppcoro::sync_wait(cppcoro::when_all_ready(
run(),
[&]() -> cppcoro::task<>
{
CHECK(startedCount == 3);
CHECK(!finished);
event1.set();
CHECK(!finished);
event2.set();
CHECK(finished);
co_return;
}()));
}
TEST_CASE("when_all() with vector<shared_task<>>")
{
int startedCount = 0;
auto makeTask = [&](cppcoro::async_manual_reset_event& event) -> cppcoro::shared_task<>
{
++startedCount;
co_await event;
};
cppcoro::async_manual_reset_event event1;
cppcoro::async_manual_reset_event event2;
bool finished = false;
auto run = [&]() -> cppcoro::task<>
{
std::vector<cppcoro::shared_task<>> tasks;
tasks.push_back(makeTask(event1));
tasks.push_back(makeTask(event2));
tasks.push_back(makeTask(event1));
auto allTask = cppcoro::when_all(std::move(tasks));
CHECK(startedCount == 0);
co_await allTask;
finished = true;
};
cppcoro::sync_wait(cppcoro::when_all_ready(
run(),
[&]() -> cppcoro::task<>
{
CHECK(startedCount == 3);
CHECK(!finished);
event1.set();
CHECK(!finished);
event2.set();
CHECK(finished);
co_return;
}()));
}
namespace
{
template<template<typename T> class TASK>
void check_when_all_vector_of_task_value()
{
cppcoro::async_manual_reset_event event1;
cppcoro::async_manual_reset_event event2;
bool whenAllCompleted = false;
cppcoro::sync_wait(cppcoro::when_all_ready(
[&]() -> cppcoro::task<>
{
std::vector<TASK<int>> tasks;
tasks.emplace_back(when_event_set_return<TASK>(event1, 1));
tasks.emplace_back(when_event_set_return<TASK>(event2, 2));
auto whenAllTask = cppcoro::when_all(std::move(tasks));
auto values = co_await whenAllTask;
REQUIRE(values.size() == 2);
CHECK(values[0] == 1);
CHECK(values[1] == 2);
whenAllCompleted = true;
}(),
[&]() -> cppcoro::task<>
{
CHECK(!whenAllCompleted);
event2.set();
CHECK(!whenAllCompleted);
event1.set();
CHECK(whenAllCompleted);
co_return;
}()));
}
}
#if defined(CPPCORO_RELEASE_OPTIMISED)
constexpr bool isOptimised = true;
#else
constexpr bool isOptimised = false;
#endif
// Disable test on MSVC x86 optimised due to bad codegen bug in
// `co_await whenAllTask` expression under MSVC 15.7 (Preview 2) and earlier.
TEST_CASE("when_all() with vector<task<T>>"
* doctest::skip(CPPCORO_COMPILER_MSVC && CPPCORO_COMPILER_MSVC <= 191426316 && CPPCORO_CPU_X86 && isOptimised))
{
check_when_all_vector_of_task_value<cppcoro::task>();
}
// Disable test on MSVC x64 optimised due to bad codegen bug in
// 'co_await whenAllTask' expression.
// Issue reported to MS on 19/11/2017.
TEST_CASE("when_all() with vector<shared_task<T>>"
* doctest::skip(CPPCORO_COMPILER_MSVC && CPPCORO_COMPILER_MSVC <= 191225805 &&
isOptimised && CPPCORO_CPU_X64))
{
check_when_all_vector_of_task_value<cppcoro::shared_task>();
}
namespace
{
template<template<typename T> class TASK>
void check_when_all_vector_of_task_reference()
{
cppcoro::async_manual_reset_event event1;
cppcoro::async_manual_reset_event event2;
int value1 = 1;
int value2 = 2;
auto makeTask = [](cppcoro::async_manual_reset_event& event, int& value) -> TASK<int&>
{
co_await event;
co_return value;
};
bool whenAllComplete = false;
cppcoro::sync_wait(cppcoro::when_all_ready(
[&]() -> cppcoro::task<>
{
std::vector<TASK<int&>> tasks;
tasks.emplace_back(makeTask(event1, value1));
tasks.emplace_back(makeTask(event2, value2));
auto whenAllTask = cppcoro::when_all(std::move(tasks));
std::vector<std::reference_wrapper<int>> values = co_await whenAllTask;
REQUIRE(values.size() == 2);
CHECK(&values[0].get() == &value1);
CHECK(&values[1].get() == &value2);
whenAllComplete = true;
}(),
[&]() -> cppcoro::task<>
{
CHECK(!whenAllComplete);
event2.set();
CHECK(!whenAllComplete);
event1.set();
CHECK(whenAllComplete);
co_return;
}()));
}
}
// Disable test on MSVC x64 optimised due to bad codegen bug in
// 'co_await whenAllTask' expression.
// Issue reported to MS on 19/11/2017.
TEST_CASE("when_all() with vector<task<T&>>"
* doctest::skip(CPPCORO_COMPILER_MSVC && CPPCORO_COMPILER_MSVC <= 191225805 &&
isOptimised && CPPCORO_CPU_X64))
{
check_when_all_vector_of_task_reference<cppcoro::task>();
}
// Disable test on MSVC x64 optimised due to bad codegen bug in
// 'co_await whenAllTask' expression.
// Issue reported to MS on 19/11/2017.
TEST_CASE("when_all() with vector<shared_task<T&>>"
* doctest::skip(CPPCORO_COMPILER_MSVC && CPPCORO_COMPILER_MSVC <= 191225805 &&
isOptimised && CPPCORO_CPU_X64))
{
check_when_all_vector_of_task_reference<cppcoro::shared_task>();
}
TEST_SUITE_END();
| 22.816092 | 111 | 0.672443 | toomuchsalt |
c1a3732f8f88d6bcca1283515024ce50f6da54b6 | 305 | cpp | C++ | allMatuCommit/根据公式输出圆周率(C++)_202021080718_20210920095442.cpp | BachWV/matu | d4e3a89385f0a205431dd34c2c7214af40bb8ddb | [
"MIT"
] | null | null | null | allMatuCommit/根据公式输出圆周率(C++)_202021080718_20210920095442.cpp | BachWV/matu | d4e3a89385f0a205431dd34c2c7214af40bb8ddb | [
"MIT"
] | null | null | null | allMatuCommit/根据公式输出圆周率(C++)_202021080718_20210920095442.cpp | BachWV/matu | d4e3a89385f0a205431dd34c2c7214af40bb8ddb | [
"MIT"
] | null | null | null | #include<iostream>
#include<math.h>
using namespace std;
int main() {
double i=0, a=1,sign=1;
double sum=0;
while (fabs(a) >= 1e-8) {
sum = sum + (sign *a);
i++;
a = 1/(2 * i + 1);
sign = -sign;
}
cout << "steps=" << i<<" " << "PI=" << sum*4.0;
} | 19.0625 | 49 | 0.429508 | BachWV |
c1a5382592dc116109dae31829044f0cf4264518 | 4,363 | cpp | C++ | src/trajectory_generator.cpp | marcomarasca/SDCND-Path-Planning | cf5a7104512d6d2d92943b53df040dc81e270511 | [
"MIT"
] | 1 | 2021-06-09T23:01:32.000Z | 2021-06-09T23:01:32.000Z | src/trajectory_generator.cpp | marcomarasca/SDCND-Path-Planning | cf5a7104512d6d2d92943b53df040dc81e270511 | [
"MIT"
] | 1 | 2020-10-03T08:58:44.000Z | 2020-10-17T13:05:14.000Z | src/trajectory_generator.cpp | marcomarasca/SDCND-Path-Planning | cf5a7104512d6d2d92943b53df040dc81e270511 | [
"MIT"
] | null | null | null | #include "trajectory_generator.h"
#include "Eigen/Dense"
#include "utils.h"
using Eigen::Matrix3d;
using Eigen::Vector3d;
PathPlanning::TrajectoryGenerator::TrajectoryGenerator(const Map &map, double step_dt, double max_speed, double max_acc)
: map(map), step_dt(step_dt), max_speed(max_speed), max_acc(max_acc) {}
PathPlanning::FTrajectory PathPlanning::TrajectoryGenerator::Generate(const Frenet &start, const Frenet &target,
size_t length) const {
const double t = length * this->step_dt;
// Computes the trajectory coefficients
const Coeff s_p_coeff = this->MinimizeJerk(start.s, target.s, t);
const Coeff s_v_coeff = this->Differentiate(s_p_coeff);
const Coeff s_a_coeff = this->Differentiate(s_v_coeff);
const Coeff d_p_coeff = this->MinimizeJerk(start.d, target.d, t);
const Coeff d_v_coeff = this->Differentiate(d_p_coeff);
const Coeff d_a_coeff = this->Differentiate(d_v_coeff);
PathPlanning::FTrajectory trajectory;
trajectory.reserve(length);
Frenet prev_state = start;
for (size_t i = 1; i <= length; ++i) {
const double t = i * this->step_dt;
const double max_s_delta = prev_state.s.v * this->step_dt + 0.5 * prev_state.s.a * this->step_dt * this->step_dt;
// Reduces longitudinal values to meet speed and acceleration constraints
const double s_p = std::min(this->Eval(t, s_p_coeff), prev_state.s.p + max_s_delta);
const double s_v = std::min(this->Eval(t, s_v_coeff), this->max_speed);
const double s_a = std::max(std::min(this->Eval(t, s_a_coeff), this->max_acc), -this->max_acc);
const double d_p = this->Eval(t, d_p_coeff);
const double d_v = this->Eval(t, d_v_coeff);
const double d_a = this->Eval(t, d_a_coeff);
const State s{Map::Mod(s_p), s_v, s_a};
const State d{d_p, d_v, d_a};
trajectory.emplace_back(s, d);
prev_state = {s, d};
}
return trajectory;
}
PathPlanning::FTrajectory PathPlanning::TrajectoryGenerator::Predict(const Frenet &start,
const StatePredictionFunction &prediction,
size_t length) const {
FTrajectory trajectory;
trajectory.reserve(length);
for (size_t i = 1; i <= length; ++i) {
const double t = i * step_dt;
trajectory.emplace_back(prediction(t));
}
return trajectory;
}
PathPlanning::CTrajectory PathPlanning::TrajectoryGenerator::FrenetToCartesian(const FTrajectory &trajectory) const {
std::vector<double> next_x_vals;
std::vector<double> next_y_vals;
for (auto &step : trajectory) {
auto coord = this->map.FrenetToCartesian(step.s.p, step.d.p);
next_x_vals.emplace_back(coord.first);
next_y_vals.emplace_back(coord.second);
}
return CTrajectory({next_x_vals, next_y_vals});
}
size_t PathPlanning::TrajectoryGenerator::TrajectoryLength(double t) const { return t / this->step_dt; }
PathPlanning::Coeff PathPlanning::TrajectoryGenerator::Differentiate(const Coeff &coefficients) const {
Coeff result(coefficients.size() - 1);
for (size_t i = 1; i < coefficients.size(); ++i) {
result[i - 1] = i * coefficients[i];
}
return result;
}
double PathPlanning::TrajectoryGenerator::Eval(double x, const Coeff &coefficients) const {
double y = 0;
for (size_t i = 0; i < coefficients.size(); ++i) {
y += coefficients[i] * std::pow(x, i);
}
return y;
}
PathPlanning::Coeff PathPlanning::TrajectoryGenerator::MinimizeJerk(const State &start, const State &target,
double t) const {
const double t_2 = t * t;
const double t_3 = t * t_2;
const double t_4 = t * t_3;
const double t_5 = t * t_4;
Matrix3d t_matrix;
t_matrix << t_3, t_4, t_5,
3 * t_2, 4 * t_3, 5 * t_4,
6 * t, 12 * t_2, 20 * t_3;
Vector3d s_vector;
s_vector << target.p - (start.p + start.v * t + 0.5 * start.a * t_2),
target.v - (start.v + start.a * t),
target.a - start.a;
Vector3d a_vector = t_matrix.inverse() * s_vector;
return {start.p, start.v, 0.5 * start.a, a_vector(0), a_vector(1), a_vector(2)};
} | 38.27193 | 121 | 0.62755 | marcomarasca |
c1a72bedb047741b20802031c3673c820b213dfb | 4,378 | cpp | C++ | src/dataaccess/datalayer/cache/cachebase.cpp | mage-game/metagame-xm-server | 193b67389262803fe0eae742800b1e878b5b3087 | [
"MIT"
] | 3 | 2021-12-16T13:57:28.000Z | 2022-03-26T07:50:08.000Z | src/dataaccess/datalayer/cache/cachebase.cpp | mage-game/metagame-xm-server | 193b67389262803fe0eae742800b1e878b5b3087 | [
"MIT"
] | null | null | null | src/dataaccess/datalayer/cache/cachebase.cpp | mage-game/metagame-xm-server | 193b67389262803fe0eae742800b1e878b5b3087 | [
"MIT"
] | 1 | 2022-03-26T07:50:11.000Z | 2022-03-26T07:50:11.000Z |
#include "cachebase.h"
#include "db/connpool.h"
#include "db/statement.h"
#include "db/connection.h"
int CacheBase::GetNagtiveCount()
{
return 100;
}
void CacheBase::Nagtive(IStatement *stmt)
{
m_nagtive_lock.Lock();
if( (int)m_nagtive_list.size() <= (GetNagtiveCount() / 2) )
{
NagtiveHelper(stmt);
}
m_nagtive_lock.Unlock();
}
void CacheBase::Unnagtive(IStatement *stmt)
{
m_nagtive_lock.Lock();
for(NagtiveList::const_iterator iter = m_nagtive_list.begin() ; iter != m_nagtive_list.end() ; ++iter)
{
m_dbcommand->Remove(stmt, *iter, false);
}
m_nagtive_list.clear();
m_nagtive_lock.Unlock();
}
long long CacheBase::GetNagtive()
{
m_nagtive_lock.Lock();
bool ret = true;
if(m_nagtive_list.empty())
{
IConnection *conn = ConnPool::Instance()->GetConn();
if (conn == 0)
{
return 0;
}
IStatement *stmt_tmp = conn->createStatement();
conn->begin(false);
ret = NagtiveHelper(stmt_tmp);
conn->commit();
delete stmt_tmp;
ConnPool::Instance()->PutConn(conn);
}
long long nagtive_id = 0;
if (ret)
{
nagtive_id = *m_nagtive_list.begin();
m_nagtive_list.pop_front();
}
m_nagtive_lock.Unlock();
return nagtive_id;
}
bool CacheBase::NagtiveHelper(IStatement *stmt)
{
DataAdapter t = m_table->GetPrototype();
t.Malloc();
for (int i = 0; i < (int)t.m_data_area.size(); ++i)
{
if (m_table->m_mata_data[i].type == DATYPE_STRING)
{
t.m_data_area[i].length = t.m_data_area[i].length > 1 ? 1 : t.m_data_area[i].length;
}
}
bool ret = true;
while((int)m_nagtive_list.size() < GetNagtiveCount())
{
if (m_dbcommand->Save(stmt, &t, false) != DBCommand::RESULT_SUC)
{
ret = false;
break;
}
m_nagtive_list.push_back(t.m_data_area[m_table->m_key_id_index].vint64);
}
t.Free();
return ret;
}
void CacheBase::Flush(IStatement *stmt)
{
MEM_NODE_MAP flushMap;
{
m_lock.Lock();
if(m_flush_map.size() == 0)
{
m_lock.Unlock();
return;
}
m_flush_map.swap(flushMap);
m_lock.Unlock();
}
for(MEM_NODE_MAP::iterator iter = flushMap.begin(); iter != flushMap.end(); ++iter)
{
switch(iter->second->GetUpdateMode())
{
case ECachedUpdateModelUpdate:
{
m_dbcommand->Update(stmt, *iter->second->GetNode(), false);
}
break;
case ECachedUpdateModelDelete:
{
DataAdapter *node = iter->second->GetNode();
m_dbcommand->Remove(stmt, node->m_data_area[m_table->m_key_id_index].vint64, false);
}
break;
}
iter->second->GetNode()->Free();
delete iter->second;
}
}
void CacheBase::Commit(ITransaction* transation)
{
m_lock.Lock();
TRANSACTION_MAP::iterator iter = m_transaction_nodes.find(transation);
if(m_transaction_nodes.end() == iter)
{
m_lock.Unlock();
return;
}
for(MEM_NODE_MAP::const_iterator iter1 = iter->second.begin(); iter1 != iter->second.end(); ++iter1)
{
MEM_NODE_MAP::iterator iter2 = m_flush_map.find(iter1->first);
if(iter1->second->GetUpdateMode() & ECachedUpdateModelDelete)
{
iter1->second->SetUpdateMode(ECachedUpdateModelDelete);
}
else if(iter1->second->GetUpdateMode() & ECachedUpdateModelAdd)
{
iter1->second->SetUpdateMode(ECachedUpdateModelUpdate);
}
else if(iter1->second->GetUpdateMode() & ECachedUpdateModelUpdate)
{
iter1->second->SetUpdateMode(ECachedUpdateModelUpdate);
}
if(iter2 == m_flush_map.end())
{
m_flush_map[iter1->first] = iter1->second;
}
else
{
iter2->second->GetNode()->Free();
delete iter2->second;
iter2->second = iter1->second;
}
}
m_transaction_nodes.erase(iter);
m_lock.Unlock();
}
void CacheBase::Rollback(ITransaction* transation)
{
m_lock.Lock();
TRANSACTION_MAP::iterator iter = m_transaction_nodes.find(transation);
if(m_transaction_nodes.end() == iter)
{
m_lock.Unlock();
return;
}
for(MEM_NODE_MAP::const_iterator iter1 = iter->second.begin(); iter1 != iter->second.end(); ++iter1)
{
if(iter1->second->GetUpdateMode() & ECachedUpdateModelAdd)
{
iter1->second->SetUpdateMode(ECachedUpdateModelDelete);
MEM_NODE_MAP::iterator iter2 = m_flush_map.find(iter1->first);
if(iter2 == m_flush_map.end())
{
m_flush_map[iter1->first] = iter1->second;
}
else
{
iter2->second->GetNode()->Free();
delete iter2->second;
iter2->second = iter1->second;
}
}
else
{
iter1->second->GetNode()->Free();
delete iter1->second;
}
}
m_transaction_nodes.erase(iter);
m_lock.Unlock();
}
| 21.89 | 103 | 0.679534 | mage-game |
c1a933dc92da5cf4d1256b14daa9af958f8914ec | 41,186 | cc | C++ | oommf/app/oxs/ext/rectangularmesh.cc | fangohr/oommf | 67fa0d69eadbbb9eef320babd07910f6d7b4e089 | [
"TCL"
] | 18 | 2016-04-29T10:11:29.000Z | 2022-02-13T08:48:39.000Z | oommf/app/oxs/ext/rectangularmesh.cc | fangohr/oommf | 67fa0d69eadbbb9eef320babd07910f6d7b4e089 | [
"TCL"
] | 29 | 2017-11-01T20:00:28.000Z | 2021-10-05T12:22:50.000Z | oommf/app/oxs/ext/rectangularmesh.cc | fangohr/oommf | 67fa0d69eadbbb9eef320babd07910f6d7b4e089 | [
"TCL"
] | 11 | 2015-10-17T19:41:29.000Z | 2021-05-12T08:32:37.000Z | /* FILE: rectangularmesh.cc -*-Mode: c++-*-
*
* Rectangular mesh, derived from Oxs_Mesh class.
*
*/
#include "nb.h"
#include "vf.h"
#include "atlas.h"
#include "meshvalue.h"
#include "oxsexcept.h"
#include "rectangularmesh.h"
#include "director.h"
#include "nb.h"
#include "energy.h" // Needed to make MSVC++ 5 happy
#include "util.h"
// Oxs_Ext registration support
OXS_EXT_REGISTER(Oxs_RectangularMesh);
OXS_EXT_REGISTER(Oxs_PeriodicRectangularMesh);
/* End includes */
////////////////////////////////////////////////////////////////////////
/// Support for max angle routines. See NOTES VI, 6-Sep-2012, p 71-73.
class OxsRectangularMeshAngle {
// This (internal) class is used to store a representation of the
// angle between two vectors. It is designed so that setting and
// order comparisons are quick; the radian angle (between 0 and pi)
// can be extracted via the GetAngle() call, but GetAngle() is slow
// and so shouldn't be called more often than necessary.
public:
void Set(const ThreeVector& a, const ThreeVector& b) {
OC_REAL8m dot = a*b;
ThreeVector cross = a^b;
sdotsq = dot * fabs(dot);
crosssq = cross.MagSq();
}
void SetAngle(OC_REAL8m angle) {
// Note: SetAngle(ang) == SetAngle(|ang|)
OC_REAL8m dot = cos(angle);
OC_REAL8m cross = sin(angle);
sdotsq = dot*fabs(dot);
crosssq = cross*cross;
}
OC_REAL8m GetAngle() {
// Returns angle in radians, 0<= ang <= pi
if(sdotsq < 0.0) {
return Oc_Atan2(sqrt(crosssq),-1*sqrt(-1*sdotsq));
}
return Oc_Atan2(sqrt(crosssq),sqrt(sdotsq));
}
friend OC_BOOL operator<(const OxsRectangularMeshAngle&,
const OxsRectangularMeshAngle&);
friend OC_BOOL operator>(const OxsRectangularMeshAngle&,
const OxsRectangularMeshAngle&);
friend OC_BOOL operator==(const OxsRectangularMeshAngle&,
const OxsRectangularMeshAngle&);
friend OC_BOOL operator!=(const OxsRectangularMeshAngle&,
const OxsRectangularMeshAngle&);
// Constructors:
OxsRectangularMeshAngle(const ThreeVector& a, const ThreeVector& b) {
Set(a,b);
}
OxsRectangularMeshAngle(OC_REAL8m angle) {
SetAngle(angle);
}
// Note: Use default destructor and assignment operator.
private:
// For vectors a, b:
OC_REAL8m crosssq; // |axb|^2 (non-negative)
OC_REAL8m sdotsq; // (a*b).|a*b| (signed)
};
OC_BOOL operator>(const OxsRectangularMeshAngle& a,
const OxsRectangularMeshAngle& b){
return (a.crosssq * b.sdotsq > a.sdotsq * b.crosssq);
}
OC_BOOL operator<(const OxsRectangularMeshAngle& a,
const OxsRectangularMeshAngle& b){
return (a.crosssq * b.sdotsq < a.sdotsq * b.crosssq);
}
OC_BOOL operator==(const OxsRectangularMeshAngle& a,
const OxsRectangularMeshAngle& b) {
return (a.crosssq * b.sdotsq == a.sdotsq * b.crosssq);
}
OC_BOOL operator!=(const OxsRectangularMeshAngle& a,
const OxsRectangularMeshAngle& b) {
return !(a == b);
}
/////////////////////////////////////////////////////////////////////
// Oxs_CommonRectangularMesh
void Oxs_CommonRectangularMesh::InitScaling(const Oxs_Box& box)
{ // Constructor helper function. Assumes cellsize is already set.
if(cellsize.x<=0.0 || cellsize.y<=0.0 || cellsize.z<=0.0) {
String msg = String("Invalid MIF input block detected for object ")
+ String(InstanceName());
throw Oxs_ExtError(msg.c_str());
}
cellvolume=cellsize.x*cellsize.y*cellsize.z;
OC_REAL8m xrange = box.GetMaxX() - box.GetMinX();
OC_REAL8m yrange = box.GetMaxY() - box.GetMinY();
OC_REAL8m zrange = box.GetMaxZ() - box.GetMinZ();
if(xrange<=0. || yrange<=0. || zrange<=0.) {
String msg = String("Invalid atlas range detected for object ")
+ String(InstanceName());
throw Oxs_ExtError(msg.c_str());
}
base = ThreeVector(box.GetMinX()+cellsize.x/2.,
box.GetMinY()+cellsize.y/2.,
box.GetMinZ()+cellsize.z/2.);
xdim = static_cast<OC_INDEX>(OC_ROUND(xrange/cellsize.x));
ydim = static_cast<OC_INDEX>(OC_ROUND(yrange/cellsize.y));
zdim = static_cast<OC_INDEX>(OC_ROUND(zrange/cellsize.z));
if(xdim<1 || ydim<1 || zdim<1) {
String msg = String("Invalid MIF input block detected for object ")
+ String(InstanceName())
+ String("; minimum range smaller than cell dimension.");
throw Oxs_ExtError(msg.c_str());
}
// Overflow test; restrict to signed value range
OC_INDEX testval = OC_INDEX((OC_UINDEX(1)<<(sizeof(OC_INDEX)*8-1))-1);
/// Maximum allowed value; Assumes 2's complement arithmetic
testval /= xdim;
testval /= ydim;
testval /= zdim;
if(testval<1) {
char buf[1024];
Oc_Snprintf(buf,sizeof(buf),"Requested mesh size (%ld x %ld x %ld)"
" has too many elements",(long)xdim,
(long)ydim,(long)zdim);
throw Oxs_ExtError(this,buf);
}
xydim = xdim*ydim;
elementcount = xydim*zdim;
if( fabs(xdim*cellsize.x - xrange) > 0.01*cellsize.x ||
fabs(ydim*cellsize.y - yrange) > 0.01*cellsize.y ||
fabs(zdim*cellsize.z - zrange) > 0.01*cellsize.z ) {
String msg = String("Invalid MIF input block detected for object ")
+ String(InstanceName())
+ String(": range is not an integral multiple of cellsize.");
throw Oxs_ExtError(msg.c_str());
}
}
// Main constructor, for use by Specify command in MIF input file
Oxs_CommonRectangularMesh::Oxs_CommonRectangularMesh
(const char* name, // Child instance id
Oxs_Director* newdtr, // App director
const char* argstr) // MIF input block parameters
: Oxs_Mesh(name,newdtr,argstr)
{
// Process arguments
cellsize = GetThreeVectorInitValue("cellsize");
Oxs_OwnedPointer<Oxs_Atlas> atlas;
OXS_GET_INIT_EXT_OBJECT("atlas",Oxs_Atlas,atlas);
Oxs_Box box;
atlas->GetWorldExtents(box);
InitScaling(box);
}
// Secondary constructor; provides a function-level API
// for use by other Oxs_Ext objects.
Oxs_CommonRectangularMesh::Oxs_CommonRectangularMesh
(const char* name, // Child instance id
Oxs_Director* newdtr, // App director
const char* argstr, // MIF input block parameters
const ThreeVector& in_cellsize,
const Oxs_Box& range_box)
: Oxs_Mesh(name,newdtr,argstr)
{
cellsize = in_cellsize;
InitScaling(range_box);
}
/////////////////////////////////////////////////////////////////////
// Constructor for internal use by MakeRefinedMesh member function.
Oxs_CommonRectangularMesh::Oxs_CommonRectangularMesh
(const char* name, // Child instance id
Oxs_Director* newdtr, // App director
const ThreeVector& in_base,
const ThreeVector& in_cellsize,
OC_INDEX in_xdim,OC_INDEX in_ydim,OC_INDEX in_zdim)
: Oxs_Mesh(name,newdtr),
base(in_base),cellsize(in_cellsize),
xdim(in_xdim),ydim(in_ydim),zdim(in_zdim)
{
if(cellsize.x<=0.0 || cellsize.y<=0.0 || cellsize.z<=0.0) {
String msg = String("Invalid cellsize data in constructor of"
" refined rectangular mesh object ")
+ String(InstanceName());
throw Oxs_ExtError(msg.c_str());
}
cellvolume=cellsize.x*cellsize.y*cellsize.z;
if(xdim<1 || ydim<1 || zdim<1) {
String msg = String("Invalid x/y/zdim data in constructor of"
" refined rectangular mesh object ")
+ String(InstanceName());
throw Oxs_ExtError(msg.c_str());
}
// Overflow test; restrict to signed value range
OC_INDEX testval = OC_INDEX((OC_UINDEX(1)<<(sizeof(OC_INDEX)*8-1))-1);
/// Maximum allowed value; Assumes 2's complement arithmetic
testval /= xdim;
testval /= ydim;
testval /= zdim;
if(testval<1) {
char buf[1024];
Oc_Snprintf(buf,sizeof(buf),"Requested refined mesh size"
" (%lu x %lu x %lu)"
" has too many elements",(unsigned long)xdim,
(unsigned long)ydim,(unsigned long)zdim);
throw Oxs_ExtError(this,buf);
}
xydim = xdim*ydim;
elementcount = xydim*zdim;
}
void Oxs_CommonRectangularMesh::GetBoundingBox(Oxs_Box& bbox) const
{
bbox.Set(base.x-cellsize.x/2., base.x-cellsize.x/2.+xdim*cellsize.x,
base.y-cellsize.y/2., base.y-cellsize.y/2.+ydim*cellsize.y,
base.z-cellsize.z/2., base.z-cellsize.z/2.+zdim*cellsize.z);
}
void
Oxs_CommonRectangularMesh::Center(OC_INDEX index,ThreeVector &location) const
{
#ifndef NDEBUG
if(index>elementcount) {
String msg = String("Index out of range "
"(Oxs_CommonRectangularMesh::Location(OC_INDEX) const)");
throw Oxs_ExtError(msg.c_str());
}
#endif
OC_INDEX iz = index/(xdim*ydim); index -= iz*xdim*ydim;
OC_INDEX iy = index/xdim; index -= iy*xdim;
OC_INDEX ix = index;
location.Set(base.x+ix*cellsize.x,
base.y+iy*cellsize.y,
base.z+iz*cellsize.z);
return;
}
OC_INDEX
Oxs_CommonRectangularMesh::FindNearestIndex(const ThreeVector& location) const
{ // Note: This code assumes cellsize.{x,y,z} are all > 0.
ThreeVector pt = location - base;
OC_INDEX ix=0;
if(pt.x>0) {
ix = static_cast<OC_INDEX>(OC_ROUND(pt.x / cellsize.x));
if(ix>=xdim) ix = xdim-1;
}
OC_INDEX iy=0;
if(pt.y>0) {
iy = static_cast<OC_INDEX>(OC_ROUND(pt.y / cellsize.y));
if(iy>=ydim) iy = ydim-1;
}
OC_INDEX iz=0;
if(pt.z>0) {
iz = static_cast<OC_INDEX>(OC_ROUND(pt.z / cellsize.z));
if(iz>=zdim) iz = zdim-1;
}
return Index(ix,iy,iz);
}
OC_BOOL
Oxs_CommonRectangularMesh::GetNeighborPoint
(const ThreeVector& pt,
OC_INDEX ngbr_index,
ThreeVector& ngbr_pt) const
{ // Fills ngbr_pt with location of neighbor element indexed
// by "ngbr_index", relative to pt. Returns 1 if
// ngbr_pt < number of neighbors (currently 6); otherwise
// 0 is returned, in which case ngbr_pt is unchanged.
// NB: ngbr_index is 0-based.
if(ngbr_index>5) return 0;
int sign = 1 - 2*(ngbr_index%2); // 0,2,4 => +1, 1,3,5 => -1
ngbr_pt = pt;
switch(ngbr_index/2) {
case 0: ngbr_pt.x += sign*cellsize.x; break;
case 1: ngbr_pt.y += sign*cellsize.y; break;
default: ngbr_pt.z += sign*cellsize.z; break;
}
return 1;
}
OC_INDEX
Oxs_CommonRectangularMesh::BoundaryList
(const Oxs_Atlas& atlas,
const String& region_name,
const Oxs_ScalarField& bdry_surface,
OC_REAL8m bdry_value,
const String& bdry_side,
vector<OC_INDEX> &BoundaryIndexList) const
{ // Boundary extraction. Returns list (technically, an STL vector) of
// indices for those elements inside base_region that have a neighbor
// (in the 6 nearest ngbr sense) such that the first element lies on
// one side (the "inside") of the surface specified by the
// Oxs_ScalarField bdry_surface + bdry_value, and the neighbor lies on
// the other (the "outside"). If the bdry_side argument is "<" or
// "<=", then the "inside" of the surface is the set of those points x
// for which bdry_surface.Value(x) < or <= (resp.) bdry_value. The
// bdry_side arguments ">" and ">=" are treated analogously. For
// backwards compatibility, "-" and "+" are accepted as synonyms for
// <= and >=, respectively.
// Return value is the number of entries in the export list.
// NB: The tested neighbors may lie outside the mesh proper, allowing
// elements on the edge of the mesh to be specified.
BoundaryIndexList.clear();
Oxs_Box world_box,work_box;
GetBoundingBox(world_box);
const OC_INDEX region_id = atlas.GetRegionId(region_name);
if(region_id<0) {
String msg=String("Region name ")
+ region_name
+ String(" not recognized by atlas ")
+ String(atlas.InstanceName())
+ String(" (Oxs_CommonRectangularMesh::BoundaryList() in object")
+ String(InstanceName())
+ String(").");
msg += String(" Known regions:");
vector<String> regions;
atlas.GetRegionList(regions);
for(unsigned int j=0;j<regions.size();++j) {
msg += String("\n ");
msg += regions[j];
}
throw Oxs_ExtError(msg);
}
atlas.GetRegionExtents(region_id,work_box);
work_box.Intersect(world_box); // work_box contains extents of
/// base_region contained inside mesh
OC_INDEX ixstart = OC_INDEX(ceil((work_box.GetMinX()-base.x)/cellsize.x));
OC_INDEX iystart = OC_INDEX(ceil((work_box.GetMinY()-base.y)/cellsize.y));
OC_INDEX izstart = OC_INDEX(ceil((work_box.GetMinZ()-base.z)/cellsize.z));
OC_INDEX ixstop = OC_INDEX(floor((work_box.GetMaxX()-base.x)/cellsize.x))+1;
OC_INDEX iystop = OC_INDEX(floor((work_box.GetMaxY()-base.y)/cellsize.y))+1;
OC_INDEX izstop = OC_INDEX(floor((work_box.GetMaxZ()-base.z)/cellsize.z))+1;
// Check sign
enum BdrySide { INVALID, LT, LE, GE, GT };
BdrySide side_check = INVALID;
if(bdry_side.compare("<")==0) side_check = LT;
else if(bdry_side.compare("<=")==0) side_check = LE;
else if(bdry_side.compare(">=")==0) side_check = GE;
else if(bdry_side.compare(">")==0) side_check = GT;
else if(bdry_side.compare("+")==0) side_check = GE;
else if(bdry_side.compare("-")==0) side_check = LE;
else {
String msg=String("Invalid boundary side representation: ")
+ bdry_side
+ String(" Should be one of <, <=, >=, or >.")
+ String(" (Oxs_CommonRectangularMesh::BoundaryList() in object")
+ String(InstanceName())
+ String(")");
throw Oxs_ExtError(msg.c_str());
}
const int check_sign = (side_check == LT || side_check == LE ? -1 : 1);
const int equal_check = (side_check == LE || side_check == GE ? 1 : 0);
OC_INDEX ixsize = ixstop-ixstart;
for(OC_INDEX iz=izstart;iz<izstop;iz++) {
for(OC_INDEX iy=iystart;iy<iystop;iy++) {
OC_INDEX row_index = Index(ixstart,iy,iz);
ThreeVector pt;
Center(row_index,pt);
for(OC_INDEX i=0; i<ixsize; ++i,pt.x+=cellsize.x) {
if(check_sign*(bdry_surface.Value(pt)-bdry_value)<0 ||
(!equal_check && bdry_surface.Value(pt) == bdry_value)) {
continue; // basept on wrong side of boundary
}
if(atlas.GetRegionId(pt) != region_id) {
continue; // Point not in specified region
}
OC_INDEX ngbr_index=0;
ThreeVector ngbr_pt;
while(GetNeighborPoint(pt,ngbr_index++,ngbr_pt)) {
if(check_sign*(bdry_surface.Value(ngbr_pt)-bdry_value)<0 ||
(!equal_check && bdry_surface.Value(ngbr_pt) == bdry_value)) {
// Neighbor on "other" side of boundary
BoundaryIndexList.push_back(row_index+i);
break; // Don't include pt more than once
}
}
}
}
}
return static_cast<OC_INDEX>(BoundaryIndexList.size());
}
// File (channel) output for ThreeVectors. Throws an exception on error.
void Oxs_CommonRectangularMesh::WriteOvf
(Tcl_Channel channel, // Output channel
OC_BOOL headers, // If false, then output only raw data
const char* title, // Long filename or title
const char* desc, // Description to embed in output file
const char* valueunit, // Field units, such as "A/m".
const char* meshtype, // Either "rectangular" or "irregular"
const char* datatype, // Either "binary" or "text"
const char* precision, // For binary, "4" or "8";
/// for text, a printf-style format
const Oxs_MeshValue<ThreeVector>* vec, // Vector array
const Oxs_MeshValue<OC_REAL8m>* scale // Optional scaling for vec
/// Set scale to NULL to use vec values directly.
) const
{
// Use default file writer for irregular mesh.
if(strcmp("irregular",meshtype)==0) {
ThreeVector stephints(cellsize.x,cellsize.y,cellsize.z);
WriteOvfIrregular(channel,headers,title,desc,valueunit,
datatype,precision,
vec,scale,&stephints);
return;
}
if(strcmp("rectangular",meshtype)!=0) {
String msg=String("Unrecognized mesh type request: ")
+ String(meshtype)
+ String("(Oxs_CommonRectangularMesh::WriteOvf() in object")
+ String(InstanceName()) + String(")");
OXS_EXTTHROW(Oxs_BadParameter,msg.c_str(),-1);
}
// Rectangular Mesh ////////////////////////////
// Check import validity
enum DataType { BINARY, TEXT };
DataType dt = BINARY;
if(strcmp("text",datatype)==0) {
dt = TEXT;
} else if(strcmp("binary",datatype)!=0){
String errmsg = String("Bad datatype: \"") + String(datatype)
+ String("\" Should be either \"binary\" or \"text\"");
OXS_EXTTHROW(Oxs_BadParameter,errmsg.c_str(),-1);
}
int datawidth = 0;
String dataformat;
if(dt == BINARY) {
datawidth = atoi(precision);
if(datawidth != 4 && datawidth != 8) {
String errmsg = String("Bad precision: ") + String(precision)
+ String(" Should be either 4 or 8.");
OXS_EXTTHROW(Oxs_BadParameter,errmsg.c_str(),-1);
}
} else {
if(precision==NULL || precision[0]=='\0')
precision="%# .17g"; // Default format
String temp = String(precision) + String(" ");
dataformat = temp + temp + String(precision) + String("\n");
}
if(!vec->CheckMesh(this)) {
char buf[1024];
Oc_Snprintf(buf,sizeof(buf),"Size mismatch; input data length=%u,"
" which is different than mesh size=%u",
vec->Size(),Size());
OXS_EXTTHROW(Oxs_BadParameter,buf,-1);
}
if(scale!=NULL && !scale->CheckMesh(this)) {
char buf[1024];
Oc_Snprintf(buf,sizeof(buf),"Size mismatch; input scale data length=%u,"
" which is different than mesh size=%u",
scale->Size(),Size());
OXS_EXTTHROW(Oxs_BadParameter,buf,-1);
}
if(headers) {
try {
// Write header
Nb_FprintfChannel(channel,NULL,1024,"# OOMMF: rectangular mesh v1.0\n");
Nb_FprintfChannel(channel,NULL,1024,"# Segment count: 1\n");
Nb_FprintfChannel(channel,NULL,1024,"# Begin: Segment\n");
Nb_FprintfChannel(channel,NULL,1024,"# Begin: Header\n");
if(title==NULL || title[0]=='\0')
Nb_FprintfChannel(channel,NULL,1024,"# Title: unknown\n");
else
Nb_FprintfChannel(channel,NULL,1024,"# Title: %s\n",title);
if(desc!=NULL && desc[0]!='\0') {
// Print out description, breaking at newlines as necessary.
// Note: This block is optional
const char *cptr1,*cptr2;
cptr1=desc;
while((cptr2=strchr(cptr1,'\n'))!=NULL) {
Nb_FprintfChannel(channel,NULL,1024,"# Desc: %.*s\n",
(int)(cptr2-cptr1),cptr1);
cptr1=cptr2+1;
}
if(*cptr1!='\0')
Nb_FprintfChannel(channel,NULL,1024,"# Desc: %s\n",cptr1);
}
Nb_FprintfChannel(channel,NULL,1024,"# meshtype: rectangular\n");
Nb_FprintfChannel(channel,NULL,1024,"# meshunit: m\n");
Nb_FprintfChannel(channel,NULL,1024,"# xbase: %.17g\n"
"# ybase: %.17g\n# zbase: %.17g\n",
static_cast<double>(base.x),
static_cast<double>(base.y),
static_cast<double>(base.z));
Nb_FprintfChannel(channel,NULL,1024,"# xstepsize: %.17g\n"
"# ystepsize: %.17g\n# zstepsize: %.17g\n",
static_cast<double>(cellsize.x),
static_cast<double>(cellsize.y),
static_cast<double>(cellsize.z));
Nb_FprintfChannel(channel,NULL,1024,"# xnodes: %d\n"
"# ynodes: %d\n# znodes: %d\n",
xdim,ydim,zdim);
Oxs_Box bbox;
GetBoundingBox(bbox);
Nb_FprintfChannel(channel,NULL,1024,
"# xmin: %.17g\n# ymin: %.17g\n# zmin: %.17g\n"
"# xmax: %.17g\n# ymax: %.17g\n# zmax: %.17g\n",
static_cast<double>(bbox.GetMinX()),
static_cast<double>(bbox.GetMinY()),
static_cast<double>(bbox.GetMinZ()),
static_cast<double>(bbox.GetMaxX()),
static_cast<double>(bbox.GetMaxY()),
static_cast<double>(bbox.GetMaxZ()));
Nb_FprintfChannel(channel,NULL,1024,"# valueunit: %s\n",valueunit);
Nb_FprintfChannel(channel,NULL,1024,"# valuemultiplier: 1\n");
// As of 6/2001, mmDisp supports display of out-of-plane rotations;
// Representing the boundary under these conditions is awkward with
// a single polygon. So don't write the boundary line, and rely
// on defaults based on the data range and step size.
OC_REAL8m minmag=0,maxmag=0;
if(Size()>0) {
minmag=DBL_MAX;
for(OC_INDEX i=0;i<Size();i++) {
OC_REAL8m val=(*vec)[i].MagSq();
if(scale!=NULL) {
OC_REAL8m tempscale=(*scale)[i];
val*=tempscale*tempscale;
}
if(val<minmag && val>0) minmag=val; // minmag is smallest non-zero
if(val>maxmag) maxmag=val; /// magnitude.
}
if(minmag>maxmag) minmag=maxmag;
maxmag=sqrt(maxmag);
minmag=sqrt(minmag);
minmag*=0.9999; // Underestimate lower bound by 0.01% to protect
/// against rounding errors.
}
Nb_FprintfChannel(channel,NULL,1024,
"# ValueRangeMinMag: %.17g\n",
static_cast<double>(minmag));
Nb_FprintfChannel(channel,NULL,1024,
"# ValueRangeMaxMag: %.17g\n",
static_cast<double>(maxmag));
Nb_FprintfChannel(channel,NULL,1024,"# End: Header\n");
} catch(...) {
OXS_EXTTHROW(Oxs_DeviceFull,
"Error writing OVF file header;"
" disk full or buffer overflow?",-1);
}
}
// Write data block
try {
if(dt == BINARY) {
if(datawidth==4) {
OC_REAL4 buf[3];
if(headers) {
Nb_FprintfChannel(channel,NULL,1024,"# Begin: Data Binary 4\n");
buf[0]=1234567.; // 4-Byte checkvalue
if(Vf_OvfFileFormatSpecs::WriteBinary(channel,buf,1)) {
throw Oxs_CommonRectangularMesh_WBError();
}
}
OC_INDEX size=Size();
for(OC_INDEX i=0 ; i<size ; ++i) {
const ThreeVector& v = (*vec)[i];
if(scale==NULL) {
buf[0] = static_cast<OC_REAL4>(v.x);
buf[1] = static_cast<OC_REAL4>(v.y);
buf[2] = static_cast<OC_REAL4>(v.z);
} else {
OC_REAL8m tempscale=(*scale)[i];
buf[0] = static_cast<OC_REAL4>(tempscale*v.x);
buf[1] = static_cast<OC_REAL4>(tempscale*v.y);
buf[2] = static_cast<OC_REAL4>(tempscale*v.z);
}
// Vf_OvfFileFormatSpecs::WriteBinary performs
// byte-swapping as needed.
if(Vf_OvfFileFormatSpecs::WriteBinary(channel,buf,3)) {
throw Oxs_CommonRectangularMesh_WBError();
}
}
if(headers) {
Nb_FprintfChannel(channel,NULL,1024,"\n# End: Data Binary 4\n");
}
} else {
// datawidth==8
OC_REAL8 buf[3];
if(headers) {
Nb_FprintfChannel(channel,NULL,1024,"# Begin: Data Binary 8\n");
buf[0]=123456789012345.; // 8-Byte checkvalue
if(Vf_OvfFileFormatSpecs::WriteBinary(channel,buf,1)) {
throw Oxs_CommonRectangularMesh_WBError();
}
}
OC_INDEX size=Size();
for(OC_INDEX i=0 ; i<size ; ++i) {
const ThreeVector& v = (*vec)[i];
if(scale==NULL) {
buf[0] = static_cast<OC_REAL8>(v.x);
buf[1] = static_cast<OC_REAL8>(v.y);
buf[2] = static_cast<OC_REAL8>(v.z);
} else {
OC_REAL8m tempscale=(*scale)[i];
buf[0] = static_cast<OC_REAL8>(tempscale*v.x);
buf[1] = static_cast<OC_REAL8>(tempscale*v.y);
buf[2] = static_cast<OC_REAL8>(tempscale*v.z);
}
// Vf_OvfFileFormatSpecs::WriteBinary performs
// byte-swapping as needed.
if(Vf_OvfFileFormatSpecs::WriteBinary(channel,buf,3)) {
throw Oxs_CommonRectangularMesh_WBError();
}
}
if(headers) {
Nb_FprintfChannel(channel,NULL,1024,"\n# End: Data Binary 8\n");
}
}
} else {
if(headers) {
Nb_FprintfChannel(channel,NULL,1024,"# Begin: Data Text\n");
}
OC_INDEX size=Size();
for(OC_INDEX i=0 ; i<size ; ++i) {
const ThreeVector& v = (*vec)[i];
if(scale==NULL) {
Nb_FprintfChannel(channel,NULL,1024,dataformat.c_str(),
static_cast<double>(v.x),
static_cast<double>(v.y),
static_cast<double>(v.z));
} else {
OC_REAL8m tempscale=(*scale)[i];
Nb_FprintfChannel(channel,NULL,1024,dataformat.c_str(),
static_cast<double>(tempscale*v.x),
static_cast<double>(tempscale*v.y),
static_cast<double>(tempscale*v.z));
}
}
if(headers) {
Nb_FprintfChannel(channel,NULL,1024,"# End: Data Text\n");
}
}
if(headers) {
Nb_FprintfChannel(channel,NULL,1024,"# End: Segment\n");
}
} catch(Oxs_CommonRectangularMesh_WBError&) {
OXS_EXTTHROW(Oxs_DeviceFull,
"Error writing OVF file binary data block;"
" disk full?",-1);
} catch(...) {
OXS_EXTTHROW(Oxs_DeviceFull,
"Error writing OVF file data block;"
" disk full or buffer overflow?",-1);
}
}
////////////////////////////////////////////////////////////////////
// Geometry string from common rectangular mesh interface.
String Oxs_CommonRectangularMesh::GetGeometryString() const {
char buf[1024];
Oc_Snprintf(buf,sizeof(buf),"%ld x %ld x %ld = %ld cells",
(long)xdim,(long)ydim,(long)zdim,(long)Size());
return String(buf);
}
/////////////////////////////////////////////////////////////////
// Vf_Ovf20_MeshNodes interface function DumpGeometry.
void Oxs_CommonRectangularMesh::DumpGeometry
(Vf_Ovf20FileHeader& header,
Vf_Ovf20_MeshType type) const
{
if(type == vf_ovf20mesh_irregular) {
DumpIrregGeometry(header);
header.xstepsize.Set(cellsize.x);
header.ystepsize.Set(cellsize.y);
header.zstepsize.Set(cellsize.z);
if(!header.IsValidGeom()) {
String msg=String("Invalid header (irregular mesh type) in"
" Oxs_CommonRectangularMesh::DumpGeometry()"
" in object ")
+ String(InstanceName());
throw Oxs_ExtError(msg.c_str());
}
return;
}
if(type != vf_ovf20mesh_rectangular) {
String msg=String("Unrecognized mesh type request in"
" Oxs_CommonRectangularMesh::DumpGeometry()"
" in object ")
+ String(InstanceName());
throw Oxs_ExtError(msg.c_str());
}
header.meshtype.Set(vf_ovf20mesh_rectangular);
header.meshunit.Set(String("m"));
Oxs_Box bbox;
GetBoundingBox(bbox);
header.xmin.Set(bbox.GetMinX());
header.ymin.Set(bbox.GetMinY());
header.zmin.Set(bbox.GetMinZ());
header.xmax.Set(bbox.GetMaxX());
header.ymax.Set(bbox.GetMaxY());
header.zmax.Set(bbox.GetMaxZ());
header.xbase.Set(base.x);
header.ybase.Set(base.y);
header.zbase.Set(base.z);
header.xnodes.Set(xdim);
header.ynodes.Set(ydim);
header.znodes.Set(zdim);
header.xstepsize.Set(cellsize.x);
header.ystepsize.Set(cellsize.y);
header.zstepsize.Set(cellsize.z);
if(!header.IsValidGeom()) {
String msg=String("Invalid header (rectangular mesh type) in"
" Oxs_CommonRectangularMesh::DumpGeometry()"
" in object ")
+ String(InstanceName());
throw Oxs_ExtError(msg.c_str());
}
}
//////////////////////////////////////////////////////////////////////
// Conversion routines from Vf_Mesh to Oxs_MeshValue<ThreeVector>.
// IsCompatible returns true iff vfmesh is a Vf_GridVec3f with
// dimensions identical to those of *this.
// NB: IsCompatible only compares the mesh dimensions, not the
// underlying physical scale, or the cell aspect ratios. Do
// we want to include such a check?, or is it more flexible
// to leave it out?
// FillMeshValueExact copies the vector field held in vfmesh to the
// export Oxs_MeshValue<ThreeVector> vec. This routine throws
// an exception on error, the primary cause of which is that
// vfmesh is not compatible with *this. In other words, if you
// don't want to catch the exception, call IsCompatible first.
// The "Exact" in the name refers to the requirement that the
// dimensions on vfmesh exactly match those of *this.
OC_BOOL Oxs_CommonRectangularMesh::IsCompatible(const Vf_Mesh* vfmesh) const
{
const Vf_GridVec3f* gridmesh
= dynamic_cast<const Vf_GridVec3f*>(vfmesh);
if(gridmesh==NULL) return 0;
OC_INDEX isize,jsize,ksize;
gridmesh->GetDimens(isize,jsize,ksize);
if(xdim != isize ||
ydim != jsize ||
zdim != ksize ) {
return 0;
}
return 1;
}
void Oxs_CommonRectangularMesh::FillMeshValueExact
(const Vf_Mesh* vfmesh,
Oxs_MeshValue<ThreeVector>& vec) const
{
const Vf_GridVec3f* gridmesh
= dynamic_cast<const Vf_GridVec3f*>(vfmesh);
if(gridmesh==NULL || !IsCompatible(vfmesh)) {
throw Oxs_ExtError(this,
"Incompatible Vf_Mesh import to"
" FillMeshValue(const Vf_Mesh*,"
" Oxs_MeshValue<ThreeVector>&)");
}
vec.AdjustSize(this);
// Both Oxs_CommonRectangularMesh and Vf_GridVec3f access with the
// x-dimension index changing fastest, z-dimension index changing
// slowest.
OC_INDEX i,j,k;
OC_REAL8m scale = gridmesh->GetValueMultiplier();
if(scale==1.0) { // Common case?
for(k=0;k<zdim;++k) for(j=0;j<ydim;++j) for(i=0;i<xdim;++i) {
const Nb_Vec3<OC_REAL8>& nbvec = gridmesh->GridVec(i,j,k);
vec[Index(i,j,k)].Set(nbvec.x,nbvec.y,nbvec.z);
}
} else {
for(k=0;k<zdim;++k) for(j=0;j<ydim;++j) for(i=0;i<xdim;++i) {
const Nb_Vec3<OC_REAL8>& nbvec = gridmesh->GridVec(i,j,k);
vec[Index(i,j,k)].Set(scale*nbvec.x,
scale*nbvec.y,
scale*nbvec.z);
}
}
}
//////////////////////////////////////////////////////////////////////
// Volume summing routines. This have advantage over the generic
// in that for Oxs_CommonRectangularMesh all cells have same volume.
OC_REAL8m Oxs_CommonRectangularMesh::VolumeSum
(const Oxs_MeshValue<OC_REAL8m>& scalar) const
{
if(!scalar.CheckMesh(this)) {
throw Oxs_ExtError(this,
"Incompatible scalar array import to"
" VolumeSum(const Oxs_MeshValue<OC_REAL8m>&)");
}
const OC_INDEX size=Size();
OC_REAL8m sum=0.0;
for(OC_INDEX i=0;i<size;i++) sum += scalar[i];
sum *= cellvolume;
return sum;
}
ThreeVector Oxs_CommonRectangularMesh::VolumeSum
(const Oxs_MeshValue<ThreeVector>& vec) const
{
if(!vec.CheckMesh(this)) {
throw Oxs_ExtError(this,
"Incompatible import array to"
" VolumeSum(const Oxs_MeshValue<ThreeVector>&)");
}
const OC_INDEX size=Size();
ThreeVector sum(0.,0.,0.);
for(OC_INDEX i=0;i<size;i++) sum += vec[i] ;
sum *= cellvolume;
return sum;
}
ThreeVector Oxs_CommonRectangularMesh::VolumeSum
(const Oxs_MeshValue<ThreeVector>& vec,
const Oxs_MeshValue<OC_REAL8m>& scale
) const
{
if(!vec.CheckMesh(this) || !scale.CheckMesh(this)) {
throw Oxs_ExtError(this,
"Incompatible import array to"
" VolumeSum(const Oxs_MeshValue<ThreeVector>&,"
" const Oxs_MeshValue<OC_REAL8m>& scale)");
}
const OC_INDEX size=Size();
ThreeVector sum(0.,0.,0.);
for(OC_INDEX i=0;i<size;i++) {
sum += scale[i] * vec[i];
}
sum *= cellvolume;
return sum;
}
OC_REAL8m Oxs_CommonRectangularMesh::VolumeSumXp
(const Oxs_MeshValue<OC_REAL8m>& scalar) const
{
if(!scalar.CheckMesh(this)) {
throw Oxs_ExtError(this,
"Incompatible scalar array import to"
" VolumeSumXp(const Oxs_MeshValue<OC_REAL8m>&)");
}
Nb_Xpfloat sum=0.;
const OC_INDEX size=Size();
for(OC_INDEX i=0;i<size;i++) sum += scalar[i];
sum *= cellvolume;
return sum.GetValue();
}
ThreeVector Oxs_CommonRectangularMesh::VolumeSumXp
(const Oxs_MeshValue<ThreeVector>& vec) const
{
if(!vec.CheckMesh(this)) {
throw Oxs_ExtError(this,
"Incompatible import array to"
" VolumeSumXp(const Oxs_MeshValue<ThreeVector>&)");
}
Nb_Xpfloat sum_x=0.,sum_y=0.,sum_z=0.;
const OC_INDEX size=Size();
for(OC_INDEX i=0;i<size;i++) {
sum_x += vec[i].x;
sum_y += vec[i].y;
sum_z += vec[i].z;
}
sum_x *= cellvolume;
sum_y *= cellvolume;
sum_z *= cellvolume;
return ThreeVector(sum_x.GetValue(),sum_y.GetValue(),sum_z.GetValue());
}
ThreeVector Oxs_CommonRectangularMesh::VolumeSumXp
(const Oxs_MeshValue<ThreeVector>& vec,
const Oxs_MeshValue<OC_REAL8m>& scale
) const
{
if(!vec.CheckMesh(this) || !scale.CheckMesh(this)) {
throw Oxs_ExtError(this,
"Incompatible import array to"
" VolumeSumXp(const Oxs_MeshValue<ThreeVector>&,"
" const Oxs_MeshValue<OC_REAL8m>& scale)");
}
Nb_Xpfloat sum_x=0.,sum_y=0.,sum_z=0.;
const OC_INDEX size=Size();
for(OC_INDEX i=0;i<size;i++) {
OC_REAL8m wgt = scale[i];
sum_x += wgt*vec[i].x;
sum_y += wgt*vec[i].y;
sum_z += wgt*vec[i].z;
}
sum_x *= cellvolume;
sum_y *= cellvolume;
sum_z *= cellvolume;
return ThreeVector(sum_x.GetValue(),sum_y.GetValue(),sum_z.GetValue());
}
/////////////////////////////////////////////////////////////////////
// Oxs_RectangularMesh (non-periodic)
// Main constructor, for use by Specify command in MIF input file
Oxs_RectangularMesh::Oxs_RectangularMesh
(const char* name, // Child instance id
Oxs_Director* newdtr, // App director
const char* argstr) // MIF input block parameters
: Oxs_CommonRectangularMesh(name,newdtr,argstr)
{
VerifyAllInitArgsUsed();
}
void Oxs_RectangularMesh::MakeRefinedMesh
(const char* name,
OC_INDEX refine_x,OC_INDEX refine_y,OC_INDEX refine_z,
Oxs_OwnedPointer<Oxs_RectangularMesh>& out_mesh) const
{
if(refine_x<1 || refine_y<1 || refine_z<1) {
char buf[1024];
Oc_Snprintf(buf,sizeof(buf),"Invalid refinment request:"
" (%lu x %lu x %lu)"
" All refinement values must be >=1;"
" Error in MakeRefinedMesh function in"
" rectangular mesh object ",
(unsigned long)refine_x,
(unsigned long)refine_y,
(unsigned long)refine_z);
String msg = String(buf) + String(InstanceName());
throw Oxs_ExtError(msg.c_str());
}
ThreeVector new_cellsize = GetCellsize();
new_cellsize.x /= static_cast<OC_REAL8m>(refine_x);
new_cellsize.y /= static_cast<OC_REAL8m>(refine_y);
new_cellsize.z /= static_cast<OC_REAL8m>(refine_z);
ThreeVector new_base = GetBase();
new_base.Accum(-0.5,GetCellsize());
new_base.Accum( 0.5,new_cellsize);
Oxs_RectangularMesh *refined_mesh
= new Oxs_RectangularMesh(name,director,new_base,new_cellsize,
refine_x*DimX(),
refine_y*DimY(),
refine_z*DimZ());
out_mesh.SetAsOwner(refined_mesh);
}
// Max angle routine. This routine returns the maximum angle
// between neighboring vectors across the mesh, for all
// those vectors for which the corresponding entry in zero_check
// is non-zero.
OC_REAL8m Oxs_RectangularMesh::MaxNeighborAngle
(const Oxs_MeshValue<ThreeVector>& vec,
const Oxs_MeshValue<OC_REAL8m>& zero_check,
OC_INDEX node_start,OC_INDEX node_stop) const
{
if(!vec.CheckMesh(this)) {
throw Oxs_ExtError(this,
"Incompatible import array to"
" MaxNeighborAngle(const Oxs_MeshValue<ThreeVector>&,"
" const Oxs_MeshValue<OC_REAL8m>& scale)");
}
if(Size()<2) return 0.0;
OxsRectangularMeshAngle maxangX(0.0); // 0.0 is min possible angle
OxsRectangularMeshAngle maxangY(0.0);
OxsRectangularMeshAngle maxangZ(0.0);
const OC_INDEX dimx = DimX(); // For convenience
const OC_INDEX dimy = DimY(); // For convenience
const OC_INDEX dimz = DimZ(); // For convenience
const OC_INDEX dimxy = dimx*dimy;
OC_INDEX ix,iy,iz;
GetCoords(node_start,ix,iy,iz);
for(OC_INDEX index=node_start;index<node_stop;++index) {
if(zero_check[index]!=0.0) {
if(ix+1<dimx && zero_check[index+1]!=0.0) {
OxsRectangularMeshAngle test(vec[index],vec[index+1]);
if(test>maxangX) maxangX = test;
}
if(iy+1<dimy && zero_check[index+dimx]!=0.0) {
OxsRectangularMeshAngle test(vec[index],vec[index+dimx]);
if(test>maxangY) maxangY = test;
}
if(iz+1<dimz && zero_check[index+dimxy]!=0.0) {
OxsRectangularMeshAngle test(vec[index],vec[index+dimxy]);
if(test>maxangZ) maxangZ = test;
}
}
if(++ix >= dimx) {
ix=0;
if(++iy >= dimy) {
iy=0; ++iz;
}
}
}
if(maxangY > maxangX) maxangX = maxangY;
if(maxangZ > maxangX) maxangX = maxangZ;
return maxangX.GetAngle();
}
/////////////////////////////////////////////////////////////////////
// Oxs_PeriodicRectangularMesh
// Main constructor, for use by Specify command in MIF input file
Oxs_PeriodicRectangularMesh::Oxs_PeriodicRectangularMesh
(const char* name, // Child instance id
Oxs_Director* newdtr, // App director
const char* argstr) // MIF input block parameters
: Oxs_CommonRectangularMesh(name,newdtr,argstr),
xperiodic(0),yperiodic(0),zperiodic(0)
{
// Periodic boundary selection.
String periodic = GetStringInitValue("periodic");
int badbits=0;
for(size_t i=0;i<periodic.size();++i) {
switch(tolower(periodic[i])) {
case 'x': xperiodic=1; break;
case 'y': yperiodic=1; break;
case 'z': zperiodic=1; break;
default: ++badbits; break;
}
}
if(badbits>0) {
String msg=String("Invalid periodic request string: ")
+ periodic
+ String("\n Should be a non-empty subset of \"xyz\".");
throw Oxs_ExtError(this,msg.c_str());
}
if(xperiodic+yperiodic+zperiodic==0) {
String msg=String("Invalid periodic request string ---"
" no periodic directions requested. "
" For non-periodic systems use"
" Oxs_RectangularMesh.");
throw Oxs_ExtError(this,msg.c_str());
}
VerifyAllInitArgsUsed();
}
// Max angle routine. This routine returns the maximum angle
// between neighboring vectors across the mesh, for all
// those vectors for which the corresponding entry in zero_check
// is non-zero.
OC_REAL8m Oxs_PeriodicRectangularMesh::MaxNeighborAngle
(const Oxs_MeshValue<ThreeVector>& vec,
const Oxs_MeshValue<OC_REAL8m>& zero_check,
OC_INDEX node_start,OC_INDEX node_stop) const
{
if(!vec.CheckMesh(this)) {
throw Oxs_ExtError(this,
"Incompatible import array to"
" MaxNeighborAngle(const Oxs_MeshValue<ThreeVector>&,"
" const Oxs_MeshValue<OC_REAL8m>& scale)");
}
if(Size()<2) return 0.0;
OxsRectangularMeshAngle maxangX(0.0); // 0.0 is min possible angle
OxsRectangularMeshAngle maxangY(0.0);
OxsRectangularMeshAngle maxangZ(0.0);
const OC_INDEX dimx = DimX(); // For convenience
const OC_INDEX dimy = DimY(); // For convenience
const OC_INDEX dimz = DimZ(); // For convenience
const OC_INDEX dimxy = dimx*dimy;
const OC_INDEX zwrap = (dimz-1)*dimxy;
OC_INDEX ix,iy,iz;
GetCoords(node_start,ix,iy,iz);
for(OC_INDEX index=node_start;index<node_stop;++index) {
if(zero_check[index]!=0.0) {
if(ix+1<dimx) {
if(zero_check[index+1]!=0.0) {
OxsRectangularMeshAngle test(vec[index],vec[index+1]);
if(test>maxangX) maxangX = test;
}
} else if(xperiodic && zero_check[index+1-dimx]!=0) {
OxsRectangularMeshAngle test(vec[index],vec[index+1-dimx]);
if(test>maxangX) maxangX = test;
}
if(iy+1<dimy) {
if(zero_check[index+dimx]!=0.0) {
OxsRectangularMeshAngle test(vec[index],vec[index+dimx]);
if(test>maxangY) maxangY = test;
}
} else if(yperiodic && zero_check[index+dimx-dimxy]!=0) {
OxsRectangularMeshAngle test(vec[index],vec[index+dimx-dimxy]);
if(test>maxangY) maxangY = test;
}
if(iz+1<dimz) {
if(zero_check[index+dimxy]!=0.0) {
OxsRectangularMeshAngle test(vec[index],vec[index+dimxy]);
if(test>maxangZ) maxangZ = test;
}
} else if(zperiodic && zero_check[index-zwrap]!=0) {
OxsRectangularMeshAngle test(vec[index],vec[index-zwrap]);
if(test>maxangZ) maxangZ = test;
}
}
if(++ix >= dimx) {
ix=0;
if(++iy >= dimy) {
iy=0; ++iz;
}
}
}
if(maxangY > maxangX) maxangX = maxangY;
if(maxangZ > maxangX) maxangX = maxangZ;
return maxangX.GetAngle();
}
| 35.292202 | 78 | 0.619215 | fangohr |
c1aa769e9759479190f0376cde279662b9846eb1 | 373 | cpp | C++ | Arduino/build/sketch/ClassName.cpp | CrtomirJuren/ball-beam-pid-control | 3ce0cdfd946213b0330c24e24cd1c453efb97990 | [
"MIT"
] | null | null | null | Arduino/build/sketch/ClassName.cpp | CrtomirJuren/ball-beam-pid-control | 3ce0cdfd946213b0330c24e24cd1c453efb97990 | [
"MIT"
] | null | null | null | Arduino/build/sketch/ClassName.cpp | CrtomirJuren/ball-beam-pid-control | 3ce0cdfd946213b0330c24e24cd1c453efb97990 | [
"MIT"
] | null | null | null | #include "Arduino.h"
#include "ClassName.h"
// class constructor
ClassName::ClassName(int pin)
{
//pinMode(pin, OUTPUT);
_pin = pin;
}
void ClassName::dot()
{
//digitalWrite(_pin, HIGH);
delay(10);
//digitalWrite(_pin, LOW);
//delay(250);
}
void ClassName::dash()
{
//digitalWrite(_pin, HIGH);
delay(10);
//digitalWrite(_pin, LOW);
//delay(250);
}
| 14.346154 | 29 | 0.632708 | CrtomirJuren |
c1aa805b870beded8db42ced40c0281d05694d63 | 2,760 | cpp | C++ | KCPlugins/Housing/mealcalendar.cpp | louvainlinux/KapCompta | 8d871a718f945748dbed9207222bfd1efb6d5526 | [
"MIT"
] | 1 | 2015-08-26T14:17:26.000Z | 2015-08-26T14:17:26.000Z | KCPlugins/Housing/mealcalendar.cpp | louvainlinux/KapCompta | 8d871a718f945748dbed9207222bfd1efb6d5526 | [
"MIT"
] | null | null | null | KCPlugins/Housing/mealcalendar.cpp | louvainlinux/KapCompta | 8d871a718f945748dbed9207222bfd1efb6d5526 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2012-2013, Olivier Tilmans
*
* 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 "mealcalendar.h"
#include <QPainter>
#include <QRect>
MealCalendar::MealCalendar(QWidget *parent) :
QCalendarWidget(parent)
{
}
void MealCalendar::setCurrentMonthHighlights(const QHash<int,int>& highlights)
{
this->highlights = QHash<int,int>(highlights);
update();
}
void MealCalendar::setHighlightsForDay(int day, int highlights)
{
this->highlights[day] = highlights;
updateCell(QDate(QCalendarWidget::yearShown(), QCalendarWidget::monthShown(), day));
}
void MealCalendar::paintCell(QPainter *painter, const QRect &rect, const QDate &date) const
{
QCalendarWidget::paintCell(painter, rect, date);
if (highlights.value(date.day()) > 0
&& date.month() == QCalendarWidget::selectedDate().month()) {
painter->save();
// Set background color to green because there are meal(s) that day
QFontMetrics fm = painter->fontMetrics();
int w = fm.width(QString::number(highlights.value(date.day())));
int h = fm.height();
int max = qMax(w, h) + 3;
QRect r = QRect(rect.x(), rect.y(), max, max);
painter->setBrush(QBrush(Qt::darkCyan, Qt::SolidPattern));
painter->setPen(Qt::NoPen);
painter->drawEllipse(r);
painter->setBrush(Qt::NoBrush);
painter->setPen(Qt::lightGray);
painter->drawRect(QRect(rect.x(), rect.y(), rect.width()-1, rect.height()-1));
painter->restore();
painter->drawText(QRect(r.x(), r.y() + max/2 - h/2, max, max),
QString::number(highlights.value(date.day())),
QTextOption(Qt::AlignCenter));
}
}
| 40.588235 | 99 | 0.681884 | louvainlinux |
c1aad387194468dec80a0d3d8197823493e1dfa5 | 10,592 | cpp | C++ | SIGMA/contig_reader.cpp | lorenzgerber/OPERA-MS | bd1fb94f73a1bb7cefe3d9ad438bc3c53c069f9f | [
"MIT"
] | 81 | 2018-03-22T15:01:08.000Z | 2022-01-17T17:52:31.000Z | SIGMA/contig_reader.cpp | lorenzgerber/OPERA-MS | bd1fb94f73a1bb7cefe3d9ad438bc3c53c069f9f | [
"MIT"
] | 68 | 2017-09-14T08:17:53.000Z | 2022-03-09T18:56:12.000Z | SIGMA/contig_reader.cpp | lorenzgerber/OPERA-MS | bd1fb94f73a1bb7cefe3d9ad438bc3c53c069f9f | [
"MIT"
] | 21 | 2017-09-14T06:15:18.000Z | 2021-09-30T03:19:22.000Z | #include <cstdlib>
#include <cstdio>
#include <iostream>
#include <fstream>
#include <string.h>
#include "contig_reader.h"
#include "sigma.h"
ContigReader::~ContigReader() {}
AllReader::AllReader(){}
long int AllReader::read(const char* contigs_file, ContigMap* contigs) {
int length = 0;
long int assembly_size = 0;
std::string id;
std::ifstream contigs_fp(contigs_file);
if (contigs_fp.is_open()) {
while(true){
std::string line;
if(!std::getline(contigs_fp, line)){
if (length !=0 && length >= Sigma::contig_len_thr){
contigs -> insert(std::make_pair(id, new Contig(id, length)));
// std::cerr << length << "\n";
// std::cerr << id <<"\n";
}
assembly_size += length;
break;
}
if(line[0] != '>'){
length += (int) line.size();
}
else{
assembly_size += length;
if (length != 0 && length >= Sigma::contig_len_thr){
contigs -> insert(std::make_pair(id, new Contig(id, length)));
// std::cerr << id << "\n";
// std::cerr << length << "\n";
}
id = line.substr(1, line.find(' ') - 1);
length = 0;
}
}
contigs_fp.close();
}
else {
fprintf(stderr, "Error opening file: %s\n", contigs_file);
exit(EXIT_FAILURE);
}
std::string assembly_size_name = Sigma::output_dir + "/assembly_size.dat";
FILE* assembly_size_file = fopen(assembly_size_name.c_str(), "w");
if (assembly_size_file != NULL) {
fprintf(assembly_size_file, "%ld\n", assembly_size);
fclose(assembly_size_file);
}
return assembly_size;
}
void AllReader::get_assembly_size(const char* contigs_file){
int length = 0;
long int assembly_size = 0;
long int assembly_nb_contig = 0;
std::ifstream contigs_fp(contigs_file);
if (contigs_fp.is_open()) {
std::string line;
while(true){
std::string line;
if(!std::getline(contigs_fp, line)){
assembly_size+= length;
break;
}
if(line[0] != '>'){
length += (int) line.size();
}
else{
assembly_size += length;
assembly_nb_contig++;
length = 0;
}
}
contigs_fp.close();
}
else {
fprintf(stderr, "Error opening file: %s\n", contigs_file);
exit(EXIT_FAILURE);
}
std::string assembly_size_name = Sigma::output_dir + "/assembly_size.dat";
FILE* assembly_size_file = fopen(assembly_size_name.c_str(), "w");
if (assembly_size_file != NULL) {
fprintf(assembly_size_file, "%ld\n", assembly_size);
fprintf(assembly_size_file, "%ld\n", assembly_nb_contig);
fclose(assembly_size_file);
}
Sigma::total_assembly_size = assembly_size;
Sigma::total_assembly_nb_contig = assembly_nb_contig;
}
SOAPdenovoReader::SOAPdenovoReader() {}
long int SOAPdenovoReader::read(const char* contigs_file, ContigMap* contigs) {
char id[256];
int length;
long int assembly_size = 0;
FILE* contigs_fp = fopen(contigs_file, "r");
if (contigs_fp != NULL) {
while (!feof(contigs_fp)) {
// >[ID] length [LENGTH] cvg_[COVERAGE]_tip_[TIP]\n
if (fscanf(contigs_fp, ">%s %*s %d %*s\n", id, &length) == 2) {
assembly_size += length;
if (length >= Sigma::contig_len_thr) {
contigs->insert(std::make_pair(id, new Contig(id, length)));
}
} else {
if( fscanf(contigs_fp, "%*[^\n]\n") );
}
}
fclose(contigs_fp);
} else {
fprintf(stderr, "Error opening file: %s\n", contigs_file);
exit(EXIT_FAILURE);
}
std::string assembly_size_name = Sigma::output_dir + "/assembly_size.dat";
FILE* assembly_size_file = fopen(assembly_size_name.c_str(), "w");
if (assembly_size_file != NULL) {
fprintf(assembly_size_file, "%ld\n", assembly_size);
fclose(assembly_size_file);
}
return assembly_size;
}
void SOAPdenovoReader::get_assembly_size(const char* contigs_file) {
int length;
long int assembly_size = 0;
long int assembly_nb_contig = 0;
FILE* contigs_fp = fopen(contigs_file, "r");
if (contigs_fp != NULL) {
while (!feof(contigs_fp)) {
// >[ID] length [LENGTH] cvg_[COVERAGE]_tip_[TIP]\n
if (fscanf(contigs_fp, ">%*s %*s %d %*s\n", &length) == 1) {
assembly_size += length;
assembly_nb_contig++;
} else {
if( fscanf(contigs_fp, "%*[^\n]\n") );
}
}
fclose(contigs_fp);
} else {
fprintf(stderr, "Error opening file: %s\n", contigs_file);
exit(EXIT_FAILURE);
}
std::string assembly_size_name = Sigma::output_dir + "/assembly_size.dat";
FILE* assembly_size_file = fopen(assembly_size_name.c_str(), "w");
if (assembly_size_file != NULL) {
fprintf(assembly_size_file, "%ld\n", assembly_size);
fprintf(assembly_size_file, "%ld\n", assembly_nb_contig);
fclose(assembly_size_file);
}
Sigma::total_assembly_size = assembly_size;
Sigma::total_assembly_nb_contig = assembly_nb_contig;
//return assembly_size;
}
RAYReader::RAYReader() {}
long int RAYReader::read(const char* contigs_file, ContigMap* contigs) {
char id[256];
int length;
long int assembly_size = 0;
FILE* contigs_fp = fopen(contigs_file, "r");
if (contigs_fp != NULL) {
while (!feof(contigs_fp)) {
// >[ID] [LENGTH] nucleotides\n
if (fscanf(contigs_fp, ">%s %d %*s\n", id, &length) == 2) {
assembly_size += length;
if (length >= Sigma::contig_len_thr) {
contigs->insert(std::make_pair(id, new Contig(id, length)));
}
} else {
if( fscanf(contigs_fp, "%*[^\n]\n") );
}
}
fclose(contigs_fp);
} else {
fprintf(stderr, "Error opening file: %s\n", contigs_file);
exit(EXIT_FAILURE);
}
std::string assembly_size_name = Sigma::output_dir + "/assembly_size.dat";
FILE* assembly_size_file = fopen(assembly_size_name.c_str(), "w");
if (assembly_size_file != NULL) {
fprintf(assembly_size_file, "%ld\n", assembly_size);
fclose(assembly_size_file);
}
return assembly_size;
}
void RAYReader::get_assembly_size(const char* contigs_file) {
int length;
long int assembly_size = 0;
long int assembly_nb_contig = 0;
FILE* contigs_fp = fopen(contigs_file, "r");
if (contigs_fp != NULL) {
while (!feof(contigs_fp)) {
// >[ID] [LENGTH] nucleotides\n
if (fscanf(contigs_fp, ">%*s %d %*s\n", &length) == 1) {
assembly_size += length;
assembly_nb_contig++;
} else {
if( fscanf(contigs_fp, "%*[^\n]\n") );
}
}
fclose(contigs_fp);
} else {
fprintf(stderr, "Error opening file: %s\n", contigs_file);
exit(EXIT_FAILURE);
}
std::string assembly_size_name = Sigma::output_dir + "/assembly_size.dat";
FILE* assembly_size_file = fopen(assembly_size_name.c_str(), "w");
if (assembly_size_file != NULL) {
fprintf(assembly_size_file, "%ld\n", assembly_size);
fprintf(assembly_size_file, "%ld\n", assembly_nb_contig);
fclose(assembly_size_file);
}
Sigma::total_assembly_size = assembly_size;
Sigma::total_assembly_nb_contig = assembly_nb_contig;
//return assembly_size;
}
VelvetReader::VelvetReader() {}
long int VelvetReader::read(const char* contigs_file, ContigMap* contigs) {
char id[256];
int length;
long int assembly_size = 0;
FILE* contigs_fp = fopen(contigs_file, "r");
if (contigs_fp != NULL) {
while (!feof(contigs_fp)) {
// >NODE_[ID]_length_[LENGTH]_cov_[COVERAGE]\n
if (fscanf(contigs_fp, ">%s\n", id) == 1 && sscanf(id, "%*[^_]_%*[^_]_%*[^_]_%d_%*s", &length) == 1) {
assembly_size += length;
if (length >= Sigma::contig_len_thr) {
contigs->insert(std::make_pair(id, new Contig(id, length)));
}
} else {
if( fscanf(contigs_fp, "%*[^\n]\n") );
}
}
fclose(contigs_fp);
} else {
fprintf(stderr, "Error opening file: %s\n", contigs_file);
exit(EXIT_FAILURE);
}
std::string assembly_size_name = Sigma::output_dir + "/assembly_size.dat";
FILE* assembly_size_file = fopen(assembly_size_name.c_str(), "w");
if (assembly_size_file != NULL) {
fprintf(assembly_size_file, "%ld\n", assembly_size);
fclose(assembly_size_file);
}
return assembly_size;
}
void VelvetReader::get_assembly_size(const char* contigs_file) {
char id[256];
int length;
long int assembly_size = 0;
long int assembly_nb_contig = 0;
FILE* contigs_fp = fopen(contigs_file, "r");
if (contigs_fp != NULL) {
while (!feof(contigs_fp)) {
// >NODE_[ID]_length_[LENGTH]_cov_[COVERAGE]\n
if (fscanf(contigs_fp, ">%s\n", id) == 1 && sscanf(id, "%*[^_]_%*[^_]_%*[^_]_%d_%*s", &length) == 1) {
assembly_size += length;
assembly_nb_contig++;
} else {
if( fscanf(contigs_fp, "%*[^\n]\n") );
}
}
fclose(contigs_fp);
} else {
fprintf(stderr, "Error opening file: %s\n", contigs_file);
exit(EXIT_FAILURE);
}
std::string assembly_size_name = Sigma::output_dir + "/assembly_size.dat";
FILE* assembly_size_file = fopen(assembly_size_name.c_str(), "w");
if (assembly_size_file != NULL) {
fprintf(assembly_size_file, "%ld\n", assembly_size);
fclose(assembly_size_file);
}
Sigma::total_assembly_size = assembly_size;
Sigma::total_assembly_nb_contig = assembly_nb_contig;
//return assembly_size;
}
| 29.179063 | 114 | 0.54966 | lorenzgerber |
c1abd739aa9b31b2058152f6914efece0b0c7b3a | 496 | hpp | C++ | libs/fnd/tuple/include/bksge/fnd/tuple/tuple_tail_type.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/fnd/tuple/include/bksge/fnd/tuple/tuple_tail_type.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/fnd/tuple/include/bksge/fnd/tuple/tuple_tail_type.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file tuple_tail_type.hpp
*
* @brief tuple_tail_type の定義
*
* @author myoukaku
*/
#ifndef BKSGE_FND_TUPLE_TUPLE_TAIL_TYPE_HPP
#define BKSGE_FND_TUPLE_TUPLE_TAIL_TYPE_HPP
#include <bksge/fnd/tuple/fwd/tuple_tail_type_fwd.hpp>
namespace bksge
{
/**
* @brief 先頭要素を除いたTupleを返す
*/
template <typename Tuple>
struct tuple_tail_type;
} // namespace bksge
#include <bksge/fnd/tuple/inl/tuple_tail_type_inl.hpp>
#endif // BKSGE_FND_TUPLE_TUPLE_TAIL_TYPE_HPP
| 17.714286 | 55 | 0.729839 | myoukaku |
c1abe2c5d195d7510f656b864aaf41cfed630299 | 8,934 | hxx | C++ | private/ispu/pkitrust/common/cjetblue.hxx | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | ds/security/cryptoapi/pkitrust/common/cjetblue.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | ds/security/cryptoapi/pkitrust/common/cjetblue.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+-------------------------------------------------------------------------
//
// Microsoft Windows
//
// Copyright (C) Microsoft Corporation, 1996 - 1999
//
// File: cjetblue.hxx
//
// Contents: Microsoft Internet Security Common
//
// History: 23-Oct-1997 pberkman created
//
//--------------------------------------------------------------------------
#ifndef CJETBLUE_HXX
#define CJETBLUE_HXX
#include "jet.h"
typedef JET_ERR (JET_API *td_JetInit)(JET_INSTANCE *pinstance);
typedef JET_ERR (JET_API *td_JetTerm)(JET_INSTANCE instance);
typedef JET_ERR (JET_API *td_JetSetSystemParameter)(JET_INSTANCE *pinstance, JET_SESID sesid, unsigned long paramid,
unsigned long lParam, const char *sz);
typedef JET_ERR (JET_API *td_JetBeginSession)( JET_INSTANCE instance, JET_SESID *psesid, const char *szUserName,
const char *szPassword);
typedef JET_ERR (JET_API *td_JetCreateDatabase)(JET_SESID sesid, const char *szFilename, const char *szConnect,
JET_DBID *pdbid, JET_GRBIT grbit);
typedef JET_ERR (JET_API *td_JetAttachDatabase)(JET_SESID sesid, const char *szFilename, JET_GRBIT grbit);
typedef JET_ERR (JET_API *td_JetDetachDatabase)(JET_SESID sesid, const char *szFilename);
typedef JET_ERR (JET_API *td_JetCreateTable)(JET_SESID sesid, JET_DBID dbid, const char *szTableName,
unsigned long lPages, unsigned long lDensity, JET_TABLEID *ptableid);
typedef JET_ERR (JET_API *td_JetCreateTableColumnIndex)(JET_SESID sesid, JET_DBID dbid, JET_TABLECREATE *ptablecreate);
typedef JET_ERR (JET_API *td_JetCloseDatabase)(JET_SESID sesid, JET_DBID dbid, JET_GRBIT grbit);
typedef JET_ERR (JET_API *td_JetCloseTable)(JET_SESID sesid, JET_TABLEID tableid);
typedef JET_ERR (JET_API *td_JetOpenDatabase)(JET_SESID sesid, const char *szFilename, const char *szConnect,
JET_DBID *pdbid, JET_GRBIT grbit);
typedef JET_ERR (JET_API *td_JetOpenTable)(JET_SESID sesid, JET_DBID dbid, const char *szTableName,
const void *pvParameters, unsigned long cbParameters,
JET_GRBIT grbit, JET_TABLEID *ptableid);
typedef JET_ERR (JET_API *td_JetBeginTransaction)(JET_SESID sesid);
typedef JET_ERR (JET_API *td_JetCommitTransaction)(JET_SESID sesid, JET_GRBIT grbit);
typedef JET_ERR (JET_API *td_JetRetrieveColumns)(JET_SESID sesid, JET_TABLEID tableid,
JET_RETRIEVECOLUMN *pretrievecolumn, unsigned long cretrievecolumn);
typedef JET_ERR (JET_API *td_JetSetColumns)(JET_SESID sesid, JET_TABLEID tableid, JET_SETCOLUMN *psetcolumn,
unsigned long csetcolumn);
typedef JET_ERR (JET_API *td_JetPrepareUpdate)(JET_SESID sesid, JET_TABLEID tableid, unsigned long prep);
typedef JET_ERR (JET_API *td_JetSetCurrentIndex2)(JET_SESID sesid, JET_TABLEID tableid, const char *szIndexName,
JET_GRBIT grbit);
typedef JET_ERR (JET_API *td_JetMove)(JET_SESID sesid, JET_TABLEID tableid, long cRow, JET_GRBIT grbit);
typedef JET_ERR (JET_API *td_JetMakeKey)(JET_SESID sesid, JET_TABLEID tableid, const void *pvData,
unsigned long cbData, JET_GRBIT grbit);
typedef JET_ERR (JET_API *td_JetSeek)(JET_SESID sesid, JET_TABLEID tableid, JET_GRBIT grbit);
class cJetBlue_
{
public:
cJetBlue_(void);
virtual ~cJetBlue_(void);
protected:
JET_ERR JetInit(JET_INSTANCE *pinstance);
JET_ERR JetTerm(JET_INSTANCE instance);
JET_ERR JetSetSystemParameter(JET_INSTANCE *pinstance, JET_SESID sesid,
unsigned long paramid, unsigned long lParam,
const char *sz);
JET_ERR JetBeginSession(JET_INSTANCE instance, JET_SESID *psesid,
const char *szUserName, const char *szPassword);
JET_ERR JetCreateDatabase(JET_SESID sesid, const char *szFilename, const char *szConnect,
JET_DBID *pdbid, JET_GRBIT grbit);
JET_ERR JetAttachDatabase(JET_SESID sesid, const char *szFilename, JET_GRBIT grbit);
JET_ERR JetDetachDatabase(JET_SESID sesid, const char *szFilename);
JET_ERR JetCreateTable(JET_SESID sesid, JET_DBID dbid,
const char *szTableName, unsigned long lPages, unsigned long lDensity,
JET_TABLEID *ptableid);
JET_ERR JetCreateTableColumnIndex(JET_SESID sesid, JET_DBID dbid,
JET_TABLECREATE *ptablecreate);
JET_ERR JetCloseDatabase(JET_SESID sesid, JET_DBID dbid, JET_GRBIT grbit);
JET_ERR JetCloseTable(JET_SESID sesid, JET_TABLEID tableid);
JET_ERR JetOpenDatabase(JET_SESID sesid, const char *szFilename, const char *szConnect,
JET_DBID *pdbid, JET_GRBIT grbit);
JET_ERR JetOpenTable(JET_SESID sesid, JET_DBID dbid, const char *szTableName,
const void *pvParameters, unsigned long cbParameters,
JET_GRBIT grbit, JET_TABLEID *ptableid);
JET_ERR JetBeginTransaction(JET_SESID sesid);
JET_ERR JetCommitTransaction(JET_SESID sesid, JET_GRBIT grbit);
JET_ERR JetRetrieveColumns(JET_SESID sesid, JET_TABLEID tableid,
JET_RETRIEVECOLUMN *pretrievecolumn,
unsigned long cretrievecolumn);
JET_ERR JetSetColumns(JET_SESID sesid, JET_TABLEID tableid, JET_SETCOLUMN *psetcolumn,
unsigned long csetcolumn);
JET_ERR JetPrepareUpdate(JET_SESID sesid, JET_TABLEID tableid, unsigned long prep);
JET_ERR JetSetCurrentIndex2(JET_SESID sesid, JET_TABLEID tableid, const char *szIndexName,
JET_GRBIT grbit);
JET_ERR JetMove(JET_SESID sesid, JET_TABLEID tableid, long cRow, JET_GRBIT grbit);
JET_ERR JetMakeKey(JET_SESID sesid, JET_TABLEID tableid, const void *pvData,
unsigned long cbData, JET_GRBIT grbit);
JET_ERR JetSeek(JET_SESID sesid, JET_TABLEID tableid, JET_GRBIT grbit);
private:
HINSTANCE hJet;
td_JetInit fp_JetInit;
td_JetTerm fp_JetTerm;
td_JetSetSystemParameter fp_JetSetSystemParameter;
td_JetBeginSession fp_JetBeginSession;
td_JetCreateDatabase fp_JetCreateDatabase;
td_JetAttachDatabase fp_JetAttachDatabase;
td_JetDetachDatabase fp_JetDetachDatabase;
td_JetCreateTable fp_JetCreateTable;
td_JetCreateTableColumnIndex fp_JetCreateTableColumnIndex;
td_JetCloseDatabase fp_JetCloseDatabase;
td_JetCloseTable fp_JetCloseTable;
td_JetOpenDatabase fp_JetOpenDatabase;
td_JetOpenTable fp_JetOpenTable;
td_JetBeginTransaction fp_JetBeginTransaction;
td_JetCommitTransaction fp_JetCommitTransaction;
td_JetRetrieveColumns fp_JetRetrieveColumns;
td_JetSetColumns fp_JetSetColumns;
td_JetPrepareUpdate fp_JetPrepareUpdate;
td_JetSetCurrentIndex2 fp_JetSetCurrentIndex2;
td_JetMove fp_JetMove;
td_JetMakeKey fp_JetMakeKey;
td_JetSeek fp_JetSeek;
BOOL CheckOrLoadFunc(void **fp, char *pszfunc);
};
#endif // CJETBLUE_HXX
| 67.172932 | 124 | 0.561115 | King0987654 |
c1ae3abca0a1e3e56e8736ed3cfaa22d6255e6da | 2,829 | cpp | C++ | Various_Support_Classes/Path.cpp | ValveDigitalHealth/EPlabResearchWorksApp | bfae0b2e5e492bca778e96457738ba316e77b197 | [
"MIT"
] | null | null | null | Various_Support_Classes/Path.cpp | ValveDigitalHealth/EPlabResearchWorksApp | bfae0b2e5e492bca778e96457738ba316e77b197 | [
"MIT"
] | null | null | null | Various_Support_Classes/Path.cpp | ValveDigitalHealth/EPlabResearchWorksApp | bfae0b2e5e492bca778e96457738ba316e77b197 | [
"MIT"
] | null | null | null | //---------------------------------------------------------------------------
/*
MIT LICENSE Copyright (c) 2021 Pawel Kuklik
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. */
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#pragma hdrstop
#include "Path.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
//-------------------------------------------------------------------------
int Path_Class::save_object_to_stream(ofstream* File)
{
int Items_Number,Size;
int version = 1;
File->write((char*)&version, sizeof (int));
File->write((char*)&Type, sizeof (int));
File->write((char*)&x1, sizeof (double));
File->write((char*)&y1, sizeof (double));
File->write((char*)&z1, sizeof (double));
File->write((char*)&x2, sizeof (double));
File->write((char*)&y2, sizeof (double));
File->write((char*)&z2, sizeof (double));
File->write((char*)&Distance, sizeof (double));
File->write((char*)&LAT_Difference, sizeof (double));
return 1;
}
//-------------------------------------------------------------------------
int Path_Class::load_object_from_stream(ifstream* File)
{
int Items_Number;
int version;
File->read((char*)&version, sizeof (int));
if( version == 1 )
{
File->read((char*)&Type, sizeof (int));
File->read((char*)&x1, sizeof (double));
File->read((char*)&y1, sizeof (double));
File->read((char*)&z1, sizeof (double));
File->read((char*)&x2, sizeof (double));
File->read((char*)&y2, sizeof (double));
File->read((char*)&z2, sizeof (double));
File->read((char*)&Distance, sizeof (double));
File->read((char*)&LAT_Difference, sizeof (double));
}
return 1;
}
//---------------------------------------------------------------------------
| 32.147727 | 78 | 0.583245 | ValveDigitalHealth |
c1b22530e46186ee57d0950099f4b8ae13f10b8f | 271 | cpp | C++ | CS154/10-8/A.cpp | daxixi/SJTU-online-Judge-solution | 8beb0ef4965a574ce6fffeba0aad308d96ac0c87 | [
"Apache-2.0"
] | null | null | null | CS154/10-8/A.cpp | daxixi/SJTU-online-Judge-solution | 8beb0ef4965a574ce6fffeba0aad308d96ac0c87 | [
"Apache-2.0"
] | null | null | null | CS154/10-8/A.cpp | daxixi/SJTU-online-Judge-solution | 8beb0ef4965a574ce6fffeba0aad308d96ac0c87 | [
"Apache-2.0"
] | null | null | null | #include<iostream>
#include<cstdio>
using namespace std;
int main()
{
int a,b;
cin>>a>>b;
cout<<a<<"+"<<b<<"="<<a+b<<endl;
cout<<a<<"*"<<b<<"="<<a*b<<endl;
cout<<a<<"/"<<b<<"="<<a/b<<endl;
cout<<a<<"%"<<b<<"="<<a%b<<endl;
return 0;
}
| 19.357143 | 39 | 0.431734 | daxixi |
c1b3da6e54fc4b5aecf92b02eedee000af1688fe | 552 | tcc | C++ | inc/libutils/io/ostream_log_strategy.tcc | nkming2/libutils | e044c8f1265aad50092e008d7706142c3029096a | [
"MIT"
] | null | null | null | inc/libutils/io/ostream_log_strategy.tcc | nkming2/libutils | e044c8f1265aad50092e008d7706142c3029096a | [
"MIT"
] | 1 | 2015-03-10T06:29:14.000Z | 2015-03-10T06:29:14.000Z | inc/libutils/io/ostream_log_strategy.tcc | nkming2/libutils | e044c8f1265aad50092e008d7706142c3029096a | [
"MIT"
] | null | null | null | /*
* ostream_log_strategy.tcc
*
* Author: Ming Tsang
* Copyright (c) 2014 Ming Tsang
* Refer to LICENSE for details
*/
#pragma once
#include <ostream>
#include "libutils/io/ostream_log_strategy.h"
namespace utils
{
namespace io
{
template<typename CharT_>
OstreamLogStrategy<CharT_>::OstreamLogStrategy(
std::basic_ostream<CharT_> *stream, const bool is_owner)
: m_stream(stream),
m_is_owner(is_owner)
{}
template<typename CharT_>
OstreamLogStrategy<CharT_>::~OstreamLogStrategy()
{
if (m_is_owner)
{
delete m_stream;
}
}
}
}
| 14.526316 | 58 | 0.730072 | nkming2 |
c1b41419eb3ae3f7964de618b84776aaec65c0c8 | 12,755 | cpp | C++ | core/src/geom/mglnrel.cpp | rhcad/touchvg-v0.6 | 8b349ecd66b2363eec96e20873267aad9ed67ff1 | [
"RSA-MD"
] | 1 | 2016-06-14T06:22:50.000Z | 2016-06-14T06:22:50.000Z | core/src/geom/mglnrel.cpp | rhcad/touchvg-v0.6 | 8b349ecd66b2363eec96e20873267aad9ed67ff1 | [
"RSA-MD"
] | null | null | null | core/src/geom/mglnrel.cpp | rhcad/touchvg-v0.6 | 8b349ecd66b2363eec96e20873267aad9ed67ff1 | [
"RSA-MD"
] | null | null | null | // mglnrel.cpp: 实现直线位置关系函数
// Copyright (c) 2004-2012, Zhang Yungui
// License: LGPL, https://github.com/rhcad/touchvg
#include "mglnrel.h"
// 判断点pt是否在有向直线a->b的左边 (开区间)
GEOMAPI bool mgIsLeft(const Point2d& a, const Point2d& b, const Point2d& pt)
{
return (b-a).crossProduct(pt-a) > 0.f;
}
// 判断点pt是否在有向直线a->b的左边
GEOMAPI bool mgIsLeft2(
const Point2d& a, const Point2d& b, const Point2d& pt, const Tol& tol)
{
float dist = (b-a).distanceToVector(pt-a);
return dist > tol.equalPoint();
}
// 判断点pt是否在有向直线a->b的左边或线上 (闭区间)
GEOMAPI bool mgIsLeftOn(const Point2d& a, const Point2d& b, const Point2d& pt)
{
return (b-a).crossProduct(pt-a) >= 0.f;
}
// 判断点pt是否在有向直线a->b的左边或线上
GEOMAPI bool mgIsLeftOn2(
const Point2d& a, const Point2d& b, const Point2d& pt, const Tol& tol)
{
float dist = (b-a).distanceToVector(pt-a);
return dist > -tol.equalPoint();
}
// 判断点pt是否在直线a->b的线上
GEOMAPI bool mgIsColinear(const Point2d& a, const Point2d& b, const Point2d& pt)
{
return mgIsZero((b-a).crossProduct(pt-a));
}
// 判断点pt是否在直线a->b的线上
GEOMAPI bool mgIsColinear2(
const Point2d& a, const Point2d& b, const Point2d& pt, const Tol& tol)
{
float dist = (b-a).crossProduct(pt-a);
return fabsf(dist) < tol.equalPoint();
}
// 判断两个线段ab和cd是否相交于线段内部
GEOMAPI bool mgIsIntersectProp(
const Point2d& a, const Point2d& b, const Point2d& c, const Point2d& d)
{
// Eliminate improper cases
if (mgIsColinear(a,b,c) || mgIsColinear(a,b,d)
|| mgIsColinear(c,d,a) || mgIsColinear(c,d,b))
return false;
return (mgIsLeft(a,b,c) ^ mgIsLeft(a,b,d))
&& (mgIsLeft(c,d,a) ^ mgIsLeft(c,d,b));
}
// 判断点pt是否在线段ab上(闭区间)
GEOMAPI bool mgIsBetweenLine(const Point2d& a, const Point2d& b, const Point2d& pt)
{
if (!mgIsColinear(a, b, pt))
return false;
// If ab not vertical, check betweenness on x; else on y.
if (a.x != b.x)
return (a.x <= pt.x && pt.x <= b.x) || (a.x >= pt.x && pt.x >= b.x);
else
return (a.y <= pt.y && pt.y <= b.y) || (a.y >= pt.y && pt.y >= b.y);
}
// 判断点pt是否在线段ab上
GEOMAPI bool mgIsBetweenLine2(
const Point2d& a, const Point2d& b, const Point2d& pt, const Tol& tol)
{
if (!mgIsColinear2(a, b, pt, tol))
return false;
// If ab not vertical, check betweenness on x; else on y.
if (a.x != b.x)
{
return ((a.x <= pt.x + tol.equalPoint())
&& (pt.x <= b.x + tol.equalPoint()))
|| ((a.x >= pt.x - tol.equalPoint())
&& (pt.x >= b.x - tol.equalPoint()));
}
else
{
return ((a.y <= pt.y + tol.equalPoint())
&& (pt.y <= b.y + tol.equalPoint()))
|| ((a.y >= pt.y - tol.equalPoint())
&& (pt.y >= b.y - tol.equalPoint()));
}
}
// 已知点pt在直线ab上, 判断点pt是否在线段ab上(闭区间)
GEOMAPI bool mgIsBetweenLine3(
const Point2d& a, const Point2d& b, const Point2d& pt, Point2d* nearpt)
{
bool ret;
if (a.x != b.x)
{
ret = (a.x <= pt.x && pt.x <= b.x) || (a.x >= pt.x && pt.x >= b.x);
if (nearpt != NULL)
*nearpt = fabsf(pt.x - a.x) < fabsf(pt.x - b.x) ? a : b;
}
else
{
ret = (a.y <= pt.y && pt.y <= b.y) || (a.y >= pt.y && pt.y >= b.y);
if (nearpt != NULL)
*nearpt = fabsf(pt.y - a.y) < fabsf(pt.y - b.y) ? a : b;
}
return ret;
}
// 判断两个线段ab和cd是否相交(交点在线段闭区间内)
GEOMAPI bool mgIsIntersect(
const Point2d& a, const Point2d& b, const Point2d& c, const Point2d& d)
{
if (mgIsIntersectProp(a, b, c, d))
return true;
else if (mgIsBetweenLine(a, b, c) || mgIsBetweenLine(a, b, d)
|| mgIsBetweenLine(c, d, a) || mgIsBetweenLine(c, d, b))
return true;
else
return false;
}
// 计算点pt到无穷直线ab的距离
GEOMAPI float mgPtToBeeline(const Point2d& a, const Point2d& b, const Point2d& pt)
{
float dist = (b-a).crossProduct(pt-a);
return dist;
}
// 计算点pt到无穷直线ab的距离
GEOMAPI float mgPtToBeeline2(
const Point2d& a, const Point2d& b, const Point2d& pt, Point2d& ptPerp)
{
// 两点重合
if (a == b)
{
ptPerp = a;
return a.distanceTo(pt);
}
// 竖直线
else if (mgEquals(a.x, b.x))
{
ptPerp.set(a.x, pt.y);
return fabsf(a.x - pt.x);
}
// 水平线
else if (mgEquals(a.y, b.y))
{
ptPerp.set(pt.x, a.y);
return fabsf(a.y - pt.y);
}
else
{
float t1 = ( b.y - a.y ) / ( b.x - a.x );
float t2 = -1.f / t1;
ptPerp.x = ( pt.y - a.y + a.x * t1 - pt.x * t2 ) / ( t1 - t2 );
ptPerp.y = a.y + (ptPerp.x - a.x) * t1;
return pt.distanceTo(ptPerp);
}
}
// 计算点pt到线段ab的最近距离
GEOMAPI float mgPtToLine(
const Point2d& a, const Point2d& b, const Point2d& pt, Point2d& nearpt)
{
Point2d ptTemp;
float dist = mgPtToBeeline2(a, b, pt, nearpt);
if (!mgIsBetweenLine3(a, b, nearpt, &ptTemp))
{
nearpt = ptTemp;
dist = pt.distanceTo(nearpt);
}
return dist;
}
// 求两条直线(ax+by+c=0)的交点
GEOMAPI bool mgCrossLineAbc(
float a1, float b1, float c1, float a2, float b2, float c2,
Point2d& ptCross, const Tol& tolVec)
{
float sinnum, cosnum;
sinnum = a1*b2 - a2*b1;
if (mgIsZero(sinnum))
return false;
cosnum = a1*a2 + b1*b2;
if (!mgIsZero(cosnum) && fabsf(sinnum / cosnum) < tolVec.equalVector())
return false;
ptCross.x = (b1*c2 - b2*c1) / sinnum;
ptCross.y = (a2*c1 - a1*c2) / sinnum;
return true;
}
// 求两条无穷直线的交点
GEOMAPI bool mgCross2Beeline(
const Point2d& a, const Point2d& b, const Point2d& c, const Point2d& d,
Point2d& ptCross, float* pu, float* pv, const Tol& tolVec)
{
float u, v, denom, cosnum;
denom = (c.x-d.x)*(b.y-a.y)-(c.y-d.y)*(b.x-a.x);
if (mgIsZero(denom)) // 平行或重合
return false;
cosnum = (b.x-a.x)*(d.x - c.x) + (b.y-a.y)*(d.y-c.y);
if (!mgIsZero(cosnum) && fabsf(denom / cosnum) < tolVec.equalVector())
return false;
u = ((c.x-a.x)*(d.y-c.y)-(c.y-a.y)*(d.x-c.x)) / denom;
v = ((c.x-a.x)*(b.y-a.y)-(c.y-a.y)*(b.x-a.x)) / denom;
if (pu != NULL) *pu = u;
if (pv != NULL) *pv = v;
ptCross.x = (1 - u) * a.x + u * b.x;
ptCross.y = (1 - u) * a.y + u * b.y;
return true;
}
// 求两条线段的交点
// 输入: (a.x,a.y),(b.x,b.y) 第一条线段上的两个点
// (c.x,c.y),(d.x,d.y) 第二条线段上的两个点
// 输出: (px, py) 交点坐标
// 返回: 有无交点
GEOMAPI bool mgCross2Line(
const Point2d& a, const Point2d& b, const Point2d& c, const Point2d& d,
Point2d& ptCross, const Tol& tolVec)
{
float u, v, denom, cosnum;
if (mgMin(a.x,b.x) - mgMax(c.x,d.x) > _MGZERO
|| mgMin(c.x,d.x) - mgMax(a.x,b.x) > _MGZERO
|| mgMin(a.y,b.y) - mgMax(c.y,d.y) > _MGZERO
|| mgMin(c.y,d.y) - mgMax(a.y,b.y) > _MGZERO)
return false;
denom = (c.x-d.x)*(b.y-a.y)-(c.y-d.y)*(b.x-a.x);
if (mgIsZero(denom))
return false;
cosnum = (b.x-a.x)*(d.x - c.x) + (b.y-a.y)*(d.y-c.y);
if (!mgIsZero(cosnum) && fabsf(denom / cosnum) < tolVec.equalVector())
return false;
u = ((c.x-a.x)*(d.y-c.y)-(c.y-a.y)*(d.x-c.x)) / denom;
if (u < _MGZERO || u > 1.f - _MGZERO)
return false;
v = ((c.x-a.x)*(b.y-a.y)-(c.y-a.y)*(b.x-a.x)) / denom;
if (v < _MGZERO || v > 1.f - _MGZERO)
return false;
ptCross.x = (1 - u) * a.x + u * b.x;
ptCross.y = (1 - u) * a.y + u * b.y;
return true;
}
// 求线段和直线的交点
GEOMAPI bool mgCrossLineBeeline(
const Point2d& a, const Point2d& b, const Point2d& c, const Point2d& d,
Point2d& ptCross, float* pv, const Tol& tolVec)
{
float u, denom, cosnum;
denom = (c.x-d.x)*(b.y-a.y)-(c.y-d.y)*(b.x-a.x);
if (mgIsZero(denom))
return false;
cosnum = (b.x-a.x)*(d.x - c.x) + (b.y-a.y)*(d.y-c.y);
if (!mgIsZero(cosnum) && fabsf(denom / cosnum) < tolVec.equalVector())
return false;
u = ((c.x-a.x)*(d.y-c.y)-(c.y-a.y)*(d.x-c.x)) / denom;
if (u < _MGZERO || u > 1.f - _MGZERO)
return false;
if (pv != NULL)
*pv = ((c.x-a.x)*(b.y-a.y)-(c.y-a.y)*(b.x-a.x)) / denom;
ptCross.x = (1 - u) * a.x + u * b.x;
ptCross.y = (1 - u) * a.y + u * b.y;
return true;
}
// 线段端点的区域编码:
// 1001 | 1000 | 1010
// 0001 | 0000 | 0010
// 0101 | 0100 | 0110
static inline unsigned ClipCode(Point2d& pt, const Box2d& box)
{
unsigned code = 0;
if (pt.y > box.ymax)
code |= 0x1000;
else if (pt.y < box.ymin)
code |= 0x0100;
if (pt.x < box.xmin)
code |= 0x0001;
else if (pt.x > box.xmax)
code |= 0x0010;
return code;
}
// 功能: 用矩形剪裁线段
// 参数: [in, out] pt1 线段起点坐标
// [in, out] pt2 线段终点坐标
// [in] box 剪裁矩形
// 返回: 剪裁后是否有处于剪裁矩形内的线段部分
GEOMAPI bool mgClipLine(Point2d& pt1, Point2d& pt2, const Box2d& _box)
{
Box2d box (_box);
box.normalize();
unsigned code1, code2;
code1 = ClipCode(pt1, box);
code2 = ClipCode(pt2, box);
for ( ; ; )
{
if (!(code1 | code2)) // 完全在矩形内
return true;
if (code1 & code2) // 完全在矩形外
return false;
float x = 0.f, y = 0.f;
unsigned code;
if (code1) // 起点不在矩形内
code = code1;
else // 终点不在矩形内
code = code2;
if (code & 0x1000) // 上
{
x = pt1.x + (pt2.x - pt1.x) * (box.ymax - pt1.y) / (pt2.y - pt1.y);
y = box.ymax;
}
else if (code & 0x0100) // 下
{
x = pt1.x + (pt2.x - pt1.x) * (box.ymin - pt1.y) / (pt2.y - pt1.y);
y = box.ymin;
}
else if (code & 0x0001) // 左
{
y = pt1.y + (pt2.y - pt1.y) * (box.xmin - pt1.x) / (pt2.x - pt1.x);
x = box.xmin;
}
else if (code & 0x0010) // 右
{
y = pt1.y + (pt2.y - pt1.y) * (box.xmax - pt1.x) / (pt2.x - pt1.x);
x = box.xmax;
}
if (code == code1)
{
pt1.x = x;
pt1.y = y;
code1 = ClipCode(pt1, box);
}
else
{
pt2.x = x;
pt2.y = y;
code2 = ClipCode(pt2, box);
}
}
}
static bool PtInArea_Edge(int &odd, const Point2d& pt, const Point2d& p1,
const Point2d& p2, const Point2d& p0)
{
// 如果从X方向上P不在边[P1,P2)上,则没有交点. 竖直边也没有
if (!((p2.x > p1.x) && (pt.x >= p1.x) && (pt.x < p2.x)) &&
!((p1.x > p2.x) && (pt.x <= p1.x) && (pt.x > p2.x)) )
{
return false;
}
// 求从Y负无穷大向上到P的射线和该边的交点(pt.x, yy)
float yy = p1.y + (pt.x - p1.x) * (p2.y - p1.y) / (p2.x - p1.x);
if (pt.y > yy) // 相交
{
if (mgEquals(pt.x, p1.x)) // 交点是顶点, 则比较P[i+1]和P[i-1]是否在pt.x同侧
{
if (((p0.x > pt.x) && (p2.x > pt.x)) ||
((p0.x < pt.x) && (p2.x < pt.x)) ) // 同侧
{
return false;
}
}
odd = 1 - odd; // 增加一个交点, 奇偶切换
}
return true;
}
// 功能: 判断一点是否在一多边形范围内
GEOMAPI MgPtInAreaRet mgPtInArea(
const Point2d& pt, int count, const Point2d* vertexs,
int& order, const Tol& tol)
{
int i;
int odd = 1; // 1: 交点数为偶数, 0: 交点数为奇数
order = -1;
for (i = 0; i < count; i++)
{
// P与某顶点重合. 返回 kMgPtAtVertex, order = 顶点号 [0, count-1]
if (pt.isEqualTo(vertexs[i], tol))
{
order = i;
return kMgPtAtVertex;
}
}
for (i = 0; i < count; i++)
{
const Point2d& p1 = vertexs[i];
const Point2d& p2 = (i+1 < count) ? vertexs[i+1] : vertexs[0];
// P在某条边上. 返回 kMgPtOnEdge, order = 边号 [0, count-1]
if (mgIsBetweenLine2(p1, p2, pt, tol))
{
order = i;
return kMgPtOnEdge;
}
if (!PtInArea_Edge(odd, pt, p1, p2,
i > 0 ? vertexs[i-1] : vertexs[count-1]))
continue;
}
// 如果射线和多边形的交点数为偶数, 则 p==1, P在区外, 返回 kMgPtOutArea
// 为奇数则p==0, P在区内, 返回 kMgPtInArea
return 0 == odd ? kMgPtInArea : kMgPtOutArea;
}
// 判断多边形是否为凸多边形
GEOMAPI bool mgIsConvex(int count, const Point2d* vs, bool* pACW)
{
if (count < 3 || vs == NULL)
return true;
bool z0 = (vs[count-1].x - vs[count-2].x) * (vs[1].y - vs[0].y)
> (vs[count-1].y - vs[count-2].y) * (vs[1].x - vs[0].x);
for (int i = 0; i < count; i++)
{
if (z0 != ((vs[i].x - vs[i-1].x) * (vs[i+1].y - vs[i].y)
> (vs[i].y - vs[i-1].y) * (vs[i+1].x - vs[i].x)))
return false;
}
if (pACW != NULL)
*pACW = z0;
return true;
}
| 27.312634 | 83 | 0.500902 | rhcad |
c1b427281453c0522ce35641f24cf15a64d5460d | 6,140 | cc | C++ | src/HistogramTest.cc | taschik/ramcloud | 6ef2e1cd61111995881d54bda6f9296b4777b928 | [
"0BSD"
] | 1 | 2016-01-18T12:41:28.000Z | 2016-01-18T12:41:28.000Z | src/HistogramTest.cc | taschik/ramcloud | 6ef2e1cd61111995881d54bda6f9296b4777b928 | [
"0BSD"
] | null | null | null | src/HistogramTest.cc | taschik/ramcloud | 6ef2e1cd61111995881d54bda6f9296b4777b928 | [
"0BSD"
] | null | null | null | /* Copyright (c) 2012 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "TestUtil.h"
#include "Histogram.h"
namespace RAMCloud {
/**
* Unit tests for Histogram.
*/
class HistogramTest : public ::testing::Test {
public:
HistogramTest() {}
DISALLOW_COPY_AND_ASSIGN(HistogramTest);
};
TEST_F(HistogramTest, constructor_regular) {
Histogram h(5000, 10);
EXPECT_EQ(5000UL, h.numBuckets);
EXPECT_EQ(10UL, h.bucketWidth);
for (uint32_t i = 0; i < h.numBuckets; i++)
EXPECT_EQ(0UL, h.buckets[i]);
EXPECT_EQ(0UL, downCast<uint64_t>(h.sampleSum));
EXPECT_EQ(0UL, h.outliers);
EXPECT_EQ(~0UL, h.min);
EXPECT_EQ(0UL, h.max);
}
TEST_F(HistogramTest, constructor_deserializer) {
Histogram h1(100, 1);
h1.storeSample(8);
h1.storeSample(23482);
h1.storeSample(27);
ProtoBuf::Histogram protoBuf;
h1.serialize(protoBuf);
Histogram h2(protoBuf);
EXPECT_EQ(h1.numBuckets, h2.numBuckets);
EXPECT_EQ(h1.bucketWidth, h2.bucketWidth);
EXPECT_EQ(downCast<uint64_t>(h1.sampleSum),
downCast<uint64_t>(h2.sampleSum));
EXPECT_EQ(h1.outliers, h2.outliers);
EXPECT_EQ(h1.max, h2.max);
EXPECT_EQ(h1.min, h2.min);
EXPECT_EQ(h1.buckets.size(), h2.buckets.size());
for (uint32_t i = 0; i < h1.buckets.size(); i++)
EXPECT_EQ(h1.buckets[i], h2.buckets[i]);
}
TEST_F(HistogramTest, storeSample) {
Histogram h(5000, 10);
h.storeSample(3);
EXPECT_EQ(3UL, h.min);
EXPECT_EQ(3UL, h.max);
EXPECT_EQ(0UL, h.outliers);
EXPECT_EQ(1UL, h.buckets[0]);
EXPECT_EQ(0UL, h.buckets[1]);
EXPECT_EQ(0UL, h.buckets[2]);
h.storeSample(3);
h.storeSample(h.numBuckets * h.bucketWidth + 40);
h.storeSample(12);
h.storeSample(78);
EXPECT_EQ(3UL, h.min);
EXPECT_EQ(h.numBuckets * h.bucketWidth + 40, h.max);
EXPECT_EQ(1UL, h.outliers);
EXPECT_EQ(2UL, h.buckets[0]);
EXPECT_EQ(1UL, h.buckets[1]);
EXPECT_EQ(0UL, h.buckets[2]);
EXPECT_EQ(3UL + 3 + 12 + 78 + h.numBuckets * h.bucketWidth + 40,
downCast<uint64_t>(h.sampleSum));
}
TEST_F(HistogramTest, reset) {
Histogram h(100, 1);
h.storeSample(23);
h.storeSample(23492834);
h.reset();
EXPECT_EQ(100UL, h.numBuckets);
EXPECT_EQ(1UL, h.bucketWidth);
for (uint32_t i = 0; i < h.numBuckets; i++)
EXPECT_EQ(0UL, h.buckets[i]);
EXPECT_EQ(0UL, downCast<uint64_t>(h.sampleSum));
EXPECT_EQ(0UL, h.outliers);
EXPECT_EQ(~0UL, h.min);
EXPECT_EQ(0UL, h.max);
}
TEST_F(HistogramTest, toString) {
Histogram h(100, 1);
EXPECT_EQ("# Histogram: buckets = 100, bucket width = 1\n"
"# 0 samples, 0 outliers, min = 18446744073709551615, max = 0\n"
"# median = 0, average = 0\n",
h.toString());
h.storeSample(23);
h.storeSample(28343);
h.storeSample(99);
EXPECT_EQ("# Histogram: buckets = 100, bucket width = 1\n"
"# 3 samples, 1 outliers, min = 23, max = 28343\n"
"# median = 99, average = 9488\n"
" 23 1 33.333 33.333\n"
" 99 1 33.333 66.667\n",
h.toString());
Histogram h2(5, 1);
h2.storeSample(3);
EXPECT_EQ("# Histogram: buckets = 5, bucket width = 1\n"
"# 1 samples, 0 outliers, min = 3, max = 3\n"
"# median = 3, average = 3\n"
" 0 0 0.000 0.000\n"
" 1 0 0.000 0.000\n"
" 2 0 0.000 0.000\n"
" 3 1 100.000 100.000\n"
" 4 0 0.000 100.000\n",
h2.toString(0));
}
TEST_F(HistogramTest, getOutliers) {
Histogram h(1, 1);
EXPECT_EQ(0UL, h.getOutliers());
h.storeSample(0);
h.storeSample(1);
h.storeSample(2);
EXPECT_EQ(2UL, h.getOutliers());
uint64_t highestOutlier;
h.getOutliers(&highestOutlier);
EXPECT_EQ(2UL, highestOutlier);
}
TEST_F(HistogramTest, getTotalSamples) {
Histogram h(1, 1);
EXPECT_EQ(0UL, h.getTotalSamples());
h.storeSample(0);
h.storeSample(1);
h.storeSample(2);
EXPECT_EQ(3UL, h.getTotalSamples());
}
TEST_F(HistogramTest, getAverage) {
// small sum
Histogram h(1, 1);
EXPECT_EQ(0UL, h.getAverage());
h.storeSample(1);
EXPECT_EQ(1UL, h.getAverage());
h.storeSample(20);
EXPECT_EQ(10UL, h.getAverage());
// sum that doesn't fit in 64-bits
h.storeSample(0xffffffffffffffffUL);
h.storeSample(0x0fffffffffffffffUL);
EXPECT_EQ(0x4400000000000004UL, h.getAverage());
}
TEST_F(HistogramTest, getMedian) {
// totalSamples == 0
Histogram noSamples(1, 1);
EXPECT_EQ(0UL, noSamples.getMedian());
// numBuckets == 0
Histogram noBuckets(0, 1);
noBuckets.storeSample(5);
EXPECT_EQ(-1UL, noBuckets.getMedian());
// median falls within outliers
Histogram h(2, 1);
h.storeSample(10);
EXPECT_EQ(-1UL, h.getMedian());
// median falls within buckets
h.storeSample(1);
h.storeSample(1);
EXPECT_EQ(1UL, h.getMedian());
// test a slightly less trivial case
Histogram h2(11, 1);
for (int i = 0; i <= 10; i++)
h2.storeSample(i);
EXPECT_EQ(5UL, h2.getMedian());
}
TEST_F(HistogramTest, serialize) {
// Covered by 'constructor_deserializer'.
}
} // namespace RAMCloud
| 29.099526 | 78 | 0.617915 | taschik |
c1b6172a8fe9e87bcf68402ad3cbbbd46eff93ff | 5,030 | cpp | C++ | Source/Tank_To_Target/MyTank.cpp | Mati-C/Tank_To_Target | e506dc0744dff975a3d2f555656adf874b395962 | [
"Apache-2.0"
] | null | null | null | Source/Tank_To_Target/MyTank.cpp | Mati-C/Tank_To_Target | e506dc0744dff975a3d2f555656adf874b395962 | [
"Apache-2.0"
] | null | null | null | Source/Tank_To_Target/MyTank.cpp | Mati-C/Tank_To_Target | e506dc0744dff975a3d2f555656adf874b395962 | [
"Apache-2.0"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "MyTank.h"
// Sets default values
AMyTank::AMyTank()
{
// Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void AMyTank::BeginPlay()
{
Super::BeginPlay();
UGameplayStatics::SetGlobalTimeDilation(GetWorld(), 1);
audioComponent = FindComponentByClass<UAudioComponent>();
extraName = GetWorld()->WorldType == EWorldType::PIE ? "UEDPIE_0_" : "";
if (GetWorld()->GetMapName() == extraName + "Level_1") {
totalTargets = targetsLV1;
timeRemaining = timeLV1;
}
else {
totalTargets = targetsLV2;
timeRemaining = timeLV2;
}
armor = maxArmor;
fireTimer = fireDelay;
bossBarFill = 1;
armorBarFill = 1;
isCountingDown = false;
}
// Called every frame
void AMyTank::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
if (!currentVelocity.IsZero())
{
FVector newLocation = GetActorLocation() + (currentVelocity * DeltaTime);
SetActorLocation(newLocation);
}
if (destroyedTargets == totalTargets)
Win();
if (GetWorld()->GetMapName() != extraName + "Level_1" || GetWorld()->GetMapName() != extraName + "Level_2")
timeRemaining -= DeltaTime;
armorBarFill = armor / maxArmor;
fireTimer += DeltaTime;
powerUpTimer -= DeltaTime;
remainingTargets = totalTargets - destroyedTargets;
if (powerUpTimer <= 0) {
unlimitedFireRate = false;
shotgunMode = false;
}
if (armor <= 0 || timeRemaining <= 0)
Lose();
if (timeRemaining <= 5 && !isCountingDown){
audioComponent->Stop();
audioComponent->Sound = countdown;
audioComponent->Play();
isCountingDown = true;
}
}
// Called to bind functionality to input
void AMyTank::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
PlayerInputComponent->BindAxis("Move X", this, &AMyTank::MoveX);
PlayerInputComponent->BindAxis("Move Y", this, &AMyTank::MoveY);
PlayerInputComponent->BindAxis("Rotate X", this, &AMyTank::RotateX);
PlayerInputComponent->BindAxis("Rotate Y", this, &AMyTank::RotateY);
PlayerInputComponent->BindAction("Shoot", IE_Pressed, this, &AMyTank::Shoot);
PlayerInputComponent->BindAction("Continue", IE_Pressed, this, &AMyTank::Continue);
}
void AMyTank::MoveX(float val)
{
if (won) return;
isMovingX = val != 0;
if (isMovingY)
val *= 0.5f;
currentVelocity.X = val * 100 * speed;
}
void AMyTank::MoveY(float val)
{
if (won) return;
isMovingY = val != 0;
if (isMovingX)
val *= 0.5f;
currentVelocity.Y = -val * 100 * speed;
}
void AMyTank::RotateX(float val)
{
if (won) return;
FRotator rot = upperBody->RelativeRotation;
rot.Yaw += rotationSpeed * val;
upperBody->SetRelativeRotation(rot);
}
void AMyTank::RotateY(float val)
{
if (won) return;
FRotator rot = rotor->RelativeRotation;
rot.Roll -= rotationSpeed * val * 0.5f;
if (rot.Roll > 15) rot.Roll = 15;
else if (rot.Roll < -20) rot.Roll = -20;
rotor->SetRelativeRotation(rot);
}
void AMyTank::Shoot()
{
if (won) return;
if (fireTimer >= fireDelay || unlimitedFireRate)
{
if (shotgunMode)
{
for (int i = 0; i <= shotgunPellets; i++)
{
FRotator rot = PH->GetComponentRotation();
rot.Yaw += FMath::FRandRange(-shotgunSpread, shotgunSpread);
rot.Roll += FMath::FRandRange(-shotgunSpread, shotgunSpread);
GetWorld()->SpawnActor<AMyBullet>(bullet, PH->GetComponentLocation(), rot, FActorSpawnParameters());
}
}
else GetWorld()->SpawnActor<AMyBullet>(bullet, PH->GetComponentLocation(), PH->GetComponentRotation(), FActorSpawnParameters());
fireTimer = 0;
}
}
void AMyTank::UnlimitedFireRate()
{
unlimitedFireRate = true;
shotgunMode = false;
powerUpTimer = powerUpTime;
}
void AMyTank::ShotgunMode()
{
unlimitedFireRate = false;
shotgunMode = true;
powerUpTimer = powerUpTime;
}
void AMyTank::Win()
{
UGameplayStatics::SetGlobalTimeDilation(GetWorld(), 0.0001f);
won = true;
audioComponent->Stop();
audioComponent->Sound = complete;
audioComponent->Play();
if (GetWorld()->GetMapName() == extraName + "Level_3")
UGameplayStatics::OpenLevel(GetWorld(), "Complete");
}
void AMyTank::Lose()
{
if (GetWorld()->GetMapName() == extraName + "Level_1")
UGameplayStatics::OpenLevel(GetWorld(), "Lose_1");
else if (GetWorld()->GetMapName() == extraName + "Level_2")
UGameplayStatics::OpenLevel(GetWorld(), "Lose_2");
else if (GetWorld()->GetMapName() == extraName + "Level_3")
UGameplayStatics::OpenLevel(GetWorld(), "Lose_3");
}
void AMyTank::Continue()
{
if (!won) return;
if (GetWorld()->GetMapName() == extraName + "Level_1")
UGameplayStatics::OpenLevel(GetWorld(), "Victory_1");
else
UGameplayStatics::OpenLevel(GetWorld(), "Victory_2");
}
void AMyTank::SetGamePaused(bool isPaused)
{
APlayerController* const MyPlayer = Cast<APlayerController>(GEngine->GetFirstLocalPlayerController(GetWorld()));
if (MyPlayer != NULL)
MyPlayer->SetPause(isPaused);
} | 24.778325 | 130 | 0.708549 | Mati-C |
c1b72f6a3c9e99980981f79a102c3a6831b1fd82 | 417 | hpp | C++ | src/stan/math/prim/mat/fun/minus.hpp | alashworth/stan-monorepo | 75596bc1f860ededd7b3e9ae9002aea97ee1cd46 | [
"BSD-3-Clause"
] | 1 | 2019-09-06T15:53:17.000Z | 2019-09-06T15:53:17.000Z | src/stan/math/prim/mat/fun/minus.hpp | alashworth/stan-monorepo | 75596bc1f860ededd7b3e9ae9002aea97ee1cd46 | [
"BSD-3-Clause"
] | 8 | 2019-01-17T18:51:16.000Z | 2019-01-17T18:51:39.000Z | src/stan/math/prim/mat/fun/minus.hpp | alashworth/stan-monorepo | 75596bc1f860ededd7b3e9ae9002aea97ee1cd46 | [
"BSD-3-Clause"
] | null | null | null | #ifndef STAN_MATH_PRIM_MAT_FUN_MINUS_HPP
#define STAN_MATH_PRIM_MAT_FUN_MINUS_HPP
namespace stan {
namespace math {
/**
* Returns the negation of the specified scalar or matrix.
*
* @tparam T Type of subtrahend.
* @param x Subtrahend.
* @return Negation of subtrahend.
*/
template <typename T>
inline T minus(const T& x) {
return -x;
}
} // namespace math
} // namespace stan
#endif
| 18.954545 | 59 | 0.688249 | alashworth |
c1b73c59470fe87a63251df369dd1fd5d8be998d | 10,049 | hxx | C++ | com/oleutest/stgbvt/ctolestg/common/inc/automate.hxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | com/oleutest/stgbvt/ctolestg/common/inc/automate.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | com/oleutest/stgbvt/ctolestg/common/inc/automate.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+-------------------------------------------------------------------------
//
// Microsoft OLE
// Copyright (C) Microsoft Corporation, 1994 - 1995.
//
// File: automate.hxx
//
// Contents: Marina automation helper class
// Marina aware applications use this class to aid in the
// automation process
//
// Classes: CMAutomate
//
// Functions:
//
// History: 09-26-95 alexe Cleaned up / added more marina funcs
// 1-25-95 kennethm Created
//
//--------------------------------------------------------------------------
#ifndef __AUTOMATE_HXX__
#define __AUTOMATE_HXX__
#include <copydata.hxx>
//
// number of marina API functions in the CMAutomate class
//
#define MAX_NUM_FUNCS 16
//
// Function names: always unicode
//
// These are the known functions. TestDlls and application can always
// cook up their own private function names, although this isn't
// recommended.
//
#define FUNCNAME_CLOSEAPPLICATION L"MarinaCloseApplication"
#define FUNCNAME_CREATEDOCUMENT L"MarinaCreateDocument"
#define FUNCNAME_OPENDOCUMENT L"MarinaOpenDocument"
#define FUNCNAME_CLOSEALLDOCUMENTS L"MarinaCloseAllDocuments"
#define FUNCNAME_GETDOCUMENTCOUNT L"MarinaApiGetDocCount"
#define FUNCNAME_GETAPPHWND L"MarinaGetAppHwnd"
#define FUNCNAME_SAVEDOCUMENT L"MarinaSaveDocument"
#define FUNCNAME_CLOSEDOCUMENT L"MarinaCloseDocument"
#define FUNCNAME_COPYDOCUMENT L"MarinaCopyDocument"
#define FUNCNAME_INSERTOBJECT L"MarinaInsertObject"
#define FUNCNAME_GETOBJECT L"MarinaGetObject"
#define FUNCNAME_GETOBJECTCOUNT L"MarinaApiGetObjCount"
#define FUNCNAME_COPYOBJECT L"MarinaCopyObject"
#define FUNCNAME_ACTIVATEOBJECT L"MarinaActivateObject"
#define FUNCNAME_GETAPPPROCESSID L"MarinaGetAppProcessId"
#define INVALID_MARINA_HANDLE (DWORD)-1
//+-------------------------------------------------------------------------
//
// Class: CMAutomate
//
// Purpose: Automation helper class for marina aware applications
//
// Interface:
//
// Public Functions:
//
// CMAutomate
// ~CMAutomate
// CMAutomate(ptr)
// FindMarinaHandle
// WriteMarinaHandle
// MarinaRegisterFile
// SetJumpTable
// DispatchCopyData
// InMarina
// MarinaParseCommandLine
//
// MarinaApiCloseApp
// MarinaApiCreateDoc
// MarinaApiOpenDoc
// MarinaApiCloseAllDocs
// MarinaApiGetDocCount
// MarinaApiGetAppHwnd
//
// MarinaApiSaveDoc
// MarinaApiCloseDoc
// MarinaApiCopyDoc
// MarinaApiInsertObject
// MarinaApiGetObject
// MarinaApiGetObjCount
//
// MarinaApiCopyObject
// MarinaApiActivateObject
//
// MarinaApiGetAppProcessId
//
// Private functions:
//
// SetClassFunctionTable
// DispatchCDExecFunction
//
// History: 2-01-95 kennethm Created
// 7-25-95 kennethm Merged function table class
// (MarinaApiXXXX functions)
// 9-26-95 alexe Cleaned up/ added more 'Marina' functions
// Removed some obsolete accessor functions
//
// Notes:
//
//--------------------------------------------------------------------------
class CMAutomate
{
public:
//
// Default constructor and destructor
//
CMAutomate();
~CMAutomate();
//
// Special case initialization constructor
//
CMAutomate(struct tagMarinaFunctionTableElement *pJumpTable);
//
// On the server side, pull out the marina handle from ole storage
// Called during object initialization.
//
HRESULT FindMarinaHandle(LPSTORAGE pStg, HWND hWndObj);
//
// On the container side, called to place the marina handle into
// storage so FindMarinaHandle can get to it
//
HRESULT WriteMarinaHandle(LPSTORAGE pStg);
//
// Register a file name with marina
//
HRESULT MarinaRegisterFile(LPCWSTR pszFileName, HWND hWnd);
//
// Set the jump table used by Dispatch functions
//
VOID SetJumpTable(struct tagMarinaFunctionTableElement *pJumpTable);
//
// Called when a WM_COPYDATA message is received
//
LRESULT DispatchCopyData(HWND hwnd, LPARAM lParam);
//
// Called when a WM_PRIVATECOPYDATA message is received
//
LRESULT DispatchPrivateCopyData(HWND hwnd, LPARAM lParam);
//
// When an application starts up, checks to see if marina started
// the application. Used by all applications
//
BOOL InMarina() const;
//
// When an application starts up, calls parsecommandline to see
// if the application was started by marina
//
HRESULT MarinaParseCommandLine(HWND hWnd);
//
// Application level marina API functions
//
virtual HRESULT MarinaApiCloseApp(
HWND hwnd,
PVOID pvParam,
PCOPYDATASTRUCT pOutParameter);
virtual HRESULT MarinaApiCreateDoc(
HWND hwnd,
PVOID pvParam,
PCOPYDATASTRUCT pOutParameter);
virtual HRESULT MarinaApiOpenDoc(
HWND hwnd,
PVOID pvParam,
PCOPYDATASTRUCT pOutParameter);
virtual HRESULT MarinaApiCloseAllDocs(
HWND hwnd,
PVOID pvParam,
PCOPYDATASTRUCT pOutParameter);
virtual HRESULT MarinaApiGetDocCount(
HWND hwnd,
PVOID pvParam,
PCOPYDATASTRUCT pOutParameter);
virtual HRESULT MarinaApiGetAppHwnd(
HWND hwnd,
PVOID pvParam,
PCOPYDATASTRUCT pOutParameter);
//
// Document level marina API functions
//
virtual HRESULT MarinaApiSaveDoc(
HWND hwnd,
PVOID pvParam,
PCOPYDATASTRUCT pOutParameter);
virtual HRESULT MarinaApiCloseDoc(
HWND hwnd,
PVOID pvParam,
PCOPYDATASTRUCT pOutParameter);
virtual HRESULT MarinaApiCopyDoc(
HWND hwnd,
PVOID pvParam,
PCOPYDATASTRUCT pOutParameter);
virtual HRESULT MarinaApiInsertObject(
HWND hwnd,
PVOID pvParam,
PCOPYDATASTRUCT pOutParameter);
virtual HRESULT MarinaApiGetObject(
HWND hwnd,
PVOID pvParam,
PCOPYDATASTRUCT pOutParameter);
virtual HRESULT MarinaApiGetObjCount(
HWND hwnd,
PVOID pvParam,
PCOPYDATASTRUCT pOutParameter);
//
// Object level marina API functions
//
virtual HRESULT MarinaApiCopyObject(
HWND hwnd,
PVOID pvParam,
PCOPYDATASTRUCT pOutParameter);
virtual HRESULT MarinaApiActivateObject(
HWND hwnd,
PVOID pvParam,
PCOPYDATASTRUCT pOutParameter);
//
// Other marina API functions
//
virtual HRESULT MarinaApiGetAppProcessId(
HWND hwnd,
PVOID pvParam,
PCOPYDATASTRUCT pOutParameter);
private:
struct tagMarinaFunctionTableElement *m_MarinaDispatchTable;
//
// The marina handle that is being used for the current call
//
DWORD m_dwMarinaHandle;
static BOOL m_fRunByMarina;
//
// The window that was registered for this particular instance of
// CMAutomate
//
DWORD m_dwRegisteredhWnd;
//
// Our own internal Marina API function table. This list contains
// pointers to all of the virtual MarinaApiXXXXX functions listed
// above after the call to SetClassFunctionTable. This is done in
// the constructor
//
struct tagMarinaClassTableElement *m_MarinaAPIFuncTable;
HRESULT SetClassFunctionTable();
//
// Performs the actual call to the user api when a marina message
// is received.
//
HRESULT DispatchCDExecFunction(
HWND hwnd,
PCDEXECINFO pCDExecInfo,
PCOPYDATASTRUCT pOutParameter);
};
//
// Each function in the jump table follows this prototype
//
typedef HRESULT (WINAPI *COPYDATA_FUNCTION)(
HWND hWnd,
LPVOID pInParameter,
PCOPYDATASTRUCT pOutParameter);
//
// This is one element in the jump table used by the CMAutomate class
// The list is terminated by a null entry at the end
//
typedef struct tagMarinaFunctionTableElement
{
COPYDATA_FUNCTION pfnFunction;
LPWSTR lpszFunctionName;
} MARINAFUNCTIONTABLEELEMENT;
//
// This is one element in the internal class API function table
// The list is terminated by a null entry at the end
//
typedef struct tagMarinaClassTableElement
{
HRESULT (CMAutomate::*pfnFunction)(
HWND hwnd,
PVOID pvParam,
PCOPYDATASTRUCT pOutParameter);
LPWSTR lpszFunctionName;
} MARINACLASSTABLEELEMENT;
//
// An itty bitty class to perform the global rpc binding.
//
// Note, the Mac doesn't support real RPC yet (04-Nov-96)
//
#ifndef _MAC
class CMarinaAutomateRPCBinding
{
public:
CMarinaAutomateRPCBinding();
~CMarinaAutomateRPCBinding();
};
#endif // !_MAC
#endif // __AUTOMATE_HXX__
| 26.868984 | 79 | 0.57757 | npocmaka |
c1ba4af221b5c9c241bd425ab1916236f7fb8228 | 1,617 | cc | C++ | lib/Differentiator.cc | wcrvt/zARCS | 113dbad3c50aa55f1d8706763f026659799c8ff1 | [
"BSD-2-Clause",
"BSD-2-Clause-FreeBSD"
] | null | null | null | lib/Differentiator.cc | wcrvt/zARCS | 113dbad3c50aa55f1d8706763f026659799c8ff1 | [
"BSD-2-Clause",
"BSD-2-Clause-FreeBSD"
] | null | null | null | lib/Differentiator.cc | wcrvt/zARCS | 113dbad3c50aa55f1d8706763f026659799c8ff1 | [
"BSD-2-Clause",
"BSD-2-Clause-FreeBSD"
] | null | null | null | // 擬似微分器クラス
// 2011/02/10 Yuki YOKOKURA
//
// 擬似微分器 G(s)=(s*gpd)/(s+gpd) (双一次変換)
//
// Copyright (C) 2011 Yuki YOKOKURA
// This program is free software;
// you can redistribute it and/or modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3 of the License, or any later version.
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details <http://www.gnu.org/licenses/>.
// Besides, you can negotiate about other options of licenses instead of GPL.
// If you would like to get other licenses, please contact us<yuki@katsura.sd.keio.ac.jp>.
#include "Differentiator.hh"
using namespace ARCS;
Differentiator::Differentiator(double Bandwidth, double SmplTime)
// コンストラクタ Bandwidth;[rad/s] 帯域,SmplTime;[s] 制御周期
: Ts(SmplTime), // [s] 制御周期の格納
gpd(Bandwidth), // [rad/s] 擬似微分の帯域の格納
uZ1(0), yZ1(0)
{
}
Differentiator::~Differentiator(){
// デストラクタ
}
double Differentiator::GetSignal(double u){
// 出力信号の取得 u;入力信号
double y;
y = ( 2.0*gpd*(u-uZ1) + (2.0-Ts*gpd)*yZ1 )/(2.0+Ts*gpd);
uZ1=u;
yZ1=y;
return y;
}
void Differentiator::SetBandwidth(double Bandwidth){
// 擬似微分の帯域の再設定 Bandwidth;[rad/s] 帯域
gpd=Bandwidth;
}
void Differentiator::SetSmplTime(double SmplTime){
// 制御周期の再設定 SmplTime;[s] 制御周期
Ts=SmplTime; // [s] 制御周期の再設定
}
void Differentiator::ClearStateVars(void){
// すべての状態変数のリセット
uZ1=0; // 状態変数1のゼロクリア
yZ1=0; // 状態変数2のゼロクリア
}
| 26.080645 | 103 | 0.714904 | wcrvt |
c1bc0f3351bec8de4f40892e22b1775e0c9f5257 | 2,528 | cpp | C++ | TAO/tao/Messaging/Buffering_Constraint_Policy.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 36 | 2015-01-10T07:27:33.000Z | 2022-03-07T03:32:08.000Z | TAO/tao/Messaging/Buffering_Constraint_Policy.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 2 | 2018-08-13T07:30:51.000Z | 2019-02-25T03:04:31.000Z | TAO/tao/Messaging/Buffering_Constraint_Policy.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 38 | 2015-01-08T14:12:06.000Z | 2022-01-19T08:33:00.000Z | // $Id: Buffering_Constraint_Policy.cpp 91628 2010-09-07 11:11:12Z johnnyw $
#include "tao/Messaging/Buffering_Constraint_Policy.h"
#if (TAO_HAS_BUFFERING_CONSTRAINT_POLICY == 1)
#include "tao/Messaging/TAO_ExtA.h"
#include "tao/SystemException.h"
#include "ace/CORBA_macros.h"
#if ! defined (__ACE_INLINE__)
#include "tao/Messaging/Buffering_Constraint_Policy.inl"
#endif /* __ACE_INLINE__ */
TAO_BEGIN_VERSIONED_NAMESPACE_DECL
TAO_Buffering_Constraint_Policy::TAO_Buffering_Constraint_Policy (const TAO::BufferingConstraint &buffering_constraint)
: ::CORBA::Object ()
, ::CORBA::Policy ()
, TAO::BufferingConstraintPolicy ()
, ::CORBA::LocalObject ()
, buffering_constraint_ (buffering_constraint)
{
}
TAO_Buffering_Constraint_Policy::TAO_Buffering_Constraint_Policy (const TAO_Buffering_Constraint_Policy &rhs)
: ::CORBA::Object ()
, ::CORBA::Policy ()
, TAO::BufferingConstraintPolicy ()
, ::CORBA::LocalObject ()
, buffering_constraint_ (rhs.buffering_constraint_)
{
}
CORBA::PolicyType
TAO_Buffering_Constraint_Policy::policy_type (void)
{
return TAO::BUFFERING_CONSTRAINT_POLICY_TYPE;
}
CORBA::Policy_ptr
TAO_Buffering_Constraint_Policy::create (const CORBA::Any& val)
{
const TAO::BufferingConstraint *buffering_constraint = 0;
if ((val >>= buffering_constraint) == 0)
throw ::CORBA::PolicyError (CORBA::BAD_POLICY_VALUE);
TAO_Buffering_Constraint_Policy *servant = 0;
ACE_NEW_THROW_EX (servant,
TAO_Buffering_Constraint_Policy (*buffering_constraint),
CORBA::NO_MEMORY ());
return servant;
}
TAO_Buffering_Constraint_Policy *
TAO_Buffering_Constraint_Policy::clone (void) const
{
TAO_Buffering_Constraint_Policy *copy = 0;
ACE_NEW_RETURN (copy,
TAO_Buffering_Constraint_Policy (*this),
0);
return copy;
}
TAO::BufferingConstraint
TAO_Buffering_Constraint_Policy::buffering_constraint (void)
{
return this->buffering_constraint_;
}
CORBA::Policy_ptr
TAO_Buffering_Constraint_Policy::copy (void)
{
TAO_Buffering_Constraint_Policy* servant = 0;
ACE_NEW_THROW_EX (servant,
TAO_Buffering_Constraint_Policy (*this),
CORBA::NO_MEMORY ());
return servant;
}
void
TAO_Buffering_Constraint_Policy::destroy (void)
{
}
TAO_Cached_Policy_Type
TAO_Buffering_Constraint_Policy::_tao_cached_type (void) const
{
return TAO_CACHED_POLICY_BUFFERING_CONSTRAINT;
}
TAO_END_VERSIONED_NAMESPACE_DECL
#endif /* TAO_HAS_BUFFERING_CONSTRAINT_POLICY == 1 */
| 25.795918 | 119 | 0.752769 | cflowe |
c1bc6a696bf8f877de9dac41d77504f04bc3c10b | 6,179 | cc | C++ | hilti/codegen/instructions/classifier.cc | asilha/hilti | ebfffc7dad31059b43a02eb26abcf7a25f742eb8 | [
"BSD-3-Clause"
] | 46 | 2015-01-21T13:31:25.000Z | 2020-10-27T10:18:03.000Z | hilti/codegen/instructions/classifier.cc | jjchromik/hilti-104-total | 0f9e0cb7114acc157211af24f8254e4b23bd78a5 | [
"BSD-3-Clause"
] | 29 | 2015-03-30T08:23:04.000Z | 2019-05-03T13:11:35.000Z | hilti/codegen/instructions/classifier.cc | jjchromik/hilti-104-total | 0f9e0cb7114acc157211af24f8254e4b23bd78a5 | [
"BSD-3-Clause"
] | 20 | 2015-01-27T12:59:38.000Z | 2020-10-28T21:40:47.000Z |
#include <hilti/hilti-intern.h>
#include "../stmt-builder.h"
using namespace hilti;
using namespace codegen;
static void _freeFields(CodeGen* cg, shared_ptr<Type> rtype, llvm::Value* fields, const Location& l)
{
auto ftypes = ast::type::checkedTrait<type::trait::TypeList>(rtype)->typeList();
auto atype = llvm::ArrayType::get(cg->llvmTypePtr(), ftypes.size());
fields = cg->builder()->CreateBitCast(fields, cg->llvmTypePtr(atype));
for ( int i = 0; i < ftypes.size(); i++ ) {
auto addr = cg->llvmGEP(fields, cg->llvmGEPIdx(0), cg->llvmGEPIdx(i));
cg->llvmFree(cg->builder()->CreateLoad(addr), "classifier-free-one-field", l);
}
cg->llvmFree(fields, "classifier-free-fields", l);
}
static llvm::Value* _matchAllField(CodeGen* cg)
{
return cg->llvmClassifierField(cg->llvmConstNull(cg->llvmTypePtr()), cg->llvmConstInt(0, 64));
}
static llvm::Value* _llvmFields(CodeGen* cg, shared_ptr<Type> rtype, shared_ptr<Type> stype,
llvm::Value* val, const Location& l)
{
auto ftypes = ast::type::checkedTrait<type::trait::TypeList>(rtype)->typeList();
auto stypes = ast::type::checkedTrait<type::trait::TypeList>(stype)->typeList();
auto atype = llvm::ArrayType::get(cg->llvmTypePtr(), ftypes.size());
auto fields = cg->llvmMalloc(atype, "hlt.classifier", l);
// Convert the fields into the internal hlt_classifier_field representation.
auto ft = ftypes.begin();
auto st = stypes.begin();
for ( int i = 0; i < ftypes.size(); i++ ) {
auto field =
cg->llvmStructGet(stype, val, i,
[&](CodeGen* cg) -> llvm::Value* { return _matchAllField(cg); },
[&](CodeGen* cg, llvm::Value* v) -> llvm::Value* {
return cg->llvmClassifierField(*ft, *st, v, l);
},
l);
auto addr = cg->llvmGEP(fields, cg->llvmGEPIdx(0), cg->llvmGEPIdx(i));
cg->llvmCreateStore(field, addr);
++ft;
++st;
}
fields = cg->builder()->CreateBitCast(fields, cg->llvmTypePtr());
return fields;
}
void StatementBuilder::visit(statement::instruction::classifier::New* i)
{
auto ctype = ast::rtti::tryCast<type::Classifier>(typedType(i->op1()));
auto op1 = builder::integer::create(
ast::type::checkedTrait<type::trait::TypeList>(ctype->ruleType())->typeList().size());
auto op2 = builder::type::create(ctype->ruleType());
auto op3 = builder::type::create(ctype->valueType());
CodeGen::expr_list args = {op1, op2, op3};
auto result = cg()->llvmCall("hlt::classifier_new", args);
cg()->llvmStore(i, result);
}
void StatementBuilder::visit(statement::instruction::classifier::Add* i)
{
auto rtype = ast::rtti::tryCast<type::Classifier>(referencedType(i->op1()))->ruleType();
// op2 can be a tuple (ref<struct>, prio) or a just a rule ref<struct>
//
// TODO: The separations for the cases below isn't fool-proof but should
// be good enough for now.
auto ttype = ast::rtti::tryCast<type::Tuple>(i->op2()->type());
if ( ttype ) {
auto op2 = cg()->llvmValue(i->op2());
auto rule = cg()->llvmExtractValue(op2, 0);
auto reftype = ast::rtti::tryCast<type::Reference>(ttype->typeList().front());
if ( reftype ) {
auto stype = reftype->argType();
auto prio =
cg()->builder()->CreateZExt(cg()->llvmExtractValue(op2, 1), cg()->llvmTypeInt(64));
auto fields = _llvmFields(cg(), rtype, stype, rule, i->location());
CodeGen::expr_list args = {i->op1(),
builder::codegen::create(builder::any::type(), fields),
builder::codegen::create(builder::integer::type(64), prio),
i->op3()};
cg()->llvmCall("hlt::classifier_add", args);
return;
}
}
auto rval = i->op2()->coerceTo(builder::reference::type(rtype));
auto rule = cg()->llvmValue(rval);
auto reftype = ast::rtti::checkedCast<type::Reference>(rval->type());
auto stype = reftype->argType();
auto fields = _llvmFields(cg(), rtype, stype, rule, i->location());
CodeGen::expr_list args = {i->op1(), builder::codegen::create(builder::any::type(), fields),
i->op3()};
cg()->llvmCall("hlt::classifier_add_no_prio", args);
}
void StatementBuilder::visit(statement::instruction::classifier::Compile* i)
{
CodeGen::expr_list args = {i->op1()};
cg()->llvmCall("hlt::classifier_compile", args);
}
void StatementBuilder::visit(statement::instruction::classifier::Get* i)
{
auto rtype = ast::rtti::tryCast<type::Classifier>(referencedType(i->op1()))->ruleType();
auto vtype = ast::rtti::tryCast<type::Classifier>(referencedType(i->op1()))->valueType();
auto op2 = i->op2()->coerceTo(builder::reference::type(rtype));
auto fields = _llvmFields(cg(), rtype, rtype, cg()->llvmValue(op2), i->location());
CodeGen::expr_list args = {i->op1(), builder::codegen::create(builder::any::type(), fields)};
auto voidp = cg()->llvmCall("hlt::classifier_get", args, false, true, [&](CodeGen* cg) {
_freeFields(cg, rtype, fields, i->location());
});
auto casted = builder()->CreateBitCast(voidp, cg()->llvmTypePtr(cg()->llvmType(vtype)));
auto result = builder()->CreateLoad(casted);
cg()->llvmStore(i, result);
}
void StatementBuilder::visit(statement::instruction::classifier::Matches* i)
{
auto rtype = ast::rtti::tryCast<type::Classifier>(referencedType(i->op1()))->ruleType();
auto op2 = i->op2()->coerceTo(builder::reference::type(rtype));
auto fields = _llvmFields(cg(), rtype, rtype, cg()->llvmValue(op2), i->location());
CodeGen::expr_list args = {i->op1(), builder::codegen::create(builder::any::type(), fields)};
auto result = cg()->llvmCall("hlt::classifier_matches", args, false, false);
_freeFields(cg(), rtype, fields, i->location());
cg()->llvmCheckException();
cg()->llvmStore(i, result);
}
| 39.356688 | 100 | 0.603172 | asilha |
c1be7a57951f38077bfeb5de9a40d7be764888cf | 20,287 | cpp | C++ | src/commlib/zcelib/zce_server_base.cpp | sailzeng/zcelib | 88e14ab436f1b40e8071e15ef6d9fae396efc3b4 | [
"Apache-2.0"
] | 72 | 2015-01-08T05:01:48.000Z | 2021-12-28T06:13:03.000Z | src/commlib/zcelib/zce_server_base.cpp | sailzeng/zcelib | 88e14ab436f1b40e8071e15ef6d9fae396efc3b4 | [
"Apache-2.0"
] | 4 | 2016-01-18T12:24:59.000Z | 2019-10-12T07:19:15.000Z | src/commlib/zcelib/zce_server_base.cpp | sailzeng/zcelib | 88e14ab436f1b40e8071e15ef6d9fae396efc3b4 | [
"Apache-2.0"
] | 40 | 2015-01-26T06:49:18.000Z | 2021-07-20T08:11:48.000Z | #include "zce_predefine.h"
#include "zce_time_value.h"
#include "zce_os_adapt_file.h"
#include "zce_os_adapt_flock.h"
#include "zce_os_adapt_process.h"
#include "zce_os_adapt_socket.h"
#include "zce_os_adapt_time.h"
#include "zce_os_adapt_dirent.h"
#include "zce_log_logging.h"
#include "zce_server_base.h"
/*********************************************************************************
class ZCE_Server_Base
*********************************************************************************/
ZCE_Server_Base *ZCE_Server_Base::base_instance_ = NULL;
// 构造函数,私有,使用单子类的实例,
ZCE_Server_Base::ZCE_Server_Base():
pid_handle_(ZCE_INVALID_HANDLE),
self_pid_(0),
app_run_(true),
app_reload_(false),
check_leak_times_(0),
mem_checkpoint_size_(0),
cur_mem_usesize_(0),
process_cpu_ratio_(0),
system_cpu_ratio_(0),
mem_use_ratio_(0)
{
memset(&last_process_perf_, 0, sizeof(last_process_perf_));
memset(&now_process_perf_, 0, sizeof(now_process_perf_));
memset(&last_system_perf_, 0, sizeof(last_system_perf_));
memset(&now_system_perf_, 0, sizeof(now_system_perf_));
}
ZCE_Server_Base::~ZCE_Server_Base()
{
// 关闭文件
if (pid_handle_ != ZCE_INVALID_HANDLE)
{
zce::flock_unlock(&pidfile_lock_, SEEK_SET, 0, PID_FILE_LEN);
zce::flock_destroy(&pidfile_lock_);
zce::close(pid_handle_);
}
}
// 初始化
int ZCE_Server_Base::socket_init()
{
int ret = 0;
ret = zce::socket_init();
if (ret != 0)
{
return ret;
}
return 0;
}
//打印输出PID File
int ZCE_Server_Base::out_pid_file(const char *pragramname)
{
int ret = 0;
std::string pidfile_name = pragramname;
pidfile_name += ".pid";
self_pid_ = zce::getpid();
//检查PID文件是否存在,,
bool must_create_new = false;
ret = zce::access(pidfile_name.c_str(), F_OK);
if ( 0 != ret)
{
must_create_new = true;
}
// 设置文件读取参数,表示其他用户可以读取,open函数会自动帮忙调整参数的。
int fileperms = 0644;
pid_handle_ = zce::open(pidfile_name.c_str(),
O_RDWR | O_CREAT,
static_cast<mode_t>(fileperms));
if (pid_handle_ == ZCE_INVALID_HANDLE)
{
ZCE_LOG(RS_ERROR, "Open pid file [%s]fail.", pidfile_name.c_str());
return -1;
}
//如果PID文件不存在,调整文件长度,(说明见下)
//这个地方没有原子保护,有一定风险,但……
if (true == must_create_new)
{
//我是用WINDOWS下的记录锁是模拟和Linux类似,但Windows的文件锁其实没有对将长度参数设置0,
//锁定整个文件的功能,所以要先把文件长度调整
zce::ftruncate(pid_handle_, PID_FILE_LEN);
}
zce::flock_init(&pidfile_lock_, pid_handle_);
char tmpbuff[PID_FILE_LEN + 1];
snprintf(tmpbuff, PID_FILE_LEN + 1, "%*.u", (int)PID_FILE_LEN * (-1), self_pid_);
// 尝试锁定全部文件,如果锁定不成功,表示有人正在用这个文件
ret = zce::flock_trywrlock(&pidfile_lock_, SEEK_SET, 0, PID_FILE_LEN);
if (ret != 0)
{
ZCE_LOG(RS_ERROR, "Trylock pid file [%s]fail. Last error =%d",
pidfile_name.c_str(), zce::last_error());
return ret;
}
//写入文件内容, 截断文件为BUFFER_LEN,
zce::ftruncate(pid_handle_, PID_FILE_LEN);
zce::lseek(pid_handle_, 0, SEEK_SET);
zce::write(pid_handle_, tmpbuff, PID_FILE_LEN);
return 0;
}
// 监测这个进程的系统状况,每N分钟运行一次就OK了
// 看门狗得到进程的状态
int ZCE_Server_Base::watch_dog_status(bool first_record)
{
int ret = 0;
// 如果不是第一次记录,保存上一次记录的结果
if (!first_record)
{
last_process_perf_ = now_process_perf_;
last_system_perf_ = now_system_perf_;
}
ret = zce::get_self_perf(&now_process_perf_);
if (0 != ret)
{
return ret;
}
ret = zce::get_system_perf(&now_system_perf_);
if (0 != ret)
{
return ret;
}
cur_mem_usesize_ = now_process_perf_.vm_size_;
// 记录第一次的内存数据
if (first_record)
{
mem_checkpoint_size_ = now_process_perf_.vm_size_;
return 0;
}
// 处理内存变化的情况
size_t vary_mem_size = 0;
if (now_process_perf_.vm_size_ >= mem_checkpoint_size_)
{
vary_mem_size = now_process_perf_.vm_size_ - mem_checkpoint_size_;
}
// 内存居然缩小了……
else
{
mem_checkpoint_size_ = now_process_perf_.vm_size_;
}
// 这个告警如何向监控汇报要考虑一下
if (vary_mem_size >= MEMORY_LEAK_THRESHOLD)
{
++check_leak_times_;
ZCE_LOG(RS_ERROR, "[zcelib] [WATCHDOG][PID:%u] Monitor could memory leak,"
"mem_checkpoint_size_ =[%u],run_mem_size_=[%u].",
self_pid_,
mem_checkpoint_size_,
now_process_perf_.vm_size_);
// 如果已经监测了若干次内存泄漏,则不再记录告警
if (check_leak_times_ > MAX_RECORD_MEMLEAK_NUMBER)
{
mem_checkpoint_size_ = now_process_perf_.vm_size_;
check_leak_times_ = 0;
}
}
// 其实到这个地方了,你可以干的事情很多,
// 甚至计算某一段时间内程序的CPU占用率过高(TNNND,后来我真做了)
timeval last_to_now = zce::timeval_sub(now_system_perf_.up_time_,
last_system_perf_.up_time_);
// 得到进程的CPU利用率
timeval proc_utime = zce::timeval_sub(now_process_perf_.run_utime_,
last_process_perf_.run_utime_);
timeval proc_stime = zce::timeval_sub(now_process_perf_.run_stime_,
last_process_perf_.run_stime_);
timeval proc_cpu_time = zce::timeval_add(proc_utime, proc_stime);
// 如果间隔时间不为0
if (zce::total_milliseconds(last_to_now) > 0)
{
process_cpu_ratio_ = static_cast<uint32_t>(zce::total_milliseconds(proc_cpu_time)
* 1000 / zce::total_milliseconds(last_to_now));
}
else
{
process_cpu_ratio_ = 0;
}
ZCE_LOG(RS_INFO, "[zcelib] [WATCHDOG][PID:%u] cpu ratio[%u] "
"totoal process user/sys[%lld/%lld] milliseconds "
"leave last point all/usr/sys[%lld/%lld/%lld] milliseconds "
"memory use//add [%ld/%ld].",
self_pid_,
process_cpu_ratio_,
zce::total_milliseconds(now_process_perf_.run_utime_),
zce::total_milliseconds(now_process_perf_.run_stime_),
zce::total_milliseconds(last_to_now),
zce::total_milliseconds(proc_utime),
zce::total_milliseconds(proc_stime),
cur_mem_usesize_,
vary_mem_size);
// 计算系统的CPU时间,非IDLE以外的时间都是消耗时间
timeval sys_idletime = zce::timeval_sub(now_system_perf_.idle_time_,
last_system_perf_.idle_time_);
timeval sys_cputime = zce::timeval_sub(last_to_now, sys_idletime);
// 如果间隔时间不为0
if (zce::total_milliseconds(last_to_now) > 0)
{
system_cpu_ratio_ =
static_cast<uint32_t>(zce::total_milliseconds(sys_cputime)
* 1000 / zce::total_milliseconds(last_to_now));
}
else
{
ZCE_LOG(RS_ERROR, "system_uptime = %llu, process_start_time = %llu",
zce::total_milliseconds(now_system_perf_.up_time_),
zce::total_milliseconds(now_process_perf_.start_time_));
system_cpu_ratio_ = 0;
}
// 系统或进程CPU使用超过阈值时记条账单
if (process_cpu_ratio_ >= PROCESS_CPU_RATIO_THRESHOLD ||
system_cpu_ratio_ >= SYSTEM_CPU_RATIO_THRESHOLD)
{
ZCE_LOG(RS_ERROR, "[zcelib] [WATCHDOG][PID:%u] point[%u] vm_size[%u] "
"process cpu ratio [%f] threshold [%f], system cpu ratio[%f] threshold[%f] "
"totoal process user/sys[%lld/%lld] milliseconds "
"leave last point all/usr/sys[%lld/%lld/%lld] milliseconds.",
self_pid_,
mem_checkpoint_size_,
now_process_perf_.vm_size_,
double(process_cpu_ratio_) / 10,
double(PROCESS_CPU_RATIO_THRESHOLD) / 10,
double(system_cpu_ratio_) / 10,
double(SYSTEM_CPU_RATIO_THRESHOLD) / 10,
zce::total_milliseconds(now_process_perf_.run_utime_),
zce::total_milliseconds(now_process_perf_.run_stime_),
zce::total_milliseconds(last_to_now),
zce::total_milliseconds(proc_utime),
zce::total_milliseconds(proc_stime));
}
// 内存使用情况的监控
can_use_size_ = now_system_perf_.freeram_size_ +
now_system_perf_.cachedram_size_ +
now_system_perf_.bufferram_size_;
if (now_system_perf_.totalram_size_ > 0)
{
mem_use_ratio_ = static_cast<uint32_t>((now_system_perf_.totalram_size_
- can_use_size_) * 1000 / now_system_perf_.totalram_size_);
}
else
{
mem_use_ratio_ = 0;
}
ZCE_LOG(RS_INFO,
"[zcelib] [WATCHDOG][SYSTEM] cpu radio [%u] "
"totoal usr/nice/sys/idle/iowait/hardirq/softirq "
"[%lld/%lld/%lld/%lld/%lld/%lld/%lld] milliseconds"
"leave last point all/use/idle[%lld/%lld/%lld] milliseconds "
"mem ratio[%u] [totoal/can use/free/buffer/cache] "
"[%lld/%lld/%lld/%lld/%lld] bytes",
system_cpu_ratio_,
zce::total_milliseconds(now_system_perf_.user_time_),
zce::total_milliseconds(now_system_perf_.nice_time_),
zce::total_milliseconds(now_system_perf_.system_time_),
zce::total_milliseconds(now_system_perf_.idle_time_),
zce::total_milliseconds(now_system_perf_.iowait_time_),
zce::total_milliseconds(now_system_perf_.hardirq_time_),
zce::total_milliseconds(now_system_perf_.softirq_time_),
zce::total_milliseconds(last_to_now),
zce::total_milliseconds(sys_cputime),
zce::total_milliseconds(sys_idletime),
mem_use_ratio_,
now_system_perf_.totalram_size_,
can_use_size_,
now_system_perf_.freeram_size_,
now_system_perf_.bufferram_size_,
now_system_perf_.cachedram_size_);
return 0;
}
int ZCE_Server_Base::process_signal(void)
{
//忽视部分信号,这样简单
zce::signal(SIGHUP, SIG_IGN);
zce::signal(SIGPIPE, SIG_IGN);
zce::signal(SIGCHLD, SIG_IGN);
#ifdef ZCE_OS_WINDOWS
//Windows下设置退出处理函数,可以用Ctrl + C 退出
SetConsoleCtrlHandler((PHANDLER_ROUTINE)exit_signal, TRUE);
#else
//这个几个信号被认可为退出信号
zce::signal(SIGINT, exit_signal);
zce::signal(SIGQUIT, exit_signal);
zce::signal(SIGTERM, exit_signal);
//重新加载部分配置,用了SIGUSR1 kill -10
zce::signal(SIGUSR1, reload_cfg_signal);
#endif
//SIGUSR1,SIGUSR2你可以用来干点自己的活,
return 0;
}
int ZCE_Server_Base::daemon_init()
{
//Daemon 精灵进程,但是我不清理目录路径,
#if defined (ZCE_OS_LINUX)
pid_t pid = zce::fork();
if (pid < 0)
{
return -1;
}
else if (pid > 0)
{
::exit(0);
}
#endif
zce::setsid();
zce::umask(0);
#if defined (ZCE_OS_WINDOWS)
//设置Console的标题信息
std::string out_str = get_app_basename();
out_str += " ";
out_str += app_author_;
::SetConsoleTitle(out_str.c_str());
#endif
return 0;
}
//通过启动参数0,得到app_base_name_,app_run_name_
int ZCE_Server_Base::create_app_name(const char *argv_0)
{
app_run_name_ = argv_0;
// 取得base name
char str_base_name[PATH_MAX + 1];
str_base_name[PATH_MAX] = '\0';
zce::basename(argv_0, str_base_name, PATH_MAX);
#if defined ZCE_OS_WINDOWS
//Windows下要去掉,EXE后缀
const size_t WIN_EXE_SUFFIX_LEN = 4;
size_t name_len = strlen(str_base_name);
if (name_len <= WIN_EXE_SUFFIX_LEN)
{
ZCE_LOG(RS_ERROR, "[framework] Exe file name is not expect?Path name[%s].", argv_0);
return -1;
}
//如果有后缀才取消,没有就放鸭子
if (strcasecmp(str_base_name + name_len - WIN_EXE_SUFFIX_LEN, ".EXE") == 0)
{
str_base_name[name_len - WIN_EXE_SUFFIX_LEN] = '\0';
}
#endif
//如果是调试版本,去掉后缀符号_d
#if defined (DEBUG) || defined (_DEBUG)
//如果是调试版本,去掉后缀符号_d
const size_t DEBUG_SUFFIX_LEN = 2;
size_t debug_name_len = strlen(str_base_name);
if (debug_name_len <= DEBUG_SUFFIX_LEN)
{
ZCE_LOG(RS_ERROR, "[framework] Exe file name is not debug _d suffix?str_base_name[%s].", str_base_name);
return -1;
}
if (0 == strcasecmp(str_base_name + debug_name_len - DEBUG_SUFFIX_LEN, "_D"))
{
str_base_name[debug_name_len - DEBUG_SUFFIX_LEN] = '\0';
}
#endif
app_base_name_ = str_base_name;
return 0;
}
//windows下设置服务信息
void ZCE_Server_Base::set_service_info(const char *svc_name,
const char *svc_desc)
{
if (svc_name != NULL)
{
service_name_ = svc_name;
}
if (svc_desc != NULL)
{
service_desc_ = svc_desc;
}
}
//得到运行信息,可能包括路径信息
const char *ZCE_Server_Base::get_app_runname()
{
return app_run_name_.c_str();
}
//得到程序进程名称,,去掉了路径,WINDOWS下去掉了后缀
const char *ZCE_Server_Base::get_app_basename()
{
return app_base_name_.c_str();
}
//设置进程是否运行的标志
void ZCE_Server_Base::set_run_sign(bool app_run)
{
app_run_ = app_run;
}
//设置reload标志
void ZCE_Server_Base::set_reload_sign(bool app_reload)
{
app_reload_ = app_reload;
}
//信号处理代码,
#ifdef ZCE_OS_WINDOWS
BOOL ZCE_Server_Base::exit_signal(DWORD)
{
base_instance_->set_run_sign(false);
return TRUE;
}
#else
void ZCE_Server_Base::exit_signal(int)
{
base_instance_->set_run_sign(false);
return;
}
// USER1信号处理函数
void ZCE_Server_Base::reload_cfg_signal(int)
{
// 信号处理函数中不能有IO等不可重入的操作,否则容易死锁
base_instance_->set_reload_sign(true);
return;
}
#endif
#if defined ZCE_OS_WINDOWS
//运行服务
int ZCE_Server_Base::win_services_run()
{
char service_name[PATH_MAX + 1];
service_name[PATH_MAX] = '\0';
strncpy(service_name, app_base_name_.c_str(), PATH_MAX);
SERVICE_TABLE_ENTRY st[] =
{
{ service_name, (LPSERVICE_MAIN_FUNCTION)win_service_main },
{ NULL, NULL }
};
BOOL b_ret = ::StartServiceCtrlDispatcher(st);
if (b_ret)
{
//LogEvent(_T("Register Service Main Function Success!"));
}
else
{
UINT error_info = ::GetLastError();
ZCE_UNUSED_ARG(error_info);
//LogEvent(_T("Register Service Main Function Error!"));
}
return 0;
}
//安装服务
int ZCE_Server_Base::win_services_install()
{
if (win_services_isinstalled())
{
printf("install service fail. service %s already exist", app_base_name_.c_str());
return 0;
}
//打开服务控制管理器
SC_HANDLE handle_scm = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (handle_scm == NULL)
{
//::MessageBox(NULL, _T("Couldn't open service manager"), app_base_name_.c_str(), MB_OK);
printf("can't open service manager.\n");
return FALSE;
}
// Get the executable file path
char file_path[MAX_PATH + 1];
file_path[MAX_PATH] = '\0';
::GetModuleFileName(NULL, file_path, MAX_PATH);
//创建服务
SC_HANDLE handle_services = ::CreateService(
handle_scm,
app_base_name_.c_str(),
service_name_.c_str(),
SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS,
SERVICE_DEMAND_START,
SERVICE_ERROR_NORMAL,
file_path,
NULL,
NULL,
"",
NULL,
NULL);
if (handle_services == NULL)
{
printf("install service %s fail. err=%d\n", app_base_name_.c_str(),
GetLastError());
::CloseServiceHandle(handle_scm);
//MessageBox(NULL, _T("Couldn't create service"), app_base_name_.c_str(), MB_OK);
return -1;
}
// 修改描述
SC_LOCK lock = LockServiceDatabase(handle_scm);
if (lock != NULL)
{
SERVICE_DESCRIPTION desc;
desc.lpDescription = (LPSTR)service_desc_.c_str();
ChangeServiceConfig2(handle_services, SERVICE_CONFIG_DESCRIPTION, &desc);
UnlockServiceDatabase(handle_scm);
}
::CloseServiceHandle(handle_services);
::CloseServiceHandle(handle_scm);
printf("install service %s succ.\n", app_base_name_.c_str());
return 0;
}
//卸载服务
int ZCE_Server_Base::win_services_uninstall()
{
if (!win_services_isinstalled())
{
printf("uninstall fail. service %s is not exist.\n", app_base_name_.c_str());
return 0;
}
SC_HANDLE handle_scm = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (handle_scm == NULL)
{
//::MessageBox(NULL, _T("Couldn't open service manager"), app_base_name_.c_str(), MB_OK);
printf("uninstall fail. can't open service manager");
return FALSE;
}
SC_HANDLE handle_services = ::OpenService(handle_scm,
app_base_name_.c_str(),
SERVICE_STOP | DELETE);
if (handle_services == NULL)
{
::CloseServiceHandle(handle_scm);
//::MessageBox(NULL, _T("Couldn't open service"), app_base_name_.c_str(), MB_OK);
printf("can't open service %s\n", app_base_name_.c_str());
return -1;
}
SERVICE_STATUS status;
::ControlService(handle_services, SERVICE_CONTROL_STOP, &status);
//删除服务
BOOL bDelete = ::DeleteService(handle_services);
::CloseServiceHandle(handle_services);
::CloseServiceHandle(handle_scm);
if (bDelete)
{
printf("uninstall service %s succ.\n", app_base_name_.c_str());
return 0;
}
printf("uninstall service %s fail.\n", app_base_name_.c_str());
//LogEvent(_T("Service could not be deleted"));
return -1;
}
//检查服务是否安装
bool ZCE_Server_Base::win_services_isinstalled()
{
bool b_result = false;
//打开服务控制管理器
SC_HANDLE handle_scm = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (handle_scm != NULL)
{
//打开服务
SC_HANDLE handle_service = ::OpenService(handle_scm, app_base_name_.c_str(), SERVICE_QUERY_CONFIG);
if (handle_service != NULL)
{
b_result = true;
::CloseServiceHandle(handle_service);
}
::CloseServiceHandle(handle_scm);
}
return b_result;
}
//服务运行函数
void WINAPI ZCE_Server_Base::win_service_main()
{
//WIN服务用的状态
static SERVICE_STATUS_HANDLE handle_service_status = NULL;
SERVICE_STATUS status;
status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
status.dwCurrentState = SERVICE_STOPPED;
status.dwControlsAccepted = SERVICE_ACCEPT_STOP;
status.dwWin32ExitCode = 0;
status.dwServiceSpecificExitCode = 0;
status.dwCheckPoint = 0;
status.dwWaitHint = 0;
// Register the control request handler
status.dwCurrentState = SERVICE_START_PENDING;
status.dwControlsAccepted = SERVICE_ACCEPT_STOP;
//注册服务控制
handle_service_status = ::RegisterServiceCtrlHandler(base_instance_->get_app_basename(),
win_services_ctrl);
if (handle_service_status == NULL)
{
//LogEvent(_T("Handler not installed"));
return;
}
SetServiceStatus(handle_service_status, &status);
status.dwWin32ExitCode = S_OK;
status.dwCheckPoint = 0;
status.dwWaitHint = 0;
status.dwCurrentState = SERVICE_RUNNING;
SetServiceStatus(handle_service_status, &status);
//base_instance_->do_run();
status.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus(handle_service_status, &status);
//LogEvent(_T("Service stopped"));
}
//服务控制台所需要的控制函数
void WINAPI ZCE_Server_Base::win_services_ctrl(DWORD op_code)
{
switch (op_code)
{
case SERVICE_CONTROL_STOP:
//
base_instance_->app_run_ = false;
break;
case SERVICE_CONTROL_PAUSE:
break;
case SERVICE_CONTROL_CONTINUE:
break;
case SERVICE_CONTROL_INTERROGATE:
break;
case SERVICE_CONTROL_SHUTDOWN:
break;
default:
//LogEvent(_T("Bad service request"));
break;
}
}
#endif //#if defined ZCE_OS_WINDOWS | 26.799207 | 112 | 0.614285 | sailzeng |
c1c177ba08b544e018421945e39c3c112afe7c03 | 544 | cpp | C++ | Chapter_2/2-7.cpp | MemoryDxx/CPP_Exercises | f789d194a72460fc4c6701c2710e1de53566394d | [
"Apache-2.0"
] | null | null | null | Chapter_2/2-7.cpp | MemoryDxx/CPP_Exercises | f789d194a72460fc4c6701c2710e1de53566394d | [
"Apache-2.0"
] | null | null | null | Chapter_2/2-7.cpp | MemoryDxx/CPP_Exercises | f789d194a72460fc4c6701c2710e1de53566394d | [
"Apache-2.0"
] | null | null | null | // 编写一个程序,要求用户输入小时数和分钟数。在main()函数中,将这两个值传递给一个void函数。
// void函数以下面的格式显示这两个值。
// Enter the number of hours: 9
// Enter the number of minutes: 28
// Time: 9:28
#include <iostream>
using namespace std;
void show_time(int hour, int minutes);
int main()
{
int hour, minutes;
cout << "Enter the number of hours: ";
cin >> hour;
cout << "Enter the number of minutes: ";
cin >> minutes;
show_time(hour, minutes);
return 0;
}
void show_time(int hour, int minutes)
{
cout << "Time: " << hour << ":" << minutes << endl;
} | 21.76 | 55 | 0.637868 | MemoryDxx |
c1c35e884065eb04f8e68a0df42130d20ab22d46 | 6,569 | cxx | C++ | Applications/ShrinkImage/niftkShrinkImage.cxx | NifTK/NifTK | 2358b333c89ff1bba1c232eecbbcdc8003305dfe | [
"BSD-3-Clause"
] | 13 | 2018-07-28T13:36:38.000Z | 2021-11-01T19:17:39.000Z | Applications/ShrinkImage/niftkShrinkImage.cxx | NifTK/NifTK | 2358b333c89ff1bba1c232eecbbcdc8003305dfe | [
"BSD-3-Clause"
] | null | null | null | Applications/ShrinkImage/niftkShrinkImage.cxx | NifTK/NifTK | 2358b333c89ff1bba1c232eecbbcdc8003305dfe | [
"BSD-3-Clause"
] | 10 | 2018-08-20T07:06:00.000Z | 2021-07-07T07:55:27.000Z | /*=============================================================================
NifTK: A software platform for medical image computing.
Copyright (c) University College London (UCL). All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
See LICENSE.txt in the top level directory for details.
=============================================================================*/
#include <niftkLogHelper.h>
#include <niftkConversionUtils.h>
#include <itkImageFileReader.h>
#include <itkImageFileWriter.h>
#include <itkNifTKImageIOFactory.h>
#include <itkShrinkImageFilter.h>
#include <itkCommandLineHelper.h>
/*!
* \file niftkShrinkImage.cxx
* \page niftkShrinkImage
* \section niftkShrinkImageSummary Runs the ITK ShrinkImageFilter.
*/
void Usage(char *exec)
{
niftk::LogHelper::PrintCommandLineHeader(std::cout);
std::cout << " " << std::endl;
std::cout << " Runs the ITK ShrinkImageFilter on a 2D or 3D image." << std::endl;
std::cout << " " << std::endl;
std::cout << " " << exec << " -i inputFileName -o outputFileName [options]" << std::endl;
std::cout << " " << std::endl;
std::cout << "*** [mandatory] ***" << std::endl << std::endl;
std::cout << " -i <filename> Input image " << std::endl;
std::cout << " -o <filename> Output image" << std::endl << std::endl;
std::cout << "*** [options] ***" << std::endl << std::endl;
std::cout << " -f <int> [2] Shrink factor" << std::endl;
}
struct arguments
{
std::string inputImage;
std::string outputImage;
int factor;
};
template <int Dimension, class PixelType>
int DoMain(arguments args)
{
typedef typename itk::Image< PixelType, Dimension > InputImageType;
typedef typename itk::ImageFileReader< InputImageType > InputImageReaderType;
typedef typename itk::ImageFileWriter< InputImageType > OutputImageWriterType;
typedef typename itk::ShrinkImageFilter<InputImageType, InputImageType> ShrinkFilterType;
typename InputImageReaderType::Pointer imageReader = InputImageReaderType::New();
imageReader->SetFileName(args.inputImage);
typename ShrinkFilterType::Pointer filter = ShrinkFilterType::New();
filter->SetInput(imageReader->GetOutput());
for (unsigned int i = 0; i < Dimension; i++)
{
filter->SetShrinkFactor(i, args.factor);
}
typename OutputImageWriterType::Pointer imageWriter = OutputImageWriterType::New();
imageWriter->SetFileName(args.outputImage);
imageWriter->SetInput(filter->GetOutput());
try
{
imageWriter->Update();
}
catch( itk::ExceptionObject & err )
{
std::cerr << "Failed: " << err << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
/**
* \brief Takes image and shrinks it by a factor in each dimension.
*/
int main(int argc, char** argv)
{
itk::NifTKImageIOFactory::Initialize();
// To pass around command line args
struct arguments args;
// Define defaults
args.factor = 2;
// Parse command line args
for(int i=1; i < argc; i++){
if(strcmp(argv[i], "-help")==0 || strcmp(argv[i], "-Help")==0 || strcmp(argv[i], "-HELP")==0 || strcmp(argv[i], "-h")==0 || strcmp(argv[i], "--h")==0){
Usage(argv[0]);
return -1;
}
else if(strcmp(argv[i], "-i") == 0){
args.inputImage=argv[++i];
std::cout << "Set -i=" << args.inputImage << std::endl;
}
else if(strcmp(argv[i], "-o") == 0){
args.outputImage=argv[++i];
std::cout << "Set -o=" << args.outputImage << std::endl;
}
else if(strcmp(argv[i], "-f") == 0){
args.factor=atoi(argv[++i]);
std::cout << "Set -f=" << niftk::ConvertToString(args.factor) << std::endl;
}
else {
std::cerr << argv[0] << ":\tParameter " << argv[i] << " unknown." << std::endl;
return -1;
}
}
// Validate command line args
if (args.inputImage.length() == 0 || args.outputImage.length() == 0)
{
Usage(argv[0]);
return EXIT_FAILURE;
}
int dims = itk::PeekAtImageDimension(args.inputImage);
if (dims != 2 && dims != 3)
{
std::cout << "Unsuported image dimension" << std::endl;
return EXIT_FAILURE;
}
int result;
switch (itk::PeekAtComponentType(args.inputImage))
{
case itk::ImageIOBase::UCHAR:
if (dims == 2)
{
result = DoMain<2, unsigned char>(args);
}
else
{
result = DoMain<3, unsigned char>(args);
}
break;
case itk::ImageIOBase::CHAR:
if (dims == 2)
{
result = DoMain<2, char>(args);
}
else
{
result = DoMain<3, char>(args);
}
break;
case itk::ImageIOBase::USHORT:
if (dims == 2)
{
result = DoMain<2, unsigned short>(args);
}
else
{
result = DoMain<3, unsigned short>(args);
}
break;
case itk::ImageIOBase::SHORT:
if (dims == 2)
{
result = DoMain<2, short>(args);
}
else
{
result = DoMain<3, short>(args);
}
break;
case itk::ImageIOBase::UINT:
if (dims == 2)
{
result = DoMain<2, unsigned int>(args);
}
else
{
result = DoMain<3, unsigned int>(args);
}
break;
case itk::ImageIOBase::INT:
if (dims == 2)
{
result = DoMain<2, int>(args);
}
else
{
result = DoMain<3, int>(args);
}
break;
case itk::ImageIOBase::ULONG:
if (dims == 2)
{
result = DoMain<2, unsigned long>(args);
}
else
{
result = DoMain<3, unsigned long>(args);
}
break;
case itk::ImageIOBase::LONG:
if (dims == 2)
{
result = DoMain<2, long>(args);
}
else
{
result = DoMain<3, long>(args);
}
break;
case itk::ImageIOBase::FLOAT:
if (dims == 2)
{
result = DoMain<2, float>(args);
}
else
{
result = DoMain<3, float>(args);
}
break;
case itk::ImageIOBase::DOUBLE:
if (dims == 2)
{
result = DoMain<2, double>(args);
}
else
{
result = DoMain<3, double>(args);
}
break;
default:
std::cerr << "non standard pixel format" << std::endl;
return EXIT_FAILURE;
}
return result;
}
| 26.487903 | 155 | 0.548942 | NifTK |
c1c4530a228a487cdcc58517d493942f7c9633b2 | 8,071 | hxx | C++ | include/idocp/contact_complementarity/contact_complementarity_component_base.hxx | KY-Lin22/idocp | 8cacfea7bb2184023eb15316aea07154a62d59bb | [
"BSD-3-Clause"
] | 1 | 2021-09-04T07:43:04.000Z | 2021-09-04T07:43:04.000Z | include/idocp/contact_complementarity/contact_complementarity_component_base.hxx | KY-Lin22/idocp | 8cacfea7bb2184023eb15316aea07154a62d59bb | [
"BSD-3-Clause"
] | null | null | null | include/idocp/contact_complementarity/contact_complementarity_component_base.hxx | KY-Lin22/idocp | 8cacfea7bb2184023eb15316aea07154a62d59bb | [
"BSD-3-Clause"
] | null | null | null | #ifndef IDOCP_CONTACT_COMPLEMENTARITY_COMPONENT_BASE_HXX_
#define IDOCP_CONTACT_COMPLEMENTARITY_COMPONENT_BASE_HXX_
#include "idocp/contact_complementarity/contact_complementarity_component_base.hpp"
#include "idocp/constraints/pdipm_func.hpp"
#include <cmath>
#include <exception>
#include <assert.h>
namespace idocp {
template <typename Derived>
inline ContactComplementarityComponentBase<Derived>::
ContactComplementarityComponentBase(const double barrier,
const double fraction_to_boundary_rate)
: barrier_(barrier),
fraction_to_boundary_rate_(fraction_to_boundary_rate) {
try {
if (barrier <= 0) {
throw std::out_of_range(
"invalid argment: barrirer must be positive");
}
if (fraction_to_boundary_rate <= 0) {
throw std::out_of_range(
"invalid argment: fraction_to_boundary_rate must be positive");
}
if (fraction_to_boundary_rate >= 1) {
throw std::out_of_range(
"invalid argment: fraction_to_boundary_rate must be less than 1");
}
}
catch(const std::exception& e) {
std::cerr << e.what() << '\n';
std::exit(EXIT_FAILURE);
}
}
template <typename Derived>
inline ContactComplementarityComponentBase<Derived>::
ContactComplementarityComponentBase()
: barrier_(0),
fraction_to_boundary_rate_(0) {
}
template <typename Derived>
inline ContactComplementarityComponentBase<Derived>::
~ContactComplementarityComponentBase() {
}
template <typename Derived>
inline bool ContactComplementarityComponentBase<Derived>::isFeasible(
Robot& robot, ConstraintComponentData& data,
const SplitSolution& s) const {
return static_cast<const Derived*>(this)->isFeasible_impl(robot, data, s);
}
template <typename Derived>
inline void ContactComplementarityComponentBase<Derived>::setSlackAndDual(
Robot& robot, ConstraintComponentData& data,
const double dtau, const SplitSolution& s) const {
static_cast<const Derived*>(this)->setSlackAndDual_impl(robot, data, dtau, s);
}
template <typename Derived>
inline void ContactComplementarityComponentBase<Derived>::augmentDualResidual(
Robot& robot, ConstraintComponentData& data, const double dtau,
const SplitSolution& s, KKTResidual& kkt_residual) {
static_cast<Derived*>(this)->augmentDualResidual_impl(robot, data, dtau,
s, kkt_residual);
}
template <typename Derived>
inline void ContactComplementarityComponentBase<Derived>::condenseSlackAndDual(
Robot& robot, ConstraintComponentData& data, const double dtau,
const SplitSolution& s, KKTMatrix& kkt_matrix, KKTResidual& kkt_residual) {
static_cast<const Derived*>(this)->condenseSlackAndDual_impl(robot, data, dtau,
s, kkt_matrix,
kkt_residual);
}
template <typename Derived>
inline void ContactComplementarityComponentBase<Derived>::
computeSlackAndDualDirection(Robot& robot, ConstraintComponentData& data,
const double dtau, const SplitSolution& s,
const SplitDirection& d) const {
static_cast<const Derived*>(this)->computeSlackAndDualDirection_impl(
robot, data, dtau, s, d);
}
template <typename Derived>
inline double ContactComplementarityComponentBase<Derived>::residualL1Nrom(
Robot& robot, ConstraintComponentData& data,
const double dtau, const SplitSolution& s) const {
return static_cast<const Derived*>(this)->residualL1Nrom_impl(
robot, data, dtau, s);
}
template <typename Derived>
inline double ContactComplementarityComponentBase<Derived>::squaredKKTErrorNorm(
Robot& robot, ConstraintComponentData& data, const double dtau,
const SplitSolution& s) const {
return static_cast<const Derived*>(this)->squaredKKTErrorNorm_impl(
robot, data, dtau, s);
}
template <typename Derived>
inline int ContactComplementarityComponentBase<Derived>::dimc() const {
return static_cast<const Derived*>(this)->dimc_impl();
}
template <typename Derived>
inline double ContactComplementarityComponentBase<Derived>::maxSlackStepSize(
const ConstraintComponentData& data,
const std::vector<bool>& is_contact_active) const {
return static_cast<const Derived*>(this)->maxSlackStepSize_impl(
data, is_contact_active);
}
template <typename Derived>
inline double ContactComplementarityComponentBase<Derived>::maxDualStepSize(
const ConstraintComponentData& data,
const std::vector<bool>& is_contact_active) const {
return static_cast<const Derived*>(this)->maxDualStepSize_impl(
data, is_contact_active);
}
template <typename Derived>
inline void ContactComplementarityComponentBase<Derived>::updateSlack(
ConstraintComponentData& data, const std::vector<bool>& is_contact_active,
const double step_size) const {
assert(step_size > 0);
static_cast<const Derived*>(this)->updateSlack_impl(data, is_contact_active,
step_size);
}
template <typename Derived>
inline void ContactComplementarityComponentBase<Derived>::updateDual(
ConstraintComponentData& data, const std::vector<bool>& is_contact_active,
const double step_size) const {
assert(step_size > 0);
static_cast<const Derived*>(this)->updateDual_impl(data, is_contact_active,
step_size);
}
template <typename Derived>
inline double ContactComplementarityComponentBase<Derived>::costSlackBarrier(
const ConstraintComponentData& data,
const std::vector<bool>& is_contact_active) const {
return static_cast<const Derived*>(this)->costSlackBarrier_impl(
data, is_contact_active);
}
template <typename Derived>
inline double ContactComplementarityComponentBase<Derived>::costSlackBarrier(
const ConstraintComponentData& data,
const std::vector<bool>& is_contact_active,
const double step_size) const {
return static_cast<const Derived*>(this)->costSlackBarrier_impl(
data, is_contact_active, step_size);
}
template <typename Derived>
inline void ContactComplementarityComponentBase<Derived>::setBarrier(
const double barrier) {
assert(barrier > 0);
barrier_ = barrier;
}
template <typename Derived>
inline void ContactComplementarityComponentBase<Derived>::
setFractionToBoundaryRate(const double fraction_to_boundary_rate) {
assert(fraction_to_boundary_rate > 0);
fraction_to_boundary_rate_ = fraction_to_boundary_rate;
}
template <typename Derived>
inline void ContactComplementarityComponentBase<Derived>::
setSlackAndDualPositive(Eigen::VectorXd& slack, Eigen::VectorXd& dual) const {
pdipmfunc::SetSlackAndDualPositive(barrier_, slack, dual);
}
template <typename Derived>
inline double ContactComplementarityComponentBase<Derived>::costSlackBarrier(
const double slack) const {
return - barrier_ * std::log(slack);
}
template <typename Derived>
inline double ContactComplementarityComponentBase<Derived>::costSlackBarrier(
const double slack, const double dslack, const double step_size) const {
return - barrier_ * std::log(slack + step_size * dslack);
}
template <typename Derived>
inline double ContactComplementarityComponentBase<Derived>::computeDuality(
const double slack, const double dual) const {
return pdipmfunc::ComputeDuality(barrier_, slack, dual);
}
template <typename Derived>
inline double ContactComplementarityComponentBase<Derived>::computeDualDirection(
const double slack, const double dual, const double dslack,
const double duality) const {
return pdipmfunc::ComputeDualDirection(slack, dual, dslack, duality);
}
template <typename Derived>
inline double ContactComplementarityComponentBase<Derived>::fractionToBoundary(
const double vec, const double dvec) const {
return pdipmfunc::FractionToBoundary(fraction_to_boundary_rate_, vec, dvec);
}
} // namespace idocp
#endif // IDOCP_CONTACT_COMPLEMENTARITY_COMPONENT_BASE_HXX_ | 33.629167 | 83 | 0.7408 | KY-Lin22 |
c1c5331af48793255435eb2125ebae830b901c86 | 1,248 | hpp | C++ | src/parser/__ast/ClassSymbol.hpp | shockazoid/HydroLanguage | 25071995477406245911989584cb3e6f036229c0 | [
"Apache-2.0"
] | null | null | null | src/parser/__ast/ClassSymbol.hpp | shockazoid/HydroLanguage | 25071995477406245911989584cb3e6f036229c0 | [
"Apache-2.0"
] | null | null | null | src/parser/__ast/ClassSymbol.hpp | shockazoid/HydroLanguage | 25071995477406245911989584cb3e6f036229c0 | [
"Apache-2.0"
] | null | null | null | //
// __ __ __
// / / / /__ __ ____/ /_____ ____
// / /_/ // / / // __ // ___// __ \
// / __ // /_/ // /_/ // / / /_/ /
// /_/ /_/ \__, / \__,_//_/ \____/
// /____/
//
// The Hydro Programming Language
//
// © 2020 Shockazoid, Inc. All Rights Reserved.
//
#ifndef __h3o_ClassSymbol__
#define __h3o_ClassSymbol__
#include <vector>
#include "TypeSpec.hpp"
#include "PackageSymbol.hpp"
namespace hydro
{
class ClassSymbol : public Symbol
{
private:
PackageSymbol *_package;
std::vector<TypeSpec *> _types;
public:
ClassSymbol(Modifier *modifier, Name *name, Scope *ownScope, PackageSymbol *package) : Symbol{modifier, name, ownScope, package}, _types{}, _package{package} {}
virtual ~ClassSymbol() {}
void append(TypeSpec *type) { _types.push_back(type); }
const std::vector<TypeSpec *> &types() const { return _types; }
PackageSymbol *package() const { return _package; }
std::string fullName() const { return _package ? _package->name()->value() + "::" + name()->value() : name()->value();
}
};
} // namespace hydro
#endif /* __h3o_ClassSymbol__ */
| 28.363636 | 164 | 0.552083 | shockazoid |
c1c6d3444305ee4a4f6864d58e43dfe263511d9b | 12,194 | cpp | C++ | src/bls-signatures/python-bindings/pythonbindings.cpp | blondfrogs/tecracoin | 8ede0a2f550a31e85634e2bf91b79bd1c9cfda7c | [
"MIT"
] | 159 | 2020-11-09T22:39:58.000Z | 2022-03-29T21:14:57.000Z | src/bls-signatures/python-bindings/pythonbindings.cpp | blondfrogs/tecracoin | 8ede0a2f550a31e85634e2bf91b79bd1c9cfda7c | [
"MIT"
] | 366 | 2015-01-08T05:10:17.000Z | 2022-03-07T02:30:03.000Z | src/bls-signatures/python-bindings/pythonbindings.cpp | blondfrogs/tecracoin | 8ede0a2f550a31e85634e2bf91b79bd1c9cfda7c | [
"MIT"
] | 110 | 2015-01-03T17:00:15.000Z | 2022-02-13T15:31:08.000Z | // Copyright 2018 Chia Network 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 <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/operators.h>
#include "../src/privatekey.hpp"
#include "../src/bls.hpp"
namespace py = pybind11;
using namespace bls;
PYBIND11_MODULE(blspy, m) {
py::class_<bn_t*>(m, "bn_ptr");
py::class_<AggregationInfo>(m, "AggregationInfo")
.def("from_msg_hash", [](const PublicKey &pk, const py::bytes &b) {
const uint8_t* input = reinterpret_cast<const uint8_t*>(&std::string(b)[0]);
return AggregationInfo::FromMsgHash(pk, input);
})
.def("from_msg", [](const PublicKey &pk, const py::bytes &b) {
const uint8_t* input = reinterpret_cast<const uint8_t*>(&std::string(b)[0]);
return AggregationInfo::FromMsg(pk, input, len(b));
})
.def("merge_infos", &AggregationInfo::MergeInfos)
.def("get_pubkeys", &AggregationInfo::GetPubKeys)
.def("get_msg_hashes", [](const AggregationInfo &self) {
std::vector<uint8_t*> msgHashes = self.GetMessageHashes();
std::vector<py::bytes> ret;
for (const uint8_t* msgHash : msgHashes) {
ret.push_back(py::bytes(reinterpret_cast<const char*>(msgHash), BLS::MESSAGE_HASH_LEN));
}
return ret;
})
.def(py::self == py::self)
.def(py::self != py::self)
.def(py::self < py::self)
.def("__repr__", [](const AggregationInfo &a) {
std::stringstream s;
s << a;
return "<AggregationInfo " + s.str() + ">";
});
py::class_<PrivateKey>(m, "PrivateKey")
.def_property_readonly_static("PRIVATE_KEY_SIZE", [](py::object self) {
return PrivateKey::PRIVATE_KEY_SIZE;
})
.def("from_seed", [](const py::bytes &b) {
const uint8_t* input = reinterpret_cast<const uint8_t*>(&std::string(b)[0]);
return PrivateKey::FromSeed(input, len(b));
})
.def("from_bytes", [](const py::bytes &b) {
const uint8_t* input = reinterpret_cast<const uint8_t*>(&std::string(b)[0]);
return PrivateKey::FromBytes(input);
})
.def("serialize", [](const PrivateKey &k) {
uint8_t* output = Util::SecAlloc<uint8_t>(PrivateKey::PRIVATE_KEY_SIZE);
k.Serialize(output);
py::bytes ret = py::bytes(reinterpret_cast<char*>(output), PrivateKey::PRIVATE_KEY_SIZE);
Util::SecFree(output);
return ret;
})
.def("get_public_key", [](const PrivateKey &k) {
return k.GetPublicKey();
})
.def("aggregate", &PrivateKey::Aggregate)
.def("sign", [](const PrivateKey &k, const py::bytes &msg) {
uint8_t* input = reinterpret_cast<uint8_t*>(&std::string(msg)[0]);
return k.Sign(input, len(msg));
})
.def("sign_prehashed", [](const PrivateKey &k, const py::bytes &msg) {
uint8_t* input = reinterpret_cast<uint8_t*>(&std::string(msg)[0]);
return k.SignPrehashed(input);
})
.def(py::self == py::self)
.def(py::self != py::self)
.def("__repr__", [](const PrivateKey &k) {
uint8_t* output = Util::SecAlloc<uint8_t>(PrivateKey::PRIVATE_KEY_SIZE);
k.Serialize(output);
std::string ret = "<PrivateKey " + Util::HexStr(output, PrivateKey::PRIVATE_KEY_SIZE) + ">";
Util::SecFree(output);
return ret;
});
py::class_<PublicKey>(m, "PublicKey")
.def_property_readonly_static("PUBLIC_KEY_SIZE", [](py::object self) {
return PublicKey::PUBLIC_KEY_SIZE;
})
.def("from_bytes", [](const py::bytes &b) {
const uint8_t* input = reinterpret_cast<const uint8_t*>(&std::string(b)[0]);
return PublicKey::FromBytes(input);
})
.def("aggregate", &PublicKey::Aggregate)
.def("get_fingerprint", &PublicKey::GetFingerprint)
.def("serialize", [](const PublicKey &pk) {
uint8_t* output = new uint8_t[PublicKey::PUBLIC_KEY_SIZE];
pk.Serialize(output);
py::bytes ret = py::bytes(reinterpret_cast<char*>(output), PublicKey::PUBLIC_KEY_SIZE);
delete[] output;
return ret;
})
.def(py::self == py::self)
.def(py::self != py::self)
.def("__repr__", [](const PublicKey &pk) {
std::stringstream s;
s << pk;
return "<PublicKey " + s.str() + ">";
});
py::class_<Signature>(m, "Signature")
.def_property_readonly_static("SIGNATURE_SIZE", [](py::object self) {
return Signature::SIGNATURE_SIZE;
})
.def("from_bytes", [](const py::bytes &b) {
const uint8_t* input = reinterpret_cast<const uint8_t*>(&std::string(b)[0]);
return Signature::FromBytes(input);
})
.def("serialize", [](const Signature &sig) {
uint8_t* output = new uint8_t[Signature::SIGNATURE_SIZE];
sig.Serialize(output);
py::bytes ret = py::bytes(reinterpret_cast<char*>(output), Signature::SIGNATURE_SIZE);
delete[] output;
return ret;
})
.def("verify", &Signature::Verify)
.def("aggregate", &Signature::AggregateSigs)
.def("divide_by", &Signature::DivideBy)
.def("set_aggregation_info", &Signature::SetAggregationInfo)
.def("get_aggregation_info", [](const Signature &sig) {
return *sig.GetAggregationInfo();
})
.def(py::self == py::self)
.def(py::self != py::self)
.def("__repr__", [](const Signature &sig) {
std::stringstream s;
s << sig;
return "<Signature " + s.str() + ">";
});
py::class_<ChainCode>(m, "ChainCode")
.def_property_readonly_static("CHAIN_CODE_KEY_SIZE", [](py::object self) {
return ChainCode::CHAIN_CODE_SIZE;
})
.def("from_bytes", [](const py::bytes &b) {
const uint8_t* input = reinterpret_cast<const uint8_t*>(&std::string(b)[0]);
return ChainCode::FromBytes(input);
})
.def("serialize", [](const ChainCode &cc) {
uint8_t* output = new uint8_t[ChainCode::CHAIN_CODE_SIZE];
cc.Serialize(output);
py::bytes ret = py::bytes(reinterpret_cast<char*>(output),
ChainCode::CHAIN_CODE_SIZE);
delete[] output;
return ret;
})
.def("__repr__", [](const ChainCode &cc) {
uint8_t* output = new uint8_t[ChainCode::CHAIN_CODE_SIZE];
cc.Serialize(output);
std::string ret = "<ChainCode " + Util::HexStr(output,
ChainCode::CHAIN_CODE_SIZE) + ">";
Util::SecFree(output);
return ret;
});
py::class_<ExtendedPublicKey>(m, "ExtendedPublicKey")
.def_property_readonly_static("EXTENDED_PUBLIC_KEY_SIZE", [](py::object self) {
return ExtendedPublicKey::EXTENDED_PUBLIC_KEY_SIZE;
})
.def("from_bytes", [](const py::bytes &b) {
const uint8_t* input = reinterpret_cast<const uint8_t*>(&std::string(b)[0]);
return ExtendedPublicKey::FromBytes(input);
})
.def("public_child", &ExtendedPublicKey::PublicChild)
.def("get_version", &ExtendedPublicKey::GetVersion)
.def("get_depth", &ExtendedPublicKey::GetDepth)
.def("get_parent_fingerprint", &ExtendedPublicKey::GetParentFingerprint)
.def("get_child_number", &ExtendedPublicKey::GetChildNumber)
.def("get_chain_code", &ExtendedPublicKey::GetChainCode)
.def("get_public_key", &ExtendedPublicKey::GetPublicKey)
.def(py::self == py::self)
.def(py::self != py::self)
.def("serialize", [](const ExtendedPublicKey &pk) {
uint8_t* output = new uint8_t[
ExtendedPublicKey::EXTENDED_PUBLIC_KEY_SIZE];
pk.Serialize(output);
py::bytes ret = py::bytes(reinterpret_cast<char*>(output),
ExtendedPublicKey::EXTENDED_PUBLIC_KEY_SIZE);
delete[] output;
return ret;
})
.def("__repr__", [](const ExtendedPublicKey &pk) {
uint8_t* output = new uint8_t[
ExtendedPublicKey::EXTENDED_PUBLIC_KEY_SIZE];
pk.Serialize(output);
std::string ret = "<ExtendedPublicKey " + Util::HexStr(output,
ExtendedPublicKey::EXTENDED_PUBLIC_KEY_SIZE) + ">";
Util::SecFree(output);
return ret;
});
py::class_<ExtendedPrivateKey>(m, "ExtendedPrivateKey")
.def_property_readonly_static("EXTENDED_PRIVATE_KEY_SIZE", [](py::object self) {
return ExtendedPrivateKey::EXTENDED_PRIVATE_KEY_SIZE;
})
.def("from_seed", [](const py::bytes &seed) {
const uint8_t* input = reinterpret_cast<const uint8_t*>(&std::string(seed)[0]);
return ExtendedPrivateKey::FromSeed(input, len(seed));
})
.def("from_bytes", [](const py::bytes &b) {
const uint8_t* input = reinterpret_cast<const uint8_t*>(&std::string(b)[0]);
return ExtendedPrivateKey::FromBytes(input);
})
.def("private_child", &ExtendedPrivateKey::PrivateChild)
.def("public_child", &ExtendedPrivateKey::PublicChild)
.def("get_version", &ExtendedPrivateKey::GetVersion)
.def("get_depth", &ExtendedPrivateKey::GetDepth)
.def("get_parent_fingerprint", &ExtendedPrivateKey::GetParentFingerprint)
.def("get_child_number", &ExtendedPrivateKey::GetChildNumber)
.def("get_chain_code", &ExtendedPrivateKey::GetChainCode)
.def("get_private_key", &ExtendedPrivateKey::GetPrivateKey)
.def("get_public_key", &ExtendedPrivateKey::GetPublicKey)
.def("get_extended_public_key", &ExtendedPrivateKey::GetExtendedPublicKey)
.def(py::self == py::self)
.def(py::self != py::self)
.def("serialize", [](const ExtendedPrivateKey &k) {
uint8_t* output = Util::SecAlloc<uint8_t>(
ExtendedPrivateKey::EXTENDED_PRIVATE_KEY_SIZE);
k.Serialize(output);
py::bytes ret = py::bytes(reinterpret_cast<char*>(output),
ExtendedPrivateKey::EXTENDED_PRIVATE_KEY_SIZE);
Util::SecFree(output);
return ret;
})
.def("__repr__", [](const ExtendedPrivateKey &k) {
uint8_t* output = Util::SecAlloc<uint8_t>(
ExtendedPrivateKey::EXTENDED_PRIVATE_KEY_SIZE);
k.Serialize(output);
std::string ret = "<ExtendedPrivateKey " + Util::HexStr(output,
ExtendedPrivateKey::EXTENDED_PRIVATE_KEY_SIZE) + ">";
Util::SecFree(output);
return ret;
});
py::class_<BLS>(m, "BLS")
.def_property_readonly_static("MESSAGE_HASH_LEN", [](py::object self) {
return BLS::MESSAGE_HASH_LEN;
});
py::class_<Util>(m, "Util")
.def("hash256", [](const py::bytes &message) {
const uint8_t* input = reinterpret_cast<const uint8_t*>(&std::string(message)[0]);
uint8_t output[BLS::MESSAGE_HASH_LEN];
Util::Hash256(output, input, len(message));
return py::bytes(reinterpret_cast<char*>(output), BLS::MESSAGE_HASH_LEN);
});
#ifdef VERSION_INFO
m.attr("__version__") = VERSION_INFO;
#else
m.attr("__version__") = "dev";
#endif
}
| 43.55 | 104 | 0.587994 | blondfrogs |
c1c86e247c906b2b7a04e1e853ada6172f61953d | 2,268 | hpp | C++ | libadb/include/libadb/api/guild/data/guild-features.hpp | faserg1/adb | 65507dc17589ac6ec00caf2ecd80f6dbc4026ad4 | [
"MIT"
] | 1 | 2022-03-10T15:14:13.000Z | 2022-03-10T15:14:13.000Z | libadb/include/libadb/api/guild/data/guild-features.hpp | faserg1/adb | 65507dc17589ac6ec00caf2ecd80f6dbc4026ad4 | [
"MIT"
] | 9 | 2022-03-07T21:00:08.000Z | 2022-03-15T23:14:52.000Z | libadb/include/libadb/api/guild/data/guild-features.hpp | faserg1/adb | 65507dc17589ac6ec00caf2ecd80f6dbc4026ad4 | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <libadb/libadb.hpp>
#include <cstdint>
namespace adb::api
{
enum class GuildFeature : uint64_t
{
UNKNOWN,
/// guild has access to set an animated guild banner image
ANIMATED_BANNER,
/// guild has access to set an animated guild icon
ANIMATED_ICON,
/// guild has access to set a guild banner image
BANNER,
/// guild has access to use commerce features (i.e. create store channels)
COMMERCE,
/// guild can enable welcome screen, Membership Screening, stage channels and discovery, and receives community updates
COMMUNITY,
/// guild is able to be discovered in the directory
DISCOVERABLE,
/// guild is able to be featured in the directory
FEATURABLE,
/// guild has access to set an invite splash background
INVITE_SPLASH,
/// guild has enabled Membership Screening
MEMBER_VERIFICATION_GATE_ENABLED,
/// guild has enabled monetization
MONETIZATION_ENABLED,
/// guild has increased custom sticker slots
MORE_STICKERS,
/// guild has access to create news channels
NEWS,
/// guild is partnered
PARTNERED,
/// guild can be previewed before joining via Membership Screening or the directory
PREVIEW_ENABLED,
/// guild has access to create private threads
PRIVATE_THREADS,
/// guild is able to set role icons
ROLE_ICONS,
/// guild has access to the seven day archive time for threads
SEVEN_DAY_THREAD_ARCHIVE,
/// guild has access to the three day archive time for threads
THREE_DAY_THREAD_ARCHIVE,
/// guild has enabled ticketed events
TICKETED_EVENTS_ENABLED,
/// guild has access to set a vanity URL
VANITY_URL,
/// guild is verified
VERIFIED,
/// guild has access to set 384kbps bitrate in voice (previously VIP voice servers)
VIP_REGIONS,
/// guild has enabled the welcome screen
WELCOME_SCREEN_ENABLED
};
LIBADB_API std::string to_string(GuildFeature e);
LIBADB_API void from_string(const std::string &str, GuildFeature &feature);
} | 36.580645 | 127 | 0.648148 | faserg1 |
c1ca71e0c6b81edbe0cdc1c6c725608a90716964 | 1,187 | cpp | C++ | Assignment2/components.cpp | bertptrs/uni-snacs | 07b99185781de2e956989c2ebd26e03d3e798d2e | [
"MIT"
] | null | null | null | Assignment2/components.cpp | bertptrs/uni-snacs | 07b99185781de2e956989c2ebd26e03d3e798d2e | [
"MIT"
] | null | null | null | Assignment2/components.cpp | bertptrs/uni-snacs | 07b99185781de2e956989c2ebd26e03d3e798d2e | [
"MIT"
] | null | null | null | #include "TwitterGraph.hpp"
#include <vector>
#include <iterator>
#include <algorithm>
int TwitterGraph::weakComponents()
{
int maxComponent = 0;
for (unsigned int i = 0; i < nodes.size(); i++)
{
if (nodes[i].componentID == NO_COMPONENT) {
const int currentComponent = maxComponent++;
bfs(i, [currentComponent, this] (int i) -> bool {
if (nodes[i].componentID == NO_COMPONENT) {
nodes[i].componentID = currentComponent;
return true;
} else if (nodes[i].componentID != currentComponent) {
recolor(nodes[i].componentID, currentComponent);
return false;
}
return false;
});
}
}
// Count the occurrernces for the different components.
vector<int> componentCounts(nodes.size(), 0);
for (const auto& node : nodes) {
componentCounts[node.componentID]++;
}
// Save the largest component ID and return the size.
const auto it = max_element(componentCounts.begin(), componentCounts.end());
giantComponentID = distance(componentCounts.begin(), it);
return giantComponentID;
}
void TwitterGraph::recolor(int original, int to)
{
for (auto& node : nodes)
{
if (node.componentID == original) {
node.componentID = to;
}
}
}
| 24.22449 | 77 | 0.680708 | bertptrs |
c1cc4c70ad3f9d721f5789909359aa35f9a06e12 | 12,805 | cpp | C++ | Engine/Source/Editor/PropertyEditor/Private/ItemPropertyNode.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | Engine/Source/Editor/PropertyEditor/Private/ItemPropertyNode.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | 2 | 2015-06-21T17:38:11.000Z | 2015-06-22T20:54:42.000Z | Engine/Source/Editor/PropertyEditor/Private/ItemPropertyNode.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#include "PropertyEditorPrivatePCH.h"
#include "PropertyNode.h"
#include "ItemPropertyNode.h"
#include "CategoryPropertyNode.h"
#include "ObjectPropertyNode.h"
FItemPropertyNode::FItemPropertyNode(void)
: FPropertyNode()
{
}
FItemPropertyNode::~FItemPropertyNode(void)
{
}
/**
* Calculates the memory address for the data associated with this item's property. This is typically the value of a UProperty or a UObject address.
*
* @param StartAddress the location to use as the starting point for the calculation; typically the address of the object that contains this property.
*
* @return a pointer to a UProperty value or UObject. (For dynamic arrays, you'd cast this value to an FArray*)
*/
uint8* FItemPropertyNode::GetValueBaseAddress( uint8* StartAddress )
{
UProperty* MyProperty = GetProperty();
if( MyProperty )
{
UArrayProperty* OuterArrayProp = Cast<UArrayProperty>(MyProperty->GetOuter());
if ( OuterArrayProp != NULL )
{
FScriptArrayHelper ArrayHelper(OuterArrayProp,ParentNode->GetValueBaseAddress(StartAddress));
if ( ParentNode->GetValueBaseAddress(StartAddress) != NULL && ArrayIndex < ArrayHelper.Num() )
{
return ArrayHelper.GetRawPtr() + ArrayOffset;
}
return NULL;
}
else
{
uint8* ValueAddress = ParentNode->GetValueAddress(StartAddress);
if (ValueAddress != NULL && ParentNode->GetProperty() != MyProperty)
{
// if this is not a fixed size array (in which the parent property and this property are the same), we need to offset from the property (otherwise, the parent already did that for us)
ValueAddress = Property->ContainerPtrToValuePtr<uint8>(ValueAddress);
}
if ( ValueAddress != NULL )
{
ValueAddress += ArrayOffset;
}
return ValueAddress;
}
}
return NULL;
}
/**
* Calculates the memory address for the data associated with this item's value. For most properties, identical to GetValueBaseAddress. For items corresponding
* to dynamic array elements, the pointer returned will be the location for that element's data.
*
* @param StartAddress the location to use as the starting point for the calculation; typically the address of the object that contains this property.
*
* @return a pointer to a UProperty value or UObject. (For dynamic arrays, you'd cast this value to whatever type is the Inner for the dynamic array)
*/
uint8* FItemPropertyNode::GetValueAddress( uint8* StartAddress )
{
uint8* Result = GetValueBaseAddress(StartAddress);
UProperty* MyProperty = GetProperty();
UArrayProperty* ArrayProperty;
if( Result != NULL && (ArrayProperty=Cast<UArrayProperty>(MyProperty))!=NULL )
{
FScriptArrayHelper ArrayHelper(ArrayProperty,Result);
Result = ArrayHelper.GetRawPtr();
}
return Result;
}
/**
* Overridden function for special setup
*/
void FItemPropertyNode::InitExpansionFlags (void)
{
UProperty* MyProperty = GetProperty();
FReadAddressList Addresses;
if( Cast<UStructProperty>(MyProperty)
|| ( Cast<UArrayProperty>(MyProperty) && GetReadAddress(false,Addresses) )
|| HasNodeFlags(EPropertyNodeFlags::EditInline)
|| ( Property->ArrayDim > 1 && ArrayIndex == -1 ) )
{
SetNodeFlags(EPropertyNodeFlags::CanBeExpanded, true);
}
}
/**
* Overridden function for Creating Child Nodes
*/
void FItemPropertyNode::InitChildNodes()
{
//NOTE - this is only turned off as to not invalidate child object nodes.
UProperty* Property = GetProperty();
UStructProperty* StructProperty = Cast<UStructProperty>(Property);
UArrayProperty* ArrayProperty = Cast<UArrayProperty>(Property);
UObjectPropertyBase* ObjectProperty = Cast<UObjectPropertyBase>(Property);
const bool bShouldShowHiddenProperties = !!HasNodeFlags(EPropertyNodeFlags::ShouldShowHiddenProperties);
const bool bShouldShowDisableEditOnInstance = !!HasNodeFlags(EPropertyNodeFlags::ShouldShowDisableEditOnInstance);
if( Property->ArrayDim > 1 && ArrayIndex == -1 )
{
// Do not add array children which are defined by an enum but the enum at the array index is hidden
// This only applies to static arrays
static const FName NAME_ArraySizeEnum("ArraySizeEnum");
UEnum* ArraySizeEnum = NULL;
if (Property->HasMetaData(NAME_ArraySizeEnum))
{
ArraySizeEnum = FindObject<UEnum>(NULL, *Property->GetMetaData(NAME_ArraySizeEnum));
}
// Expand array.
for( int32 ArrayIndex = 0 ; ArrayIndex < Property->ArrayDim ; ArrayIndex++ )
{
bool bShouldBeHidden = false;
if( ArraySizeEnum )
{
// The enum at this array index is hidden
bShouldBeHidden = ArraySizeEnum->HasMetaData(TEXT("Hidden"), ArrayIndex );
}
if( !bShouldBeHidden )
{
TSharedPtr<FItemPropertyNode> NewItemNode( new FItemPropertyNode);
FPropertyNodeInitParams InitParams;
InitParams.ParentNode = SharedThis(this);
InitParams.Property = Property;
InitParams.ArrayOffset = ArrayIndex*Property->ElementSize;
InitParams.ArrayIndex = ArrayIndex;
InitParams.bAllowChildren = true;
InitParams.bForceHiddenPropertyVisibility = bShouldShowHiddenProperties;
InitParams.bCreateDisableEditOnInstanceNodes = bShouldShowDisableEditOnInstance;
NewItemNode->InitNode( InitParams );
AddChildNode(NewItemNode);
}
}
}
else if( ArrayProperty )
{
void* Array = NULL;
FReadAddressList Addresses;
if ( GetReadAddress(!!HasNodeFlags(EPropertyNodeFlags::SingleSelectOnly), Addresses ) )
{
Array = Addresses.GetAddress(0);
}
if( Array )
{
for( int32 ArrayIndex = 0 ; ArrayIndex < FScriptArrayHelper::Num(Array) ; ArrayIndex++ )
{
TSharedPtr<FItemPropertyNode> NewItemNode( new FItemPropertyNode );
FPropertyNodeInitParams InitParams;
InitParams.ParentNode = SharedThis(this);
InitParams.Property = ArrayProperty->Inner;
InitParams.ArrayOffset = ArrayIndex*ArrayProperty->Inner->ElementSize;
InitParams.ArrayIndex = ArrayIndex;
InitParams.bAllowChildren = true;
InitParams.bForceHiddenPropertyVisibility = bShouldShowHiddenProperties;
InitParams.bCreateDisableEditOnInstanceNodes = bShouldShowDisableEditOnInstance;
NewItemNode->InitNode( InitParams );
AddChildNode(NewItemNode);
}
}
}
else if( StructProperty )
{
// Expand struct.
for( TFieldIterator<UProperty> It(StructProperty->Struct); It; ++It )
{
UProperty* StructMember = *It;
const bool bShowIfEditableProperty = StructMember->HasAnyPropertyFlags(CPF_Edit);
const bool bShowIfDisableEditOnInstance = !StructMember->HasAnyPropertyFlags(CPF_DisableEditOnInstance) || bShouldShowDisableEditOnInstance;
if (bShouldShowHiddenProperties || (bShowIfEditableProperty && bShowIfDisableEditOnInstance))
{
TSharedPtr<FItemPropertyNode> NewItemNode( new FItemPropertyNode );//;//CreatePropertyItem(StructMember,INDEX_NONE,this);
FPropertyNodeInitParams InitParams;
InitParams.ParentNode = SharedThis(this);
InitParams.Property = StructMember;
InitParams.ArrayOffset = 0;
InitParams.ArrayIndex = INDEX_NONE;
InitParams.bAllowChildren = true;
InitParams.bForceHiddenPropertyVisibility = bShouldShowHiddenProperties;
InitParams.bCreateDisableEditOnInstanceNodes = bShouldShowDisableEditOnInstance;
NewItemNode->InitNode( InitParams );
AddChildNode(NewItemNode);
if ( FPropertySettings::Get().ExpandDistributions() == false)
{
// auto-expand distribution structs
if ( Cast<UObjectProperty>(StructMember) || Cast<UWeakObjectProperty>(StructMember) || Cast<ULazyObjectProperty>(StructMember) || Cast<UAssetObjectProperty>(StructMember) )
{
const FName StructName = StructProperty->Struct->GetFName();
if (StructName == NAME_RawDistributionFloat || StructName == NAME_RawDistributionVector)
{
NewItemNode->SetNodeFlags(EPropertyNodeFlags::Expanded, true);
}
}
}
}
}
}
else if( ObjectProperty || Property->IsA(UInterfaceProperty::StaticClass()))
{
uint8* ReadValue = NULL;
FReadAddressList ReadAddresses;
if( GetReadAddress(!!HasNodeFlags(EPropertyNodeFlags::SingleSelectOnly), ReadAddresses, false ) )
{
// We've got some addresses, and we know they're all NULL or non-NULL.
// Have a peek at the first one, and only build an objects node if we've got addresses.
if( UObject* Obj = (ReadAddresses.Num() > 0) ? ObjectProperty->GetObjectPropertyValue(ReadAddresses.GetAddress(0)) : nullptr )
{
//verify it's not above in the hierarchy somewhere
FObjectPropertyNode* ParentObjectNode = FindObjectItemParent();
while (ParentObjectNode)
{
for ( TPropObjectIterator Itor( ParentObjectNode->ObjectIterator() ) ; Itor ; ++Itor )
{
if (*Itor == Obj)
{
SetNodeFlags(EPropertyNodeFlags::NoChildrenDueToCircularReference, true);
//stop the circular loop!!!
return;
}
}
FPropertyNode* UpwardTravesalNode = ParentObjectNode->GetParentNode();
ParentObjectNode = (UpwardTravesalNode==NULL) ? NULL : UpwardTravesalNode->FindObjectItemParent();
}
TSharedPtr<FObjectPropertyNode> NewObjectNode( new FObjectPropertyNode );
for ( int32 AddressIndex = 0 ; AddressIndex < ReadAddresses.Num() ; ++AddressIndex )
{
NewObjectNode->AddObject( ObjectProperty->GetObjectPropertyValue(ReadAddresses.GetAddress(AddressIndex) ) );
}
FPropertyNodeInitParams InitParams;
InitParams.ParentNode = SharedThis(this);
InitParams.Property = Property;
InitParams.ArrayOffset = 0;
InitParams.ArrayIndex = INDEX_NONE;
InitParams.bAllowChildren = true;
InitParams.bForceHiddenPropertyVisibility = bShouldShowHiddenProperties;
InitParams.bCreateDisableEditOnInstanceNodes = bShouldShowDisableEditOnInstance;
NewObjectNode->InitNode( InitParams );
AddChildNode(NewObjectNode);
}
}
}
}
void FItemPropertyNode::SetDisplayNameOverride( const FText& InDisplayNameOverride )
{
DisplayNameOverride = InDisplayNameOverride;
}
FText FItemPropertyNode::GetDisplayName() const
{
FText FinalDisplayName;
if( !DisplayNameOverride.IsEmpty() )
{
FinalDisplayName = DisplayNameOverride;
}
else
{
const UProperty* PropertyPtr = GetProperty();
if( GetArrayIndex()==-1 && PropertyPtr != NULL )
{
// This item is not a member of an array, get a traditional display name
if ( FPropertySettings::Get().ShowFriendlyPropertyNames() )
{
//We are in "readable display name mode"../ Make a nice name
FinalDisplayName = PropertyPtr->GetDisplayNameText();
if ( FinalDisplayName.IsEmpty() )
{
FString PropertyDisplayName;
bool bIsBoolProperty = Cast<const UBoolProperty>(PropertyPtr) != NULL;
const UStructProperty* ParentStructProperty = Cast<const UStructProperty>(ParentNode->GetProperty());
if( ParentStructProperty && ParentStructProperty->Struct->GetFName() == NAME_Rotator )
{
if( Property->GetFName() == "Roll" )
{
PropertyDisplayName = TEXT("X");
}
else if( Property->GetFName() == "Pitch" )
{
PropertyDisplayName = TEXT("Y");
}
else if( Property->GetFName() == "Yaw" )
{
PropertyDisplayName = TEXT("Z");
}
else
{
check(0);
}
}
else
{
PropertyDisplayName = Property->GetName();
}
if( GetDefault<UEditorStyleSettings>()->bShowFriendlyNames )
{
PropertyDisplayName = FName::NameToDisplayString( PropertyDisplayName, bIsBoolProperty );
}
FinalDisplayName = FText::FromString( PropertyDisplayName );
}
}
else
{
FinalDisplayName = FText::FromString( PropertyPtr->GetName() );
}
}
else
{
// Get the ArraySizeEnum class from meta data.
static const FName NAME_ArraySizeEnum("ArraySizeEnum");
UEnum* ArraySizeEnum = NULL;
if (PropertyPtr && PropertyPtr->HasMetaData(NAME_ArraySizeEnum))
{
ArraySizeEnum = FindObject<UEnum>(NULL, *Property->GetMetaData(NAME_ArraySizeEnum));
}
// This item is a member of an array, its display name is its index
if ( PropertyPtr == NULL || ArraySizeEnum == NULL )
{
FinalDisplayName = FText::AsNumber( GetArrayIndex() );
}
else
{
FString TempDisplayName = ArraySizeEnum->GetEnumName(GetArrayIndex());
//fixup the display name if we have displayname metadata
AdjustEnumPropDisplayName(ArraySizeEnum, TempDisplayName);
FinalDisplayName = FText::FromString(TempDisplayName); // todo: should this be using ArraySizeEnum->GetEnumText?
}
}
}
return FinalDisplayName;
}
void FItemPropertyNode::SetToolTipOverride( const FText& InToolTipOverride )
{
ToolTipOverride = InToolTipOverride;
}
FText FItemPropertyNode::GetToolTipText() const
{
if(!ToolTipOverride.IsEmpty())
{
return ToolTipOverride;
}
return PropertyEditorHelpers::GetToolTipText(GetProperty());
}
| 33.697368 | 187 | 0.728622 | PopCap |
c1cce410996db859dcd794148ec3017312a5f179 | 23,362 | cc | C++ | ash/services/ime/public/cpp/rulebased/def/ml_phone.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | ash/services/ime/public/cpp/rulebased/def/ml_phone.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | ash/services/ime/public/cpp/rulebased/def/ml_phone.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2018 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 "ash/services/ime/public/cpp/rulebased/def/ml_phone.h"
#include "base/cxx17_backports.h"
namespace ml_phone {
const char* kId = "ml_phone";
bool kIs102 = false;
const char* kTransforms[] = {
u8"\\\\([a-zA-Z0-9@$])",
u8"\\1",
u8"([a-zA-Z])\u001d([a-zA-Z0-9`~!@#$%^&*()_=+:;\"',<.>?/|\\-])",
u8"\\1\\2",
u8"\\\\(ch)",
u8"\\1",
u8"([a-zA-Z])\u001d(ch)",
u8"\\1\\2",
u8"(M|\u001d?_M|\u0d02\u001d?m)",
u8"\u0d2e\u0d4d\u0d2e\u0d4d",
u8"([\u0d03-\u0d0a\u0d0c-\u0d4c\u0d4e-\u0d79])\u001d?R",
u8"\\1\u0d7c",
u8"([\u0d02-\u0d4c\u0d4e-\u0d79])\u001d?~",
u8"\\1\u0d4d",
u8"([\u0d02-\u0d4c\u0d4e-\u0d7f])\u0d7b\u001d?j",
u8"\\1\u0d1e\u0d4d\u0d1e\u0d4d",
u8"([\u0d15-\u0d3a])\u001d?a",
u8"\\1\u0d3e",
u8"([\u0d15-\u0d3a])\u001d?i",
u8"\\1\u0d48",
u8"([\u0d15-\u0d3a])\u001d?u",
u8"\\1\u0d57",
u8"([\u0d66-\u0d6f])\u001d?0",
u8"\\1\u0d66",
u8"([\u0d66-\u0d6f])\u001d?1",
u8"\\1\u0d67",
u8"([\u0d66-\u0d6f])\u001d?2",
u8"\\1\u0d68",
u8"([\u0d66-\u0d6f])\u001d?3",
u8"\\1\u0d69",
u8"([\u0d66-\u0d6f])\u001d?4",
u8"\\1\u0d6a",
u8"([\u0d66-\u0d6f])\u001d?5",
u8"\\1\u0d6b",
u8"([\u0d66-\u0d6f])\u001d?6",
u8"\\1\u0d6c",
u8"([\u0d66-\u0d6f])\u001d?7",
u8"\\1\u0d6d",
u8"([\u0d66-\u0d6f])\u001d?8",
u8"\\1\u0d6e",
u8"([\u0d66-\u0d6f])\u001d?9",
u8"\\1\u0d6f",
u8"([wv]|\u001d?_[wv])",
u8"\u0d35\u0d4d",
u8"(\u001d?R|\u0d0b\u001d?)A",
u8"\u0d31\u0d3e",
u8"(\u001d?R|\u0d0b\u001d?)E",
u8"\u0d31\u0d47",
u8"(\u001d?R|\u0d0b\u001d?)I",
u8"\u0d31\u0d40",
u8"(\u001d?R|\u0d0b\u001d?)U",
u8"\u0d31\u0d42",
u8"(\u001d?R|\u0d0b\u001d?)a",
u8"\u0d31",
u8"(\u001d?R|\u0d0b\u001d?)e",
u8"\u0d31\u0d46",
u8"(\u001d?R|\u0d0b\u001d?)i",
u8"\u0d31\u0d3f",
u8"(\u001d?R|\u0d0b\u001d?)u",
u8"\u0d31\u0d41",
u8"(\u001d?_)?B",
u8"\u0d2c\u0d4d\u0d2c\u0d4d",
u8"(\u001d?_)?D",
u8"\u0d21\u0d4d",
u8"(\u001d?_)?G",
u8"\u0d17\u0d4d\u0d17\u0d4d",
u8"(\u001d?_)?J",
u8"\u0d1c\u0d4d\u0d1c\u0d4d",
u8"(\u001d?_)?K",
u8"\u0d15\u0d4d\u0d15\u0d4d",
u8"(\u001d?_)?P",
u8"\u0d2a\u0d4d\u0d2a\u0d4d",
u8"(\u001d?_)?Y",
u8"\u0d2f\u0d4d\u0d2f\u0d4d",
u8"(\u001d?_)?Z",
u8"\u0d34\u0d4d",
u8"(\u001d?_)?T",
u8"\u0d1f\u0d4d",
u8"(\u001d?_)?[Sz]",
u8"\u0d36\u0d4d",
u8"(\u001d?_)?[VW]",
u8"\u0d35\u0d4d\u0d35\u0d4d",
u8"(\u001d?_)?[Cc]",
u8"\u0d1a\u0d4d",
u8"(\u001d?_)?[Xx]",
u8"\u0d15\u0d4d\u0d38\u0d4d",
u8"(\u001d?_)?b",
u8"\u0d2c\u0d4d",
u8"(\u001d?_)?d",
u8"\u0d26\u0d4d",
u8"(\u001d?_)?g",
u8"\u0d17\u0d4d",
u8"(\u001d?_)?h",
u8"\u0d39\u0d4d",
u8"(\u001d?_)?j",
u8"\u0d1c\u0d4d",
u8"(\u001d?_)?p",
u8"\u0d2a\u0d4d",
u8"(\u001d?_)?s",
u8"\u0d38\u0d4d",
u8"(\u001d?_)?y",
u8"\u0d2f\u0d4d",
u8"(\u0d05\u001d?a|_?A)",
u8"\u0d06",
u8"(\u0d07\u001d?i|\u0d0e\u001d?a|_?I|[\u0d0e\u0d07]\u001d?e)",
u8"\u0d08",
u8"(\u0d09\u001d?u|\u0d12\u001d?o|_?U)",
u8"\u0d0a",
u8"(\u0d0b\u001d?|\u001d?R)O",
u8"\u0d31\u0d4b",
u8"(\u0d0b\u001d?|\u001d?R)o",
u8"\u0d31\u0d4a",
u8"(\u0d0b\u001d?|\u001d?R)~",
u8"\u0d31\u0d4d",
u8"(\u0d15\u0d4d\u001d?h|\u001d?_[qQ]|[qQ])",
u8"\u0d16\u0d4d",
u8"(\u0d15\u0d4d|\u0d7f)\u001d?\\^",
u8"\u0d15\u0d4d\u200d",
u8"(\u0d1f\u0d4d\u001d?t|\u0d31\u0d4d\u0d31\u0d4d\u001d?[tT])",
u8"\u0d1f\u0d4d\u0d1f\u0d4d",
u8"(\u0d28\u0d4d\u001d?T|\u0d7a\u001d?[Tt])",
u8"\u0d23\u0d4d\u0d1f\u0d4d",
u8"(\u0d23\u0d4d\u001d?t|\u0d7b\u001d?T)",
u8"\u0d23\u0d4d\u0d1f\u0d4d",
u8"(\u0d23\u0d4d|\u0d7a)\u001d?\\^",
u8"\u0d23\u0d4d\u200d",
u8"(\u0d28\u0d4d\u001d?ch?|\u0d7b\u001d?ch?)",
u8"\u0d1e\u0d4d\u0d1a\u0d4d",
u8"(\u0d28\u0d4d|\u0d7b)\u001d?k",
u8"\u0d19\u0d4d\u0d15\u0d4d",
u8"(\u0d2a\u0d4d\u001d?h|\u001d?_[Ff]|[Ff])",
u8"\u0d2b\u0d4d",
u8"(\u0d30\u0d4d|\u0d7c)\u001d?\\^",
u8"\u0d30\u0d4d\u200d",
u8"(\u0d30\u0d4d|\u0d7c)\u001d?r",
u8"\u0d31\u0d4d",
u8"(\u0d4b\u0d3e*)\u001d?O",
u8"\\1\u0d3e",
u8"(\u0d4d\u001d?I|\u0d46\u001d?[ea]|\u0d3f\u001d?[ie])",
u8"\u0d40",
u8"(\u0d4d\u001d?U|\u0d41\u001d?u|\u0d4a\u001d?o)",
u8"\u0d42",
u8"(\u0d4d\u0d05|\u0d46)\u001d?i",
u8"\u0d48",
u8"(\u0d4d\u0d05|\u0d4a)\u001d?u",
u8"\u0d57",
u8"(\u0d7b|\u0d28\u0d4d)\u001d?\\^",
u8"\u0d28\u0d4d\u200d",
u8"(\u0d7b|\u0d28\u0d4d)\u001d?t",
u8"\u0d28\u0d4d\u0d31\u0d4d",
u8"(\u0d7d\u001d?L|\u0d7e\u001d?[lL])",
u8"\u0d33\u0d4d\u0d33\u0d4d",
u8"(\u0d7d|\u0d32\u0d4d)\u001d?\\^",
u8"\u0d32\u0d4d\u200d",
u8"(\u0d7e|\u0d33\u0d4d)\u001d?\\^",
u8"\u0d33\u0d4d\u200d",
u8"(k|\u001d?_[kc])",
u8"\u0d15\u0d4d",
u8"(\u0d7c\u001d?~|\u001d?_r)",
u8"\u0d30\u0d4d",
u8"(\u0d7e\u001d?~|\u001d?_L)",
u8"\u0d33\u0d4d",
u8"(\u0d7d\u001d?~|\u001d?_l)",
u8"\u0d32\u0d4d",
u8"(\u0d7a\u001d?~|\u001d?_N)",
u8"\u0d23\u0d4d",
u8"(\u0d7b\u001d?~|\u001d?_n)",
u8"\u0d28\u0d4d",
u8"(\u0d02\u001d?~|\u001d?_m)",
u8"\u0d2e\u0d4d",
u8"0#",
u8"\u0d66",
u8"1#",
u8"\u0d67",
u8"1/2#",
u8"\u0d74",
u8"1/4#",
u8"\u0d73",
u8"10#",
u8"\u0d70",
u8"100#",
u8"\u0d71",
u8"1000#",
u8"\u0d72",
u8"2#",
u8"\u0d68",
u8"3#",
u8"\u0d69",
u8"3/4#",
u8"\u0d75",
u8"4#",
u8"\u0d6a",
u8"5#",
u8"\u0d6b",
u8"6#",
u8"\u0d6c",
u8"7#",
u8"\u0d6d",
u8"8#",
u8"\u0d6e",
u8"9#",
u8"\u0d6f",
u8"@",
u8"\u0d4d",
u8"@a",
u8"\u0d4d\u0d05",
u8"@aL",
u8"\u0d7e",
u8"@aN",
u8"\u0d7a",
u8"@aa",
u8"\u0d3e",
u8"@ai",
u8"\u0d48",
u8"@al",
u8"\u0d7d",
u8"@am",
u8"\u0d02",
u8"@an",
u8"\u0d7b",
u8"@ar",
u8"\u0d7c",
u8"@au",
u8"\u0d57",
u8"C",
u8"\u0d1a\u0d4d\u0d1a\u0d4d",
u8"H",
u8"\u0d03",
u8"[\u0d05\u0d0e]\u001d?i",
u8"\u0d10",
u8"[\u0d05\u0d12]\u001d?u",
u8"\u0d14",
u8"\\$",
u8"\u20b9",
u8"\u001d?_X",
u8"\u0d15\u0d4d\u0d37\u0d4d",
u8"\u0d02\u001d?A",
u8"\u0d2e\u0d3e",
u8"\u0d02\u001d?E",
u8"\u0d2e\u0d47",
u8"\u0d02\u001d?I",
u8"\u0d2e\u0d40",
u8"\u0d02\u001d?O",
u8"\u0d2e\u0d4b",
u8"\u0d02\u001d?U",
u8"\u0d2e\u0d42",
u8"\u0d02\u001d?[Ll]",
u8"\u0d2e\u0d4d\u0d32\u0d4d",
u8"\u0d02\u001d?a",
u8"\u0d2e",
u8"\u0d02\u001d?e",
u8"\u0d2e\u0d46",
u8"\u0d02\u001d?i",
u8"\u0d2e\u0d3f",
u8"\u0d02\u001d?n",
u8"\u0d2e\u0d4d\u0d28\u0d4d",
u8"\u0d02\u001d?o",
u8"\u0d2e\u0d4a",
u8"\u0d02\u001d?p",
u8"\u0d2e\u0d4d\u0d2a\u0d4d",
u8"\u0d02\u001d?r",
u8"\u0d2e\u0d4d\u0d30\u0d4d",
u8"\u0d02\u001d?R",
u8"\u0d2e\u0d43",
u8"\u0d02\u001d?u",
u8"\u0d2e\u0d41",
u8"\u0d02\u001d?y",
u8"\u0d2e\u0d4d\u0d2f\u0d4d",
u8"\u0d05\u001d?#",
u8"\u0d3d",
u8"\u0d06\u001d?[Aa]",
u8"\u0d06\u0d3e",
u8"\u0d08\u001d?#",
u8"\u0d5f",
u8"\u0d08\u001d?[eiI]",
u8"\u0d08\u0d57",
u8"\u0d0a\u001d?[uoU]",
u8"\u0d0a\u0d57",
u8"\u0d0b\u0d0b\u001d?#",
u8"\u0d60",
u8"\u0d0c\u001d?L",
u8"\u0d61",
u8"\u0d13\u001d?O",
u8"\u0d13\u0d3e",
u8"\u0d14\u001d?u",
u8"\u0d14\u0d57",
u8"\u0d15\u0d4d\u001d?#",
u8"\u0d7f",
u8"\u0d17\u0d4d\u001d?h",
u8"\u0d18\u0d4d",
u8"\u0d1a\u0d4d\u001d?h",
u8"\u0d1b\u0d4d",
u8"\u0d1c\u0d4d\u001d?h",
u8"\u0d1d\u0d4d",
u8"\u0d1e\u0d4d\u0d1e\u0d4d\u001d?ch",
u8"\u0d1e\u0d4d\u0d1a\u0d4d",
u8"\u0d1e\u0d4d\u0d1e\u0d4d\u001d?j",
u8"\u0d1e\u0d4d\u0d1c\u0d4d",
u8"\u0d1e\u0d4d\u0d1e\u0d4d\u0d28\u0d4d\u001d?j",
u8"\u0d1e\u0d4d\u0d1e\u0d4d",
u8"\u0d1e\u0d4d\u0d1e\u0d4d\u0d7b\u001d?j",
u8"\u0d1e\u0d4d\u0d1e\u0d4d",
u8"\u0d1e\u0d4d\u0d28\u0d4d\u001d?j",
u8"\u0d1e\u0d4d\u0d1e\u0d4d",
u8"\u0d1f\u0d4d\u001d?h",
u8"\u0d20\u0d4d",
u8"\u0d1f\u0d4d\u0d1f\u0d4d\u001d?h",
u8"\u0d24\u0d4d\u0d24\u0d4d",
u8"\u0d21\u0d4d\u001d?h",
u8"\u0d22\u0d4d",
u8"\u0d23\u0d4d\u0d1f\u0d4d\u001d?T",
u8"\u0d7a\u0d1f\u0d4d\u0d1f\u0d4d",
u8"\u0d23\u0d4d\u0d21\u0d4d\u001d?D",
u8"\u0d7a\u0d21\u0d4d\u0d21\u0d4d",
u8"\u0d23\u0d4d\u0d26\u0d4d\u001d?d",
u8"\u0d7a\u0d26\u0d4d\u0d26\u0d4d",
u8"\u0d23\u0d4d\u0d28\u0d4d\u001d?n",
u8"\u0d7a\u0d28\u0d4d\u0d28\u0d4d",
u8"\u0d23\u0d4d\u0d2a\u0d4d\u001d?p",
u8"\u0d7a\u0d2a\u0d4d\u0d2a\u0d4d",
u8"\u0d23\u0d4d\u0d2e\u0d4d\u001d?m",
u8"\u0d7a\u0d2e\u0d4d\u0d2e\u0d4d",
u8"\u0d23\u0d4d\u0d2f\u0d4d\u001d?y",
u8"\u0d7a\u0d2f\u0d4d\u0d2f\u0d4d",
u8"\u0d23\u0d4d\u0d32\u0d4d\u001d?l",
u8"\u0d7a\u0d32\u0d4d\u0d32\u0d4d",
u8"\u0d23\u0d4d\u0d33\u0d4d\u001d?L",
u8"\u0d7a\u0d33\u0d4d\u0d33\u0d4d",
u8"\u0d23\u0d4d\u0d35\u0d4d\u001d?v",
u8"\u0d7a\u0d35\u0d4d\u0d35\u0d4d",
u8"\u0d24\u0d4d\u001d?h",
u8"\u0d25\u0d4d",
u8"\u0d24\u0d4d\u0d24\u0d4d\u001d?h",
u8"\u0d24\u0d4d\u0d25\u0d4d",
u8"\u0d26\u0d4d\u001d?h",
u8"\u0d27\u0d4d",
u8"\u0d28\u0d41\u001d?#",
u8"\u0d79",
u8"\u0d28\u0d4d\u001d?#",
u8"\u0d29\u0d4d",
u8"\u0d28\u001d?#",
u8"\u0d29",
u8"\u0d28\u0d4d\u001d?g",
u8"\u0d19\u0d4d",
u8"\u0d7b\u001d?j",
u8"\u0d1e\u0d4d",
u8"\u0d28\u0d4d\u0d1f\u0d4d\u001d?T",
u8"\u0d7b\u0d1f\u0d4d\u0d1f\u0d4d",
u8"\u0d28\u0d4d\u0d21\u0d4d\u001d?D",
u8"\u0d7b\u0d21\u0d4d\u0d21\u0d4d",
u8"\u0d28\u0d4d\u0d26\u0d4d\u001d?d",
u8"\u0d7b\u0d26\u0d4d\u0d26\u0d4d",
u8"\u0d28\u0d4d\u0d28\u0d4d\u001d?n",
u8"\u0d7b\u0d28\u0d4d\u0d28\u0d4d",
u8"\u0d28\u0d4d\u0d2a\u0d4d\u001d?p",
u8"\u0d7b\u0d2a\u0d4d\u0d2a\u0d4d",
u8"\u0d28\u0d4d\u0d2e\u0d4d\u001d?m",
u8"\u0d7b\u0d2e\u0d4d\u0d2e\u0d4d",
u8"\u0d28\u0d4d\u0d2f\u0d4d\u001d?y",
u8"\u0d7b\u0d2f\u0d4d\u0d2f\u0d4d",
u8"\u0d28\u0d4d\u0d30\u0d4d\u001d?r",
u8"\u0d7b\u0d31\u0d4d",
u8"\u0d28\u0d4d\u0d31\u0d4d\u001d?h",
u8"\u0d28\u0d4d\u0d24\u0d4d",
u8"\u0d28\u0d4d\u0d32\u0d4d\u001d?l",
u8"\u0d7b\u0d32\u0d4d\u0d32\u0d4d",
u8"\u0d28\u0d4d\u0d33\u0d4d\u001d?L",
u8"\u0d7b\u0d33\u0d4d\u0d33\u0d4d",
u8"\u0d28\u0d4d\u0d35\u0d4d\u001d?v",
u8"\u0d7b\u0d35\u0d4d\u0d35\u0d4d",
u8"\u0d2c\u0d4d\u001d?h",
u8"\u0d2d\u0d4d",
u8"\u0d2e\u0d4d\u0d1f\u0d4d\u001d?T",
u8"\u0d02\u0d1f\u0d4d\u0d1f\u0d4d",
u8"\u0d2e\u0d4d\u0d21\u0d4d\u001d?D",
u8"\u0d02\u0d21\u0d4d\u0d21\u0d4d",
u8"\u0d2e\u0d4d\u0d26\u0d4d\u001d?d",
u8"\u0d02\u0d26\u0d4d\u0d26\u0d4d",
u8"\u0d2e\u0d4d\u0d28\u0d4d\u001d?n",
u8"\u0d02\u0d28\u0d4d\u0d28\u0d4d",
u8"\u0d2e\u0d4d\u0d2a\u0d4d\u001d?p",
u8"\u0d02\u0d2a\u0d4d\u0d2a\u0d4d",
u8"\u0d2e\u0d4d\u0d2e\u0d4d\u001d?m",
u8"\u0d02\u0d2e\u0d4d\u0d2e\u0d4d",
u8"\u0d2e\u0d4d\u0d2f\u0d4d\u001d?y",
u8"\u0d02\u0d2f\u0d4d\u0d2f\u0d4d",
u8"\u0d2e\u0d4d\u0d32\u0d4d\u001d?l",
u8"\u0d02\u0d32\u0d4d\u0d32\u0d4d",
u8"\u0d2e\u0d4d\u0d33\u0d4d\u001d?L",
u8"\u0d02\u0d33\u0d4d\u0d33\u0d4d",
u8"\u0d2e\u0d4d\u0d35\u0d4d\u001d?v",
u8"\u0d02\u0d35\u0d4d\u0d35\u0d4d",
u8"\u0d30\u0d4d\u0d1f\u0d4d\u001d?T",
u8"\u0d7c\u0d1f\u0d4d\u0d1f\u0d4d",
u8"\u0d30\u0d4d\u0d21\u0d4d\u001d?D",
u8"\u0d7c\u0d21\u0d4d\u0d21\u0d4d",
u8"\u0d30\u0d4d\u0d26\u0d4d\u001d?d",
u8"\u0d7c\u0d26\u0d4d\u0d26\u0d4d",
u8"\u0d30\u0d4d\u0d28\u0d4d\u001d?n",
u8"\u0d7c\u0d28\u0d4d\u0d28\u0d4d",
u8"\u0d30\u0d4d\u0d2a\u0d4d\u001d?p",
u8"\u0d7c\u0d2a\u0d4d\u0d2a\u0d4d",
u8"\u0d30\u0d4d\u0d2e\u0d4d\u001d?m",
u8"\u0d7c\u0d2e\u0d4d\u0d2e\u0d4d",
u8"\u0d30\u0d4d\u0d2f\u0d4d\u001d?y",
u8"\u0d7c\u0d2f\u0d4d\u0d2f\u0d4d",
u8"\u0d30\u0d4d\u0d32\u0d4d\u001d?l",
u8"\u0d7c\u0d32\u0d4d\u0d32\u0d4d",
u8"\u0d30\u0d4d\u0d33\u0d4d\u001d?L",
u8"\u0d7c\u0d33\u0d4d\u0d33\u0d4d",
u8"\u0d30\u0d4d\u0d35\u0d4d\u001d?v",
u8"\u0d7c\u0d35\u0d4d\u0d35\u0d4d",
u8"\u0d31\u0d4d\u0d31\u0d4d\u001d?#",
u8"\u0d3a\u0d4d",
u8"\u0d31\u0d4d\u0d31\u001d?#",
u8"\u0d3a",
u8"\u0d31\u0d4d\u0d31\u0d4d\u001d?h",
u8"\u0d24\u0d4d",
u8"\u0d32\u0d4d\u0d1f\u0d4d\u001d?T",
u8"\u0d7d\u0d1f\u0d4d\u0d1f\u0d4d",
u8"\u0d32\u0d4d\u0d21\u0d4d\u001d?D",
u8"\u0d7d\u0d21\u0d4d\u0d21\u0d4d",
u8"\u0d32\u0d4d\u0d26\u0d4d\u001d?d",
u8"\u0d7d\u0d26\u0d4d\u0d26\u0d4d",
u8"\u0d32\u0d4d\u0d28\u0d4d\u001d?n",
u8"\u0d7d\u0d28\u0d4d\u0d28\u0d4d",
u8"\u0d32\u0d4d\u0d2a\u0d4d\u001d?p",
u8"\u0d7d\u0d2a\u0d4d\u0d2a\u0d4d",
u8"\u0d32\u0d4d\u0d2e\u0d4d\u001d?m",
u8"\u0d7d\u0d2e\u0d4d\u0d2e\u0d4d",
u8"\u0d32\u0d4d\u0d2f\u0d4d\u001d?y",
u8"\u0d7d\u0d2f\u0d4d\u0d2f\u0d4d",
u8"\u0d32\u0d4d\u0d32\u0d4d\u001d?l",
u8"\u0d7d\u0d32\u0d4d\u0d32\u0d4d",
u8"\u0d32\u0d4d\u0d33\u0d4d\u001d?L",
u8"\u0d7d\u0d33\u0d4d\u0d33\u0d4d",
u8"\u0d32\u0d4d\u0d35\u0d4d\u001d?v",
u8"\u0d7d\u0d35\u0d4d\u0d35\u0d4d",
u8"\u0d33\u0d4d\u001d?#",
u8"\u0d0c",
u8"\u0d33\u0d4d\u001d?L",
u8"\u0d33\u0d4d\u0d33\u0d4d",
u8"\u0d33\u0d4d\u0d1f\u0d4d\u001d?T",
u8"\u0d7e\u0d1f\u0d4d\u0d1f\u0d4d",
u8"\u0d33\u0d4d\u0d21\u0d4d\u001d?D",
u8"\u0d7e\u0d21\u0d4d\u0d21\u0d4d",
u8"\u0d33\u0d4d\u0d26\u0d4d\u001d?d",
u8"\u0d7e\u0d26\u0d4d\u0d26\u0d4d",
u8"\u0d33\u0d4d\u0d28\u0d4d\u001d?n",
u8"\u0d7e\u0d28\u0d4d\u0d28\u0d4d",
u8"\u0d33\u0d4d\u0d2a\u0d4d\u001d?p",
u8"\u0d7e\u0d2a\u0d4d\u0d2a\u0d4d",
u8"\u0d33\u0d4d\u0d2e\u0d4d\u001d?m",
u8"\u0d7e\u0d2e\u0d4d\u0d2e\u0d4d",
u8"\u0d33\u0d4d\u0d2f\u0d4d\u001d?y",
u8"\u0d7e\u0d2f\u0d4d\u0d2f\u0d4d",
u8"\u0d33\u0d4d\u0d32\u0d4d\u001d?l",
u8"\u0d7e\u0d32\u0d4d\u0d32\u0d4d",
u8"\u0d33\u0d4d\u0d33\u0d4d\u001d?L",
u8"\u0d7e\u0d33\u0d4d\u0d33\u0d4d",
u8"\u0d33\u0d4d\u0d33\u0d4d\u001d?#",
u8"\u0d61",
u8"\u0d33\u0d4d\u0d35\u0d4d\u001d?v",
u8"\u0d7e\u0d35\u0d4d\u0d35\u0d4d",
u8"\u0d36\u0d4d\u001d?h",
u8"\u0d34\u0d4d",
u8"\u0d38\u0d02\u001d?r",
u8"\u0d38\u0d02\u0d7c",
u8"\u0d38\u0d02\u001d?y",
u8"\u0d38\u0d02\u0d2f\u0d4d",
u8"\u0d38\u0d4d\u001d?h",
u8"\u0d37\u0d4d",
u8"\u0d3e\u001d?[Aa]",
u8"\u0d3e\u0d3e",
u8"\u0d40\u001d?[eiI]",
u8"\u0d40\u0d40",
u8"\u0d42\u001d?[uoU]",
u8"\u0d42\u0d42",
u8"\u0d43\u001d?R",
u8"\u0d43\u0d7c",
u8"\u0d43\u0d7c\u001d?#",
u8"\u0d44",
u8"\u0d4c\u001d?u",
u8"\u0d4c\u0d57",
u8"\u0d4d(\u001d?A|\u0d05\u001d?a)",
u8"\u0d3e",
u8"\u0d4d[\u0d33\u0d32]\u0d4d\u001d?#",
u8"\u0d62",
u8"\u0d4d[\u0d33\u0d32]\u0d4d[\u0d33\u0d32]\u0d4d\u001d?#",
u8"\u0d63",
u8"\u0d4d\u001d?E",
u8"\u0d47",
u8"\u0d4d\u001d?L",
u8"\u0d4d\u0d32\u0d4d",
u8"\u0d4d\u001d?O",
u8"\u0d4b",
u8"\u0d4d\u001d?R",
u8"\u0d43",
u8"\u0d4d\u001d?RA",
u8"\u0d4d\u0d30\u0d3e",
u8"\u0d4d\u001d?RE",
u8"\u0d4d\u0d30\u0d47",
u8"\u0d4d\u001d?RI",
u8"\u0d4d\u0d30\u0d40",
u8"\u0d4d\u001d?RO",
u8"\u0d4d\u0d30\u0d4b",
u8"\u0d4d\u001d?RU",
u8"\u0d4d\u0d30\u0d42",
u8"\u0d4d\u001d?Ra",
u8"\u0d4d\u0d30",
u8"\u0d4d\u001d?Re",
u8"\u0d4d\u0d30\u0d46",
u8"\u0d4d\u001d?Ri",
u8"\u0d4d\u0d30\u0d3f",
u8"\u0d4d\u001d?Ro",
u8"\u0d4d\u0d30\u0d4a",
u8"\u0d4d\u001d?Ru",
u8"\u0d4d\u0d30\u0d41",
u8"\u0d4d\u001d?R~",
u8"\u0d4d\u0d30\u0d4d",
u8"\u0d4d\u001d?_B",
u8"\u0d4d\u200c\u0d2c\u0d4d\u0d2c\u0d4d",
u8"\u0d4d\u001d?_C",
u8"\u0d4d\u200c\u0d1a\u0d4d",
u8"\u0d4d\u001d?_G",
u8"\u0d4d\u200c\u0d17\u0d4d\u0d17\u0d4d",
u8"\u0d4d\u001d?_J",
u8"\u0d4d\u200c\u0d1c\u0d4d\u0d1c\u0d4d",
u8"\u0d4d\u001d?_K",
u8"\u0d4d\u200c\u0d15\u0d4d\u0d15\u0d4d",
u8"\u0d4d\u001d?_N",
u8"\u0d4d\u200c\u0d23\u0d4d",
u8"\u0d4d\u001d?_Z",
u8"\u0d4d\u200c\u0d36\u0d4d\u0d36\u0d4d",
u8"\u0d4d\u001d?_b",
u8"\u0d4d\u200c\u0d2c\u0d4d",
u8"\u0d4d\u001d?_g",
u8"\u0d4d\u200c\u0d17\u0d4d",
u8"\u0d4d\u001d?_j",
u8"\u0d4d\u200c\u0d1c\u0d4d",
u8"\u0d4d\u001d?_n",
u8"\u0d4d\u200c\u0d28\u0d4d",
u8"\u0d4d\u001d?_r",
u8"\u0d4d\u200c\u0d30\u0d4d",
u8"\u0d4d\u001d?_s",
u8"\u0d4d\u200c\u0d38\u0d4d",
u8"\u0d4d\u001d?_T",
u8"\u0d4d\u200c\u0d1f\u0d4d",
u8"\u0d4d\u001d?_t",
u8"\u0d4d\u200c\u0d31\u0d4d\u0d31\u0d4d",
u8"\u0d4d\u001d?_D",
u8"\u0d4d\u200c\u0d21\u0d4d",
u8"\u0d4d\u001d?_L",
u8"\u0d4d\u200c\u0d33\u0d4d",
u8"\u0d4d\u001d?_M",
u8"\u0d4d\u200c\u0d2e\u0d4d\u0d2e\u0d4d",
u8"\u0d4d\u001d?_P",
u8"\u0d4d\u200c\u0d2a\u0d4d\u0d2a\u0d4d",
u8"\u0d4d\u001d?_X",
u8"\u0d4d\u200c\u0d15\u0d4d\u0d37\u0d4d",
u8"\u0d4d\u001d?_Y",
u8"\u0d4d\u200c\u0d2f\u0d4d\u0d2f\u0d4d",
u8"\u0d4d\u001d?_d",
u8"\u0d4d\u200c\u0d26\u0d4d",
u8"\u0d4d\u001d?_h",
u8"\u0d4d\u200c\u0d39\u0d4d",
u8"\u0d4d\u001d?_l",
u8"\u0d4d\u200c\u0d32\u0d4d",
u8"\u0d4d\u001d?_m",
u8"\u0d4d\u200c\u0d2e\u0d4d",
u8"\u0d4d\u001d?_p",
u8"\u0d4d\u200c\u0d2a\u0d4d",
u8"\u0d4d\u001d?_x",
u8"\u0d4d\u200c\u0d15\u0d4d\u0d38\u0d4d",
u8"\u0d4d\u001d?_y",
u8"\u0d4d\u200c\u0d2f\u0d4d",
u8"\u0d4d\u001d?_[kc]",
u8"\u0d4d\u200c\u0d15\u0d4d",
u8"\u0d4d\u001d?_[qQ]",
u8"\u0d4d\u200c\u0d16\u0d4d",
u8"\u0d4d\u001d?_[fF]",
u8"\u0d4d\u200c\u0d2b\u0d4d",
u8"\u0d4d\u001d?_[VW]",
u8"\u0d4d\u200c\u0d35\u0d4d\u0d35\u0d4d",
u8"\u0d4d\u001d?_[vw]",
u8"\u0d4d\u200c\u0d35\u0d4d",
u8"\u0d4d\u001d?_[zS]",
u8"\u0d4d\u200c\u0d36\u0d4d",
u8"\u0d33\u0d4d\u001d?_",
u8"\u0d7e",
u8"\u0d23\u0d4d\u001d?_",
u8"\u0d7a",
u8"\u0d32\u0d4d\u001d?_",
u8"\u0d7d",
u8"\u0d2e\u0d4d\u001d?_",
u8"\u0d02",
u8"\u0d28\u0d4d\u001d?_",
u8"\u0d7b",
u8"\u0d30\u0d4d\u001d?_",
u8"\u0d7c",
u8"\u0d4d\u001d?a",
u8"",
u8"\u0d4d\u001d?e",
u8"\u0d46",
u8"\u0d4d\u001d?i",
u8"\u0d3f",
u8"\u0d4d\u001d?o",
u8"\u0d4a",
u8"\u0d4d\u001d?u",
u8"\u0d41",
u8"\u0d4d\u001d?~",
u8"\u0d4d",
u8"\u0d4d\u001d?~A",
u8"\u0d4d\u0d06",
u8"\u0d4d\u001d?~E",
u8"\u0d4d\u0d0f",
u8"\u0d4d\u001d?~I",
u8"\u0d4d\u0d08",
u8"\u0d4d\u001d?~O",
u8"\u0d4d\u0d13",
u8"\u0d4d\u001d?~R",
u8"\u0d4d\u0d0b",
u8"\u0d4d\u001d?~U",
u8"\u0d4d\u0d0a",
u8"\u0d4d\u001d?~a",
u8"\u0d4d\u0d05",
u8"\u0d4d\u001d?~e",
u8"\u0d4d\u0d0e",
u8"\u0d4d\u001d?~i",
u8"\u0d4d\u0d07",
u8"\u0d4d\u001d?~o",
u8"\u0d4d\u0d12",
u8"\u0d4d\u001d?~u",
u8"\u0d4d\u0d09",
u8"\u0d57\u001d?#",
u8"\u0d4c",
u8"\u0d57\u001d?[uieIuUou]",
u8"\u0d57\u0d57",
u8"\u0d7a\u001d?A",
u8"\u0d23\u0d3e",
u8"\u0d7a\u001d?D",
u8"\u0d23\u0d4d\u0d21\u0d4d",
u8"\u0d7a\u001d?E",
u8"\u0d23\u0d47",
u8"\u0d7a\u001d?I",
u8"\u0d23\u0d40",
u8"\u0d7a\u001d?N",
u8"\u0d23\u0d4d\u0d23\u0d4d",
u8"\u0d7a\u001d?O",
u8"\u0d23\u0d4b",
u8"\u0d7a\u001d?U",
u8"\u0d23\u0d42",
u8"\u0d7a\u001d?a",
u8"\u0d23",
u8"\u0d7a\u001d?e",
u8"\u0d23\u0d46",
u8"\u0d7a\u001d?i",
u8"\u0d23\u0d3f",
u8"\u0d7a\u001d?m",
u8"\u0d23\u0d4d\u0d2e\u0d4d",
u8"\u0d7a\u001d?o",
u8"\u0d23\u0d4a",
u8"\u0d7a\u001d?R",
u8"\u0d23\u0d43",
u8"\u0d7a\u001d?u",
u8"\u0d23\u0d41",
u8"\u0d7a\u001d?v",
u8"\u0d23\u0d4d\u0d35\u0d4d",
u8"\u0d7a\u001d?y",
u8"\u0d23\u0d4d\u0d2f\u0d4d",
u8"\u0d7b\u001d?A",
u8"\u0d28\u0d3e",
u8"\u0d7b\u001d?E",
u8"\u0d28\u0d47",
u8"\u0d7b\u001d?I",
u8"\u0d28\u0d40",
u8"\u0d7b\u001d?O",
u8"\u0d28\u0d4b",
u8"\u0d7b\u001d?U",
u8"\u0d28\u0d42",
u8"\u0d7b\u001d?a",
u8"\u0d28",
u8"\u0d7b\u001d?d",
u8"\u0d28\u0d4d\u0d26\u0d4d",
u8"\u0d7b\u001d?e",
u8"\u0d28\u0d46",
u8"\u0d7b\u001d?g",
u8"\u0d19\u0d4d",
u8"\u0d7b\u001d?i",
u8"\u0d28\u0d3f",
u8"\u0d7b\u001d?m",
u8"\u0d28\u0d4d\u0d2e\u0d4d",
u8"\u0d7b\u001d?n",
u8"\u0d28\u0d4d\u0d28\u0d4d",
u8"\u0d7b\u001d?o",
u8"\u0d28\u0d4a",
u8"\u0d7b\u001d?r",
u8"\u0d28\u0d4d\u0d30\u0d4d",
u8"\u0d7b\u001d?R",
u8"\u0d28\u0d43",
u8"\u0d7b\u001d?u",
u8"\u0d28\u0d41",
u8"\u0d7b\u001d?v",
u8"\u0d28\u0d4d\u0d35\u0d4d",
u8"\u0d7b\u001d?y",
u8"\u0d28\u0d4d\u0d2f\u0d4d",
u8"\u0d7c\u001d?#",
u8"\u0d4e",
u8"\u0d7c\u001d?A",
u8"\u0d30\u0d3e",
u8"\u0d7c\u001d?E",
u8"\u0d30\u0d47",
u8"\u0d7c\u001d?I",
u8"\u0d30\u0d40",
u8"\u0d7c\u001d?O",
u8"\u0d30\u0d4b",
u8"\u0d7c\u001d?U",
u8"\u0d30\u0d42",
u8"\u0d7c\u001d?a",
u8"\u0d30",
u8"\u0d7c\u001d?e",
u8"\u0d30\u0d46",
u8"\u0d7c\u001d?i",
u8"\u0d30\u0d3f",
u8"\u0d7c\u001d?o",
u8"\u0d30\u0d4a",
u8"\u0d7c\u001d?R",
u8"\u0d30\u0d43",
u8"\u0d7c\u001d?u",
u8"\u0d30\u0d41",
u8"\u0d7c\u001d?y",
u8"\u0d30\u0d4d\u0d2f\u0d4d",
u8"\u0d7d\u001d?A",
u8"\u0d32\u0d3e",
u8"\u0d7d\u001d?E",
u8"\u0d32\u0d47",
u8"\u0d7d\u001d?I",
u8"\u0d32\u0d40",
u8"\u0d7d\u001d?O",
u8"\u0d32\u0d4b",
u8"\u0d7d\u001d?U",
u8"\u0d32\u0d42",
u8"\u0d7d\u001d?[lL]",
u8"\u0d32\u0d4d\u0d32\u0d4d",
u8"\u0d7d\u001d?a",
u8"\u0d32",
u8"\u0d7d\u001d?e",
u8"\u0d32\u0d46",
u8"\u0d7d\u001d?i",
u8"\u0d32\u0d3f",
u8"\u0d7d\u001d?m",
u8"\u0d32\u0d4d\u0d2e\u0d4d",
u8"\u0d7d\u001d?o",
u8"\u0d32\u0d4a",
u8"\u0d7d\u001d?p",
u8"\u0d32\u0d4d\u0d2a\u0d4d",
u8"\u0d7d\u001d?R",
u8"\u0d32\u0d43",
u8"\u0d7d\u001d?u",
u8"\u0d32\u0d41",
u8"\u0d7d\u001d?v",
u8"\u0d32\u0d4d\u0d35\u0d4d",
u8"\u0d7d\u001d?y",
u8"\u0d32\u0d4d\u0d2f\u0d4d",
u8"\u0d7e\u001d?A",
u8"\u0d33\u0d3e",
u8"\u0d7e\u001d?E",
u8"\u0d33\u0d47",
u8"\u0d7e\u001d?I",
u8"\u0d33\u0d40",
u8"\u0d7e\u001d?O",
u8"\u0d33\u0d4b",
u8"\u0d7e\u001d?U",
u8"\u0d33\u0d42",
u8"\u0d7e\u001d?a",
u8"\u0d33",
u8"\u0d7e\u001d?e",
u8"\u0d33\u0d46",
u8"\u0d7e\u001d?i",
u8"\u0d33\u0d3f",
u8"\u0d7e\u001d?o",
u8"\u0d33\u0d4a",
u8"\u0d7e\u001d?R",
u8"\u0d33\u0d43",
u8"\u0d7e\u001d?u",
u8"\u0d33\u0d41",
u8"\u0d7e\u001d?y",
u8"\u0d33\u0d4d\u0d2f\u0d4d",
u8"_?E",
u8"\u0d0f",
u8"_?O",
u8"\u0d13",
u8"_?R",
u8"\u0d0b",
u8"_?a",
u8"\u0d05",
u8"_?e",
u8"\u0d0e",
u8"_?i",
u8"\u0d07",
u8"_?o",
u8"\u0d12",
u8"_?u",
u8"\u0d09",
u8"cch",
u8"\u0d1a\u0d4d\u0d1a\u0d4d",
u8"cchh",
u8"\u0d1a\u0d4d\u0d1b\u0d4d",
u8"ch",
u8"\u0d1a\u0d4d",
u8"t",
u8"\u0d31\u0d4d\u0d31\u0d4d",
u8"L",
u8"\u0d7e",
u8"N",
u8"\u0d7a",
u8"l",
u8"\u0d7d",
u8"m",
u8"\u0d02",
u8"n",
u8"\u0d7b",
u8"r",
u8"\u0d7c"};
const unsigned int kTransformsLen = base::size(kTransforms);
const char* kHistoryPrune = "a|@|@a|c|R|_|~";
} // namespace ml_phone
| 27.745843 | 73 | 0.577476 | zealoussnow |
c1cd2d1fa8ea050fe57df86849a68b839f990fce | 465 | hpp | C++ | lib/c_Homie/c_homie.hpp | Christian-Me/homie-firmware | ea43546e763b7cf08a0393cd2bdcdea297a6462e | [
"Apache-2.0"
] | 3 | 2021-01-03T02:38:55.000Z | 2021-01-05T20:18:09.000Z | lib/c_Homie/c_homie.hpp | Christian-Me/homie-firmware | ea43546e763b7cf08a0393cd2bdcdea297a6462e | [
"Apache-2.0"
] | null | null | null | lib/c_Homie/c_homie.hpp | Christian-Me/homie-firmware | ea43546e763b7cf08a0393cd2bdcdea297a6462e | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "Arduino.h"
#include <Homie.h>
// #include "homieSyslog.h"
// #include "datatypes.h"
#include "homie_property.hpp"
#include "homie_node.hpp"
#include "homie_device.hpp"
bool globalInputHandler(const HomieNode& node, const HomieRange& range, const String& property, const String& value);
void onHomieEvent(const HomieEvent& event);
void homieParameterSet(const __FlashStringHelper *nodeId, const __FlashStringHelper *parameterId, bool state); | 35.769231 | 117 | 0.787097 | Christian-Me |
c1cf903d7f5e461b255265f82f593fdd96415556 | 150 | cpp | C++ | Language Specific Notes/C Language Notes/String/6. Basic String Scanning Way 3.cpp | sayanmondal31/dev_stage | 0e52eb90ef71ee2a2c631720e38b0d36fe73e626 | [
"MIT"
] | 1 | 2020-10-22T18:48:16.000Z | 2020-10-22T18:48:16.000Z | Language Specific Notes/C Language Notes/String/6. Basic String Scanning Way 3.cpp | debajyatibanerjee0002/dev_stage | 2d853de917f574353f200b040427e8572e00d140 | [
"MIT"
] | 4 | 2020-10-17T16:30:38.000Z | 2020-10-19T10:18:48.000Z | Language Specific Notes/C Language Notes/String/6. Basic String Scanning Way 3.cpp | debajyatibanerjee0002/dev_stage | 2d853de917f574353f200b040427e8572e00d140 | [
"MIT"
] | 3 | 2020-10-17T12:40:21.000Z | 2020-10-18T16:26:39.000Z | #include<stdio.h>
int main(){
char name[20];
printf("Enter your name:-");
scanf("%[^\n]s", name);
printf("Hello Mr. %s",name);
return 0;
}
| 12.5 | 29 | 0.566667 | sayanmondal31 |
c1d0e9b8c0fa7e1fac552721151019790254a8e0 | 12,917 | cpp | C++ | esp/chips/ulp/assembler/ulp_assembler.cpp | kermitdafrog8/REDasm-Loaders | b401849f9aa54dfd9562aed1a6d2e03f75ac455f | [
"MIT"
] | 4 | 2019-06-09T10:22:28.000Z | 2022-02-12T13:11:43.000Z | esp/chips/ulp/assembler/ulp_assembler.cpp | kermitdafrog8/REDasm-Loaders | b401849f9aa54dfd9562aed1a6d2e03f75ac455f | [
"MIT"
] | 1 | 2019-07-15T13:55:31.000Z | 2022-01-10T08:06:31.000Z | esp/chips/ulp/assembler/ulp_assembler.cpp | kermitdafrog8/REDasm-Loaders | b401849f9aa54dfd9562aed1a6d2e03f75ac455f | [
"MIT"
] | 2 | 2020-10-11T13:13:46.000Z | 2021-09-10T22:35:04.000Z | #include "ulp_assembler.h"
#include "ulp_constants.h"
#define WORDS_TO_ADDR(instr) (instr) * sizeof(ULPInstruction)
std::array<const char*, 7> ULPAssembler::ALUSEL = {
"add", "sub", "and", "or", "move", "lsh", "rsh"
};
bool ULPAssembler::decode(const RDBufferView* view, ULPInstruction* ulpinstr)
{
if(!ulpinstr || (view->size < sizeof(ULPInstruction))) return false;
ulpinstr->data = RD_FromLittleEndian32(*reinterpret_cast<u32*>(view->data));
return true;
}
void ULPAssembler::renderInstruction(RDContext*, const RDRendererParams* rp)
{
ULPInstruction ulpinstr;
if(!ULPAssembler::decode(&rp->view, &ulpinstr)) return;
switch(ulpinstr.unk.opcode)
{
case ULP_OP_ALU: ULPAssembler::renderAlu(&ulpinstr, rp); break;
case ULP_OP_STORE: ULPAssembler::renderStore(&ulpinstr, rp); break;
case ULP_OP_LOAD: ULPAssembler::renderLoad(&ulpinstr, rp); break;
case ULP_OP_JUMP: ULPAssembler::renderJmp(&ulpinstr, rp); break;
case ULP_OP_HALT: RDRenderer_Mnemonic(rp->renderer, "halt", Theme_Ret); break;
case ULP_OP_WAKESLEEP: ULPAssembler::renderWakeSleep(&ulpinstr, rp); break;
case ULP_OP_WAIT: ULPAssembler::renderWait(&ulpinstr, rp); break;
case ULP_OP_TSENS: ULPAssembler::renderTSens(&ulpinstr, rp); break;
case ULP_OP_ADC: ULPAssembler::renderAdc(&ulpinstr, rp); break;
case ULP_OP_I2C: ULPAssembler::renderI2C(&ulpinstr, rp); break;
case ULP_OP_REGRD: ULPAssembler::renderRegRD(&ulpinstr, rp); break;
case ULP_OP_REGWR: ULPAssembler::renderRegWR(&ulpinstr, rp); break;
default: RDRenderer_Unknown(rp->renderer); break;
}
}
void ULPAssembler::emulate(RDContext*, RDEmulateResult* result)
{
ULPInstruction ulpinstr;
if(!ULPAssembler::decode(RDEmulateResult_GetView(result), &ulpinstr)) return;
RDEmulateResult_SetSize(result, sizeof(ULPInstruction));
switch(ulpinstr.unk.opcode)
{
case ULP_OP_JUMP: ULPAssembler::emulateJmp(&ulpinstr, result); break;
case ULP_OP_HALT: RDEmulateResult_AddReturn(result); break;
default: break;
}
}
std::string ULPAssembler::regName(u8 reg) { return "r" + std::to_string(reg); }
void ULPAssembler::emulateJmp(const ULPInstruction* ulpinstr, RDEmulateResult* result)
{
rd_address address = RDEmulateResult_GetAddress(result);
switch(ulpinstr->unk.choice)
{
case 0: {
if(!ulpinstr->jump.sel) {
if(ulpinstr->jump.type) RDEmulateResult_AddBranchTrue(result, ulpinstr->jump.addr);
else RDEmulateResult_AddBranch(result, WORDS_TO_ADDR(ulpinstr->jump.addr));
}
else RDEmulateResult_AddBranchIndirect(result);
if(ulpinstr->jump.type) RDEmulateResult_AddBranchFalse(result, address + sizeof(ULPInstruction));
break;
}
case 1:
case 2: {
rd_address relative = WORDS_TO_ADDR(ulpinstr->jumpr.step & 0x7F);
int sign = ulpinstr->jumpr.step & 0x80 ? -1 : +1;
RDEmulateResult_AddBranchTrue(result, address + sign * relative);
RDEmulateResult_AddBranchFalse(result, address + sizeof(ULPInstruction));
break;
}
default: break;
}
}
void ULPAssembler::renderAlu(const ULPInstruction* ulpinstr, const RDRendererParams* rp)
{
switch(ulpinstr->unk.choice)
{
case 0: ULPAssembler::renderAluReg(ulpinstr, rp); break;
case 1: ULPAssembler::renderAluImm(ulpinstr, rp); break;
case 2: ULPAssembler::renderAluStage(ulpinstr, rp); break;
default: break;
}
}
void ULPAssembler::renderAluReg(const ULPInstruction* ulpinstr, const RDRendererParams* rp)
{
RDRenderer_MnemonicWord(rp->renderer, ALUSEL[ulpinstr->alureg.sel], Theme_Default);
RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->alureg.rdst).c_str());
RDRenderer_Text(rp->renderer, ", ");
RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->alureg.rsrc1).c_str());
if(ulpinstr->alureg.sel == ALU_SEL_MOVE) return;
RDRenderer_Text(rp->renderer, ", ");
RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->alureg.rsrc2).c_str());
}
void ULPAssembler::renderAluImm(const ULPInstruction* ulpinstr, const RDRendererParams* rp)
{
RDRenderer_MnemonicWord(rp->renderer, ALUSEL[ulpinstr->aluimm.sel], Theme_Default);
RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->aluimm.rdst).c_str());
if(ulpinstr->aluimm.sel != ALU_SEL_MOVE)
{
RDRenderer_Text(rp->renderer, ", ");
RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->aluimm.rsrc1).c_str());
}
RDRenderer_Text(rp->renderer, ", ");
RDRenderer_Unsigned(rp->renderer, ulpinstr->aluimm.imm);
}
void ULPAssembler::renderAluStage(const ULPInstruction* ulpinstr, const RDRendererParams* rp)
{
static std::array<const char*, 3> STAgeSEL = {
"stage_inc", "stage_dec", "stage_rst"
};
RDRenderer_MnemonicWord(rp->renderer, STAgeSEL[ulpinstr->alustage.sel], Theme_Default);
if(ulpinstr->alustage.sel == 2) return;
RDRenderer_Unsigned(rp->renderer, ulpinstr->alustage.imm);
}
void ULPAssembler::renderJmp(const ULPInstruction* ulpinstr, const RDRendererParams* rp)
{
switch(ulpinstr->unk.choice)
{
case 0: {
RDRenderer_MnemonicWord(rp->renderer, "jump", ulpinstr->jump.type ? Theme_JumpCond : Theme_Jump);
if(ulpinstr->jump.sel) RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->jump.rdest).c_str());
else RDRenderer_Reference(rp->renderer, WORDS_TO_ADDR(ulpinstr->jump.addr));
if(ulpinstr->jump.type) {
RDRenderer_Text(rp->renderer, ", ");
if(ulpinstr->jump.type == 1) RDRenderer_Text(rp->renderer, "eq");
else if(ulpinstr->jump.type == 2) RDRenderer_Text(rp->renderer, "ov");
}
break;
}
case 1: {
rd_address relative = WORDS_TO_ADDR(ulpinstr->jumpr.step & 0x7F);
int sign = ulpinstr->jumpr.step & 0x80 ? -1 : +1;
RDRenderer_MnemonicWord(rp->renderer, "jumpr", Theme_JumpCond);
RDRenderer_Reference(rp->renderer, rp->address + sign * relative);
RDRenderer_Text(rp->renderer, ", ");
RDRenderer_Unsigned(rp->renderer, ulpinstr->jumps.thres);
RDRenderer_Text(rp->renderer, ", ");
RDRenderer_Text(rp->renderer, ulpinstr->jumpr.cond ? "ge" : "lt");
break;
}
case 2: {
rd_address relative = WORDS_TO_ADDR(ulpinstr->jumps.step & 0x7F);
int sign = ulpinstr->jumps.step & 0x80 ? -1 : +1;
RDRenderer_MnemonicWord(rp->renderer, "jumps", Theme_JumpCond);
RDRenderer_Unsigned(rp->renderer, rp->address + (sign * relative));
RDRenderer_Text(rp->renderer, ", ");
RDRenderer_Unsigned(rp->renderer, ulpinstr->jumps.thres);
RDRenderer_Text(rp->renderer, ", ");
if(ulpinstr->jumps.cond == 0) RDRenderer_Text(rp->renderer, "lt");
else if(ulpinstr->jumps.cond == 1) RDRenderer_Text(rp->renderer, "gt");
else RDRenderer_Text(rp->renderer, "eq");
break;
}
default: break;
}
}
void ULPAssembler::renderWakeSleep(const ULPInstruction* ulpinstr, const RDRendererParams* rp)
{
if(ulpinstr->wakesleep.wakeorsleep)
{
RDRenderer_MnemonicWord(rp->renderer, "sleep", Theme_Default);
RDRenderer_Unsigned(rp->renderer, ulpinstr->wakesleep.reg);
}
else
RDRenderer_Mnemonic(rp->renderer, "wake", Theme_Default);
}
void ULPAssembler::renderWait(const ULPInstruction* ulpinstr, const RDRendererParams* rp)
{
if(ulpinstr->wait.cycles)
{
RDRenderer_MnemonicWord(rp->renderer, "wait", Theme_Default);
RDRenderer_Unsigned(rp->renderer, ulpinstr->wait.cycles);
}
else
RDRenderer_Mnemonic(rp->renderer, "nop", Theme_Nop);
}
void ULPAssembler::renderTSens(const ULPInstruction* ulpinstr, const RDRendererParams* rp)
{
RDRenderer_MnemonicWord(rp->renderer, "tsens", Theme_Default);
RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->tsens.rdst).c_str());
RDRenderer_Text(rp->renderer, ", ");
RDRenderer_Unsigned(rp->renderer, ulpinstr->tsens.delay);
}
void ULPAssembler::renderAdc(const ULPInstruction* ulpinstr, const RDRendererParams* rp)
{
RDRenderer_MnemonicWord(rp->renderer, "adc", Theme_Default);
RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->adc.rdst).c_str());
RDRenderer_Text(rp->renderer, ", ");
RDRenderer_Unsigned(rp->renderer, ulpinstr->adc.sel);
RDRenderer_Text(rp->renderer, ", ");
RDRenderer_Unsigned(rp->renderer, ulpinstr->adc.sarmux);
}
void ULPAssembler::renderI2C(const ULPInstruction* ulpinstr, const RDRendererParams* rp)
{
if(ulpinstr->i2c.rw)
{
RDRenderer_MnemonicWord(rp->renderer, "i2c_wr", Theme_Default);
RDRenderer_Unsigned(rp->renderer, ulpinstr->i2c.subaddr);
RDRenderer_Text(rp->renderer, ", ");
RDRenderer_Unsigned(rp->renderer, ulpinstr->i2c.data);
RDRenderer_Text(rp->renderer, ", ");
RDRenderer_Unsigned(rp->renderer, ulpinstr->i2c.high);
RDRenderer_Text(rp->renderer, ", ");
RDRenderer_Unsigned(rp->renderer, ulpinstr->i2c.low);
RDRenderer_Text(rp->renderer, ", ");
RDRenderer_Unsigned(rp->renderer, ulpinstr->i2c.sel);
}
else
{
RDRenderer_MnemonicWord(rp->renderer, "i2c_rd", Theme_Default);
RDRenderer_Unsigned(rp->renderer, ulpinstr->i2c.subaddr);
RDRenderer_Text(rp->renderer, ", ");
RDRenderer_Unsigned(rp->renderer, ulpinstr->i2c.high);
RDRenderer_Text(rp->renderer, ", ");
RDRenderer_Unsigned(rp->renderer, ulpinstr->i2c.low);
RDRenderer_Text(rp->renderer, ", ");
RDRenderer_Unsigned(rp->renderer, ulpinstr->i2c.sel);
}
}
void ULPAssembler::renderRegRD(const ULPInstruction* ulpinstr, const RDRendererParams* rp)
{
unsigned int address = WORDS_TO_ADDR(ulpinstr->regwr.addr) + DR_REG_RTCCNTL_BASE;
unsigned int base;
if(address >= DR_REG_RTC_I2C_BASE) base = DR_REG_RTC_I2C_BASE;
else if(address >= DR_REG_SENS_BASE) base = DR_REG_SENS_BASE;
else if(address >= DR_REG_RTCIO_BASE) base = DR_REG_RTCIO_BASE;
else base = DR_REG_RTCCNTL_BASE;
unsigned int offset = address - base;
RDRenderer_MnemonicWord(rp->renderer, "reg_rd", Theme_Default);
if(offset) RDRenderer_Constant(rp->renderer, (rd_tohex(base) + "+" + rd_tohex(offset)).c_str());
else RDRenderer_Unsigned(rp->renderer, base);
RDRenderer_Text(rp->renderer, ", ");
RDRenderer_Unsigned(rp->renderer, ulpinstr->regwr.high);
RDRenderer_Text(rp->renderer, ", ");
RDRenderer_Unsigned(rp->renderer, ulpinstr->regwr.low);
}
void ULPAssembler::renderRegWR(const ULPInstruction* ulpinstr, const RDRendererParams* rp)
{
unsigned int address = WORDS_TO_ADDR(ulpinstr->regwr.addr) + DR_REG_RTCCNTL_BASE;
unsigned int base;
if(address >= DR_REG_RTC_I2C_BASE) base = DR_REG_RTC_I2C_BASE;
else if(address >= DR_REG_SENS_BASE) base = DR_REG_SENS_BASE;
else if(address >= DR_REG_RTCIO_BASE) base = DR_REG_RTCIO_BASE;
else base = DR_REG_RTCCNTL_BASE;
unsigned int offset = address - base;
RDRenderer_MnemonicWord(rp->renderer, "reg_wr", Theme_Default);
if(offset) RDRenderer_Constant(rp->renderer, (rd_tohex(base) + "+" + rd_tohex(offset)).c_str());
else RDRenderer_Unsigned(rp->renderer, base);
RDRenderer_Text(rp->renderer, ", ");
RDRenderer_Unsigned(rp->renderer, ulpinstr->regwr.high);
RDRenderer_Text(rp->renderer, ", ");
RDRenderer_Unsigned(rp->renderer, ulpinstr->regwr.low);
RDRenderer_Text(rp->renderer, ", ");
RDRenderer_Unsigned(rp->renderer, ulpinstr->regwr.data);
}
void ULPAssembler::renderStore(const ULPInstruction* ulpinstr, const RDRendererParams* rp)
{
RDRenderer_MnemonicWord(rp->renderer, "st", Theme_Default);
RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->ld.rdst).c_str());
RDRenderer_Text(rp->renderer, ", ");
RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->ld.rsrc).c_str());
RDRenderer_Text(rp->renderer, ", ");
RDRenderer_Signed(rp->renderer, ulpinstr->ld.offset);
}
void ULPAssembler::renderLoad(const ULPInstruction* ulpinstr, const RDRendererParams* rp)
{
RDRenderer_MnemonicWord(rp->renderer, "ld", Theme_Default);
RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->ld.rdst).c_str());
RDRenderer_Text(rp->renderer, ", ");
RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->ld.rsrc).c_str());
RDRenderer_Text(rp->renderer, ", ");
RDRenderer_Signed(rp->renderer, ulpinstr->ld.offset);
}
| 39.622699 | 122 | 0.682821 | kermitdafrog8 |
c1d0f0e54409bb9ec02d355676ea3b5bf88e393f | 9,839 | hpp | C++ | service/src/geopm/CircularBuffer.hpp | dannosliwcd/geopm | 3ec0d223e700350ff37f6d10adde7b9bfbdba286 | [
"BSD-3-Clause"
] | 77 | 2015-10-16T22:20:51.000Z | 2022-03-30T22:51:12.000Z | service/src/geopm/CircularBuffer.hpp | dannosliwcd/geopm | 3ec0d223e700350ff37f6d10adde7b9bfbdba286 | [
"BSD-3-Clause"
] | 1,627 | 2016-05-17T18:25:53.000Z | 2022-03-31T22:49:45.000Z | service/src/geopm/CircularBuffer.hpp | dannosliwcd/geopm | 3ec0d223e700350ff37f6d10adde7b9bfbdba286 | [
"BSD-3-Clause"
] | 44 | 2015-10-28T15:59:44.000Z | 2022-03-25T20:28:18.000Z | /*
* Copyright (c) 2015 - 2021, Intel Corporation
*
* 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 Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY LOG OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CIRCULARBUFFER_HPP_INCLUDE
#define CIRCULARBUFFER_HPP_INCLUDE
#include <stdlib.h>
#include <vector>
#include "Exception.hpp"
namespace geopm
{
/// @brief Templated container for a circular buffer implementation.
/// The CircularBuffer container implements a fixed size buffer. Once
/// at capacity, any new insertions cause the oldest entry to be dropped.
template <class type>
class CircularBuffer
{
public:
CircularBuffer();
/// @brief Constructor for the CircularBuffer template.
///
/// Creates an empty circular buffer with a set capacity.
///
/// @param [in] size Requested capacity for the buffer.
CircularBuffer(unsigned int size);
/// @brief CircularBuffer destructor, virtual
virtual ~CircularBuffer();
/// @brief Re-size the circular buffer.
///
/// Resets the capacity of the circular buffer without
/// modifying its current contents.
///
/// @param [in] size Requested capacity for the buffer.
void set_capacity(const unsigned int size);
/// @brief Clears all entries from the buffer.
void clear(void);
/// @brief Size of the buffer contents.
///
/// Returns the number of items in the buffer. This
/// value will be less than or equal to the current
/// capacity of the buffer.
//
/// @return Size of the buffer contents.
int size(void) const;
/// @brief Capacity of the buffer.
///
/// Returns the current size of the circular buffer at
/// the time of the call.
///
/// @return Capacity of the buffer.
int capacity(void) const;
/// @brief Insert a value into the buffer.
///
/// If the buffer is not full, the new value is simply
/// added to the buffer. It the buffer is at capacity,
/// The head of the buffer is dropped and moved to the
/// next oldest entry and the new value is then inserted
/// at the end of the buffer.
///
/// @param [in] value The value to be inserted.
void insert(const type value);
/// @brief Returns a constant reference to the value from the buffer.
///
/// Accesses the contents of the circular buffer
/// at a particular index. Valid indices range
/// from 0 to [size-1]. Where size is the number
/// of valid entries in the buffer. An attempt to
/// retrieve a value for an out of bound index
/// will throw a geopm::Exception with an
/// error_value() of GEOPM_ERROR_INVALID.
///
/// @param [in] index Buffer index to retrieve.
///
/// @return Value from the specified buffer index.
const type& value(const unsigned int index) const;
/// @brief Create a vector from the circular buffer contents.
///
/// @return Vector containing the circular buffer contents.
std::vector<type> make_vector(void) const;
/// @brief Create a vector slice from the circular buffer contents.
///
/// @param [in] start Start index (inclusive).
/// @param [in] end End index (exclusive).
/// @return Vector containing the circular buffer contents at [start, end).
std::vector<type> make_vector(const unsigned int start, const unsigned int end) const;
private:
/// @brief Vector holding the buffer data.
std::vector<type> m_buffer;
/// @brief Index of the current head of the buffer.
unsigned long m_head;
/// @brief The number of valid entries in the buffer.
unsigned long m_count;
/// @brief Current capacity of the buffer.
size_t m_max_size;
};
template <class type>
CircularBuffer<type>::CircularBuffer()
: CircularBuffer(0)
{
}
template <class type>
CircularBuffer<type>::CircularBuffer(unsigned int size)
: m_buffer(size)
, m_head(0)
, m_count(0)
, m_max_size(size)
{
}
template <class type>
CircularBuffer<type>::~CircularBuffer()
{
}
template <class type>
int CircularBuffer<type>::size() const
{
return m_count;
}
template <class type>
int CircularBuffer<type>::capacity() const
{
return m_max_size;
}
template <class type>
void CircularBuffer<type>::clear()
{
m_head = 0;
m_count = 0;
}
template <class type>
void CircularBuffer<type>::set_capacity(const unsigned int size)
{
if (size < m_count && m_max_size > 0) {
int size_diff = m_count - size;
std::vector<type> temp;
//Copy newest data into temporary vector
for (unsigned int i = m_head + size_diff; i != ((m_head + m_count) % m_max_size); i = ((i + 1) % m_max_size)) {
temp.push_back(m_buffer[i]);
}
//now re-size and swap out with tmp vector data
m_buffer.resize(size);
m_buffer.swap(temp);
m_count = size;
}
else {
m_buffer.resize(size);
}
m_head = 0;
m_max_size = size;
}
template <class type>
void CircularBuffer<type>::insert(const type value)
{
if (m_max_size < 1) {
throw Exception("CircularBuffer::insert(): Cannot insert into a buffer of 0 size", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
}
if (m_count < m_max_size) {
m_buffer[m_count] = value;
m_count++;
}
else {
m_buffer[m_head] = value;
m_head = ((m_head + 1) % m_max_size);
}
}
template <class type>
const type& CircularBuffer<type>::value(const unsigned int index) const
{
if (index >= m_count) {
throw Exception("CircularBuffer::value(): index is out of bounds", GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
return m_buffer[(m_head + index) % m_max_size];
}
template <class type>
std::vector<type> CircularBuffer<type>::make_vector(void) const
{
std::vector<type> result(size());
if (m_head == 0) {
std::copy(m_buffer.begin(), m_buffer.begin() + m_count, result.begin());
}
else {
std::copy(m_buffer.begin() + m_head, m_buffer.end(), result.begin());
std::copy(m_buffer.begin(), m_buffer.begin() + m_head, result.end() - m_head);
}
return result;
}
template <class type>
std::vector<type> CircularBuffer<type>::make_vector(const unsigned int idx_start, const unsigned int idx_end) const
{
if (idx_start >= (unsigned int)size()) {
throw Exception("CircularBuffer::make_vector(): start is out of bounds", GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
if (idx_end > (unsigned int)size()) {
throw Exception("CircularBuffer::make_vector(): end is out of bounds", GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
if (idx_end <= idx_start) {
throw Exception("CircularBuffer::make_vector(): end index is smaller than start index", GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
int slice_length = idx_end - idx_start;
std::vector<type> result(slice_length);
unsigned int start=(m_head + idx_start) % capacity();
unsigned int end=(((m_head + idx_end) - 1) % capacity()) + 1;
if(end > start) {
std::copy(m_buffer.begin() + start, m_buffer.begin() + end, result.begin());
}
else {
std::copy(m_buffer.begin() + start, m_buffer.end(), result.begin());
std::copy(m_buffer.begin(), m_buffer.begin() + end, result.begin() + capacity() - start);
}
return result;
}
}
#endif
| 37.128302 | 141 | 0.594166 | dannosliwcd |
c1d52f3d55ec9edc06f61216a567651b36c52abd | 717 | cpp | C++ | ITU/proj_1/NormalInput.cpp | mikeek/FIT | da7fb8b4b57b0a28b345348d8fe1ecf30dccb9a2 | [
"MIT"
] | 1 | 2017-03-25T11:59:15.000Z | 2017-03-25T11:59:15.000Z | ITU/proj_1/NormalInput.cpp | mikeek/FIT | da7fb8b4b57b0a28b345348d8fe1ecf30dccb9a2 | [
"MIT"
] | null | null | null | ITU/proj_1/NormalInput.cpp | mikeek/FIT | da7fb8b4b57b0a28b345348d8fe1ecf30dccb9a2 | [
"MIT"
] | 6 | 2017-04-06T10:49:03.000Z | 2021-01-18T20:29:35.000Z | #include "NormalInput.h"
#include <time.h>
NormalInput::NormalInput()
{
}
float NormalInput::realTime(clock_t clockDiff)
{
return ((float) clockDiff) / CLOCKS_PER_SEC;
}
QChar NormalInput::resolve(int index, QString charField)
{
clock_t nowTime = clock();
clock_t diff = nowTime - _lastTime;
_lastTime = nowTime;
if (index == _lastButton && realTime(diff) < QUICK_PRESS_INTEVAL) {
/* Quick press, change last character */
_lastResult = CHANGE_LAST;
if (_lastPosition >= charField.length()) {
_lastPosition = 0;
}
return charField[_lastPosition++];
}
_lastResult = APPEND_NEW;
_lastButton = index;
_lastPosition = 0;
return charField[_lastPosition++];
}
| 20.485714 | 69 | 0.679219 | mikeek |
c1d79e8137b7a89ccda5ccb6ffc0ce4534e92535 | 18,441 | cpp | C++ | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/network/socket/qlocalsocket_unix.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/network/socket/qlocalsocket_unix.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/network/socket/qlocalsocket_unix.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtNetwork module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qlocalsocket.h"
#include "qlocalsocket_p.h"
#include "qnet_unix_p.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <qdir.h>
#include <qdebug.h>
#include <qelapsedtimer.h>
#ifdef Q_OS_VXWORKS
# include <selectLib.h>
#endif
#define QT_CONNECT_TIMEOUT 30000
QT_BEGIN_NAMESPACE
QLocalSocketPrivate::QLocalSocketPrivate() : QIODevicePrivate(),
delayConnect(0),
connectTimer(0),
connectingSocket(-1),
connectingOpenMode(0),
state(QLocalSocket::UnconnectedState)
{
}
void QLocalSocketPrivate::init()
{
Q_Q(QLocalSocket);
// QIODevice signals
q->connect(&unixSocket, SIGNAL(aboutToClose()), q, SIGNAL(aboutToClose()));
q->connect(&unixSocket, SIGNAL(bytesWritten(qint64)),
q, SIGNAL(bytesWritten(qint64)));
q->connect(&unixSocket, SIGNAL(readyRead()), q, SIGNAL(readyRead()));
// QAbstractSocket signals
q->connect(&unixSocket, SIGNAL(connected()), q, SIGNAL(connected()));
q->connect(&unixSocket, SIGNAL(disconnected()), q, SIGNAL(disconnected()));
q->connect(&unixSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
q, SLOT(_q_stateChanged(QAbstractSocket::SocketState)));
q->connect(&unixSocket, SIGNAL(error(QAbstractSocket::SocketError)),
q, SLOT(_q_error(QAbstractSocket::SocketError)));
q->connect(&unixSocket, SIGNAL(readChannelFinished()), q, SIGNAL(readChannelFinished()));
unixSocket.setParent(q);
}
void QLocalSocketPrivate::_q_error(QAbstractSocket::SocketError socketError)
{
Q_Q(QLocalSocket);
QString function = QLatin1String("QLocalSocket");
QLocalSocket::LocalSocketError error = (QLocalSocket::LocalSocketError)socketError;
QString errorString = generateErrorString(error, function);
q->setErrorString(errorString);
emit q->error(error);
}
void QLocalSocketPrivate::_q_stateChanged(QAbstractSocket::SocketState newState)
{
Q_Q(QLocalSocket);
QLocalSocket::LocalSocketState currentState = state;
switch(newState) {
case QAbstractSocket::UnconnectedState:
state = QLocalSocket::UnconnectedState;
serverName.clear();
fullServerName.clear();
break;
case QAbstractSocket::ConnectingState:
state = QLocalSocket::ConnectingState;
break;
case QAbstractSocket::ConnectedState:
state = QLocalSocket::ConnectedState;
break;
case QAbstractSocket::ClosingState:
state = QLocalSocket::ClosingState;
break;
default:
#if defined QLOCALSOCKET_DEBUG
qWarning() << "QLocalSocket::Unhandled socket state change:" << newState;
#endif
return;
}
if (currentState != state)
emit q->stateChanged(state);
}
QString QLocalSocketPrivate::generateErrorString(QLocalSocket::LocalSocketError error, const QString &function) const
{
QString errorString;
switch (error) {
case QLocalSocket::ConnectionRefusedError:
errorString = QLocalSocket::tr("%1: Connection refused").arg(function);
break;
case QLocalSocket::PeerClosedError:
errorString = QLocalSocket::tr("%1: Remote closed").arg(function);
break;
case QLocalSocket::ServerNotFoundError:
errorString = QLocalSocket::tr("%1: Invalid name").arg(function);
break;
case QLocalSocket::SocketAccessError:
errorString = QLocalSocket::tr("%1: Socket access error").arg(function);
break;
case QLocalSocket::SocketResourceError:
errorString = QLocalSocket::tr("%1: Socket resource error").arg(function);
break;
case QLocalSocket::SocketTimeoutError:
errorString = QLocalSocket::tr("%1: Socket operation timed out").arg(function);
break;
case QLocalSocket::DatagramTooLargeError:
errorString = QLocalSocket::tr("%1: Datagram too large").arg(function);
break;
case QLocalSocket::ConnectionError:
errorString = QLocalSocket::tr("%1: Connection error").arg(function);
break;
case QLocalSocket::UnsupportedSocketOperationError:
errorString = QLocalSocket::tr("%1: The socket operation is not supported").arg(function);
break;
case QLocalSocket::OperationError:
errorString = QLocalSocket::tr("%1: Operation not permitted when socket is in this state").arg(function);
break;
case QLocalSocket::UnknownSocketError:
default:
errorString = QLocalSocket::tr("%1: Unknown error %2").arg(function).arg(errno);
}
return errorString;
}
void QLocalSocketPrivate::errorOccurred(QLocalSocket::LocalSocketError error, const QString &function)
{
Q_Q(QLocalSocket);
switch (error) {
case QLocalSocket::ConnectionRefusedError:
unixSocket.setSocketError(QAbstractSocket::ConnectionRefusedError);
break;
case QLocalSocket::PeerClosedError:
unixSocket.setSocketError(QAbstractSocket::RemoteHostClosedError);
break;
case QLocalSocket::ServerNotFoundError:
unixSocket.setSocketError(QAbstractSocket::HostNotFoundError);
break;
case QLocalSocket::SocketAccessError:
unixSocket.setSocketError(QAbstractSocket::SocketAccessError);
break;
case QLocalSocket::SocketResourceError:
unixSocket.setSocketError(QAbstractSocket::SocketResourceError);
break;
case QLocalSocket::SocketTimeoutError:
unixSocket.setSocketError(QAbstractSocket::SocketTimeoutError);
break;
case QLocalSocket::DatagramTooLargeError:
unixSocket.setSocketError(QAbstractSocket::DatagramTooLargeError);
break;
case QLocalSocket::ConnectionError:
unixSocket.setSocketError(QAbstractSocket::NetworkError);
break;
case QLocalSocket::UnsupportedSocketOperationError:
unixSocket.setSocketError(QAbstractSocket::UnsupportedSocketOperationError);
break;
case QLocalSocket::UnknownSocketError:
default:
unixSocket.setSocketError(QAbstractSocket::UnknownSocketError);
}
QString errorString = generateErrorString(error, function);
q->setErrorString(errorString);
emit q->error(error);
// errors cause a disconnect
unixSocket.setSocketState(QAbstractSocket::UnconnectedState);
bool stateChanged = (state != QLocalSocket::UnconnectedState);
state = QLocalSocket::UnconnectedState;
q->close();
if (stateChanged)
q->emit stateChanged(state);
}
void QLocalSocket::connectToServer(OpenMode openMode)
{
Q_D(QLocalSocket);
if (state() == ConnectedState || state() == ConnectingState) {
QString errorString = d->generateErrorString(QLocalSocket::OperationError, QLatin1String("QLocalSocket::connectToserver"));
setErrorString(errorString);
emit error(QLocalSocket::OperationError);
return;
}
d->errorString.clear();
d->unixSocket.setSocketState(QAbstractSocket::ConnectingState);
d->state = ConnectingState;
emit stateChanged(d->state);
if (d->serverName.isEmpty()) {
d->errorOccurred(ServerNotFoundError,
QLatin1String("QLocalSocket::connectToServer"));
return;
}
// create the socket
if (-1 == (d->connectingSocket = qt_safe_socket(PF_UNIX, SOCK_STREAM, 0, O_NONBLOCK))) {
d->errorOccurred(UnsupportedSocketOperationError,
QLatin1String("QLocalSocket::connectToServer"));
return;
}
// _q_connectToSocket does the actual connecting
d->connectingName = d->serverName;
d->connectingOpenMode = openMode;
d->_q_connectToSocket();
return;
}
/*!
\internal
Tries to connect connectingName and connectingOpenMode
\sa connectToServer(), waitForConnected()
*/
void QLocalSocketPrivate::_q_connectToSocket()
{
Q_Q(QLocalSocket);
QString connectingPathName;
// determine the full server path
if (connectingName.startsWith(QLatin1Char('/'))) {
connectingPathName = connectingName;
} else {
connectingPathName = QDir::tempPath();
connectingPathName += QLatin1Char('/') + connectingName;
}
const QByteArray encodedConnectingPathName = QFile::encodeName(connectingPathName);
struct sockaddr_un name;
name.sun_family = PF_UNIX;
if (sizeof(name.sun_path) < (uint)encodedConnectingPathName.size() + 1) {
QString function = QLatin1String("QLocalSocket::connectToServer");
errorOccurred(QLocalSocket::ServerNotFoundError, function);
return;
}
::memcpy(name.sun_path, encodedConnectingPathName.constData(),
encodedConnectingPathName.size() + 1);
if (-1 == qt_safe_connect(connectingSocket, (struct sockaddr *)&name, sizeof(name))) {
QString function = QLatin1String("QLocalSocket::connectToServer");
switch (errno)
{
case EINVAL:
case ECONNREFUSED:
errorOccurred(QLocalSocket::ConnectionRefusedError, function);
break;
case ENOENT:
errorOccurred(QLocalSocket::ServerNotFoundError, function);
break;
case EACCES:
case EPERM:
errorOccurred(QLocalSocket::SocketAccessError, function);
break;
case ETIMEDOUT:
errorOccurred(QLocalSocket::SocketTimeoutError, function);
break;
case EAGAIN:
// Try again later, all of the sockets listening are full
if (!delayConnect) {
delayConnect = new QSocketNotifier(connectingSocket, QSocketNotifier::Write, q);
q->connect(delayConnect, SIGNAL(activated(int)), q, SLOT(_q_connectToSocket()));
}
if (!connectTimer) {
connectTimer = new QTimer(q);
q->connect(connectTimer, SIGNAL(timeout()),
q, SLOT(_q_abortConnectionAttempt()),
Qt::DirectConnection);
connectTimer->start(QT_CONNECT_TIMEOUT);
}
delayConnect->setEnabled(true);
break;
default:
errorOccurred(QLocalSocket::UnknownSocketError, function);
}
return;
}
// connected!
cancelDelayedConnect();
serverName = connectingName;
fullServerName = connectingPathName;
if (unixSocket.setSocketDescriptor(connectingSocket,
QAbstractSocket::ConnectedState, connectingOpenMode)) {
q->QIODevice::open(connectingOpenMode | QIODevice::Unbuffered);
q->emit connected();
} else {
QString function = QLatin1String("QLocalSocket::connectToServer");
errorOccurred(QLocalSocket::UnknownSocketError, function);
}
connectingSocket = -1;
connectingName.clear();
connectingOpenMode = 0;
}
bool QLocalSocket::setSocketDescriptor(qintptr socketDescriptor,
LocalSocketState socketState, OpenMode openMode)
{
Q_D(QLocalSocket);
QAbstractSocket::SocketState newSocketState = QAbstractSocket::UnconnectedState;
switch (socketState) {
case ConnectingState:
newSocketState = QAbstractSocket::ConnectingState;
break;
case ConnectedState:
newSocketState = QAbstractSocket::ConnectedState;
break;
case ClosingState:
newSocketState = QAbstractSocket::ClosingState;
break;
case UnconnectedState:
newSocketState = QAbstractSocket::UnconnectedState;
break;
}
QIODevice::open(openMode);
d->state = socketState;
return d->unixSocket.setSocketDescriptor(socketDescriptor,
newSocketState, openMode);
}
void QLocalSocketPrivate::_q_abortConnectionAttempt()
{
Q_Q(QLocalSocket);
q->close();
}
void QLocalSocketPrivate::cancelDelayedConnect()
{
if (delayConnect) {
delayConnect->setEnabled(false);
delete delayConnect;
delayConnect = 0;
connectTimer->stop();
delete connectTimer;
connectTimer = 0;
}
}
qintptr QLocalSocket::socketDescriptor() const
{
Q_D(const QLocalSocket);
return d->unixSocket.socketDescriptor();
}
qint64 QLocalSocket::readData(char *data, qint64 c)
{
Q_D(QLocalSocket);
return d->unixSocket.read(data, c);
}
qint64 QLocalSocket::writeData(const char *data, qint64 c)
{
Q_D(QLocalSocket);
return d->unixSocket.writeData(data, c);
}
void QLocalSocket::abort()
{
Q_D(QLocalSocket);
d->unixSocket.abort();
}
qint64 QLocalSocket::bytesAvailable() const
{
Q_D(const QLocalSocket);
return QIODevice::bytesAvailable() + d->unixSocket.bytesAvailable();
}
qint64 QLocalSocket::bytesToWrite() const
{
Q_D(const QLocalSocket);
return d->unixSocket.bytesToWrite();
}
bool QLocalSocket::canReadLine() const
{
Q_D(const QLocalSocket);
return QIODevice::canReadLine() || d->unixSocket.canReadLine();
}
void QLocalSocket::close()
{
Q_D(QLocalSocket);
d->unixSocket.close();
d->cancelDelayedConnect();
if (d->connectingSocket != -1)
::close(d->connectingSocket);
d->connectingSocket = -1;
d->connectingName.clear();
d->connectingOpenMode = 0;
d->serverName.clear();
d->fullServerName.clear();
QIODevice::close();
}
bool QLocalSocket::waitForBytesWritten(int msecs)
{
Q_D(QLocalSocket);
return d->unixSocket.waitForBytesWritten(msecs);
}
bool QLocalSocket::flush()
{
Q_D(QLocalSocket);
return d->unixSocket.flush();
}
void QLocalSocket::disconnectFromServer()
{
Q_D(QLocalSocket);
d->unixSocket.disconnectFromHost();
}
QLocalSocket::LocalSocketError QLocalSocket::error() const
{
Q_D(const QLocalSocket);
switch (d->unixSocket.error()) {
case QAbstractSocket::ConnectionRefusedError:
return QLocalSocket::ConnectionRefusedError;
case QAbstractSocket::RemoteHostClosedError:
return QLocalSocket::PeerClosedError;
case QAbstractSocket::HostNotFoundError:
return QLocalSocket::ServerNotFoundError;
case QAbstractSocket::SocketAccessError:
return QLocalSocket::SocketAccessError;
case QAbstractSocket::SocketResourceError:
return QLocalSocket::SocketResourceError;
case QAbstractSocket::SocketTimeoutError:
return QLocalSocket::SocketTimeoutError;
case QAbstractSocket::DatagramTooLargeError:
return QLocalSocket::DatagramTooLargeError;
case QAbstractSocket::NetworkError:
return QLocalSocket::ConnectionError;
case QAbstractSocket::UnsupportedSocketOperationError:
return QLocalSocket::UnsupportedSocketOperationError;
case QAbstractSocket::UnknownSocketError:
return QLocalSocket::UnknownSocketError;
default:
#if defined QLOCALSOCKET_DEBUG
qWarning() << "QLocalSocket error not handled:" << d->unixSocket.error();
#endif
break;
}
return UnknownSocketError;
}
bool QLocalSocket::isValid() const
{
Q_D(const QLocalSocket);
return d->unixSocket.isValid();
}
qint64 QLocalSocket::readBufferSize() const
{
Q_D(const QLocalSocket);
return d->unixSocket.readBufferSize();
}
void QLocalSocket::setReadBufferSize(qint64 size)
{
Q_D(QLocalSocket);
d->unixSocket.setReadBufferSize(size);
}
bool QLocalSocket::waitForConnected(int msec)
{
Q_D(QLocalSocket);
if (state() != ConnectingState)
return (state() == ConnectedState);
QElapsedTimer timer;
timer.start();
pollfd pfd = qt_make_pollfd(d->connectingSocket, POLLIN);
do {
const int timeout = (msec > 0) ? qMax(msec - timer.elapsed(), Q_INT64_C(0)) : msec;
const int result = qt_poll_msecs(&pfd, 1, timeout);
if (result == -1)
d->errorOccurred(QLocalSocket::UnknownSocketError,
QLatin1String("QLocalSocket::waitForConnected"));
else if (result > 0)
d->_q_connectToSocket();
} while (state() == ConnectingState && !timer.hasExpired(msec));
return (state() == ConnectedState);
}
bool QLocalSocket::waitForDisconnected(int msecs)
{
Q_D(QLocalSocket);
if (state() == UnconnectedState) {
qWarning("QLocalSocket::waitForDisconnected() is not allowed in UnconnectedState");
return false;
}
return (d->unixSocket.waitForDisconnected(msecs));
}
bool QLocalSocket::waitForReadyRead(int msecs)
{
Q_D(QLocalSocket);
if (state() == QLocalSocket::UnconnectedState)
return false;
return (d->unixSocket.waitForReadyRead(msecs));
}
QT_END_NAMESPACE
| 33.167266 | 131 | 0.684236 | GrinCash |
c1d7f4b4f194d2668e731bd31795607911da6c76 | 1,915 | cpp | C++ | d3util/logger.cpp | d3roch4/d3util | d438e35c6fceff8cdca9ef6ea3e6c043389c6e4c | [
"MIT"
] | null | null | null | d3util/logger.cpp | d3roch4/d3util | d438e35c6fceff8cdca9ef6ea3e6c043389c6e4c | [
"MIT"
] | null | null | null | d3util/logger.cpp | d3roch4/d3util | d438e35c6fceff8cdca9ef6ea3e6c043389c6e4c | [
"MIT"
] | null | null | null | #include "logger.h"
#include <boost/log/attributes/attribute_value_set.hpp>
#include <boost/log/sources/severity_logger.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/console.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/expressions.hpp>
#include <boost/shared_ptr.hpp>
void init_logger(const std::string& prefixFile, boost::log::trivial::severity_level severity)
{
auto format = "[%TimeStamp%] [%ThreadID%] [%Severity%] [%ProcessID%] [%LineID%] %Message%";
namespace keywords = boost::log::keywords;
namespace expr = boost::log::expressions;
boost::log::add_console_log(
std::clog,
keywords::format =
(
expr::stream
//<< std::hex //To print the LineID in Hexadecimal format
// << std::setw(8) << std::setfill('0')
<< expr::attr< unsigned int >("LineID")
// << expr::format_date_time<boost::posix_time::ptime>("TimeStamp","%H:%M:%S.%f")
<< "<" << boost::log::trivial::severity
<< ">" << expr::smessage
)
);
boost::log::add_file_log
(
keywords::file_name = prefixFile, /*< file name pattern >*/
keywords::rotation_size = 10 * 1024, /*< rotate files every 1 KiB >*/
/*< log record format >*/
keywords::format =
(
expr::stream
//<< std::hex //To print the LineID in Hexadecimal format
// << std::setw(8) << std::setfill('0')
<< expr::attr< unsigned int >("LineID")
<< "\t"
// << expr::format_date_time<boost::posix_time::ptime>("TimeStamp","%H:%M:%S.%f")
<< "\t: <" << boost::log::trivial::severity
<< "> \t" << expr::smessage
)
);
// boost::log::core::get()->set_filter
// (
// boost::log::trivial::severity >= severity
// );
}
| 36.132075 | 95 | 0.562924 | d3roch4 |
c1d8c9b1a9b00818d5ae083fa70c5fabe91ba6eb | 9,016 | cpp | C++ | 2020/0125_ddcc2020-machine/A.cpp | kazunetakahashi/atcoder | 16ce65829ccc180260b19316e276c2fcf6606c53 | [
"MIT"
] | 7 | 2019-03-24T14:06:29.000Z | 2020-09-17T21:16:36.000Z | 2020/0125_ddcc2020-machine/A.cpp | kazunetakahashi/atcoder | 16ce65829ccc180260b19316e276c2fcf6606c53 | [
"MIT"
] | null | null | null | 2020/0125_ddcc2020-machine/A.cpp | kazunetakahashi/atcoder | 16ce65829ccc180260b19316e276c2fcf6606c53 | [
"MIT"
] | 1 | 2020-07-22T17:27:09.000Z | 2020-07-22T17:27:09.000Z | #define DEBUG 1
/**
* File : A.cpp
* Author : Kazune Takahashi
* Created : 2020/1/25 11:32:12
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(const Mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(const Mint &a) { return *this += -a; }
Mint &operator*=(const Mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(const Mint &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(const Mint &a) const { return Mint(*this) += a; }
Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
bool operator<(const Mint &a) const { return x < a.x; }
bool operator<=(const Mint &a) const { return x <= a.x; }
bool operator>(const Mint &a) const { return x > a.x; }
bool operator>=(const Mint &a) const { return x >= a.x; }
bool operator==(const Mint &a) const { return x == a.x; }
bool operator!=(const Mint &a) const { return !(*this == a); }
const Mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2LL; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1LL; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
template <typename T>
int popcount(T x) // C++20
{
int ans{0};
while (x != 0)
{
ans += x & 1;
x >>= 1;
}
return ans;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
class Sieve
{
static constexpr ll MAX_SIZE{10000010LL};
ll N;
vector<ll> f;
vector<ll> prime_nums;
public:
Sieve(ll N = MAX_SIZE) : N{N}, f(N, 0), prime_nums{}
{
f[0] = f[1] = -1;
for (auto i = 2; i < N; i++)
{
if (f[i])
{
continue;
}
prime_nums.push_back(i);
f[i] = i;
for (auto j = 2 * i; j < N; j += i)
{
if (!f[j])
{
f[j] = i;
}
}
}
}
bool is_prime(ll x) const
{ // 2 \leq x \leq MAX_SIZE^2
if (x < N)
{
return f[x];
}
for (auto e : prime_nums)
{
if (x % e == 0)
{
return false;
}
}
return true;
}
vector<ll> const &primes() const
{
return prime_nums;
}
vector<ll> factor_list(ll x) const
{
if (x < 2)
{
return {};
}
vector<ll> res;
auto it{prime_nums.begin()};
if (x < N)
{
while (x != 1)
{
res.push_back(f[x]);
x /= f[x];
}
}
else
{
while (x != 1 && it != prime_nums.end())
{
if (x % *it == 0)
{
res.push_back(*it);
x /= *it;
}
else
{
++it;
}
}
if (x != 1)
{
res.push_back(x);
}
}
return res;
}
vector<tuple<ll, ll>> factor(ll x) const
{
if (x < 2)
{
return {};
}
auto factors{factor_list(x)};
vector<tuple<ll, ll>> res{make_tuple(factors[0], 0)};
for (auto x : factors)
{
if (x == get<0>(res.back()))
{
get<1>(res.back())++;
}
else
{
res.emplace_back(x, 1);
}
}
return res;
}
};
// ----- main() -----
using ld = long double;
using point = complex<ld>;
constexpr ld PI{3.14159265358979323846};
class Solve
{
ld La, Lb, Lc, Na, Nb, Nc, Ne, Ma, Mb, Mc, Tc;
int alpha;
Sieve sieve;
ld Ta = 0;
ld Tb;
point Oa{0, 900}, Ob{900, 0}, Oc{900, 900}, Oe{90, 50};
point Aa{1, 0}, Ab{0, 1}, Ac{-1, 0};
ld S{500}, A{3000}, D{60};
public:
Solve(ld La, ld Lb, ld Lc, ld Na, ld Nb, ld Nc, ld Ne, ld Ma, ld Mb, ld Mc, ld Tc) : La{La}, Lb{Lb}, Lc{Lc}, Na{Na}, Nb{Nb}, Nc{Nc}, Ne{Ne}, Ma{Ma}, Mb{Mb}, Mc{Mc}, Tc{Tc} {}
void flush()
{
for (auto i = 0; i < 20; ++i)
{
ld now{0};
ld W{Ma};
if (now + Ma * Na > 100)
{
W = 500;
}
flush_A(W);
now += Na * W;
W = Mb;
if (now + Mb * Nb > 100)
{
W = 500;
}
flush_B(W);
now += Nb * W;
W = Mc;
if (now + Mc * Nc > 100)
{
W = 500;
}
flush_C(W);
now += Nc * W;
flush_E(now / Ne);
}
}
private:
void update_Tb()
{
if (alpha == 0)
{
Tb = 0;
}
else
{
ll p{sieve.primes()[alpha + 1]};
ll r{p % 180};
Tb = (r <= 90 ? r : 180 - r);
}
}
point arg(ld theta) { return theta / 180 * PI * point(0, 1); }
point Pa() { return exp(-arg(Ta)) * La + Oa; }
point Pb() { return exp(arg(Tb)) * Lb + Ob; }
point Pc() { return exp(arg(Tc)) * Lc + Oc; }
void flush_simple(ld X, ld Sx, ld Ax, ld Dx, ld Y, ld Sy, ld Ay, ld Dy, ld Ta, ld Wa, ld Wb, ld Wc, ld We)
{
cout << fixed << setprecision(0) << X << ", " << Sx << ", " << Ax << ", " << Dx << ", " << Y << ", " << Sy << ", " << Ay << ", " << Dy << ", " << Ta << ", " << Wa << ", " << Wb << ", " << Wc << ", " << We << endl;
}
void flush_A(ld W)
{
flush_simple(Pa().real(), S, A, D, Pa().imag(), S, A, D, Ta, W, 0, 0, 0);
alpha += W;
}
void flush_B(ld W)
{
flush_simple(Pb().real(), S, A, D, Pb().imag(), S, A, D, Ta, 0, W, 0, 0);
}
void flush_C(ld W)
{
flush_simple(Pc().real(), S, A, D, Pc().imag(), S, A, D, Ta, 0, 0, W, 0);
}
void flush_E(ld W)
{
flush_simple(Oe.real(), S, A, D, Oe.imag(), S, A, D, Ta, 0, 0, 0, W);
}
};
int main()
{
ld La, Lb, Lc, Na, Nb, Nc, Ne, Ma, Mb, Mc, Tc;
cin >> La >> Lb >> Lc >> Na >> Nb >> Nc >> Ne >> Ma >> Mb >> Mc >> Tc;
Solve solve(La, Lb, Lc, Na / 1000, Nb / 1000, Nc / 1000, Ne / 1000, Ma, Mb, Mc, Tc);
solve.flush();
}
| 20.822171 | 217 | 0.504326 | kazunetakahashi |
c1dae3a0935d087c2e8201fa1600b24661885a92 | 1,590 | cpp | C++ | Engine/Source/Runtime/Engine/Private/Info.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Runtime/Engine/Private/Info.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Runtime/Engine/Private/Info.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "GameFramework/Info.h"
#include "UObject/ConstructorHelpers.h"
#include "Components/BillboardComponent.h"
#include "Engine/Texture2D.h"
AInfo::AInfo(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
#if WITH_EDITORONLY_DATA
SpriteComponent = CreateEditorOnlyDefaultSubobject<UBillboardComponent>(TEXT("Sprite"));
RootComponent = SpriteComponent;
if (!IsRunningCommandlet() && (SpriteComponent != nullptr))
{
// Structure to hold one-time initialization
struct FConstructorStatics
{
ConstructorHelpers::FObjectFinderOptional<UTexture2D> SpriteTexture;
FName ID_Info;
FText NAME_Info;
FConstructorStatics()
: SpriteTexture(TEXT("/Engine/EditorResources/S_Actor"))
, ID_Info(TEXT("Info"))
, NAME_Info(NSLOCTEXT("SpriteCategory", "Info", "Info"))
{
}
};
static FConstructorStatics ConstructorStatics;
SpriteComponent->Sprite = ConstructorStatics.SpriteTexture.Get();
SpriteComponent->SpriteInfo.Category = ConstructorStatics.ID_Info;
SpriteComponent->SpriteInfo.DisplayName = ConstructorStatics.NAME_Info;
SpriteComponent->bIsScreenSizeScaled = true;
}
#endif // WITH_EDITORONLY_DATA
PrimaryActorTick.bCanEverTick = false;
bAllowTickBeforeBeginPlay = true;
bReplicates = false;
NetUpdateFrequency = 10.0f;
bHidden = true;
bReplicateMovement = false;
bCanBeDamaged = false;
}
#if WITH_EDITORONLY_DATA
/** Returns SpriteComponent subobject **/
UBillboardComponent* AInfo::GetSpriteComponent() const { return SpriteComponent; }
#endif
| 30.576923 | 89 | 0.774843 | windystrife |
c1dcfb9b6c8c2eca8d0e535bd836ef6a35f7e905 | 569 | hpp | C++ | src/Render.hpp | Sartek/Platformer | a499c870c05d7169aaf56b8a93694668750a4b4e | [
"CC-BY-3.0"
] | null | null | null | src/Render.hpp | Sartek/Platformer | a499c870c05d7169aaf56b8a93694668750a4b4e | [
"CC-BY-3.0"
] | null | null | null | src/Render.hpp | Sartek/Platformer | a499c870c05d7169aaf56b8a93694668750a4b4e | [
"CC-BY-3.0"
] | null | null | null | #ifndef RENDER
#define RENDER
#include <SFML/Graphics.hpp>
#include <vector>
class Render
{
public:
Render();
virtual ~Render();
void Background();
void Tile(unsigned int x,unsigned int y,unsigned int id);
void Hud();
void Player();
private:
sf::Texture Tile1;
sf::Texture Tile2;
sf::Texture Tile3;
sf::Texture background;
sf::Sprite backgroundSprite;
sf::Texture Sprite1;
sf::Texture Sprite2;
sf::Sprite playerSprite;
sf::RenderTexture hud;
sf::Sprite hudSprite;
std::vector<std::vector<sf::Sprite*> > SpriteArea;
};
#endif // RENDER
| 18.966667 | 61 | 0.697715 | Sartek |
c1ddba9fc988d2143876f14b51096ac13e954eb6 | 3,913 | hpp | C++ | include/RootMotion/BipedReferences_AutoDetectParams.hpp | Fernthedev/BeatSaber-Quest-Codegen | 716e4ff3f8608f7ed5b83e2af3be805f69e26d9e | [
"Unlicense"
] | null | null | null | include/RootMotion/BipedReferences_AutoDetectParams.hpp | Fernthedev/BeatSaber-Quest-Codegen | 716e4ff3f8608f7ed5b83e2af3be805f69e26d9e | [
"Unlicense"
] | null | null | null | include/RootMotion/BipedReferences_AutoDetectParams.hpp | Fernthedev/BeatSaber-Quest-Codegen | 716e4ff3f8608f7ed5b83e2af3be805f69e26d9e | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: RootMotion.BipedReferences
#include "RootMotion/BipedReferences.hpp"
// Including type: System.ValueType
#include "System/ValueType.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Type namespace: RootMotion
namespace RootMotion {
// Size: 0x2
#pragma pack(push, 1)
// WARNING Layout: Sequential may not be correctly taken into account!
// Autogenerated type: RootMotion.BipedReferences/RootMotion.AutoDetectParams
// [TokenAttribute] Offset: FFFFFFFF
struct BipedReferences::AutoDetectParams/*, public System::ValueType*/ {
public:
// public System.Boolean legsParentInSpine
// Size: 0x1
// Offset: 0x0
bool legsParentInSpine;
// Field size check
static_assert(sizeof(bool) == 0x1);
// public System.Boolean includeEyes
// Size: 0x1
// Offset: 0x1
bool includeEyes;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Creating value type constructor for type: AutoDetectParams
constexpr AutoDetectParams(bool legsParentInSpine_ = {}, bool includeEyes_ = {}) noexcept : legsParentInSpine{legsParentInSpine_}, includeEyes{includeEyes_} {}
// Creating interface conversion operator: operator System::ValueType
operator System::ValueType() noexcept {
return *reinterpret_cast<System::ValueType*>(this);
}
// Get instance field reference: public System.Boolean legsParentInSpine
bool& dyn_legsParentInSpine();
// Get instance field reference: public System.Boolean includeEyes
bool& dyn_includeEyes();
// static public RootMotion.BipedReferences/RootMotion.AutoDetectParams get_Default()
// Offset: 0x1D2FDEC
static RootMotion::BipedReferences::AutoDetectParams get_Default();
// public System.Void .ctor(System.Boolean legsParentInSpine, System.Boolean includeEyes)
// Offset: 0x1D2FDD8
// template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
// ABORTED: conflicts with another method. AutoDetectParams(bool legsParentInSpine, bool includeEyes)
}; // RootMotion.BipedReferences/RootMotion.AutoDetectParams
#pragma pack(pop)
static check_size<sizeof(BipedReferences::AutoDetectParams), 1 + sizeof(bool)> __RootMotion_BipedReferences_AutoDetectParamsSizeCheck;
static_assert(sizeof(BipedReferences::AutoDetectParams) == 0x2);
}
DEFINE_IL2CPP_ARG_TYPE(RootMotion::BipedReferences::AutoDetectParams, "RootMotion", "BipedReferences/AutoDetectParams");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: RootMotion::BipedReferences::AutoDetectParams::get_Default
// Il2CppName: get_Default
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<RootMotion::BipedReferences::AutoDetectParams (*)()>(&RootMotion::BipedReferences::AutoDetectParams::get_Default)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::BipedReferences::AutoDetectParams), "get_Default", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::BipedReferences::AutoDetectParams::AutoDetectParams
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 52.878378 | 186 | 0.741375 | Fernthedev |
c1df4685e1acba2c8fd40b402c8ab3199b11ce7c | 4,224 | cpp | C++ | shapes/rect.cpp | JacobSchneck/Flowers | 34f460cc584322f1eb1359bc203d2a89be23bccc | [
"MIT"
] | 2 | 2021-05-28T02:19:01.000Z | 2021-05-28T02:19:23.000Z | shapes/rect.cpp | JacobSchneck/Flowers | 34f460cc584322f1eb1359bc203d2a89be23bccc | [
"MIT"
] | null | null | null | shapes/rect.cpp | JacobSchneck/Flowers | 34f460cc584322f1eb1359bc203d2a89be23bccc | [
"MIT"
] | null | null | null | #include "../graphics.h"
#include "rect.h"
#include <iostream>
using namespace std;
/********************* Dimensions Struct ********************/
dimensions::dimensions() : width(0), height(0) {}
dimensions::dimensions(double w, double h) : width(w), height(h) {}
ostream& operator << (ostream& outs, const dimensions &d) {
outs << "[" << d.width << ", " << d.height << "]";
return outs;
}
Rect::Rect() : Shape(), size({0, 0}) {}
Rect::Rect(dimensions size) : Shape() {
setSize(size);
}
Rect::Rect(color fill) : Shape(fill), size({0, 0}) {}
Rect::Rect(point2D center) : Shape(center), size({0, 0}) {}
Rect::Rect(color fill, point2D center) : Shape(fill, center), size({0, 0}) {}
Rect::Rect(double red, double green, double blue, double alpha) : Shape(red, green, blue, alpha), size({0, 0}) {}
Rect::Rect(double x, double y) : Shape(x, y), size({0, 0}) {}
Rect::Rect(double red, double green, double blue, double alpha, double x, double y) : Shape(red, green, blue, alpha, x, y), size({0, 0}) {}
Rect::Rect(color fill, double x, double y) : Shape(fill, x, y), size({0, 0}) {}
Rect::Rect(double red, double green, double blue, double alpha, point2D center) : Shape(red, green, blue, alpha, center), size({0, 0}) {}
Rect::Rect(color fill, dimensions size) : Shape(fill) {
setSize(size);
}
Rect::Rect(point2D center, dimensions size) : Shape(center) {
setSize(size);
}
Rect::Rect(color fill, point2D center, dimensions size) : Shape(fill, center) {
setSize(size);
}
Rect::Rect(double red, double green, double blue, double alpha, dimensions size) : Shape(red, green, blue, alpha) {
setSize(size);
}
Rect::Rect(double x, double y, dimensions size) : Shape(x, y) {
setSize(size);
}
Rect::Rect(double red, double green, double blue, double alpha, double x, double y, dimensions size) : Shape(red, green, blue, alpha, x, y) {
setSize(size);
}
Rect::Rect(color fill, double x, double y, dimensions size) : Shape(fill, x, y) {
setSize(size);
}
Rect::Rect(double red, double green, double blue, double alpha, point2D center, dimensions size) : Shape(red, green, blue, alpha, center) {
setSize(size);
}
dimensions Rect::getSize() const {
return size;
}
double Rect::getWidth() const {
return size.width;
}
double Rect::getHeight() const {
return size.height;
}
double Rect::getLeftX() const {
return center.x - (size.width / 2.0);
}
double Rect::getRightX() const {
return center.x + (size.width / 2.0);
}
double Rect::getTopY() const {
return center.y - (size.height / 2.0);
}
double Rect::getBottomY() const {
return center.y + (size.height / 2.0);
}
void Rect::setSize(dimensions size) {
if (size.width >= 0 && size.height >= 0) {
this->size = size;
}
}
void Rect::setSize(double width, double height) {
setSize({width, height});
}
void Rect::setWidth(double width) {
setSize({width, size.height});
}
void Rect::setHeight(double height) {
setSize({size.width, height});
}
void Rect::changeSize(double deltaWidth, double deltaHeight) {
setSize({size.width + deltaWidth, size.height + deltaHeight});
}
void Rect::changeWidth(double delta) {
setSize({size.width + delta, size.height});
}
void Rect::changeHeight(double delta) {
setSize({size.width, size.height + delta});
}
// TODO: Implement this method
bool Rect::isOverlapping(const Rect &r) const {
// There are only two cases when rectangles are *not* overlapping:
// 1. when one is to the left of the other
// 2. when one is above the other
if ( (r.getLeftX() > getLeftX() && r.getRightX() < getRightX()) && (r.getBottomY() < getBottomY() && r.getTopY() > getTopY())) {
return true;
}
// if (r.getLeftX() > getLeftX() && r.getRightX() < getRightX() && r.getTopY() > getTopY()) {
// return true;
// }
return false;
}
// TODO: Implement this method
void Rect::draw() const {
// Don't forget to set the color to the fill field
glBegin(GL_QUADS);
glColor3f( fill.red, fill.green, fill.blue);
glVertex2i(getLeftX(), getBottomY());
glVertex2i(getRightX(), getBottomY());
glVertex2i(getRightX(), getTopY());
glVertex2i(getLeftX(), getTopY());
glEnd();
} | 27.076923 | 141 | 0.634233 | JacobSchneck |
c1e3d1b37f7c91dd15c250c077927364a96f7072 | 35,873 | cpp | C++ | src/USER-INTEL/pair_gayberne_intel.cpp | luwei0917/GlpG_Nature_Communication | a7f4f8b526e633b158dc606050e8993d70734943 | [
"MIT"
] | 1 | 2018-11-28T15:04:55.000Z | 2018-11-28T15:04:55.000Z | src/USER-INTEL/pair_gayberne_intel.cpp | luwei0917/GlpG_Nature_Communication | a7f4f8b526e633b158dc606050e8993d70734943 | [
"MIT"
] | null | null | null | src/USER-INTEL/pair_gayberne_intel.cpp | luwei0917/GlpG_Nature_Communication | a7f4f8b526e633b158dc606050e8993d70734943 | [
"MIT"
] | null | null | null | /* ----------------------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
This software is distributed under the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
/* ----------------------------------------------------------------------
Contributing author: W. Michael Brown (Intel)
------------------------------------------------------------------------- */
#include "pair_gayberne_intel.h"
#include "math_extra_intel.h"
#ifdef _LMP_INTEL_OFFLOAD
#pragma offload_attribute(push,target(mic))
#endif
#include <cmath>
#ifdef _LMP_INTEL_OFFLOAD
#pragma offload_attribute(pop)
#endif
#include "atom.h"
#include "comm.h"
#include "atom_vec_ellipsoid.h"
#include "force.h"
#include "memory.h"
#include "modify.h"
#include "neighbor.h"
#include "neigh_list.h"
#include "neigh_request.h"
#include "suffix.h"
using namespace LAMMPS_NS;
#define FC_PACKED1_T typename ForceConst<flt_t>::fc_packed1
#define FC_PACKED2_T typename ForceConst<flt_t>::fc_packed2
#define FC_PACKED3_T typename ForceConst<flt_t>::fc_packed3
/* ---------------------------------------------------------------------- */
PairGayBerneIntel::PairGayBerneIntel(LAMMPS *lmp) :
PairGayBerne(lmp)
{
suffix_flag |= Suffix::INTEL;
respa_enable = 0;
}
/* ---------------------------------------------------------------------- */
void PairGayBerneIntel::compute(int eflag, int vflag)
{
if (fix->precision()==FixIntel::PREC_MODE_MIXED)
compute<float,double>(eflag, vflag, fix->get_mixed_buffers(),
force_const_single);
else if (fix->precision()==FixIntel::PREC_MODE_DOUBLE)
compute<double,double>(eflag, vflag, fix->get_double_buffers(),
force_const_double);
else
compute<float,float>(eflag, vflag, fix->get_single_buffers(),
force_const_single);
fix->balance_stamp();
vflag_fdotr = 0;
}
template <class flt_t, class acc_t>
void PairGayBerneIntel::compute(int eflag, int vflag,
IntelBuffers<flt_t,acc_t> *buffers,
const ForceConst<flt_t> &fc)
{
if (eflag || vflag) {
ev_setup(eflag, vflag);
} else evflag = vflag_fdotr = 0;
const int inum = list->inum;
const int nall = atom->nlocal + atom->nghost;
const int nthreads = comm->nthreads;
const int host_start = fix->host_start_pair();
const int offload_end = fix->offload_end_pair();
const int ago = neighbor->ago;
if (fix->separate_buffers() == 0) {
fix->start_watch(TIME_PACK);
const AtomVecEllipsoid::Bonus * const bonus = avec->bonus;
const int * const ellipsoid = atom->ellipsoid;
QUAT_T * _noalias const quat = buffers->get_quat();
#if defined(_OPENMP)
#pragma omp parallel default(none) shared(eflag,vflag,buffers,fc)
#endif
{
int ifrom, ito, tid;
IP_PRE_omp_range_id_align(ifrom, ito, tid, nall, nthreads,
sizeof(ATOM_T));
if (ago != 0) buffers->thr_pack(ifrom,ito,ago);
for (int i = ifrom; i < ito; i++) {
int qi = ellipsoid[i];
if (qi > -1) {
quat[i].w = bonus[qi].quat[0];
quat[i].i = bonus[qi].quat[1];
quat[i].j = bonus[qi].quat[2];
quat[i].k = bonus[qi].quat[3];
}
}
}
quat[nall].w = (flt_t)1.0;
quat[nall].i = (flt_t)0.0;
quat[nall].j = (flt_t)0.0;
quat[nall].k = (flt_t)0.0;
fix->stop_watch(TIME_PACK);
}
if (evflag || vflag_fdotr) {
int ovflag = 0;
if (vflag_fdotr) ovflag = 2;
else if (vflag) ovflag = 1;
if (eflag) {
if (force->newton_pair) {
eval<1,1,1>(1, ovflag, buffers, fc, 0, offload_end);
eval<1,1,1>(0, ovflag, buffers, fc, host_start, inum);
} else {
eval<1,1,0>(1, ovflag, buffers, fc, 0, offload_end);
eval<1,1,0>(0, ovflag, buffers, fc, host_start, inum);
}
} else {
if (force->newton_pair) {
eval<1,0,1>(1, ovflag, buffers, fc, 0, offload_end);
eval<1,0,1>(0, ovflag, buffers, fc, host_start, inum);
} else {
eval<1,0,0>(1, ovflag, buffers, fc, 0, offload_end);
eval<1,0,0>(0, ovflag, buffers, fc, host_start, inum);
}
}
} else {
if (force->newton_pair) {
eval<0,0,1>(1, 0, buffers, fc, 0, offload_end);
eval<0,0,1>(0, 0, buffers, fc, host_start, inum);
} else {
eval<0,0,0>(1, 0, buffers, fc, 0, offload_end);
eval<0,0,0>(0, 0, buffers, fc, host_start, inum);
}
}
}
template <int EVFLAG, int EFLAG, int NEWTON_PAIR, class flt_t, class acc_t>
void PairGayBerneIntel::eval(const int offload, const int vflag,
IntelBuffers<flt_t,acc_t> *buffers,
const ForceConst<flt_t> &fc,
const int astart, const int aend)
{
const int inum = aend - astart;
if (inum == 0) return;
int nlocal, nall, minlocal;
fix->get_buffern(offload, nlocal, nall, minlocal);
const int ago = neighbor->ago;
ATOM_T * _noalias const x = buffers->get_x(offload);
QUAT_T * _noalias const quat = buffers->get_quat(offload);
const AtomVecEllipsoid::Bonus *bonus = avec->bonus;
const int *ellipsoid = atom->ellipsoid;
#ifdef _LMP_INTEL_OFFLOAD
if (fix->separate_buffers()) {
fix->start_watch(TIME_PACK);
if (offload) {
#pragma omp parallel default(none) \
shared(buffers,nlocal,nall,bonus,ellipsoid)
{
int ifrom, ito, tid;
int nthreads = comm->nthreads;
IP_PRE_omp_range_id_align(ifrom, ito, tid, nlocal,
nthreads, sizeof(ATOM_T));
if (ago != 0) buffers->thr_pack_cop(ifrom, ito, 0);
for (int i = ifrom; i < ito; i++) {
int qi = ellipsoid[i];
if (qi > -1) {
quat[i].w = bonus[qi].quat[0];
quat[i].i = bonus[qi].quat[1];
quat[i].j = bonus[qi].quat[2];
quat[i].k = bonus[qi].quat[3];
}
}
int nghost = nall - nlocal;
if (nghost) {
IP_PRE_omp_range_align(ifrom, ito, tid, nall - nlocal,
nthreads, sizeof(ATOM_T));
int offset = 0;
ifrom += nlocal;
ito += nlocal;
if (ago != 0) {
offset = fix->offload_min_ghost() - nlocal;
buffers->thr_pack_cop(ifrom, ito, offset, ago == 1);
}
for (int i = ifrom; i < ito; i++) {
int qi = ellipsoid[i + offset];
if (qi > -1) {
quat[i].w = bonus[qi].quat[0];
quat[i].i = bonus[qi].quat[1];
quat[i].j = bonus[qi].quat[2];
quat[i].k = bonus[qi].quat[3];
}
}
}
}
} else {
if (ago != 0) buffers->thr_pack_host(fix->host_min_local(), nlocal, 0);
for (int i = fix->host_min_local(); i < nlocal; i++) {
int qi = ellipsoid[i];
if (qi > -1) {
quat[i].w = bonus[qi].quat[0];
quat[i].i = bonus[qi].quat[1];
quat[i].j = bonus[qi].quat[2];
quat[i].k = bonus[qi].quat[3];
}
}
int offset = fix->host_min_ghost() - nlocal;
if (ago != 0) buffers->thr_pack_host(nlocal, nall, offset);
for (int i = nlocal; i < nall; i++) {
int qi = ellipsoid[i + offset];
if (qi > -1) {
quat[i].w = bonus[qi].quat[0];
quat[i].i = bonus[qi].quat[1];
quat[i].j = bonus[qi].quat[2];
quat[i].k = bonus[qi].quat[3];
}
}
}
fix->stop_watch(TIME_PACK);
}
#endif
// const int * _noalias const ilist = list->ilist;
const int * _noalias const numneigh = list->numneigh;
const int * _noalias const cnumneigh = buffers->cnumneigh(list);
const int * _noalias const firstneigh = buffers->firstneigh(list);
const flt_t * _noalias const special_lj = fc.special_lj;
const FC_PACKED1_T * _noalias const ijc = fc.ijc[0];
const FC_PACKED2_T * _noalias const lj34 = fc.lj34[0];
const FC_PACKED3_T * _noalias const ic = fc.ic;
const flt_t mu = fc.mu;
const flt_t gamma = fc.gamma;
const flt_t upsilon = fc.upsilon;
flt_t * const rsq_formi = fc.rsq_form[0];
flt_t * const delx_formi = fc.delx_form[0];
flt_t * const dely_formi = fc.dely_form[0];
flt_t * const delz_formi = fc.delz_form[0];
int * const jtype_formi = fc.jtype_form[0];
int * const jlist_formi = fc.jlist_form[0];
const int ntypes = atom->ntypes + 1;
const int eatom = this->eflag_atom;
// Determine how much data to transfer
int x_size, q_size, f_stride, ev_size, separate_flag;
IP_PRE_get_transfern(ago, NEWTON_PAIR, EVFLAG, EFLAG, vflag,
buffers, offload, fix, separate_flag,
x_size, q_size, ev_size, f_stride);
int tc;
FORCE_T * _noalias f_start;
acc_t * _noalias ev_global;
IP_PRE_get_buffers(offload, buffers, fix, tc, f_start, ev_global);
const int max_nbors = _max_nbors;
const int nthreads = tc;
int pad = 1;
if (offload) {
if (INTEL_MIC_NBOR_PAD > 1)
pad = INTEL_MIC_NBOR_PAD * sizeof(float) / sizeof(flt_t);
} else {
if (INTEL_NBOR_PAD > 1)
pad = INTEL_NBOR_PAD * sizeof(float) / sizeof(flt_t);
}
const int pad_width = pad;
#ifdef _LMP_INTEL_OFFLOAD
int *overflow = fix->get_off_overflow_flag();
double *timer_compute = fix->off_watch_pair();
if (offload) fix->start_watch(TIME_OFFLOAD_LATENCY);
#pragma offload target(mic:_cop) if(offload) \
in(special_lj:length(0) alloc_if(0) free_if(0)) \
in(ijc,lj34,ic:length(0) alloc_if(0) free_if(0)) \
in(rsq_formi, delx_formi, dely_formi: length(0) alloc_if(0) free_if(0)) \
in(delz_formi, jtype_formi, jlist_formi: length(0) alloc_if(0) free_if(0))\
in(firstneigh:length(0) alloc_if(0) free_if(0)) \
in(cnumneigh:length(0) alloc_if(0) free_if(0)) \
in(numneigh:length(0) alloc_if(0) free_if(0)) \
in(x:length(x_size) alloc_if(0) free_if(0)) \
in(quat:length(nall+1) alloc_if(0) free_if(0)) \
in(overflow:length(0) alloc_if(0) free_if(0)) \
in(nthreads,inum,nall,ntypes,vflag,eatom,minlocal,separate_flag) \
in(astart,nlocal,f_stride,max_nbors,mu,gamma,upsilon,offload,pad_width) \
out(f_start:length(f_stride) alloc_if(0) free_if(0)) \
out(ev_global:length(ev_size) alloc_if(0) free_if(0)) \
out(timer_compute:length(1) alloc_if(0) free_if(0)) \
signal(f_start)
#endif
{
#if defined(__MIC__) && defined(_LMP_INTEL_OFFLOAD)
*timer_compute=MIC_Wtime();
#endif
#ifdef _LMP_INTEL_OFFLOAD
if (separate_flag) {
if (separate_flag < 3) {
int all_local = nlocal;
int ghost_min = overflow[LMP_GHOST_MIN];
nlocal = overflow[LMP_LOCAL_MAX] + 1;
int nghost = overflow[LMP_GHOST_MAX] + 1 - ghost_min;
if (nghost < 0) nghost = 0;
nall = nlocal + nghost;
separate_flag--;
int flength;
if (NEWTON_PAIR) flength = nall;
else flength = nlocal;
IP_PRE_get_stride(f_stride, flength, sizeof(FORCE_T),
separate_flag);
if (nghost) {
if (nlocal < all_local || ghost_min > all_local) {
memmove(x + nlocal, x + ghost_min,
(nall - nlocal) * sizeof(ATOM_T));
memmove(quat + nlocal, quat + ghost_min,
(nall - nlocal) * sizeof(QUAT_T));
}
}
}
x[nall].x = (flt_t)INTEL_BIGP;
x[nall].y = (flt_t)INTEL_BIGP;
x[nall].z = (flt_t)INTEL_BIGP;
quat[nall].w = (flt_t)1.0;
quat[nall].i = (flt_t)0.0;
quat[nall].j = (flt_t)0.0;
quat[nall].k = (flt_t)0.0;
}
#endif
acc_t oevdwl, ov0, ov1, ov2, ov3, ov4, ov5;
if (EVFLAG) {
oevdwl = (acc_t)0.0;
if (vflag) ov0 = ov1 = ov2 = ov3 = ov4 = ov5 = (acc_t)0.0;
}
// loop over neighbors of my atoms
#if defined(_OPENMP)
#pragma omp parallel default(none) \
shared(f_start,f_stride,nlocal,nall,minlocal) \
reduction(+:oevdwl,ov0,ov1,ov2,ov3,ov4,ov5)
#endif
{
int iifrom, iito, tid;
IP_PRE_omp_range_id(iifrom, iito, tid, inum, nthreads);
iifrom += astart;
iito += astart;
FORCE_T * _noalias const f = f_start - minlocal * 2 + (tid * f_stride);
memset(f + minlocal * 2, 0, f_stride * sizeof(FORCE_T));
flt_t * _noalias const rsq_form = rsq_formi + tid * max_nbors;
flt_t * _noalias const delx_form = delx_formi + tid * max_nbors;
flt_t * _noalias const dely_form = dely_formi + tid * max_nbors;
flt_t * _noalias const delz_form = delz_formi + tid * max_nbors;
int * _noalias const jtype_form = jtype_formi + tid * max_nbors;
int * _noalias const jlist_form = jlist_formi + tid * max_nbors;
int ierror = 0;
for (int i = iifrom; i < iito; ++i) {
// const int i = ilist[ii];
const int itype = x[i].w;
const int ptr_off = itype * ntypes;
const FC_PACKED1_T * _noalias const ijci = ijc + ptr_off;
const FC_PACKED2_T * _noalias const lj34i = lj34 + ptr_off;
const int * _noalias const jlist = firstneigh + cnumneigh[i];
const int jnum = numneigh[i];
const flt_t xtmp = x[i].x;
const flt_t ytmp = x[i].y;
const flt_t ztmp = x[i].z;
flt_t a1_0, a1_1, a1_2, a1_3, a1_4, a1_5, a1_6, a1_7, a1_8;
flt_t b1_0, b1_1, b1_2, b1_3, b1_4, b1_5, b1_6, b1_7, b1_8;
flt_t g1_0, g1_1, g1_2, g1_3, g1_4, g1_5, g1_6, g1_7, g1_8;
if (ijci[itype].form == ELLIPSE_ELLIPSE) {
flt_t temp_0,temp_1,temp_2,temp_3,temp_4,temp_5,temp_6,temp_7,temp_8;
ME_quat_to_mat_trans(quat[i],a1);
ME_diag_times3(ic[itype].well,a1,temp);
ME_transpose_times3(a1,temp,b1);
ME_diag_times3(ic[itype].shape2,a1,temp);
ME_transpose_times3(a1,temp,g1);
}
acc_t fxtmp, fytmp, fztmp, fwtmp, t1tmp, t2tmp, t3tmp;
acc_t sevdwl, sv0, sv1, sv2, sv3, sv4, sv5;
fxtmp = fytmp = fztmp = t1tmp = t2tmp = t3tmp = (acc_t)0.0;
if (EVFLAG) {
if (EFLAG) fwtmp = sevdwl = (acc_t)0.0;
if (vflag==1) sv0 = sv1 = sv2 = sv3 = sv4 = sv5 = (acc_t)0.0;
}
bool multiple_forms = false;
int packed_j = 0;
for (int jj = 0; jj < jnum; jj++) {
int jm = jlist[jj];
int j = jm & NEIGHMASK;
const int jtype = x[j].w;
if (ijci[jtype].form == ELLIPSE_ELLIPSE) {
flt_t delx = x[j].x-xtmp;
flt_t dely = x[j].y-ytmp;
flt_t delz = x[j].z-ztmp;
flt_t rsq = delx * delx + dely * dely + delz * delz;
if (rsq < ijci[jtype].cutsq) {
rsq_form[packed_j] = rsq;
delx_form[packed_j] = delx;
dely_form[packed_j] = dely;
delz_form[packed_j] = delz;
jtype_form[packed_j] = jtype;
jlist_form[packed_j] = jm;
packed_j++;
}
} else
multiple_forms = true;
}
const int edge = (packed_j % pad_width);
if (edge) {
const int packed_end = packed_j + (pad_width - edge);
#if defined(LMP_SIMD_COMPILER)
#pragma loop_count min=1, max=15, avg=8
#endif
for ( ; packed_j < packed_end; packed_j++)
jlist_form[packed_j] = nall;
}
// -------------------------------------------------------------
#ifdef INTEL_V512
__assume(packed_j % INTEL_VECTOR_WIDTH == 0);
__assume(packed_j % 8 == 0);
__assume(packed_j % INTEL_MIC_VECTOR_WIDTH == 0);
#endif
#if defined(LMP_SIMD_COMPILER)
#pragma vector aligned
#pragma simd reduction(+:fxtmp,fytmp,fztmp,fwtmp,t1tmp,t2tmp,t3tmp, \
sevdwl,sv0,sv1,sv2,sv3,sv4,sv5)
#endif
for (int jj = 0; jj < packed_j; jj++) {
flt_t a2_0, a2_1, a2_2, a2_3, a2_4, a2_5, a2_6, a2_7, a2_8;
flt_t b2_0, b2_1, b2_2, b2_3, b2_4, b2_5, b2_6, b2_7, b2_8;
flt_t g2_0, g2_1, g2_2, g2_3, g2_4, g2_5, g2_6, g2_7, g2_8;
flt_t temp_0,temp_1,temp_2,temp_3,temp_4,temp_5,temp_6,temp_7,temp_8;
flt_t fforce_0, fforce_1, fforce_2, ttor_0, ttor_1, ttor_2;
flt_t rtor_0, rtor_1, rtor_2;
const int sbindex = jlist_form[jj] >> SBBITS & 3;
const int j = jlist_form[jj] & NEIGHMASK;
flt_t factor_lj = special_lj[sbindex];
const int jtype = jtype_form[jj];
const flt_t sigma = ijci[jtype].sigma;
const flt_t epsilon = ijci[jtype].epsilon;
const flt_t shape2_0 = ic[jtype].shape2[0];
const flt_t shape2_1 = ic[jtype].shape2[1];
const flt_t shape2_2 = ic[jtype].shape2[2];
flt_t one_eng, evdwl;
ME_quat_to_mat_trans(quat[j], a2);
ME_diag_times3(ic[jtype].well, a2, temp);
ME_transpose_times3(a2, temp, b2);
ME_diag_times3a(shape2, a2, temp);
ME_transpose_times3(a2, temp, g2);
flt_t tempv_0, tempv_1, tempv_2, tempv2_0, tempv2_1, tempv2_2;
flt_t temp1, temp2, temp3;
flt_t r12hat_0, r12hat_1, r12hat_2;
ME_normalize3(delx_form[jj], dely_form[jj], delz_form[jj], r12hat);
flt_t r = sqrt(rsq_form[jj]);
// compute distance of closest approach
flt_t g12_0, g12_1, g12_2, g12_3, g12_4, g12_5, g12_6, g12_7, g12_8;
ME_plus3(g1, g2, g12);
flt_t kappa_0, kappa_1, kappa_2;
ME_mldivide3(g12, delx_form[jj], dely_form[jj], delz_form[jj],
kappa, ierror);
// tempv = G12^-1*r12hat
flt_t inv_r = (flt_t)1.0 / r;
tempv_0 = kappa_0 * inv_r;
tempv_1 = kappa_1 * inv_r;
tempv_2 = kappa_2 * inv_r;
flt_t sigma12 = ME_dot3(r12hat, tempv);
sigma12 = std::pow((flt_t)0.5 * sigma12,(flt_t) - 0.5);
flt_t h12 = r - sigma12;
// energy
// compute u_r
flt_t varrho = sigma / (h12 + gamma * sigma);
flt_t varrho6 = std::pow(varrho, (flt_t)6.0);
flt_t varrho12 = varrho6 * varrho6;
flt_t u_r = (flt_t)4.0 * epsilon * (varrho12 - varrho6);
// compute eta_12
flt_t eta = (flt_t)2.0 * ijci[jtype].lshape;
flt_t det_g12 = ME_det3(g12);
eta = std::pow(eta / det_g12, upsilon);
// compute chi_12
flt_t b12_0, b12_1, b12_2, b12_3, b12_4, b12_5, b12_6, b12_7, b12_8;
flt_t iota_0, iota_1, iota_2;
ME_plus3(b1, b2, b12);
ME_mldivide3(b12, delx_form[jj], dely_form[jj], delz_form[jj],
iota, ierror);
// tempv = G12^-1*r12hat
tempv_0 = iota_0 * inv_r;
tempv_1 = iota_1 * inv_r;
tempv_2 = iota_2 * inv_r;
flt_t chi = ME_dot3(r12hat, tempv);
chi = std::pow(chi * (flt_t)2.0, mu);
// force
// compute dUr/dr
temp1 = ((flt_t)2.0 * varrho12 * varrho - varrho6 * varrho) /
sigma;
temp1 = temp1 * (flt_t)24.0 * epsilon;
flt_t u_slj = temp1 * std::pow(sigma12, (flt_t)3.0) * (flt_t)0.5;
flt_t dUr_0, dUr_1, dUr_2;
temp2 = ME_dot3(kappa, r12hat);
flt_t uslj_rsq = u_slj / rsq_form[jj];
dUr_0 = temp1 * r12hat_0 + uslj_rsq * (kappa_0 - temp2 * r12hat_0);
dUr_1 = temp1 * r12hat_1 + uslj_rsq * (kappa_1 - temp2 * r12hat_1);
dUr_2 = temp1 * r12hat_2 + uslj_rsq * (kappa_2 - temp2 * r12hat_2);
// compute dChi_12/dr
flt_t dchi_0, dchi_1, dchi_2;
temp1 = ME_dot3(iota, r12hat);
temp2 = (flt_t)-4.0 / rsq_form[jj] * mu *
std::pow(chi, (mu - (flt_t)1.0) / mu);
dchi_0 = temp2 * (iota_0 - temp1 * r12hat_0);
dchi_1 = temp2 * (iota_1 - temp1 * r12hat_1);
dchi_2 = temp2 * (iota_2 - temp1 * r12hat_2);
temp1 = -eta * u_r;
temp2 = eta * chi;
fforce_0 = temp1 * dchi_0 - temp2 * dUr_0;
fforce_1 = temp1 * dchi_1 - temp2 * dUr_1;
fforce_2 = temp1 * dchi_2 - temp2 * dUr_2;
// torque for particle 1 and 2
// compute dUr
tempv_0 = -uslj_rsq * kappa_0;
tempv_1 = -uslj_rsq * kappa_1;
tempv_2 = -uslj_rsq * kappa_2;
ME_vecmat(kappa, g1, tempv2);
ME_cross3(tempv, tempv2, dUr);
flt_t dUr2_0, dUr2_1, dUr2_2;
if (NEWTON_PAIR || j < nlocal) {
ME_vecmat(kappa, g2, tempv2);
ME_cross3(tempv, tempv2, dUr2);
}
// compute d_chi
ME_vecmat(iota, b1, tempv);
ME_cross3(tempv, iota, dchi);
temp1 = (flt_t)-4.0 / rsq_form[jj];
dchi_0 *= temp1;
dchi_1 *= temp1;
dchi_2 *= temp1;
flt_t dchi2_0, dchi2_1, dchi2_2;
if (NEWTON_PAIR || j < nlocal) {
ME_vecmat(iota, b2, tempv);
ME_cross3(tempv, iota, dchi2);
dchi2_0 *= temp1;
dchi2_1 *= temp1;
dchi2_2 *= temp1;
}
// compute d_eta
flt_t deta_0, deta_1, deta_2;
deta_0 = deta_1 = deta_2 = (flt_t)0.0;
ME_compute_eta_torque(g12, a1, shape2, temp);
temp1 = -eta * upsilon;
tempv_0 = temp1 * temp_0;
tempv_1 = temp1 * temp_1;
tempv_2 = temp1 * temp_2;
ME_mv0_cross3(a1, tempv, tempv2);
deta_0 += tempv2_0;
deta_1 += tempv2_1;
deta_2 += tempv2_2;
tempv_0 = temp1 * temp_3;
tempv_1 = temp1 * temp_4;
tempv_2 = temp1 * temp_5;
ME_mv1_cross3(a1, tempv, tempv2);
deta_0 += tempv2_0;
deta_1 += tempv2_1;
deta_2 += tempv2_2;
tempv_0 = temp1 * temp_6;
tempv_1 = temp1 * temp_7;
tempv_2 = temp1 * temp_8;
ME_mv2_cross3(a1, tempv, tempv2);
deta_0 += tempv2_0;
deta_1 += tempv2_1;
deta_2 += tempv2_2;
// compute d_eta for particle 2
flt_t deta2_0, deta2_1, deta2_2;
if (NEWTON_PAIR || j < nlocal) {
deta2_0 = deta2_1 = deta2_2 = (flt_t)0.0;
ME_compute_eta_torque(g12, a2, shape2, temp);
tempv_0 = temp1 * temp_0;
tempv_1 = temp1 * temp_1;
tempv_2 = temp1 * temp_2;
ME_mv0_cross3(a2, tempv, tempv2);
deta2_0 += tempv2_0;
deta2_1 += tempv2_1;
deta2_2 += tempv2_2;
tempv_0 = temp1 * temp_3;
tempv_1 = temp1 * temp_4;
tempv_2 = temp1 * temp_5;
ME_mv1_cross3(a2, tempv, tempv2);
deta2_0 += tempv2_0;
deta2_1 += tempv2_1;
deta2_2 += tempv2_2;
tempv_0 = temp1 * temp_6;
tempv_1 = temp1 * temp_7;
tempv_2 = temp1 * temp_8;
ME_mv2_cross3(a2, tempv, tempv2);
deta2_0 += tempv2_0;
deta2_1 += tempv2_1;
deta2_2 += tempv2_2;
}
// torque
temp1 = u_r * eta;
temp2 = u_r * chi;
temp3 = chi * eta;
ttor_0 = (temp1 * dchi_0 + temp2 * deta_0 + temp3 * dUr_0) *
(flt_t)-1.0;
ttor_1 = (temp1 * dchi_1 + temp2 * deta_1 + temp3 * dUr_1) *
(flt_t)-1.0;
ttor_2 = (temp1 * dchi_2 + temp2 * deta_2 + temp3 * dUr_2) *
(flt_t)-1.0;
if (NEWTON_PAIR || j < nlocal) {
rtor_0 = (temp1 * dchi2_0 + temp2 * deta2_0 + temp3 * dUr2_0) *
(flt_t)-1.0;
rtor_1 = (temp1 * dchi2_1 + temp2 * deta2_1 + temp3 * dUr2_1) *
(flt_t)-1.0;
rtor_2 = (temp1 * dchi2_2 + temp2 * deta2_2 + temp3 * dUr2_2) *
(flt_t)-1.0;
}
one_eng = temp1 * chi;
#ifndef INTEL_VMASK
if (jlist_form[jj] == nall) {
one_eng = (flt_t)0.0;
fforce_0 = 0.0;
fforce_1 = 0.0;
fforce_2 = 0.0;
ttor_0 = 0.0;
ttor_1 = 0.0;
ttor_2 = 0.0;
rtor_0 = 0.0;
rtor_1 = 0.0;
rtor_2 = 0.0;
}
#endif
fforce_0 *= factor_lj;
fforce_1 *= factor_lj;
fforce_2 *= factor_lj;
ttor_0 *= factor_lj;
ttor_1 *= factor_lj;
ttor_2 *= factor_lj;
#ifdef INTEL_VMASK
if (jlist_form[jj] < nall) {
#endif
fxtmp += fforce_0;
fytmp += fforce_1;
fztmp += fforce_2;
t1tmp += ttor_0;
t2tmp += ttor_1;
t3tmp += ttor_2;
if (NEWTON_PAIR || j < nlocal) {
rtor_0 *= factor_lj;
rtor_1 *= factor_lj;
rtor_2 *= factor_lj;
int jp = j * 2;
f[jp].x -= fforce_0;
f[jp].y -= fforce_1;
f[jp].z -= fforce_2;
jp++;
f[jp].x += rtor_0;
f[jp].y += rtor_1;
f[jp].z += rtor_2;
}
if (EVFLAG) {
flt_t ev_pre = (flt_t)0.0;
if (NEWTON_PAIR || i < nlocal)
ev_pre += (flt_t)0.5;
if (NEWTON_PAIR || j < nlocal)
ev_pre += (flt_t)0.5;
if (EFLAG) {
evdwl = factor_lj * one_eng;
sevdwl += ev_pre * evdwl;
if (eatom) {
if (NEWTON_PAIR || i < nlocal)
fwtmp += (flt_t)0.5 * evdwl;
if (NEWTON_PAIR || j < nlocal)
f[j*2].w += (flt_t)0.5 * evdwl;
}
}
if (vflag == 1) {
ev_pre *= (flt_t)-1.0;
sv0 += ev_pre * delx_form[jj] * fforce_0;
sv1 += ev_pre * dely_form[jj] * fforce_1;
sv2 += ev_pre * delz_form[jj] * fforce_2;
sv3 += ev_pre * delx_form[jj] * fforce_1;
sv4 += ev_pre * delx_form[jj] * fforce_2;
sv5 += ev_pre * dely_form[jj] * fforce_2;
}
} // EVFLAG
#ifdef INTEL_VMASK
}
#endif
} // for jj
// -------------------------------------------------------------
if (multiple_forms)
ierror = 2;
int ip = i * 2;
f[ip].x += fxtmp;
f[ip].y += fytmp;
f[ip].z += fztmp;
ip++;
f[ip].x += t1tmp;
f[ip].y += t2tmp;
f[ip].z += t3tmp;
if (EVFLAG) {
if (EFLAG) {
if (eatom) f[i * 2].w += fwtmp;
oevdwl += sevdwl;
}
if (vflag == 1) {
ov0 += sv0;
ov1 += sv1;
ov2 += sv2;
ov3 += sv3;
ov4 += sv4;
ov5 += sv5;
}
}
} // for i
int o_range;
if (NEWTON_PAIR)
o_range = nall;
else
o_range = nlocal;
if (offload == 0) o_range -= minlocal;
IP_PRE_omp_range_align(iifrom, iito, tid, o_range, nthreads,
sizeof(FORCE_T));
const int two_iito = iito * 2;
acc_t *facc = &(f_start[0].x);
const int sto = two_iito * 4;
const int fst4 = f_stride * 4;
#if defined(_OPENMP)
#pragma omp barrier
#endif
int t_off = f_stride;
if (EFLAG && eatom) {
for (int t = 1; t < nthreads; t++) {
#if defined(LMP_SIMD_COMPILER)
#pragma vector nontemporal
#pragma novector
#endif
for (int n = iifrom * 2; n < two_iito; n++) {
f_start[n].x += f_start[n + t_off].x;
f_start[n].y += f_start[n + t_off].y;
f_start[n].z += f_start[n + t_off].z;
f_start[n].w += f_start[n + t_off].w;
}
t_off += f_stride;
}
} else {
for (int t = 1; t < nthreads; t++) {
#if defined(LMP_SIMD_COMPILER)
#pragma vector nontemporal
#pragma novector
#endif
for (int n = iifrom * 2; n < two_iito; n++) {
f_start[n].x += f_start[n + t_off].x;
f_start[n].y += f_start[n + t_off].y;
f_start[n].z += f_start[n + t_off].z;
}
t_off += f_stride;
}
}
if (EVFLAG) {
if (vflag==2) {
const ATOM_T * _noalias const xo = x + minlocal;
#if defined(LMP_SIMD_COMPILER)
#pragma vector nontemporal
#pragma novector
#endif
for (int n = iifrom; n < iito; n++) {
const int nt2 = n * 2;
ov0 += f_start[nt2].x * xo[n].x;
ov1 += f_start[nt2].y * xo[n].y;
ov2 += f_start[nt2].z * xo[n].z;
ov3 += f_start[nt2].y * xo[n].x;
ov4 += f_start[nt2].z * xo[n].x;
ov5 += f_start[nt2].z * xo[n].y;
}
}
}
if (ierror)
f_start[1].w = ierror;
} // omp
if (EVFLAG) {
if (EFLAG) {
ev_global[0] = oevdwl;
ev_global[1] = (acc_t)0.0;
}
if (vflag) {
ev_global[2] = ov0;
ev_global[3] = ov1;
ev_global[4] = ov2;
ev_global[5] = ov3;
ev_global[6] = ov4;
ev_global[7] = ov5;
}
}
#if defined(__MIC__) && defined(_LMP_INTEL_OFFLOAD)
*timer_compute = MIC_Wtime() - *timer_compute;
#endif
} // offload
if (offload)
fix->stop_watch(TIME_OFFLOAD_LATENCY);
else
fix->stop_watch(TIME_HOST_PAIR);
if (EVFLAG)
fix->add_result_array(f_start, ev_global, offload, eatom, 0, 2);
else
fix->add_result_array(f_start, 0, offload, 0, 0, 2);
}
/* ---------------------------------------------------------------------- */
void PairGayBerneIntel::init_style()
{
PairGayBerne::init_style();
neighbor->requests[neighbor->nrequest-1]->intel = 1;
int ifix = modify->find_fix("package_intel");
if (ifix < 0)
error->all(FLERR,
"The 'package intel' command is required for /intel styles");
fix = static_cast<FixIntel *>(modify->fix[ifix]);
fix->pair_init_check();
#ifdef _LMP_INTEL_OFFLOAD
if (force->newton_pair) fix->set_offload_noghost(1);
_cop = fix->coprocessor_number();
#endif
if (fix->precision() == FixIntel::PREC_MODE_MIXED)
pack_force_const(force_const_single, fix->get_mixed_buffers());
else if (fix->precision() == FixIntel::PREC_MODE_DOUBLE)
pack_force_const(force_const_double, fix->get_double_buffers());
else
pack_force_const(force_const_single, fix->get_single_buffers());
}
/* ---------------------------------------------------------------------- */
template <class flt_t, class acc_t>
void PairGayBerneIntel::pack_force_const(ForceConst<flt_t> &fc,
IntelBuffers<flt_t,acc_t> *buffers)
{
int tp1 = atom->ntypes + 1;
_max_nbors = buffers->get_max_nbors();
int mthreads = comm->nthreads;
if (mthreads < buffers->get_off_threads())
mthreads = buffers->get_off_threads();
fc.set_ntypes(tp1, _max_nbors, mthreads, memory, _cop);
buffers->set_ntypes(tp1);
flt_t **cutneighsq = buffers->get_cutneighsq();
// Repeat cutsq calculation because done after call to init_style
double cut, cutneigh;
for (int i = 1; i <= atom->ntypes; i++) {
for (int j = i; j <= atom->ntypes; j++) {
if (setflag[i][j] != 0 || (setflag[i][i] != 0 && setflag[j][j] != 0)) {
cut = init_one(i,j);
cutneigh = cut + neighbor->skin;
cutsq[i][j] = cutsq[j][i] = cut*cut;
cutneighsq[i][j] = cutneighsq[j][i] = cutneigh * cutneigh;
}
}
}
for (int i = 0; i < 4; i++) {
fc.special_lj[i] = force->special_lj[i];
fc.special_lj[0] = 1.0;
}
fc.gamma = gamma;
fc.upsilon = upsilon;
fc.mu = mu;
for (int i = 0; i < tp1; i++) {
for (int j = 0; j < tp1; j++) {
fc.ijc[i][j].lj1 = lj1[i][j];
fc.ijc[i][j].lj2 = lj2[i][j];
fc.ijc[i][j].cutsq = cutsq[i][j];
fc.ijc[i][j].offset = offset[i][j];
fc.ijc[i][j].sigma = sigma[i][j];
fc.ijc[i][j].epsilon = epsilon[i][j];
fc.ijc[i][j].form = form[i][j];
fc.ijc[i][j].lshape = lshape[i] * lshape[j];
fc.lj34[i][j].lj3 = lj3[i][j];
fc.lj34[i][j].lj4 = lj4[i][j];
}
for (int j = 0; j < 4; j++) {
fc.ic[i].shape2[j] = shape2[i][j];
fc.ic[i].well[j] = well[i][j];
}
}
#ifdef _LMP_INTEL_OFFLOAD
if (_cop < 0) return;
flt_t * special_lj = fc.special_lj;
FC_PACKED1_T *oijc = fc.ijc[0];
FC_PACKED2_T *olj34 = fc.lj34[0];
FC_PACKED3_T *oic = fc.ic;
flt_t * ocutneighsq = cutneighsq[0];
int tp1sq = tp1 * tp1;
if (oijc != NULL && oic != NULL) {
#pragma offload_transfer target(mic:_cop) \
in(special_lj: length(4) alloc_if(0) free_if(0)) \
in(oijc,olj34: length(tp1sq) alloc_if(0) free_if(0)) \
in(oic: length(tp1) alloc_if(0) free_if(0)) \
in(ocutneighsq: length(tp1sq))
}
#endif
}
/* ---------------------------------------------------------------------- */
template <class flt_t>
void PairGayBerneIntel::ForceConst<flt_t>::set_ntypes(const int ntypes,
const int one_length,
const int nthreads,
Memory *memory,
const int cop) {
if (ntypes != _ntypes) {
if (_ntypes > 0) {
fc_packed3 *oic = ic;
#ifdef _LMP_INTEL_OFFLOAD
flt_t * ospecial_lj = special_lj;
fc_packed1 *oijc = ijc[0];
fc_packed2 *olj34 = lj34[0];
flt_t * orsq_form = rsq_form[0];
flt_t * odelx_form = delx_form[0];
flt_t * odely_form = dely_form[0];
flt_t * odelz_form = delz_form[0];
int * ojtype_form = jtype_form[0];
int * ojlist_form = jlist_form[0];
if (ospecial_lj != NULL && oijc != NULL && olj34 != NULL &&
orsq_form != NULL && odelx_form != NULL && odely_form != NULL &&
odelz_form != NULL && ojtype_form != NULL && ojlist_form != NULL &&
_cop >= 0) {
#pragma offload_transfer target(mic:_cop) \
nocopy(ospecial_lj, oijc, olj34, oic: alloc_if(0) free_if(1)) \
nocopy(orsq_form, odelx_form, odely_form: alloc_if(0) free_if(1)) \
nocopy(odelz_form, ojtype_form, ojlist_form: alloc_if(0) free_if(1))
}
#endif
_memory->destroy(oic);
_memory->destroy(ijc);
_memory->destroy(lj34);
_memory->destroy(rsq_form);
_memory->destroy(delx_form);
_memory->destroy(dely_form);
_memory->destroy(delz_form);
_memory->destroy(jtype_form);
_memory->destroy(jlist_form);
}
if (ntypes > 0) {
_cop = cop;
memory->create(ijc, ntypes, ntypes, "fc.ijc");
memory->create(lj34, ntypes, ntypes, "fc.lj34");
memory->create(ic, ntypes, "fc.ic");
memory->create(rsq_form, nthreads, one_length, "rsq_form");
memory->create(delx_form, nthreads, one_length, "delx_form");
memory->create(dely_form, nthreads, one_length, "dely_form");
memory->create(delz_form, nthreads, one_length, "delz_form");
memory->create(jtype_form, nthreads, one_length, "jtype_form");
memory->create(jlist_form, nthreads, one_length, "jlist_form");
for (int zn = 0; zn < nthreads; zn++)
for (int zo = 0; zo < one_length; zo++) {
rsq_form[zn][zo] = 10.0;
delx_form[zn][zo] = 10.0;
dely_form[zn][zo] = 10.0;
delz_form[zn][zo] = 10.0;
jtype_form[zn][zo] = 1;
jlist_form[zn][zo] = 0;
}
#ifdef _LMP_INTEL_OFFLOAD
flt_t * ospecial_lj = special_lj;
fc_packed1 *oijc = ijc[0];
fc_packed2 *olj34 = lj34[0];
fc_packed3 *oic = ic;
flt_t * orsq_form = rsq_form[0];
flt_t * odelx_form = delx_form[0];
flt_t * odely_form = dely_form[0];
flt_t * odelz_form = delz_form[0];
int * ojtype_form = jtype_form[0];
int * ojlist_form = jlist_form[0];
int off_onel = one_length * nthreads;
int tp1sq = ntypes*ntypes;
if (ospecial_lj != NULL && oijc != NULL && olj34 != NULL &&
oic != NULL && orsq_form != NULL && odelx_form != NULL &&
odely_form != NULL && odelz_form != NULL && ojtype_form !=NULL &&
ojlist_form !=NULL && cop >= 0) {
#pragma offload_transfer target(mic:cop) \
nocopy(ospecial_lj: length(4) alloc_if(1) free_if(0)) \
nocopy(oijc,olj34: length(tp1sq) alloc_if(1) free_if(0)) \
nocopy(oic: length(ntypes) alloc_if(1) free_if(0)) \
in(orsq_form: length(off_onel) alloc_if(1) free_if(0)) \
in(odelx_form: length(off_onel) alloc_if(1) free_if(0)) \
in(odely_form: length(off_onel) alloc_if(1) free_if(0)) \
in(odelz_form: length(off_onel) alloc_if(1) free_if(0)) \
in(ojtype_form: length(off_onel) alloc_if(1) free_if(0)) \
in(ojlist_form: length(off_onel) alloc_if(1) free_if(0))
}
#endif
}
}
_ntypes = ntypes;
_memory = memory;
}
| 32.760731 | 79 | 0.557857 | luwei0917 |
c1e419456001f698245dfa37647536f3b621cf1c | 3,597 | cpp | C++ | src/mem/Pem.cpp | OmniNegro123/med | 48b00bfb9319f735a2406ff2efe7253c46007236 | [
"BSD-3-Clause"
] | 37 | 2015-10-05T17:44:20.000Z | 2022-03-24T02:55:04.000Z | src/mem/Pem.cpp | OmniNegro123/med | 48b00bfb9319f735a2406ff2efe7253c46007236 | [
"BSD-3-Clause"
] | 6 | 2017-04-01T02:26:22.000Z | 2022-02-19T07:46:29.000Z | src/mem/Pem.cpp | OmniNegro123/med | 48b00bfb9319f735a2406ff2efe7253c46007236 | [
"BSD-3-Clause"
] | 4 | 2020-07-23T17:27:36.000Z | 2021-12-25T20:29:56.000Z | #include <cinttypes>
#include <cstring>
#include <cstdio>
#include <iostream>
#include "mem/Pem.hpp"
#include "med/MedCommon.hpp"
#include "med/MedException.hpp"
#include "med/ScanParser.hpp"
#include "med/MedTypes.hpp"
#include "med/MemOperator.hpp"
Pem::Pem(size_t size, MemIO* memio) : Mem(size) {
this->memio = memio;
scanType = ScanType::Unknown;
}
Pem::Pem(Address addr, size_t size, MemIO* memio) : Mem(size) {
this->memio = memio;
setAddress(addr);
scanType = ScanType::Unknown;
}
Pem::~Pem() {}
string Pem::bytesToString(Byte* buf, const string& scanType) {
if (scanType == SCAN_TYPE_CUSTOM) {
return memToString(buf, SCAN_TYPE_INT_8);
}
return memToString(buf, scanType);
}
string Pem::getValue(const string& scanType) {
MemPtr pem = memio->read(address, size);
if (!pem) {
return "(invalid)";
}
Byte* buf = pem->getData();
return Pem::bytesToString(buf, scanType);
}
string Pem::getValue() {
string scanType = getScanType();
return getValue(scanType);
}
BytePtr Pem::getValuePtr(int n) {
int size = n > 0 ? n : this->size;
BytePtr buf(new Byte[size]);
MemPtr pem = memio->read(address, size);
if (!pem) {
return NULL;
}
memcpy(buf.get(), pem->getData(), size);
return buf;
}
string Pem::getScanType() {
return scanTypeToString(scanType);
}
SizedBytes Pem::stringToBytes(const string& value, const string& scanType) {
// If scanType is string, it will just copy all
if (scanType == SCAN_TYPE_STRING) {
int size = MAX_STRING_SIZE;
Byte* buf = new Byte[size];
sprintf((char*)buf, "%s", value.c_str());
int length = strlen((char*)buf);
BytePtr data(new Byte[length]);
memcpy(data.get(), buf, length);
delete[] buf;
return SizedBytes(data, length);
}
else { // Allows parse comma
vector<string> tokens = ScanParser::getValues(value);
int size = scanTypeToSize(stringToScanType(scanType));
BytePtr data(new Byte[size * tokens.size()]);
Byte* pointer = data.get();
for (size_t i = 0; i < tokens.size(); i++) {
stringToMemory(tokens[i], stringToScanType(scanType), pointer);
pointer += size;
}
return SizedBytes(data, size * tokens.size());
}
}
void Pem::setValue(const string& value, const string& scanType) {
SizedBytes buffer = Pem::stringToBytes(value, scanType);
Byte* bytes = buffer.getBytes();
int size = buffer.getSize();
MemPtr mem(new Mem(size));
mem->setAddress(address);
memcpy(mem->getData(), bytes, size);
memio->write(address, mem, size);
}
void Pem::setScanType(const string& scanType) {
this->scanType = stringToScanType(scanType);
size_t newSize;
Byte* newData;
Byte* temp;
if (this->scanType == ScanType::String) {
newSize = MAX_STRING_SIZE;
newData = new Byte[newSize];
}
else {
newSize = scanTypeToSize(this->scanType);
newData = new Byte[newSize];
}
temp = data;
data = newData;
size = newSize;
delete[] temp;
}
MemIO* Pem::getMemIO() {
return memio;
}
void Pem::rememberValue(const string& value, const string& scanType) {
rememberedValue = Pem::stringToBytes(value, scanType);
}
void Pem::rememberValue(Byte* value, size_t size) {
rememberedValue = SizedBytes(value, size);
}
string Pem::recallValue(const string& scanType) {
if (rememberedValue.isEmpty()) {
return "";
}
return Pem::bytesToString(rememberedValue.getBytes(), scanType);
}
Byte* Pem::recallValuePtr() {
return rememberedValue.getBytes();
}
PemPtr Pem::convertToPemPtr(MemPtr mem, MemIO* memio) {
return PemPtr(new Pem(mem->getAddress(), mem->getSize(), memio));
}
| 23.98 | 76 | 0.671115 | OmniNegro123 |
c1e6d152166ecd91c9d8301fab3452eef9ef214c | 1,488 | cpp | C++ | UVa 12961 - Lottery/sample/12961 - Lottery.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2020-11-24T03:17:21.000Z | 2020-11-24T03:17:21.000Z | UVa 12961 - Lottery/sample/12961 - Lottery.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | null | null | null | UVa 12961 - Lottery/sample/12961 - Lottery.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2021-04-11T16:22:31.000Z | 2021-04-11T16:22:31.000Z | #include <bits/stdc++.h>
using namespace std;
class XOR_GAUSSIAN { // XOR Gaussian Elimination
public:
static const int MAXN = 32767, MAXM = 64;
char mtx[MAXN][MAXM+1], varX[MAXN];
int compute(int n, int m) {
int row = 0, col = 0, arb = 0;
int equ = n, var = m;
while (row < equ && col < var) {
int c = row;
for (int i = row; i < equ; i++)
if (mtx[i][col])
c = i;
for (int i = 0; i <= var; i++)
swap(mtx[c][i], mtx[row][i]);
if (mtx[row][col] == 0) {
col++, arb++;
continue;
}
for (int i = 0; i < equ; i++) {
if (i == row || mtx[i][col] == 0) continue;
for (int j = var; j >= 0; j--)
mtx[i][j] ^= mtx[row][j];
}
row++, col++;
}
return row;
memset(varX, 0, sizeof(varX));
for (int i = 0, j; i < equ; i++) {
if (mtx[i][var] == 0)
continue;
for (j = 0; j < var && mtx[i][j] == 0; j++);
varX[j] = mtx[i][var];
}
}
} gauss;
int main() {
int n, m, x;
while (scanf("%d %d", &n, &m) == 2) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
scanf("%d", &x);
gauss.mtx[i][j] = x&1;
}
}
int rank = gauss.compute(n, m);
if (rank < m) puts("S");
else {
if (n > rank) puts("N"); // for zeroes
else puts("S");
}
}
return 0;
}
/*
4 3
0 0 1
0 0 1
0 0 1
0 1 0
2 3
1 2 3
5 6 7
3 3
3 2 1
6 5 4
4 4 4
4 3
9 4 7
4 4 4
2 7 2
2 2 1
4 2
0 0
0 1
1 0
1 1
*/
| 17.927711 | 50 | 0.43078 | tadvi |
c1eaf17fe306911b6779f75d8a108fd00525c34f | 5,538 | cpp | C++ | Turtle/Event.cpp | mirek-fidler/Turtle | fd413460c3d92c9a85fc620f6f3db50d96f3be2f | [
"BSD-2-Clause"
] | 2 | 2021-01-07T20:30:16.000Z | 2021-02-11T21:33:07.000Z | Turtle/Event.cpp | mirek-fidler/Turtle | fd413460c3d92c9a85fc620f6f3db50d96f3be2f | [
"BSD-2-Clause"
] | null | null | null | Turtle/Event.cpp | mirek-fidler/Turtle | fd413460c3d92c9a85fc620f6f3db50d96f3be2f | [
"BSD-2-Clause"
] | null | null | null | #include "Turtle.h"
#define LLOG(x) // RLOG(x)
#define LDUMP(x) // RDUMP(x)
#define LTIMING(x)
namespace Upp {
static bool sQuit; // Ctrl::IsEndSession() would be much better to use had it been implemented.
static BiVector<String> sEventQueue;
Point ReadPoint(CParser& p)
{
Point pt;
pt.x = p.ReadInt();
pt.y = p.ReadInt();
return pt;
}
bool TurtleServer::ProcessEvent(bool *quit)
{
if(!IsWaitingEvent())
return false;
while(sEventQueue.GetCount() >= 2
&& *sEventQueue[0] == 'M'
&& *sEventQueue[1] == 'M')
sEventQueue.DropHead(); // MouseMove compression
String event = sEventQueue[0];
sEventQueue.DropHead();
LLOG("Processing event " << event);
CParser p(event);
try
{
if(p.Id("i"))
{
ResetImageCache();
}
else
if(p.Id("R"))
{
Resize(p);
}
else
if(p.Id("M"))
{
MouseMove(p);
}
else
if(p.Id("W"))
{
MouseWheel(p);
}
else
if(p.Id("I"))
{
mousein = true;
}
else
if(p.Id("O"))
{
mousebuttons = 0;
mousein = false;
}
else
if(p.Id("D"))
{
MouseButton(Ctrl::DOWN, p);
}
else
if(p.Id("U"))
{
MouseButton(Ctrl::UP, p);
}
else
if(p.Id("K"))
{
KeyDown(event, p);
}
else
if(p.Id("k"))
{
KeyUp(event, p);
}
else
if(p.Id("C"))
{
KeyPress(event, p);
}
}
catch(const CParser::Error&)
{
LLOG("ProcessEvent() -> Parser error");
}
return true;
}
void TurtleServer::WaitEvent(int ms)
{
websocket.Do();
SocketWaitEvent we;
websocket.AddTo(we);
we.Wait(ms);
}
bool TurtleServer::IsWaitingEvent()
{
websocket.Do();
String s = websocket.Receive();
if(websocket.IsClosed()) {
Ctrl::EndSession();
sQuit = true; // Ugly..
return false;
}
if(s.GetCount() == 0)
return sEventQueue.GetCount();
LLOG("Received data " << s);
StringStream ss(s);
while(!ss.IsEof()) {
String s = ss.GetLine();
CParser p(s);
try
{
if(p.Id("S")) {
uint32 l = p.ReadNumber();
uint32 h = p.ReadNumber();
recieved_update_serial = MAKEQWORD(l, h);
stat_client_ms = p.ReadNumber();
}
else
sEventQueue.AddTail(s);
}
catch(const CParser::Error&)
{
LLOG("IsWaitingEvent() -> Parser error.");
}
}
if(recieved_update_serial == serial_0) {
serial_0 = 0;
stat_roundtrip_ms = msecs() - serial_time0;
serial_time0 = Null;
}
if(websocket.IsError())
LLOG("ERROR: " << websocket.GetErrorDesc());
return sEventQueue.GetCount();
}
void TurtleServer::SyncClient()
{
while(recieved_update_serial < update_serial && !sQuit) {
Ctrl::GuiSleep(10);
IsWaitingEvent();
}
}
void TurtleServer::MouseButton(dword event, CParser& p)
{
auto MaxDistance = [](Point a, Point b) -> int
{
return IsNull(a) ? INT_MAX : max(abs(a.x - b.x), abs(a.y - b.y));
};
static int64 sMouseDownTime;
static Point sMouseDownPos;
int bt = p.ReadInt();
Point pt = ReadPoint(p);
int64 tm = p.ReadInt64();
dword down = (dword) event == Ctrl::DOWN;
dword bt2 = decode(bt, 0, (1 << 0), 2, (1 << 1), (1 << 2));
mousebuttons = (mousebuttons & ~bt2) | ((dword)-(int32)down & bt2); // Toggles button flags.
if(event == Ctrl::DOWN) {
if(MaxDistance(sMouseDownPos, pt) < GUI_DragDistance() && tm - sMouseDownTime < 800) {
event = Ctrl::DOUBLE;
sMouseDownTime = 0;
}
else {
sMouseDownPos = pt;
sMouseDownTime = tm;
}
}
ReadModifierKeys(p);
Ctrl::DoMouseFB(decode(bt, 0, Ctrl::LEFT, 2, Ctrl::RIGHT, Ctrl::MIDDLE) | event, pt, 0);
}
void TurtleServer::MouseWheel(CParser& p)
{
double w = p.ReadDouble();
Point pt = ReadPoint(p);
ReadModifierKeys(p);
Ctrl::DoMouseFB(Ctrl::MOUSEWHEEL, pt, w < 0 ? 120 : -120);
}
void TurtleServer::MouseMove(CParser& p)
{
Point pt = ReadPoint(p);
ReadModifierKeys(p);
Ctrl::DoMouseFB(Ctrl::MOUSEMOVE, pt, 0);
}
void TurtleServer::KeyDown(const String& event, CParser& p)
{
int count = 1;
int code = p.ReadInt();
int which = p.ReadInt();
for(;;) {
if(sEventQueue.GetCount()
&& sEventQueue[0] == event) { // Chrome autorepeat
sEventQueue.DropHead();
count++;
}
else
if(sEventQueue.GetCount() >= 2
&& *sEventQueue[0] == 'C'
&& sEventQueue[1] == event) { // Firefox autorepeat
String h = sEventQueue[0];
sEventQueue.DropHead();
sEventQueue.DropHead();
sEventQueue.AddHead(h);
count++;
}
else
break;
}
ReadModifierKeys(p);
Ctrl::DoKeyFB(TranslateWebKeyToK(which), count);
}
void TurtleServer::KeyUp(const String& event, CParser& p)
{
int code = p.ReadInt();
int which = p.ReadInt();
ReadModifierKeys(p);
Ctrl::DoKeyFB(TranslateWebKeyToK(which) | K_KEYUP, 1);
}
void TurtleServer::KeyPress(const String& event, CParser& p)
{
int code = p.ReadInt();
int which = p.ReadInt();
ReadModifierKeys(p);
while(sEventQueue.GetCount() && sEventQueue[0] == event) // 'K_'s are not there anymore
sEventQueue.DropHead();
if(which && !GetAlt() && !GetCtrl() && findarg(which, 0x09, 0x0D, 0x20) < 0)
Ctrl::DoKeyFB(which, 1);
}
void TurtleServer::Resize(CParser& p)
{
desktopsize = ReadPoint(p);
SetCanvasSize(desktopsize);
Ctrl::SetDesktopSize(desktopsize);
}
void TurtleServer::SetMouseCursor(const Image& image)
{
int64 q = image.GetAuxData();
if(q) {
Put8(STD_CURSORIMAGE);
Put8(clamp((int)q, 1, 16));
}
else {
Point pt = image.GetHotSpot();
String h;
h << "url('data:image/png;base64,"
<< Base64Encode(PNGEncoder().SaveString(image))
<< "') " << pt.x << ' ' << pt.y << ", default";
Put8(SETCURSORIMAGE);
Put16(0); // TODO: Cursor cache
Put(h);
Put8(MOUSECURSOR);
Put16(0); // TODO: Cursor cache
}
}
}
| 18.646465 | 95 | 0.62333 | mirek-fidler |