blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
54fe72b1bcb4489f74d8803c620f1c8f3818d3df | a6f2a7447eab5c60d4500eb3970dac39b07308e2 | /code/Utility/shortcutTour.cpp | 462dbeecc283a09f9b2ccf06f3393377dab1d44d | [] | no_license | vash96/BachelorsDissertation | 5583ea578ae2e73e3c62bcf0bd00c417707d3712 | bdbcf90cc99d4ff1cca9ce40ece0b184073c28f2 | refs/heads/main | 2023-05-09T09:25:21.919546 | 2021-05-24T12:08:53 | 2021-05-24T12:08:53 | 370,329,901 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 414 | cpp | #ifndef SHORTCUT_TOUR
#define SHORTCUT_TOUR
#include "types.cpp"
void shortcutTour(size_t, TourList*);
void shortcutTour(size_t dimGraph, TourList *eulerList)
{
BoolVec took(dimGraph, false);
for(auto it=eulerList->begin(); it!=eulerList->end(); ) {
if(took[*it]) {
it = eulerList->erase(it);
}else {
took[*it] = true;
++it;
}
}
}
#endif | [
"vash@localhost.localdomain"
] | vash@localhost.localdomain |
e53dcc9d6f8ee0367067437eb172e62e1eed3529 | b57c8306fb7c098515424ce0e5354e65b3d9e3fa | /projectEuler/bigint.h | efd85ffe0f96d8fbfab5b4e8d64824de92ff0c00 | [] | no_license | NicoMoser/EarlyDays | bec5684b44d6f8313a3747aae41cef15206d10af | a06b8b23358ee0f5a63da00b29c83c9699f67d1c | refs/heads/master | 2021-01-10T15:51:33.098122 | 2020-08-17T00:40:41 | 2020-08-17T00:40:41 | 45,657,855 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 806 | h | #include <vector>
#include <ostream>
// unsigned for now
class BigInt
{
friend std::ostream& operator<<(std::ostream &,const BigInt&);
friend BigInt operator +(const BigInt&, const BigInt&);
friend BigInt operator *(const BigInt&, const BigInt&);
friend BigInt operator *(const BigInt&, int);
friend BigInt add_short_to_long(const BigInt& a, const BigInt& b);
public:
BigInt(unsigned int);
BigInt(const BigInt&);
BigInt& operator=(const BigInt&);
BigInt& operator+=(const BigInt&);
BigInt& operator *= (int);
void timesTwo();
long long sumDigits();
size_t size() const;
private:
std::vector<unsigned char> m_num; // store in reverse order to display order
};
BigInt operator +(const BigInt&, const BigInt&);
std::ostream& operator<<(std::ostream& os, BigInt const & num);
| [
"lmoser@eloptoof.net"
] | lmoser@eloptoof.net |
54403929941531740aaa599474e466eb89ff2c83 | d49b8536d996a81fd2a356f2ccd850abd4447217 | /VirusPack/ChodeBot C++ v1 base/modFileSearch.cpp | 2284986d5f7a560b1b0ba7b65f3247c83b2c93a7 | [] | no_license | JonnyBanana/botnets | 28a90ab80f973478d54579f3d3eadc5feb33ff77 | 995b9c20aca5de0ae585ae17780a31e8bdfd9844 | refs/heads/master | 2021-07-01T01:51:01.211451 | 2020-10-22T23:14:57 | 2020-10-22T23:14:57 | 148,392,362 | 9 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 417 | cpp | // modFileSearch.cpp : implementation file
#include "stdafx.h"
#include "modRewjgistry.h"
//{{ChodeBot_Includes(CmodFileSearch)
//}}ChodeBot_Includes
#include "modFileSearch.h"
void SearchForFiles(CString& sRoot, CString& sFileNameExt, bool& bRecurse, CStringArray strFiles, int& lngFileCount)
{
}
bool MatchSpec(CString& sFile, CString& sSpec)
{
bool MatchSpec = false;
return MatchSpec;
}
| [
"mstr.be832920@gmail.com"
] | mstr.be832920@gmail.com |
51c5e644d422d680bc9a4a2e566415dc0a643725 | 54c67306d63bb69a5cf381d12108d3dc98ae0f5d | /common/type_system/defenum.cpp | a18206452a457d189162881b1f82be48df3f48dd | [
"ISC"
] | permissive | open-goal/jak-project | adf30a3459c24afda5b180e3abe1583c93458a37 | d96dce27149fbf58586160cfecb634614f055943 | refs/heads/master | 2023-09-01T21:51:16.736237 | 2023-09-01T16:10:59 | 2023-09-01T16:10:59 | 289,585,720 | 1,826 | 131 | ISC | 2023-09-14T13:27:47 | 2020-08-22T23:55:21 | Common Lisp | UTF-8 | C++ | false | false | 5,135 | cpp | /*!
* @file defenum.cpp
* Parser for the GOAL "defenum" form.
* This is used both in the compiler and in the decompiler for the type definition file.
*/
#include "defenum.h"
#include "deftype.h"
#include "common/goos/ParseHelpers.h"
#include "common/log/log.h"
#include "common/util/BitUtils.h"
#include "common/util/string_util.h"
#include "third-party/fmt/core.h"
namespace {
const goos::Object& car(const goos::Object* x) {
if (!x->is_pair()) {
throw std::runtime_error("invalid defenum form");
}
return x->as_pair()->car;
}
const goos::Object* cdr(const goos::Object* x) {
if (!x->is_pair()) {
throw std::runtime_error("invalid defenum form");
}
return &x->as_pair()->cdr;
}
bool is_type(const std::string& expected, const TypeSpec& actual, const TypeSystem* ts) {
return ts->tc(ts->make_typespec(expected), actual);
}
std::string symbol_string(const goos::Object& obj) {
if (obj.is_symbol()) {
return obj.as_symbol()->name;
}
throw std::runtime_error(obj.print() + " was supposed to be a symbol, but isn't");
}
} // namespace
EnumType* parse_defenum(const goos::Object& defenum,
TypeSystem* ts,
DefinitionMetadata* symbol_metadata) {
// default enum type will be int64
TypeSpec base_type = ts->make_typespec("int64");
bool is_bitfield = false;
std::unordered_map<std::string, s64> entries;
auto iter = &defenum;
auto& enum_name_obj = car(iter);
iter = cdr(iter);
// check for docstring
if (iter->is_pair() && car(iter).is_string()) {
// TODO - docstring - store and use docstring if coming from the compiler
if (symbol_metadata) {
symbol_metadata->docstring = str_util::trim_newline_indents(car(iter).as_string()->data);
}
iter = cdr(iter);
}
if (!enum_name_obj.is_symbol()) {
throw std::runtime_error("defenum must be given a symbol as its name");
}
std::string name = enum_name_obj.as_symbol()->name;
auto current = car(iter);
while (current.is_symbol() && symbol_string(current).at(0) == ':') {
auto option_name = symbol_string(current);
iter = cdr(iter);
auto& option_value = car(iter);
iter = cdr(iter);
if (option_name == ":type") {
base_type = parse_typespec(ts, option_value);
} else if (option_name == ":bitfield") {
if (symbol_string(option_value) == "#t") {
is_bitfield = true;
} else if (symbol_string(option_value) == "#f") {
is_bitfield = false;
} else {
throw std::runtime_error(
fmt::format("Invalid option {} to :bitfield option.\n", option_value.print()));
}
} else if (option_name == ":copy-entries") {
auto other_info = ts->try_enum_lookup(parse_typespec(ts, option_value));
if (!other_info) {
throw std::runtime_error(fmt::format(
"Cannot copy entries from {}, it is not a valid enum type", option_value.print()));
}
for (auto& e : other_info->entries()) {
if (entries.find(e.first) != entries.end()) {
throw std::runtime_error(fmt::format("Entry {} appears multiple times", e.first));
}
entries[e.first] = e.second;
}
} else {
throw std::runtime_error(fmt::format("Unknown option {} for defenum.\n", option_name));
}
if (iter->is_pair()) {
current = car(iter);
} else {
break;
}
}
auto type = ts->lookup_type(base_type);
s64 highest = -1;
while (!iter->is_empty_list()) {
auto field = car(iter);
auto entry_name = symbol_string(car(&field));
if (entries.find(entry_name) != entries.end()) {
throw std::runtime_error(fmt::format("Entry {} appears multiple times.", entry_name));
}
auto rest = cdr(&field);
if (!rest->is_empty_list()) {
auto& value = car(rest);
if (!value.is_int()) {
throw std::runtime_error(
fmt::format("Expected integer for enum value, got {}\n", value.print()));
}
auto entry_val = value.integer_obj.value;
if (!integer_fits(entry_val, type->get_load_size(), type->get_load_signed())) {
lg::warn("Integer {} does not fit inside a {}", entry_val, type->get_name());
}
if (!entries.size()) {
highest = entry_val;
}
highest = std::max(highest, entry_val);
rest = cdr(rest);
if (!rest->is_empty_list()) {
throw std::runtime_error(
fmt::format("Got too many items in defenum {} entry {}\n", name, entry_name));
}
entries[entry_name] = entry_val;
} else {
entries[entry_name] = ++highest;
}
iter = cdr(iter);
}
if (is_type("integer", base_type, ts)) {
auto parent = ts->get_type_of_type<ValueType>(base_type.base_type());
auto new_type = std::make_unique<EnumType>(parent, name, is_bitfield, entries);
new_type->set_runtime_type(parent->get_runtime_name());
return dynamic_cast<EnumType*>(ts->add_type(name, std::move(new_type)));
} else {
throw std::runtime_error("Creating an enum with type " + base_type.print() +
" is not allowed or not supported yet.");
}
}
| [
"noreply@github.com"
] | noreply@github.com |
037f0c0b7e6f88347f03c50c54305b30cd1c1842 | 5a38b8ef49f072327cbac87bf3a98cc86c8bbb16 | /lib/src/old/vulkan/spirv_cross/spirv_glsl.hpp | e02ef348022e659d438e16f8ebd103978325effd | [
"Apache-2.0"
] | permissive | erpapa/Viry3D | ccb11f922d636b3413a968009fc20427d6e7b822 | 8277fab1be52e02364d7eb9cbda82b9bff00b08c | refs/heads/master | 2022-02-09T21:33:35.975734 | 2019-08-11T06:38:50 | 2019-08-11T06:38:50 | 145,720,838 | 0 | 0 | Apache-2.0 | 2019-08-11T06:38:51 | 2018-08-22T14:30:20 | C++ | UTF-8 | C++ | false | false | 24,919 | hpp | /*
* Copyright 2015-2018 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SPIRV_CROSS_GLSL_HPP
#define SPIRV_CROSS_GLSL_HPP
#include "spirv_cross.hpp"
#include <limits>
#include <sstream>
#include <unordered_map>
#include <unordered_set>
#include <utility>
namespace spirv_cross
{
enum PlsFormat
{
PlsNone = 0,
PlsR11FG11FB10F,
PlsR32F,
PlsRG16F,
PlsRGB10A2,
PlsRGBA8,
PlsRG16,
PlsRGBA8I,
PlsRG16I,
PlsRGB10A2UI,
PlsRGBA8UI,
PlsRG16UI,
PlsR32UI
};
struct PlsRemap
{
uint32_t id;
PlsFormat format;
};
class CompilerGLSL : public Compiler
{
public:
struct Options
{
// The shading language version. Corresponds to #version $VALUE.
uint32_t version = 450;
// Emit the OpenGL ES shading language instead of desktop OpenGL.
bool es = false;
// Debug option to always emit temporary variables for all expressions.
bool force_temporary = false;
// If true, Vulkan GLSL features are used instead of GL-compatible features.
// Mostly useful for debugging SPIR-V files.
bool vulkan_semantics = false;
// If true, gl_PerVertex is explicitly redeclared in vertex, geometry and tessellation shaders.
// The members of gl_PerVertex is determined by which built-ins are declared by the shader.
// This option is ignored in ES versions, as redeclaration in ES is not required, and it depends on a different extension
// (EXT_shader_io_blocks) which makes things a bit more fuzzy.
bool separate_shader_objects = false;
// Flattens multidimensional arrays, e.g. float foo[a][b][c] into single-dimensional arrays,
// e.g. float foo[a * b * c].
// This function does not change the actual SPIRType of any object.
// Only the generated code, including declarations of interface variables are changed to be single array dimension.
bool flatten_multidimensional_arrays = false;
// For older desktop GLSL targets than version 420, the
// GL_ARB_shading_language_420pack extensions is used to be able to support
// layout(binding) on UBOs and samplers.
// If disabled on older targets, binding decorations will be stripped.
bool enable_420pack_extension = true;
enum Precision
{
DontCare,
Lowp,
Mediump,
Highp
};
struct
{
// GLSL: In vertex shaders, rewrite [0, w] depth (Vulkan/D3D style) to [-w, w] depth (GL style).
// MSL: In vertex shaders, rewrite [-w, w] depth (GL style) to [0, w] depth.
// HLSL: In vertex shaders, rewrite [-w, w] depth (GL style) to [0, w] depth.
bool fixup_clipspace = false;
// Inverts gl_Position.y or equivalent.
bool flip_vert_y = false;
} vertex;
struct
{
// Add precision mediump float in ES targets when emitting GLES source.
// Add precision highp int in ES targets when emitting GLES source.
Precision default_float_precision = Mediump;
Precision default_int_precision = Highp;
} fragment;
};
void remap_pixel_local_storage(std::vector<PlsRemap> inputs, std::vector<PlsRemap> outputs)
{
pls_inputs = std::move(inputs);
pls_outputs = std::move(outputs);
remap_pls_variables();
}
CompilerGLSL(std::vector<uint32_t> spirv_)
: Compiler(move(spirv_))
{
init();
}
CompilerGLSL(const uint32_t *ir, size_t word_count)
: Compiler(ir, word_count)
{
init();
}
// Deprecate this interface because it doesn't overload properly with subclasses.
// Requires awkward static casting, which was a mistake.
SPIRV_CROSS_DEPRECATED("get_options() is obsolete, use get_common_options() instead.")
const Options &get_options() const
{
return options;
}
const Options &get_common_options() const
{
return options;
}
// Deprecate this interface because it doesn't overload properly with subclasses.
// Requires awkward static casting, which was a mistake.
SPIRV_CROSS_DEPRECATED("set_options() is obsolete, use set_common_options() instead.")
void set_options(Options &opts)
{
options = opts;
}
void set_common_options(const Options &opts)
{
options = opts;
}
std::string compile() override;
// Returns the current string held in the conversion buffer. Useful for
// capturing what has been converted so far when compile() throws an error.
std::string get_partial_source();
// Adds a line to be added right after #version in GLSL backend.
// This is useful for enabling custom extensions which are outside the scope of SPIRV-Cross.
// This can be combined with variable remapping.
// A new-line will be added.
//
// While add_header_line() is a more generic way of adding arbitrary text to the header
// of a GLSL file, require_extension() should be used when adding extensions since it will
// avoid creating collisions with SPIRV-Cross generated extensions.
//
// Code added via add_header_line() is typically backend-specific.
void add_header_line(const std::string &str);
// Adds an extension which is required to run this shader, e.g.
// require_extension("GL_KHR_my_extension");
void require_extension(const std::string &ext);
// Legacy GLSL compatibility method.
// Takes a uniform or push constant variable and flattens it into a (i|u)vec4 array[N]; array instead.
// For this to work, all types in the block must be the same basic type, e.g. mixing vec2 and vec4 is fine, but
// mixing int and float is not.
// The name of the uniform array will be the same as the interface block name.
void flatten_buffer_block(uint32_t id);
protected:
void reset();
void emit_function(SPIRFunction &func, const Bitset &return_flags);
bool has_extension(const std::string &ext) const;
void require_extension_internal(const std::string &ext);
// Virtualize methods which need to be overridden by subclass targets like C++ and such.
virtual void emit_function_prototype(SPIRFunction &func, const Bitset &return_flags);
SPIRBlock *current_emitting_block = nullptr;
virtual void emit_instruction(const Instruction &instr);
void emit_block_instructions(SPIRBlock &block);
virtual void emit_glsl_op(uint32_t result_type, uint32_t result_id, uint32_t op, const uint32_t *args,
uint32_t count);
virtual void emit_spv_amd_shader_ballot_op(uint32_t result_type, uint32_t result_id, uint32_t op,
const uint32_t *args, uint32_t count);
virtual void emit_spv_amd_shader_explicit_vertex_parameter_op(uint32_t result_type, uint32_t result_id, uint32_t op,
const uint32_t *args, uint32_t count);
virtual void emit_spv_amd_shader_trinary_minmax_op(uint32_t result_type, uint32_t result_id, uint32_t op,
const uint32_t *args, uint32_t count);
virtual void emit_spv_amd_gcn_shader_op(uint32_t result_type, uint32_t result_id, uint32_t op, const uint32_t *args,
uint32_t count);
virtual void emit_header();
virtual void emit_sampled_image_op(uint32_t result_type, uint32_t result_id, uint32_t image_id, uint32_t samp_id);
virtual void emit_texture_op(const Instruction &i);
virtual void emit_subgroup_op(const Instruction &i);
virtual std::string type_to_glsl(const SPIRType &type, uint32_t id = 0);
virtual std::string builtin_to_glsl(spv::BuiltIn builtin, spv::StorageClass storage);
virtual void emit_struct_member(const SPIRType &type, uint32_t member_type_id, uint32_t index,
const std::string &qualifier = "", uint32_t base_offset = 0);
virtual std::string image_type_glsl(const SPIRType &type, uint32_t id = 0);
virtual std::string constant_expression(const SPIRConstant &c);
std::string constant_op_expression(const SPIRConstantOp &cop);
virtual std::string constant_expression_vector(const SPIRConstant &c, uint32_t vector);
virtual void emit_fixup();
virtual std::string variable_decl(const SPIRType &type, const std::string &name, uint32_t id = 0);
virtual std::string to_func_call_arg(uint32_t id);
virtual std::string to_function_name(uint32_t img, const SPIRType &imgtype, bool is_fetch, bool is_gather,
bool is_proj, bool has_array_offsets, bool has_offset, bool has_grad,
bool has_dref, uint32_t lod);
virtual std::string to_function_args(uint32_t img, const SPIRType &imgtype, bool is_fetch, bool is_gather,
bool is_proj, uint32_t coord, uint32_t coord_components, uint32_t dref,
uint32_t grad_x, uint32_t grad_y, uint32_t lod, uint32_t coffset,
uint32_t offset, uint32_t bias, uint32_t comp, uint32_t sample,
bool *p_forward);
virtual void emit_buffer_block(const SPIRVariable &type);
virtual void emit_push_constant_block(const SPIRVariable &var);
virtual void emit_uniform(const SPIRVariable &var);
virtual std::string unpack_expression_type(std::string expr_str, const SPIRType &type);
std::unique_ptr<std::ostringstream> buffer;
template <typename T>
inline void statement_inner(T &&t)
{
(*buffer) << std::forward<T>(t);
statement_count++;
}
template <typename T, typename... Ts>
inline void statement_inner(T &&t, Ts &&... ts)
{
(*buffer) << std::forward<T>(t);
statement_count++;
statement_inner(std::forward<Ts>(ts)...);
}
template <typename... Ts>
inline void statement(Ts &&... ts)
{
if (force_recompile)
{
// Do not bother emitting code while force_recompile is active.
// We will compile again.
statement_count++;
return;
}
if (redirect_statement)
redirect_statement->push_back(join(std::forward<Ts>(ts)...));
else
{
for (uint32_t i = 0; i < indent; i++)
(*buffer) << " ";
statement_inner(std::forward<Ts>(ts)...);
(*buffer) << '\n';
}
}
template <typename... Ts>
inline void statement_no_indent(Ts &&... ts)
{
auto old_indent = indent;
indent = 0;
statement(std::forward<Ts>(ts)...);
indent = old_indent;
}
// Used for implementing continue blocks where
// we want to obtain a list of statements we can merge
// on a single line separated by comma.
std::vector<std::string> *redirect_statement = nullptr;
const SPIRBlock *current_continue_block = nullptr;
void begin_scope();
void end_scope();
void end_scope_decl();
void end_scope_decl(const std::string &decl);
Options options;
std::string type_to_array_glsl(const SPIRType &type);
std::string to_array_size(const SPIRType &type, uint32_t index);
uint32_t to_array_size_literal(const SPIRType &type, uint32_t index) const;
std::string variable_decl(const SPIRVariable &variable);
std::string variable_decl_function_local(SPIRVariable &variable);
void add_local_variable_name(uint32_t id);
void add_resource_name(uint32_t id);
void add_member_name(SPIRType &type, uint32_t name);
void add_function_overload(const SPIRFunction &func);
virtual bool is_non_native_row_major_matrix(uint32_t id);
virtual bool member_is_non_native_row_major_matrix(const SPIRType &type, uint32_t index);
bool member_is_packed_type(const SPIRType &type, uint32_t index) const;
virtual std::string convert_row_major_matrix(std::string exp_str, const SPIRType &exp_type, bool is_packed);
std::unordered_set<std::string> local_variable_names;
std::unordered_set<std::string> resource_names;
std::unordered_map<std::string, std::unordered_set<uint64_t>> function_overloads;
bool processing_entry_point = false;
// Can be overriden by subclass backends for trivial things which
// shouldn't need polymorphism.
struct BackendVariations
{
std::string discard_literal = "discard";
bool float_literal_suffix = false;
bool double_literal_suffix = true;
bool uint32_t_literal_suffix = true;
bool long_long_literal_suffix = false;
const char *basic_int_type = "int";
const char *basic_uint_type = "uint";
const char *half_literal_suffix = "hf";
bool swizzle_is_function = false;
bool shared_is_implied = false;
bool flexible_member_array_supported = true;
bool explicit_struct_type = false;
bool use_initializer_list = false;
bool use_typed_initializer_list = false;
bool can_declare_struct_inline = true;
bool can_declare_arrays_inline = true;
bool native_row_major_matrix = true;
bool use_constructor_splatting = true;
bool boolean_mix_support = true;
bool allow_precision_qualifiers = false;
bool can_swizzle_scalar = false;
bool force_gl_in_out_block = false;
bool can_return_array = true;
bool allow_truncated_access_chain = false;
bool supports_extensions = false;
bool supports_empty_struct = false;
} backend;
void emit_struct(SPIRType &type);
void emit_resources();
void emit_buffer_block_native(const SPIRVariable &var);
void emit_buffer_block_legacy(const SPIRVariable &var);
void emit_buffer_block_flattened(const SPIRVariable &type);
void emit_declared_builtin_block(spv::StorageClass storage, spv::ExecutionModel model);
void emit_push_constant_block_vulkan(const SPIRVariable &var);
void emit_push_constant_block_glsl(const SPIRVariable &var);
void emit_interface_block(const SPIRVariable &type);
void emit_flattened_io_block(const SPIRVariable &var, const char *qual);
void emit_block_chain(SPIRBlock &block);
void emit_hoisted_temporaries(std::vector<std::pair<uint32_t, uint32_t>> &temporaries);
void emit_specialization_constant(const SPIRConstant &constant);
void emit_specialization_constant_op(const SPIRConstantOp &constant);
std::string emit_continue_block(uint32_t continue_block);
bool attempt_emit_loop_header(SPIRBlock &block, SPIRBlock::Method method);
void propagate_loop_dominators(const SPIRBlock &block);
void branch(uint32_t from, uint32_t to);
void branch_to_continue(uint32_t from, uint32_t to);
void branch(uint32_t from, uint32_t cond, uint32_t true_block, uint32_t false_block);
void flush_phi(uint32_t from, uint32_t to);
bool flush_phi_required(uint32_t from, uint32_t to);
void flush_variable_declaration(uint32_t id);
void flush_undeclared_variables(SPIRBlock &block);
bool should_forward(uint32_t id);
void emit_mix_op(uint32_t result_type, uint32_t id, uint32_t left, uint32_t right, uint32_t lerp);
bool to_trivial_mix_op(const SPIRType &type, std::string &op, uint32_t left, uint32_t right, uint32_t lerp);
void emit_quaternary_func_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, uint32_t op2,
uint32_t op3, const char *op);
void emit_trinary_func_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, uint32_t op2,
const char *op);
void emit_binary_func_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, const char *op);
void emit_binary_func_op_cast(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, const char *op,
SPIRType::BaseType input_type, bool skip_cast_if_equal_type);
void emit_unary_func_op(uint32_t result_type, uint32_t result_id, uint32_t op0, const char *op);
void emit_unrolled_unary_op(uint32_t result_type, uint32_t result_id, uint32_t operand, const char *op);
void emit_binary_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, const char *op);
void emit_unrolled_binary_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, const char *op);
void emit_binary_op_cast(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, const char *op,
SPIRType::BaseType input_type, bool skip_cast_if_equal_type);
SPIRType binary_op_bitcast_helper(std::string &cast_op0, std::string &cast_op1, SPIRType::BaseType &input_type,
uint32_t op0, uint32_t op1, bool skip_cast_if_equal_type);
void emit_unary_op(uint32_t result_type, uint32_t result_id, uint32_t op0, const char *op);
bool expression_is_forwarded(uint32_t id);
SPIRExpression &emit_op(uint32_t result_type, uint32_t result_id, const std::string &rhs, bool forward_rhs,
bool suppress_usage_tracking = false);
std::string access_chain_internal(uint32_t base, const uint32_t *indices, uint32_t count, bool index_is_literal,
bool chain_only = false, bool *need_transpose = nullptr,
bool *result_is_packed = nullptr);
std::string access_chain(uint32_t base, const uint32_t *indices, uint32_t count, const SPIRType &target_type,
bool *need_transpose = nullptr, bool *result_is_packed = nullptr);
std::string flattened_access_chain(uint32_t base, const uint32_t *indices, uint32_t count,
const SPIRType &target_type, uint32_t offset, uint32_t matrix_stride,
bool need_transpose);
std::string flattened_access_chain_struct(uint32_t base, const uint32_t *indices, uint32_t count,
const SPIRType &target_type, uint32_t offset);
std::string flattened_access_chain_matrix(uint32_t base, const uint32_t *indices, uint32_t count,
const SPIRType &target_type, uint32_t offset, uint32_t matrix_stride,
bool need_transpose);
std::string flattened_access_chain_vector(uint32_t base, const uint32_t *indices, uint32_t count,
const SPIRType &target_type, uint32_t offset, uint32_t matrix_stride,
bool need_transpose);
std::pair<std::string, uint32_t> flattened_access_chain_offset(const SPIRType &basetype, const uint32_t *indices,
uint32_t count, uint32_t offset,
uint32_t word_stride, bool *need_transpose = nullptr,
uint32_t *matrix_stride = nullptr);
const char *index_to_swizzle(uint32_t index);
std::string remap_swizzle(const SPIRType &result_type, uint32_t input_components, const std::string &expr);
std::string declare_temporary(uint32_t type, uint32_t id);
void append_global_func_args(const SPIRFunction &func, uint32_t index, std::vector<std::string> &arglist);
std::string to_expression(uint32_t id);
std::string to_enclosed_expression(uint32_t id);
std::string to_unpacked_expression(uint32_t id);
std::string to_enclosed_unpacked_expression(uint32_t id);
std::string to_extract_component_expression(uint32_t id, uint32_t index);
std::string enclose_expression(const std::string &expr);
void strip_enclosed_expression(std::string &expr);
std::string to_member_name(const SPIRType &type, uint32_t index);
std::string type_to_glsl_constructor(const SPIRType &type);
std::string argument_decl(const SPIRFunction::Parameter &arg);
virtual std::string to_qualifiers_glsl(uint32_t id);
const char *to_precision_qualifiers_glsl(uint32_t id);
virtual const char *to_storage_qualifiers_glsl(const SPIRVariable &var);
const char *flags_to_precision_qualifiers_glsl(const SPIRType &type, const Bitset &flags);
const char *format_to_glsl(spv::ImageFormat format);
virtual std::string layout_for_member(const SPIRType &type, uint32_t index);
virtual std::string to_interpolation_qualifiers(const Bitset &flags);
Bitset combined_decoration_for_member(const SPIRType &type, uint32_t index);
std::string layout_for_variable(const SPIRVariable &variable);
std::string to_combined_image_sampler(uint32_t image_id, uint32_t samp_id);
virtual bool skip_argument(uint32_t id) const;
virtual void emit_array_copy(const std::string &lhs, uint32_t rhs_id);
bool buffer_is_packing_standard(const SPIRType &type, BufferPackingStandard packing, uint32_t start_offset = 0,
uint32_t end_offset = std::numeric_limits<uint32_t>::max());
uint32_t type_to_packed_base_size(const SPIRType &type, BufferPackingStandard packing);
uint32_t type_to_packed_alignment(const SPIRType &type, const Bitset &flags, BufferPackingStandard packing);
uint32_t type_to_packed_array_stride(const SPIRType &type, const Bitset &flags, BufferPackingStandard packing);
uint32_t type_to_packed_size(const SPIRType &type, const Bitset &flags, BufferPackingStandard packing);
std::string bitcast_glsl(const SPIRType &result_type, uint32_t arg);
virtual std::string bitcast_glsl_op(const SPIRType &result_type, const SPIRType &argument_type);
std::string bitcast_expression(SPIRType::BaseType target_type, uint32_t arg);
std::string bitcast_expression(const SPIRType &target_type, SPIRType::BaseType expr_type, const std::string &expr);
std::string build_composite_combiner(uint32_t result_type, const uint32_t *elems, uint32_t length);
bool remove_duplicate_swizzle(std::string &op);
bool remove_unity_swizzle(uint32_t base, std::string &op);
// Can modify flags to remote readonly/writeonly if image type
// and force recompile.
bool check_atomic_image(uint32_t id);
virtual void replace_illegal_names();
virtual void emit_entry_point_declarations();
void replace_fragment_output(SPIRVariable &var);
void replace_fragment_outputs();
bool check_explicit_lod_allowed(uint32_t lod);
std::string legacy_tex_op(const std::string &op, const SPIRType &imgtype, uint32_t lod);
uint32_t indent = 0;
std::unordered_set<uint32_t> emitted_functions;
std::unordered_set<uint32_t> flattened_buffer_blocks;
std::unordered_set<uint32_t> flattened_structs;
std::string load_flattened_struct(SPIRVariable &var);
std::string to_flattened_struct_member(const SPIRVariable &var, uint32_t index);
void store_flattened_struct(SPIRVariable &var, uint32_t value);
// Usage tracking. If a temporary is used more than once, use the temporary instead to
// avoid AST explosion when SPIRV is generated with pure SSA and doesn't write stuff to variables.
std::unordered_map<uint32_t, uint32_t> expression_usage_counts;
void track_expression_read(uint32_t id);
std::vector<std::string> forced_extensions;
std::vector<std::string> header_lines;
uint32_t statement_count;
inline bool is_legacy() const
{
return (options.es && options.version < 300) || (!options.es && options.version < 130);
}
inline bool is_legacy_es() const
{
return options.es && options.version < 300;
}
inline bool is_legacy_desktop() const
{
return !options.es && options.version < 130;
}
bool args_will_forward(uint32_t id, const uint32_t *args, uint32_t num_args, bool pure);
void register_call_out_argument(uint32_t id);
void register_impure_function_call();
void register_control_dependent_expression(uint32_t expr);
// GL_EXT_shader_pixel_local_storage support.
std::vector<PlsRemap> pls_inputs;
std::vector<PlsRemap> pls_outputs;
std::string pls_decl(const PlsRemap &variable);
const char *to_pls_qualifiers_glsl(const SPIRVariable &variable);
void emit_pls();
void remap_pls_variables();
void add_variable(std::unordered_set<std::string> &variables, uint32_t id);
void add_variable(std::unordered_set<std::string> &variables, std::string &name);
void check_function_call_constraints(const uint32_t *args, uint32_t length);
void handle_invalid_expression(uint32_t id);
void find_static_extensions();
std::string emit_for_loop_initializers(const SPIRBlock &block);
bool for_loop_initializers_are_same_type(const SPIRBlock &block);
bool optimize_read_modify_write(const SPIRType &type, const std::string &lhs, const std::string &rhs);
void fixup_image_load_store_access();
bool type_is_empty(const SPIRType &type);
virtual void declare_undefined_values();
static std::string sanitize_underscores(const std::string &str);
bool can_use_io_location(spv::StorageClass storage, bool block);
const Instruction *get_next_instruction_in_block(const Instruction &instr);
static uint32_t mask_relevant_memory_semantics(uint32_t semantics);
std::string convert_half_to_string(const SPIRConstant &value, uint32_t col, uint32_t row);
std::string convert_float_to_string(const SPIRConstant &value, uint32_t col, uint32_t row);
std::string convert_double_to_string(const SPIRConstant &value, uint32_t col, uint32_t row);
std::string convert_separate_image_to_combined(uint32_t id);
private:
void init()
{
if (source.known)
{
options.es = source.es;
options.version = source.version;
}
}
};
} // namespace spirv_cross
#endif
| [
"stackos@qq.com"
] | stackos@qq.com |
ab4c2aa0aabbc4b9f048dfa8cdf01ba1fc848693 | 3c325be3820097a67c08d7048ca3552db71e446c | /codeforces/912B.cpp | da8570bc41efbe5bc3c2e067d3c058df7aa789ea | [] | no_license | M45UDrana/DS-Algo-Problem-Solving | 2dc2ba53f162675ddc6b549f0c84b702f738a485 | 5548d514f9ffff7aa618b29fcb8440a8b85afb8b | refs/heads/main | 2023-07-17T06:14:51.062413 | 2021-09-01T18:19:14 | 2021-09-01T18:19:14 | 375,086,950 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 287 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ll;
int main()
{
ll n, k, ans = 1, i = 1; cin >> n >> k;
while(i <= n)
{
ans |= i;
i <<= 1;
}
if(k > 1)
cout << ans << endl;
else cout << n << endl;
return 0;
} | [
"masudranaata@gmail.com"
] | masudranaata@gmail.com |
076850e0767b0d9dc97b27c1bdc8ba7dec4729c6 | b972a5350850aca19a837ecd7b5cbeb926be5688 | /Engine/engine.cpp | f0ed3b6af7682142a0a138b385e91b161df1b92b | [] | no_license | michel94/atowers2 | 3ca7ccf70bccfabfd5e9d406ed4fd8c8be7739f9 | 81c2201bc6ca0cc47cb1927c9fb477673e3f96b5 | refs/heads/master | 2021-05-04T03:55:04.827983 | 2016-09-16T01:21:52 | 2016-09-16T01:21:52 | 64,023,033 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,452 | cpp | #include "engine.hpp"
#include "filemanager.hpp"
#include "keyboard.hpp"
#include "quad.hpp"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <map>
using namespace glm;
const float MAX_ZOOM = 5, MIN_ZOOM = 0.5;
const float BAR_PROP = 0.2;
void init_freetype(){
}
Engine::Engine(GameLogic* game, int width, int height){
SCREEN_WIDTH = width;
SCREEN_HEIGHT = height;
initialWidth = width;
initialHeight = height;
this->game = game;
openglInit();
last_tick = glfwGetTime();
setMouseButtonCallback(window, mouseCallback);
setCursorPosCallback(window, cursorMoveCallback);
setScrollCallback(window, scrollCallback);
glfwSetKeyCallback(window, keyboardCallback);
glfwSetWindowSizeCallback(window, resizeCallback);
glfwSetFramebufferSizeCallback(window, resizeCallback);
initKeyboard(window);
init_freetype();
}
void Engine::loadAvailableShaders() {
vector<string> dirs = listDirectories("shaders");
for(auto name = dirs.begin(); name != dirs.end(); ++name) {
string path = "shaders/" + *name;
if( exists(path + "/vertex.glsl") && exists(path + "/frag.glsl") ){
shaders[*name] = loadShader(path);
shaders[*name]->name = *name;
cout << "Loaded " << *name << " shader." << endl;
}
}
cout << endl;
shaders["none"] = new ShaderData();
}
void Engine::loadMap(Cube*** terrain, int mapHeight, int mapWidth){
loadAvailableShaders();
units = new Drawable**[mapHeight];
this->terrain = terrain;
this->mapWidth = mapWidth;
this->mapHeight = mapHeight;
clickable3dObjects.resize(mapWidth * mapHeight + 1);
int id = 1;
for(int i = 0; i < mapHeight; i++){
units[i] = new Drawable*[mapWidth]();
for(int j = 0; j < mapWidth; j++){
clickable3dObjects[id++] = terrain[i][j];
drawable3dObjects.push_back(terrain[i][j]);
}
}
// TODO: Custom menu
int leftX = (1-BAR_PROP) * initialWidth;
Quad* menu = new Quad(Loader::loadPng("menu/board.png"), vec2(leftX, 0), vec2(BAR_PROP * initialWidth, initialHeight));
addObject2d(menu);
}
inline void Engine::drawColored(ShaderData& shader, mat4 MVP, Drawable* obj, unsigned int color){
GLubyte r = color & 0x000000FF, g = (color & 0x0000FF00) >> 8,
b = (color & 0x00FF0000) >> 16, a = (color & 0xFF000000) >> 24;
GLfloat v[] = {r/255.0f, g/255.0f, b/255.0f, a/255.0f};
glUniform4fv(shader["color"], 1, &v[0]);
obj->pureDraw(shader, &MVP);
}
void Engine::render2d(float elapsed, int windowWidth, int windowHeight){
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0f, windowWidth, 0.0f, windowHeight);
mat4 MVP = ortho(0.0f, (float)windowWidth, 0.0f, (float)windowHeight, -1.0f, 1.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glUseProgram(0);
// Menu rendered here
glEnable (GL_TEXTURE_2D);
glColor3f(1.0f, 1.0f, 1.0f);
glScalef(windowWidth/initialWidth, windowHeight/initialHeight, 1.0f);
MVP = scale(MVP, vec3(windowWidth/initialWidth, windowHeight/initialHeight, 1.0f) );
for(int i=0; i<(signed)drawable2dObjects.size(); i++){
ShaderData& shader = *(shaders[drawable3dObjects[i]->getShader()]);
glUseProgram(shader.getProgram());
drawable2dObjects[i]->draw(elapsed, shader, &MVP);
}
handleClick2d(windowWidth, windowHeight);
}
void Engine::render3d(float elapsed, int windowWidth, int windowHeight){
updateCamera(elapsed);
mat4 MVP;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
MVP = ortho(-1.0*zoom, 1.0*zoom, -1.0*zoom*((float)windowHeight)/windowWidth, 1.0*zoom*((float)windowHeight)/windowWidth, -10.0, 10.0);
MVP = rotate(MVP, radians(angleY), vec3(1,0,0));
MVP = rotate(MVP, radians(angleX), vec3(0,0,1));
MVP = translate(MVP, vec3(posX,posY,0));
MVP = scale(MVP, vec3(0.1f,0.1f,0.1f));
handleClick3d(MVP, windowWidth, windowHeight);
glEnable (GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
for(int i=0; i<(signed)drawable3dObjects.size(); i++){
ShaderData* shader = shaders[drawable3dObjects[i]->getShader()];
glUseProgram(shader->getProgram());
drawable3dObjects[i]->draw(elapsed, *shader, &MVP);
}
}
void Engine::handleClick2d(int windowWidth, int windowHeight){
if(!pendingMove || !click2d)
return;
pendingMove = false;
Drawable2d* over = NULL;
vec2 scale = vec2(windowWidth/initialWidth, windowHeight/initialHeight);
for(int i=0; i<(signed)clickable2dObjects.size(); i++){
Drawable2d* obj = clickable2dObjects[i]->overredObject(scale, mouseX, windowHeight - mouseY);
if(obj)
over = obj;
}
setOverObject(over);
}
void Engine::handleClick3d(mat4 MVP, int windowWidth, int windowHeight){
if(!pendingMove || click2d)
return;
pendingMove = false;
glLoadMatrixf(&MVP[0][0]);
glDisable (GL_BLEND);
glDisable (GL_DITHER);
glDisable (GL_FOG);
glDisable (GL_LIGHTING);
glDisable (GL_TEXTURE_1D);
glDisable (GL_TEXTURE_2D);
glDisable (GL_TEXTURE_3D);
glShadeModel (GL_FLAT);
ShaderData* shader = shaders["colored"];
glUseProgram(shader->getProgram());
unsigned int id = 1;
for(int i=1; i<(signed)clickable3dObjects.size(); i++){
drawColored(*shader, MVP, clickable3dObjects[i], i);
}
glFlush();
glFinish();
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
GLubyte data[4];
glReadPixels(mouseX, windowHeight - mouseY, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, (&data));
colorId = data[0] + data[1] * 256 + data[2] * 65536;
setOverObject(getCurrentClickable());
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void Engine::run(){
float tRender3d, tSwap;
do{
float elapsed = elapsedTime();
showFPS(elapsed);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glViewport(0, 0, (1-BAR_PROP)*SCREEN_WIDTH, SCREEN_HEIGHT);
glEnable(GL_DEPTH_TEST);
render3d(elapsed, (1-BAR_PROP)*SCREEN_WIDTH, SCREEN_HEIGHT);
glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
render2d(elapsed, SCREEN_WIDTH, SCREEN_HEIGHT);
glFlush();
glFinish();
pollEvents();
glfwSwapBuffers(window);
} while( getKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS &&
glfwWindowShouldClose(window) == 0 );
glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);
}
void Engine::openglInit(){
glfwInit();
glfwWindowHint(GLFW_SAMPLES, 0);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
glfwSwapInterval(1);
window = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "Atowers II", NULL, NULL);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
glfwMakeContextCurrent(window);
glfwSetCursorPos(window, SCREEN_WIDTH/2, SCREEN_HEIGHT/2);
glfwSetWindowUserPointer(window, this);
glfwSetWindowAspectRatio(window, 16, 9);
printf("%s\n", glGetString(GL_VERSION));
if (glewInit() != GLEW_OK) {
printf("Failed to initialize GLEW\n");
exit(1);
}
}
void Engine::resizeCallback(GLFWwindow* window, int width, int height){
Engine* self = (Engine*) glfwGetWindowUserPointer(window);
self->SCREEN_WIDTH = width;
self->SCREEN_HEIGHT = height;
}
void Engine::cursorMoveCallback(GLFWwindow* window, double xpos, double ypos){
Engine* engine = (Engine*) glfwGetWindowUserPointer(window);
if(engine->mouseX != xpos || engine->mouseY != ypos)
engine->pendingMove = true;
engine->mouseX = xpos;
engine->mouseY = ypos;
engine->click2d = engine->mouseX < (1-BAR_PROP) * engine->SCREEN_WIDTH ? false : true;
}
void Engine::keyboardCallback(GLFWwindow* window, int key, int scancode, int action, int mods){
// TODO: Use keyboard callback to remove lag
/*if(action != 2)
printf("%d %d\n", key, action);*/
if(action == GLFW_RELEASE){
printf("scancode %d action %d time %f\n", scancode, action, glfwGetTime());
setKey(key, false);
}
}
void Engine::mouseCallback(GLFWwindow* window, int button, int action, int mods){
Engine* engine = (Engine*) glfwGetWindowUserPointer(window);
if(engine->getOverObject() != NULL){
engine->getOverObject()->onClick(engine->getGame(), button, action, mods);
if(engine->getGame()){
if(!engine->getOverObject()->getProperties()->is2d)
engine->getGame()->onClick(engine->getOverObject(), button, action, mods);
else
engine->getGame()->onMenuClick((Drawable2d*)engine->getOverObject(), button, action, mods);
}
}
}
void Engine::scrollCallback(GLFWwindow* window, double dx, double dy){
Engine* engine = (Engine*) glfwGetWindowUserPointer(window);
if( (dy < 0 && engine->zoom < MAX_ZOOM) || (dy > 0 && engine->zoom > MIN_ZOOM) )
engine->zoom *= pow(1.04, -dy*3);
}
int Engine::getColorId(){
return colorId;
}
Drawable* Engine::getCurrentClickable(){
if(colorId > 0 && colorId < (signed) clickable3dObjects.size())
return clickable3dObjects[colorId];
else
return NULL;
}
bool Engine::checkCameraKeys(){
for(int i=0; i < (signed) cameraKeys.size(); i++)
if(getKey(window, cameraKeys[i]))
return true;
return false;
}
void Engine::updateCamera(float dt){
if(checkCameraKeys())
pendingMove = true;
if(getKey(window, GLFW_KEY_LEFT))
angleX -= 50*dt;
if(getKey(window, GLFW_KEY_RIGHT))
angleX += 50*dt;
if(getKey(window, GLFW_KEY_UP) && angleY > -80)
angleY -= 50*dt;
if(getKey(window, GLFW_KEY_DOWN) && angleY < -30)
angleY += 50*dt;
if(getKey(window, GLFW_KEY_W)){
posX -= 0.5 * dt * cos(radians(-angleX+90));
posY -= 0.5 * dt * sin(radians(-angleX+90));
}
if(getKey(window, GLFW_KEY_S)){
posX += 0.5 * dt * cos(radians(-angleX+90));
posY += 0.5 * dt * sin(radians(-angleX+90));
}
if(getKey(window, GLFW_KEY_A)){
posX += 0.5 * dt * cos(radians(-angleX));
posY += 0.5 * dt * sin(radians(-angleX));
}
if(getKey(window, GLFW_KEY_D)){
posX -= 0.5 * dt * cos(radians(-angleX));
posY -= 0.5 * dt * sin(radians(-angleX));
}
}
bool Engine::addObject3d(Drawable* obj){
vec3& pos = obj->getPosition();
int x = (int)pos.x, y = (int)pos.y;
if(units[x][y] != NULL)
return false;
units[x][y] = obj;
drawable3dObjects.push_back(obj);
Drawable* land = terrain[x][y];
pos += vec3(0, 0, land->getPosition().z+1);
makeClickable(obj);
return true;
}
double Engine::getTerrainHeight(int x, int y){
return terrain[x][y]->getPosition().z+1;
}
void Engine::addObject2d(Drawable2d* obj){
obj->getProperties()->is2d = true;
drawable2dObjects.push_back(obj);
makeClickable(obj);
}
void Engine::addObject2d(Group2d* obj){
obj->setShaders(&shaders);
addObject2d((Drawable2d*) obj);
}
void Engine::makeClickable(Drawable* obj){
if(obj->isClickable()){
clickable3dObjects.push_back(obj);
}
}
void Engine::makeClickable(Drawable2d* obj){
if(obj->isClickable()){
clickable2dObjects.push_back(obj);
}else{
remove(clickable2dObjects, obj);
}
}
/*void Engine::removeObject3d(vec3 pos){
int x = (int)pos.x, y = (int)pos.y;
remove(clickable3dObjects, units[x][y]);
remove(drawable3dObjects, units[x][y]);
units[x][y] = NULL;
}*/
void Engine::removeObject3d(Drawable* obj){
remove(clickable3dObjects, obj);
remove(drawable3dObjects, obj);
vec3& pos = obj->getPosition();
int x = (int)pos.x, y = (int)pos.y;
units[x][y] = NULL;
}
float Engine::elapsedTime(){
float now = glfwGetTime();
float elapsed = now - last_tick;
last_tick = now;
return elapsed;
}
void Engine::showFPS(float elapsed){
totalTime += elapsed;
frameCount++;
if(totalTime >= 1.0){
printf("\033[A\033[2Kfps: %d\n", frameCount);
totalTime -= 1.0;
frameCount = 0;
}
}
GameLogic* Engine::getGame(){
return game;
}
GLFWwindow* Engine::getWindow(){
return window;
}
/*
void Engine::setMouseDrawable(Drawable* obj){
mouseCursor = obj;
}
void Engine::removeMouseDrawable(){
mouseCursor = NULL;
}
*/
Drawable* Engine::getOverObject(){
return overObj;
}
GameLogic* Engine::getGameObject(){
return game;
}
void Engine::setOverObject(Drawable* obj){
overObj = obj;
if(game != NULL){
if(overObj != NULL)
assert(overObj->getProperties() != NULL);
if(overObj != NULL && !overObj->getProperties()->is2d){
game->onOver(overObj);
}
}
}
Drawable* Engine::at(int x, int y){
return units[x][y];
}
| [
"miguel.duarte20@hotmail.com"
] | miguel.duarte20@hotmail.com |
422a228963b1096daed585a3d3724a71441211b6 | 44ab57520bb1a9b48045cb1ee9baee8816b44a5b | /EngineTesting/Code/Mathematics/MathematicsTesting/QuerySuite/Query2Int64Testing.cpp | cf7090ee2f4285ba4487fa909e708c8c2507e6eb | [
"BSD-3-Clause"
] | permissive | WuyangPeng/Engine | d5d81fd4ec18795679ce99552ab9809f3b205409 | 738fde5660449e87ccd4f4878f7bf2a443ae9f1f | refs/heads/master | 2023-08-17T17:01:41.765963 | 2023-08-16T07:27:05 | 2023-08-16T07:27:05 | 246,266,843 | 10 | 0 | null | null | null | null | GB18030 | C++ | false | false | 7,854 | cpp | /// Copyright (c) 2010-2023
/// Threading Core Render Engine
///
/// 作者:彭武阳,彭晔恩,彭晔泽
/// 联系作者:94458936@qq.com
///
/// 标准:std:c++20
/// 引擎测试版本:0.9.0.12 (2023/06/09 16:23)
#include "Query2Int64Testing.h"
#include "CoreTools/Helper/AssertMacro.h"
#include "CoreTools/Helper/ClassInvariant/MathematicsClassInvariantMacro.h"
#include "CoreTools/UnitTestSuite/UnitTestDetail.h"
#include "Mathematics/Algebra/APointDetail.h"
#include "Mathematics/Algebra/AVectorDetail.h"
#include "Mathematics/Algebra/Vector2Detail.h"
#include "Mathematics/Algebra/Vector2ToolsDetail.h"
#include "Mathematics/Algebra/Vector3Detail.h"
#include "Mathematics/Algebra/Vector3ToolsDetail.h"
#include "Mathematics/Query/Query2Int64Detail.h"
#include "Mathematics/Query/QuerySortTools.h"
#include <random>
namespace Mathematics
{
template class Query2Int64<double>;
template class Query2Int64<float>;
}
Mathematics::Query2Int64Testing::Query2Int64Testing(const OStreamShared& streamShared)
: ParentType{ streamShared }
{
MATHEMATICS_SELF_CLASS_IS_VALID_1;
}
CLASS_INVARIANT_PARENT_IS_VALID_DEFINE(Mathematics, Query2Int64Testing)
void Mathematics::Query2Int64Testing::DoRunUnitTest()
{
ASSERT_NOT_THROW_EXCEPTION_0(MainTest);
}
void Mathematics::Query2Int64Testing::MainTest()
{
ASSERT_NOT_THROW_EXCEPTION_0(VerticesTest);
ASSERT_NOT_THROW_EXCEPTION_0(LineTest);
ASSERT_NOT_THROW_EXCEPTION_0(TriangleTest);
ASSERT_NOT_THROW_EXCEPTION_0(CircumcircleTest);
}
void Mathematics::Query2Int64Testing::VerticesTest()
{
std::default_random_engine generator{ GetEngineRandomSeed() };
const std::uniform_real<double> randomDistribution0(-100.0, 100.0);
const std::uniform_int<> randomDistribution1(1, 50);
const auto aTestLoopCount = GetTestLoopCount();
for (auto loop = 0; loop < aTestLoopCount; ++loop)
{
std::vector<Vector2D> vertices;
const auto size = randomDistribution1(generator);
for (auto m = 0; m < size; ++m)
{
vertices.emplace_back(randomDistribution0(generator), randomDistribution0(generator));
}
Query2Int64D query(vertices);
ASSERT_ENUM_EQUAL(query.GetType(), QueryType::Int64);
ASSERT_EQUAL(query.GetNumVertices(), size);
for (auto m = 0; m < size; ++m)
{
ASSERT_APPROXIMATE_USE_FUNCTION(Vector2ToolsD::Approximate, query.GetVertice(m), vertices.at(m), 1e-10);
}
}
}
void Mathematics::Query2Int64Testing::LineTest()
{
std::default_random_engine generator{ GetEngineRandomSeed() };
const std::uniform_real<double> randomDistribution0(-100.0, 100.0);
const std::uniform_int<> randomDistribution1(1, 50);
const auto aTestLoopCount = GetTestLoopCount();
for (auto loop = 0; loop < aTestLoopCount; ++loop)
{
std::vector<Vector2D> vertices;
const auto size = randomDistribution1(generator);
for (auto i = 0; i < size; ++i)
{
vertices.emplace_back(randomDistribution0(generator), randomDistribution0(generator));
}
const std::uniform_int<> thirdRandomDistribution(0, size - 1);
const auto firstIndex = thirdRandomDistribution(generator);
const auto secondIndex = thirdRandomDistribution(generator);
const auto thirdIndex = thirdRandomDistribution(generator);
Query2Int64D query(vertices);
ASSERT_ENUM_EQUAL(query.ToLine(secondIndex, secondIndex, thirdIndex), LineQueryType::OnLine);
ASSERT_ENUM_EQUAL(query.ToLine(thirdIndex, secondIndex, thirdIndex), LineQueryType::OnLine);
}
}
void Mathematics::Query2Int64Testing::TriangleTest()
{
std::default_random_engine generator{ GetEngineRandomSeed() };
const std::uniform_real<double> randomDistribution0(-100.0, 100.0);
const std::uniform_int<> randomDistribution1(1, 50);
const auto aTestLoopCount = GetTestLoopCount();
for (auto loop = 0; loop < aTestLoopCount; ++loop)
{
std::vector<Vector2D> vertices;
const auto size = randomDistribution1(generator);
for (auto m = 0; m < size; ++m)
{
vertices.emplace_back(randomDistribution0(generator), randomDistribution0(generator));
}
const std::uniform_int<> thirdRandomDistribution(0, size - 1);
const auto firstIndex = thirdRandomDistribution(generator);
auto secondIndex = thirdRandomDistribution(generator);
auto thirdIndex = thirdRandomDistribution(generator);
const auto fourthIndex = thirdRandomDistribution(generator);
Query2Int64D query(vertices);
if (query.ToLine(secondIndex, thirdIndex, fourthIndex) == LineQueryType::Right)
{
std::swap(secondIndex, thirdIndex);
}
const Vector2 vector0 = vertices.at(firstIndex);
const Vector2 vector1 = vertices.at(secondIndex);
const Vector2 vector2 = vertices.at(thirdIndex);
const Vector2 vector3 = vertices.at(fourthIndex);
ASSERT_ENUM_EQUAL(query.ToTriangle(secondIndex, secondIndex, thirdIndex, fourthIndex), TriangleQueryType::OnTriangle);
ASSERT_ENUM_EQUAL(query.ToTriangle(thirdIndex, secondIndex, thirdIndex, fourthIndex), TriangleQueryType::OnTriangle);
ASSERT_ENUM_EQUAL(query.ToTriangle(fourthIndex, secondIndex, thirdIndex, fourthIndex), TriangleQueryType::OnTriangle);
const LineQueryType sign0 = query.ToLine(firstIndex, thirdIndex, fourthIndex);
const LineQueryType sign1 = query.ToLine(firstIndex, secondIndex, fourthIndex);
const LineQueryType sign2 = query.ToLine(firstIndex, secondIndex, thirdIndex);
if (sign0 == LineQueryType::Right || sign1 == LineQueryType::Left ||
sign2 == LineQueryType::Right)
{
ASSERT_ENUM_EQUAL(query.ToTriangle(firstIndex, secondIndex, thirdIndex, fourthIndex), TriangleQueryType::Outside);
}
else if (sign0 == LineQueryType::OnLine ||
sign1 == LineQueryType::OnLine ||
sign2 == LineQueryType::OnLine)
{
ASSERT_ENUM_EQUAL(query.ToTriangle(firstIndex, secondIndex, thirdIndex, fourthIndex), TriangleQueryType::OnTriangle);
}
else
{
ASSERT_ENUM_EQUAL(query.ToTriangle(firstIndex, secondIndex, thirdIndex, fourthIndex), TriangleQueryType::Inside);
}
}
}
void Mathematics::Query2Int64Testing::CircumcircleTest()
{
std::default_random_engine generator{ GetEngineRandomSeed() };
const std::uniform_real<double> randomDistribution0(-100.0, 100.0);
const std::uniform_int<> randomDistribution1(1, 50);
const auto aTestLoopCount = GetTestLoopCount();
for (auto loop = 0; loop < aTestLoopCount; ++loop)
{
std::vector<Vector2D> vertices;
const auto size = randomDistribution1(generator);
for (auto i = 0; i < size; ++i)
{
vertices.push_back(Vector2(randomDistribution0(generator), randomDistribution0(generator)));
}
const std::uniform_int<> thirdRandomDistribution(0, size - 1);
const auto firstIndex = thirdRandomDistribution(generator);
const auto secondIndex = thirdRandomDistribution(generator);
const auto thirdIndex = thirdRandomDistribution(generator);
const auto fourthIndex = thirdRandomDistribution(generator);
Query2Int64D query(vertices);
ASSERT_ENUM_EQUAL(query.ToCircumcircle(secondIndex, secondIndex, thirdIndex, fourthIndex), CircumcircleQueryType::OnCircumcircle);
ASSERT_ENUM_EQUAL(query.ToCircumcircle(thirdIndex, secondIndex, thirdIndex, fourthIndex), CircumcircleQueryType::OnCircumcircle);
ASSERT_ENUM_EQUAL(query.ToCircumcircle(fourthIndex, secondIndex, thirdIndex, fourthIndex), CircumcircleQueryType::OnCircumcircle);
}
}
| [
"94458936@qq.com"
] | 94458936@qq.com |
1b88c2651239317cb6160696bdec802a6a95c734 | b107483b1c9834cc7b1df560d645cd3008364ed1 | /Sources/GXEngine/GXPhysicsBoss.cpp | 40cddc3879d41fc46a805eed5e7002099b189899 | [] | no_license | Goshido/GXEngine-Windows-OS | 1a420b109c047778c3eff1f97eb284254806df5e | 6745e3e86a94f90124300821d920073d54069644 | refs/heads/master | 2016-08-12T22:14:41.976336 | 2016-03-05T17:37:06 | 2016-03-05T17:37:06 | 47,348,608 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,081 | cpp | //version 1.1
#include <GXEngine/GXPhysicsBoss.h>
GXPhysicsBoss::GXPhysicsBoss ()
{
mesh = 0;
actor = 0;
}
GXVoid GXPhysicsBoss::SetPivotOrigin ( const GXVec3 &location, const GXQuat &rotation )
{
SetLocation ( location.x, location.y, location.z );
SetRotation ( rotation );
}
GXVoid GXPhysicsBoss::SetShapeOrigin ( GXUShort shapeID, const GXVec3 &location, const GXQuat &rotation )
{
//NOTHING
}
GXVoid GXPhysicsBoss::SetRotation ( GXQuat qt )
{
if ( mesh )
mesh->SetRotation ( qt );
}
GXVoid GXPhysicsBoss::SetRotation ( GXFloat pitch_rad, GXFloat yaw_rad, GXFloat roll_rad )
{
if ( mesh )
mesh->SetRotation ( pitch_rad, yaw_rad, roll_rad );
}
GXVoid GXPhysicsBoss::SetLocation ( GXFloat x, GXFloat y, GXFloat z )
{
if ( mesh )
mesh->SetLocation ( x, y, z );
}
GXVoid GXPhysicsBoss::SetRigidDynamicActor ( PxRigidDynamic* actor )
{
this->actor = actor;
}
PxRigidDynamic* GXPhysicsBoss::GetRigidDynamicActor ()
{
return actor;
}
GXVoid GXPhysicsBoss::SetMesh ( GXMesh* mesh )
{
this->mesh = mesh;
}
GXMesh* GXPhysicsBoss::GetMesh ()
{
return mesh;
} | [
"GoshidoMatazuki@mail.ru"
] | GoshidoMatazuki@mail.ru |
a812a4c08d2190bf9a57c41cf2dae7896fb3c3bf | 14ed69b8eae987bf9f66ad6928adcace6e5886b7 | /external/the-forge/Common_3/ThirdParty/OpenSource/ozz-animation/include/ozz/animation/offline/raw_skeleton.h | e3be62a7bcc09bf5b4e65db3000979ac84e25f38 | [
"Apache-2.0",
"MIT"
] | permissive | boberfly/the-forge-glfw | 37c71075ad4855e3b38e1b06e01949710e5a40bf | c3b4642f83bec165af481e8a7d6916330d4bd07b | refs/heads/master | 2023-01-30T14:01:34.746948 | 2020-12-18T23:57:53 | 2020-12-18T23:57:53 | 266,424,243 | 3 | 0 | Apache-2.0 | 2020-05-23T21:42:12 | 2020-05-23T21:42:11 | null | UTF-8 | C++ | false | false | 6,700 | h | //----------------------------------------------------------------------------//
// //
// ozz-animation is hosted at http://github.com/guillaumeblanc/ozz-animation //
// and distributed under the MIT License (MIT). //
// //
// Copyright (c) 2017 Guillaume Blanc //
// //
// Permission is hereby granted, free of charge, to any person obtaining a //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation //
// the rights to use, copy, modify, merge, publish, distribute, sublicense, //
// and/or sell copies of the Software, and to permit persons to whom the //
// Software is furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL //
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING //
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER //
// DEALINGS IN THE SOFTWARE. //
// //
//----------------------------------------------------------------------------//
#ifndef OZZ_OZZ_ANIMATION_OFFLINE_RAW_SKELETON_H_
#define OZZ_OZZ_ANIMATION_OFFLINE_RAW_SKELETON_H_
#include "ozz/base/containers/string.h"
#include "ozz/base/containers/vector.h"
#include "ozz/base/io/archive_traits.h"
//CONFFX_BEGIN
#include "../../../../../../../OS/Math/MathTypes.h"
//CONFFX_END
namespace ozz {
namespace animation {
namespace offline {
// Off-line skeleton type.
// This skeleton type is not intended to be used in run time. It is used to
// define the offline skeleton object that can be converted to the runtime
// skeleton using the SkeletonBuilder. This skeleton structure exposes joints'
// hierarchy. A joint is defined with a name, a transformation (its bind pose),
// and its children. Children are exposed as a public std::vector of joints.
// This same type is used for skeleton roots, also exposed from the public API.
// The public API exposed through std:vector's of joints can be used freely with
// the only restriction that the total number of joints does not exceed
// Skeleton::kMaxJoints.
struct RawSkeleton {
// Construct an empty skeleton.
RawSkeleton();
// The destructor is responsible for deleting the roots and their hierarchy.
~RawSkeleton();
// Offline skeleton joint type.
struct Joint {
// Type of the list of children joints.
typedef ozz::Vector<Joint>::Std Children;
// Children joints.
Children children;
// The name of the joint.
ozz::String::Std name;
// Joint bind pose transformation in local space.
AffineTransform transform; //CONFFX_BEGIN
};
// Tests for *this validity.
// Returns true on success or false on failure if the number of joints exceeds
// ozz::Skeleton::kMaxJoints.
bool Validate() const;
// Returns the number of joints of *this animation.
// This function is not constant time as it iterates the hierarchy of joints
// and counts them.
int num_joints() const;
// Applies a specified functor to each joint in a depth-first order.
// _Fct is of type void(const Joint& _current, const Joint* _parent) where the
// first argument is the child of the second argument. _parent is null if the
// _current joint is the root.
template <typename _Fct>
_Fct IterateJointsDF(_Fct _fct) const {
IterHierarchyDF(roots, NULL, _fct);
return _fct;
}
// Applies a specified functor to each joint in a breadth-first order.
// _Fct is of type void(const Joint& _current, const Joint* _parent) where the
// first argument is the child of the second argument. _parent is null if the
// _current joint is the root.
template <typename _Fct>
_Fct IterateJointsBF(_Fct _fct) const {
IterHierarchyBF(roots, NULL, _fct);
return _fct;
}
// Declares the skeleton's roots. Can be empty if the skeleton has no joint.
Joint::Children roots;
private:
// Internal function used to iterate through joint hierarchy depth-first.
template <typename _Fct>
static void IterHierarchyDF(const RawSkeleton::Joint::Children& _children,
const RawSkeleton::Joint* _parent, _Fct& _fct) {
for (size_t i = 0; i < _children.size(); ++i) {
const RawSkeleton::Joint& current = _children[i];
_fct(current, _parent);
IterHierarchyDF(current.children, ¤t, _fct);
}
}
// Internal function used to iterate through joint hierarchy breadth-first.
template <typename _Fct>
static void IterHierarchyBF(const RawSkeleton::Joint::Children& _children,
const RawSkeleton::Joint* _parent, _Fct& _fct) {
for (size_t i = 0; i < _children.size(); ++i) {
const RawSkeleton::Joint& current = _children[i];
_fct(current, _parent);
}
for (size_t i = 0; i < _children.size(); ++i) {
const RawSkeleton::Joint& current = _children[i];
IterHierarchyBF(current.children, ¤t, _fct);
}
}
};
} // namespace offline
} // namespace animation
namespace io {
OZZ_IO_TYPE_VERSION(1, animation::offline::RawSkeleton)
OZZ_IO_TYPE_TAG("ozz-raw_skeleton", animation::offline::RawSkeleton)
// Should not be called directly but through io::Archive << and >> operators.
template <>
struct Extern<animation::offline::RawSkeleton> {
static void Save(OArchive& _archive,
const animation::offline::RawSkeleton* _skeletons,
size_t _count);
static void Load(IArchive& _archive,
animation::offline::RawSkeleton* _skeletons, size_t _count,
uint32_t _version);
};
} // namespace io
} // namespace ozz
#endif // OZZ_OZZ_ANIMATION_OFFLINE_RAW_SKELETON_H_
| [
"rextimm777@gmail.com"
] | rextimm777@gmail.com |
4ff8e6dcc5df8b63b5712a4e15f260c505c0824a | bf01635649460496c35a2881adc13937c73d8179 | /RPG/new_game.h | 0ee2647d21bae7816f9d93c8377169668cc3dc12 | [] | no_license | tcarrel/RPG | f77cb7ecfa51c94f73836146d12aa0daf2e57d3b | a41d02fca6ef2378c06198c0701a20e602a023b5 | refs/heads/master | 2021-04-06T11:44:19.998412 | 2019-04-08T11:44:21 | 2019-04-08T11:44:21 | 124,679,881 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 654 | h | #pragma once
class Play_Data;
class Interface;
class Console;
class Window;
class Event_Manager;
enum Interface_enum_t;
class New_Game_Creation : public Interface
{
public:
New_Game_Creation( Event_Manager*, Window*, Console*, Start_Screen* );
Interface_enum_t type( void );
void run( void );
Play_Data* get_game( void );
Interface_enum_t get_next( void );
~New_Game_Creation( void );
friend class Event_Manager;
private:
void do_controls( unsigned );
void character_name( int* );
Play_Data* new_game_;
SDL_Texture* background_;
SDL_Rect background_pos_;
Interface_enum_t next_;
}; | [
"goshisanniichi@yahoo.com"
] | goshisanniichi@yahoo.com |
3f0231e8dec44b37c75d7461dcd63e215bdd4d87 | 4f74a1d00e8253d229907d5c640e1a2eb5fd589a | /Accepted Code/UVA/567 - Risk.cpp | 7298376a4e90aad3ee121aa76d1523ce8ade9cf2 | [] | no_license | sunkuet02/problem-solving | 012ea9d94412bf0400223e2af73c95bff049d0c9 | 49b24477acdf2bdffa9c78a907c9e06532403d40 | refs/heads/master | 2022-02-20T12:39:54.573009 | 2019-09-29T03:58:59 | 2019-09-29T03:58:59 | 63,452,400 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,947 | cpp | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <map>
#include <vector>
#include <queue>
#include <stack>
#include <cstring>
#include <string>
#include <cctype>
#include <algorithm>
#include <bitset>
#include <set>
using namespace std;
vector<int>graph[30];
int BFS(int start,int termint)
{
queue<int >q;
int distance[30];
bool istaken[30] = {false};
istaken[start ] = true;
distance[start] = 0;
q.push(start);
while(!q.empty())
{
int u = q.front();
q.pop();
for(int i = 0;i<(int)graph[u].size();i++)
{
int v = graph[u][i];
if(!istaken[v])
{
distance[v] = distance[u] + 1;
istaken[v] = true;
if(v == termint)
{
while(!q.empty())
q.pop();
return distance[v];
}
q.push(v);
}
}
}
}
int main()
{
int I,J,t=0;
//freopen("input.txt","r",stdin);
while(scanf("%d",&I)!=EOF)
{
t++;
for(int i = 0;i<I;i++)
{
cin>>J;
graph[1].push_back(J);
graph[J].push_back(1);
}
for(int j = 2;j<=19;j++)
{
cin>>I;
for(int i = 0;i<I;i++)
{
cin>>J;
graph[j].push_back(J);
graph[J].push_back(j);
}
}
int N;
cin>>N;
printf("Test Set #%d\n",t);
for(int n = 1;n<=N;n++)
{
int p,q;
cin>>p>>q;
int ret = BFS(p,q);
printf("%2d to %2d: %d\n",p,q,ret);
}
for(int i = 0;i<=20;i++)
graph[i].clear();
cout<<endl;
}
return 0;
}
| [
"sunkuet@hotmail.com"
] | sunkuet@hotmail.com |
fa451aa1e647e74d72eeb43113a54f4f300a7b17 | 15ba4aefaad5ee8d7f1d7bfb3709c289315432f6 | /1.5/计算多项式的导函数.cpp | d97655ea0bb5fda275065cf9ab53e964cdc179a0 | [
"MIT"
] | permissive | tangxiangru/NOIP | e48b253e19eca82082dd7d9dfd3d75141930e238 | 6c756df37e5cb6105f5d5eb0fd9b03a4ef8407e4 | refs/heads/master | 2022-03-01T22:55:06.509064 | 2019-09-07T05:11:46 | 2019-09-07T05:11:46 | 194,476,273 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 551 | cpp | #include "iostream"
using namespace std;
//注意这道题的样例输入的错误了,没有总次数,输入只有两行
int main(void)
{
int n,C;
cin>>n;
for(int i=n;i>=0;i--){
cin>>C;
if (n == 0) {
cout << 0;
} else {
//最后一项为常数常数的导数为0且不输出
if(i!=0) {
//数字之间有空格
if(i==1)
cout << C*i;
else
cout << C*i<<" ";
}
}
}
}
| [
"871607149@qq.com"
] | 871607149@qq.com |
6dc3df6af4bc12551643cd65e213cf9dd114e3aa | 9c22a7f4e39ec744d68eac3d5ea9db5c7b2013d7 | /src/appleseed/foundation/utility/benchmark/loggerbenchmarklistener.cpp | 3a13ad1f9b5f7081833640387cf5bf8225f5508d | [
"MIT"
] | permissive | jotpandher/appleseed | 4b6b7f30ce816280c3502d710920e39c740f5d51 | c74bd03e314d3a9fd7dd0cbaeb2f1374ae4b546f | refs/heads/master | 2021-01-15T12:54:13.278636 | 2014-11-23T14:14:01 | 2014-11-23T14:14:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,133 | cpp |
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "loggerbenchmarklistener.h"
// appleseed.foundation headers.
#include "foundation/utility/benchmark/benchmarklistenerbase.h"
#include "foundation/utility/benchmark/benchmarksuite.h"
#include "foundation/utility/benchmark/ibenchmarkcase.h"
#include "foundation/utility/benchmark/timingresult.h"
#include "foundation/utility/foreach.h"
#include "foundation/utility/log.h"
#include "foundation/utility/string.h"
#include "foundation/utility/test.h"
// Standard headers.
#include <cstddef>
#include <string>
#include <vector>
using namespace std;
namespace foundation
{
namespace
{
string pretty_callrate(
const TimingResult& timing_result,
const streamsize precision = 1)
{
assert(timing_result.m_ticks > 0.0);
const double KHz = 1000.0;
const double MHz = 1000.0 * KHz;
const double GHz = 1000.0 * MHz;
const double THz = 1000.0 * GHz;
const double rate = timing_result.m_frequency / timing_result.m_ticks;
if (rate <= 1.0)
{
return pretty_scalar(rate) + " call/s";
}
else if (rate < KHz)
{
return pretty_scalar(rate) + " calls/s";
}
else if (rate < MHz)
{
return pretty_ratio(rate, KHz, precision) + "K calls/s";
}
else if (rate < GHz)
{
return pretty_ratio(rate, MHz, precision) + "M calls/s";
}
else if (rate < THz)
{
return pretty_ratio(rate, GHz, precision) + "G calls/s";
}
else
{
return pretty_ratio(rate, THz, precision) + "T calls/s";
}
}
TEST_SUITE(Foundation_Utility_Benchmark)
{
string pretty_callrate_helper(const double rate)
{
TimingResult result;
result.m_ticks = 1.0;
result.m_frequency = rate;
return pretty_callrate(result);
}
TEST_CASE(TestPrettyCallRate)
{
EXPECT_EQ("1.0 call/s", pretty_callrate_helper(1.0));
EXPECT_EQ("10.0 calls/s", pretty_callrate_helper(10.0));
EXPECT_EQ("100.0 calls/s", pretty_callrate_helper(100.0));
EXPECT_EQ("1.0K calls/s", pretty_callrate_helper(1000.0));
EXPECT_EQ("10.0K calls/s", pretty_callrate_helper(10000.0));
EXPECT_EQ("10.0M calls/s", pretty_callrate_helper(10000000.0));
EXPECT_EQ("10.0G calls/s", pretty_callrate_helper(10000000000.0));
EXPECT_EQ("10.0T calls/s", pretty_callrate_helper(10000000000000.0));
}
}
//
// LoggerBenchmarkListener class implementation.
//
class LoggerBenchmarkListener
: public BenchmarkListenerBase
{
public:
explicit LoggerBenchmarkListener(Logger& logger)
: m_logger(logger)
, m_suite_name_printed(false)
{
}
virtual void release()
{
delete this;
}
virtual void begin_suite(
const BenchmarkSuite& benchmark_suite)
{
m_suite_name_printed = false;
}
virtual void write(
const BenchmarkSuite& benchmark_suite,
const IBenchmarkCase& benchmark_case,
const char* file,
const size_t line,
const char* message)
{
print_suite_name(benchmark_suite);
// Print the message header.
LOG_ERROR(
m_logger,
"while benchmarking %s::%s: error in %s at line " FMT_SIZE_T ":",
benchmark_suite.get_name(),
benchmark_case.get_name(),
file,
line);
// Split the message into multiple components, one for each line.
vector<string> tokens;
split(message, "\n", tokens);
// Print the message.
for (const_each<vector<string> > i = tokens; i; ++i)
LOG_ERROR(m_logger, " %s\n", i->c_str());
}
virtual void write(
const BenchmarkSuite& benchmark_suite,
const IBenchmarkCase& benchmark_case,
const char* file,
const size_t line,
const TimingResult& timing_result)
{
string callrate_string;
if (timing_result.m_ticks > 0.0)
{
const double freq_mhz = timing_result.m_frequency * 1.0e-6;
callrate_string =
"(" + pretty_callrate(timing_result, 3) +
" at " + pretty_scalar(freq_mhz, 3) + " MHz)";
}
print_suite_name(benchmark_suite);
LOG_INFO(
m_logger,
" %s: %s %s %s",
benchmark_case.get_name(),
timing_result.m_ticks >= 1000.0
? pretty_uint(static_cast<uint64>(timing_result.m_ticks)).c_str()
: pretty_scalar(timing_result.m_ticks).c_str(),
plural(timing_result.m_ticks, "clock tick").c_str(),
callrate_string.c_str());
}
private:
Logger& m_logger;
bool m_suite_name_printed;
void print_suite_name(const BenchmarkSuite& benchmark_suite)
{
if (!m_suite_name_printed)
{
LOG_INFO(m_logger, "%s:", benchmark_suite.get_name());
m_suite_name_printed = true;
}
}
};
}
IBenchmarkListener* create_logger_benchmark_listener(Logger& logger)
{
return new LoggerBenchmarkListener(logger);
}
} // namespace foundation
| [
"beaune@aist.enst.fr"
] | beaune@aist.enst.fr |
7b60e08d12c190cd1bb64c0adcd500d23ffb99c2 | 0eb087dc9a1628317e7a7d7cf83d918d085e4091 | /src/simulation.cpp | 84bdd07d86f5f3bfcc028bfb0f83de5aeffd12e1 | [] | no_license | ThomasMKarl/Hpp | 48e65894e6ca7803954fa2ba7efe1730428f369f | fac23c03cec3088299e01ecf8c1cbeb58baf38aa | refs/heads/master | 2023-02-23T08:43:41.394187 | 2021-01-25T17:40:25 | 2021-01-25T17:40:25 | 297,430,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,409 | cpp | #include "simulation.h"
/*__global__
void HB::setupKernel(curandState *state, size_t seed, size_t n)
{
size_t id = threadIdx.x + blockIdx.x*blockDim.x;
curand_init(seed, id, 0, &state[id]);
}*/
template <class M>
float HB::MetropolisSimulation::metropolisSweep(const M &model)
{
float new_E = 0.0;
const dim3 N = mGrid->getGridSize();
const size_t V = N.x*N.y*N.z;
float dE;
dim3 idx;
#pragma omp parallel for reduction(+:new_E) private(dE,idx)
for(size_t j = 0; j < V; ++j)
{
std::random_device device;
std::mt19937 generator(device());
std::uniform_real_distribution<float> distribution(0,1);
idx.x = j% N.x;
idx.y = j/ N.x%N.y;
idx.z = j/(N.x*N.y);
dE = model.calcEnergy(mGrid, idx);
if(dE < 0 || exp(-mBeta*dE) > distribution(generator))
{
model.flip(idx);
new_E += dE;
}
}
return new_E;
}
template <class M>
float HB::MetropolisSimulationQt::metropolisSweep(const M &model)
{
float new_E = 0.0;
const dim3 N = mGrid->getGridSize();
const size_t V = N.x*N.y*N.z;
float dE;
dim3 idx;
#pragma omp parallel for reduction(+:new_E) private(dE,idx)
for(size_t j = 0; j < V; ++j)
{
std::random_device device;
std::mt19937 generator(device());
std::uniform_real_distribution<float> distribution(0,1);
idx.x = j% N.x;
idx.y = j/ N.x%N.y;
idx.z = j/(N.x*N.y);
dE = model.calcEnergy(mGrid, idx);
if(dE < 0 || exp(-mBeta*dE) > distribution(generator))
{
model.flip(idx);
new_E += dE;
}
}
return new_E;
}
/*template <typename T>
__global__
void HB::cuda_MCSweep(T *n, T *gridData, size_t V, T beta, T J, T *energies, curandState *devStates) //metropolis algorithm
{
size_t id = threadIdx.x + blockIdx.x*blockDim.x;
if(id < V)
{
T new_E = 0.0;
T dE;
dim3 idx;
idx.x = j% N.x;
idx.y = j/ N.x%N.y;
idx.z = j/(N.x*N.y);
dE = HB::Device::calcEnergy(gridData, n, idx);
if(dE < 0 || exp(-beta*dE) > gsl_rng_uniform(rng))
{
HB::Device::flip(gridData, idx, rng);
new_E += dE;
}
energies[idx] = new_E;
}
}*/
/*template <typename T, class M>
void HB::metropolisRun(M &model, HB::DeviceGrid &grid, T beta, size_t steps, std::vector<T> &energies)
{
energies.resize(0);
T energy = model.calcEnergy();
dim3 N = grid.getGridSize();
size_t Volume = N.x*N.y*N.z;
energies.push_back(energy/Volume);
size_t threads = 256;
size_t blocks = (V+threads-1)/threads;
thrust::device_vector<T> energies_to_reduce;
energies_to_reduce.resize(V);
curandState *devStates;
CUDA_CALL(cudaMalloc((void **)&devStates, V*sizeof(curandState)));
setup_kernel<<<blocks,threads>>>(devStates, time(NULL), V);
CUDA_CALL(cudaDeviceSynchronize());
for(size_t i = 0; i < steps; ++i)
{
cuda_MCSweep<<<blocks,threads>>>(grid->getTable().data(),
grid.data(),
V,
beta,
grid.getCoupling(),
thrust::raw_pointer_cast(
energies_to_reduce.data()),
devStates);
CUDA_CALL(cudaDeviceSynchronize());
energy += thrust::reduce(thrust::plus,
energies_to_reduce.first(),
energies_to_reduce.last(),
0.0);
//std::cout << i << " " << energy/V << std::endl;
energies.push_back(energy/Volume);
}
CUDA_CALL(cudaFree(devStates));
}*/
template <class M>
void HB::MetropolisSimulation::simulate(const M &model)
{
mEnergies.resize(0);
mMagnetization.resize(0);
float energy = model.calcEnergy(mGrid);
const dim3 N = mGrid->getGridSize();
const double Volume = double(N.x*N.y*N.z);
mEnergies.push_back(energy/Volume);
mMagnetization.push_back(model.calcMagn(mGrid)/Volume);
for(size_t i = 0; i < mSteps; ++i)
{
energy += metropolisSweep(model);
//std::cout << i << " " << energy/V << std::endl;
mEnergies.push_back(energy/Volume);
mMagnetization.push_back(model.calcMagn(mGrid)/Volume);
}
}
template <class M>
void HB::MetropolisSimulationQt::simulate(const M &model)
{
QPainter qp(this);
unsigned PenSize = 10;
unsigned offset = PenSize ? PenSize : 1;
QPen WhitePen(Qt::white, PenSize, Qt::SolidLine),
BlackPen(Qt::black, PenSize, Qt::SolidLine);
float energy = model.calcEnergy(mGrid);
metropolisSweep(model);
const dim3 N = mGrid->getGridSize();
dim3 index;
for(unsigned int i = 0; i < N.x; i++)
{
for(unsigned int j = 0; i < N.y; j++)
{
index.x = i; index.y = j; index.z = 0;
if(mGrid->getSpin(index) == 1) qp.setPen(WhitePen);
else qp.setPen(BlackPen);
qp.drawPoint(offset * i, offset * j);
//draw white point if spin 1, black if -1
}
}
}
template <class M>
void HB::SimulatedAnnealing::simulate(const M &model)
{
mEnergies.resize(0);
mMagnetization.resize(0);
float energy = model.calcEnergy(mGrid);
const dim3 N = mGrid->getGridSize();
const double Volume = double(N.x*N.y*N.z);
mEnergies.push_back(energy/Volume);
mMagnetization.push_back(model.calcMagn(mGrid)/Volume);
float beta;
for(float t = mTemperatureSteps.x; t <= mTemperatureSteps.y; t += mTemperatureSteps.z)
{
beta = 1.0f/t;
for(size_t i = 0; i < mSteps; ++i)
{
energy += metropolisSweep(model);
//std::cout << i << " " << energy/V << std::endl;
if(t + mTemperatureSteps.z > mTemperatureSteps.y)
{
mEnergies.push_back(energy/Volume);
mMagnetization.push_back(model.calcMagn(mGrid)/Volume);
}
}
}
}
void simulate(const HB::Models &models)
{
for(const auto &model : models)
{
model->simulate();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
template <typename T>
T mean(const std::vector<T> &o)
{
const size_t n = o.size();
T mean = 0.0;
#pragma omp parallel for reduction(+:mean)
for(size_t i = 0; i < n; ++i) mean += o[i];
return mean/T(n);
}
template <typename T>
T covFunc(const size_t t, const std::vector<T> &o) //autocovariance-function
{
const size_t n = o.size() - t;
T a = 0.0;
T b = 0.0;
T c = 0.0;
#pragma omp parallel for reduction(+:a,b,c)
for(size_t i = 0; i < n; ++i)
{
a += o[i]*o[i+t];
b += o[i];
c += o[i+t];
}
a /= T(n);
b /= T(n);
c /= T(n);
return a-(b*c);
}
template <typename T>
T intAuto(const std::vector<T> &o) //integrated autocorrelation-time
{
const size_t n = o.size();
T sum = 0;
const T var = cov_func(0, o);
T cov;
for(size_t t = 1; t < n; t++)
{
cov = cov_func(t, o);
if(cov > 0)
{
sum += (1-t/T(n)) * cov/var;
}
else break;
}
return 0.5 + sum;
}
template <typename T>
T error(const std::vector<T> &o) //error on expectation for given observable
{
return sqrt(cov_func(0, o)/T(o.size()));
}
template <typename T>
T blockingError(const std::vector<T> &o, const size_t block_number)
{
const size_t n = o.size();
size_t block_size = o.size()/block_number;
std::vector<T> block(block_size);
std::vector<T> variances(block_number);
for(size_t i = 0; i < block_number; ++i)
{
if(i == block_number - 1) block_size += n%block_number;
#pragma omp parallel for
for(size_t j = 0; j < block_size; ++j)
{
block[j] = o[j + i*block_number];
}
variances[i] = cov_func(0, block);
}
return sqrt(cov_func(0, variances)/T(block_number));
}
template <typename T>
T bootstrapError(const std::vector<T> &o, const size_t sample_size, const size_t sample_number, const T tau)
{
const size_t n = o.size();
std::vector<T> sample(sample_size);
std::vector<T> resample(sample_number);
for(size_t i = 0; i < sample_number; ++i)
{
#pragma omp parallel for
for(size_t j = 0; j < sample_size; ++j)
{
std::random_device device;
std::mt19937 generator(device());
std::uniform_real_distribution<float> distribution(0,1);
sample[j] = o[d2i(n/(2*tau))*distribution(generator)];
}
resample[i] = cov_func(0, sample);
}
return sqrt(cov_func(0, resample));
}
template <typename T>
T HB::errorProp(const std::vector<T> &o, const T tau)
{
const size_t n = o.size();
T mean_x;
{
std::vector<T> squares(n);
#pragma omp parallel for
for(size_t i = 0; i < n; ++i) squares[i] = o[i]*o[i];
mean_x = mean(squares);
}
const T mean_y = mean(o);
std::vector<T> f(n);
T square;
#pragma omp parallel for private(square)
for(size_t i = 0; i < n; ++i)
{
square = o[i]*o[i];
f[i] = (square - mean_x) - 2.0*o[i]*(square - mean_y);
}
return sqrt( 2.0*cov_func(0,f) * tau/T(f.size()) );
}
template <typename T>
T HB::errorPropEnergy(const std::vector<T> &energies, const T beta, const T tau, const size_t V)
{
return beta*beta*error_prop(energies, tau)/T(V);
}
template <typename T>
T HB::errorPropMagnetization(const std::vector<T> &magn, const T beta, const T tau, const size_t V)
{
return beta*error_prop(magn, tau)/T(V);
}
template <typename T>
size_t HB::d2i(const T d) //round double to int
{
if(d < 0) d *= -1;
return d<0?d-.5:d+.5;
}
template <typename T>
void HB::removeCorr(const std::vector<T> &o)
{
std::vector<T> help;
T autot = int_auto(o);
size_t n = o.size();
const size_t therm = d2i(20*autot);
size_t corr;
if(therm >= n)
{
std::cerr << n << " values given, but thermalisation needed " << therm << " steps!" << "\n";
return;
}
//std::cout << therm << std::endl;
n -= therm;
help.resize(n);
#pragma omp parallel for
for(size_t i = 0; i < n; ++i) help[i] = o[i+therm];
autot = int_auto(o);
//std::cout << autot << std::endl;
corr = d2i(2.0*autot);
if(corr == 1) return;
n /= corr;
o.resize(n);
#pragma omp parallel for
for(size_t i = 0; i < n; ++i) o[i] = help[i*corr];
}
template <typename T>
T HB::specificHeat(const std::vector<T> &energies, const T beta, const size_t V)
{
return beta*beta*cov_func(0, energies)/T(V);
}
template <typename T>
T HB::magnSusz(const std::vector<T> &magn, const T beta, const size_t V)
{
return beta*cov_func(0, magn)/T(V);
}
/*template <typename T, class S> __global__
HB::cuda_MCSweep(HB::NB *map, S *grid, dim3 gridSize, T beta, T J, T *new_E, curandState *state) //metropolis algorithm
{
T dE;
dim3 idx;
curandState localState = state[id];
idx.x = id% gridSize.x;
idx.y = id/ gridSize.x%gridSize.y;
idx.z = id/(gridSize.x*gridSize.y);
dE = model.cuda_calcEnergy(idx);
if(dE < 0 || exp(-beta*dE) > curand_uniform(&localState))
{
model.cuda_flip(idx, rng);
new_E[id] = dE;
}
else new_E[id] = 0.0;
state[id] = localState;
}*/
| [
"thomas.karl@ur.de"
] | thomas.karl@ur.de |
7d58bb0265cada4bc18e69aa5ddc86948084dbdd | ad123649273d25a34b0658b478d17363172f9b51 | /FileMd5Database/CSV.h | d1be2daae3e614afb3d3a99e4fa326994fa8d447 | [
"MIT"
] | permissive | iriszero48/FileMd5Database | 6d256302c6c3fc7a95235ee9400b8717c706c90d | 044af9cf148e8ea85560e65713f7d44392e87db4 | refs/heads/master | 2023-05-30T07:32:09.592784 | 2021-06-09T16:18:37 | 2021-06-09T16:18:37 | 284,423,166 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,024 | h | #pragma once
#include <fstream>
#include <memory>
class CsvFile
{
std::ofstream fs;
const std::uint64_t bufferSize = 1024 * 1024;
std::unique_ptr<char[]> buffer = std::make_unique<char[]>(bufferSize);
bool isFirst;
const std::string separator;
const std::string escapeSeq;
const std::string specialChars;
public:
explicit CsvFile(const std::string& filename, std::string separator = ";");
CsvFile() = delete;
~CsvFile();
void Flush();
void EndRow();
CsvFile& operator << (CsvFile& (*val)(CsvFile&));
CsvFile& operator << (const char* val);
CsvFile& operator << (const std::string& val);
template<typename T>
CsvFile& operator << (const T& val)
{
return Write(val);
}
static CsvFile& EndRow(CsvFile& file);
static CsvFile& Flush(CsvFile& file);
private:
template<typename T>
CsvFile& Write(const T& val)
{
if (!isFirst)
{
fs << separator;
}
else
{
isFirst = false;
}
fs << val;
return *this;
}
[[nodiscard]] std::string Escape(const std::string& val) const;
};
| [
"1026448790@qq.com"
] | 1026448790@qq.com |
52f2ee646323bd494c3b1d5691d8b1b86f950082 | aaca2118af6db0be9431ad767fe1c85edd5f5bb1 | /node/code/node_v14_s47/node_v14_s47.ino | e8ec18120b041b94d804d99abc3a8a7b8114ef18 | [] | no_license | xisphias/Lysimeter | ec8374d6d6ca41afea9504264dd8919762c2480a | 97a431713e7415245c72a024c1197f2ab06cea30 | refs/heads/master | 2021-01-20T03:22:47.214049 | 2017-09-01T01:15:39 | 2017-09-01T01:15:39 | 89,532,879 | 0 | 2 | null | 2017-05-18T00:53:35 | 2017-04-26T22:40:36 | null | UTF-8 | C++ | false | false | 19,388 | ino | /**
* TODO:
* Add timeout function to ping and timestamp
*
**/
#include "Thermistor.h"
#include "HX711.h" //https://github.com/bogde/HX711
#include <EEPROM.h> //Built in
#include "Sleepy.h" //https://github.com/kinasmith/Sleepy
#include "RFM69.h"
#include "RFM69_ATC.h" //https://www.github.com/lowpowerlab/rfm69
/****************************************************************************/
/*********************** DON'T FORGET TO SET ME ***********************/
/****************************************************************************/
#define NODEID 47 //Node Address
#define NETWORKID 100 //Network to communicate on
/****************************************************************************/
#define GATEWAYID 0 //Address of datalogger/reciever
#define FREQUENCY RF69_433MHZ
#define IS_RFM69HW //uncomment only for RFM69HW!
#define ATC_RSSI -70 //ideal Signal Strength of trasmission
#define ACK_WAIT_TIME 200 // # of ms to wait for an ack
#define ACK_RETRIES 5 // # of attempts before giving up
#define DOUT 8
#define CLK 7
#define zOutput 3.3
#define zInput A7 // Connect common (Z) to A7 (analog input)
#define eX A5 //Thermister excitation voltage
#define BAT_EN A0
#define BAT_V A6
#define LED 9
//#define SERIAL_EN //Comment this out to remove Serial comms and save a few kb's of space
#ifdef SERIAL_EN
#define DEBUG(input) {Serial.print(input); delay(1);}
#define DEBUGln(input) {Serial.println(input); delay(1);}
#define DEBUGFlush() { Serial.flush(); }
#else
#define DEBUG(input);
#define DEBUGln(input);
#define DEBUGFlush();
#endif
//battery voltage divider. Measure and set these values manually
const int bat_div_R1 = 14700;
const int bat_div_R2 = 3820;
const uint8_t scaleNmeasurements = 80; //no times to measure load cell for average
const int muxSelectPins[3] = {3, 4, 5}; // S0~3, S1~4, S2~5
// Define calibration for LC Y0 , Y1 , Y2 , Y3 , Y4 , Y5 , Y6 , Y8 }
long calibration_factor[8] = {54004,57228,55087,53939,54166,54772,56301,53976};
long zero_factor[8] = {36576,-13038,-492,-22636,-13376,-11023,-19119,-18178};
uint16_t count = 0; //measurement number
uint16_t EEPROM_ADDR = 5; //Start of data storage in EEPROM
/*==============|| TIMING ||==============*/
const uint8_t SLEEP_INTERVAL = 8; //sleep time in minutes
// 80 measurements * 8 ~ 120 sec, 40 ~ 56sec + 12 sec other stuff
const uint16_t SLEEP_MS = 60000; //one minute in milliseconds
const uint32_t SLEEP_SECONDS = SLEEP_INTERVAL * (SLEEP_MS / 1000); //Sleep interval in seconds
unsigned long timeout_start = 0; //holder for timeout counter
int timeout = 5000; //time in milsec to wait for ping/ts response
byte Retries = 1; //times to try ping and timestamp before giving up
int cycletime = 0; //counter for measurment time to add to sleeptime
HX711 scale(DOUT, CLK);
Thermistor temp(7);
ISR(WDT_vect) {
Sleepy::watchdogEvent(); // set watchdog for Sleepy
}
#ifdef ATC_RSSI
RFM69_ATC radio;
#else
RFM69 radio;
#endif //Declare radio (using Automatic Power Adjustments)
/*==============|| DATA ||==============*/
//Data structure for transmitting the Timestamp from datalogger to sensor (4 bytes)
struct TimeStamp {
uint32_t timestamp;
};
TimeStamp theTimeStamp; //creates global instantiation of this
//Data structure for storing data in EEPROM
struct Data {
uint16_t count = 0;
int battery_voltage = 0;
int board_temp = 0;
long w[8] = {0, 0, 0, 0, 0, 0, 0, 0};
int t[8] = {0, 0, 0, 0, 0, 0, 0, 0};
};
struct Payload {
uint32_t time = 0;
uint16_t count = 0;
int battery_voltage = 0;
int board_temp = 0;
long w[8] = {0, 0, 0, 0, 0, 0, 0, 0};
int t[8] = {0, 0, 0, 0, 0, 0, 0, 0};
};
Payload thisPayload;
void setup() {
Serial.begin(115200); // Initialize the serial port
// Set up the select pins as outputs:
for (int i = 0; i < 3; i++)
{
pinMode(muxSelectPins[i], OUTPUT);
digitalWrite(muxSelectPins[i], HIGH);
}
// pinMode(zInput, INPUT); // Set up Z as an input Don't need to do this, see below
pinMode(eX, OUTPUT); // Set excitation
pinMode(BAT_EN, OUTPUT); // Set excitation
// pinMode(BAT_V, INPUT); //Don't need to set pinMode for analog inputs. Setting it to INPUT sets as a DIGITAL INPUT, and is then set back to AnalogInput when analogRead() is called
digitalWrite(eX, LOW);
digitalWrite(BAT_EN, LOW);
pinMode(LED, OUTPUT); //led
//--SETUP OTHER STUFF
scale.set_scale(calibration_factor[0]);
scale.set_offset(zero_factor[0]);
//scale.tare(); //Reset the scale to 0
//long zero_factor = scale.read_average(10); //Get a baseline reading
//DEBUG("Zero factor: "); DEBUGln(zero_factor); //This can be used to remove the need to tare the scale. Useful in permanent scale projects.
//Setup Radio
radio.initialize(FREQUENCY, NODEID, NETWORKID);
//set radio rate to 4.8k
radio.writeReg(0x03,0x1A);
radio.writeReg(0x04,0x0B);
//set baud to 9.6k
// radio.writeReg(0x03,0x0D);
// radio.writeReg(0x04,0x05);
//set radio rate to 1.2k
// radio.writeReg(0x03,0x68);
// radio.writeReg(0x04,0x2B);
#ifdef IS_RFM69HW
radio.setHighPower();
#endif
radio.encrypt(null);
#ifdef ATC_RSSI
radio.enableAutoPower(ATC_RSSI);
#endif
DEBUG("-- Network Address: "); DEBUG(NETWORKID); DEBUG("."); DEBUGln(NODEID);
// Ping the datalogger. If it is alive, it will respond with a 1
while (!ping()) {
DEBUGln("Failed to setup ping");
//If datalogger doesn't respond, Blink, wait x seconds, and try again
radio.sleep();
Serial.flush();
Sleepy::loseSomeTime(1000);
Blink(20, 5);
}
DEBUGln("-- Datalogger Available");
}
void loop() {
//Gets current time at start of measurement cycle. Stores in global theTimeStamp struct
unsigned long starttime = millis();
bool gotTime = false;
for (int i = 0; i < Retries; i++) {
DEBUG("Timestamp request: "); DEBUGln(i);
gotTime = getTime();
if (gotTime) {
i = Retries;
Serial.print(" [RX:"); Serial.print(radio.RSSI); Serial.print("]");
}
}
if (!gotTime) { //Gets time from datalogger and stores in Global Variable
DEBUGln("time - No Response from Datalogger");
Blink(100,2);
// If the node gets no response the next measurement cycle will have the same timestamp
// as the last cycle. Could also set the timestamp here to a flag value...
}
count++;
DEBUG("- Measurement...");DEBUGln(count);
Blink(20, 3);
thisPayload.count = count;
thisPayload.battery_voltage = get_battery_voltage();
DEBUG("Bat V: ");
DEBUGln(float(thisPayload.battery_voltage) / 100.0);
thisPayload.board_temp = get_board_temp();
DEBUG("Board TempC: ");
DEBUGln(thisPayload.board_temp);
// Print the header:
DEBUGln("ch1\t\tch2\t\tch3\t\tch4\t\tch5\t\tch6\t\tch7\t\tch8");
DEBUGln("---\t\t---\t\t---\t\t---\t\t---\t\t---\t\t---\t\t---");
for (uint8_t i = 0; i < 8; i++)
{
selectMuxPin(i); // Select one at a time
delay(10); //this may or may not be needed
measureWeight(i);
digitalWrite(eX, HIGH);
delay(10);
thisPayload.t[i] = int(temp.getTemp() * 100); // need to check thermistor resistance on cable
digitalWrite(eX, LOW);
DEBUG(float(thisPayload.w[i]) / 10000.0);
DEBUG("kg ");
DEBUG(float(thisPayload.t[i]) / 100.0);
DEBUG(".C ");
}
DEBUGln();
// unsigned long onemeasure = millis();
// measureWeight(7);
// DEBUG("onemeasure: ");DEBUGln((millis() - onemeasure)/1000);
bool gotPing = false;
for (int i = 0; i < Retries; i++) {
DEBUG("Ping request: "); DEBUGln(i);
gotPing = ping();
if (gotPing) i = Retries;
}
cycletime = int((millis()-starttime)/1000);
DEBUG("measurement cycle time: ");DEBUGln(cycletime);
if (gotPing) {
//If the Datalogger is listening and available to recieve data
DEBUGln("- Datalogger Available");
//Check to see if there is data waiting to be sent
thisPayload.time = theTimeStamp.timestamp; //set payload time to current time
//DEBUGln(EEPROM.read(5));
if (EEPROM.read(5) > 0) { //check the first byte of data storage, if there is data, send it all
DEBUGln("- Stored Data Available, Sending...");
sendStoredEEPROMData();
}
if (EEPROM.read(5) == 0) { //Make sure there is no data stored, then send the measurement that was just taken
DEBUG("- No Stored Data, Sending ");
digitalWrite(LED, HIGH); //turn on LED
starttime = millis();
if (radio.sendWithRetry(GATEWAYID, (const void*)(&thisPayload), sizeof(thisPayload)), ACK_RETRIES, ACK_WAIT_TIME) {
Serial.println(thisPayload.count);
DEBUG("send time: ");DEBUGln(millis()-starttime);
DEBUG(sizeof(thisPayload)); DEBUG(" bytes -> ");
DEBUG('['); DEBUG(GATEWAYID); DEBUG("] ");
DEBUG(thisPayload.time);
digitalWrite(LED, LOW); //Turn Off LED
Blink(100, 1);
} else {
digitalWrite(LED, LOW); //Turn Off LED
Serial.println("- send fail");
DEBUGln("snd - Failed . . . no ack");
DEBUG("- Saving Locally");
writeDataToEEPROM(); //save that data to EEPROM
Blink(100, 2);
}
DEBUGln();
}
else {
//If there is no response from the Datalogger while sending the stored data, save
DEBUGln("- Datalogger Not Available for EEPROM send, Saving Locally");
writeDataToEEPROM(); //save that data to EEPROM
Blink(100, 3);
}
}
else {
//If there is no response from the Datalogger save data locally
Serial.println("- ping fail");
DEBUGln("- Datalogger Not Available, Saving Locally");
writeDataToEEPROM(); //save that data to EEPROM
Blink(100, 3);
}
DEBUG("- Sleeping for "); DEBUG(SLEEP_SECONDS); DEBUG(" seconds"); DEBUGln();
Serial.flush();
radio.sleep();
for (uint8_t i = 0; i < SLEEP_INTERVAL; i++)
Sleepy::loseSomeTime(SLEEP_MS);
// Sleepy::loseSomeTime(1000);
/*==============|| Wakes Up Here! ||==============*/
}
//measure load cell weight and store values
void measureWeight(uint8_t i)
{
Blink(20, int(scaleNmeasurements/10));
scale.power_up(); //powers on HX711
scale.set_scale(calibration_factor[i]); //sets calibration to this LC
scale.set_offset(zero_factor[i]); //sets zero to this LC
thisPayload.w[i] = round(scale.get_units(scaleNmeasurements) * 10000);
scale.power_down(); //powers off HX711
}
// The selectMuxPin function sets the S0, S1, and S2 pins
// accordingly, given a pin from 0-7.
void selectMuxPin(uint8_t pin)
{
for (int i = 0; i < 3; i++)
{
if (pin & (1 << i))
digitalWrite(muxSelectPins[i], HIGH);
else
digitalWrite(muxSelectPins[i], LOW);
}
}
int get_board_temp() {
int temperature = 0;
//code to pull temp from RFM69
temperature = radio.readTemperature(-1); // -1 = user cal factor, adjust for correct ambient
if (temperature > 100) temperature -= 255;
return temperature;
}
int get_battery_voltage() {
int readings = 0;
float v = 0;
float LSB = 3.3 / 1023;
float bV = 0;
digitalWrite(BAT_EN, HIGH);
delay(10);
for (byte i = 0; i < 3; i++)
{
readings += analogRead(BAT_V);
}
readings /= 3;
v = readings * LSB;
bV = ((bat_div_R1 + bat_div_R2) * v) / bat_div_R2;
bV *= 100.0;
digitalWrite(BAT_EN, LOW);
return int(bV);
}
/**
Retrieves data which was stored in EEPROM and sends it to the datalogger
with corrected timestamps for all recordings based off of the last stored
time.
*/
void sendStoredEEPROMData() {
DEBUGln("-- Retrieving Stored EEPROM DATA --");
Data blank; //init blank struct to erase data
Data theData; //struct to save data in
Payload tmp; //for temporary holding of data
/*
The stored time is the time of the last successful transmission,
so we need to add 1 Sleep Interval to the Stored Time to get accurate timestamp
*/
uint8_t storeIndex = 1;
uint32_t eep_time = 0UL;
byte sendRetries = 3;
EEPROM.get(1, eep_time); //get previously stored time (at address 1)
EEPROM_ADDR = 1 + sizeof(theTimeStamp.timestamp); //Set to next address
EEPROM.get(EEPROM_ADDR, theData); //Read in saved data to the Data struct
DEBUG(".stored time "); DEBUGln(theTimeStamp.timestamp);
DEBUGln(theData.battery_voltage); //this is where nothing would happen. EEPROM 5 was >0 so we got here, but battery V was 0, so we exited without sending and without clearing the eeprom.
while (theData.count > 0 && sendRetries < 10) { //while there is data available in the EEPROM // changed to count instead of battery V b/c batV was 0 in theData
uint32_t rec_time = eep_time + ((cycletime + SLEEP_SECONDS) * storeIndex); //Calculate the actual recorded time
DEBUG(".eep time "); DEBUGln(eep_time);
DEBUG(".rec time "); DEBUGln(rec_time);
//Save data into the Payload struct
tmp.time = rec_time;
tmp.count = theData.count;
tmp.battery_voltage = theData.battery_voltage;
tmp.board_temp = theData.board_temp;
for (int i = 0; i < 8; i++)
tmp.w[i] = theData.w[i];
for (int i = 0; i < 8; i++)
tmp.t[i] = theData.t[i];
//Send data to datalogger
digitalWrite(LED, HIGH); //turn on LED to signal transmission
if (radio.sendWithRetry(GATEWAYID, (const void*)(&tmp), sizeof(tmp)), ACK_RETRIES, ACK_WAIT_TIME) {
Serial.println("-stored sent");
DEBUG(".data sent, erasing...");
EEPROM.put(EEPROM_ADDR, blank); //If successfully sent, erase that data chunk...
EEPROM_ADDR += sizeof(theData); //increment to next...
DEBUG("reading index "); DEBUGln(EEPROM_ADDR);
EEPROM.get(EEPROM_ADDR, theData); // and read in the next saved data...
storeIndex += 1; //and increment the count of saved values
DEBUG(".store index "); DEBUGln(storeIndex);
digitalWrite(LED, LOW);
} else {
sendRetries++;
Serial.println("-stored send fail");
uint16_t waitTime = random(10000);
digitalWrite(LED, LOW);
DEBUG(".data send failed:"); DEBUG(sendRetries);
DEBUG("..waiting for retry for:");
DEBUG(waitTime);DEBUGln(" ms");
Blink(20, 5);
radio.sleep();
Sleepy::loseSomeTime(waitTime);
}
}
if(!(theData.count > 0)) { //only reset if eeprom was erased
DEBUGln(1 + sizeof(theTimeStamp.timestamp));
EEPROM_ADDR = 1 + sizeof(theTimeStamp.timestamp); //Reset Index to beginning of EEPROM_ADDR
//NOTE: This will front load the fatigue on the EEPROM causing failures of the first indeces
//NOTE: first. A good thing to do would be to build in a load balancing system to randomly
//NOTE: place data in the EEPROM with pointers to it.
}
}
/**
Saves sensor readings to EEPROM in case of tranmission failures to the datalogger.
*/
void writeDataToEEPROM() {
DEBUGln("-- Storing EEPROM DATA --");
Data theData; //Data struct to store data to be written to EEPROM
uint32_t eep_time = 0UL; //place to hold the saved time
//pull data from Payload to local struct to save
theData.count = thisPayload.count;
theData.battery_voltage = thisPayload.battery_voltage;
theData.board_temp = thisPayload.board_temp;
for (int i = 0; i < 8; i++)
theData.w[i] = thisPayload.w[i];
for (int i = 0; i < 8; i++)
theData.t[i] = thisPayload.t[i];
//update the saved eeprom time to the time of the
//last successful transaction (if they are different)
EEPROM.get(1, eep_time);
DEBUG(".saved time "); DEBUGln(eep_time);
DEBUG(".current time "); DEBUGln(theTimeStamp.timestamp);
if (theTimeStamp.timestamp != eep_time) {
EEPROM.put(1, theTimeStamp.timestamp);
DEBUGln(".updated time");
}
//check if there is space to save the next reading
//if there isn't, put the device to sleep forever and prime it
//so that next time it is started, it will dump all saved data to datalogger
if (EEPROM_ADDR < EEPROM.length() - sizeof(theData)) {
DEBUG(".saving "); DEBUG(sizeof(theData)); DEBUG(" bytes to address "); DEBUGln(EEPROM_ADDR);
EEPROM.put(EEPROM_ADDR, theData);
EEPROM_ADDR += sizeof(theData);
} else { //if there is not room, set INDEX 0 to 255 and sleep forever
EEPROM.write(0, 255); //this is not used...
DEBUGln(".eeprom FULL Sleepying For 12 hours");
Serial.flush();
radio.sleep();
//Sleepy::powerDown();
for (uint8_t i = 0; i < (60*12); i++) //sleep for 12 hours
Sleepy::loseSomeTime(SLEEP_MS);
}
}
/**
Requests the current time from the datalogger. Time is saved
to the global struct theTimeStamp.timestamp
@return boolean, TRUE on recieve, FALSE on failure
NOTE: This would be better if it just returned the uint32 value
of the timestamp instead of a boolean and then saving the time to a
global variable.
Success checking could still be done with if(!getTime()>0){} if it returned 0 or -1 on failure.
*/
bool getTime()
{
bool HANDSHAKE_SENT = false;
bool TIME_RECIEVED = false;
timeout_start = millis();
digitalWrite(LED, HIGH); //turn on LED to signal tranmission event
//Send request for time to the Datalogger
if (!HANDSHAKE_SENT) {
DEBUG("time - ");
if (radio.sendWithRetry(GATEWAYID, "t", 1, ACK_RETRIES, ACK_WAIT_TIME)) { //'t' requests time
DEBUG("snd . . ");
HANDSHAKE_SENT = true;
}
else {
//if there is no response, returns false and exits function
digitalWrite(LED, LOW); //turn off LED
// Blink(200, 4);
DEBUGln("failed . . . no ack");
return false;
}
}
//Wait for the time to be returned from the datalogger
while (!TIME_RECIEVED && HANDSHAKE_SENT) {
if (radio.receiveDone()) {
if (radio.DATALEN == sizeof(theTimeStamp)) { //check to make sure it's the right size
theTimeStamp = *(TimeStamp*)radio.DATA; //save data to global variable
DEBUG(" rcv - "); DEBUG('['); DEBUG(radio.SENDERID); DEBUG("] ");
DEBUG(theTimeStamp.timestamp); DEBUG(" [RX_RSSI:"); DEBUG(radio.RSSI); DEBUG("]"); DEBUGln();
TIME_RECIEVED = true;
digitalWrite(LED, LOW); //turn off LED
}
else {
digitalWrite(LED, LOW); //turn off LED
//Blink(200, 5);
DEBUGln("failed . . . received not timestamp");
return false;
}
if (radio.ACKRequested()) radio.sendACK();
}
if (millis() > timeout_start + timeout) { //it is possible that you could get the time and timeout, but only in the edge case
DEBUGln(" ...timestamp timeout");
return false;
}
}
return true;
}
/**
Requests a response from the Datalogger. For checking that the Datalogger is online
before sending data to it. It also latches this sensor to the datalogger until a 'r' is sent
eliminating issues with crosstalk and corruption due to multiple sensors sending data simultaniously.
@return boolean, TRUE is successful, FALSE is failure
*/
bool ping()
{
digitalWrite(LED, HIGH); //signal start of communication
//Send request for status to the Datalogger
DEBUG("ping - ");
if (radio.sendWithRetry(GATEWAYID, "p", 1, ACK_RETRIES, ACK_WAIT_TIME)) {
DEBUGln(" > p");
digitalWrite(LED, LOW);
return true;
}
else {
digitalWrite(LED, LOW);
// Blink(200, 6);
DEBUGln("failed: no ping ack");
return false; //if there is no response, returns false and exits function
}
}
void Blink(byte DELAY_MS, byte loops) {
for (byte i = 0; i < loops; i++)
{
digitalWrite(LED, HIGH);
delay(DELAY_MS);
digitalWrite(LED, LOW);
delay(DELAY_MS);
}
}
| [
"jasonclark@snail.local"
] | jasonclark@snail.local |
5912cdc9fd9f6fa8401d71656cb3a4df8db6e608 | 24645c1c980b887b173c499a295f1048cdf14984 | /Hist/test.cpp | f64522eb7cfe4a6cd742fe8f9e83884bcd97fb63 | [] | no_license | zhwan934940943/OpenCV_Test | df6e689a2420c028a5907a74c088960d0cf0e8b0 | 3bb72d25aa9a0fdee60eab2c88cfea5a59acf858 | refs/heads/master | 2022-12-20T23:56:37.386571 | 2020-10-02T14:20:54 | 2020-10-02T14:20:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 552 | cpp | #include<opencv2/opencv.hpp>
#include<my_utilityfunctions.h>
using namespace std;
using namespace cv;
int main()
{
Mat img = imread("../../../datasets/eye2.png");
checkImg(img);
uchar a = saturate_cast<uchar> (300) ;
Mat img_gray;
img2Gray(img, img_gray);
measureTime([&]() {
my_canny(img_gray);
});
measureTime([&]() {
Mat dst;
double thresh_dl = 15;
cv::Canny(img_gray, dst, thresh_dl, thresh_dl * 2, 3, true);
});
//vector<int> a;
//for (auto i = 1; i < 100; ++i)
// a.push_back(i);
return system("pause");
}
| [
"934940943@qq.com"
] | 934940943@qq.com |
ec6065f5373427d30b30b72ecdac43dfca0ba977 | 0bf4e9718ac2e2845b2227d427862e957701071f | /google_code_jam/all/r2_09/b/p2.cpp | cc59e191e1c47ee12f1a49fbcd0bf1d750885b60 | [] | no_license | unjambonakap/prog_contest | adfd6552d396f4845132f3ad416f98d8a5c9efb8 | e538cf6a1686539afb1d06181252e9b3376e8023 | refs/heads/master | 2022-10-18T07:33:46.591777 | 2022-09-30T14:44:47 | 2022-09-30T15:00:33 | 145,024,455 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,058 | cpp | #include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <cmath>
#include <cassert>
#define PI asin(1)*2.
#define EPS 10e-8
#define REP(i,n) for(i = 0; i < (n); i++)
#define REPC(i,n,c) for(i = 0; (i < (n)) && (c); i++)
#define REPV(i, n) for (i = (n) - 1; i >= 0; i--)
#define REPVC(i, n, c) for (i = (n) - 1; (i >= 0) && (c); i--)
#define FOR(i, a, b) for(i = (a); i <= (b); i++)
#define FORC(i, a, b, c) for(i = (a); (i <= (b)) && (c); i++)
#define FORV(i, a, b) for(i = (a); i >= (b); i--)
#define FORVC(i, a, b, c) for(i = (a); (i >= (b)) && (c); i--)
#define FE(i,t) for (typeof(t.begin())i=t.begin();i!=t.end();i++)
#define MAX(a,b) (((a) < (b)) ? (b) : (a))
#define MIN(a,b) (((a) < (b)) ? (a) : (b))
#define pb push_back
#define SZ(a) ((a).size())
#define two(x) (1 << (x))
#define twoll(x) (1LL << (x))
#define ALL(a) (a).begin(), (a).end()
#define CLR(a) (a).clear()
#define SWAP(a,b,c) (c=a, a=b, b=c)
#define SQR(x) (pow((x),2))
#define DIST(x,y) (SQR(x)+SQR(y))
#define CMP(x,y) ((fabs((x)-(y)) < EPS) ? 0 : ((x) < (y)) ? -1 : 1)
#define ll long long
using namespace std;
typedef pair<int,int> pii;
typedef vector<int> vi;
typedef queue<int> qi;
#define MAX_R 55
#define MAX_C 55
#define WALL '#'
#define EMPTY '.'
int w, h, f;
char map[MAX_R][MAX_C];
int dp[MAX_C][MAX_R][MAX_C][MAX_C];
int play(int x, int y, int sa, int sb, int fa){
int ea, eb, lhole, rhole;
int *p=&dp[x][y][sa][sb];
int s, m;
if (fa > f)return -2;
if (y == h-1) return 0;
if (*p != -1)return *p;
if (map[x][y+1] == EMPTY)
return play(x, y+1, x, x, fa+1);
ea=eb=x;
lhole=rhole=0;
while(ea >= 1){
ea--;
if (map[ea][y] == WALL && ea < sa){ea++; break;}
if (map[ea][y+1] == EMPTY){ea++, lhole=1; break;}
}
while(eb < w-1){
eb++;
if (map[eb][y] == WALL && eb > sb){eb--; break;}
if (map[eb][y+1] == EMPTY){eb--, rhole=1; break;}
}
m=-2;
if (lhole == 1){
s=play(ea-1, y+1, ea-1, ea-1, 1);
if (s >= 0 && (m == -2 || s < m))
m=s;
}
if (rhole == 1){
s=play(eb+1, y+1, eb+1, eb+1, 1);
if (s >= 0 && (m == -2 || s < m))
m=s;
}
int i, j;
s=-1;
if (ea != eb){
FOR(i, ea, eb){
FOR(j, i, eb){
if (i == ea && j == eb)continue;
if (j != eb){
s=play(j, y+1, i, j, 1);
//printf("%d %d ==> %d %d\n", i, j, j, s);
if (s >= 0 && (m == -2 || s+j-i < m))
m=s+j-i+1;
}if (i != ea){
s=play(i, y+1, i, j, 1);
//printf("%d %d ==> %d %d\n", i, j, i, s);
if (s >= 0 && (m == -2 || s+j-i < m))
m=s+j-i+1;
}
}
}
}
return ((*p)=m);
}
int solve(){
int i, j;
int x, y, v, nv, ny;
memset(dp, -1, sizeof(dp));
return play(0, 0, 0, 0, 0);
}
int main(){
int i, j, k, T;
cin >> T;
REP(i, T){
cin >> h >> w >> f;
scanf("\n");
REP(j, h){
REP(k, w)
scanf("%c", &map[k][j]);
scanf("\n");
}
printf("Case #%d: ", i+1);
j=solve();
if (j < 0)
printf("No\n");
else
printf("Yes %d\n", j);
}
return EXIT_SUCCESS;
}
| [
"benoit@uuu.com"
] | benoit@uuu.com |
fe42129fcb30f54be3019c30b21460749c2c4ab6 | 01abcef4b29e7bb5c6e22b3e246dd0d92e3f4da2 | /src/image_tcp/Utils.h | ad12e3229eabb764f3a876fe73a92c2f15a0f970 | [] | no_license | taxuewill/fastrtps_study | 690b63cb91092371186fdb5b8e155cc34c793a62 | 0140db5c5dab7db87c2ef0cab720a691bc345a28 | refs/heads/master | 2020-08-13T11:49:56.336998 | 2019-10-21T11:32:34 | 2019-10-21T11:32:34 | 214,963,819 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 454 | h | #ifndef UTILS_H
#define UTILS_H
#include <string>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <vector>
int64_t getCurrentTimestamp();
class CaculatorUtil{
public:
CaculatorUtil() = default;
void feedTime(int64_t time);
void dumpResult();
private:
std::vector<int64_t> timeVec;
int64_t minTime =0;
int64_t maxTime =0;
};
#endif // UTILS_H | [
"jing.wang2@ninebot.com"
] | jing.wang2@ninebot.com |
4ab31a9130e9560252c05d8ca88b34dde4f069c3 | 29640ff8c6804c873d2879d73b06843f3befafb7 | /Source/UE4_HomeTask7_Slate/MyHUD.h | 5d29a4a136a5c8eedccacb8beb62b1bb2c127b48 | [] | no_license | LinkFly/UE4_HomeTask7_Slate | ceea153d2a94eedcc88bfa7359357e152755b210 | 1f6ee2c2cdc34ae28cc2bb6bf42d5576df7fa20c | refs/heads/master | 2021-08-14T08:44:02.467785 | 2017-11-15T05:14:32 | 2017-11-15T05:14:32 | 110,786,778 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 409 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/HUD.h"
#include "SHealthBar.h"
#include "MyHUD.generated.h"
/**
*
*/
UCLASS()
class UE4_HOMETASK7_SLATE_API AMyHUD : public AHUD
{
GENERATED_BODY()
protected:
virtual void PostInitializeComponents() override;
TSharedPtr<class SHealthBar> HealthBarUI;
};
| [
"linkfly@yandex.ru"
] | linkfly@yandex.ru |
0080221a3f9c6d3724efa782301efa61d2eb95da | ecfbddcdf4fb6328d21dd69c4c768dd908689b5d | /source/polyvec/polygon-tracer/postprocessor.cpp | 0b2d51ea46ba8305cf3121a28dbaaa58a52265b7 | [
"MIT"
] | permissive | ShnitzelKiller/polyfit | 83aece9269e12b3d47d5cb0e4eb2884f551c9635 | 51ddc6365a794db1678459140658211cb78f65b1 | refs/heads/master | 2022-12-04T07:28:01.805877 | 2020-09-02T00:36:32 | 2020-09-02T00:36:32 | 291,927,085 | 0 | 0 | MIT | 2020-09-01T07:24:42 | 2020-09-01T07:24:41 | null | UTF-8 | C++ | false | false | 24,334 | cpp | // Polyvec
#include <polyvec/polygon-tracer/postprocessor.hpp>
#include <polyvec/polygon-tracer/error-metrics.hpp>
#include <polyvec/geometry/raster.hpp>
#include <polyvec/core/log.hpp>
#include <polyvec/geometry/angle.hpp>
#include <polyvec/polygon-tracer/regularized.hpp>
#include <polyvec/utils/matrix.hpp>
#include <polyvec/options.hpp>
#include <polyvec/curve-tracer/spline.hpp>
#include <polyvec/curve-tracer/fit_classifier.hpp>
#include <polyvec/curve-tracer/bezier_merging.hpp>
#include <polyvec/regularity/find_symmetric_primitives.hpp>
#include <polyvec/regularity/continuations.hpp>
// libc++
#include <unordered_set>
#define FANCY_SYMMETRIC_LOGIC 1
using namespace Eigen;
using namespace polyvec;
using namespace polyfit;
using namespace std;
NAMESPACE_BEGIN(polyvec)
PostProcessor::PostProcessor(
const mat2x& B,
const std::vector<Vertex>& M,
std::vector<BoundaryGraph::Edge>& E,
vecXi& P,
mat2x& PP,
std::vector<polyfit::Symmetry::SubPath>& raster_symmetries,
std::vector<polyfit::Symmetry::SubPath>& raster_symmetries_local,
polyfit::Regularity::RegularityInformation& RE,
std::vector<TangentFitType>& tangent_fits,
CurvePrimitiveSequence& curves,
const char* classifier_uri,
const int polygon_id
) :
circular(true),
B(B), M(M), E(E), P(P), PP(PP), raster_symmetries(raster_symmetries), raster_symmetries_local(raster_symmetries_local),
regularity(RE), tangent_fits(tangent_fits), curves(curves),
classifier_uri(classifier_uri), polygon_id(polygon_id) {
BoundaryGraph::connect_valid_edges(B, M, _E_original, true, &_accuracy_map);
}
/*
Finds all the polygon edges which are within 2 pixels and for which one of the two corners
has been identified as C^0 and attempts to remove them.
The edge connecting the two pixels is removed and the shortest path is rerun, making sure that
none of the regularities is broken.
*/
struct Collapsable {
Collapsable(const int v_src, const int v_dst, const int v_force) :
v_src(v_src), v_dst(v_dst), v_force(v_force) { }
int v_src;
int v_dst;
int v_force;
};
void PostProcessor::retrace_with_C0_corners() {
std::vector<bool> corners_C0(B.cols(), false);
std::vector<size_t> corners;
for (Index i = 0; i < P.size(); ++i) {
if (tangent_fits[i] == TANGENT_FIT_CONSTANT) {
corners_C0[P(i)] = true;
corners.emplace_back(P(i));
}
}
// Actually forcing the path to go through the corners
_E = _E_original;
_E_delete.clear();
for (size_t i = 0; i < _E.size(); ++i) {
const vec2 p = B.col(_E[i].v0);
const vec2 pn = B.col(_E[i].v1);
for (size_t j = 0; j < corners.size(); ++j) {
if (PathUtils::contains_open(B, _E[i].v0, _E[i].v1, corners[j], circular)) {
_E_delete.emplace_back(i);
break;
}
}
}
EraseOrdered(_E, _E_delete);
PolygonTracer::regularized(_G_state, B, M, _E, regularity, P, raster_symmetries, raster_symmetries_local, circular, nullptr, corners_C0);
BoundaryGraph::trace_to_points(B, P, PP);
}
void PostProcessor::collapse_short_segments() {
FitClassifierRandomForest classifier;
classifier.load_from_file(classifier_uri.c_str());
collapse_short_segments_iteration();
trace_curves_from_polygon(classifier);
}
int PostProcessor::collapse_short_segments_iteration() {
double max_edge_length_sq = Options::get()->post_processor_max_short_edge_length;
max_edge_length_sq *= max_edge_length_sq;
// Let's gather all the edges which need to be collapsed
std::vector<Collapsable> to_collapse;
std::vector<int> C;
PathUtils::compute_convexities(B, C);
for (Index i = 0; i < P.size(); ++i) {
const int v = P(i);
const int vn = CircularAt(P, i + 1);
const vec2 p = B.col(v);
const vec2 pn = B.col(vn);
const double edge_length_sq = (p - pn).squaredNorm();
const bool is_inflection = AngleUtils::have_opposite_convexity(
B.col(CircularAt(P, i - 1)), p, pn, B.col(CircularAt(P, i + 2))
);
if (is_inflection) {
continue;
}
if (edge_length_sq > max_edge_length_sq + PF_EPS) {
continue;
}
PF_ASSERT(tangent_fits.size() == P.size());
const TangentFitType fit_src = tangent_fits[i];
const TangentFitType fit_dst = CircularAt(tangent_fits, i + 1);
if (fit_src != TANGENT_FIT_CONSTANT && fit_dst != TANGENT_FIT_CONSTANT) {
continue;
}
//
const int is_diagonal = CircularDist(B, v, vn) == 3;
if (is_diagonal && fit_src == TANGENT_FIT_CONSTANT && fit_dst == TANGENT_FIT_CONSTANT) {
const int cn = CircularAt(C, vn - 1);
const int cp = CircularAt(C, v + 1);
if (cn == -1) {
to_collapse.emplace_back(v, vn, Circular(C, vn - 1));
}
else if (cp == -1) {
to_collapse.emplace_back(v, vn, Circular(C, v + 1));
}
}
// Figuring out where to place the corner, if only one of the corners is C^0 then that is where it will
// be placed. If both are C^0 and it's symmetric then into a midpoint if it exists, otherwise we need
// attempt both corners.
else if (fit_src == TANGENT_FIT_CONSTANT && fit_dst == TANGENT_FIT_CONSTANT) {
const bool midpoint_exists = CircularDist(P, v, vn) == 2 && GeomRaster::are_points_axis_aligned(p, pn);
if (midpoint_exists) {
to_collapse.emplace_back(v, vn, (int)Circular(B, v + 1));
}
else {
const int dist_prev = CircularDist(B, PathUtils::next_transition_vertex(C, v, -1, circular), v);
const int dist_next = CircularDist(B, vn, PathUtils::next_transition_vertex(C, vn, +1, circular));
if (dist_prev > dist_next) {
to_collapse.emplace_back(v, vn, v);
}
else if (dist_prev < dist_next) {
to_collapse.emplace_back(v, vn, vn);
}
}
}
else if (fit_src == TANGENT_FIT_CONSTANT) {
to_collapse.emplace_back(v, vn, v);
}
else if (fit_dst == TANGENT_FIT_CONSTANT) {
to_collapse.emplace_back(v, vn, vn);
}
else {
continue;
}
}
_set_immovable_corners();
//return 0;
int collapsed = 0;
for (size_t i = 0; i < to_collapse.size(); ++i) {
// Are we collapsing onto an immovable corners
bool collapsing_regularity_safely =
(!_immovable[to_collapse[i].v_dst] && _immovable[to_collapse[i].v_src] && to_collapse[i].v_src == to_collapse[i].v_force) ||
(!_immovable[to_collapse[i].v_src] && _immovable[to_collapse[i].v_dst] && to_collapse[i].v_dst == to_collapse[i].v_force) ||
(!_immovable[to_collapse[i].v_src] && !_immovable[to_collapse[i].v_dst]);
// but not both should be immovable
if (_immovable[to_collapse[i].v_src] && _immovable[to_collapse[i].v_dst]) {
collapsing_regularity_safely = false;
}
// Are we collapsing a regularity or collapsing it into the very same vertex
PF_DEV_F("Attempting to collapse (%d %d) -> %d is_safe %d", to_collapse[i].v_src, to_collapse[i].v_dst, to_collapse[i].v_force, collapsing_regularity_safely);
if (collapsing_regularity_safely) {
if (_relocate_short_edge(to_collapse[i].v_src, to_collapse[i].v_dst, to_collapse[i].v_force)) {
++collapsed;
}
}
if (collapsed == 2) {
break;
}
}
return collapsed;
}
/*
Run steps which have not been run during post-processing (i.e. curve fitting)
*/
void PostProcessor::trace_curves_from_polygon(FitClassifier& classifier) {
// come on...
std::vector<Vertex> PV(P.size());
for (size_t i = 0; i < PV.size(); ++i) {
PV[i] = P(i);
}
CurveSequenceFitter fitter(B, PP, PV, regularity, polygon_id);
curves = fitter.fit_evolutionary_simple(classifier, tangent_fits, nullptr);
}
namespace {
bool is_degenerate(const mat2x& B, const vecXi& P, const int v0, const int v1, const bool circular) {
if (!circular && (v0 == 0 || v1 == P.size() - 1)) {
return false;
}
const vec2 p0p = B.col(CircularAt(P, v0 - 1));
const vec2 p0 = B.col(CircularAt(P, v0));
const vec2 p1 = B.col(CircularAt(P, v1));
const vec2 p1n = B.col(CircularAt(P, v1 + 1));
if (!AngleUtils::have_opposite_convexity(p0p, p0, p1, p1n)) {
return false;
}
if ((p0 - p1).squaredNorm() > 1. + PF_EPS) {
return false;
}
return true;
}
}
bool PostProcessor::_should_accept_trace() const {
unsigned int degenerate_edges_before = 0;
for (Index i = 0; i < P.size(); ++i) {
degenerate_edges_before += is_degenerate(B, P, i, Circular(P, i + 1), circular) ? 1 : 0;
}
unsigned int degenerate_edges_after = 0;
for (Index i = 0; i < _P.size(); ++i) {
degenerate_edges_after += is_degenerate(B, _P, i, Circular(_P, i + 1), circular) ? 1 : 0;
}
if (degenerate_edges_after > degenerate_edges_before) {
return false;
}
// Count symmetries
unsigned int symmetries_before = regularity.vertex_symmetries().size();
return true;
}
// let's not retrace just move the point to a more smooth location.
bool PostProcessor::_relocate_short_edge(const int v_src, const int v_dst, const int v_force) {
// Not enough degrees of freedom
if (P.size() < 6) {
return false;
}
PF_VERBOSE_F("Postprocessor graph has %d edges", E.size());
PF_VERBOSE_F("Relocating %d %d -> %d", v_src, v_dst, v_force);
// v_force can either be v_src or v_dst or the midpoint
const bool collapsing_to_midpoint = CircularDist(B, v_src, v_dst) == 2 && Circular(B, v_src + 1) == v_force;
PF_ASSERT(v_force == v_src || v_force == v_dst || collapsing_to_midpoint);
if (collapsing_to_midpoint && find(M.begin(), M.end(), v_force) == M.end()) {
return false;
}
// Replace the first half of the subpath
const bool replace_to_src = collapsing_to_midpoint || v_force == v_dst;
const bool replace_from_dst = collapsing_to_midpoint || v_force == v_src;
// I am sorry
std::vector<int> C;
BoundaryGraph::trace_to_points(B, P, PP);
PathUtils::compute_convexities(PP, C);
// We need to find the polygon indices for this vertices
int v_src_poly = -1;
for (Index i = 0; i < P.size(); ++i) {
if (P(i) == v_src) {
v_src_poly = i;
break;
}
}
int v_dst_poly = Circular(P, v_src_poly + 1);
// This has been collapsed in previous edits
if (P(v_dst_poly) != v_dst) {
return false;
}
// Making sure that we are not breaking existing symmetries
#if FANCY_SYMMETRIC_LOGIC
bool would_break_symmetry = false;
for (auto& r : regularity.vertex_symmetries()) {
const int dist_to_src = CircularDist(P, v_dst_poly, r.v0);
const int dist_from_dst = CircularDist(P, r.v1, v_src_poly);
if (min(dist_to_src, dist_from_dst) >= 2) {
continue;
}
if (Circular(P, r.v0 + 1) == r.v1 || Circular(P, r.v0 - 1) == r.v1) {
// We want to preserve the same angle
const int v_prev_0 = PathUtils::opposite(P.size(), r.v1, r.v0);
const int v_prev_1 = PathUtils::opposite(P.size(), r.v0, r.v1);
bool are_symmetric = false;
for (const auto s : regularity.vertex_symmetries(v_prev_0)) {
if ((s.v0 == v_prev_0 && s.v1 == v_prev_1) ||
(s.v1 == v_prev_0 && s.v0 == v_prev_1)) {
are_symmetric = true;
break;
}
}
PF_DEV_F("angle_0 %d %d %d angle_1 %d %d %d", v_prev_0, r.v0, r.v1, v_prev_1, r.v1, r.v0);
const float angle_0 = AngleUtils::spanned_shortest(B.col(P(v_prev_0)), B.col(P(r.v0)), B.col(P(r.v1)));
const float angle_1 = AngleUtils::spanned_shortest(B.col(P(v_prev_1)), B.col(P(r.v1)), B.col(P(r.v0)));
PF_DEV_F("Vertex symmetry %d %d angle_0 %f s %f", r.v0, r.v1, angle_0, angle_1);
int c_src = C[v_src_poly];
int c_dst = C[v_dst_poly];
int c_next = replace_to_src ? C[Circular(P, v_src_poly - 1)] : C[Circular(P, v_dst_poly + 1)];
// The purpose of the collapse is to remove visually disruptive inflections, making sure we are removing an inflection
if (abs(angle_0 - angle_1) < PF_EPS && !are_symmetric && c_src == c_dst && c_next == c_dst) {
would_break_symmetry = true;
}
}
}
if (would_break_symmetry) {
return false;
}
#endif
PF_ASSERT(P(v_dst_poly) == v_dst);
vec3i fix_src, fix_dst;
if (v_src == v_force) {
fix_src = vec3i(Circular(P, v_src_poly - 2), Circular(P, v_src_poly - 1), Circular(P, v_src_poly));
fix_dst = vec3i(Circular(P, v_dst_poly + 2), Circular(P, v_dst_poly +3), Circular(P, v_dst_poly + 4));
} else if (v_dst == v_force) {
fix_src = vec3i(Circular(P, v_src_poly - 4), Circular(P, v_src_poly - 3), Circular(P, v_src_poly - 2));
fix_dst = vec3i(Circular(P, v_dst_poly), Circular(P, v_dst_poly + 1), Circular(P, v_dst_poly + 2));
} else {
fix_src = vec3i(Circular(P, v_src_poly - 3), Circular(P, v_src_poly - 2), Circular(P, v_src_poly - 1));
fix_dst = vec3i(Circular(P, v_dst_poly + 1), Circular(P, v_dst_poly + 2), Circular(P, v_dst_poly + 3));
}
PF_VERBOSE_F("fix_src %d %d %d", P(fix_src(0)), P(fix_src(1)), P(fix_src(2)));
PF_VERBOSE_F("fix_dst %d %d %d", P(fix_dst(0)), P(fix_dst(1)), P(fix_dst(2)));
vector<bool> corners_C0(B.cols(), false);
if (collapsing_to_midpoint) {
corners_C0[P(fix_src(2))] = true;
corners_C0[P(fix_dst(0))] = true;
} else {
corners_C0[v_force] = true;
}
vector<BoundaryGraph::Node> N;
BoundaryGraph::construct_nodes(B, E, M, N);
vector<ShortestPath::Node> G;
BoundaryGraph::construct_trace_graph(B, E, M, N, G, true, corners_C0);
Index hn_src = -1, hn_dst = -1;
for (Index i = 0; i < G.size(); ++i) {
const auto& n = N[G[i].v];
if (hn_src != -1 && hn_dst != -1) {
break;
}
if (n.v0 == P(fix_src(0)) && n.v1 == P(fix_src(1)) && n.v2 == P(fix_src(2))) {
PF_ASSERT(hn_src == -1);
hn_src = i;
}
if (n.v0 == P(fix_dst(0)) && n.v1 == P(fix_dst(1)) && n.v2 == P(fix_dst(2))) {
PF_ASSERT(hn_dst == -1);
hn_dst = i;
}
}
// The path has changed since the last time
if (hn_src == -1 || hn_dst == -1) {
return false;
}
vector<Index> subP;
ShortestPath::find(_G_state, G, hn_src, hn_dst, subP);
for (Index v : subP) {
PF_VERBOSE_F("%d", N[G[v].v].v1);
}
int v_remove = fix_src(2);
const int v_remove_last = P(fix_dst(1));
while (P(v_remove) != v_remove_last) {
PF_VERBOSE_F("%d != %d", P(v_remove), v_remove_last);
EraseOrdered(P, { v_remove });
v_remove = Circular(P, v_remove);
PF_ASSERT(P.size() > 0);
}
PF_VERBOSE_F("Remove index %d (%d)", v_remove, P(v_remove));
for (size_t i = 1; i < subP.size() - 1; ++i) {
MatrixUtils::insert_at(P, v_remove + i - 1, N[G[subP[i]].v].v1);
}
PF_VERBOSE_F("Total length %d", P.size());
for (Index i = 0; i < P.size(); ++i) {
PF_VERBOSE_F("P %d", P(i));
}
BoundaryGraph::trace_to_points(B, P, PP);
regularity.reset();
regularity.update(B, P, raster_symmetries, raster_symmetries_local, true);
auto candidates = Regularity::find_continuation_candidates(B, P, regularity, circular, false);
Regularity::pick_continuations(B, P, candidates, regularity, circular, E);
return true;
}
/*
Removes the edge connecting v_src and v_dst and forces the path to go through v_force.
Returns true if the polygon has been updated without introducing new degenerate edges or inflections.
If the operation has succeded the list of edges which have been delete is added to the permanent list of deleted
edges.
*/
bool PostProcessor::_attempt_remove_edge_force_corner ( const int v_src, const int v_dst, const int v_force ) {
_E = _E_original;
_E_delete.clear();
_E_delete_temp.clear();
// This whole thing needs to be rewritten anyway
PF_VERBOSE_F("Remove edge %d %d", v_src, v_dst);
int v_poly = -1;
for (Index i = 0; i < P.size(); ++i) {
if (P(i) == v_src) {
v_poly = i;
break;
}
}
PF_ASSERT(v_poly != -1);
const vec3i v_fix_before(CircularAt(P, v_poly - 5), CircularAt(P, v_poly - 4), CircularAt(P, v_poly - 3));
const vec3i v_fix_after(CircularAt(P, v_poly + 2), CircularAt(P, v_poly + 3), CircularAt(P, v_poly + 4));
PF_VERBOSE_F("Fix before (%d %d %d)", v_fix_before(0), v_fix_before(1), v_fix_before(2));
PF_VERBOSE_F("Fix after (%d %d %d)", v_fix_after(0), v_fix_after(1), v_fix_after(2));
for (size_t i = 0; i < _E.size(); ++i) {
if (_E[i].v0 == v_src && _E[i].v1 == v_dst) {
_E_delete.emplace_back(i);
continue;
}
if (PathUtils::contains_open(B, _E[i].v0, _E[i].v1, v_force, true)) {
_E_delete.emplace_back(i);
continue;
}
if ((_E[i].v0 == v_fix_before(0) && _E[i].v1 == v_fix_before(1)) ||
(_E[i].v0 == v_fix_before(1) && _E[i].v1 == v_fix_before(2)) ||
(_E[i].v0 == v_fix_after(0) && _E[i].v1 == v_fix_after(1)) ||
(_E[i].v0 == v_fix_after(1) && _E[i].v1 == v_fix_after(2))) {
continue;
}
if (PathUtils::contains_open(B, v_fix_after(0), v_fix_after(2), _E[i].v0, true) ||
PathUtils::contains_open(B, v_fix_after(0), v_fix_after(2), _E[i].v1, true) ||
PathUtils::contains_open(B, v_fix_before(0), v_fix_before(2), _E[i].v0, true) ||
PathUtils::contains_open(B, v_fix_before(0), v_fix_before(2), _E[i].v1, true)) {
_E_delete_temp.emplace_back(i);
}
}
_E_delete_all.clear();
_E_delete_all.insert(_E_delete_all.end(), _E_delete.begin(), _E_delete.end());
_E_delete_all.insert(_E_delete_all.end(), _E_delete_permanent.begin(), _E_delete_permanent.end());
//_E_delete_all.insert(_E_delete_all.end(), _E_delete_temp.begin(), _E_delete_temp.end());
sort(_E_delete_all.begin(), _E_delete_all.end());
EraseDuplicatesOrdered(_E_delete_all);
EraseOrdered(_E, _E_delete_all);
ShortestPath::State G_state;
PolygonTracer::regularized(G_state, B, M, _E, _RE, _P, raster_symmetries, raster_symmetries_local, true);
if (_P.size() > 0 && _should_accept_trace()) {
P = _P;
regularity = _RE;
BoundaryGraph::trace_to_points(B, P, PP);
// Making the current delete list permanent
_E_delete_permanent.insert(_E_delete_permanent.end(), _E_delete.begin(), _E_delete.end());
return true;
}
return false;
}
void PostProcessor::_reset_immovable_corners() {
_immovable.resize(B.cols(), false);
}
/*
Setting every corner which is a critical part of a regularity to 0
*/
void PostProcessor::_set_immovable_corners() {
double max_edge_length_sq = Options::get()->post_processor_max_short_edge_length;
max_edge_length_sq *= max_edge_length_sq;
PF_VERBOSE_F("Setting immovable corners with %d regularities", (int)regularity.size());
_reset_immovable_corners();
for (auto& r : regularity.parallels()) {
PF_VERBOSE_S("Regularity parallel");
if (r.connected_00_11) {
_immovable[P(r.v00)] = true;
_immovable[P(r.v11)] = true;
PF_VERBOSE_F("Making %d immovable", r.v00);
PF_VERBOSE_F("Making %d immovable", r.v11);
}
if (r.connected_01_10) {
_immovable[P(r.v01)] = true;
_immovable[P(r.v10)] = true;
PF_VERBOSE_F("Making %d immovable", r.v01);
PF_VERBOSE_F("Making %d immovable", r.v10);
}
}
for (auto& r : regularity.continuations()) {
PF_VERBOSE_S("Regularity continuation");
//_immovable[P(r.data.continuation.v0_prev)] = true;
//_immovable[P(r.data.continuation.v0)] = true;
//_immovable[P(r.data.continuation.v1)] = true;
//_immovable[P(r.data.continuation.v1_next)] = true;
}
// We also do not want to break axis-aligned lines
for (Index i = 0; i < P.size(); ++i) {
const int v = P(i);
const int vn = CircularAt(P, i + 1);
const vec2 p = B.col(v);
const vec2 pn = B.col(vn);
if (!GeomRaster::are_points_axis_aligned(p, pn)) {
continue;
}
const double len_sq = (p - pn).squaredNorm();
if (len_sq < max_edge_length_sq + PF_EPS) {
continue;
}
_immovable[v] = true;
_immovable[vn] = true;
}
// Aswell as axis-aligned angles
for (Index i = 0; i < P.size(); ++i) {
const int v = P(i);
const int vn = CircularAt(P, i + 1);
const int vnn = CircularAt(P, i + 2);
const double angle_vn = AngleUtils::spanned_shortest(B.col(v), B.col(vn), B.col(vnn));
const double len_sq = min((B.col(v) - B.col(vn)).squaredNorm(), (B.col(vn) - B.col(vnn)).squaredNorm());
if (abs(angle_vn - M_PI_2) < PF_EPS && len_sq > 1. + PF_EPS) {
_immovable[v] = true;
_immovable[vn] = true;
_immovable[vnn] = true;
}
}
// We shouldn't be moving points which are along the axis of symmetry
// That is exactly a midpoint!
for (Index i = 0; i < M.size(); ++i) {
_immovable[M[i]] = true;
}
}
const std::vector<bool>& PostProcessor::get_immovable_corners() const {
return _immovable;
}
const std::vector<BoundaryGraph::Edge>& PostProcessor::get_original_edges() const {
return _E_original;
}
const std::vector<size_t>& PostProcessor::get_permanently_deleted_edges() const {
return _E_delete_permanent;
}
void PostProcessor::merge_curves()
{
polyfit::BezierMerging::MergeRecursivelyOptions options;
options.allow_merging_lines = true;
options.distance_tolerance = 0.25;
options.alpha_max = 0.8;
options.per_bezier_const = 1.5;
auto symmetric_curves = Regularity::find_symmetric_primitives(regularity.edge_symmetries(), curves, P.size());
std::vector<Eigen::Matrix2Xd> in_curves, out_curves;
std::vector<std::vector<int>> out2in;
for (auto& p : curves.primitives)
{
auto c = p.curve->get_curve();
auto bezier = dynamic_pointer_cast<BezierCurve>(c);
auto line = dynamic_pointer_cast<GlobFitCurve_Line>(c);
if (bezier)
{
in_curves.push_back(bezier->get_control_points());
continue;
}
if (line)
{
in_curves.push_back(line->get_points());
continue;
}
throw std::runtime_error("There is a primitive whose type was not anticipated during curve merging.");
}
polyfit::BezierMerging::merge_curves(
in_curves, true, options, symmetric_curves, out_curves, out2in);
CurvePrimitiveSequence new_sequence;
std::vector<TangentFitType> new_tangent_fits;
for (int i = 0; i < out_curves.size(); ++i)
{
new_sequence.primitives.emplace_back();
if (out_curves[i].cols() == 2)
new_sequence.primitives.back().curve = std::make_shared<GlobFitCurveParametrization>(std::make_shared<GlobFitCurve_Line>(out_curves[i]));
else if (out_curves[i].cols() == 4)
new_sequence.primitives.back().curve = std::make_shared<GlobFitCurveParametrization>(std::make_shared<BezierCurve>(out_curves[i]));
else
throw std::runtime_error("Curve merging produced a curve with " + std::to_string(out_curves[i].cols()) + " control points");
// dummy type
new_tangent_fits.push_back(TANGENT_FIT_CONSTANT);
}
curves = std::move(new_sequence);
tangent_fits = std::move(new_tangent_fits);
}
NAMESPACE_END(polyvec) | [
"edoaramis@gmail.com"
] | edoaramis@gmail.com |
3df8fc23d38fb7f667519946a556b217bcd3706f | 1e018556f02f2b1eb729d52e704bcc6b7f9f5f7b | /video/common/Video/jhcGenVSrc.h | 88365faa164105390f65f553879d55ff941df44e | [
"Apache-2.0"
] | permissive | ghas-results/ALIA | 3e9de2e4d98e0376c43d7a10ce568d64a9023ab1 | 4dc5e76c3280ece5471eddca875c6b7fa35e6beb | refs/heads/master | 2023-08-10T03:40:25.889007 | 2020-07-20T02:19:49 | 2020-07-20T02:19:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,999 | h | // jhcGenVSrc.h : wrapper to homogenize other video sources
//
// Written by Jonathan H. Connell, jconnell@alum.mit.edu
//
///////////////////////////////////////////////////////////////////////////
//
// Copyright 1998-2019 IBM Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////////
#ifndef _JHCGENVSRC_
/* CPPDOC_BEGIN_EXCLUDE */
#define _JHCGENVSRC_
/* CPPDOC_END_EXCLUDE */
#include "jhcGlobal.h"
#include "Video/jhcVideoSrc.h"
//= Wrapper to homogenize other video sources.
// This is a shell that internally contains another video source.
// A lot of member variables are duplicated, but can use with "new".
// Usually create one of these with a file or framegrabber name.
// Can also reinitialize to a different file after creation.
// Uses global registry object "jvreg" to find correct source class.
// NOTE: Global macro JHC_GVID must be declared to get types to self-register.
class jhcGenVSrc : public jhcVideoSrc
{
// PROTECTED MEMBER VARIABLES
protected:
int xlim, ylim, Mono;
jhcVideoSrc *gvid;
char def_ext[20];
// PUBLIC MEMBER VARIABLES
public:
int index; /** When to make index (if applicable, e.g. MPEG). */
// PUBLIC MEMBER FUNCTIONS
public:
~jhcGenVSrc ();
jhcGenVSrc ();
jhcGenVSrc (const char *name);
void Default (const char *ext);
// basic construction and operation
int SetSource (const char *name);
void Release ();
void Prefetch (int doit =1)
{if (gvid != NULL) gvid->Prefetch(doit);}
void Close () {Release();}
// pass-through configuration functions
void SetStep (int offset, int key =0);
void SetRate (double fps);
void SetSize (int xmax, int ymax, int bw =0);
int SetVal (const char *tag, int val)
{return((gvid == NULL) ? -1 : gvid->SetVal(tag, val));}
int SetDef (const char *tag =NULL, int servo =0)
{return((gvid == NULL) ? -1 : gvid->SetDef(tag, servo));}
int SetABits (int n)
{if (gvid != NULL) adim = gvid->SetABits(n); return adim;}
int SetAChan (int ch)
{if (gvid != NULL) ach = gvid->SetAChan(ch); return ach;}
int SetARate (int sps)
{if (gvid != NULL) asps = gvid->SetARate(sps); return asps;}
// pass-through property functions
const char *StrClass ();
int BaseClass (const char *cname);
int StepTime (double rate =-1.0, int src =0);
int TimeStamp ()
{return((gvid == NULL) ? 0 : gvid->TimeStamp());}
const char *FrameName (int idx_wid =-1, int full =0)
{return((gvid == NULL) ? NULL : gvid->FrameName(idx_wid, full));}
int GetVal (int *val, const char *tag)
{return((gvid == NULL) ? -1 : gvid->GetVal(val, tag));}
int GetDef (int *vdef, const char *tag, int *vmin =NULL, int *vmax =NULL, int *vstep =NULL)
{return((gvid == NULL) ? -1 : gvid->GetDef(vdef, tag, vmin, vmax, vstep));}
int AuxCnt () const
{return((gvid != NULL) ? gvid->AuxCnt() : 0);}
const UC8 *AuxData () const
{return((gvid!= NULL) ? gvid->AuxData() : NULL);}
// PROTECTED MEMBER FUNCTIONS
protected:
// initializers for various encapsulated types
void init_vals ();
int new_source (const char *hint =NULL);
#ifdef _LIB
int RegisterAll (); // make sure types get registered for static libraries
#endif
// PRIVATE MEMBER FUNCTIONS
private:
// core functionality
int iSeek (int number);
int iGet (jhcImg& dest, int *advance, int src, int block);
int iDual (jhcImg& dest, jhcImg& dest2);
int iAGet (US16 *snd, int n, int ch);
};
#endif
| [
"jconnell@us.ibm.com"
] | jconnell@us.ibm.com |
2773c314f24ba66bf8fb5c966e7c581ca946e237 | 1b126b8ecb845b5b6c60b544b7613e2a13d4c596 | /program_wdm_source/Samples/Chap15/Fastinst/win98/setup.h | 6aa8470aa62d9a4d94961bb9bf57d2318f680d4f | [
"LicenseRef-scancode-oreilly-notice"
] | permissive | jeppeter/program_wdm_source | e44589a99b065f627174cd3c6dec815f860b8c0d | 53a3d11ad580a82874fec389074c709d567dbf52 | refs/heads/master | 2020-09-29T15:37:37.299494 | 2019-12-10T08:20:08 | 2019-12-10T08:20:08 | 227,065,077 | 3 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,568 | h | // Setup.h -- Declaration of setup helper classes
// Copyright (C) 1999 by Walter Oney
// All rights reserved
#ifndef SETUP_H
#define SETUP_H
typedef void* PVOID;
typedef const char* PCTSTR;
typedef char* PTSTR;
#ifndef arraysize
#define arraysize(p) (sizeof(p)/sizeof((p)[0]))
#endif
///////////////////////////////////////////////////////////////////////////////
struct InstallStruct {
CString devid; // target device id
CString mfgname; // name of manufacturer
CString devname; // name of device
CString instname; // install section name
BOOL done; // TRUE when time to stop enumeration
};
///////////////////////////////////////////////////////////////////////////////
class CInf;
typedef BOOL (*PENUMDEVCALLBACK)(CInf* inf, const CString& devname, const CString& instsecname, const CStringArray& devid, PVOID context, UINT& code);
typedef BOOL (*PENUMMFGCALLBACK)(CInf* inf, const CString& mfgname, const CString& modelname, PVOID context, UINT& code);
///////////////////////////////////////////////////////////////////////////////
class CInf
{ // class CInf
public:
CInf();
~CInf();
CString m_name; // name of file
CString m_classname; // name of device class
ATOM m_atom; // INF name atom
HINF m_hinf; // open handle
UINT EnumDevices(const CString& modelname, PENUMDEVCALLBACK callback, PVOID context);
UINT EnumManufacturers(PENUMMFGCALLBACK callback, PVOID context);
UINT Open(PCTSTR name, BOOL defsearch = TRUE);
}; // class CInf
#endif
| [
"jeppeter@gmail.com"
] | jeppeter@gmail.com |
59ab81fb4f87a29eac6f7d9e8216a6491ac75a20 | 5062ce8ea9a52fe9fb46812ce5142af8b48b5c04 | /SINYD_SC_SettingTool_MFC/RemoteServerPathSetDlg.cpp | 97a1f9a7f92fed77ac0eef8e90275cd7bc470b71 | [] | no_license | yangyefeng/SINYD_SC | 95c1991adb6f997458b66d4364d28b6bdf9b3551 | d7c997cef9902f1574b3f5ce091f356f271d7d50 | refs/heads/master | 2020-03-10T03:43:26.649240 | 2018-04-12T01:10:40 | 2018-04-12T01:10:40 | 129,172,767 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 3,662 | cpp | // RemoteServerPathSetDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "SINYD_SC_SettingTool_MFC.h"
#include "RemoteServerPathSetDlg.h"
#include "afxdialogex.h"
// CRemoteServerPathSetDlg 对话框
IMPLEMENT_DYNAMIC(CRemoteServerPathSetDlg, CDialogEx)
CRemoteServerPathSetDlg::CRemoteServerPathSetDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(IDD_DIALOG_RemoteSet, pParent)
{
}
CRemoteServerPathSetDlg::~CRemoteServerPathSetDlg()
{
}
void CRemoteServerPathSetDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CRemoteServerPathSetDlg, CDialogEx)
ON_BN_CLICKED(IDOK, &CRemoteServerPathSetDlg::OnBnClickedOk)
ON_BN_CLICKED(IDC_BUTTON_RemoteTest, &CRemoteServerPathSetDlg::OnBnClickedButtonRemotetest)
END_MESSAGE_MAP()
// CRemoteServerPathSetDlg 消息处理程序
void CRemoteServerPathSetDlg::OnBnClickedOk()
{
// TODO: 在此添加控件通知处理程序代码
CString path;
GetDlgItemText(IDC_EDIT_ServerPath, path);
path.TrimRight('/');
path += '/';
FILE* file = fopen(".\\cwRsync\\RemoteServerPath.txt", "w");
if (file)
{
fprintf(file, CT2A(path));
fclose(file);
file = NULL;
MessageBox(L"服务器路径设置成功");
}
else
{
MessageBox(L"服务器路径设置失败,请确认cwRsync文件夹是否存在");
return;
}
CDialogEx::OnOK();
}
BOOL CRemoteServerPathSetDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// TODO: 在此添加额外的初始化
FILE* file = fopen(".\\cwRsync\\RemoteServerPath.txt", "r");
if (file)
{
char cpath[MAX_PATH] = { 0 };
fgets(cpath, MAX_PATH, file);
CStringA path(cpath);
path.Trim('\n');
SetDlgItemTextA(this->GetSafeHwnd(), IDC_EDIT_ServerPath, path);
fclose(file);
file = NULL;
}
return TRUE; // return TRUE unless you set the focus to a control
// 异常: OCX 属性页应返回 FALSE
}
void CRemoteServerPathSetDlg::OnBnClickedButtonRemotetest()
{
// TODO: 在此添加控件通知处理程序代码
//全新创建log文件
SECURITY_ATTRIBUTES sa = { sizeof(SECURITY_ATTRIBUTES),NULL,TRUE };
HANDLE cmdOutput = CreateFile(L".\\cwRsync\\rsynctest.log",
GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
&sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (cmdOutput != INVALID_HANDLE_VALUE)
{
CloseHandle(cmdOutput);
}
//拼接测试命令
CString cmd;
GetDlgItemText(IDC_EDIT_ServerPath, cmd);
cmd.TrimRight('/');
cmd += '/';
cmd = L".\\cwRsync\\rsync.exe " + cmd;
cmd = cmd + L" --log-file .\\cwRsync\\rsynctest.log";
//执行脚本命令
PROCESS_INFORMATION pi;
STARTUPINFO si;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
if (!CreateProcess(NULL,
cmd.GetBuffer(),
NULL,
NULL,
TRUE,
CREATE_NO_WINDOW | CREATE_DEFAULT_ERROR_MODE,
NULL,
NULL,
&si, &pi))
{
MessageBox(L"启动Rsync程序失败!");
}
else
{
WaitForSingleObject(pi.hProcess, INFINITE);
DWORD exeCode = 0;
GetExitCodeProcess(pi.hProcess, &exeCode);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
if (exeCode == 0)
{
MessageBox(L"测试成功!");
}
else
{
CString err;
err.Format(L"测试失败,错误码 = %d\n", exeCode);
FILE* log = fopen(".\\cwRsync\\rsynctest.log", "r,ccs=UTF-8");
if (log)
{
while (!feof(log))
{
wchar_t buf[1024] = { 0 };
fgetws(buf, 1024, log);
err = err + buf;
}
fclose(log);
}
MessageBox(err);
}
}
}
| [
"yangyf@sinyd.com"
] | yangyf@sinyd.com |
49e1020be0bd43147f4099c7e840a10019526143 | 3b7fbefe1545dc62e79711ef05f89bb35c1908ca | /genetic_algo/genetic.h | eae1b4b26d3ee3501a50f855f80a2b6acdfdb782 | [
"MIT"
] | permissive | wangarcher/examine | 7eb299c4244138187f941c1641ca3fe3ea959593 | e04c923f0db397558ea765d7fbf1050fe4aec3dd | refs/heads/master | 2023-02-28T18:34:45.191042 | 2021-02-05T06:10:14 | 2021-02-05T06:10:14 | 296,781,692 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,175 | h | #ifndef _GENETIC_H_
#define _GENETIC_H_
using namespace std;
#define PI 3.14159265358979323846
//遗传算法参数,种群规模(0~100)、繁殖代数、函数变量个数、交叉概率、编译概率
# define GROUP_SCALE 50
# define MAX_GENS 500
# define N_VARS 2
# define P_MATING 0.8
# define P_MUTATION 0.15
struct Individual
{
double Xn[N_VARS]; //存放变量值
double Fitness; //适应值
double ReFitness; //适应值概率密度
double SumFitness; //累加分布,为轮盘转
};
struct X_Range
{
double Upper; //变量的上界取值
double Lower; //变量的下界取值
};
template<typename T>
T randT(T Lower, T Upper); //产生任意类型随机数函数
void crossover(int &seed);
void elitist(); //基因保留
void evaluate();
void initGroup(int &seed);
void selectBest();
void mutate(int &seed);
double r8_uniform_ab(double a, double b, int &seed);
int i4_uniform_ab(int a, int b, int &seed);
void report(int Xnration);
void selector(int &seed);
void showTime();
void Xover(int one, int two, int &seed);
#endif // !_GENETIC_H_
| [
"archer7wang@outlook.com"
] | archer7wang@outlook.com |
1988842a94cd3af41eecb4448c906f253cf0a219 | 0a2e29c07edc9c186600bf4d6d78a767dbb8782a | /ksjsczapi_demo_qimage/KSJVBImageZoom.cpp | 33a2f564d20cfaf196b04c3e2c853ccfec525413 | [] | no_license | catchbest/ksjscz_demo | 368eb8eff03f6515ffa3fa84cb62b40998fc5b97 | e814ebd7192fae7471696a27b5eff91d6fec07b0 | refs/heads/master | 2021-04-29T05:23:49.971725 | 2019-06-11T08:03:09 | 2019-06-11T08:03:09 | 77,984,184 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,761 | cpp |
#include <stddef.h>
#include "KSJVBImageZoom.h"
CKSJVBImageZoom::CKSJVBImageZoom() :
m_nImageWidth(0),
m_nImageHeight(0),
m_nClientWidth(0),
m_nClientHeight(0),
m_eZoomMode(ZM_FITIMG),
m_fZoomScale(1.0f),
m_fSrcX(0.0f),
m_fSrcY(0.0f),
m_fSrcWidth(0.0f),
m_fSrcHeight(0.0f),
m_fDesX(0.0f),
m_fDesY(0.0f),
m_fDesWidth(0.0f),
m_fDesHeight(0.0f),
m_fOffsetX(0.0f),
m_fOffsetY(0.0f),
m_fDesImageWidth(0.0f),
m_fDesImageHeight(0.0f)
{
}
CKSJVBImageZoom::~CKSJVBImageZoom()
{
}
void CKSJVBImageZoom::SetImageSize(int nWidth, int nHeight)
{
if (m_nImageWidth == nWidth && m_nImageHeight == nHeight) return;
if (m_nImageWidth <= 0 || m_nImageHeight <= 0)
{
m_fOffsetX = (m_nClientWidth - nWidth) / 2.0f;
m_fOffsetY = (m_nClientHeight - nHeight) / 2.0f;
}
m_nImageWidth = nWidth;
m_nImageHeight = nHeight;
if (m_nClientWidth > 0 && m_nClientHeight > 0 && m_nImageWidth > 0 && m_nImageHeight > 0)
{
if (m_eZoomMode == ZM_FITIMG)
{
if (m_nClientWidth > 0 && m_nClientHeight > 0 && m_nImageWidth > 0 && m_nImageHeight > 0)
{
float dx = (float)m_nClientWidth / m_nImageWidth;
float dy = (float)m_nClientHeight / m_nImageHeight;
UpdateScale((dx < dy) ? dx : dy, m_nClientWidth / 2, m_nClientHeight / 2);
}
}
else
{
UpdateParams();
}
}
else UpdateParams();
}
void CKSJVBImageZoom::SetClientSize(int nWidth, int nHeight)
{
if (m_nClientWidth <= 0 || m_nClientHeight <= 0)
{
m_fOffsetX = (nWidth - m_nImageWidth) / 2.0f;
m_fOffsetY = (nHeight - m_nImageHeight) / 2.0f;
}
m_nClientWidth = nWidth;
m_nClientHeight = nHeight;
if (m_nClientWidth > 0 && m_nClientHeight > 0 && m_nImageWidth > 0 && m_nImageHeight > 0)
{
if (m_eZoomMode == ZM_FITIMG)
{
if (m_nClientWidth > 0 && m_nClientHeight > 0 && m_nImageWidth > 0 && m_nImageHeight > 0)
{
float dx = (float)m_nClientWidth / m_nImageWidth;
float dy = (float)m_nClientHeight / m_nImageHeight;
UpdateScale((dx < dy) ? dx : dy, m_nClientWidth / 2, m_nClientHeight / 2);
}
}
else
{
UpdateParams();
}
}
else UpdateParams();
}
void CKSJVBImageZoom::SetZoomMode(KSJ_ZOOM_MODE mode)
{
if (m_eZoomMode != mode)
{
m_eZoomMode = mode;
if (m_nClientWidth > 0 && m_nClientHeight > 0 && m_nImageWidth > 0 && m_nImageHeight > 0)
{
if (m_eZoomMode == ZM_FITIMG)
{
if (m_nClientWidth > 0 && m_nClientHeight > 0 && m_nImageWidth > 0 && m_nImageHeight > 0)
{
float dx = (float)m_nClientWidth / m_nImageWidth;
float dy = (float)m_nClientHeight / m_nImageHeight;
UpdateScale((dx < dy) ? dx : dy, m_nClientWidth / 2, m_nClientHeight / 2);
}
}
}
}
}
void CKSJVBImageZoom::SetOffset(int nOffsetX, int nOffsetY)
{
m_fOffsetX = nOffsetX;
m_fOffsetY = nOffsetY;
ViewFieldRectify();
}
void CKSJVBImageZoom::GetOffset(int& nOffsetX, int& nOffsetY)
{
nOffsetX = m_fOffsetX;
nOffsetY = m_fOffsetY;
}
KSJ_ZOOM_MODE CKSJVBImageZoom::GetZoomMode()
{
return m_eZoomMode;
}
void CKSJVBImageZoom::ZoomOut(int nOperateX, int nOperateY)
{
m_eZoomMode = ZM_ZOOM;
if (m_fZoomScale>0.1f) UpdateScale(m_fZoomScale * 0.95f, nOperateX, nOperateY);
}
void CKSJVBImageZoom::ZoomIn(int nOperateX, int nOperateY)
{
m_eZoomMode = ZM_ZOOM;
if (m_fZoomScale < 20.0f) UpdateScale(m_fZoomScale / 0.95f, nOperateX, nOperateY);
}
void CKSJVBImageZoom::Move(int nDivX, int nDivY)
{
m_fOffsetX += nDivX;
m_fOffsetY += nDivY;
ViewFieldRectify();
}
void CKSJVBImageZoom::ViewFieldRectify()
{
if (m_fDesImageWidth <= m_nClientWidth)
{
m_fOffsetX = (m_nClientWidth - m_fDesImageWidth) / 2.0f;
m_fSrcX = 0.0f;
m_fSrcWidth = m_nImageWidth;
m_fDesX = m_fOffsetX;
m_fDesWidth = m_fDesImageWidth;
}
else
{
if (m_fOffsetX > 0) m_fOffsetX = 0;
else if ((m_fDesImageWidth + m_fOffsetX) < m_nClientWidth) m_fOffsetX = m_nClientWidth - m_fDesImageWidth;
m_fDesX = 0.0f;
m_fDesWidth = m_nClientWidth;
m_fSrcX = (m_fDesX - m_fOffsetX) / m_fZoomScale;
m_fSrcWidth = m_fDesWidth / m_fZoomScale;
}
if (m_fDesImageHeight <= m_nClientHeight)
{
m_fOffsetY = (m_nClientHeight - m_fDesImageHeight) / 2;
m_fSrcY = 0;
m_fSrcHeight = m_nImageHeight;
m_fDesY = m_fOffsetY;
m_fDesHeight = m_fDesImageHeight;
}
else
{
if (m_fOffsetY > 0) m_fOffsetY = 0;
else if ((m_fDesImageHeight + m_fOffsetY) < m_nClientHeight) m_fOffsetY = m_nClientHeight - m_fDesImageHeight;
m_fDesY = 0.0f;
m_fDesHeight = m_nClientHeight;
m_fSrcY = (m_fDesY - m_fOffsetY) / m_fZoomScale;
m_fSrcHeight = m_fDesHeight / m_fZoomScale;
}
}
void CKSJVBImageZoom::UpdateParams()
{
m_fDesImageWidth = m_fZoomScale * m_nImageWidth;
m_fDesImageHeight = m_fZoomScale * m_nImageHeight;
ViewFieldRectify();
}
void CKSJVBImageZoom::UpdateScale(float dNewScale, int nOperateX, int nOperateY)
{
m_fOffsetX = nOperateX + (m_fOffsetX - nOperateX) / m_fZoomScale * dNewScale;
m_fOffsetY = nOperateY + (m_fOffsetY - nOperateY) / m_fZoomScale * dNewScale;
m_fZoomScale = dNewScale;
m_fDesImageWidth = m_fZoomScale*m_nImageWidth;
m_fDesImageHeight = m_fZoomScale*m_nImageHeight;
ViewFieldRectify();
}
void CKSJVBImageZoom::GetImageShowPosition(int& x, int& y, int& w, int& h)
{
x = m_fOffsetX;
y = m_fOffsetY;
w = m_fDesImageWidth + m_fOffsetX - x;
h = m_fDesImageHeight + m_fOffsetY - y;
}
void CKSJVBImageZoom::GetValidShowPosition(int& nImageSrcX, int& nImageSrcY, int& nImageWidth, int& nImageHeight, int& nClientDesX, int& nClientDesY, int& nClientWidth, int& nClientHeight)
{
nImageSrcX = m_fSrcX;
nImageSrcY = m_fSrcY;
nImageWidth = m_fSrcWidth + m_fSrcX - nImageSrcX;
nImageHeight = m_fSrcHeight + m_fSrcY - nImageSrcY;
nClientDesX = m_fDesX;
nClientDesY = m_fDesY;
nClientWidth = m_fDesWidth + m_fDesX - nClientDesX;
nClientHeight = m_fDesHeight + m_fDesY - nClientDesY;
}
| [
"2881377368@qq.com"
] | 2881377368@qq.com |
e89e5c7208254022a1b26d7889fa11a27aaee9f4 | 05ca918c9f8c8c94a55cd2af5feda216d97dbd46 | /sumordifference.cpp | 8ba33e61ef455cdcd233aefa83313374d42e2120 | [] | no_license | Gowthamr221/DSA-Practice | 6d0c5abaf45f6c0ee6f07e7743a16016366f0572 | dcece318ab6893373800a7f1c2f5c631c4e0fc43 | refs/heads/main | 2023-03-19T20:03:03.133732 | 2021-03-12T15:37:20 | 2021-03-12T15:37:20 | 339,117,742 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 316 | cpp | #include<iostream>
#include<bits/stdc++.h>
#include<vector>
#include<cmath>
#include<cctype>
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int num1,num2;
cin >> num1 >> num2;
if(num1>num2){
cout << num1-num2 << endl;
}
else{
cout << (num1+num2) << endl;
}
return 0;
} | [
"33353028+Gowthamr221@users.noreply.github.com"
] | 33353028+Gowthamr221@users.noreply.github.com |
caa253c5781848dd58e08a8c972d0dca779e6c88 | 729c7bfa2e292d8c6a7ec79c045201cc7e5eabf4 | /tempat_sampah_pintar/tempat_sampah_pintar.ino | e0d2a92177464f3a3419a13555ee26cb7ddab3b2 | [] | no_license | barenMaulana/ARDUINO | a74249f175e0ec562ab032ab8f9189e93b3be81a | ee442339713a84e9779fe0bbca45762cfd01bf1b | refs/heads/master | 2023-01-31T13:04:42.481686 | 2020-12-17T06:59:00 | 2020-12-17T06:59:00 | 295,136,787 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,102 | ino | #include <DFPlayer_Mini_Mp3.h>
#include <SoftwareSerial.h>
#include <Servo.h>
#define PIN_BUSY A0
#define triggerPin D8
#define echoPin D7
Servo myservo;
int sudut= 140;
SoftwareSerial mp3Serial(D3, D4); // RX, TX
void setup () {
pinMode(PIN_BUSY, INPUT);
Serial.begin (9600);
Serial.println("Setting up software serial");
mp3Serial.begin (9600);
Serial.println("Setting up mp3 player");
mp3_set_serial (mp3Serial);
// Delay is required before accessing player. From my experience it's ~1 sec
delay(1000);
mp3_set_volume (50);
//ultrasonic
pinMode(triggerPin, OUTPUT);
pinMode(echoPin, INPUT);
//servo
myservo.attach(D5);
}
int lompatan = 0;
void loop () {
long duration, jarak;
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
duration = pulseIn(echoPin, HIGH);
jarak = (duration/2) / 29.1;
Serial.println("jarak :");
Serial.print(jarak);
Serial.println(" cm");
// if(lompatan == 4){
// for(int j = 0; j <= 3; j++){
// myservo.write(0);
// Serial.println("play next");
// mp3_next ();
// Serial.println(lompatan);
// Serial.print("Busy: ");
// Serial.println(analogRead(PIN_BUSY));
// delay (1000);
//
// myservo.write(sudut);
// Serial.println("Stop");
// mp3_stop ();
// Serial.print("Busy: ");
// Serial.println(analogRead(PIN_BUSY));
// }
// }
if(jarak <= 30){
lompatan++;
if(lompatan >= 4){
for(int i = 1; i <= 4; i++){
mp3_next ();
}
}
myservo.write(0);
Serial.println("play next");
mp3_next ();
Serial.println(lompatan);
Serial.print("Busy: ");
Serial.println(analogRead(PIN_BUSY));
if(lompatan == 4){
for(int i = 1; i <= 3; i++){
mp3_next ();
mp3_stop ();
}
}else{
delay (6000);
}
}
myservo.write(sudut);
Serial.println("Stop");
mp3_stop ();
Serial.print("Busy: ");
Serial.println(analogRead(PIN_BUSY));
}
| [
"barenmaulana@gmail.com"
] | barenmaulana@gmail.com |
e4553e366fc7eae47ce2a1f09ef428eeefbccb46 | fe6b2a94ebfcc55d7bcf2b5d929261e26df185dc | /Submission/Team11/Code11/SPA/Parser/SyntaxErrorException.h | 679989b54fae09935f4f5f5800b0cefdc839f2ec | [] | no_license | ChuaPingChan/SpaXI | 637ef01979cd06f3ab285b4ec632b7f27875a1f9 | 3c4256d340c5eab0742616cd2c8dec9068e78256 | refs/heads/master | 2021-08-24T17:44:46.329356 | 2017-11-21T08:55:54 | 2017-11-21T08:55:54 | 110,552,137 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 924 | h | #include <string>
#include <exception>
class SyntaxErrorException : public std::exception
{
public:
/** Constructor (C strings).
* @param message C-style string error message.
* The string contents are copied upon construction.
* Hence, responsibility for deleting the char* lies
* with the caller.
*/
explicit SyntaxErrorException(const char * message);
/** Constructor (C++ STL strings).
* @param message The error message.
*/
explicit SyntaxErrorException(const std::string& message);
/** Returns a pointer to the (constant) error description.
* @return A pointer to a const char*. The underlying memory
* is in possession of the Exception object. Callers must
* not attempt to free the memory.
*/
virtual const char* what() const throw();
protected:
std::string msg_;
};
| [
"chua_pingchan@u.nus.edu"
] | chua_pingchan@u.nus.edu |
3814d1e9ba98490284ba6d1524dc7d758996d0eb | 38c10c01007624cd2056884f25e0d6ab85442194 | /content/shell/browser/shell_aura.cc | edc83efe36d24aab7a38c95e9c74694ce79d0176 | [
"BSD-3-Clause"
] | permissive | zenoalbisser/chromium | 6ecf37b6c030c84f1b26282bc4ef95769c62a9b2 | e71f21b9b4b9b839f5093301974a45545dad2691 | refs/heads/master | 2022-12-25T14:23:18.568575 | 2016-07-14T21:49:52 | 2016-07-23T08:02:51 | 63,980,627 | 0 | 2 | BSD-3-Clause | 2022-12-12T12:43:41 | 2016-07-22T20:14:04 | null | UTF-8 | C++ | false | false | 1,835 | cc | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/shell/browser/shell.h"
#include "content/public/browser/web_contents.h"
#include "content/shell/browser/shell_platform_data_aura.h"
#include "ui/aura/env.h"
#include "ui/aura/test/test_screen.h"
#include "ui/aura/window.h"
#include "ui/aura/window_event_dispatcher.h"
namespace content {
// static
void Shell::PlatformInitialize(const gfx::Size& default_window_size) {
CHECK(!platform_);
aura::TestScreen* screen = aura::TestScreen::Create(gfx::Size());
gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, screen);
platform_ = new ShellPlatformDataAura(default_window_size);
}
void Shell::PlatformExit() {
CHECK(platform_);
delete platform_;
platform_ = NULL;
aura::Env::DeleteInstance();
}
void Shell::PlatformCleanUp() {
}
void Shell::PlatformEnableUIControl(UIControl control, bool is_enabled) {
}
void Shell::PlatformSetAddressBarURL(const GURL& url) {
}
void Shell::PlatformSetIsLoading(bool loading) {
}
void Shell::PlatformCreateWindow(int width, int height) {
CHECK(platform_);
if (!headless_)
platform_->ShowWindow();
platform_->ResizeWindow(gfx::Size(width, height));
}
void Shell::PlatformSetContents() {
CHECK(platform_);
aura::Window* content = web_contents_->GetNativeView();
aura::Window* parent = platform_->host()->window();
if (!parent->Contains(content))
parent->AddChild(content);
content->Show();
}
void Shell::PlatformResizeSubViews() {
}
void Shell::Close() {
delete this;
}
void Shell::PlatformSetTitle(const base::string16& title) {
}
bool Shell::PlatformHandleContextMenu(
const content::ContextMenuParams& params) {
return false;
}
} // namespace content
| [
"zeno.albisser@hemispherian.com"
] | zeno.albisser@hemispherian.com |
b2efa28c0ce2af124725bf3830c6b17d8f86d18a | d9db0c8e49e014bcf6abaf05e27a15b963ebcc6d | /Assignment 1/test8.cpp | ec3ef9295f947b58a8534ae308307520f4fd4168 | [] | no_license | reikdas/AlgoLab | 66cfd5fb2e9ffbeeeaaa22cdbb829f627ef14966 | e24dc688823eb6cc9591dbd70a591b6940245309 | refs/heads/master | 2020-04-08T01:56:52.428329 | 2018-11-23T23:56:49 | 2018-11-23T23:56:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 463 | cpp | #include <iostream>
#include <vector>
int find(std::vector<int> &arr, int low, int high)
{
int mid = (high + low)/2;
if(low <= high)
{
if(arr[mid] > arr[mid-1] && arr[mid] > arr[mid+1])
return mid;
else if(arr[mid] < arr[mid+1])
return find(arr, mid+1, high);
else
return find(arr, low, mid-1);
}
return mid;
}
int main()
{
int n; std::cin>>n;
std::vector<int> arr(n);
for(auto& i:arr)
std::cin>>i;
std::cout<<find(arr, 0, n-1)<<'\n';
}
| [
"rohanmarkgomes@gmail.com"
] | rohanmarkgomes@gmail.com |
5890efd589e40db06f175c4da31bca793276d3da | 4b31387726e8e2b67d2678239499b1b3baa7e9a3 | /Pochaev_Nikita_lr3/qt-material-widgets/radix-sort/radixSort.cpp | 8a9e3f8160a924db1c40fb555130615dc4c17ec8 | [] | no_license | Ksenox/AISD_8381 | ec93203e727d6a45da1251503e9efac1c228d9ce | de1c5c00cad0dbcde1aebf18f3862a35119af360 | refs/heads/master | 2022-12-13T21:46:47.996646 | 2019-12-25T21:55:57 | 2019-12-25T21:55:57 | 206,580,371 | 9 | 6 | null | 2022-12-11T12:55:56 | 2019-09-05T14:13:02 | C++ | UTF-8 | C++ | false | false | 5,117 | cpp | #include "basicheaders.h"
#include "radixSort.h"
#include "console.h"
#include "partitioncustom.h"
radixSort::radixSort(bool sortFlag, bool stepFlag, bool consoleMode)
{
this->stepFlag = stepFlag;
this->sortFlag = sortFlag;
this->consoleMode = consoleMode;
this->printResFlag = false;
lsb = 0;
operationsCounter = 0;
}
// Least significant digit radix sort
void radixSort::lsd_radix_sort()
{
operationsCounter++;
QFile log("../log.txt");
log.open(QIODevice::Append);
QTextStream logStream(&log);
if(lsb == ITERCOUNT) {sendDeactivateNextStepBut(); return;}
if (stepFlag == true)
{
logStream << "Step " << lsb << ": " << endl;
if(consoleMode == false) emit strToPrintInWindow("Step " + QString::number(lsb) + ": \n");
for (auto i : inpArr)
{
logStream << i << ' ';
if(consoleMode == false) emit strToPrintInWindow(QString::number(i) + " ");
}
logStream << endl;
if(consoleMode == false) emit strToPrintInWindow("\n");
}
stablePartitionCustom(inpArr.begin(), inpArr.end(), radix_test(lsb), operationsCounter);
++lsb;
log.close();
}
// Most significant digit radix sort (recursive)
void radixSort::msd_radix_sort(std::vector<int32_t>::iterator first, \
std::vector<int32_t>::iterator last, int msb = 31)
{
if (first != last && msb >= 0)
{
operationsCounter++;
std::vector<int32_t>::iterator mid = partitionCustom(first, last, \
radix_test(msb), operationsCounter);
msb--; // decrement most-significant-bit
msd_radix_sort(first, mid, msb); // sort left partition
msd_radix_sort(mid, last, msb); // sort right partition
}
}
// write input array to radix sort class object
void radixSort::writeData(std::vector<int32_t> inpArr)
{
this->inpArr.reserve(inpArr.size());
std::copy(inpArr.begin(), inpArr.end(), std::back_inserter(this->inpArr));
}
void radixSort::mainSortFunc()
{
if(DEBUG) qDebug() << "mainSortFunc implements" << endl;
QFile log("../log.txt");
log.open(QIODevice::Append);
QTextStream logStream(&log);
if (sortFlag == true)
{
if(stepFlag == true)
{
if (lsb == 1)
{
logStream << "LSD radix sort process:" << endl;
if(consoleMode == false) emit strToPrintInWindow("LSD radix sort process:\n");
}
} else
{
for(int i = 0; i < ITERCOUNT; ++i)
lsd_radix_sort();
}
lsd_radix_sort();
} else
{
msd_radix_sort(inpArr.begin(), inpArr.end());
}
if ((lsb == ITERCOUNT || sortFlag == false) && printResFlag == false)
{
resPrint();
printResFlag = true;
}
log.close();
QFile assessment("../assessment.txt");
assessment.open(QIODevice::Append);
QTextStream assessmentStream(&assessment);
QString temp;
temp = sortFlag ? " LSD " : " MSD ";
assessmentStream << "For sorting of " << inpArr.size() << " elements array ";
assessmentStream << "by " << temp << "sort ";
assessmentStream << "was made " << operationsCounter << " operations." << endl << endl;
assessment.close();
}
void radixSort::implementForFile(QString fileName)
{
QFile file(fileName);
std::vector<int32_t> inpArr;
// creating and naming log file
QFile log("../log.txt");
log.open(QFile::WriteOnly|QFile::Truncate);
QTextStream logStream(&log);
logStream << "************\n";
logStream << "* LOG FILE *\n";
logStream << "************\n";
log.close();
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream stream(&file);
foreach (QString i,QString(stream.readAll()).split(QRegExp("[\r\n]"),QString::SkipEmptyParts))
{
inpArr.push_back(static_cast<int32_t>(i.toInt()));
}
}
file.close();
writeData(inpArr);
mainSortFunc();
}
void radixSort::implementForLine(std::vector<int32_t> inpArr)
{
// creating and naming log file
QFile log("../log.txt");
log.open(QFile::WriteOnly|QFile::Truncate);
QTextStream logStream(&log);
logStream << "************\n";
logStream << "* LOG FILE *\n";
logStream << "************\n";
log.close();
writeData(inpArr);
mainSortFunc();
}
void radixSort::resPrint()
{
if(DEBUG) std::cout << "Result printing, lsb = " << lsb << std::endl;
QFile log("../log.txt");
log.open(QIODevice::Append);
QTextStream logStream(&log);
logStream << "Results of radix sort:" << endl;
if(consoleMode == false) emit strToPrintInWindow("Results of radix sort:\n");
else std::cout << "Results of radix sort:" << std:: endl;
for (auto i : inpArr)
{
logStream << i << endl;
if(consoleMode == false) emit strToPrintInWindow(QString::number(i) + "\n");
else std::cout << i << std:: endl;
}
}
void radixSort::callWorkSortFunc()
{
mainSortFunc();
}
radixSort::~radixSort()
{
}
| [
"pochaev.nik@gmail.com"
] | pochaev.nik@gmail.com |
27b667d46f6bf6f0a3c002325091f23cc9f5269d | acdc207d0fd8aa991d89218afba3534ead13bd21 | /central_widget.cpp | 4d6ade1a2f870e77ebb58cdad6f3548aed6fd006 | [] | no_license | ComicSansMS/voctrain | c9c13e852a79a7fe0044e451fd85f38e422fef24 | fdbbf709ea12ed21080093f0cfe604719567863f | refs/heads/master | 2020-07-07T08:35:44.858087 | 2019-08-20T05:36:15 | 2019-08-20T05:37:52 | 203,305,457 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,052 | cpp | #include <central_widget.hpp>
#include <QKeyEvent>
#include <algorithm>
#include <iterator>
Q_A vocabulary[] = {
{QString::fromUtf16(u"А а"), QString{"a"}},
{QString::fromUtf16(u"Б б"), QString{"b"}},
{QString::fromUtf16(u"В в"), QString{"v"}},
{QString::fromUtf16(u"Г г"), QString{"h"}},
{QString::fromUtf16(u"Ґ ґ"), QString{"g"}},
{QString::fromUtf16(u"Д д"), QString{"d"}},
{QString::fromUtf16(u"Е е"), QString{"e"}},
{QString::fromUtf16(u"Є є"), QString{"je"}},
{QString::fromUtf16(u"Ж ж"), QString{"sch"}},
{QString::fromUtf16(u"З з"), QString{"s"}},
{QString::fromUtf16(u"И и"), QString{"y"}},
{QString::fromUtf16(u"І і"), QString{"i"}},
{QString::fromUtf16(u"Ї ї"), QString{"ji"}},
{QString::fromUtf16(u"Й й"), QString{"j"}},
{QString::fromUtf16(u"К к"), QString{"k"}},
{QString::fromUtf16(u"Л л"), QString{"l"}},
{QString::fromUtf16(u"М м"), QString{"m"}},
{QString::fromUtf16(u"Н н"), QString{"n"}},
{QString::fromUtf16(u"О о"), QString{"o"}},
{QString::fromUtf16(u"П п"), QString{"p"}},
{QString::fromUtf16(u"Р р"), QString{"r"}},
{QString::fromUtf16(u"С с"), QString{"s"}},
{QString::fromUtf16(u"Т т"), QString{"t"}},
{QString::fromUtf16(u"У у"), QString{"u"}},
{QString::fromUtf16(u"Ф ф"), QString{"f"}},
{QString::fromUtf16(u"Х х"), QString{"ch"}},
{QString::fromUtf16(u"Ц ц"), QString{"z"}},
{QString::fromUtf16(u"Ч ч"), QString{"tsch"}},
{QString::fromUtf16(u"Ш ш"), QString{"sch"}},
{QString::fromUtf16(u"Щ щ"), QString{"stsch"}},
{QString::fromUtf16(u"ь"), QString{"-"}},
{QString::fromUtf16(u"Ю ю"), QString{"ju"}},
{QString::fromUtf16(u"Я я"), QString{"ja"}},
};
auto constexpr n_vocabulary = sizeof(vocabulary) / sizeof(vocabulary[0]);
CentralWidget::CentralWidget(QWidget* parent)
:QWidget(parent),m_question(new QLabel("", this)), m_answer(new QLineEdit(this)),
m_result(new QLabel("", this)), m_submit(new QPushButton("Start!", this)), m_rng(std::random_device()()),
m_state(State::Init), m_currentVoc(0), m_hitLimit(3)
{
m_layout.addWidget(m_question);
m_layout.addWidget(m_answer);
m_layout.addWidget(m_result);
m_layout.addWidget(m_submit);
setLayout(&m_layout);
connect(m_submit, &QPushButton::clicked, this, &CentralWidget::onSubmit);
connect(m_answer, &QLineEdit::returnPressed, this, &CentralWidget::onSubmit);
initVocabulary();
}
void CentralWidget::onSubmit()
{
switch (m_state) {
case State::Init:
/* fallthrough */
case State::Guess:
newGuess();
m_state = State::Reveal;
break;
case State::Reveal:
reveal();
m_state = isDone() ? State::Done : State::Guess;
break;
case State::Done:
m_submit->setText("Done!");
break;
}
}
void CentralWidget::newGuess()
{
std::uniform_int_distribution<std::size_t> dist(0, n_vocabulary - 1);
do {
m_currentVoc = dist(m_rng);
} while (m_hits[m_currentVoc] >= m_hitLimit);
m_question->setText(vocabulary[m_currentVoc].q);
m_answer->setText("");
m_answer->setEnabled(true);
m_result->setText("");
m_submit->setText("Submit");
m_answer->setFocus();
}
void CentralWidget::reveal()
{
m_answer->setEnabled(false);
if (m_answer->text().toLower() == vocabulary[m_currentVoc].a) {
m_result->setText("Correct!");
++m_hits[m_currentVoc];
} else {
m_result->setText(vocabulary[m_currentVoc].a);
++m_misses[m_currentVoc];
}
m_submit->setText("Next");
m_submit->setFocus();
}
bool CentralWidget::isDone()
{
return std::all_of(std::begin(m_hits), std::end(m_hits), [limit = m_hitLimit](int i) { return i >= limit; });
}
void CentralWidget::initVocabulary()
{
std::copy(std::begin(vocabulary), std::end(vocabulary), std::back_inserter(m_vocabulary));
m_hits.resize(m_vocabulary.size(), 0);
m_misses.resize(m_vocabulary.size(), 0);
}
| [
"der_ghulbus@ghulbus-inc.de"
] | der_ghulbus@ghulbus-inc.de |
5c37611c50fcd6862c64878668642bc25b7ba643 | e04f52ed50f42ad255c66d7b6f87ba642f41e125 | /appseed/rdpclient/client1/Windows/wf_rail.cpp | ce93b60afa33b2aaa27f5336405b946227ce2a35 | [] | no_license | ca2/app2018 | 6b5f3cfecaa56b0e8c8ec92ed26e8ce44f9b44c0 | 89e713c36cdfb31329e753ba9d7b9ff5b80fe867 | refs/heads/main | 2023-03-19T08:41:48.729250 | 2018-11-15T16:27:31 | 2018-11-15T16:27:31 | 98,031,531 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,568 | cpp | /**
* FreeRDP: A Remote Desktop Protocol Implementation
*
* Copyright 2013-2014 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* 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.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <freerdp/log.h>
#include <winpr/tchar.h>
#include <winpr/print.h>
#include "wf_rail.h"
#define TAG CLIENT_TAG("windows")
#define GET_X_LPARAM(lParam) ((UINT16) (lParam & 0xFFFF))
#define GET_Y_LPARAM(lParam) ((UINT16) ((lParam >> 16) & 0xFFFF))
/* RemoteApp Core Protocol Extension */
struct _WINDOW_STYLE
{
UINT32 style;
const char* name;
BOOL multi;
};
typedef struct _WINDOW_STYLE WINDOW_STYLE;
static const WINDOW_STYLE WINDOW_STYLES[] =
{
{ WS_BORDER, "WS_BORDER", FALSE },
{ WS_CAPTION, "WS_CAPTION", FALSE },
{ WS_CHILD, "WS_CHILD", FALSE },
{ WS_CLIPCHILDREN, "WS_CLIPCHILDREN", FALSE },
{ WS_CLIPSIBLINGS, "WS_CLIPSIBLINGS", FALSE },
{ WS_DISABLED, "WS_DISABLED", FALSE },
{ WS_DLGFRAME, "WS_DLGFRAME", FALSE },
{ WS_GROUP, "WS_GROUP", FALSE },
{ WS_HSCROLL, "WS_HSCROLL", FALSE },
{ WS_ICONIC, "WS_ICONIC", FALSE },
{ WS_MAXIMIZE, "WS_MAXIMIZE", FALSE },
{ WS_MAXIMIZEBOX, "WS_MAXIMIZEBOX", FALSE },
{ WS_MINIMIZE, "WS_MINIMIZE", FALSE },
{ WS_MINIMIZEBOX, "WS_MINIMIZEBOX", FALSE },
{ WS_OVERLAPPED, "WS_OVERLAPPED", FALSE },
{ WS_OVERLAPPEDWINDOW, "WS_OVERLAPPEDWINDOW", TRUE },
{ WS_POPUP, "WS_POPUP", FALSE },
{ WS_POPUPWINDOW, "WS_POPUPWINDOW", TRUE },
{ WS_SIZEBOX, "WS_SIZEBOX", FALSE },
{ WS_SYSMENU, "WS_SYSMENU", FALSE },
{ WS_TABSTOP, "WS_TABSTOP", FALSE },
{ WS_THICKFRAME, "WS_THICKFRAME", FALSE },
{ WS_VISIBLE, "WS_VISIBLE", FALSE }
};
static const WINDOW_STYLE EXTENDED_WINDOW_STYLES[] =
{
{ WS_EX_ACCEPTFILES, "WS_EX_ACCEPTFILES", FALSE },
{ WS_EX_APPWINDOW, "WS_EX_APPWINDOW", FALSE },
{ WS_EX_CLIENTEDGE, "WS_EX_CLIENTEDGE", FALSE },
{ WS_EX_COMPOSITED, "WS_EX_COMPOSITED", FALSE },
{ WS_EX_CONTEXTHELP, "WS_EX_CONTEXTHELP", FALSE },
{ WS_EX_CONTROLPARENT, "WS_EX_CONTROLPARENT", FALSE },
{ WS_EX_DLGMODALFRAME, "WS_EX_DLGMODALFRAME", FALSE },
{ WS_EX_LAYERED, "WS_EX_LAYERED", FALSE },
{ WS_EX_LAYOUTRTL, "WS_EX_LAYOUTRTL", FALSE },
{ WS_EX_LEFT, "WS_EX_LEFT", FALSE },
{ WS_EX_LEFTSCROLLBAR, "WS_EX_LEFTSCROLLBAR", FALSE },
{ WS_EX_LTRREADING, "WS_EX_LTRREADING", FALSE },
{ WS_EX_MDICHILD, "WS_EX_MDICHILD", FALSE },
{ WS_EX_NOACTIVATE, "WS_EX_NOACTIVATE", FALSE },
{ WS_EX_NOINHERITLAYOUT, "WS_EX_NOINHERITLAYOUT", FALSE },
{ WS_EX_NOPARENTNOTIFY, "WS_EX_NOPARENTNOTIFY", FALSE },
{ WS_EX_OVERLAPPEDWINDOW, "WS_EX_OVERLAPPEDWINDOW", TRUE },
{ WS_EX_PALETTEWINDOW, "WS_EX_PALETTEWINDOW", TRUE },
{ WS_EX_RIGHT, "WS_EX_RIGHT", FALSE },
{ WS_EX_RIGHTSCROLLBAR, "WS_EX_RIGHTSCROLLBAR", FALSE },
{ WS_EX_RTLREADING, "WS_EX_RTLREADING", FALSE },
{ WS_EX_STATICEDGE, "WS_EX_STATICEDGE", FALSE },
{ WS_EX_TOOLWINDOW, "WS_EX_TOOLWINDOW", FALSE },
{ WS_EX_TOPMOST, "WS_EX_TOPMOST", FALSE },
{ WS_EX_TRANSPARENT, "WS_EX_TRANSPARENT", FALSE },
{ WS_EX_WINDOWEDGE, "WS_EX_WINDOWEDGE", FALSE }
};
void PrintWindowStyles(UINT32 style)
{
int i;
WLog_INFO(TAG, "\tWindow Styles:\t{");
for (i = 0; i < ARRAYSIZE(WINDOW_STYLES); i++)
{
if (style & WINDOW_STYLES[i].style)
{
if (WINDOW_STYLES[i].multi)
{
if ((style & WINDOW_STYLES[i].style) != WINDOW_STYLES[i].style)
continue;
}
WLog_INFO(TAG, "\t\t%s", WINDOW_STYLES[i].name);
}
}
}
void PrintExtendedWindowStyles(UINT32 style)
{
int i;
WLog_INFO(TAG, "\tExtended Window Styles:\t{");
for (i = 0; i < ARRAYSIZE(EXTENDED_WINDOW_STYLES); i++)
{
if (style & EXTENDED_WINDOW_STYLES[i].style)
{
if (EXTENDED_WINDOW_STYLES[i].multi)
{
if ((style & EXTENDED_WINDOW_STYLES[i].style) != EXTENDED_WINDOW_STYLES[i].style)
continue;
}
WLog_INFO(TAG, "\t\t%s", EXTENDED_WINDOW_STYLES[i].name);
}
}
}
void PrintRailWindowState(WINDOW_ORDER_INFO* orderInfo, WINDOW_STATE_ORDER* windowState)
{
if (orderInfo->fieldFlags & WINDOW_ORDER_STATE_NEW)
WLog_INFO(TAG, "WindowCreate: WindowId: 0x%04X", orderInfo->windowId);
else
WLog_INFO(TAG, "WindowUpdate: WindowId: 0x%04X", orderInfo->windowId);
WLog_INFO(TAG, "{");
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OWNER)
{
WLog_INFO(TAG, "\tOwnerWindowId: 0x%04X", windowState->ownerWindowId);
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_STYLE)
{
WLog_INFO(TAG, "\tStyle: 0x%04X ExtendedStyle: 0x%04X",
windowState->style, windowState->extendedStyle);
PrintWindowStyles(windowState->style);
PrintExtendedWindowStyles(windowState->extendedStyle);
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_SHOW)
{
WLog_INFO(TAG, "\tShowState: %d", windowState->showState);
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TITLE)
{
char* title = NULL;
ConvertFromUnicode(CP_UTF8, 0, (WCHAR*) windowState->titleInfo.string,
windowState->titleInfo.length / 2, &title, 0, NULL, NULL);
WLog_INFO(TAG, "\tTitleInfo: %s (length = %d)", title,
windowState->titleInfo.length);
free(title);
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_OFFSET)
{
WLog_INFO(TAG, "\tClientOffsetX: %d ClientOffsetY: %d",
windowState->clientOffsetX, windowState->clientOffsetY);
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE)
{
WLog_INFO(TAG, "\tClientAreaWidth: %d ClientAreaHeight: %d",
windowState->clientAreaWidth, windowState->clientAreaHeight);
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RP_CONTENT)
{
WLog_INFO(TAG, "\tRPContent: %d", windowState->RPContent);
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ROOT_PARENT)
{
WLog_INFO(TAG, "\tRootParentHandle: 0x%04X", windowState->rootParentHandle);
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET)
{
WLog_INFO(TAG, "\tWindowOffsetX: %d WindowOffsetY: %d",
windowState->windowOffsetX, windowState->windowOffsetY);
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_CLIENT_DELTA)
{
WLog_INFO(TAG, "\tWindowClientDeltaX: %d WindowClientDeltaY: %d",
windowState->windowClientDeltaX, windowState->windowClientDeltaY);
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE)
{
WLog_INFO(TAG, "\tWindowWidth: %d WindowHeight: %d",
windowState->windowWidth, windowState->windowHeight);
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_RECTS)
{
UINT32 index;
RECTANGLE_16* rect;
WLog_INFO(TAG, "\tnumWindowRects: %d", windowState->numWindowRects);
for (index = 0; index < windowState->numWindowRects; index++)
{
rect = &windowState->windowRects[index];
WLog_INFO(TAG, "\twindowRect[%d]: left: %d top: %d right: %d bottom: %d",
index, rect->left, rect->top, rect->right, rect->bottom);
}
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET)
{
WLog_INFO(TAG, "\tvisibileOffsetX: %d visibleOffsetY: %d",
windowState->visibleOffsetX, windowState->visibleOffsetY);
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY)
{
UINT32 index;
RECTANGLE_16* rect;
WLog_INFO(TAG, "\tnumVisibilityRects: %d", windowState->numVisibilityRects);
for (index = 0; index < windowState->numVisibilityRects; index++)
{
rect = &windowState->visibilityRects[index];
WLog_INFO(TAG, "\tvisibilityRect[%d]: left: %d top: %d right: %d bottom: %d",
index, rect->left, rect->top, rect->right, rect->bottom);
}
}
WLog_INFO(TAG, "}");
}
static void PrintRailIconInfo(WINDOW_ORDER_INFO* orderInfo, ICON_INFO* iconInfo)
{
WLog_INFO(TAG, "ICON_INFO");
WLog_INFO(TAG, "{");
WLog_INFO(TAG, "\tbigIcon: %s", (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ICON_BIG) ? "true" : "false");
WLog_INFO(TAG, "\tcacheEntry; 0x%04X", iconInfo->cacheEntry);
WLog_INFO(TAG, "\tcacheId: 0x%04X", iconInfo->cacheId);
WLog_INFO(TAG, "\tbpp: %d", iconInfo->bpp);
WLog_INFO(TAG, "\twidth: %d", iconInfo->width);
WLog_INFO(TAG, "\theight: %d", iconInfo->height);
WLog_INFO(TAG, "\tcbColorTable: %d", iconInfo->cbColorTable);
WLog_INFO(TAG, "\tcbBitsMask: %d", iconInfo->cbBitsMask);
WLog_INFO(TAG, "\tcbBitsColor: %d", iconInfo->cbBitsColor);
WLog_INFO(TAG, "\tcolorTable: %p", iconInfo->colorTable);
WLog_INFO(TAG, "\tbitsMask: %p", iconInfo->bitsMask);
WLog_INFO(TAG, "\tbitsColor: %p", iconInfo->bitsColor);
WLog_INFO(TAG, "}");
}
//LRESULT CALLBACK wf_RailWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
//{
// HDC hDC;
// int x, y;
// int width;
// int height;
// UINT32 xPos;
// UINT32 yPos;
// PAINTSTRUCT ps;
// UINT32 inputFlags;
// wfContext* wfc = NULL;
// rdpInput* input = NULL;
// rdpContext* context = NULL;
// wfRailWindow* railWindow;
//
// railWindow = (wfRailWindow*) GetWindowLongPtr(hWnd, GWLP_USERDATA);
//
// if (railWindow)
// wfc = railWindow->wfc;
//
// if (wfc)
// context = (rdpContext*) wfc;
//
// if (context)
// input = context->input;
//
// switch (msg)
// {
// case WM_PAINT:
// {
// if (!wfc)
// return 0;
//
// hDC = BeginPaint(hWnd, &ps);
//
// x = ps.rcPaint.left;
// y = ps.rcPaint.top;
// width = ps.rcPaint.right - ps.rcPaint.left + 1;
// height = ps.rcPaint.bottom - ps.rcPaint.top + 1;
//
// BitBlt(hDC, x, y, width, height, wfc->primary->hdc,
// railWindow->x + x, railWindow->y + y, SRCCOPY);
//
// EndPaint(hWnd, &ps);
// }
// break;
//
// case WM_LBUTTONDOWN:
// {
// if (!railWindow || !input)
// return 0;
//
// xPos = GET_X_LPARAM(lParam) + railWindow->x;
// yPos = GET_Y_LPARAM(lParam) + railWindow->y;
// inputFlags = PTR_FLAGS_DOWN | PTR_FLAGS_BUTTON1;
//
// if (input)
// input->MouseEvent(input, inputFlags, xPos, yPos);
// }
// break;
//
// case WM_LBUTTONUP:
// {
// if (!railWindow || !input)
// return 0;
//
// xPos = GET_X_LPARAM(lParam) + railWindow->x;
// yPos = GET_Y_LPARAM(lParam) + railWindow->y;
// inputFlags = PTR_FLAGS_BUTTON1;
//
// if (input)
// input->MouseEvent(input, inputFlags, xPos, yPos);
// }
// break;
//
// case WM_RBUTTONDOWN:
// {
// if (!railWindow || !input)
// return 0;
//
// xPos = GET_X_LPARAM(lParam) + railWindow->x;
// yPos = GET_Y_LPARAM(lParam) + railWindow->y;
// inputFlags = PTR_FLAGS_DOWN | PTR_FLAGS_BUTTON2;
//
// if (input)
// input->MouseEvent(input, inputFlags, xPos, yPos);
// }
// break;
//
// case WM_RBUTTONUP:
// {
// if (!railWindow || !input)
// return 0;
//
// xPos = GET_X_LPARAM(lParam) + railWindow->x;
// yPos = GET_Y_LPARAM(lParam) + railWindow->y;
// inputFlags = PTR_FLAGS_BUTTON2;
//
// if (input)
// input->MouseEvent(input, inputFlags, xPos, yPos);
// }
// break;
//
// case WM_MOUSEMOVE:
// {
// if (!railWindow || !input)
// return 0;
//
// xPos = GET_X_LPARAM(lParam) + railWindow->x;
// yPos = GET_Y_LPARAM(lParam) + railWindow->y;
// inputFlags = PTR_FLAGS_MOVE;
//
// if (input)
// input->MouseEvent(input, inputFlags, xPos, yPos);
// }
// break;
//
// case WM_MOUSEWHEEL:
// break;
//
// case WM_CLOSE:
// DestroyWindow(hWnd);
// break;
//
// case WM_DESTROY:
// PostQuitMessage(0);
// break;
//
// default:
// return DefWindowProc(hWnd, msg, wParam, lParam);
// }
//
// return 0;
//}
//
//#define RAIL_DISABLED_WINDOW_STYLES (WS_BORDER | WS_THICKFRAME | WS_DLGFRAME | WS_CAPTION | \
// WS_OVERLAPPED | WS_VSCROLL | WS_HSCROLL | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX)
//#define RAIL_DISABLED_EXTENDED_WINDOW_STYLES (WS_EX_DLGMODALFRAME | WS_EX_CLIENTEDGE | WS_EX_STATICEDGE | WS_EX_WINDOWEDGE)
//
//static BOOL wf_rail_window_common(rdpContext* context, WINDOW_ORDER_INFO* orderInfo, WINDOW_STATE_ORDER* windowState)
//{
// wfRailWindow* railWindow = NULL;
// wfContext* wfc = (wfContext*) context;
// RailClientContext* rail = wfc->rail;
// UINT32 fieldFlags = orderInfo->fieldFlags;
//
// PrintRailWindowState(orderInfo, windowState);
//
// if (fieldFlags & WINDOW_ORDER_STATE_NEW)
// {
// HANDLE hInstance;
// WCHAR* titleW = NULL;
// WNDCLASSEX wndClassEx;
//
// railWindow = (wfRailWindow*) calloc(1, sizeof(wfRailWindow));
//
// if (!railWindow)
// return FALSE;
//
// railWindow->wfc = wfc;
//
// railWindow->dwStyle = windowState->style;
// railWindow->dwStyle &= ~RAIL_DISABLED_WINDOW_STYLES;
// railWindow->dwExStyle = windowState->extendedStyle;
// railWindow->dwExStyle &= ~RAIL_DISABLED_EXTENDED_WINDOW_STYLES;
//
// railWindow->x = windowState->windowOffsetX;
// railWindow->y = windowState->windowOffsetY;
// railWindow->width = windowState->windowWidth;
// railWindow->height = windowState->windowHeight;
//
// if (fieldFlags & WINDOW_ORDER_FIELD_TITLE)
// {
// char* title = NULL;
//
// ConvertFromUnicode(CP_UTF8, 0, (WCHAR*) windowState->titleInfo.string,
// windowState->titleInfo.length / 2, &title, 0, NULL, NULL);
//
// railWindow->title = title;
// }
// else
// {
// railWindow->title = _strdup("RdpRailWindow");
// }
//
// ConvertToUnicode(CP_UTF8, 0, railWindow->title, -1, &titleW, 0);
//
// hInstance = GetModuleHandle(NULL);
//
// ZeroMemory(&wndClassEx, sizeof(WNDCLASSEX));
// wndClassEx.cbSize = sizeof(WNDCLASSEX);
// wndClassEx.style = 0;
// wndClassEx.lpfnWndProc = wf_RailWndProc;
// wndClassEx.cbClsExtra = 0;
// wndClassEx.cbWndExtra = 0;
// wndClassEx.hIcon = NULL;
// wndClassEx.hCursor = NULL;
// wndClassEx.hbrBackground = NULL;
// wndClassEx.lpszMenuName = NULL;
// wndClassEx.lpszClassName = _T("RdpRailWindow");
// wndClassEx.hInstance = hInstance;
// wndClassEx.hIconSm = NULL;
//
// RegisterClassEx(&wndClassEx);
//
// railWindow->hWnd = CreateWindowExW(
// railWindow->dwExStyle, /* dwExStyle */
// _T("RdpRailWindow"), /* lpClassName */
// titleW, /* lpWindowName */
// railWindow->dwStyle, /* dwStyle */
// railWindow->x, /* x */
// railWindow->y, /* y */
// railWindow->width, /* nWidth */
// railWindow->height, /* nHeight */
// NULL, /* hWndParent */
// NULL, /* hMenu */
// hInstance, /* hInstance */
// NULL /* lpParam */
// );
//
// SetWindowLongPtr(railWindow->hWnd, GWLP_USERDATA, (LONG_PTR) railWindow);
//
// HashTable_Add(wfc->railWindows, (void*) (UINT_PTR) orderInfo->windowId, (void*) railWindow);
//
// free(titleW);
//
// UpdateWindow(railWindow->hWnd);
//
// return TRUE;
// }
// else
// {
// railWindow = (wfRailWindow*) HashTable_GetItemValue(wfc->railWindows,
// (void*) (UINT_PTR) orderInfo->windowId);
// }
//
// if (!railWindow)
// return TRUE;
//
// if ((fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET) ||
// (fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE))
// {
// if (fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET)
// {
// railWindow->x = windowState->windowOffsetX;
// railWindow->y = windowState->windowOffsetY;
// }
//
// if (fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE)
// {
// railWindow->width = windowState->windowWidth;
// railWindow->height = windowState->windowHeight;
// }
//
// SetWindowPos(railWindow->hWnd, NULL,
// railWindow->x,
// railWindow->y,
// railWindow->width,
// railWindow->height,
// 0);
// }
//
// if (fieldFlags & WINDOW_ORDER_FIELD_OWNER)
// {
//
// }
//
// if (fieldFlags & WINDOW_ORDER_FIELD_STYLE)
// {
// railWindow->dwStyle = windowState->style;
// railWindow->dwStyle &= ~RAIL_DISABLED_WINDOW_STYLES;
// railWindow->dwExStyle = windowState->extendedStyle;
// railWindow->dwExStyle &= ~RAIL_DISABLED_EXTENDED_WINDOW_STYLES;
//
// SetWindowLongPtr(railWindow->hWnd, GWL_STYLE, (LONG) railWindow->dwStyle);
// SetWindowLongPtr(railWindow->hWnd, GWL_EXSTYLE, (LONG) railWindow->dwExStyle);
// }
//
// if (fieldFlags & WINDOW_ORDER_FIELD_SHOW)
// {
// ShowWindow(railWindow->hWnd, windowState->showState);
// }
//
// if (fieldFlags & WINDOW_ORDER_FIELD_TITLE)
// {
// char* title = NULL;
// WCHAR* titleW = NULL;
//
// ConvertFromUnicode(CP_UTF8, 0, (WCHAR*) windowState->titleInfo.string,
// windowState->titleInfo.length / 2, &title, 0, NULL, NULL);
//
// free(railWindow->title);
// railWindow->title = title;
//
// ConvertToUnicode(CP_UTF8, 0, railWindow->title, -1, &titleW, 0);
//
// SetWindowTextW(railWindow->hWnd, titleW);
//
// free(titleW);
// }
//
// if (fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_OFFSET)
// {
//
// }
//
// if (fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE)
// {
//
// }
//
// if (fieldFlags & WINDOW_ORDER_FIELD_WND_CLIENT_DELTA)
// {
//
// }
//
// if (fieldFlags & WINDOW_ORDER_FIELD_RP_CONTENT)
// {
//
// }
//
// if (fieldFlags & WINDOW_ORDER_FIELD_ROOT_PARENT)
// {
//
// }
//
// if (fieldFlags & WINDOW_ORDER_FIELD_WND_RECTS)
// {
// UINT32 index;
// HRGN hWndRect;
// HRGN hWndRects;
// RECTANGLE_16* rect;
//
// if (windowState->numWindowRects > 0)
// {
// rect = &(windowState->windowRects[0]);
// hWndRects = CreateRectRgn(rect->left, rect->top, rect->right, rect->bottom);
//
// for (index = 1; index < windowState->numWindowRects; index++)
// {
// rect = &(windowState->windowRects[index]);
// hWndRect = CreateRectRgn(rect->left, rect->top, rect->right, rect->bottom);
// CombineRgn(hWndRects, hWndRects, hWndRect, RGN_OR);
// DeleteObject(hWndRect);
// }
//
// SetWindowRgn(railWindow->hWnd, hWndRects, TRUE);
// DeleteObject(hWndRects);
// }
// }
//
// if (fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET)
// {
//
// }
//
// if (fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY)
// {
//
// }
//
// UpdateWindow(railWindow->hWnd);
// return TRUE;
//}
static BOOL wf_rail_window_delete(rdpContext* context, WINDOW_ORDER_INFO* orderInfo)
{
wfRailWindow* railWindow = NULL;
wfContext* wfc = (wfContext*) context;
RailClientContext* rail = wfc->rail;
WLog_DBG(TAG, "RailWindowDelete");
railWindow = (wfRailWindow*) HashTable_GetItemValue(wfc->railWindows,
(void*) (UINT_PTR) orderInfo->windowId);
if (!railWindow)
return TRUE;
HashTable_Remove(wfc->railWindows, (void*) (UINT_PTR) orderInfo->windowId);
DestroyWindow(railWindow->hWnd);
free(railWindow);
return TRUE;
}
static BOOL wf_rail_window_icon(rdpContext* context, WINDOW_ORDER_INFO* orderInfo, WINDOW_ICON_ORDER* windowIcon)
{
HDC hDC;
int bpp;
int width;
int height;
HICON hIcon;
BOOL bigIcon;
ICONINFO iconInfo;
BITMAPINFO bitmapInfo;
wfRailWindow* railWindow;
BITMAPINFOHEADER* bitmapInfoHeader;
wfContext* wfc = (wfContext*) context;
RailClientContext* rail = wfc->rail;
WLog_DBG(TAG, "RailWindowIcon");
PrintRailIconInfo(orderInfo, windowIcon->iconInfo);
railWindow = (wfRailWindow*) HashTable_GetItemValue(wfc->railWindows,
(void*) (UINT_PTR) orderInfo->windowId);
if (!railWindow)
return TRUE;
bigIcon = (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ICON_BIG) ? TRUE : FALSE;
hDC = GetDC(railWindow->hWnd);
iconInfo.fIcon = TRUE;
iconInfo.xHotspot = 0;
iconInfo.yHotspot = 0;
ZeroMemory(&bitmapInfo, sizeof(BITMAPINFO));
bitmapInfoHeader = &(bitmapInfo.bmiHeader);
bpp = windowIcon->iconInfo->bpp;
width = windowIcon->iconInfo->width;
height = windowIcon->iconInfo->height;
bitmapInfoHeader->biSize = sizeof(BITMAPINFOHEADER);
bitmapInfoHeader->biWidth = width;
bitmapInfoHeader->biHeight = height;
bitmapInfoHeader->biPlanes = 1;
bitmapInfoHeader->biBitCount = bpp;
bitmapInfoHeader->biCompression = 0;
bitmapInfoHeader->biSizeImage = height * width * ((bpp + 7) / 8);
bitmapInfoHeader->biXPelsPerMeter = width;
bitmapInfoHeader->biYPelsPerMeter = height;
bitmapInfoHeader->biClrUsed = 0;
bitmapInfoHeader->biClrImportant = 0;
iconInfo.hbmMask = CreateDIBitmap(hDC,
bitmapInfoHeader, CBM_INIT,
windowIcon->iconInfo->bitsMask,
&bitmapInfo, DIB_RGB_COLORS);
iconInfo.hbmColor = CreateDIBitmap(hDC,
bitmapInfoHeader, CBM_INIT,
windowIcon->iconInfo->bitsColor,
&bitmapInfo, DIB_RGB_COLORS);
hIcon = CreateIconIndirect(&iconInfo);
if (hIcon)
{
WPARAM wParam;
LPARAM lParam;
wParam = (WPARAM) bigIcon ? ICON_BIG : ICON_SMALL;
lParam = (LPARAM) hIcon;
SendMessage(railWindow->hWnd, WM_SETICON, wParam, lParam);
}
ReleaseDC(NULL, hDC);
if (windowIcon->iconInfo->cacheEntry != 0xFFFF)
{
/* icon should be cached */
}
return TRUE;
}
static BOOL wf_rail_window_cached_icon(rdpContext* context, WINDOW_ORDER_INFO* orderInfo, WINDOW_CACHED_ICON_ORDER* windowCachedIcon)
{
WLog_DBG(TAG, "RailWindowCachedIcon");
return TRUE;
}
static void wf_rail_notify_icon_common(rdpContext* context, WINDOW_ORDER_INFO* orderInfo, NOTIFY_ICON_STATE_ORDER* notifyIconState)
{
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_VERSION)
{
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_TIP)
{
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_INFO_TIP)
{
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_STATE)
{
}
if (orderInfo->fieldFlags & WINDOW_ORDER_ICON)
{
ICON_INFO* iconInfo = &(notifyIconState->icon);
PrintRailIconInfo(orderInfo, iconInfo);
}
if (orderInfo->fieldFlags & WINDOW_ORDER_CACHED_ICON)
{
}
}
static BOOL wf_rail_notify_icon_create(rdpContext* context, WINDOW_ORDER_INFO* orderInfo, NOTIFY_ICON_STATE_ORDER* notifyIconState)
{
wfContext* wfc = (wfContext*) context;
RailClientContext* rail = wfc->rail;
WLog_DBG(TAG, "RailNotifyIconCreate");
wf_rail_notify_icon_common(context, orderInfo, notifyIconState);
return TRUE;
}
static BOOL wf_rail_notify_icon_update(rdpContext* context, WINDOW_ORDER_INFO* orderInfo, NOTIFY_ICON_STATE_ORDER* notifyIconState)
{
wfContext* wfc = (wfContext*) context;
RailClientContext* rail = wfc->rail;
WLog_DBG(TAG, "RailNotifyIconUpdate");
wf_rail_notify_icon_common(context, orderInfo, notifyIconState);
return TRUE;
}
static BOOL wf_rail_notify_icon_delete(rdpContext* context, WINDOW_ORDER_INFO* orderInfo)
{
wfContext* wfc = (wfContext*) context;
RailClientContext* rail = wfc->rail;
WLog_DBG(TAG, "RailNotifyIconDelete");
return TRUE;
}
static BOOL wf_rail_monitored_desktop(rdpContext* context, WINDOW_ORDER_INFO* orderInfo, MONITORED_DESKTOP_ORDER* monitoredDesktop)
{
wfContext* wfc = (wfContext*) context;
RailClientContext* rail = wfc->rail;
WLog_DBG(TAG, "RailMonitorDesktop");
return TRUE;
}
static BOOL wf_rail_non_monitored_desktop(rdpContext* context, WINDOW_ORDER_INFO* orderInfo)
{
wfContext* wfc = (wfContext*) context;
RailClientContext* rail = wfc->rail;
WLog_DBG(TAG, "RailNonMonitorDesktop");
return TRUE;
}
//void wf_rail_register_update_callbacks(rdpUpdate* update)
//{
// rdpWindowUpdate* window = update->window;
//
// window->WindowCreate = wf_rail_window_common;
// window->WindowUpdate = wf_rail_window_common;
// window->WindowDelete = wf_rail_window_delete;
// window->WindowIcon = wf_rail_window_icon;
// window->WindowCachedIcon = wf_rail_window_cached_icon;
// window->NotifyIconCreate = wf_rail_notify_icon_create;
// window->NotifyIconUpdate = wf_rail_notify_icon_update;
// window->NotifyIconDelete = wf_rail_notify_icon_delete;
// window->MonitoredDesktop = wf_rail_monitored_desktop;
// window->NonMonitoredDesktop = wf_rail_non_monitored_desktop;
//}
/* RemoteApp Virtual Channel Extension */
static int wf_rail_server_execute_result(RailClientContext* context, RAIL_EXEC_RESULT_ORDER* execResult)
{
WLog_DBG(TAG, "RailServerExecuteResult: 0x%04X", execResult->rawResult);
return 1;
}
static int wf_rail_server_system_param(RailClientContext* context, RAIL_SYSPARAM_ORDER* sysparam)
{
return 1;
}
static int wf_rail_server_handshake(RailClientContext* context, RAIL_HANDSHAKE_ORDER* handshake)
{
RAIL_EXEC_ORDER exec;
RAIL_SYSPARAM_ORDER sysparam;
RAIL_HANDSHAKE_ORDER clientHandshake;
RAIL_CLIENT_STATUS_ORDER clientStatus;
wfContext* wfc = (wfContext*) context->custom;
rdpSettings* settings = wfc->settings;
clientHandshake.buildNumber = 0x00001DB0;
context->ClientHandshake(context, &clientHandshake);
ZeroMemory(&clientStatus, sizeof(RAIL_CLIENT_STATUS_ORDER));
clientStatus.flags = RAIL_CLIENTSTATUS_ALLOWLOCALMOVESIZE;
context->ClientInformation(context, &clientStatus);
if (settings->RemoteAppLanguageBarSupported)
{
RAIL_LANGBAR_INFO_ORDER langBarInfo;
langBarInfo.languageBarStatus = 0x00000008; /* TF_SFT_HIDDEN */
context->ClientLanguageBarInfo(context, &langBarInfo);
}
ZeroMemory(&sysparam, sizeof(RAIL_SYSPARAM_ORDER));
sysparam.params = 0;
sysparam.params |= SPI_MASK_SET_HIGH_CONTRAST;
sysparam.highContrast.colorScheme.string = NULL;
sysparam.highContrast.colorScheme.length = 0;
sysparam.highContrast.flags = 0x7E;
sysparam.params |= SPI_MASK_SET_MOUSE_BUTTON_SWAP;
sysparam.mouseButtonSwap = FALSE;
sysparam.params |= SPI_MASK_SET_KEYBOARD_PREF;
sysparam.keyboardPref = FALSE;
sysparam.params |= SPI_MASK_SET_DRAG_FULL_WINDOWS;
sysparam.dragFullWindows = FALSE;
sysparam.params |= SPI_MASK_SET_KEYBOARD_CUES;
sysparam.keyboardCues = FALSE;
sysparam.params |= SPI_MASK_SET_WORK_AREA;
sysparam.workArea.left = 0;
sysparam.workArea.top = 0;
sysparam.workArea.right = settings->DesktopWidth;
sysparam.workArea.bottom = settings->DesktopHeight;
sysparam.dragFullWindows = FALSE;
context->ClientSystemParam(context, &sysparam);
ZeroMemory(&exec, sizeof(RAIL_EXEC_ORDER));
exec.RemoteApplicationProgram = settings->RemoteApplicationProgram;
exec.RemoteApplicationWorkingDir = settings->ShellWorkingDirectory;
exec.RemoteApplicationArguments = settings->RemoteApplicationCmdLine;
context->ClientExecute(context, &exec);
return 1;
}
static int wf_rail_server_handshake_ex(RailClientContext* context, RAIL_HANDSHAKE_EX_ORDER* handshakeEx)
{
return 1;
}
static int wf_rail_server_local_move_size(RailClientContext* context, RAIL_LOCALMOVESIZE_ORDER* localMoveSize)
{
return 1;
}
static int wf_rail_server_min_max_info(RailClientContext* context, RAIL_MINMAXINFO_ORDER* minMaxInfo)
{
return 1;
}
static int wf_rail_server_language_bar_info(RailClientContext* context, RAIL_LANGBAR_INFO_ORDER* langBarInfo)
{
return 1;
}
static int wf_rail_server_get_appid_response(RailClientContext* context, RAIL_GET_APPID_RESP_ORDER* getAppIdResp)
{
return 1;
}
void wf_rail_invalidate_region(wfContext* wfc, REGION16* invalidRegion)
{
int index;
int count;
RECT updateRect;
RECTANGLE_16 windowRect;
ULONG_PTR* pKeys = NULL;
wfRailWindow* railWindow;
const RECTANGLE_16* extents;
REGION16 windowInvalidRegion;
region16_init(&windowInvalidRegion);
count = HashTable_GetKeys(wfc->railWindows, &pKeys);
for (index = 0; index < count; index++)
{
railWindow = (wfRailWindow*) HashTable_GetItemValue(wfc->railWindows, (void*) pKeys[index]);
if (railWindow)
{
windowRect.left = railWindow->x;
windowRect.top = railWindow->y;
windowRect.right = railWindow->x + railWindow->width;
windowRect.bottom = railWindow->y + railWindow->height;
region16_clear(&windowInvalidRegion);
region16_intersect_rect(&windowInvalidRegion, invalidRegion, &windowRect);
if (!region16_is_empty(&windowInvalidRegion))
{
extents = region16_extents(&windowInvalidRegion);
updateRect.left = extents->left - railWindow->x;
updateRect.top = extents->top - railWindow->y;
updateRect.right = extents->right - railWindow->x;
updateRect.bottom = extents->bottom - railWindow->y;
InvalidateRect(railWindow->hWnd, &updateRect, FALSE);
}
}
}
region16_uninit(&windowInvalidRegion);
}
//BOOL wf_rail_init(wfContext* wfc, RailClientContext* rail)
//{
// rdpContext* context = (rdpContext*) wfc;
//
// wfc->rail = rail;
// rail->custom = (void*) wfc;
//
// rail->ServerExecuteResult = wf_rail_server_execute_result;
// rail->ServerSystemParam = wf_rail_server_system_param;
// rail->ServerHandshake = wf_rail_server_handshake;
// rail->ServerHandshakeEx = wf_rail_server_handshake_ex;
// rail->ServerLocalMoveSize = wf_rail_server_local_move_size;
// rail->ServerMinMaxInfo = wf_rail_server_min_max_info;
// rail->ServerLanguageBarInfo = wf_rail_server_language_bar_info;
// rail->ServerGetAppIdResponse = wf_rail_server_get_appid_response;
//
// wf_rail_register_update_callbacks(context->update);
//
// wfc->railWindows = HashTable_New(TRUE);
// return (wfc->railWindows != NULL);
//}
void wf_rail_uninit(wfContext* wfc, RailClientContext* rail)
{
wfc->rail = NULL;
rail->custom = NULL;
HashTable_Free(wfc->railWindows);
}
| [
"camilo@ca2.email"
] | camilo@ca2.email |
2fe8c585b6d3746e9be7fa21c73b2c4e877ec1d0 | d7ae48a461cf7394c3e2d98d94e329d1f2228f1b | /src/main_menu.h | 981cdb6209908b5d126718369a6abcc90676a457 | [] | no_license | opk1/cAudio | 25aa4c2135f4b5602730f775a5201484ddc0e40c | 384c2bc235d366432b1f460b69d7bfcde251df59 | refs/heads/master | 2021-01-19T03:23:38.059017 | 2014-05-12T00:33:32 | 2014-05-12T00:33:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,174 | h | #pragma once
#ifndef _MAINMENU_
#define _MAINMENU_
#include "client_menu.h"
#include "server_menu.h"
#include "main.h"
namespace TCPIP {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::IO;
/// <summary>
/// Summary for main_menu
/// </summary>
public ref class main_menu : public System::Windows::Forms::Form
{
public:
String^ errMsg;
main_menu(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
/// <summary>
/// Clean up any resources being used.
/// </summary>
~main_menu()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ clientButton;
private: System::Windows::Forms::Button^ serverButton;
protected:
protected:
protected:
private:
/// <summary>
/// Required designer variable.
/// </summary>
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent(void)
{
this->clientButton = (gcnew System::Windows::Forms::Button());
this->serverButton = (gcnew System::Windows::Forms::Button());
this->SuspendLayout();
//
// clientButton
//
this->clientButton->Location = System::Drawing::Point(44, 41);
this->clientButton->Name = L"clientButton";
this->clientButton->Size = System::Drawing::Size(142, 67);
this->clientButton->TabIndex = 0;
this->clientButton->Text = L"Client";
this->clientButton->UseVisualStyleBackColor = true;
this->clientButton->Click += gcnew System::EventHandler(this, &main_menu::clientButton_Click);
//
// serverButton
//
this->serverButton->Location = System::Drawing::Point(44, 123);
this->serverButton->Name = L"serverButton";
this->serverButton->Size = System::Drawing::Size(142, 67);
this->serverButton->TabIndex = 1;
this->serverButton->Text = L"Server";
this->serverButton->UseVisualStyleBackColor = true;
this->serverButton->Click += gcnew System::EventHandler(this, &main_menu::serverButton_Click);
//
// main_menu
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(231, 234);
this->Controls->Add(this->serverButton);
this->Controls->Add(this->clientButton);
this->Name = L"main_menu";
this->Text = L"main_menu";
this->ResumeLayout(false);
}
#pragma endregion
private: System::Void clientButton_Click(System::Object^ sender, System::EventArgs^ e)
{
client_menu ^client = gcnew client_menu();
client->Show();
this->Hide();
}
private: System::Void serverButton_Click(System::Object^ sender, System::EventArgs^ e)
{
server_menu ^server = gcnew server_menu();
server->Show();
this->Hide();
}
};
}
#endif | [
"dsathanielle@gmail.com"
] | dsathanielle@gmail.com |
7beba34c2a772f22d24e3db3e5301a06909e0226 | ba9322f7db02d797f6984298d892f74768193dcf | /alidns/include/alibabacloud/alidns/model/GetMainDomainNameRequest.h | cb41d85b815818f451feaa7edcfde0d5c7220959 | [
"Apache-2.0"
] | permissive | sdk-team/aliyun-openapi-cpp-sdk | e27f91996b3bad9226c86f74475b5a1a91806861 | a27fc0000a2b061cd10df09cbe4fff9db4a7c707 | refs/heads/master | 2022-08-21T18:25:53.080066 | 2022-07-25T10:01:05 | 2022-07-25T10:01:05 | 183,356,893 | 3 | 0 | null | 2019-04-25T04:34:29 | 2019-04-25T04:34:28 | null | UTF-8 | C++ | false | false | 1,718 | h | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ALIBABACLOUD_ALIDNS_MODEL_GETMAINDOMAINNAMEREQUEST_H_
#define ALIBABACLOUD_ALIDNS_MODEL_GETMAINDOMAINNAMEREQUEST_H_
#include <string>
#include <vector>
#include <alibabacloud/core/RpcServiceRequest.h>
#include <alibabacloud/alidns/AlidnsExport.h>
namespace AlibabaCloud
{
namespace Alidns
{
namespace Model
{
class ALIBABACLOUD_ALIDNS_EXPORT GetMainDomainNameRequest : public RpcServiceRequest
{
public:
GetMainDomainNameRequest();
~GetMainDomainNameRequest();
std::string getInputString()const;
void setInputString(const std::string& inputString);
std::string getUserClientIp()const;
void setUserClientIp(const std::string& userClientIp);
std::string getLang()const;
void setLang(const std::string& lang);
std::string getAccessKeyId()const;
void setAccessKeyId(const std::string& accessKeyId);
private:
std::string inputString_;
std::string userClientIp_;
std::string lang_;
std::string accessKeyId_;
};
}
}
}
#endif // !ALIBABACLOUD_ALIDNS_MODEL_GETMAINDOMAINNAMEREQUEST_H_ | [
"haowei.yao@alibaba-inc.com"
] | haowei.yao@alibaba-inc.com |
d441d6d8fc3559771e8cd82cb3cfd165a88939e6 | 4aacacfe7222a1061723afa58debb8461a03f03e | /274 H-Index/002.cpp | 07dbcd0f0e86718bef525513f46a4dd4e3d0fbcf | [] | no_license | wangqian1992511/LeetCode | 8143807cc52f951ac926ab24a86bbcf9306fc915 | a056f1dc977200595f39a118948a178bb09f747e | refs/heads/master | 2020-03-30T07:11:15.402450 | 2017-07-14T07:46:37 | 2017-07-14T07:46:37 | 34,139,175 | 9 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 428 | cpp | class Solution {
public:
int hIndex(vector<int>& citations) {
int l = 0, r = citations.size(), n = citations.size();
while (l < r) {
int m = (l + r + 1) >> 1, t = 0;
for (int i = 0; i < n; i++)
if (citations[i] >= m)
t++;
if (t < m)
r = m - 1;
else
l = m;
}
return l;
}
}; | [
"wangqian1992511@gmail.com"
] | wangqian1992511@gmail.com |
20135f50baf747ddbc0036fcc8795d373bd4176f | 260545118d5a4119da25f1a582567f431caef0fd | /personalizado/pedido 4508/v6.1/casa/code/buffer.inc | 24919dc969020077b42a810c9aaaa830be23575e | [] | no_license | sscanf/vph1 | 9649d9363d67be710a54aa07ea42ea085eb91140 | 68a9b2fc28788adeb5f74a1dbfe936f2b39dc5bd | refs/heads/master | 2020-06-23T15:59:26.379696 | 2019-07-24T16:23:24 | 2019-07-24T16:23:24 | 198,670,344 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,204 | inc |
; ANSI-C/cC++ Compiler for HC08 V-5.0.15, Apr 11 2002
;
; Automatic generated include file for the assembler
; Generated using the following files :
; file :'Z:\vph1\Code\buffer.cpp'
; file :'E:\Documents and settings\oscar\Mis documentos\bin\Metrowerks\CodeWarrior HC08_V2.0\lib\HC08c\INCLUDE\math.h'
; file :'E:\Documents and settings\oscar\Mis documentos\bin\Metrowerks\CodeWarrior HC08_V2.0\lib\HC08c\INCLUDE\ieeemath.h'
; file :'E:\Documents and settings\oscar\Mis documentos\bin\Metrowerks\CodeWarrior HC08_V2.0\lib\HC08c\INCLUDE\stdlib.h'
; file :'E:\Documents and settings\oscar\Mis documentos\bin\Metrowerks\CodeWarrior HC08_V2.0\lib\HC08c\INCLUDE\stddef.h'
; file :'E:\Documents and settings\oscar\Mis documentos\bin\Metrowerks\CodeWarrior HC08_V2.0\lib\HC08c\INCLUDE\libdefs.h'
; file :'E:\Documents and settings\oscar\Mis documentos\bin\Metrowerks\CodeWarrior HC08_V2.0\lib\HC08c\INCLUDE\hidef.h'
; file :'E:\Documents and settings\oscar\Mis documentos\bin\Metrowerks\CodeWarrior HC08_V2.0\lib\HC08c\INCLUDE\stddef.h'
; file :'E:\Documents and settings\oscar\Mis documentos\bin\Metrowerks\CodeWarrior HC08_V2.0\lib\HC08c\INCLUDE\stdtypes.h'
; file :'Z:\vph1\Code\buffer.h'
;
| [
"oscar.casamitjana@globalzitro.com"
] | oscar.casamitjana@globalzitro.com |
62a4fdb18bd313eb5c11e6f5560fb6c0e22e3f94 | 7d29954c47203863c457c04794725a5e320b8c9d | /loadbalancers/cpuonly.hh | 496a7a81552831fbcdacb7a7cba28601b3f377b2 | [
"MIT"
] | permissive | gitter-badger/NBA | 879340c00c5d83e0187b0162ab2bc1f9dc3d6add | f85ce709eb0a54d0340cc74ffe2532ae9ece8541 | refs/heads/master | 2020-12-24T19:45:53.787219 | 2015-08-07T04:36:57 | 2015-08-07T04:36:57 | 40,404,246 | 0 | 0 | null | 2015-08-08T13:48:52 | 2015-08-08T13:48:52 | null | UTF-8 | C++ | false | false | 470 | hh | #ifndef __LB_CPUONLY_HH__
#define __LB_CPUONLY_HH__
#include "../lib/loadbalancer.hh"
namespace nba {
class CPUOnlyLB : public LoadBalancer
{
public:
int gate_keeper(PacketBatch *batch, vector<ComputeDevice*>& devices)
{
return -1;
}
uint64_t update_params(SystemInspector &inspector, uint64_t timestamp)
{
// do nothing...
return 1000000u;
}
};
}
EXPORT_LOADBALANCER(CPUOnlyLB);
#endif
// vim: ts=8 sts=4 sw=4 et
| [
"joongi@an.kaist.ac.kr"
] | joongi@an.kaist.ac.kr |
29c1f57cdf61f86eae3e1775f8ccf2586b974ad7 | becd5ee93440020322e3ad99926cebc0e71d786d | /src/storage/query/GetNeighborsProcessor.cpp | 149a7c9018ba96611b1b63e0511ba70666ff4ff8 | [
"Apache-2.0"
] | permissive | heyanlong/nebula | aa94f589a2d77d0cb6e40dcced1f5ee0a8e6a79c | 07ccfde198c978b8c86b7091773e3238bfcdf454 | refs/heads/master | 2023-09-04T13:49:18.522506 | 2021-11-03T15:16:03 | 2021-11-03T15:16:03 | 424,433,008 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,021 | cpp | /* Copyright (c) 2020 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License.
*/
#include "storage/query/GetNeighborsProcessor.h"
#include "storage/StorageFlags.h"
#include "storage/exec/AggregateNode.h"
#include "storage/exec/EdgeNode.h"
#include "storage/exec/FilterNode.h"
#include "storage/exec/GetNeighborsNode.h"
#include "storage/exec/HashJoinNode.h"
#include "storage/exec/TagNode.h"
namespace nebula {
namespace storage {
ProcessorCounters kGetNeighborsCounters;
void GetNeighborsProcessor::process(const cpp2::GetNeighborsRequest& req) {
if (executor_ != nullptr) {
executor_->add([req, this]() { this->doProcess(req); });
} else {
doProcess(req);
}
}
void GetNeighborsProcessor::doProcess(const cpp2::GetNeighborsRequest& req) {
spaceId_ = req.get_space_id();
auto retCode = getSpaceVidLen(spaceId_);
if (retCode != nebula::cpp2::ErrorCode::SUCCEEDED) {
for (auto& p : req.get_parts()) {
pushResultCode(retCode, p.first);
}
onFinished();
return;
}
if (req.common_ref().has_value() && req.get_common()->profile_detail_ref().value_or(false)) {
profileDetailFlag_ = true;
}
this->planContext_ = std::make_unique<PlanContext>(
this->env_, spaceId_, this->spaceVidLen_, this->isIntId_, req.common_ref());
// build TagContext and EdgeContext
retCode = checkAndBuildContexts(req);
if (retCode != nebula::cpp2::ErrorCode::SUCCEEDED) {
for (auto& p : req.get_parts()) {
pushResultCode(retCode, p.first);
}
onFinished();
return;
}
int64_t limit = FLAGS_max_edge_returned_per_vertex;
bool random = false;
if ((*req.traverse_spec_ref()).limit_ref().has_value()) {
if (*(*req.traverse_spec_ref()).limit_ref() >= 0) {
limit = *(*req.traverse_spec_ref()).limit_ref();
}
if ((*req.traverse_spec_ref()).random_ref().has_value()) {
random = *(*req.traverse_spec_ref()).random_ref();
}
}
// todo(doodle): specify by each query
if (!FLAGS_query_concurrently) {
runInSingleThread(req, limit, random);
} else {
runInMultipleThread(req, limit, random);
}
}
void GetNeighborsProcessor::runInSingleThread(const cpp2::GetNeighborsRequest& req,
int64_t limit,
bool random) {
contexts_.emplace_back(RuntimeContext(planContext_.get()));
expCtxs_.emplace_back(StorageExpressionContext(spaceVidLen_, isIntId_));
auto plan = buildPlan(&contexts_.front(), &expCtxs_.front(), &resultDataSet_, limit, random);
std::unordered_set<PartitionID> failedParts;
for (const auto& partEntry : req.get_parts()) {
auto partId = partEntry.first;
for (const auto& row : partEntry.second) {
CHECK_GE(row.values.size(), 1);
auto vId = row.values[0].getStr();
if (!NebulaKeyUtils::isValidVidLen(spaceVidLen_, vId)) {
LOG(ERROR) << "Space " << spaceId_ << ", vertex length invalid, "
<< " space vid len: " << spaceVidLen_ << ", vid is " << vId;
pushResultCode(nebula::cpp2::ErrorCode::E_INVALID_VID, partId);
onFinished();
return;
}
// the first column of each row would be the vertex id
auto ret = plan.go(partId, vId);
if (ret != nebula::cpp2::ErrorCode::SUCCEEDED) {
if (failedParts.find(partId) == failedParts.end()) {
failedParts.emplace(partId);
handleErrorCode(ret, spaceId_, partId);
}
}
}
}
if (UNLIKELY(profileDetailFlag_)) {
profilePlan(plan);
}
onProcessFinished();
onFinished();
}
void GetNeighborsProcessor::runInMultipleThread(const cpp2::GetNeighborsRequest& req,
int64_t limit,
bool random) {
for (size_t i = 0; i < req.get_parts().size(); i++) {
nebula::DataSet result = resultDataSet_;
results_.emplace_back(std::move(result));
contexts_.emplace_back(RuntimeContext(planContext_.get()));
expCtxs_.emplace_back(StorageExpressionContext(spaceVidLen_, isIntId_));
}
size_t i = 0;
std::vector<folly::Future<std::pair<nebula::cpp2::ErrorCode, PartitionID>>> futures;
for (const auto& [partId, rows] : req.get_parts()) {
futures.emplace_back(
runInExecutor(&contexts_[i], &expCtxs_[i], &results_[i], partId, rows, limit, random));
i++;
}
folly::collectAll(futures).via(executor_).thenTry([this](auto&& t) mutable {
CHECK(!t.hasException());
const auto& tries = t.value();
for (size_t j = 0; j < tries.size(); j++) {
CHECK(!tries[j].hasException());
const auto& [code, partId] = tries[j].value();
if (code != nebula::cpp2::ErrorCode::SUCCEEDED) {
handleErrorCode(code, spaceId_, partId);
} else {
resultDataSet_.append(std::move(results_[j]));
}
}
this->onProcessFinished();
this->onFinished();
});
}
folly::Future<std::pair<nebula::cpp2::ErrorCode, PartitionID>> GetNeighborsProcessor::runInExecutor(
RuntimeContext* context,
StorageExpressionContext* expCtx,
nebula::DataSet* result,
PartitionID partId,
const std::vector<nebula::Row>& rows,
int64_t limit,
bool random) {
return folly::via(
executor_, [this, context, expCtx, result, partId, input = std::move(rows), limit, random]() {
auto plan = buildPlan(context, expCtx, result, limit, random);
for (const auto& row : input) {
CHECK_GE(row.values.size(), 1);
auto vId = row.values[0].getStr();
if (!NebulaKeyUtils::isValidVidLen(spaceVidLen_, vId)) {
LOG(ERROR) << "Space " << spaceId_ << ", vertex length invalid, "
<< " space vid len: " << spaceVidLen_ << ", vid is " << vId;
return std::make_pair(nebula::cpp2::ErrorCode::E_INVALID_VID, partId);
}
// the first column of each row would be the vertex id
auto ret = plan.go(partId, vId);
if (ret != nebula::cpp2::ErrorCode::SUCCEEDED) {
return std::make_pair(ret, partId);
}
}
if (UNLIKELY(this->profileDetailFlag_)) {
profilePlan(plan);
}
return std::make_pair(nebula::cpp2::ErrorCode::SUCCEEDED, partId);
});
}
StoragePlan<VertexID> GetNeighborsProcessor::buildPlan(RuntimeContext* context,
StorageExpressionContext* expCtx,
nebula::DataSet* result,
int64_t limit,
bool random) {
/*
The StoragePlan looks like this:
+--------+---------+
| GetNeighborsNode |
+--------+---------+
|
+--------+---------+
| AggregateNode |
+--------+---------+
|
+--------+---------+
| FilterNode |
+--------+---------+
|
+--------+---------+
+-->+ HashJoinNode +<----+
| +------------------+ |
+--------+---------+ +---------+--------+
| TagNodes | | EdgeNodes |
+------------------+ +------------------+
*/
StoragePlan<VertexID> plan;
std::vector<TagNode*> tags;
for (const auto& tc : tagContext_.propContexts_) {
auto tag = std::make_unique<TagNode>(context, &tagContext_, tc.first, &tc.second);
tags.emplace_back(tag.get());
plan.addNode(std::move(tag));
}
std::vector<SingleEdgeNode*> edges;
for (const auto& ec : edgeContext_.propContexts_) {
auto edge = std::make_unique<SingleEdgeNode>(context, &edgeContext_, ec.first, &ec.second);
edges.emplace_back(edge.get());
plan.addNode(std::move(edge));
}
auto hashJoin =
std::make_unique<HashJoinNode>(context, tags, edges, &tagContext_, &edgeContext_, expCtx);
for (auto* tag : tags) {
hashJoin->addDependency(tag);
}
for (auto* edge : edges) {
hashJoin->addDependency(edge);
}
IterateNode<VertexID>* join = hashJoin.get();
IterateNode<VertexID>* upstream = hashJoin.get();
plan.addNode(std::move(hashJoin));
if (filter_) {
auto filter =
std::make_unique<FilterNode<VertexID>>(context, upstream, expCtx, filter_->clone());
filter->addDependency(upstream);
upstream = filter.get();
plan.addNode(std::move(filter));
}
if (edgeContext_.statCount_ > 0) {
auto agg = std::make_unique<AggregateNode<VertexID>>(context, upstream, &edgeContext_);
agg->addDependency(upstream);
upstream = agg.get();
plan.addNode(std::move(agg));
}
std::unique_ptr<GetNeighborsNode> output;
if (random) {
output = std::make_unique<GetNeighborsSampleNode>(
context, join, upstream, &edgeContext_, result, limit);
} else {
output =
std::make_unique<GetNeighborsNode>(context, join, upstream, &edgeContext_, result, limit);
}
output->addDependency(upstream);
plan.addNode(std::move(output));
return plan;
}
nebula::cpp2::ErrorCode GetNeighborsProcessor::checkAndBuildContexts(
const cpp2::GetNeighborsRequest& req) {
resultDataSet_.colNames.emplace_back(kVid);
// reserve second colname for stat
resultDataSet_.colNames.emplace_back("_stats");
auto code = getSpaceVertexSchema();
if (code != nebula::cpp2::ErrorCode::SUCCEEDED) {
return code;
}
code = getSpaceEdgeSchema();
if (code != nebula::cpp2::ErrorCode::SUCCEEDED) {
return code;
}
code = buildTagContext(req.get_traverse_spec());
if (code != nebula::cpp2::ErrorCode::SUCCEEDED) {
return code;
}
code = buildEdgeContext(req.get_traverse_spec());
if (code != nebula::cpp2::ErrorCode::SUCCEEDED) {
return code;
}
code = buildYields(req);
if (code != nebula::cpp2::ErrorCode::SUCCEEDED) {
return code;
}
code = buildFilter(req);
if (code != nebula::cpp2::ErrorCode::SUCCEEDED) {
return code;
}
return nebula::cpp2::ErrorCode::SUCCEEDED;
}
nebula::cpp2::ErrorCode GetNeighborsProcessor::buildTagContext(const cpp2::TraverseSpec& req) {
if (!req.vertex_props_ref().has_value()) {
// If the list is not given, no prop will be returned.
return nebula::cpp2::ErrorCode::SUCCEEDED;
}
auto returnProps =
(*req.vertex_props_ref()).empty() ? buildAllTagProps() : *req.vertex_props_ref();
auto ret = handleVertexProps(returnProps);
if (ret != nebula::cpp2::ErrorCode::SUCCEEDED) {
return ret;
}
buildTagColName(std::move(returnProps));
buildTagTTLInfo();
return nebula::cpp2::ErrorCode::SUCCEEDED;
}
nebula::cpp2::ErrorCode GetNeighborsProcessor::buildEdgeContext(const cpp2::TraverseSpec& req) {
edgeContext_.offset_ = tagContext_.propContexts_.size() + 2;
if (!req.edge_props_ref().has_value()) {
// If the list is not given, no prop will be returned.
return nebula::cpp2::ErrorCode::SUCCEEDED;
}
auto returnProps = (*req.edge_props_ref()).empty() ? buildAllEdgeProps(*req.edge_direction_ref())
: *req.edge_props_ref();
auto ret = handleEdgeProps(returnProps);
if (ret != nebula::cpp2::ErrorCode::SUCCEEDED) {
return ret;
}
if (req.stat_props_ref().has_value()) {
ret = handleEdgeStatProps(*req.stat_props_ref());
if (ret != nebula::cpp2::ErrorCode::SUCCEEDED) {
return ret;
}
}
buildEdgeColName(std::move(returnProps));
buildEdgeTTLInfo();
return nebula::cpp2::ErrorCode::SUCCEEDED;
}
void GetNeighborsProcessor::buildTagColName(const std::vector<cpp2::VertexProp>& tagProps) {
for (const auto& tagProp : tagProps) {
auto tagId = tagProp.get_tag();
auto tagName = tagContext_.tagNames_[tagId];
std::string colName = "_tag:" + tagName;
for (const auto& prop : *tagProp.props_ref()) {
colName += ":" + std::move(prop);
}
VLOG(1) << "append col name: " << colName;
resultDataSet_.colNames.emplace_back(std::move(colName));
}
}
void GetNeighborsProcessor::buildEdgeColName(const std::vector<cpp2::EdgeProp>& edgeProps) {
for (const auto& edgeProp : edgeProps) {
auto edgeType = edgeProp.get_type();
auto edgeName = edgeContext_.edgeNames_[edgeType];
std::string colName = "_edge:";
colName.append(edgeType > 0 ? "+" : "-").append(edgeName);
for (const auto& prop : *edgeProp.props_ref()) {
colName += ":" + std::move(prop);
}
VLOG(1) << "append col name: " << colName;
resultDataSet_.colNames.emplace_back(std::move(colName));
}
}
nebula::cpp2::ErrorCode GetNeighborsProcessor::handleEdgeStatProps(
const std::vector<cpp2::StatProp>& statProps) {
edgeContext_.statCount_ = statProps.size();
std::string colName = "_stats";
auto pool = &this->planContext_->objPool_;
for (size_t statIdx = 0; statIdx < statProps.size(); statIdx++) {
const auto& statProp = statProps[statIdx];
auto exp = Expression::decode(pool, *statProp.prop_ref());
if (exp == nullptr) {
return nebula::cpp2::ErrorCode::E_INVALID_STAT_TYPE;
}
// we only support edge property/rank expression for now
switch (exp->kind()) {
case Expression::Kind::kEdgeRank:
case Expression::Kind::kEdgeProperty: {
auto* edgeExp = static_cast<const PropertyExpression*>(exp);
const auto& edgeName = edgeExp->sym();
const auto& propName = edgeExp->prop();
auto edgeRet = this->env_->schemaMan_->toEdgeType(spaceId_, edgeName);
if (!edgeRet.ok()) {
VLOG(1) << "Can't find edge " << edgeName << ", in space " << spaceId_;
return nebula::cpp2::ErrorCode::E_EDGE_NOT_FOUND;
}
auto edgeType = edgeRet.value();
auto iter = edgeContext_.schemas_.find(std::abs(edgeType));
if (iter == edgeContext_.schemas_.end()) {
VLOG(1) << "Can't find spaceId " << spaceId_ << " edgeType " << std::abs(edgeType);
return nebula::cpp2::ErrorCode::E_EDGE_NOT_FOUND;
}
CHECK(!iter->second.empty());
const auto& edgeSchema = iter->second.back();
const meta::SchemaProviderIf::Field* field = nullptr;
if (exp->kind() == Expression::Kind::kEdgeProperty) {
field = edgeSchema->field(propName);
if (field == nullptr) {
VLOG(1) << "Can't find related prop " << propName << " on edge " << edgeName;
return nebula::cpp2::ErrorCode::E_EDGE_PROP_NOT_FOUND;
}
auto ret = checkStatType(field, statProp.get_stat());
if (ret != nebula::cpp2::ErrorCode::SUCCEEDED) {
return ret;
}
}
auto statInfo = std::make_pair(statIdx, statProp.get_stat());
addPropContextIfNotExists(edgeContext_.propContexts_,
edgeContext_.indexMap_,
edgeContext_.edgeNames_,
edgeType,
edgeName,
propName,
field,
false,
false,
&statInfo);
break;
}
default: {
return nebula::cpp2::ErrorCode::E_INVALID_STAT_TYPE;
}
}
colName += ":" + std::move(statProp.get_alias());
}
resultDataSet_.colNames[1] = std::move(colName);
return nebula::cpp2::ErrorCode::SUCCEEDED;
}
nebula::cpp2::ErrorCode GetNeighborsProcessor::checkStatType(
const meta::SchemaProviderIf::Field* field, cpp2::StatType statType) {
// todo(doodle): how to deal with nullable fields? For now, null add anything
// is null, if there is even one null, the result will be invalid
auto fType = field->type();
switch (statType) {
case cpp2::StatType::SUM:
case cpp2::StatType::AVG:
case cpp2::StatType::MIN:
case cpp2::StatType::MAX: {
if (fType == nebula::cpp2::PropertyType::INT64 ||
fType == nebula::cpp2::PropertyType::INT32 ||
fType == nebula::cpp2::PropertyType::INT16 || fType == nebula::cpp2::PropertyType::INT8 ||
fType == nebula::cpp2::PropertyType::FLOAT ||
fType == nebula::cpp2::PropertyType::DOUBLE) {
return nebula::cpp2::ErrorCode::SUCCEEDED;
}
return nebula::cpp2::ErrorCode::E_INVALID_STAT_TYPE;
}
case cpp2::StatType::COUNT: {
break;
}
}
return nebula::cpp2::ErrorCode::SUCCEEDED;
}
void GetNeighborsProcessor::onProcessFinished() { resp_.set_vertices(std::move(resultDataSet_)); }
void GetNeighborsProcessor::profilePlan(StoragePlan<VertexID>& plan) {
auto& nodes = plan.getNodes();
std::lock_guard<std::mutex> lck(BaseProcessor<cpp2::GetNeighborsResponse>::profileMut_);
for (auto& node : nodes) {
profileDetail(node->name_, node->duration_.elapsedInUSec());
}
}
} // namespace storage
} // namespace nebula
| [
"noreply@github.com"
] | noreply@github.com |
37583c06e472e4c9c9a246fea770f362d904c92e | 3c5c1e3836edf3e9627a64600785503d1814df51 | /build/Android/Debug/app/src/main/include/Fuse.RootViewport.h | 3222ef2d61edd8551274bdcf9d6aa274aad7b727 | [] | no_license | fypwyt/wytcarpool | 70a0c9ca12d0f2981187f2ea21a8a02ee4cbcbd4 | 4fbdeedf261ee8ecd563260816991741ec701432 | refs/heads/master | 2021-09-08T10:32:17.612628 | 2018-03-09T05:24:54 | 2018-03-09T05:24:54 | 124,490,692 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,578 | h | // This file was generated based on C:/Users/Brian/AppData/Local/Fusetools/Packages/Fuse.Nodes/1.6.0/RootViewport.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Binding.h>
#include <Fuse.ICommonViewport.h>
#include <Fuse.INotifyUnrooted.h>
#include <Fuse.IProperties.h>
#include <Fuse.ITemplateSource.h>
#include <Fuse.IViewport.h>
#include <Fuse.Node.h>
#include <Fuse.Scripting.IScriptObject.h>
#include <Fuse.Visual.h>
#include <Uno.Collections.ICollection-1.h>
#include <Uno.Collections.IEnumerable-1.h>
#include <Uno.Collections.IList-1.h>
#include <Uno.Float2.h>
#include <Uno.IDisposable.h>
#include <Uno.UX.IPropertyListener.h>
namespace g{namespace Fuse{struct DrawContext;}}
namespace g{namespace Fuse{struct FrustumViewport;}}
namespace g{namespace Fuse{struct PreviewState;}}
namespace g{namespace Fuse{struct Ray;}}
namespace g{namespace Fuse{struct RootViewport;}}
namespace g{
namespace Fuse{
// public class RootViewport :33
// {
struct RootViewport_type : ::g::Fuse::Visual_type
{
::g::Fuse::IViewport interface12;
::g::Uno::IDisposable interface13;
::g::Fuse::ICommonViewport interface14;
};
RootViewport_type* RootViewport_typeof();
void RootViewport__ctor_3_fn(RootViewport* __this);
void RootViewport__ctor_4_fn(RootViewport* __this, uObject* frame);
void RootViewport__Draw_fn(RootViewport* __this, ::g::Fuse::DrawContext* dc);
void RootViewport__EstablishSize_fn(RootViewport* __this);
void RootViewport__EstablishSizeInternals_fn(RootViewport* __this);
void RootViewport__OnInvalidateLayout_fn(RootViewport* __this);
void RootViewport__OnResized_fn(RootViewport* __this, uObject* s, uObject* a);
void RootViewport__get_PixelSize_fn(RootViewport* __this, ::g::Uno::Float2* __retval);
void RootViewport__get_PixelsPerPoint_fn(RootViewport* __this, float* __retval);
void RootViewport__PointToWorldRay_fn(RootViewport* __this, ::g::Uno::Float2* pixelPos, ::g::Fuse::Ray* __retval);
void RootViewport__get_PreviewState_fn(RootViewport* __this, ::g::Fuse::PreviewState** __retval);
void RootViewport__add_Resized_fn(RootViewport* __this, uDelegate* value);
void RootViewport__remove_Resized_fn(RootViewport* __this, uDelegate* value);
void RootViewport__get_Size_fn(RootViewport* __this, ::g::Uno::Float2* __retval);
void RootViewport__UnoIDisposableDispose_fn(RootViewport* __this);
void RootViewport__get_VisualContext_fn(RootViewport* __this, int32_t* __retval);
void RootViewport__WorldToLocalRay_fn(RootViewport* __this, uObject* world, ::g::Fuse::Ray* worldRay, ::g::Fuse::Visual* where, ::g::Fuse::Ray* __retval);
struct RootViewport : ::g::Fuse::Visual
{
uStrong<uObject*> _frame;
uStrong<uObject*> Frustum;
uStrong< ::g::Fuse::FrustumViewport*> _frustumViewport;
bool _sizeOverridden;
float _pixelsPerPoint;
float _pixelsPerOSPoint;
float _overridePixelsPerPoint;
::g::Uno::Float2 _pixelSize;
uStrong< ::g::Fuse::PreviewState*> _previewState;
uStrong<uDelegate*> Resized1;
void ctor_3();
void ctor_4(uObject* frame);
void EstablishSize();
void EstablishSizeInternals();
void OnResized(uObject* s, uObject* a);
::g::Uno::Float2 PixelSize();
float PixelsPerPoint();
::g::Fuse::Ray PointToWorldRay(::g::Uno::Float2 pixelPos);
::g::Fuse::PreviewState* PreviewState();
void add_Resized(uDelegate* value);
void remove_Resized(uDelegate* value);
::g::Uno::Float2 Size();
::g::Fuse::Ray WorldToLocalRay(uObject* world, ::g::Fuse::Ray worldRay, ::g::Fuse::Visual* where);
};
// }
}} // ::g::Fuse
| [
"s1141120@studentdmn.ouhk.edu.hk"
] | s1141120@studentdmn.ouhk.edu.hk |
98e01f7164ffda9a145a3278ffe9ec1e8237c5db | a68d1148a78dae34788b85af1ae05d72fe66347f | /MaterialSystem/src/TF2Vulkan/MaterialVar.h | 7bfd4232a0f6a043a4c0512c9373c824c6630578 | [
"MIT"
] | permissive | PazerOP/TF2Vulkan | e8d477ad4f9df6ccf7d5d1f65a7af9ddcb03476a | c4836b0567f91e0887aa6e13ff7cb0a4ab293c8e | refs/heads/master | 2020-05-16T17:03:53.011995 | 2019-10-10T20:05:05 | 2019-10-10T20:05:05 | 183,180,332 | 25 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,413 | h | #pragma once
#include "IMaterialVar2.h"
#include <string>
#include <variant>
namespace TF2Vulkan
{
class Material;
class MaterialVar final : public IMaterialVar2
{
static constexpr int VEC_COMPONENT_COUNT = 4;
public:
MaterialVar(Material* parent, const char* name, const char* value);
const char* GetName() const;
MaterialVarSym_t GetNameAsSymbol() const override;
ITexture* GetTextureValue() override;
void SetTextureValue(ITexture* texture) override;
IMaterial* GetMaterialValue() override;
void SetMaterialValue(IMaterial* material) override;
bool IsDefined() const override;
void SetUndefined() override;
const char* GetStringValue() const override;
void SetStringValue(const char* val) override;
using IMaterialVar2::GetFourCCValue;
void GetFourCCValue(FourCC* type, const void** data) const override;
void SetFourCCValue(FourCC type, void* data) override;
void SetFloatValue(float val) override;
void SetIntValue(int val) override;
void GetLinearVecValue(float* val, int components) const override;
void SetVecValue(const float* val, int components) override;
void SetVecValue(float x, float y) override;
void SetVecValue(float x, float y, float z) override;
void SetVecValue(float x, float y, float z, float w) override;
void SetVecComponentValue(float val, int component) override;
const VMatrix& GetMatrixValue() const override;
void SetMatrixValue(const VMatrix& matrix) override;
bool MatrixIsIdentity() const override;
IMaterial* GetOwningMaterial() override;
void CopyFrom(const IMaterialVar* other) override;
void SetValueAutodetectType(const char* val) override;
protected:
int GetIntValueInternal() const override;
float GetFloatValueInternal() const override;
const float* GetVecValueInternal() const override;
void GetVecValueInternal(float* val, int components) const override;
int VectorSizeInternal() const override;
private:
static bool HasStringRep(MaterialVarType_t type);
Material* m_Parent = nullptr;
void ChangeTypeTo(MaterialVarType_t type);
void SetStringImpl(const char* str);
void ClearStringValue();
struct FourCCData;
struct MatrixData;
union
{
IMaterial* m_Material = nullptr;
ITexture* m_Texture;
FourCCData* m_FourCC;
MatrixData* m_Matrix;
} m_ExtendedValue;
static_assert(sizeof(m_ExtendedValue) == sizeof(m_ExtendedValue.m_Material));
};
}
| [
"mrhaynie@live.com"
] | mrhaynie@live.com |
278bcac4f7cd5a0c758fa395b00312fe2573d51d | f1aaed1e27416025659317d1f679f7b3b14d654e | /MenuMate/MenuMate/Source/DocketFormat.h | 7f281c37d0ec8877f096181ec77fe33a06b34804 | [] | no_license | radtek/Pos | cee37166f89a7fcac61de9febb3760d12b823ce5 | f117845e83b41d65f18a4635a98659144d66f435 | refs/heads/master | 2020-11-25T19:49:37.755286 | 2016-09-16T14:55:17 | 2016-09-16T14:55:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 707 | h | //---------------------------------------------------------------------------
#ifndef DocketFormatH
#define DocketFormatH
#include "MM_DBCore.h"
#include <map>
//---------------------------------------------------------------------------
class TDocketFormat
{
public :
TDocketFormat();
void Load(Database::TDBTransaction &DBTransaction);
std::map<long,UnicodeString> KeyItemHeader;
WideString BulletSide; // " > "
WideString BulletOpt; // " "
WideString BulletSetMenuItem; // " "
WideString NoteHeader; // "Note: "
WideString MixHeader; // " Mix: "
WideString SideHeader; // " Sides: "
WideString DishesPerSeatMultiplerString;
bool UnRavelKitchenPrinting;
};
#endif
| [
"ravish.sharma@menumate.com"
] | ravish.sharma@menumate.com |
bb203eec4ebebccfe9548b08065b4e2203e0b94f | 00085b6110f415c047cbe5c008f9ababa17ccf20 | /Stitching algorithm/imagestitcher.h | 6d2db781ac28878faa8978d768384fcfa2d5b185 | [] | no_license | nefelihutton/SMART_System | 5d661e1a3ab126ba3532bbb678cf3b9c88dae651 | 5b2901fd495d70885697086a31791642fd909a60 | refs/heads/master | 2023-03-15T11:10:14.882660 | 2020-04-16T08:22:45 | 2020-04-16T08:22:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 983 | h | #ifndef IMAGESTITCHER_H
#define IMAGESTITCHER_H
#include "opencv2/opencv.hpp"
#include <QString>
class ImageStitcher
{
public:
ImageStitcher();
virtual ~ImageStitcher();
bool StitchImagesByPath(const QStringList &srcPathList,
int picColNum,
int picRowNum,
double overlapedRatio,
unsigned char *buf,
int canvasWidth,
int canvasHeight,
int *validWidth,
int *validHeight);
private:
bool ImageMosacBack(const QStringList &srcPathList, double overlapedRatio, int picColNum, int picRowNum, cv::Mat &dst, int *validWidth, int *validHeight);
void OptimizeSeamBack(int index, cv::Mat &img, cv::Mat &trans, int picColNum, int picRowNum, int width, int height, const QList<cv::Point> &offsetList, cv::Mat &dst);
};
#endif // IMAGESTITCHER_H
| [
"215701826@qq.com"
] | 215701826@qq.com |
798db876c51f4cb887c51352829f3f195bdfb014 | 9fad4848e43f4487730185e4f50e05a044f865ab | /src/components/autofill/core/browser/autofill_xml_parser_unittest.cc | cfa42904b16af8b7d51740f033fe191e8c599ceb | [
"BSD-3-Clause"
] | permissive | dummas2008/chromium | d1b30da64f0630823cb97f58ec82825998dbb93e | 82d2e84ce3ed8a00dc26c948219192c3229dfdaa | refs/heads/master | 2020-12-31T07:18:45.026190 | 2016-04-14T03:17:45 | 2016-04-14T03:17:45 | 56,194,439 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,860 | cc | // Copyright 2013 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/autofill/core/browser/autofill_xml_parser.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/strings/string_number_conversions.h"
#include "components/autofill/core/browser/autofill_server_field_info.h"
#include "components/autofill/core/browser/field_types.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace autofill {
namespace {
class AutofillQueryXmlParserTest : public testing::Test {
public:
AutofillQueryXmlParserTest(): upload_required_(USE_UPLOAD_RATES) {}
~AutofillQueryXmlParserTest() override{};
protected:
void ParseQueryXML(std::string xml, bool should_succeed) {
EXPECT_EQ(should_succeed,
ParseAutofillQueryXml(std::move(xml), &field_infos_,
&upload_required_));
}
std::vector<AutofillServerFieldInfo> field_infos_;
UploadRequired upload_required_;
};
TEST_F(AutofillQueryXmlParserTest, BasicQuery) {
// An XML string representing a basic query response.
std::string xml = "<autofillqueryresponse>"
"<field autofilltype=\"0\" />"
"<field autofilltype=\"1\" />"
"<field autofilltype=\"3\" />"
"<field autofilltype=\"2\" />"
"<field autofilltype=\"61\" defaultvalue=\"default\"/>"
"</autofillqueryresponse>";
ParseQueryXML(std::move(xml), true);
EXPECT_EQ(USE_UPLOAD_RATES, upload_required_);
ASSERT_EQ(5U, field_infos_.size());
EXPECT_EQ(NO_SERVER_DATA, field_infos_[0].field_type);
EXPECT_EQ(UNKNOWN_TYPE, field_infos_[1].field_type);
EXPECT_EQ(NAME_FIRST, field_infos_[2].field_type);
EXPECT_EQ(EMPTY_TYPE, field_infos_[3].field_type);
EXPECT_TRUE(field_infos_[3].default_value.empty());
EXPECT_EQ(FIELD_WITH_DEFAULT_VALUE, field_infos_[4].field_type);
EXPECT_EQ("default", field_infos_[4].default_value);
}
// Test parsing the upload required attribute.
TEST_F(AutofillQueryXmlParserTest, TestUploadRequired) {
std::string xml = "<autofillqueryresponse uploadrequired=\"true\">"
"<field autofilltype=\"0\" />"
"</autofillqueryresponse>";
ParseQueryXML(std::move(xml), true);
EXPECT_EQ(upload_required_, upload_required_);
ASSERT_EQ(1U, field_infos_.size());
EXPECT_EQ(NO_SERVER_DATA, field_infos_[0].field_type);
field_infos_.clear();
xml = "<autofillqueryresponse uploadrequired=\"false\">"
"<field autofilltype=\"0\" />"
"</autofillqueryresponse>";
ParseQueryXML(std::move(xml), true);
EXPECT_EQ(UPLOAD_NOT_REQUIRED, upload_required_);
ASSERT_EQ(1U, field_infos_.size());
EXPECT_EQ(NO_SERVER_DATA, field_infos_[0].field_type);
field_infos_.clear();
xml = "<autofillqueryresponse uploadrequired=\"bad_value\">"
"<field autofilltype=\"0\" />"
"</autofillqueryresponse>";
ParseQueryXML(std::move(xml), true);
EXPECT_EQ(USE_UPLOAD_RATES, upload_required_);
ASSERT_EQ(1U, field_infos_.size());
EXPECT_EQ(NO_SERVER_DATA, field_infos_[0].field_type);
}
// Test badly formed XML queries.
TEST_F(AutofillQueryXmlParserTest, ParseErrors) {
// Test no Autofill type.
std::string xml = "<autofillqueryresponse>"
"<field/>"
"</autofillqueryresponse>";
ParseQueryXML(std::move(xml), false);
// Test an incorrect Autofill type.
xml = "<autofillqueryresponse>"
"<field autofilltype=\"-1\"/>"
"</autofillqueryresponse>";
ParseQueryXML(std::move(xml), true);
EXPECT_EQ(USE_UPLOAD_RATES, upload_required_);
ASSERT_EQ(1U, field_infos_.size());
// AutofillType was out of range and should be set to NO_SERVER_DATA.
EXPECT_EQ(NO_SERVER_DATA, field_infos_[0].field_type);
// Test upper bound for the field type, MAX_VALID_FIELD_TYPE.
field_infos_.clear();
xml = "<autofillqueryresponse><field autofilltype=\"" +
base::IntToString(MAX_VALID_FIELD_TYPE) + "\"/></autofillqueryresponse>";
ParseQueryXML(std::move(xml), true);
EXPECT_EQ(USE_UPLOAD_RATES, upload_required_);
ASSERT_EQ(1U, field_infos_.size());
// AutofillType was out of range and should be set to NO_SERVER_DATA.
EXPECT_EQ(NO_SERVER_DATA, field_infos_[0].field_type);
// Test an incorrect Autofill type.
field_infos_.clear();
xml = "<autofillqueryresponse>"
"<field autofilltype=\"No Type\"/>"
"</autofillqueryresponse>";
// Unknown autofill type is handled gracefully.
ParseQueryXML(std::move(xml), true);
EXPECT_EQ(USE_UPLOAD_RATES, upload_required_);
ASSERT_EQ(1U, field_infos_.size());
EXPECT_EQ(NO_SERVER_DATA, field_infos_[0].field_type);
}
} // namespace
} // namespace autofill
| [
"dummas@163.com"
] | dummas@163.com |
c0bd066cb89a327d3a4e90558ddd51602f6eea3a | c2398aab3d10bff489cdc007b6b8b23d56408571 | /ANSConstants.cpp | 5c36a91bac11036fcb833f1e21317ba4b5e3be7b | [] | no_license | Hau-Bold/ANS | e0b64b962cb1c5e9816a7dc8552ae23dee045cc1 | bbcb549931be2b0f66343f6a52496d0d13921bf2 | refs/heads/master | 2020-05-04T07:58:36.262632 | 2019-04-02T08:57:46 | 2019-04-02T08:57:46 | 147,683,765 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,469 | cpp | #include"ANSConstants.h"
/**constants for entropy*/
const std::string ANSConstants::ENTROPIE = "Entropy:";
const std::string ANSConstants::ENTROPIE_NORMALIZED = "Entropy normalized:";
const std::string ANSConstants::PRECONDITIONED_ENTROPIE = "Preconditioned entropy:";
const std::string ANSConstants::PRECONDITIONED_ENTROPIE_NORMALIZED = "Preconditioned entropy normalized:";
/**constants for sum of frequencies*/
const std::string ANSConstants::SUM_OF_FREQUENCIES = "Sum of frequencies";
const std::string ANSConstants::SUM_OF_NORMALIZED_FREQUENCIES = "Sum of frequencies";
const std::string ANSConstants::SUM_OF_PRECONDITIONED_FREQUENCIES = "Sum of preconditioned frequencies";
const std::string ANSConstants::SUM_OF_PRECONDITIONED_FREQUENCIES_NORMALIZED = "Sum of preconditioned frequencies normalized";
//constants for binary file.
const std::string ANSConstants::FORMAT_ENDING = ".bin";
const std::string ANSConstants::FORMAT_ENDING_ENCODING = ".ppm";
std::string ANSConstants::MESSAGE_DURATION_OF_PRECONDITIONING = "Precondition took %.2f seconds\n";
std::string ANSConstants::MESSAGE_DURATION_OF_POSTCONDITIONING = "Postcondition took %.2f seconds\n";
std::string ANSConstants::MESSAGE_DURATION_OF_COMPRESSION = "Compression took %.2f seconds\n";
std::string ANSConstants::MESSAGE_DURATION_OF_READING_BINARY_FILE = "Reading binary file took %.2f seconds\n";
std::string ANSConstants::MESSAGE_DURATION_OF_DECOMPRESSION = "Decompression took %.2f seconds\n";
| [
"Michael-Krasser@t-online.de"
] | Michael-Krasser@t-online.de |
cc21952195cffb305c4d2d2b4323724fa78f5f5e | 9519d5bdc02326027eb0664511796470590df20d | /CTDL_GT/DSA06011_TongGan0Nhat.cpp | b87208d5219f305c645ba97bcc091dcf810bc115 | [] | no_license | Tonoss-412/Code-Cpp | 4c2676016f6553197375f7daed51a45ec8265fbb | 3d39b228f8a2c87e0b639ad99262e966adab31b0 | refs/heads/master | 2023-06-23T04:17:07.725388 | 2021-07-21T12:40:10 | 2021-07-21T12:40:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 676 | cpp | #include <bits/stdc++.h>
#define faster() ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define base 1000000007
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef unsigned int uint;
typedef vector <int> vi;
typedef vector <string> vs;
void solve(){
int n, a[100000], ans=INT_MAX;
cin >> n;
for (int i=0; i<n; i++) cin >> a[i];
for (int i=0; i<n-1; i++){
for (int j=i+1; j<n; j++){
if (abs(ans)>abs(a[i]+a[j])) {
ans=a[i]+a[j];
}
}
}
cout << ans;
cout << endl;
}
int main()
{
faster();
int t;
cin >> t;
while (t--) solve();
return 0;
} | [
"kieuoanh16012001@gmail.com"
] | kieuoanh16012001@gmail.com |
add9fdff5a331f5ac299e2280775f602f9eefe30 | cf0fab9ca3e9840be6a021e28b01a977f15576da | /Funzioni/TDE11112011-2.cpp | e93141ee4fcbc91b31851e88447f05b0f8d2eb2d | [
"Apache-2.0"
] | permissive | mvaloriani/InformaticaA | 82a43c82fa539ec13af60c03e5c58036f9cc917f | ce77031ea6f1122057600d60a09ff166961ab3d3 | refs/heads/master | 2022-12-23T07:12:10.368798 | 2022-12-19T11:01:48 | 2022-12-19T11:01:48 | 43,888,381 | 2 | 1 | null | null | null | null | IBM852 | C++ | false | false | 1,745 | cpp | /*
I risultati della finale olimpica di nuoto della staffetta 4x100
stile libero sono rappresentati mediante una matrice di dimensioni 4x8.
Ogni cella rappresenta il risultato di un singolo
frazionista tramite la seguente struttura:
typedef struct { int min,sec,cent;} tempo;
typedef struct {char[15] nome,cognome,nazionalitÓ;
tempo t; } frazione;
La matrice Ŕ dichiarata in questo modo:
typedef risultato frazione[4][8]
I risultati sono disposti nella matrice secondo la corsia
(e.g. corsia 1 nella prima colonna)
Scrivere una funzione che riceve in ingresso la matrice
che contiene il risultato e restituisce il numero della corsia vincente.
int corsiaVincente(risultato ris);
Scrivere una funzione che riceve in ingresso la matrice
che contiene il risultato e una variabile che contiene il
record mondiale di staffetta e che restituisce 1 se il record
mondiale Ŕ stato battuto, 0 altrimenti.
int recordBattuto(risultato ris, tempo record);
*/
#include <stdlib.h>
#include <stdio.h>
typedef struct { int min, sec, cent; } tempo;
typedef struct {
tempo t;
char[15] nome;
} frazione;
typedef frazione risultato[4][8];
long converti(tempo t) {
return t.min * 6000 + t.sec * 100 + cent;
}
long calcolaCorsia(risultato ris, int k) {
int i, tot = 0;
for (i = 0; i<4; i++) {
tot += converti(ris[i][k]);
}
return tot;
}
int corsiaVincente(risultato ris) {
int i, min, corrente, imin = 0;
min == calcolaCorsia(ris, 0);
for (i = 0; i<8; i++) {
corrente = calcolaCorsia(ris, i);
if (corrente<min) {
min = corrente; imin = i;
}
}
return imin + 1;
}
int recordBattuto(risultato ris, tempo record) {
int v;
v = corsiaVincente(ris);
if (calcolaCorsia(ris, v)<converti(record))
return 1;
else
return 0;
}
| [
"m-atteo@hotmail.it"
] | m-atteo@hotmail.it |
c456ba25219a38f78b815805c72a746537cbc347 | 15eb185e990074d5b8eec7e41a4a1fdcdc3ad0d2 | /hub4com/plugins/pinmap/precomp.h | 517b7ab73fd51dd071c7d754ae10f1671a9b2b4c | [] | no_license | rtigithub/com0com | 7268cafe40b9f9955719e82b17ada2addad44c3e | da14c4461ea0d047fcadef0b761635378b4eb856 | refs/heads/master | 2022-02-15T03:57:49.542332 | 2012-06-18T07:32:13 | 2012-06-18T07:32:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,092 | h | /*
* $Id$
*
* Copyright (c) 2008-2009 Vyacheslav Frolov
*
* 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 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*
* $Log$
* Revision 1.1 2008/08/11 07:26:48 vfrolov
* Initial revision
*
*/
#ifndef _PRECOMP_H_
#define _PRECOMP_H_
#include <windows.h>
#include <crtdbg.h>
#include <iostream>
using namespace std;
#pragma warning(disable:4512) // assignment operator could not be generated
#endif /* _PRECOMP_H_ */
| [
""
] | |
3fbadb77d1858023766be98252d4dc859e3ea06c | d7784cb9ce174ec5091d327b21ebcf4c6c507388 | /atcoder/codefestival/2015/quala_A/b_1.cpp | 8d522167f905abbe858e5ffff2480fd77826424c | [] | no_license | mmxsrup/procon | 3a349b10c852ad593ecedcdd1c9fdb93cb8d8f3b | af059cc3f6786db71f0077d1ec5d902171b9860a | refs/heads/master | 2021-01-17T15:05:05.580007 | 2017-12-06T07:52:53 | 2017-12-06T07:52:53 | 84,103,106 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 557 | cpp |
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
using namespace std;
typedef long long ll;
typedef pair<int,int> pint;
typedef vector<int> vint;
typedef vector<pint> vpint;
#define mp make_pair
#define fi first
#define se second
#define all(v) (v).begin(),(v).end()
#define rep(i,n) for(int i=0;i<(n);i++)
int main(void){
int n;cin >> n;
vint a(n);
rep(i, n) scanf("%d", &a[i]);
ll sum = 0;
rep(i, n){
sum = sum * 2 + a[i];
}
printf("%lld\n", sum);
return 0;
} | [
"mmxsrup@yahoo.co.jp"
] | mmxsrup@yahoo.co.jp |
34ae85ef375e86341dbaae69e1a676adc87f9728 | fcc88521f63a3c22c81a9242ae3b203f2ea888fd | /C++/0015-3Sum/soln.cpp | bc2dc2e0ab25e430bc9bf7848b06d7962c20dcd2 | [
"MIT"
] | permissive | wyaadarsh/LeetCode-Solutions | b5963e3427aa547d485d3a2cb24e6cedc72804fd | 3719f5cb059eefd66b83eb8ae990652f4b7fd124 | refs/heads/master | 2022-12-06T15:50:37.930987 | 2020-08-30T15:49:27 | 2020-08-30T15:49:27 | 291,811,790 | 0 | 1 | MIT | 2020-08-31T19:57:35 | 2020-08-31T19:57:34 | null | UTF-8 | C++ | false | false | 871 | cpp | class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> ans;
if(nums.size() < 3) return ans;
sort(nums.begin(), nums.end());
for(int i = 0; i < nums.size() - 2; ++i)
{
if(i > 0 && nums[i] == nums[i - 1]) continue;
int l = i + 1;
int r = nums.size() - 1;
while (l < r)
{
int s = nums[i] + nums[l] + nums[r];
if (s == 0)
{
ans.push_back({nums[i], nums[l], nums[r]});
while(l < r && nums[l] == nums[l + 1]) ++l;
while(l < r && nums[r] == nums[r - 1]) --r;
++l;
--r;
} else if (s < 0) ++l;
else --r;
}
}
return ans;
}
}; | [
"zhang623@wisc.edu"
] | zhang623@wisc.edu |
7f84314d7502db80cbc08f6465a59c5347d277f2 | d06373ba0bf8e69cf0d8dd555156e07b524667f0 | /c++/function_fail.cpp | 5010b230dcd60004fc67d478aef4bc0e9e8673b0 | [
"MIT"
] | permissive | LongJohnCoder/gandalv | 3a66eb793dcc9dba2bbefdaf0ccf6354bce8d582 | 0eba287949dafd9a4eb0ce3a4678392634903eea | refs/heads/master | 2020-12-15T00:44:41.199532 | 2020-01-15T22:42:21 | 2020-01-15T22:42:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 282 | cpp | // @expect error
#include <smack.h>//<cassert>
int cap(int x) {
int y = x;
if (10 < x) {
y = 10;
}
return y;
}
int main() {
assert(cap(2) != 2);
assert(cap(15) == 10);
int x = __VERIFIER_nondet_int();
assert(cap(x) <= 10);
return 0;
}
| [
"jjgarzella@gmail.com"
] | jjgarzella@gmail.com |
4b1b90cb711d7642436338d5f66c28cce966ed21 | fb73f038b901124afe7356f96275d5ea3559d847 | /localization/naveen/fiducials/fiducial_slam/src/map0.cpp | 7adf78124a28756643d4f5ea286516d22d27c58e | [] | no_license | quadcopter-ar/QuadcopterAR | 2abaa7e5daf9f3e6b545c5e2efb901cdf75c7f04 | 9a1be7980396cdf0d391a2993af9a49897e0da95 | refs/heads/master | 2020-04-11T00:48:09.385188 | 2019-08-05T16:47:58 | 2019-08-05T16:47:58 | 161,396,463 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 27,287 | cpp | /*
* Copyright (c) 2017, Ubiquity Robotics
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 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
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE 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.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of the FreeBSD Project.
*
*/
#include <fiducial_slam/map0.h>
#include <fiducial_slam/helpers.h>
#include <string>
#include <tf2/LinearMath/Vector3.h>
#include <tf2/LinearMath/Quaternion.h>
#include <std_msgs/String.h>
#include <std_msgs/ColorRGBA.h>
#include <geometry_msgs/TransformStamped.h>
#include <geometry_msgs/Point.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <visualization_msgs/Marker.h>
#include <boost/filesystem.hpp>
// Update the variance of a gaussian that has been combined with another
// Does not Take into account the degree of overlap of observations
static double updateVarianceAlexey(double var1, double var2) {
return max(1.0 / (1.0/var1 + 1.0/var2), 1e-6);
}
static bool useAlexey = false;
// Update the variance of a gaussian that has been combined with another
// Taking into account the degree of overlap
static double updateVarianceDavid(const tf2::Vector3 &newMean,
const tf2::Vector3 &mean1, double var1,
const tf2::Vector3 &mean2, double var2) {
if (useAlexey) {
return updateVarianceAlexey(var1, var2);
}
//=((2*PI())^0.5)*C3*D3*EXP((((((C2-E2)^2))/(2*C3^2))+(((D2-E2)^2)/(2*(D3^2)))))
double d1 = (mean1 - newMean).length2();
double d2 = (mean2 - newMean).length2();
double newVar = sqrt(2.0*M_PI) * var1 * var2 *
exp(((d1 / (2.0*var1)) + d2 / (2.0*var2)));
if (newVar > 100)
newVar = 100;
if (newVar < 10e-4)
newVar = 10e-4;
return newVar;
}
// Update transform t1 with t2 using variances as weights.
// The result is in t1
static void updateTransform(tf2::Transform &t1, double var1,
const tf2::Transform &t2, double var2) {
tf2::Vector3 o1 = t1.getOrigin();
tf2::Vector3 o2 = t2.getOrigin();
t1.setOrigin((var1 * o2 + var2 * o1) / (var1 + var2));
tf2::Quaternion q1 = t1.getRotation();
tf2::Quaternion q2 = t2.getRotation();
t1.setRotation(q1.slerp(q2, var1 / (var1 + var2)).normalized());
}
// Update this transform with a new one, with variances as weights
// combine variances using David method
void TransformWithVariance::update(const TransformWithVariance& newT) {
tf2::Vector3 o1 = transform.getOrigin();
tf2::Quaternion q1 = transform.getRotation();
double var1 = variance;
tf2::Vector3 o2 = newT.transform.getOrigin();
tf2::Quaternion q2 = newT.transform.getRotation();
double var2 = newT.variance;
transform.setOrigin((var1 * o2 + var2 * o1) / (var1 + var2));
transform.setRotation(q1.slerp(q2, var1 / (var1 + var2)).normalized());
variance = updateVarianceDavid(transform.getOrigin(), o1, var1, o2, var2);
}
// Weighted average of 2 transforms, variances computed using Alexey Method
TransformWithVariance averageTransforms(const TransformWithVariance& t1, const TransformWithVariance& t2) {
TransformWithVariance out;
tf2::Vector3 o1 = t1.transform.getOrigin();
tf2::Quaternion q1 = t1.transform.getRotation();
double var1 = t1.variance;
tf2::Vector3 o2 = t2.transform.getOrigin();
tf2::Quaternion q2 = t2.transform.getRotation();
double var2 = t2.variance;
out.transform.setOrigin((var1 * o2 + var2 * o1) / (var1 + var2));
out.transform.setRotation(q1.slerp(q2, var1 / (var1 + var2)).normalized());
out.variance = updateVarianceAlexey(var1, var2);
return out;
}
// Constructor for observation
Observation::Observation(int fid, const tf2::Stamped<TransformWithVariance>& camFid,
double ierr, double oerr) {
this->fid = fid;
this->imageError = ierr;
this->poseError = 0.0;
tf2_ros::TransformBroadcaster broadcaster;
geometry_msgs::TransformStamped ts = toMsg(camFid);
ts.child_frame_id = "map0fid" + to_string(fid);
broadcaster.sendTransform(ts);
T_camFid = camFid;
T_fidCam = T_camFid;
T_fidCam.transform = T_camFid.transform.inverse();
}
// Update a fiducial position in map with a new estimate
void Fiducial::update(const tf2::Stamped<TransformWithVariance>& newPose) {
pose.update(newPose);
numObs++;
}
// Create a fiducial from an estimate of its position in the map
Fiducial::Fiducial(int id, const tf2::Stamped<TransformWithVariance>& pose) {
this->id = id;
this->pose = pose;
this->lastPublished = ros::Time(0);
this->numObs = 0;
this->visible = false;
}
// Constructor for map
Map::Map(ros::NodeHandle &nh) : tfBuffer(ros::Duration(30.0)){
frameNum = 0;
initialFrameNum = 0;
originFid = -1;
isInitializingMap = false;
havePose = false;
listener = make_unique<tf2_ros::TransformListener>(tfBuffer);
posePub = ros::Publisher(
nh.advertise<geometry_msgs::PoseWithCovarianceStamped>("/fiducial_pose", 1));
markerPub = ros::Publisher(
nh.advertise<visualization_msgs::Marker>("/fiducials", 100));
mapPub = ros::Publisher(
nh.advertise<fiducial_msgs::FiducialMapEntryArray>("/fiducial_map",
1));
clearSrv = nh.advertiseService("clear_map", &Map::clearCallback, this);
nh.param<std::string>("map_frame", mapFrame, "map");
nh.param<std::string>("odom_frame", odomFrame, "odom");
nh.param<std::string>("base_frame", baseFrame, "base_link");
nh.param<float>("tf_publish_interval", tfPublishInterval, 1.0);
nh.param<double>("future_date_transforms", future_date_transforms, 0.1);
nh.param<bool>("publish_6dof_pose", publish_6dof_pose, false);
// threshold of object error for using multi-fidicial pose
// set -ve to never use
nh.param<double>("multi_error_theshold", multiErrorThreshold, 0.1);
nh.param<std::string>("map_file", mapFilename,
string(getenv("HOME")) + "/.ros/slam/map.txt");
boost::filesystem::path mapPath(mapFilename);
boost::filesystem::path dir = mapPath.parent_path();
boost::filesystem::create_directories(dir);
std::string initialMap;
nh.param<std::string>("initial_map_file", initialMap, "");
if (!initialMap.empty()) {
loadMap(initialMap);
}
else {
loadMap();
}
publishMarkers();
}
// Update map with a set of observations
void Map::update(vector<Observation>& obs, const ros::Time &time)
{
ROS_INFO("Updating map with %d observations. Map has %d fiducials",
(int)obs.size(), (int)fiducials.size());
frameNum++;
if (obs.size() > 0 && fiducials.size() == 0) {
isInitializingMap = true;
}
if (isInitializingMap) {
autoInit(obs, time);
}
else {
tf2::Stamped<TransformWithVariance> T_mapCam;
T_mapCam.frame_id_ = mapFrame;
if (updatePose(obs, time, T_mapCam) > 0 && obs.size() > 1) {
updateMap(obs, time, T_mapCam);
}
}
publishMap();
}
// update estimates of observed fiducials from previously estimated
// camera pose
void Map::updateMap(const vector<Observation>& obs, const ros::Time &time,
const tf2::Stamped<TransformWithVariance>& T_mapCam)
{
map<int, Fiducial>::iterator fit;
for (fit = fiducials.begin(); fit != fiducials.end(); fit++) {
Fiducial &f = fit->second;
f.visible = false;
}
for (int i=0; i<obs.size(); i++) {
const Observation &o = obs[i];
if (o.fid == 0) {
continue;
}
// This should take into account the variances from both
tf2::Stamped<TransformWithVariance> T_mapFid = T_mapCam * o.T_camFid;
T_mapFid.frame_id_ = mapFrame;
// New scope for logging vars
{
tf2::Vector3 trans = T_mapFid.transform.getOrigin();
ROS_INFO("Estimate of %d %lf %lf %lf err %lf %lf var %lf",
o.fid, trans.x(), trans.y(), trans.z(),
o.T_camFid.variance, o.poseError, T_mapFid.variance);
if (std::isnan(trans.x()) ||
std::isnan(trans.y()) ||
std::isnan(trans.z())) {
ROS_WARN("Skipping NAN estimate\n");
continue;
};
}
if (fiducials.find(o.fid) == fiducials.end()) {
ROS_INFO("New fiducial %d", o.fid);
fiducials[o.fid] = Fiducial(o.fid, T_mapFid);
}
Fiducial &f = fiducials[o.fid];
f.visible = true;
if (f.pose.variance != 0) {
f.update(T_mapFid);
f.numObs++;
}
for (int j=0; j<obs.size(); j++) {
int fid = obs[j].fid;
if (f.id != fid) {
f.links[fid] = 1;
}
}
publishMarker(fiducials[o.fid]);
}
}
// lookup specified transform
bool Map::lookupTransform(const std::string &from, const std::string &to,
const ros::Time &time, tf2::Transform &T) const
{
geometry_msgs::TransformStamped transform;
try {
transform = tfBuffer.lookupTransform(from, to, time);
tf2::fromMsg(transform.transform, T);
return true;
}
catch (tf2::TransformException &ex) {
ROS_WARN("%s",ex.what());
return false;
}
}
// update pose estimate of robot
int Map::updatePose(vector<Observation>& obs, const ros::Time &time,
tf2::Stamped<TransformWithVariance>& T_mapCam)
{
int numEsts = 0;
tf2::Stamped<TransformWithVariance> T_fid0Cam;
bool useMulti = false;
for (int i=0; i<obs.size(); i++) {
Observation &o = obs[i];
if (o.fid == 0) {
// virtual fiducial 0 is at the origin
T_fid0Cam = o.T_fidCam;
tf2::Vector3 t = T_fid0Cam.transform.getOrigin();
double r, p, y;
T_fid0Cam.transform.getBasis().getRPY(r, p, y);
ROS_INFO("Pose MUL %lf %lf %lf %lf %lf %lf %lf",
t.x(), t.y(), t.z(), r, p, y, T_fid0Cam.variance);
if (T_fid0Cam.variance < multiErrorThreshold) {
useMulti = true;
}
}
else if (fiducials.find(o.fid) != fiducials.end()) {
const Fiducial &fid = fiducials[o.fid];
tf2::Stamped<TransformWithVariance> p = fid.pose * o.T_fidCam;
p.frame_id_ = mapFrame;
p.stamp_ = o.T_fidCam.stamp_;
o.position = p.transform.getOrigin();
double roll, pitch, yaw;
p.transform.getBasis().getRPY(roll, pitch, yaw);
/*
we print out all 6DOF of the camera pose in the world
frame as estimated from a single fiducial here.
This is also the transform from base_link to camera
that would cause base_link to be at the origin of the
map frame. This can be used to determine the pose of
the camera on the robot if a fiducial is correctly setup
in the map file
*/
ROS_INFO("Pose %d %lf %lf %lf %lf %lf %lf %lf", o.fid,
o.position.x(), o.position.y(), o.position.z(),
roll, pitch, yaw, p.variance);
//drawLine(fid.pose.getOrigin(), o.position);
if (std::isnan(o.position.x()) ||
std::isnan(o.position.y()) ||
std::isnan(o.position.z())) {
ROS_WARN("Skipping NAN estimate\n");
continue;
};
if (numEsts == 0) {
T_mapCam = p;
}
else {
T_mapCam.setData(averageTransforms(T_mapCam, p));
T_mapCam.stamp_ = p.stamp_;
}
numEsts++;
}
}
if (numEsts == 0) {
ROS_INFO("Finished frame - no estimates\n");
return numEsts;
}
// New scope for logging vars
{
tf2::Vector3 trans = T_mapCam.transform.getOrigin();
double r, p, y;
T_mapCam.transform.getBasis().getRPY(r, p, y);
ROS_INFO("Pose ALL %lf %lf %lf %lf %lf %lf %f",
trans.x(), trans.y(), trans.z(), r, p, y, T_mapCam.variance);
}
if (useMulti) {
T_mapCam = T_fid0Cam;
}
// Determine transform from camera to robot
tf2::Transform T_camBase;
// Use robotPose instead of camera pose to hold map to robot
tf2::Stamped<TransformWithVariance> basePose = T_mapCam;
if (lookupTransform(obs[0].T_camFid.frame_id_, baseFrame, time, T_camBase)) {
basePose.setData(T_mapCam * T_camBase);
//basePose.setData(cameraTransform * cameraPose);
// New scope for logging vars
{
tf2::Vector3 c = T_mapCam.transform.getOrigin();
ROS_INFO("camera %lf %lf %lf %f",
c.x(), c.y(), c.z(), T_mapCam.variance);
tf2::Vector3 trans = basePose.transform.getOrigin();
ROS_INFO("Pose b_l %lf %lf %lf %f",
trans.x(), trans.y(), trans.z(), basePose.variance);
}
}
basePose.frame_id_ = mapFrame;
posePub.publish(toPose(basePose));
tf2::Stamped<TransformWithVariance> outPose = basePose;
outPose.frame_id_ = mapFrame;
string outFrame=baseFrame;
if (!odomFrame.empty()) {
outFrame=odomFrame;
tf2::Transform odomTransform;
if (lookupTransform(odomFrame, baseFrame, outPose.stamp_, odomTransform)) {
outPose.setData(basePose * odomTransform.inverse());
outFrame = odomFrame;
tf2::Vector3 c = odomTransform.getOrigin();
ROS_INFO("odom %lf %lf %lf",
c.x(), c.y(), c.z());
}
}
// Make outgoing transform make sense - ie only consist of x, y, yaw
// This can be disabled via the publish_6dof_pose param, mainly for debugging
if (!publish_6dof_pose) {
tf2::Vector3 translation = outPose.transform.getOrigin();
translation.setZ(0);
outPose.transform.setOrigin(translation);
double roll, pitch, yaw;
outPose.transform.getBasis().getRPY(roll, pitch, yaw);
outPose.transform.getBasis().setRPY(0, 0, yaw);
}
poseTf = toMsg(outPose);
poseTf.child_frame_id = outFrame;
havePose = true;
publishTf();
ROS_INFO("Finished frame\n");
return numEsts;
}
// Publish map -> odom tf
void Map::publishTf()
{
tfPublishTime = ros::Time::now();
poseTf.header.stamp = tfPublishTime + ros::Duration(future_date_transforms);
broadcaster.sendTransform(poseTf);
}
// publish latest tf if enough time has elapsed
void Map::update()
{
ros::Time now = ros::Time::now();
if (havePose && tfPublishInterval != 0.0 &&
(now - tfPublishTime).toSec() > tfPublishInterval) {
publishTf();
tfPublishTime = now;
}
publishMarkers();
}
// Find closest fiducial to camera
static int findClosestObs(const vector<Observation>& obs)
{
double smallestDist = -1;
int closestIdx = -1;
for (int i=0; i<obs.size(); i++) {
const Observation &o = obs[0];
double d = o.T_camFid.transform.getOrigin().length2();
if (smallestDist < 0 || d < smallestDist) {
smallestDist = d;
closestIdx = i;
}
}
return closestIdx;
}
// Initialize a map from the closest observed fiducial
// Figure out the closest marker, and then figure out the
// pose of that marker such that base_link is at the origin of the
// map frame
void Map::autoInit(const vector<Observation>& obs, const ros::Time &time) {
ROS_INFO("Auto init map %d", frameNum);
tf2::Transform T_baseCam;
if (fiducials.size() == 0) {
int idx = findClosestObs(obs);
if (idx == -1) {
ROS_WARN("Could not find a fiducial to initialize map from");
}
const Observation &o = obs[idx];
originFid = o.fid;
ROS_INFO("Initializing map from fiducial %d", o.fid);
tf2::Stamped<TransformWithVariance> T = o.T_camFid;
if (lookupTransform(baseFrame, o.T_camFid.frame_id_,
o.T_camFid.stamp_, T_baseCam)) {
T.setData(T_baseCam * T);
}
fiducials[o.fid] = Fiducial(o.fid, T);
}
else {
for (int i=0; i<obs.size(); i++) {
const Observation &o = obs[0];
if (o.fid == originFid) {
tf2::Stamped<TransformWithVariance> T = o.T_camFid;
tf2::Vector3 trans = T.transform.getOrigin();
ROS_INFO("Estimate of %d from base %lf %lf %lf err %lf",
o.fid, trans.x(), trans.y(), trans.z(), o.T_camFid.variance);
if (lookupTransform(baseFrame, o.T_camFid.frame_id_,
o.T_camFid.stamp_, T_baseCam)) {
T.setData(T_baseCam * T);
}
fiducials[originFid].update(T);
break;
}
}
}
if (frameNum - initialFrameNum > 10 && originFid != -1) {
isInitializingMap = false;
fiducials[originFid].pose.variance = 0.0;
}
}
// save map to file
bool Map::saveMap() {
return saveMap(mapFilename);
}
bool Map::saveMap(std::string filename)
{
ROS_INFO("Saving map with %d fiducials to file %s\n",
(int)fiducials.size(), filename.c_str());
FILE *fp = fopen(filename.c_str(), "w");
if (fp == NULL) {
ROS_WARN("Could not open %s for write\n", filename.c_str());
return false;
}
map<int, Fiducial>::iterator it;
map<int, int>::iterator lit;
for (it = fiducials.begin(); it != fiducials.end(); it++) {
Fiducial &f = it->second;
tf2::Vector3 trans = f.pose.transform.getOrigin();
double rx, ry, rz;
f.pose.transform.getBasis().getRPY(rx, ry, rz);
fprintf(fp, "%d %lf %lf %lf %lf %lf %lf %lf %d", f.id,
trans.x(), trans.y(), trans.z(),
rad2deg(rx), rad2deg(ry), rad2deg(rz),
f.pose.variance, f.numObs);
for (lit = f.links.begin(); lit != f.links.end(); lit++) {
fprintf(fp, " %d", lit->first);
}
fprintf(fp, "\n");
}
fclose(fp);
return true;
}
// Load map from file
bool Map::loadMap() {
return loadMap(mapFilename);
}
bool Map::loadMap(std::string filename)
{
int numRead = 0;
ROS_INFO("Load map %s", filename.c_str());
FILE *fp = fopen(filename.c_str(), "r");
if (fp == NULL) {
ROS_WARN("Could not open %s for read\n", filename.c_str());
return false;
}
const int BUFSIZE = 2048;
char linebuf[BUFSIZE];
char linkbuf[BUFSIZE];
while (!feof(fp)) {
if (fgets(linebuf, BUFSIZE - 1, fp) == NULL)
break;
int id;
double tx, ty, tz, rx, ry, rz, var;
int numObs = 0;
linkbuf[0] = '\0';
int nElems = sscanf(linebuf, "%d %lf %lf %lf %lf %lf %lf %lf %d%[^\t\n]*s",
&id, &tx, &ty, &tz, &rx, &ry, &rz, &var, &numObs, linkbuf);
if (nElems == 9 || nElems == 10) {
tf2::Vector3 tvec(tx, ty, tz);
tf2::Quaternion q;
q.setRPY(deg2rad(rx), deg2rad(ry), deg2rad(rz));
auto twv = TransformWithVariance(tvec, q, var);
// TODO: figure out what the timestamp in Fiducial should be
Fiducial f = Fiducial(id, tf2::Stamped<TransformWithVariance>(twv, ros::Time::now(), mapFrame));
f.numObs = numObs;
istringstream ss(linkbuf);
string s;
while (getline(ss, s, ' ')) {
if (!s.empty()) {
f.links[stoi(s)] = 1;
}
}
fiducials[id] = f;
numRead++;
}
else {
ROS_WARN("Invalid line: %s", linebuf);
}
}
fclose(fp);
ROS_INFO("Load map %s read %d entries", filename.c_str(), numRead);
return true;
}
// Publish the map
void Map::publishMap()
{
fiducial_msgs::FiducialMapEntryArray fmea;
map<int, Fiducial>::iterator it;
for (it = fiducials.begin(); it != fiducials.end(); it++) {
const Fiducial &f = it->second;
if (f.id == 0) {
continue;
}
fiducial_msgs::FiducialMapEntry fme;
fme.fiducial_id = f.id;
tf2::Vector3 t = f.pose.transform.getOrigin();
fme.x = t.x();
fme.y = t.y();
fme.z = t.z();
double rx, ry, rz;
f.pose.transform.getBasis().getRPY(rx, ry, rz);
fme.rx = rx;
fme.ry = ry;
fme.rz = rz;
fmea.fiducials.push_back(fme);
}
mapPub.publish(fmea);
}
// Publish the next marker visualization messages that hasn't been
// published recently
void Map::publishMarkers()
{
ros::Time now = ros::Time::now();
map<int, Fiducial>::iterator it;
for (it = fiducials.begin(); it != fiducials.end(); it++) {
Fiducial &f = it->second;
if ((now - f.lastPublished).toSec() > 1.0) {
publishMarker(f);
}
}
}
// Publish visualization messages for a single fiducial
void Map::publishMarker(Fiducial &fid)
{
fid.lastPublished = ros::Time::now();
// Flattened cube
visualization_msgs::Marker marker;
marker.type = visualization_msgs::Marker::CUBE;
marker.action = visualization_msgs::Marker::ADD;
toMsg(fid.pose.transform, marker.pose);
marker.scale.x = 0.15;
marker.scale.y = 0.15;
marker.scale.z = 0.01;
if (fid.visible) {
marker.color.r = 1.0f;
marker.color.g = 0.0f;
marker.color.b = 0.0f;
marker.color.a = 1.0f;
}
else {
marker.color.r = 0.0f;
marker.color.g = 1.0f;
marker.color.b = 0.0f;
marker.color.a = 1.0f;
}
marker.id = fid.id;
marker.ns = "fiducial";
marker.header.frame_id = "/map";
markerPub.publish(marker);
// cylinder scaled by stddev
visualization_msgs::Marker cylinder;
cylinder.type = visualization_msgs::Marker::CYLINDER;
cylinder.action = visualization_msgs::Marker::ADD;
cylinder.header.frame_id = "/map";
cylinder.color.r = 0.0f;
cylinder.color.g = 0.0f;
cylinder.color.b = 1.0f;
cylinder.color.a = 0.5f;
cylinder.id = fid.id; + 10000;
cylinder.ns = "sigma";
cylinder.scale.x = cylinder.scale.y = std::max(sqrt(fid.pose.variance), 0.1);
cylinder.scale.z = 0.01;
cylinder.pose.position.x = marker.pose.position.x;
cylinder.pose.position.y = marker.pose.position.y;
cylinder.pose.position.z = marker.pose.position.z;
cylinder.pose.position.z += (marker.scale.z/2.0) + 0.05;
markerPub.publish(cylinder);
// Text
visualization_msgs::Marker text;
text.type = visualization_msgs::Marker::TEXT_VIEW_FACING;
text.action = visualization_msgs::Marker::ADD;
text.header.frame_id = "/map";
text.color.r = text.color.g = text.color.b = text.color.a = 1.0f;
text.id = fid.id;
text.scale.x = text.scale.y = text.scale.z = 0.1;
text.pose.position.x = marker.pose.position.x;
text.pose.position.y = marker.pose.position.y;
text.pose.position.z = marker.pose.position.z;
text.pose.position.z += (marker.scale.z/2.0) + 0.1;
text.id = fid.id + 30000;
text.ns = "text";
text.text = std::to_string(fid.id);
markerPub.publish(text);
// Links
visualization_msgs::Marker links;
links.type = visualization_msgs::Marker::LINE_LIST;
links.action = visualization_msgs::Marker::ADD;
links.header.frame_id = "/map";
links.color.r = 0.0f;
links.color.g = 0.0f;
links.color.b = 1.0f;
links.color.a = 1.0f;
links.id = fid.id + 40000;
links.ns = "links";
links.scale.x = links.scale.y = links.scale.z = 0.02;
links.pose.position.x = 0;
links.pose.position.y = 0;
links.pose.position.z = 0;
geometry_msgs::Point gp0, gp1;
tf2::Vector3 p0 = fid.pose.transform.getOrigin();
gp0.x = p0.x();
gp0.y = p0.y();
gp0.z = p0.z();
map<int, int>::iterator lit;
for (lit = fid.links.begin(); lit != fid.links.end(); lit++) {
int ofid = lit->first;
// only draw links in one direction
if (fid.id < ofid) {
if (fiducials.find(ofid) != fiducials.end()) {
tf2::Vector3 p1 = fiducials[ofid].pose.transform.getOrigin();
gp1.x = p1.x();
gp1.y = p1.y();
gp1.z = p1.z();
links.points.push_back(gp0);
links.points.push_back(gp1);
}
}
}
markerPub.publish(links);
}
// Publish a line marker between two points
void Map::drawLine(const tf2::Vector3 &p0, const tf2::Vector3 &p1)
{
static int lid = 60000;
visualization_msgs::Marker line;
line.type = visualization_msgs::Marker::LINE_LIST;
line.action = visualization_msgs::Marker::ADD;
line.header.frame_id = "/map";
line.color.r = 1.0f;
line.color.g = 0.0f;
line.color.b = 0.0f;
line.color.a = 1.0f;
line.id = lid++;
line.ns = "lines";
line.scale.x = line.scale.y = line.scale.z = 0.01;
line.pose.position.x = 0;
line.pose.position.y = 0;
geometry_msgs::Point gp0, gp1;
gp0.x = p0.x();
gp0.y = p0.y();
gp0.z = p0.z();
gp1.x = p1.x();
gp1.y = p1.y();
gp1.z = p1.z();
line.points.push_back(gp0);
line.points.push_back(gp1);
markerPub.publish(line);
}
// Service to clear the map and enable auto initialization
bool Map::clearCallback(std_srvs::Empty::Request &req,
std_srvs::Empty::Response &res)
{
ROS_INFO("Clearing fiducial map from service call");
fiducials.clear();
initialFrameNum = frameNum;
originFid = -1;
return true;
}
| [
"simmons.gabe@gmail.com"
] | simmons.gabe@gmail.com |
6453d184848165ca2b37836502ff1a7fb051d613 | 343991667d37fba873674d8dc157f59f108c4370 | /bin/mac64.build/cpp/include/phoenix/Vector.h | 5c10496cc2ca56d44c085066accf1e0c25205d79 | [] | no_license | PlumpMath/StarSlam | 7718152d348de29dc68c759a81fa9cfefe9647b9 | 4a05d1575a763ffab76db259050bfe3b9a16a910 | refs/heads/master | 2021-01-18T20:24:31.646389 | 2015-09-20T20:11:56 | 2015-09-20T20:11:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,008 | h | #ifndef INCLUDED_phoenix_Vector
#define INCLUDED_phoenix_Vector
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
HX_DECLARE_CLASS1(phoenix,Matrix)
HX_DECLARE_CLASS1(phoenix,Quaternion)
HX_DECLARE_CLASS1(phoenix,Vector)
namespace phoenix{
class HXCPP_CLASS_ATTRIBUTES Vector_obj : public hx::Object{
public:
typedef hx::Object super;
typedef Vector_obj OBJ_;
Vector_obj();
Void __construct(hx::Null< Float > __o__x,hx::Null< Float > __o__y,hx::Null< Float > __o__z,hx::Null< Float > __o__w);
public:
inline void *operator new( size_t inSize, bool inContainer=true,const char *inName="phoenix.Vector")
{ return hx::Object::operator new(inSize,inContainer,inName); }
static hx::ObjectPtr< Vector_obj > __new(hx::Null< Float > __o__x,hx::Null< Float > __o__y,hx::Null< Float > __o__z,hx::Null< Float > __o__w);
static Dynamic __CreateEmpty();
static Dynamic __Create(hx::DynamicArray inArgs);
//~Vector_obj();
HX_DO_RTTI_ALL;
Dynamic __Field(const ::String &inString, hx::PropertyAccess inCallProp);
static bool __GetStatic(const ::String &inString, Dynamic &outValue, hx::PropertyAccess inCallProp);
Dynamic __SetField(const ::String &inString,const Dynamic &inValue, hx::PropertyAccess inCallProp);
static bool __SetStatic(const ::String &inString, Dynamic &ioValue, hx::PropertyAccess inCallProp);
void __GetFields(Array< ::String> &outFields);
static void __register();
void __Mark(HX_MARK_PARAMS);
void __Visit(HX_VISIT_PARAMS);
::String __ToString() const { return HX_HCSTRING("Vector","\xe3","\x24","\xf2","\xcb"); }
Float x;
Float y;
Float z;
Float w;
Float length;
Float lengthsq;
Float angle2D;
::phoenix::Vector normalized;
::phoenix::Vector inverted;
bool ignore_listeners;
Dynamic listen_x;
Dynamic &listen_x_dyn() { return listen_x;}
Dynamic listen_y;
Dynamic &listen_y_dyn() { return listen_y;}
Dynamic listen_z;
Dynamic &listen_z_dyn() { return listen_z;}
bool _construct;
virtual ::phoenix::Vector copy_from( ::phoenix::Vector _other);
Dynamic copy_from_dyn();
virtual ::phoenix::Vector set( Float _x,Float _y,Float _z,Float _w);
Dynamic set_dyn();
virtual ::phoenix::Vector set_xy( Float _x,Float _y);
Dynamic set_xy_dyn();
virtual ::phoenix::Vector set_xyz( Float _x,Float _y,Float _z);
Dynamic set_xyz_dyn();
virtual ::phoenix::Vector lerp_xy( Float _dest_x,Float _dest_y,Float _t);
Dynamic lerp_xy_dyn();
virtual ::phoenix::Vector lerp_xyz( Float _dest_x,Float _dest_y,Float _dest_z,Float _t);
Dynamic lerp_xyz_dyn();
virtual ::phoenix::Vector lerp( ::phoenix::Vector _other,Float _t);
Dynamic lerp_dyn();
virtual ::phoenix::Vector weighted_average_xy( Float _dest_x,Float _dest_y,Float _slowness);
Dynamic weighted_average_xy_dyn();
virtual ::phoenix::Vector weighted_average_xyz( Float _dest_x,Float _dest_y,Float _dest_z,Float _slowness);
Dynamic weighted_average_xyz_dyn();
virtual ::phoenix::Vector _int( );
Dynamic _int_dyn();
virtual ::phoenix::Vector int_x( );
Dynamic int_x_dyn();
virtual ::phoenix::Vector int_y( );
Dynamic int_y_dyn();
virtual ::phoenix::Vector int_z( );
Dynamic int_z_dyn();
virtual ::String toString( );
Dynamic toString_dyn();
virtual bool equals( ::phoenix::Vector other);
Dynamic equals_dyn();
virtual ::phoenix::Vector clone( );
Dynamic clone_dyn();
virtual ::phoenix::Vector normalize( );
Dynamic normalize_dyn();
virtual Float dot( ::phoenix::Vector other);
Dynamic dot_dyn();
virtual ::phoenix::Vector cross( ::phoenix::Vector a,::phoenix::Vector b);
Dynamic cross_dyn();
virtual ::phoenix::Vector invert( );
Dynamic invert_dyn();
virtual ::phoenix::Vector add( ::phoenix::Vector other);
Dynamic add_dyn();
virtual ::phoenix::Vector add_xyz( hx::Null< Float > _x,hx::Null< Float > _y,hx::Null< Float > _z);
Dynamic add_xyz_dyn();
virtual ::phoenix::Vector subtract( ::phoenix::Vector other);
Dynamic subtract_dyn();
virtual ::phoenix::Vector subtract_xyz( hx::Null< Float > _x,hx::Null< Float > _y,hx::Null< Float > _z);
Dynamic subtract_xyz_dyn();
virtual ::phoenix::Vector multiply( ::phoenix::Vector other);
Dynamic multiply_dyn();
virtual ::phoenix::Vector multiply_xyz( hx::Null< Float > _x,hx::Null< Float > _y,hx::Null< Float > _z);
Dynamic multiply_xyz_dyn();
virtual ::phoenix::Vector divide( ::phoenix::Vector other);
Dynamic divide_dyn();
virtual ::phoenix::Vector divide_xyz( hx::Null< Float > _x,hx::Null< Float > _y,hx::Null< Float > _z);
Dynamic divide_xyz_dyn();
virtual ::phoenix::Vector addScalar( Float v);
Dynamic addScalar_dyn();
virtual ::phoenix::Vector subtractScalar( Float v);
Dynamic subtractScalar_dyn();
virtual ::phoenix::Vector multiplyScalar( Float v);
Dynamic multiplyScalar_dyn();
virtual ::phoenix::Vector divideScalar( Float v);
Dynamic divideScalar_dyn();
virtual Float set_length( Float value);
Dynamic set_length_dyn();
virtual Float get_length( );
Dynamic get_length_dyn();
virtual Float get_lengthsq( );
Dynamic get_lengthsq_dyn();
virtual ::phoenix::Vector get_normalized( );
Dynamic get_normalized_dyn();
virtual Float set_x( Float _x);
Dynamic set_x_dyn();
virtual Float set_y( Float _y);
Dynamic set_y_dyn();
virtual Float set_z( Float _z);
Dynamic set_z_dyn();
virtual ::phoenix::Vector get_inverted( );
Dynamic get_inverted_dyn();
virtual Float set_angle2D( Float value);
Dynamic set_angle2D_dyn();
virtual Float get_angle2D( );
Dynamic get_angle2D_dyn();
virtual ::phoenix::Vector truncate( Float max);
Dynamic truncate_dyn();
virtual Float rotationTo( ::phoenix::Vector other);
Dynamic rotationTo_dyn();
virtual ::phoenix::Vector applyQuaternion( ::phoenix::Quaternion q);
Dynamic applyQuaternion_dyn();
virtual ::phoenix::Vector applyProjection( ::phoenix::Matrix m);
Dynamic applyProjection_dyn();
virtual ::phoenix::Vector transform( ::phoenix::Matrix _m);
Dynamic transform_dyn();
virtual ::phoenix::Vector transformDirection( ::phoenix::Matrix m);
Dynamic transformDirection_dyn();
virtual ::phoenix::Vector setEulerFromRotationMatrix( ::phoenix::Matrix m,hx::Null< int > order);
Dynamic setEulerFromRotationMatrix_dyn();
virtual ::phoenix::Vector setEulerFromQuaternion( ::phoenix::Quaternion q,hx::Null< int > order);
Dynamic setEulerFromQuaternion_dyn();
virtual ::phoenix::Vector degrees( );
Dynamic degrees_dyn();
virtual ::phoenix::Vector radians( );
Dynamic radians_dyn();
static ::phoenix::Vector Add( ::phoenix::Vector a,::phoenix::Vector b);
static Dynamic Add_dyn();
static ::phoenix::Vector Subtract( ::phoenix::Vector a,::phoenix::Vector b);
static Dynamic Subtract_dyn();
static ::phoenix::Vector MultiplyVector( ::phoenix::Vector a,::phoenix::Vector b);
static Dynamic MultiplyVector_dyn();
static ::phoenix::Vector DivideVector( ::phoenix::Vector a,::phoenix::Vector b);
static Dynamic DivideVector_dyn();
static ::phoenix::Vector Multiply( ::phoenix::Vector a,Float b);
static Dynamic Multiply_dyn();
static ::phoenix::Vector Divide( ::phoenix::Vector a,Float b);
static Dynamic Divide_dyn();
static ::phoenix::Vector AddScalar( ::phoenix::Vector a,Float b);
static Dynamic AddScalar_dyn();
static ::phoenix::Vector SubtractScalar( ::phoenix::Vector a,Float b);
static Dynamic SubtractScalar_dyn();
static ::phoenix::Vector Cross( ::phoenix::Vector a,::phoenix::Vector b);
static Dynamic Cross_dyn();
static Float RotationTo( ::phoenix::Vector a,::phoenix::Vector b);
static Dynamic RotationTo_dyn();
static Void Listen( ::phoenix::Vector _v,Dynamic listener);
static Dynamic Listen_dyn();
static ::phoenix::Vector Degrees( ::phoenix::Vector _radian_vector);
static Dynamic Degrees_dyn();
static ::phoenix::Vector Radians( ::phoenix::Vector _degree_vector);
static Dynamic Radians_dyn();
};
} // end namespace phoenix
#endif /* INCLUDED_phoenix_Vector */
| [
"aledoux6@gatech.edu"
] | aledoux6@gatech.edu |
9ea7235ef762d970a6e414b2fad2ea54d306070a | cbf9d42397cc2bda21d2451d576c6e0307666243 | /src/Rodin/FormLanguage/List.h | 10a9b8efd489d56185a435f25f89aa8243954feb | [
"BSL-1.0"
] | permissive | cbritopacheco/rodin | 272bd34b8d91ec825934a617d1fea751786a9632 | a64520db90ac444b7ce61ca353aa9fe85e4868d0 | refs/heads/master | 2023-08-21T20:19:35.539806 | 2023-08-14T20:36:37 | 2023-08-14T20:36:37 | 422,234,328 | 24 | 5 | BSL-1.0 | 2023-08-14T18:42:04 | 2021-10-28T14:22:55 | C++ | UTF-8 | C++ | false | false | 4,433 | h | /*
* Copyright Carlos BRITO PACHECO 2021 - 2022.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE or copy at
* https://www.boost.org/LICENSE_1_0.txt)
*/
#include <vector>
#include <memory>
#include "Base.h"
#ifndef RODIN_FORMLANGUAGE_LIST_H
#define RODIN_FORMLANGUAGE_LIST_H
namespace Rodin::FormLanguage
{
template <class T>
class List : public Base
{
static_assert(std::is_base_of_v<Base, T>);
public:
using reference = T&;
using const_reference = const T&;
class Iterator
{
using internal_iterator = typename std::vector<std::unique_ptr<T>>::iterator;
public:
explicit constexpr Iterator(internal_iterator it) : m_it(it) {}
constexpr Iterator& operator++() { m_it++; return *this; }
constexpr Iterator operator++(int) { Iterator r = *this; ++(*this); return r; }
constexpr bool operator==(const Iterator& other) const { return m_it == other.m_it; }
constexpr bool operator!=(const Iterator& other) const { return !(*this == other); }
constexpr reference operator*() const { assert(*m_it); return static_cast<reference>(**m_it); }
private:
internal_iterator m_it;
};
class ConstIterator
{
using internal_const_iterator = typename std::vector<std::unique_ptr<T>>::const_iterator;
public:
explicit constexpr ConstIterator(internal_const_iterator it) : m_it(it) {}
constexpr ConstIterator& operator++() { m_it++; return *this; }
constexpr ConstIterator operator++(int) { ConstIterator r = *this; ++(*this); return r; }
constexpr bool operator==(const ConstIterator& other) const { return m_it == other.m_it; }
constexpr bool operator!=(const ConstIterator& other) const { return !(*this == other); }
constexpr const_reference operator*() const { assert(*m_it); return static_cast<const_reference>(**m_it); }
private:
internal_const_iterator m_it;
};
constexpr List() = default;
constexpr List(const List& other)
: Base(other)
{
m_list.reserve(other.m_list.size());
for (const auto& p : other.m_list)
m_list.emplace_back(p->copy());
}
constexpr List(List&& other)
: Base(std::move(other)),
m_list(std::move(other.m_list))
{}
virtual ~List() = default;
constexpr List& operator=(const List& other)
{
if (this != &other)
{
m_list.reserve(other.m_list.size());
for (const auto& p : other.m_list)
m_list.emplace_back(p->copy());
}
return *this;
}
constexpr List& operator=(List&& other)
{
m_list = std::move(other.m_list);
return *this;
}
constexpr reference at(size_t i)
{
return *m_list.at(i);
}
constexpr const_reference at(size_t i) const
{
return *m_list.at(i);
}
constexpr List& add(const T& v)
{
m_list.emplace_back(v.copy());
return *this;
}
constexpr List& add(const FormLanguage::List<T>& other)
{
m_list.reserve(m_list.size() + other.m_list.size());
for (const auto& p : other.m_list)
m_list.emplace_back(p->copy());
return *this;
}
constexpr List& clear()
{
m_list.clear();
return *this;
}
constexpr size_t size() const
{
return m_list.size();
}
constexpr Iterator begin() noexcept
{
return Iterator(m_list.begin());
}
constexpr Iterator end() noexcept
{
return Iterator(m_list.end());
}
constexpr ConstIterator begin() const noexcept
{
return ConstIterator(m_list.begin());
}
constexpr ConstIterator end() const noexcept
{
return ConstIterator(m_list.end());
}
constexpr ConstIterator cbegin() const noexcept
{
return ConstIterator(m_list.cbegin());
}
constexpr ConstIterator cend() const noexcept
{
return ConstIterator(m_list.cend());
}
virtual List* copy() const noexcept override
{
return new List(*this);
}
private:
std::vector<std::unique_ptr<T>> m_list;
};
}
#endif
| [
"carlos.brito524@gmail.com"
] | carlos.brito524@gmail.com |
2ec06b6c28dfb43536f89298d636ea83fe8d8109 | 468d5bc5ba168a9d162dcd71209a2f76f8152578 | /rfid-app/scanner/a_transport.h | 2a4e642bd55a237d889cab20074e6bf88f172ca4 | [] | no_license | AvatarSD/rfidscanner | b4dd611e324e49982dcd5662d7b80322cac11c8d | 4a0d421330121f2ba0e108e6bc5a896d8235c413 | refs/heads/master | 2021-01-19T18:29:05.899248 | 2017-11-20T19:23:06 | 2017-11-20T19:23:06 | 101,141,710 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 654 | h | #ifndef TRANSPORT_H
#define TRANSPORT_H
#include <QTimer>
#include <QSharedPointer>
#include "events.h"
/********************** Level 1(A) ***********************/
/*************** Interface ****************/
/******** ScannerPhy *******/
class ScannerPhy : public Eventful
{
Q_OBJECT
public:
ScannerPhy(QObject*parent=nullptr) : Eventful(parent){}
virtual ~ScannerPhy(){}
signals:
void inData(QByteArray data);
void opened();
void closed();
public slots:
virtual void outData(QByteArray data)=0;
virtual int open()=0;
virtual void close()=0;
virtual bool isOpen()=0;
};
#endif // TRANSPORT_H
| [
"sd1995@ukr.net"
] | sd1995@ukr.net |
68a167c33208680f54f36200b8040c7664158cdd | 607c4f4497ac2a3b16287cd66262d3decaa30278 | /client/kui/kopengles/DataPool/Material/CPass.cpp | 839ccda40aa48579fdbec346c639c3a5673896e8 | [] | no_license | ExpLife0011/kui | 53eed82f1d762bf241f47e989050c6df5f6d9bec | 0d5f45a814429bea3463284b50f849813e97a257 | refs/heads/master | 2020-03-22T08:56:20.740779 | 2018-04-19T08:42:56 | 2018-04-19T08:42:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,621 | cpp | #include "RenderEngine.h"
namespace OpenHMI
{
CPass::CPass(CCacheMaterial* p)
: m_pProgram(NULL)
, m_pParent(p)
, m_eType(CMaterialPool::EPT_INTERNAL_UI_COMMON)
, m_pRenderDelegate(NULL)
, m_bEnableBlend(TRUE)
, m_eBlendSrcFactor(CRenderState::EBF_ONE)
, m_eBlendDstFactor(CRenderState::EBF_ONE_MINUS_SRC_ALPHA)
, m_bEnableCullFace(TRUE)
, m_eCullFace(CRenderState::ECF_CCW)
{
;
}
CPass::~CPass()
{
m_aryTexState.clear();
if( m_pRenderDelegate )
{
delete m_pRenderDelegate;
m_pRenderDelegate = NULL;
}
}
void CPass::enableBlend(BOOLEAN bEnable)
{
m_bEnableBlend = bEnable;
}
void CPass::applyBlend(CRenderState::EBlendFactor eSrcFactor, CRenderState::EBlendFactor eDstFactor)
{
m_eBlendSrcFactor = eSrcFactor;
m_eBlendDstFactor = eDstFactor;
}
void CPass::enableCullFace(BOOLEAN bEnable)
{
m_bEnableCullFace = bEnable;
}
void CPass::applyCullFace(CRenderState::ECullFace eCullFace)
{
m_eCullFace = eCullFace;
}
void CPass::addTextureState(CMaterialPool::tagTextureState& rTexState)
{
m_aryTexState.addItem(rTexState);
}
void CPass::setTextureStates(const Array2<CMaterialPool::tagTextureState>& ary)
{
m_aryTexState.clear();
for( UINT i = 0; i< ary.size(); ++i )
{
const CMaterialPool::tagTextureState& r = ary[i];
m_aryTexState.addItem(r);
}
}
void CPass::begin()
{
;
}
void CPass::end()
{
if (m_pProgram)
{
m_pProgram->end(this);
}
}
void CPass::apply(Object* p, CRenderState* pRndState)
{
if ( m_eType == CMaterialPool::EPT_INTERNAL_UI_COMMON )
{
pRndState->enableDepthTest(FALSE);
applyRenderStates(pRndState);
applyProgram(p);
}
else if ( m_eType == CMaterialPool::EPT_INTERNAL_MODEL_CUSTOM && m_pRenderDelegate )
{
//CCacheProgram* pProgram = CProgramPool::getInstance()->getProgram(m_iProgramID);
if ( m_pProgram )
{
C3DBatchRender* pRender = (C3DBatchRender*)p;
if ( pRender == NULL )
{
return ;
}
C3DBatchRenderGroup * pGroup = pRender->getParent();
CCamera* pCamera = pGroup->getCamera();
m_pProgram->begin();
m_pRenderDelegate->render(m_pProgram->getUniformLoc(), pCamera, pRender->getModelMatrix(), p, pRndState);
}
}
}
void CPass::applyRenderStates(CRenderState* pRndState)
{
if ( pRndState )
{
pRndState->enableBlend(m_bEnableBlend);
if ( m_bEnableBlend )
{
pRndState->blendFunc(m_eBlendSrcFactor, m_eBlendDstFactor);
}
pRndState->enableCullFace(m_bEnableCullFace);
if ( m_bEnableCullFace )
{
pRndState->cullFace(m_eCullFace);
}
}
}
void CPass::applyProgram(Object* p)
{
//CCacheProgram* pProgram = CProgramPool::getInstance()->getProgram(m_iProgramID);
if (m_pProgram)
{
m_pProgram->begin();
m_pProgram->setUniforms(p);
m_pProgram->setTextureUniforms(this);
}
}
void CPass::applyTextureParameters(UINT uidx, CCacheTexture* pTex)
{
if ( uidx < m_aryTexState.size() && pTex )
{
const CMaterialPool::tagTextureState& rState = m_aryTexState[uidx];
pTex->setFilter(CCacheTexture::FP_MIN_FILTER, (CCacheTexture::EFilterMode)rState.m_uiFilterMode);
pTex->setFilter(CCacheTexture::FP_MAG_FILTER, (CCacheTexture::EFilterMode)rState.m_uiFilterMode);
pTex->setWrap(CCacheTexture::WRAP_S, (CCacheTexture::EWrapMode)rState.m_uiWrapMode);
pTex->setWrap(CCacheTexture::WRAP_T, (CCacheTexture::EWrapMode)rState.m_uiWrapMode);
}
}
CCacheTexture* CPass::getTexture(UINT idx)
{
if ( idx < m_aryTexState.size() )
{
UINT uiTexIdx = m_aryTexState[idx].m_uiTexIdx;
return m_pParent->getCustomTexture(uiTexIdx);
}
return NULL;
}
} | [
"yanyan520209@126.com"
] | yanyan520209@126.com |
a6d0f5dc727b65bfe83da98af181249d4d8df3c2 | f7449a2e3f8b7c9204bf8a68a863286a3899be1c | /EncryptionPublisher.h | 070fe62a4a1d47afdebc8e069457fed0919ffaf1 | [] | no_license | Tommyisr/Apartment_CPP | 9b69ce339e80c01ca6554f7d436fca539e3d2c8a | 76457e0544e593fb1e9d3e976d581e9359e94eac | refs/heads/master | 2020-03-30T16:50:24.703617 | 2018-10-03T14:53:03 | 2018-10-03T14:53:03 | 151,429,685 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 404 | h | #ifndef MTM4_ENCRYPTIONPUBLISHER_H
#define MTM4_ENCRYPTIONPUBLISHER_H
#include "Publisher.h"
class EncryptionPublisher : public Publisher {
char key;
public:
EncryptionPublisher(int priority, BrokerIfc& broker, char key, std::ostream& messagesSink = std::cout);
virtual void sendMessage(const std::string& message, const Topic& t ) override;
};
#endif //MTM4_ENCRYPTIONPUBLISHER_H
| [
"noreply@github.com"
] | noreply@github.com |
b0442c026b632849e5e271896d822b4ec16e71c4 | 0de9688de651ee81660dee187291bd97e5da1ee2 | /tool/code/trunk/cxx/Data/Evaluation/templates/ccipdConfusionMatrix.hxx | eccd4e6ec148fedfa1aca5d8220e3706053ce226 | [] | no_license | zengruizhao/Radiomics | 2845cd7f17a46fae95be5d68b135ceda76ed4e44 | 34c1f1bff12fb994c904eaab0691f33819067003 | refs/heads/master | 2022-04-26T11:56:59.338297 | 2020-05-01T08:15:12 | 2020-05-01T08:15:12 | 257,222,358 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,679 | hxx | #ifndef __ccipdConfusionMatrix_hxx
#define __ccipdConfusionMatrix_hxx
#include "ccipdDisableWarningsMacro.h"
#include <itkImageRegionConstIterator.h>
#include <iostream>
#include "ccipdEnableWarningsMacro.h"
namespace ccipd
{
// Should be moved to types.h
struct ConfusionMatrix
{
unsigned int TP; // True Positive
unsigned int FP; // False Positives
unsigned int TN; // True Negatives
unsigned int FN; // False Negatives
ConfusionMatrix() : TP(0), FP(0), TN(0), FN(0){}
};
template <class TScalarImageType>
ConfusionMatrix
CalculateConfusionMatrix(typename TScalarImageType::Pointer pInputImage
, typename TScalarImageType::Pointer pReferenceImage
, typename TScalarImageType::PixelType NegativeValue //= 0
, typename TScalarImageType::PixelType PositiveValue //= 1
)
{
// Check that the size of the input image is the same as the size of the
if (pInputImage->GetLargestPossibleRegion().GetSize() != pReferenceImage->GetLargestPossibleRegion().GetSize())
{
std::cerr << "Error: dimension mismatch ...";
}
typedef itk::ImageRegionConstIterator<TScalarImageType> ConstIteratorType;
ConstIteratorType in(pInputImage, pInputImage->GetRequestedRegion());
ConstIteratorType ref(pReferenceImage, pInputImage->GetRequestedRegion());
ConfusionMatrix cm;
for (in.GoToBegin(), ref.GoToBegin(); !in.IsAtEnd(); ++in, ++ref)
{
if (ref.Get() == PositiveValue)
{
if (in.Get() == PositiveValue) cm.TP++;
else if (in.Get() == NegativeValue) cm.FN++;
}
else if (ref.Get() == NegativeValue)
{
if (in.Get() == NegativeValue) cm.TN++;
else if (in.Get() == PositiveValue) cm.FP++;
}
}
return cm;
}
} // namespace
#endif
| [
"zzr_nuist@163.com"
] | zzr_nuist@163.com |
49a59744b7d3ae2e066c3063a7dd3d27689fd1fe | 584d088c264ac58050ed0757b08d032b6c7fc83b | /FlashTest/zflash.cpp | 9e86c0dcbdfe9e86c466cfe968194f3141ce7a82 | [] | no_license | littlewingsoft/lunaproject | a843ca37c04bdc4e1e4e706381043def1789ab39 | 9102a39deaad74b2d73ee0ec3354f37f6f85702f | refs/heads/master | 2020-05-30T15:21:20.515967 | 2011-02-04T18:41:43 | 2011-02-04T18:41:43 | 32,302,109 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,891 | cpp | //code by zZz/KCN aka Anatoliy Samara. feb2003
#include "zflash.h"
#include "zflash_flash.h"
#include <stdio.h>
#include <atlbase.h>
CComModule _Module;
#include <atlwin.h>
#include <sstream>
void __Error(wchar_t *message,const char *file=__FILE__,int line=__LINE__)
{
std::wstringstream ss;
ss << message << " FILE:" << file << " LINE:" << line;
OutputDebugString( ss.str().c_str() );
}
CAxWindow cw;
IUnknown *unk=NULL;
IShockwaveFlash *iflash=NULL;
IViewObjectEx *viewobject;
IOleInPlaceObjectWindowless* mWndlessObject=0;
IOleClientSite* pkIOleClientSite=0;
IOleInPlaceSiteWindowless* pkIOleInPlaceSiteWindowless=0;
IOleInPlaceFrame* pkIOleInPlaceFrame=0;
IStorage* pkIStorage=0;
int bm_width=0,bm_height=0;
HDC hdcCompatible = NULL;
HBITMAP hBitmap = NULL;
void *frame_buffer;
RECTL rectl;
bool g_bLoop = false;
namespace ZFLASH{
int GetWidth()
{
return bm_width ;
}
int GetHeight()
{
return bm_height ;
}
bool Loop()
{
return g_bLoop;
}
void Loop(bool bLoop )
{
g_bLoop = bLoop;
}
int Init(int version_needed)
{
int player_ok=1;
IShockwaveFlash *try_flash;
OleInitialize(NULL);
CoCreateInstance(CLSID_ShockwaveFlash,NULL,CLSCTX_INPROC_SERVER,IID_IShockwaveFlash,(void **)&try_flash);
if (!try_flash){
player_ok=0;
wchar_t temp[1024];
wsprintf( temp, L"Flash Player v%d.%02d is not registered on this system!\nFlash Player is required to run this programm.\n\nRegister it now?",version_needed>>16,version_needed&0xffff);
int res=MessageBox(NULL,temp,L"Requirements",MB_ICONQUESTION|MB_YESNO);
if (res==IDYES)
{
HMODULE hlib=LoadLibraryW( L"swflash.ocx");
if (!hlib)
__Error( L"File swflash.ocx not found");
void (__stdcall *DllRegisterServer)(void);
DllRegisterServer=(void (__stdcall *)(void))GetProcAddress(hlib,"DllRegisterServer");
DllRegisterServer();
}
else
{
return 0;
}
}
else{
long version;
try_flash->FlashVersion(&version);
if (version<version_needed)
player_ok=0;
try_flash->Release();
}
if (!player_ok)
{
}
return 1;
}
int msgProc( unsigned int msg, unsigned int wParam, unsigned long lParam )
{
LRESULT lr;
//IOleClientSite, IOleInPlaceSiteWindowless, IOleInPlaceFrame, IStorage
if( mWndlessObject )
mWndlessObject->OnWindowMessage( msg, wParam, lParam, &lr );
return 1;
}
void ReleaseInterfaces(){
if (unk) {
unk->Release();
unk=NULL;
}
if (iflash){
iflash->Release();
iflash=NULL;
}
}
void ReleaseGDI(){
if (hBitmap){
DeleteObject(hBitmap);
}
if (hdcCompatible){
DeleteDC(hdcCompatible);
}
}
void Exit()
{
cw.DestroyWindow();
ReleaseInterfaces();
ReleaseGDI();
}
void* CreateBuffer(int width,int height)
{
ReleaseGDI();
HDC desktop_dc=GetDC(GetDesktopWindow());
hdcCompatible = CreateCompatibleDC(desktop_dc);
BITMAPINFO binfo;
memset(&binfo,0,sizeof(binfo));
binfo.bmiHeader.biSize=sizeof(binfo);
binfo.bmiHeader.biPlanes=1;
binfo.bmiHeader.biBitCount=32;
binfo.bmiHeader.biCompression=BI_RGB;
binfo.bmiHeader.biHeight=height;
binfo.bmiHeader.biWidth=width;
hBitmap=CreateDIBSection(hdcCompatible,&binfo,DIB_RGB_COLORS,&frame_buffer,NULL,0);
SelectObject(hdcCompatible, hBitmap);
bm_width=width;
bm_height=height;
RECT rc={0,0,width,height};
AdjustWindowRect(&rc, cw.GetWindowLong( GWL_STYLE ), FALSE);
cw.SetWindowPos(NULL,0,0,rc.right-rc.left,rc.bottom-rc.top,SWP_NOMOVE|SWP_NOREDRAW|SWP_DEFERERASE|
SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOOWNERZORDER|SWP_NOSENDCHANGING|
SWP_NOZORDER);
rectl.left=0;
rectl.right=bm_width;
rectl.top=0;
rectl.bottom=bm_height;
return frame_buffer;
}
DWORD* LoadMovie(const std::wstring& movie_name, int w,int h )
{
wchar_t * flash_clsid_c = L"{D27CDB6E-AE6D-11CF-96B8-444553540000}";
ReleaseInterfaces();
ReleaseGDI();
AtlAxWinInit();
if (cw.IsWindow())
cw.DestroyWindow();
RECT rc={0,0,400,400};
AdjustWindowRect(&rc,0,FALSE);
cw.Create( NULL, &rc, flash_clsid_c, 0 );
cw.QueryControl(&unk);
if (!unk)
__Error( L"NULL IUnknown");
HRESULT hr = unk->QueryInterface( IID_IShockwaveFlash, (void **)&iflash );
if (!iflash) __Error( L"Unable to query IFlash");
hr = iflash->QueryInterface(__uuidof(IOleInPlaceObjectWindowless), (void**)&mWndlessObject);
//pkIOleClientSite
//pkIOleInPlaceSiteWindowless->
//pkIOleInPlaceFrame
//pkIStorage;
LPWSTR buf =(LPWSTR) malloc( sizeof(WCHAR)*256 );
if (movie_name[0]=='.')
{
GetCurrentDirectory( 256,buf);
WCHAR last_ch= buf[wcsnlen_s(buf,256)-1];
if (last_ch!='\\'&&last_ch!= L'/'){
wcsncat_s( buf,256, L"/", 1 );
}
wcsncat_s( buf,256, movie_name.c_str(), movie_name.length() );
}
else
{
//strcpy( buf, movie_name );
wcscpy_s( buf,256,movie_name.c_str() );
}
std::wstring ttt = buf;
//LPWSTR real_name =(LPWSTR) malloc( sizeof(WCHAR)*256);//unsigned short
//MultiByteToWideChar( CP_ACP,0, buf, -1, real_name,256);
//iflash->put_Playing(FALSE);
hr = iflash->LoadMovie( 0,buf);//real_name
//iflash->put_Quality(5);
hr = iflash->QueryInterface( IID_IViewObjectEx,(void **)&viewobject);
//iflash->SetZoomRect(0,0,256,256);
free( buf );
//free( real_name );
return (DWORD*)CreateBuffer( w, h );;
}
int DrawFrame(){
static long lastframe=-1;
long frame=0;
VARIANT_BOOL bPlay = 0;
if( g_bLoop )
{
iflash->IsPlaying( &bPlay );
if( bPlay == 0 )
iflash->Play();
}
iflash->CurrentFrame(&frame);
if (frame!=lastframe){
lastframe=frame;
viewobject->Draw( DVASPECT_CONTENT, -1, NULL, NULL, NULL, hdcCompatible, &rectl, &rectl, NULL, NULL);
return 1;
}
return 0;
}
}//namespace | [
"jungmoona@2e9c511a-93cf-11dd-bb0a-adccfa6872b9"
] | jungmoona@2e9c511a-93cf-11dd-bb0a-adccfa6872b9 |
f4de0028afc525081e0ff33c99abf504ffa48ffd | a07c530c84a78534b4443e354d62e6834359e7d7 | /C++/No.51 N-Queens.cpp | f2eb7feeec54eb01b8d29a788837e831967de6d9 | [
"MIT"
] | permissive | YC-Qiu/MyLeetCodeRepo | 9a61631eaf40f6d88a79300ec6b5712b4c8717c9 | f8fd6e28572d5b7ab938bbc1239608d1ebfbb9df | refs/heads/main | 2023-02-08T01:48:38.763471 | 2020-12-28T07:48:30 | 2020-12-28T07:48:30 | 323,263,690 | 1 | 0 | MIT | 2020-12-28T07:48:32 | 2020-12-21T07:34:42 | C++ | UTF-8 | C++ | false | false | 1,543 | cpp | #include<iostream>
#include<vector>
#include<string>
using namespace std;
class Solution {
public:
int MAX_ROW;
void genPerms(vector<int> path, size_t permLength) {
if (!promising(path, permLength))
return;
if (permLength == MAX_ROW) {
// Do something with the path
ans.push_back(vector<string>());
vector<string>& strvec = ans[ans.size() - 1];
for (int x : path) {
string temp = form;
temp[x] = 'Q';
strvec.push_back(temp);
}
return;
} // if
for (size_t i = 0; i < MAX_ROW; ++i) {
path[permLength] = i;
genPerms(path, permLength + 1);
} // for
} // genPerms()
bool promising(vector<int>& path, size_t permLength) {
int last = permLength - 1;
for (int i = 0; i < last;i++) {
if (path[i] == path[last] || last - i == path[last] - path[i] || last - i == path[i] - path[last]) return false;
}
return true;
}
string form;
vector<vector<string>> ans;
vector<vector<string>> solveNQueens(int n) {
MAX_ROW = n;
form = string(MAX_ROW, '.');
vector<int> path(MAX_ROW);
genPerms(path, 0);
return ans;
}
};
//int main() {
// Solution sol;
// auto vec = sol.solveNQueens(4);
// for (auto v: vec) {
// for (auto str : v) {
// cout << str << " ";
// }
// cout << endl;
// }
// return 0;
//} | [
"ycqiu@umich.edu"
] | ycqiu@umich.edu |
181e742ddfc6936a4647620c73a9358198982c3d | 6ad7e478bfbe7529a0558b83774feb48fc9e8b5f | /355 a.cpp | 42dcba790a2799b6067502d1820cdf6730c946ef | [] | no_license | Shaykat/CodeForces | fe590460f1cff10837b74bd80cb82f8071462ca5 | fc7f62709c5d8df6689c067c4fc55a89a39e1757 | refs/heads/master | 2021-01-11T02:00:07.676993 | 2017-11-27T21:41:24 | 2017-11-27T21:41:24 | 70,825,203 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 346 | cpp | #include<bits/stdc++.h>
using namespace std;
#define s 1010
int a[s];
int main(){
int n,h,res=0;
cin >> n >> h;
for(int i = 0; i < n; i++){
cin >> a[i];
}
for(int i = 0; i < n; i++){
if(a[i] > h){
res += 2;
}
else {
res++;
}
}
cout << res << endl;
}
| [
"shaykat2057@gmail.com"
] | shaykat2057@gmail.com |
c062b6157921028baac1f3459291c8708d1a3f7a | 399b5e377fdd741fe6e7b845b70491b9ce2cccfd | /LLVM_src/libcxx/test/std/utilities/function.objects/negators/not1.depr_in_cxx17.fail.cpp | 9fbe6db66f92578470517f9367144bc5a333391d | [
"NCSA",
"LLVM-exception",
"MIT",
"Apache-2.0"
] | permissive | zslwyuan/LLVM-9-for-Light-HLS | 6ebdd03769c6b55e5eec923cb89e4a8efc7dc9ab | ec6973122a0e65d963356e0fb2bff7488150087c | refs/heads/master | 2021-06-30T20:12:46.289053 | 2020-12-07T07:52:19 | 2020-12-07T07:52:19 | 203,967,206 | 1 | 3 | null | 2019-10-29T14:45:36 | 2019-08-23T09:25:42 | C++ | UTF-8 | C++ | false | false | 876 | cpp | //===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// <functional>
// not1
// deprecated in C++17
// UNSUPPORTED: clang-4.0
// UNSUPPORTED: c++98, c++03, c++11, c++14
// REQUIRES: verify-support
// MODULES_DEFINES: _LIBCPP_ENABLE_DEPRECATION_WARNINGS
#define _LIBCPP_ENABLE_DEPRECATION_WARNINGS
#include <functional>
#include "test_macros.h"
struct Predicate {
typedef int argument_type;
bool operator()(argument_type) const { return true; }
};
int main() {
std::not1(Predicate()); // expected-error{{'not1<Predicate>' is deprecated}}
}
| [
"tliang@connect.ust.hk"
] | tliang@connect.ust.hk |
eb09c1a3f0cb99cc0f40c292cb85baa9fe228011 | 0f7a4119185aff6f48907e8a5b2666d91a47c56b | /sstd_utility/glm/gtx/gradient_paint.hpp | 778319069c81a2e2be65a3bb22ee89fa84c0c81b | [] | no_license | jixhua/QQmlQuickBook | 6636c77e9553a86f09cd59a2e89a83eaa9f153b6 | 782799ec3426291be0b0a2e37dc3e209006f0415 | refs/heads/master | 2021-09-28T13:02:48.880908 | 2018-11-17T10:43:47 | 2018-11-17T10:43:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,444 | hpp | /// @ref gtx_gradient_paint
/// @file glm/gtx/gradient_paint.hpp
///
/// @see core (dependence)
/// @see gtx_optimum_pow (dependence)
///
/// @defgroup gtx_gradient_paint GLM_GTX_gradient_paint
/// @ingroup gtx
///
/// Include <glm/gtx/gradient_paint.hpp> to use the features of this extension.
///
/// Functions that return the color of procedural gradient for specific coordinates.
#pragma once
// Dependency:
#include "../glm.hpp"
#include "../gtx/optimum_pow.hpp"
#ifndef GLM_ENABLE_EXPERIMENTAL
# error "GLM: GLM_GTX_gradient_paint is an experimental extension and may change in the future. Use #define GLM_ENABLE_EXPERIMENTAL before including it, if you really want to use it."
#endif
#if GLM_MESSAGES == GLM_ENABLE && !defined(GLM_EXT_INCLUDED)
# pragma message("GLM: GLM_GTX_gradient_paint extension included")
#endif
namespace glm
{
/// @addtogroup gtx_gradient_paint
/// @{
/// Return a color from a radial gradient.
/// @see - gtx_gradient_paint
template<typename T, qualifier Q>
GLM_FUNC_DECL T radialGradient(
vec<2, T, Q> const& Center,
T const& Radius,
vec<2, T, Q> const& Focal,
vec<2, T, Q> const& Position);
/// Return a color from a linear gradient.
/// @see - gtx_gradient_paint
template<typename T, qualifier Q>
GLM_FUNC_DECL T linearGradient(
vec<2, T, Q> const& Point0,
vec<2, T, Q> const& Point1,
vec<2, T, Q> const& Position);
/// @}
}// namespace glm
#include "gradient_paint.inl"
| [
"nanguazhude@vip.qq.com"
] | nanguazhude@vip.qq.com |
53da61fb69e0db412f0d84a535dc5bb52ba7abed | 4707400f71b9004b47380581a76b279329a160e3 | /Sprawdzarka OPTILio/optil-fabryki-99.99%.cpp | 154a51590664332a63488373007f0be7b9ba46fe | [] | no_license | swacisko/CODES | e5c73594374608ee8b3688f4e51e5ca4867d79f9 | 5e492c9711c93be493c7952bb08e30f9ad7a57b6 | refs/heads/master | 2021-01-19T00:37:03.262832 | 2017-01-09T21:00:04 | 2017-01-09T21:00:04 | 73,085,634 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,904 | cpp | #include<cstdio>
//#include<iostream>
#include<vector>
//#include<string>
//#include<map>
//#include<complex>
//#include<stack>
//#include<list>
#include<bitset>
#include<set>
//#include<iterator>
#include<cmath>
//#include<queue>
//#include<time.h>
//#include<string.h>
//#include<fstream>
//#include<sstream>
#include<algorithm>
//#include<conio.h>
using namespace std;
#define REP( x,y ) for( int x=0; x<(y); x++ )
#define FORD( x,y,z ) for( int x=y; x>=(z); x-- )
#define FOR(x,b,e) for( int x = b; x <= (e); ++x )
#define SIZE(v) (int)v.size()
#define ALL(c) c.begin(),c.end()
#define VAR(v,n) _intypeof(n) v=(n)
#define FOREACH(i,c) for( VAR(i,c.begin());i!=c.end();++i )
#define PB push_back
#define MP make_pair
#define ST first
#define ND second
#define WRITE( V ){ FOREACH(it,V) cout << *it << ", "; cout << endl; }
#define WRITE_ALL(V) { REP( i,SIZE(V) ){ cout << i << " ---- "; FOREACH(it,V[i]) cout << *it << ", "; cout << endl; } }
#define WRP(p) p.ST << " " << p.ND
#define CLEAR( dst,quant ) memset( dst,0, (quant)*sizeof( _intypeof(*dst) ) );
#define WAR if( show_help )
//#define ENDL(x) REP(crow,(x)) cout << endl;
const int MILJON = 1000000;
const bool show_help = 1;
long long INF = 1000000001;
//int N,M,K,a,b,c,y,t,w,l_zest;
const long double EPS = 1e-11;
typedef vector<double> VD;
typedef vector< VD > VVD;
typedef pair<double,int> PDI;
typedef pair<double, double> PDD;
typedef vector<bool> VB;
typedef vector< VB > VVB;
typedef long long LL;
typedef vector<int> VI;
typedef vector< VI > VVI;
typedef pair<int,int> PII;
typedef pair<LL,LL> PLL;
typedef vector<LL> VLL;
typedef vector<VLL> VVLL;
typedef vector<PII> VPII;
typedef vector<char> VC;
typedef vector< VC > VVC;
VVI SUMY;
int getsumy( int w, int h1, int h2 ){
if( h1 < 0 ) h1 = 0;
if( h2 >= SIZE(SUMY) ) h2 = SIZE(SUMY)-1;
int res = SUMY[h2][w];
if( h1 > 0 ) res -= SUMY[h1-1][w];
return res;
}
class CTree{
public:
#define NR ((p1+k1)>>1)
// typedef int int; // to co ma byc przechowywane w wezlach
int N; // ilosc liczb, na ktorych chcemy operowac, tzn jesli chcemy operowac na 5 liczbach, to potrzebujemy stworzyc tablice rozmiarow 2 * 8
int s; // jest to liczba bedaca najmniejsza potega dwojki, nie mniejsza niz N, UWAGA - liczba L do ktorej chcemy sie odniesc jest w tablicy tab na miejscu s + L
int* sum; // tablica sumy elementow w danym przedziale - w zasadzie to reprezentuje tylko liczby, ktore wstawiamuy do drzewa, zadnych sum nie przechowuje w wezlach, bo sie nie da :)
int* el; // tabllica reprezentujaca ilosc przedzialow pokrywajacych dany wezel
int size; // rozmiar tablicy tab(i innych jesli beda)
int p,k; // liczby p oraz k oznaczaja poczatek i koniec przedzialu, ktory chcemy dodac
int l; // l oznacza ilosc 'przedzialow' jakie chcemy dodac
int ID;
// konstruktor przyjmujacy jako wartosc maksymalna liczbe, na ktorej bedziemy wykonywac operacje, tzn tab bedzie reprezentowac liczby 0,1,2,...,N-1 !!!
CTree( int aN, int id ) : N(aN), s(1), ID(id) {
while( s <= N ) s <<= 1;
size = (s << 1 );
sum = new int[size];
el = new int[size];
REP(i,size){
sum[i] = 0;
el[i] = 0;
}
}
~CTree(){
delete[] sum; sum = 0;
delete[] el; el = 0;
}
// p1 - poczatek przedzialu reprezentowanego przez wezel, k1 - koniec przedzialu repr.przez wezel, g - numer wezla
void help_Add( int p1, int k1, int g ){
if( p1 > k || k1 < p ) return; // jesli przedzialy sa rozlaczne, to nic nie robie
if( p1 >= p && k1 <= k ){ // jesli wstawiany przedzal zawiera w calosci przedzial reprezentowany przez wezel to...
sum[g] += l*getsumy( ID, max( p,p1 ), min(k,k1) );
el[g] += l;
return;
}
// w przeciwnym razie rozbijam wezel na 2 podwezly
help_Add( p1, NR, (g<<1) );
help_Add( NR + 1, k1, (g<<1)+1 );
// int overlap = min( k,k1 ) - max( p,p1 ) + 1;
sum[g] = sum[(g<<1)] + sum[(g<<1)+1] + el[g]* getsumy( ID, max(p,p1), min(k,k1) ) ;
}
// funkcja dodaje l1 przedzialow p1, p1+1, ..., k1
void Add( int p1, int k1, int l1=1 ){
// printf("Wchodze do Add\n");
p = p1; k = k1; l = l1;
help_Add( 0,s-1,1 );
// printf("Wychodze z Add\n");
}
// p1 - poczatek przedzialu reprezentowanego przez wezel, k1 - koniec przedzialu repr.przez wezel, g - numer wezla
int help_sum( int p1, int k1, int g ){
if( p1 > k || k1 < p ) return 0; // jesli przedzialy sa rozlaczne, to nic nie robie
if( p1 >= p && k1 <= k ) return sum[g]; // jesli wstawiany przedzal zawiera w calosci przedzial reprezentowany przez wezel to zwracam wartosc sum danego wezla
// poniewaz wartosc sum jest aktualizowana w help_Add, wiec teraz nie musze dodawac iloscynu dlugosci przedzialu z el[g]
//int overlap = min( k,k1 ) - max( p,p1 ) + 1;
return ( help_sum( p1,NR, (g<<1) ) + help_sum( NR + 1, k1, (g<<1)+1 ) + el[g]*getsumy( ID, max(p,p1), min(k,k1) ) ); // ale tutaj dodaje wartosci znalezione w podwezlach plus ilosc pokryc danego wezla
}
// funkcja zwraca sume elementow na przedziale p1-k1 wlacznie
int FindSum( int p1, int k1 ){
// printf( "Wchodze do FindSum ID = %d p1=%d k1=%d\n", ID, p1,k1 );
p = p1; k = k1;
int res = help_sum( 0,s-1,1 );
// printf("\tWychodze z FindSum ID = %d\n", ID);
return res;
}
// funkcja ustawiajaca wartosc danego elementu o indeksie ind na okreslona wartosc val
void set( int ind, int val ){
int s = FindSum( ind, ind );
Add( ind, ind, val - s );
}
// funkcja zwracajaca dana wartosc elementu o indeksie ind
int get( int ind ){
return FindSum( ind, ind );
}
/*void operator=( const CTree & oth ){
delete[]sum; sum = 0;
delete[]el; el = 0;
size = oth.size;
N = oth.N;
s = oth.s;
sum = new int[ size ];
el = new int[ size ];
REP(i,size){
sum[i] = oth.sum[i];
el[i] = oth.el[i];
}
}*/
/*void write(){
REP( i, N ){
cout << "Emelemt " << i <<"-ty: " << FindSum( i,i ) << endl;
}
ENDL(1);
}*/
};
struct Well{
public:
Well( int r, int id ){
this->r = r;
ID = id;
w = h = -1;
}
int ID;
int w,h;
int r;
};
bool sortById( const Well &v, const Well &w ){
return v.ID < w.ID;
}
bool sortBySize( const Well &v, const Well &w ){
return v.r < w.r;
}
typedef vector<Well> VW;
int R,W,H;
VW wells;
VVI mapa;
vector< CTree* > trees;
VVB was;
bool swapped;
void readData(){
int r;
scanf( "%d", &R );
wells.clear();
REP(i,R){
scanf( "%d",&r );
wells.PB( Well( r,i ) );
}
scanf( "%d %d", &W, &H );
mapa = VVI( H, VI(W) );
REP(i,H){
REP(k,W){
scanf( "%d", &mapa[i][k] );
}
}
swapped = false;
/*if( W > H ){
swapped = true;
VVI m = VVI(W,VI(H));
REP( i, W ){
REP( k,H ){
m[i][k] = mapa[k][i];
}
}
mapa = m;
swap(W,H);
}*/
was = VVB( H, VB(W,false) );
}
void createTrees(){
//printf("createTrees\n");
trees.clear();
REP(i,W){
trees.PB( new CTree(H,i) );
// printf( "Dodalem %d drzewo\n", i+1 );
}
//printf("Stworzylem drzewa\n");
REP( i, SIZE(mapa) ){
REP( k, SIZE(mapa[i]) ){
trees[k]->Add(i,i);
// printf( "%d,%d\t", mapa[i][k], trees[k]->FindSum(i,i) );
}
// printf("\n");
}
}
void createSUMY(){
SUMY = mapa;
for( int i=1; i<H; i++ ){
for(int k=0; k<W; k++){
SUMY[i][k] += SUMY[i-1][k];
// printf("%d\t", SUMY[i][k]);
}
// printf("\n");
}
}
int getSum( int w, int h, int r ){
int sum = 0;
int dh = 0;
for( int i = w-r; i<= w+r; i++ ){
//if( i < 0 || i >= W ) continue;
if( i < 0 ){ i = -1; continue; }
else if( i >= W ) break;
dh = (int) sqrt( r*r - (w-i)*(w-i) );
sum += trees[i]->FindSum( max(0,h-dh), min(H-1,h+dh) );
}
return sum;
}
void AddToTrees( int w, int h, int r ){
int dh = 0;
for( int i = w-r; i<= w+r; i++ ){
//if( i < 0 || i >= W ) continue;
if( i < 0 ){ i = -1; continue; }
else if( i >= W ) break;
dh = (int) sqrt( r*r - (w-i)*(w-i) );
trees[i]->Add( max(0,h-dh), min(H-1,h+dh) );
}
}
PII getMinPos( int r ){
PII pos;
int minval = INF;
int val;
int DISTH = 29;
int DISTW = 27;
if( W*H*R <= 2000000 ) DISTW = DISTH = 1;
// printf( "Hello1\n" );
for( int i=0; i<H; i++ ){
if( was[i][0] == true ) continue;
val = getSum( 0,i,r );
if( val < minval ){
minval = val;
pos = MP( i,0 );
}
if( was[i][W-1] == true ) continue;
val = getSum( W-1,i,r );
if( val < minval ){
minval = val;
pos = MP( i,W-1 );
}
}
// printf( "Hello2\n" );
for( int k=0; k<W; k++ ){
if( was[0][k] == true ) continue;
val = getSum( k,0,r );
if( val < minval ){
minval = val;
pos = MP( 0,k );
}
if( was[H-1][k] == true ) continue;
val = getSum( k,H-1,r );
if( val < minval ){
minval = val;
pos = MP( H-1,k );
}
}
// printf( "Hello3\n" );
if( DISTW != 1 ){
for( int i=1; i<=4; i++ ){
for( int k=1; k<=4; k++ ){
if( was[i][k] == true ) continue;
val = getSum( k,i,r );
if( val < minval ){
minval = val;
pos = MP( i,k );
}
if( was[H-i-1][k] == true ) continue;
val = getSum( k,H-i-1,r );
if( val < minval ){
minval = val;
pos = MP( H-i-1,k );
}
if( was[i][W-k-1] == true ) continue;
val = getSum( W-k-1,i,r );
if( val < minval ){
minval = val;
pos = MP( i,W-k-1 );
}
if( was[H-i-1][W-k-1] == true ) continue;
val = getSum( W-k-1,H-i-1,r );
if( val < minval ){
minval = val;
pos = MP( H-i-1,W-k-1 );
}
}
}
} // IF DISTW != 1
// printf( "Hello4\n" );
for( int i=1; i<H-1; i+= DISTH ){
for( int k=1; k<W-1; k+=DISTW ){
if( was[i][k] == true ){
//if( k >= 0 && k < W-1 ) k -= (DISTW-1);
continue;
}
val = getSum( k,i,r );
if( val < minval ){
minval = val;
pos = MP( i,k );
}
}
}
was[ pos.ST ][pos.ND] = true;
// printf( "minval = %d\n",minval );
return pos;
}
void writeMap(){
REP( i, H ){
REP(k,W){
printf( "%d\t", trees[k]->FindSum(i,i) );
}
printf("\n");
}
}
void solve(){
readData();
createSUMY();
createTrees();
// printf("Przed czymkolwiek\n");
//writeMap();
sort( ALL(wells), sortBySize );
reverse( ALL(wells) );
PII pos;
REP( r, R ){
// printf( "Studnia %d: r = %d\n", r+1, wells[r].r );
pos = getMinPos( wells[r].r );
wells[r].h = pos.ST;
wells[r].w = pos.ND;
AddToTrees( pos.ND, pos.ST,wells[r].r );
// printf("Po dodaniu pierwszej studni na pozycji w = %d h = %d\n\n", pos.ND, pos.ST );
// writeMap();
}
sort( ALL(wells), sortById );
REP( i,R ){
if( swapped == false ) printf( "%d %d\n", wells[i].h, wells[i].w );
else printf( "%d %d\n", wells[i].w, wells[i].h );
}
}
int main(){
solve();
return 0;
}
/*
3
2 4 6
10 8
0 1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 0
2 3 4 5 6 7 8 9 0 1
3 4 5 6 7 8 9 0 1 2
4 5 6 7 8 9 0 1 2 3
5 6 7 8 9 0 1 2 3 4
6 7 8 9 0 1 2 3 4 5
7 8 9 0 1 2 3 4 5 6
*/
| [
"swatsylwester@gmail.com"
] | swatsylwester@gmail.com |
92920a62278e2af4f3a09f5cbd297c11e3a7dd04 | 7f5eb1042f0a7950632d43db674b07874d012637 | /src/core/web/web_types.hpp | 2c42e4c873c57e9fd6e62d31a702cc9a4146f8f4 | [
"MIT"
] | permissive | judoassistant/judoassistant | 68ca39b67b31bf45686f507fa6564da0f5641a98 | 1440e4f02da3126e2bb8a16f40a29f4076c9a222 | refs/heads/master | 2023-08-05T04:39:57.461602 | 2022-10-20T19:16:22 | 2022-10-20T19:16:52 | 168,874,097 | 10 | 0 | MIT | 2022-10-20T17:50:07 | 2019-02-02T20:23:42 | C++ | UTF-8 | C++ | false | false | 725 | hpp | #pragma once
#include <array>
// Header declaring different types used for communication
using WebToken = std::array<uint8_t, 32>;
enum class UserRegistrationResponse {
SERVER_ERROR,
EMAIL_EXISTS,
INVALID_PASSWORD,
SUCCESSFUL,
};
enum class WebTokenRequestResponse {
SERVER_ERROR,
INCORRECT_CREDENTIALS,
SUCCESSFUL,
};
enum class WebTokenValidationResponse {
SERVER_ERROR,
EXPIRED_TOKEN,
INVALID_TOKEN,
SUCCESSFUL,
};
enum class WebNameCheckResponse {
SERVER_ERROR,
OCCUPIED_OTHER_USER,
OCCUPIED_SAME_TOURNAMENT,
OCCUPIED_OTHER_TOURNAMENT,
FREE,
};
enum class WebNameRegistrationResponse {
SERVER_ERROR,
SUCCESSFUL,
OCCUPIED_OTHER_USER,
};
| [
"svendcsvendsen@gmail.com"
] | svendcsvendsen@gmail.com |
a10020eed78892ba411586d8bc4c0492b4af100c | 759107ca8da218a7b5995292dc0136e2b6c5d815 | /App3/LightPoint.cpp | 77e4c508b887e4fd6dad1da595411a5a9739b496 | [] | no_license | Mishok43/WoodenEngine | 0529adc8509da37d410ee708b8c8c88a39d838c7 | 69c1c0177b9aa3cb94d03d47ac20da341dffd823 | refs/heads/master | 2020-03-12T06:18:50.246629 | 2018-12-05T11:14:41 | 2018-12-05T11:14:41 | 130,482,617 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 803 | cpp | #include "LightPoint.h"
namespace WoodenEngine
{
WLightPoint::WLightPoint(
XMFLOAT3 Strength,
XMFLOAT3 Position,
float FalloffStart,
float FalloffEnd):
WLight(WLight::ELightType::Point),
Strength(Strength),
FalloffStart(FalloffStart),
FalloffEnd(FalloffEnd)
{
SetPosition(Position);
}
void WLightPoint::SetStrength(XMFLOAT3 Strength)
{
this->Strength = Strength;
}
void WLightPoint::SetFalloff(float FalloffStart, float FalloffEnd)
{
this->FalloffStart = FalloffStart;
this->FalloffEnd = FalloffEnd;
}
SLightData WLightPoint::GetShaderData() const noexcept
{
SLightData LightData;
LightData.Position = GetWorldPosition();
LightData.FalloffStart = FalloffStart;
LightData.FalloffEnd = FalloffEnd;
LightData.Strength = Strength;
return LightData;
}
}
| [
"devmishok@gmail.com"
] | devmishok@gmail.com |
82eeaa39f6ca24a9edb29d6d8c9f1c6bf3d07166 | 5904174635b81ad9920ae3fcff7c2f286aa23e48 | /src/algorithm/learner.cpp | ab12579f5eda9915b16196d35dc17a57c0356707 | [
"BSD-3-Clause",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-ssleay-windows",
"LicenseRef-scancode-unknown-license-reference",
"OpenSSL",
"BSD-2-Clause"
] | permissive | artoderk/phxpaxos | ae8aa6a1510b09fc0bee3064558660f7102126cc | 94e2c6636bf7d67eee1123872e7b22a4a7a47721 | refs/heads/master | 2021-01-12T12:15:41.593336 | 2016-10-26T08:10:00 | 2016-10-26T08:10:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,249 | cpp | /*
Tencent is pleased to support the open source community by making
PhxPaxos available.
Copyright (C) 2016 THL A29 Limited, a Tencent company.
All rights reserved.
Licensed under the BSD 3-Clause License (the "License"); you may
not use this file except in compliance with the License. You may
obtain a copy of the License at
https://opensource.org/licenses/BSD-3-Clause
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.
See the AUTHORS file for names of contributors.
*/
#include "learner.h"
#include "acceptor.h"
#include "crc32.h"
#include "cp_mgr.h"
#include "sm_base.h"
namespace phxpaxos
{
LearnerState :: LearnerState(const Config * poConfig, const LogStorage * poLogStorage)
: m_oPaxosLog(poLogStorage)
{
m_poConfig = (Config *)poConfig;
Init();
}
LearnerState :: ~LearnerState()
{
}
void LearnerState :: Init()
{
m_sLearnedValue = "";
m_bIsLearned = false;
m_iNewChecksum = 0;
}
const uint32_t LearnerState :: GetNewChecksum() const
{
return m_iNewChecksum;
}
void LearnerState :: LearnValueWithoutWrite(const uint64_t llInstanceID,
const std::string & sValue, const uint32_t iNewChecksum)
{
m_sLearnedValue = sValue;
m_bIsLearned = true;
m_iNewChecksum = iNewChecksum;
}
int LearnerState :: LearnValue(const uint64_t llInstanceID, const BallotNumber & oLearnedBallot,
const std::string & sValue, const uint32_t iLastChecksum)
{
if (llInstanceID > 0 && iLastChecksum == 0)
{
m_iNewChecksum = 0;
}
else if (sValue.size() > 0)
{
m_iNewChecksum = crc32(iLastChecksum, (const uint8_t *)sValue.data(), sValue.size(), CRC32SKIP);
}
AcceptorStateData oState;
oState.set_instanceid(llInstanceID);
oState.set_acceptedvalue(sValue);
oState.set_promiseid(oLearnedBallot.m_llProposalID);
oState.set_promisenodeid(oLearnedBallot.m_llNodeID);
oState.set_acceptedid(oLearnedBallot.m_llProposalID);
oState.set_acceptednodeid(oLearnedBallot.m_llNodeID);
oState.set_checksum(m_iNewChecksum);
WriteOptions oWriteOptions;
oWriteOptions.bSync = false;
int ret = m_oPaxosLog.WriteState(oWriteOptions, m_poConfig->GetMyGroupIdx(), llInstanceID, oState);
if (ret != 0)
{
PLGErr("LogStorage.WriteLog fail, InstanceID %lu ValueLen %zu ret %d",
llInstanceID, sValue.size(), ret);
return ret;
}
LearnValueWithoutWrite(llInstanceID, sValue, m_iNewChecksum);
PLGDebug("OK, InstanceID %lu ValueLen %zu checksum %u",
llInstanceID, sValue.size(), m_iNewChecksum);
return 0;
}
const std::string & LearnerState :: GetLearnValue()
{
return m_sLearnedValue;
}
const bool LearnerState :: GetIsLearned()
{
return m_bIsLearned;
}
//////////////////////////////////////////////////////////////////////////////
Learner :: Learner(
const Config * poConfig,
const MsgTransport * poMsgTransport,
const Instance * poInstance,
const Acceptor * poAcceptor,
const LogStorage * poLogStorage,
const IOLoop * poIOLoop,
const CheckpointMgr * poCheckpointMgr,
const SMFac * poSMFac)
: Base(poConfig, poMsgTransport, poInstance), m_oLearnerState(poConfig, poLogStorage),
m_oPaxosLog(poLogStorage), m_oLearnerSender((Config *)poConfig, this, &m_oPaxosLog),
m_oCheckpointReceiver((Config *)poConfig, (LogStorage *)poLogStorage)
{
m_poAcceptor = (Acceptor *)poAcceptor;
InitForNewPaxosInstance();
m_iAskforlearn_noopTimerID = 0;
m_poIOLoop = (IOLoop *)poIOLoop;
m_poCheckpointMgr = (CheckpointMgr *)poCheckpointMgr;
m_poSMFac = (SMFac *)poSMFac;
m_poCheckpointSender = nullptr;
m_llHighestSeenInstanceID = 0;
m_iHighestSeenInstanceID_FromNodeID = nullnode;
m_bIsIMLearning = false;
m_llLastAckInstanceID = 0;
}
Learner :: ~Learner()
{
delete m_poCheckpointSender;
}
void Learner :: Init()
{
m_oLearnerSender.start();
}
const bool Learner :: IsLearned()
{
return m_oLearnerState.GetIsLearned();
}
const std::string & Learner :: GetLearnValue()
{
return m_oLearnerState.GetLearnValue();
}
void Learner :: InitForNewPaxosInstance()
{
m_oLearnerState.Init();
}
const uint32_t Learner :: GetNewChecksum() const
{
return m_oLearnerState.GetNewChecksum();
}
////////////////////////////////////////////////////////////////
void Learner :: Stop()
{
m_oLearnerSender.Stop();
if (m_poCheckpointSender != nullptr)
{
m_poCheckpointSender->Stop();
}
}
////////////////////////////////////////////////////////////////
const bool Learner :: IsIMLatest()
{
return (GetInstanceID() + 1) >= m_llHighestSeenInstanceID;
}
const uint64_t Learner :: GetSeenLatestInstanceID()
{
return m_llHighestSeenInstanceID;
}
void Learner :: SetSeenInstanceID(const uint64_t llInstanceID, const nodeid_t llFromNodeID)
{
if (llInstanceID > m_llHighestSeenInstanceID)
{
m_llHighestSeenInstanceID = llInstanceID;
m_iHighestSeenInstanceID_FromNodeID = llFromNodeID;
}
}
//////////////////////////////////////////////////////////////
void Learner :: Reset_AskforLearn_Noop(const int iTimeout)
{
if (m_iAskforlearn_noopTimerID > 0)
{
m_poIOLoop->RemoveTimer(m_iAskforlearn_noopTimerID);
}
m_poIOLoop->AddTimer(iTimeout, Timer_Learner_Askforlearn_noop, m_iAskforlearn_noopTimerID);
}
void Learner :: AskforLearn_Noop(const bool bIsStart)
{
Reset_AskforLearn_Noop();
m_bIsIMLearning = false;
m_poCheckpointMgr->ExitCheckpointMode();
AskforLearn();
if (bIsStart)
{
AskforLearn();
}
}
///////////////////////////////////////////////////////////////
void Learner :: AskforLearn()
{
BP->GetLearnerBP()->AskforLearn();
PLGHead("START");
PaxosMsg oPaxosMsg;
oPaxosMsg.set_instanceid(GetInstanceID());
oPaxosMsg.set_nodeid(m_poConfig->GetMyNodeID());
oPaxosMsg.set_msgtype(MsgType_PaxosLearner_AskforLearn);
if (m_poConfig->IsIMFollower())
{
//this is not proposal nodeid, just use this val to bring followto nodeid info.
oPaxosMsg.set_proposalnodeid(m_poConfig->GetFollowToNodeID());
}
PLGHead("END InstanceID %lu MyNodeID %lu", oPaxosMsg.instanceid(), oPaxosMsg.nodeid());
BroadcastMessage(oPaxosMsg, BroadcastMessage_Type_RunSelf_None, Message_SendType_TCP);
BroadcastMessageToTempNode(oPaxosMsg, Message_SendType_UDP);
}
void Learner :: OnAskforLearn(const PaxosMsg & oPaxosMsg)
{
BP->GetLearnerBP()->OnAskforLearn();
PLGHead("START Msg.InstanceID %lu Now.InstanceID %lu Msg.from_nodeid %lu MinChosenInstanceID %lu",
oPaxosMsg.instanceid(), GetInstanceID(), oPaxosMsg.nodeid(),
m_poCheckpointMgr->GetMinChosenInstanceID());
SetSeenInstanceID(oPaxosMsg.instanceid(), oPaxosMsg.nodeid());
if (oPaxosMsg.proposalnodeid() == m_poConfig->GetMyNodeID())
{
//Found a node follow me.
PLImp("Found a node %lu follow me.", oPaxosMsg.nodeid());
m_poConfig->AddFollowerNode(oPaxosMsg.nodeid());
}
if (oPaxosMsg.instanceid() >= GetInstanceID())
{
return;
}
if (oPaxosMsg.instanceid() >= m_poCheckpointMgr->GetMinChosenInstanceID())
{
if (!m_oLearnerSender.Prepare(oPaxosMsg.instanceid(), oPaxosMsg.nodeid()))
{
BP->GetLearnerBP()->OnAskforLearnGetLockFail();
PLGErr("LearnerSender working for others.");
if (oPaxosMsg.instanceid() == (GetInstanceID() - 1))
{
PLGImp("InstanceID only difference one, just send this value to other.");
//send one value
AcceptorStateData oState;
int ret = m_oPaxosLog.ReadState(m_poConfig->GetMyGroupIdx(), oPaxosMsg.instanceid(), oState);
if (ret == 0)
{
BallotNumber oBallot(oState.acceptedid(), oState.acceptednodeid());
SendLearnValue(oPaxosMsg.nodeid(), oPaxosMsg.instanceid(), oBallot, oState.acceptedvalue(), 0);
}
}
return;
}
}
SendNowInstanceID(oPaxosMsg.instanceid(), oPaxosMsg.nodeid());
}
void Learner :: SendNowInstanceID(const uint64_t llInstanceID, const nodeid_t iSendNodeID)
{
BP->GetLearnerBP()->SendNowInstanceID();
PaxosMsg oPaxosMsg;
oPaxosMsg.set_instanceid(llInstanceID);
oPaxosMsg.set_nodeid(m_poConfig->GetMyNodeID());
oPaxosMsg.set_msgtype(MsgType_PaxosLearner_SendNowInstanceID);
oPaxosMsg.set_nowinstanceid(GetInstanceID());
oPaxosMsg.set_minchoseninstanceid(m_poCheckpointMgr->GetMinChosenInstanceID());
if ((GetInstanceID() - llInstanceID) > 50)
{
//instanceid too close not need to send vsm/master checkpoint.
string sSystemVariablesCPBuffer;
int ret = m_poConfig->GetSystemVSM()->GetCheckpointBuffer(sSystemVariablesCPBuffer);
if (ret == 0)
{
oPaxosMsg.set_systemvariables(sSystemVariablesCPBuffer);
}
string sMasterVariablesCPBuffer;
if (m_poConfig->GetMasterSM() != nullptr)
{
int ret = m_poConfig->GetMasterSM()->GetCheckpointBuffer(sMasterVariablesCPBuffer);
if (ret == 0)
{
oPaxosMsg.set_mastervariables(sMasterVariablesCPBuffer);
}
}
}
SendMessage(iSendNodeID, oPaxosMsg);
}
void Learner :: OnSendNowInstanceID(const PaxosMsg & oPaxosMsg)
{
BP->GetLearnerBP()->OnSendNowInstanceID();
PLGHead("START Msg.InstanceID %lu Now.InstanceID %lu Msg.from_nodeid %lu Msg.MaxInstanceID %lu systemvariables_size %zu mastervariables_size %zu",
oPaxosMsg.instanceid(), GetInstanceID(), oPaxosMsg.nodeid(), oPaxosMsg.nowinstanceid(),
oPaxosMsg.systemvariables().size(), oPaxosMsg.mastervariables().size());
SetSeenInstanceID(oPaxosMsg.nowinstanceid(), oPaxosMsg.nodeid());
bool bSystemVariablesChange = false;
int ret = m_poConfig->GetSystemVSM()->UpdateByCheckpoint(oPaxosMsg.systemvariables(), bSystemVariablesChange);
if (ret == 0 && bSystemVariablesChange)
{
PLGHead("SystemVariables changed!, all thing need to reflesh, so skip this msg");
return;
}
bool bMasterVariablesChange = false;
if (m_poConfig->GetMasterSM() != nullptr)
{
ret = m_poConfig->GetMasterSM()->UpdateByCheckpoint(oPaxosMsg.mastervariables(), bMasterVariablesChange);
if (ret == 0 && bMasterVariablesChange)
{
PLGHead("MasterVariables changed!");
}
}
if (oPaxosMsg.instanceid() != GetInstanceID())
{
PLGErr("Lag msg, skip");
return;
}
if (oPaxosMsg.nowinstanceid() <= GetInstanceID())
{
PLGErr("Lag msg, skip");
return;
}
if (oPaxosMsg.minchoseninstanceid() > GetInstanceID())
{
BP->GetCheckpointBP()->NeedAskforCheckpoint();
PLGHead("my instanceid %lu small than other's minchoseninstanceid %lu, other nodeid %lu",
GetInstanceID(), oPaxosMsg.minchoseninstanceid(), oPaxosMsg.nodeid());
AskforCheckpoint(oPaxosMsg.nodeid());
}
else if (!m_bIsIMLearning)
{
ComfirmAskForLearn(oPaxosMsg.nodeid());
}
}
////////////////////////////////////////////
void Learner :: ComfirmAskForLearn(const nodeid_t iSendNodeID)
{
BP->GetLearnerBP()->ComfirmAskForLearn();
PLGHead("START");
PaxosMsg oPaxosMsg;
oPaxosMsg.set_instanceid(GetInstanceID());
oPaxosMsg.set_nodeid(m_poConfig->GetMyNodeID());
oPaxosMsg.set_msgtype(MsgType_PaxosLearner_ComfirmAskforLearn);
PLGHead("END InstanceID %lu MyNodeID %lu", GetInstanceID(), oPaxosMsg.nodeid());
SendMessage(iSendNodeID, oPaxosMsg);
m_bIsIMLearning = true;
}
void Learner :: OnComfirmAskForLearn(const PaxosMsg & oPaxosMsg)
{
BP->GetLearnerBP()->OnComfirmAskForLearn();
PLGHead("START Msg.InstanceID %lu Msg.from_nodeid %lu", oPaxosMsg.instanceid(), oPaxosMsg.nodeid());
if (!m_oLearnerSender.Comfirm(oPaxosMsg.instanceid(), oPaxosMsg.nodeid()))
{
BP->GetLearnerBP()->OnComfirmAskForLearnGetLockFail();
PLGErr("LearnerSender comfirm fail, maybe is lag msg");
return;
}
PLGImp("OK, success comfirm");
}
int Learner :: SendLearnValue(
const nodeid_t iSendNodeID,
const uint64_t llLearnInstanceID,
const BallotNumber & oLearnedBallot,
const std::string & sLearnedValue,
const uint32_t iChecksum,
const bool bNeedAck)
{
BP->GetLearnerBP()->SendLearnValue();
PaxosMsg oPaxosMsg;
oPaxosMsg.set_msgtype(MsgType_PaxosLearner_SendLearnValue);
oPaxosMsg.set_instanceid(llLearnInstanceID);
oPaxosMsg.set_nodeid(m_poConfig->GetMyNodeID());
oPaxosMsg.set_proposalnodeid(oLearnedBallot.m_llNodeID);
oPaxosMsg.set_proposalid(oLearnedBallot.m_llProposalID);
oPaxosMsg.set_value(sLearnedValue);
oPaxosMsg.set_lastchecksum(iChecksum);
if (bNeedAck)
{
oPaxosMsg.set_flag(PaxosMsgFlagType_SendLearnValue_NeedAck);
}
return SendMessage(iSendNodeID, oPaxosMsg, Message_SendType_TCP);
}
void Learner :: OnSendLearnValue(const PaxosMsg & oPaxosMsg)
{
BP->GetLearnerBP()->OnSendLearnValue();
PLGHead("START Msg.InstanceID %lu Now.InstanceID %lu Msg.ballot_proposalid %lu Msg.ballot_nodeid %lu Msg.ValueSize %zu",
oPaxosMsg.instanceid(), GetInstanceID(), oPaxosMsg.proposalid(),
oPaxosMsg.nodeid(), oPaxosMsg.value().size());
if (oPaxosMsg.instanceid() > GetInstanceID())
{
PLGDebug("[Latest Msg] i can't learn");
return;
}
if (oPaxosMsg.instanceid() < GetInstanceID())
{
PLGDebug("[Lag Msg] no need to learn");
}
else
{
//learn value
BallotNumber oBallot(oPaxosMsg.proposalid(), oPaxosMsg.proposalnodeid());
int ret = m_oLearnerState.LearnValue(oPaxosMsg.instanceid(), oBallot, oPaxosMsg.value(), GetLastChecksum());
if (ret != 0)
{
PLGErr("LearnState.LearnValue fail, ret %d", ret);
return;
}
PLGHead("END LearnValue OK, proposalid %lu proposalid_nodeid %lu valueLen %zu",
oPaxosMsg.proposalid(), oPaxosMsg.nodeid(), oPaxosMsg.value().size());
}
if (oPaxosMsg.flag() == PaxosMsgFlagType_SendLearnValue_NeedAck)
{
//every time' when receive valid need ack learn value, reset noop timeout.
Reset_AskforLearn_Noop();
SendLearnValue_Ack(oPaxosMsg.nodeid());
}
}
void Learner :: SendLearnValue_Ack(const nodeid_t iSendNodeID)
{
PLGHead("START LastAck.Instanceid %lu Now.Instanceid %lu", m_llLastAckInstanceID, GetInstanceID());
if (GetInstanceID() < m_llLastAckInstanceID + SENDLEARNVALUE_ACK_LEAD)
{
PLGImp("No need to ack");
return;
}
BP->GetLearnerBP()->SendLearnValue_Ack();
m_llLastAckInstanceID = GetInstanceID();
PaxosMsg oPaxosMsg;
oPaxosMsg.set_instanceid(GetInstanceID());
oPaxosMsg.set_msgtype(MsgType_PaxosLearner_SendLearnValue_Ack);
oPaxosMsg.set_nodeid(m_poConfig->GetMyNodeID());
SendMessage(iSendNodeID, oPaxosMsg);
PLGHead("End. ok");
}
void Learner :: OnSendLearnValue_Ack(const PaxosMsg & oPaxosMsg)
{
BP->GetLearnerBP()->OnSendLearnValue_Ack();
PLGHead("Msg.Ack.Instanceid %lu Msg.from_nodeid %lu", oPaxosMsg.instanceid(), oPaxosMsg.nodeid());
m_oLearnerSender.Ack(oPaxosMsg.instanceid(), oPaxosMsg.nodeid());
}
//////////////////////////////////////////////////////////////
void Learner :: TransmitToFollower()
{
if (m_poConfig->GetMyFollowerCount() == 0)
{
return;
}
PaxosMsg oPaxosMsg;
oPaxosMsg.set_msgtype(MsgType_PaxosLearner_SendLearnValue);
oPaxosMsg.set_instanceid(GetInstanceID());
oPaxosMsg.set_nodeid(m_poConfig->GetMyNodeID());
oPaxosMsg.set_proposalnodeid(m_poAcceptor->GetAcceptorState()->GetAcceptedBallot().m_llNodeID);
oPaxosMsg.set_proposalid(m_poAcceptor->GetAcceptorState()->GetAcceptedBallot().m_llProposalID);
oPaxosMsg.set_value(m_poAcceptor->GetAcceptorState()->GetAcceptedValue());
oPaxosMsg.set_lastchecksum(GetLastChecksum());
BroadcastMessageToFollower(oPaxosMsg, Message_SendType_TCP);
PLGHead("ok");
}
void Learner :: ProposerSendSuccess(
const uint64_t llLearnInstanceID,
const uint64_t llProposalID)
{
BP->GetLearnerBP()->ProposerSendSuccess();
PaxosMsg oPaxosMsg;
oPaxosMsg.set_msgtype(MsgType_PaxosLearner_ProposerSendSuccess);
oPaxosMsg.set_instanceid(llLearnInstanceID);
oPaxosMsg.set_nodeid(m_poConfig->GetMyNodeID());
oPaxosMsg.set_proposalid(llProposalID);
oPaxosMsg.set_lastchecksum(GetLastChecksum());
//run self first
BroadcastMessage(oPaxosMsg, BroadcastMessage_Type_RunSelf_First);
}
void Learner :: OnProposerSendSuccess(const PaxosMsg & oPaxosMsg)
{
BP->GetLearnerBP()->OnProposerSendSuccess();
PLGHead("START Msg.InstanceID %lu Now.InstanceID %lu Msg.ProposalID %lu State.AcceptedID %lu "
"State.AcceptedNodeID %lu, Msg.from_nodeid %lu",
oPaxosMsg.instanceid(), GetInstanceID(), oPaxosMsg.proposalid(),
m_poAcceptor->GetAcceptorState()->GetAcceptedBallot().m_llProposalID,
m_poAcceptor->GetAcceptorState()->GetAcceptedBallot().m_llNodeID,
oPaxosMsg.nodeid());
if (oPaxosMsg.instanceid() != GetInstanceID())
{
//Instance id not same, that means not in the same instance, ignord.
PLGDebug("InstanceID not same, skip msg");
return;
}
if (m_poAcceptor->GetAcceptorState()->GetAcceptedBallot().isnull())
{
//Not accept any yet.
BP->GetLearnerBP()->OnProposerSendSuccessNotAcceptYet();
PLGDebug("I haven't accpeted any proposal");
return;
}
BallotNumber oBallot(oPaxosMsg.proposalid(), oPaxosMsg.nodeid());
if (m_poAcceptor->GetAcceptorState()->GetAcceptedBallot()
!= oBallot)
{
//Proposalid not same, this accept value maybe not chosen value.
PLGDebug("ProposalBallot not same to AcceptedBallot");
BP->GetLearnerBP()->OnProposerSendSuccessBallotNotSame();
return;
}
//learn value.
m_oLearnerState.LearnValueWithoutWrite(
oPaxosMsg.instanceid(),
m_poAcceptor->GetAcceptorState()->GetAcceptedValue(),
m_poAcceptor->GetAcceptorState()->GetChecksum());
BP->GetLearnerBP()->OnProposerSendSuccessSuccessLearn();
PLGHead("END Learn value OK, value %zu", m_poAcceptor->GetAcceptorState()->GetAcceptedValue().size());
TransmitToFollower();
}
////////////////////////////////////////////////////////////////////////
void Learner :: AskforCheckpoint(const nodeid_t iSendNodeID)
{
PLGHead("START");
int ret = m_poCheckpointMgr->PrepareForAskforCheckpoint(iSendNodeID);
if (ret != 0)
{
return;
}
PaxosMsg oPaxosMsg;
oPaxosMsg.set_instanceid(GetInstanceID());
oPaxosMsg.set_nodeid(m_poConfig->GetMyNodeID());
oPaxosMsg.set_msgtype(MsgType_PaxosLearner_AskforCheckpoint);
PLGHead("END InstanceID %lu MyNodeID %lu", GetInstanceID(), oPaxosMsg.nodeid());
SendMessage(iSendNodeID, oPaxosMsg);
}
void Learner :: OnAskforCheckpoint(const PaxosMsg & oPaxosMsg)
{
CheckpointSender * poCheckpointSender = GetNewCheckpointSender(oPaxosMsg.nodeid());
if (poCheckpointSender != nullptr)
{
poCheckpointSender->start();
PLGHead("new checkpoint sender started, send to nodeid %lu", oPaxosMsg.nodeid());
}
else
{
PLGErr("Checkpoint Sender is running");
}
}
int Learner :: SendCheckpointBegin(
const nodeid_t iSendNodeID,
const uint64_t llUUID,
const uint64_t llSequence,
const uint64_t llCheckpointInstanceID)
{
CheckpointMsg oCheckpointMsg;
oCheckpointMsg.set_msgtype(CheckpointMsgType_SendFile);
oCheckpointMsg.set_nodeid(m_poConfig->GetMyNodeID());
oCheckpointMsg.set_flag(CheckpointSendFileFlag_BEGIN);
oCheckpointMsg.set_uuid(llUUID);
oCheckpointMsg.set_sequence(llSequence);
oCheckpointMsg.set_checkpointinstanceid(llCheckpointInstanceID);
PLGImp("END, SendNodeID %lu uuid %lu sequence %lu cpi %lu",
iSendNodeID, llUUID, llSequence, llCheckpointInstanceID);
return SendMessage(iSendNodeID, oCheckpointMsg, Message_SendType_TCP);
}
int Learner :: SendCheckpointEnd(
const nodeid_t iSendNodeID,
const uint64_t llUUID,
const uint64_t llSequence,
const uint64_t llCheckpointInstanceID)
{
CheckpointMsg oCheckpointMsg;
oCheckpointMsg.set_msgtype(CheckpointMsgType_SendFile);
oCheckpointMsg.set_nodeid(m_poConfig->GetMyNodeID());
oCheckpointMsg.set_flag(CheckpointSendFileFlag_END);
oCheckpointMsg.set_uuid(llUUID);
oCheckpointMsg.set_sequence(llSequence);
oCheckpointMsg.set_checkpointinstanceid(llCheckpointInstanceID);
PLGImp("END, SendNodeID %lu uuid %lu sequence %lu cpi %lu",
iSendNodeID, llUUID, llSequence, llCheckpointInstanceID);
return SendMessage(iSendNodeID, oCheckpointMsg, Message_SendType_TCP);
}
int Learner :: SendCheckpoint(
const nodeid_t iSendNodeID,
const uint64_t llUUID,
const uint64_t llSequence,
const uint64_t llCheckpointInstanceID,
const uint32_t iChecksum,
const std::string & sFilePath,
const int iSMID,
const uint64_t llOffset,
const std::string & sBuffer)
{
CheckpointMsg oCheckpointMsg;
oCheckpointMsg.set_msgtype(CheckpointMsgType_SendFile);
oCheckpointMsg.set_nodeid(m_poConfig->GetMyNodeID());
oCheckpointMsg.set_flag(CheckpointSendFileFlag_ING);
oCheckpointMsg.set_uuid(llUUID);
oCheckpointMsg.set_sequence(llSequence);
oCheckpointMsg.set_checkpointinstanceid(llCheckpointInstanceID);
oCheckpointMsg.set_checksum(iChecksum);
oCheckpointMsg.set_filepath(sFilePath);
oCheckpointMsg.set_smid(iSMID);
oCheckpointMsg.set_offset(llOffset);
oCheckpointMsg.set_buffer(sBuffer);
PLGImp("END, SendNodeID %lu uuid %lu sequence %lu cpi %lu checksum %u smid %d offset %lu buffsize %zu filepath %s",
iSendNodeID, llUUID, llSequence, llCheckpointInstanceID,
iChecksum, iSMID, llOffset, sBuffer.size(), sFilePath.c_str());
return SendMessage(iSendNodeID, oCheckpointMsg, Message_SendType_TCP);
}
int Learner :: OnSendCheckpoint_Begin(const CheckpointMsg & oCheckpointMsg)
{
int ret = m_oCheckpointReceiver.NewReceiver(oCheckpointMsg.nodeid(), oCheckpointMsg.uuid());
if (ret == 0)
{
PLGImp("NewReceiver ok");
ret = m_poCheckpointMgr->SetMinChosenInstanceID(oCheckpointMsg.checkpointinstanceid());
if (ret != 0)
{
PLGErr("SetMinChosenInstanceID fail, ret %d CheckpointInstanceID %lu",
ret, oCheckpointMsg.checkpointinstanceid());
return ret;
}
}
return ret;
}
int Learner :: OnSendCheckpoint_Ing(const CheckpointMsg & oCheckpointMsg)
{
BP->GetCheckpointBP()->OnSendCheckpointOneBlock();
return m_oCheckpointReceiver.ReceiveCheckpoint(oCheckpointMsg);
}
int Learner :: OnSendCheckpoint_End(const CheckpointMsg & oCheckpointMsg)
{
if (!m_oCheckpointReceiver.IsReceiverFinish(oCheckpointMsg.nodeid(),
oCheckpointMsg.uuid(), oCheckpointMsg.sequence()))
{
PLGErr("receive end msg but receiver not finish");
return -1;
}
BP->GetCheckpointBP()->ReceiveCheckpointDone();
std::vector<StateMachine *> vecSMList = m_poSMFac->GetSMList();
for (auto & poSM : vecSMList)
{
if (poSM->SMID() == SYSTEM_V_SMID
|| poSM->SMID() == MASTER_V_SMID)
{
//system variables sm no checkpoint
//master variables sm no checkpoint
continue;
}
string sTmpDirPath = m_oCheckpointReceiver.GetTmpDirPath(poSM->SMID());
std::vector<std::string> vecFilePathList;
int ret = FileUtils :: IterDir(sTmpDirPath, vecFilePathList);
if (ret != 0)
{
PLGErr("IterDir fail, dirpath %s", sTmpDirPath.c_str());
}
if (vecFilePathList.size() == 0)
{
PLGImp("this sm %d have no checkpoint", poSM->SMID());
continue;
}
ret = poSM->LoadCheckpointState(
m_poConfig->GetMyGroupIdx(),
sTmpDirPath,
vecFilePathList,
oCheckpointMsg.checkpointinstanceid());
if (ret != 0)
{
BP->GetCheckpointBP()->ReceiveCheckpointAndLoadFail();
return ret;
}
}
BP->GetCheckpointBP()->ReceiveCheckpointAndLoadSucc();
PLGImp("All sm load state ok, start to exit process");
exit(-1);
return 0;
}
void Learner :: OnSendCheckpoint(const CheckpointMsg & oCheckpointMsg)
{
PLGHead("START uuid %lu flag %d sequence %lu cpi %lu checksum %u smid %d offset %lu buffsize %zu filepath %s",
oCheckpointMsg.uuid(), oCheckpointMsg.flag(), oCheckpointMsg.sequence(),
oCheckpointMsg.checkpointinstanceid(), oCheckpointMsg.checksum(), oCheckpointMsg.smid(),
oCheckpointMsg.offset(), oCheckpointMsg.buffer().size(), oCheckpointMsg.filepath().c_str());
int ret = 0;
if (oCheckpointMsg.flag() == CheckpointSendFileFlag_BEGIN)
{
ret = OnSendCheckpoint_Begin(oCheckpointMsg);
}
else if (oCheckpointMsg.flag() == CheckpointSendFileFlag_ING)
{
ret = OnSendCheckpoint_Ing(oCheckpointMsg);
}
else if (oCheckpointMsg.flag() == CheckpointSendFileFlag_END)
{
ret = OnSendCheckpoint_End(oCheckpointMsg);
}
if (ret != 0)
{
PLGErr("[FAIL] reset checkpoint receiver and reset askforlearn");
m_oCheckpointReceiver.Reset();
Reset_AskforLearn_Noop(5000);
SendCheckpointAck(oCheckpointMsg.nodeid(), oCheckpointMsg.uuid(), oCheckpointMsg.sequence(), CheckpointSendFileAckFlag_Fail);
}
else
{
SendCheckpointAck(oCheckpointMsg.nodeid(), oCheckpointMsg.uuid(), oCheckpointMsg.sequence(), CheckpointSendFileAckFlag_OK);
Reset_AskforLearn_Noop(120000);
}
}
int Learner :: SendCheckpointAck(
const nodeid_t iSendNodeID,
const uint64_t llUUID,
const uint64_t llSequence,
const int iFlag)
{
CheckpointMsg oCheckpointMsg;
oCheckpointMsg.set_msgtype(CheckpointMsgType_SendFile_Ack);
oCheckpointMsg.set_nodeid(m_poConfig->GetMyNodeID());
oCheckpointMsg.set_uuid(llUUID);
oCheckpointMsg.set_sequence(llSequence);
oCheckpointMsg.set_flag(iFlag);
return SendMessage(iSendNodeID, oCheckpointMsg, Message_SendType_TCP);
}
void Learner :: OnSendCheckpointAck(const CheckpointMsg & oCheckpointMsg)
{
PLGHead("START flag %d", oCheckpointMsg.flag());
if (m_poCheckpointSender != nullptr && !m_poCheckpointSender->IsEnd())
{
if (oCheckpointMsg.flag() == CheckpointSendFileAckFlag_OK)
{
m_poCheckpointSender->Ack(oCheckpointMsg.nodeid(), oCheckpointMsg.uuid(), oCheckpointMsg.sequence());
}
else
{
m_poCheckpointSender->End();
}
}
}
CheckpointSender * Learner :: GetNewCheckpointSender(const nodeid_t iSendNodeID)
{
if (m_poCheckpointSender != nullptr)
{
if (m_poCheckpointSender->IsEnd())
{
m_poCheckpointSender->join();
delete m_poCheckpointSender;
m_poCheckpointSender = nullptr;
}
}
if (m_poCheckpointSender == nullptr)
{
m_poCheckpointSender = new CheckpointSender(iSendNodeID, m_poConfig, this, m_poSMFac, m_poCheckpointMgr);
return m_poCheckpointSender;
}
return nullptr;
}
}
| [
"lynncui00@gmail.com"
] | lynncui00@gmail.com |
b365c3b5171c7b47700ebe5dc7dce16a7bc51f41 | 8c203ae5ae7de67b254bb0d6450135667e7f1e41 | /Source/PlateShootingGame/Private/Weapons/Projectiles/Projectile.cpp | 6f3689430a2feb90b625723b14a4a96436441908 | [] | no_license | AdemJensen/PlateShootingGame-UE4 | 48c37ce11e8a370119b22cff12f52eb8d631d406 | 6b94c962084afa659da169d2eb131b7d0cabf460 | refs/heads/master | 2023-02-02T01:14:08.448025 | 2020-12-21T13:28:49 | 2020-12-21T13:28:49 | 307,062,331 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,097 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "Weapons/Projectiles/Projectile.h"
#include "GameFramework/Character.h"
#include "Components/CapsuleComponent.h"
#include "GeneratedCodeHelpers.h"
#include "Kismet/GameplayStatics.h"
void AProjectile::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME(AProjectile, MassInKg);
}
AProjectile::AProjectile()
{
PrimaryActorTick.bCanEverTick = true;
bReplicates = true;
AActor::SetReplicateMovement(true);
ProjectileBody = CreateDefaultSubobject<UStaticMeshComponent>("ProjectileBody");
ProjectileArrow = CreateDefaultSubobject<UArrowComponent>("ProjectileDirection");
//CollisionBox = CreateDefaultSubobject<UCapsuleComponent>("ProjectileCollision");
RootComponent = ProjectileBody;
//CollisionBox->SetupAttachment(RootComponent);
ProjectileArrow->SetupAttachment(RootComponent);
ProjectileBody->BodyInstance.bOverrideMass = true;
ProjectileBody->BodyInstance.SetMassOverride(MassInKg);
}
| [
"rentenglong@163.com"
] | rentenglong@163.com |
390ff3a0ca98d94c51a27c0a86a5d15a5e820683 | 1715ced50247a48019028aec2f263c31e02db0f6 | /test/sparse/laplacian_crs_mpi.cpp | 2db0114101a6805bdbf71cac7c0ec27f1227a633 | [
"BSL-1.0"
] | permissive | t-sakashita/rokko | 0b9368c441a67b25a3819e199697e53c97a4e823 | ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9 | refs/heads/master | 2023-08-17T00:27:23.907796 | 2020-09-17T11:25:00 | 2020-09-17T11:25:00 | 9,142,365 | 18 | 2 | BSL-1.0 | 2021-03-21T12:15:40 | 2013-04-01T06:31:20 | C++ | UTF-8 | C++ | false | false | 3,447 | cpp | /*****************************************************************************
*
* Rokko: Integrated Interface for libraries of eigenvalue decomposition
*
* Copyright (C) 2012-2020 by Rokko Developers https://github.com/t-sakashita/rokko
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
*****************************************************************************/
#include <rokko/rokko.hpp>
#include <rokko/utility/laplacian_matrix.hpp>
#include <rokko/utility/various_mpi_comm.hpp>
#include <gtest/gtest.h>
constexpr double eps = 1e-8;
int global_argc;
char** global_argv;
void run_test(std::string const& library, MPI_Comm comm) {
constexpr int dim = 20;
std::cout << "library = " << library << std::endl;
rokko::parameters params;
params.set("num_eigvals", 1);
params.set("block_size", 5);
params.set("max_iters", 500);
params.set("conv_tol", eps);
rokko::parallel_sparse_ev solver(library);
if (comm != MPI_COMM_NULL) {
auto map = solver.default_mapping(dim, rokko::mpi_comm{comm});
rokko::distributed_crs_matrix mat(map, 3);
if (map.start_row() == 0) {
mat.insert(0, {0, 1}, {1., -1.});
}
for (int row = std::max(1,map.start_row()); row < std::min(map.end_row(),dim-1); ++row) {
mat.insert(row, {row-1, row, row+1}, {-1., 2., -1.});
}
if (map.end_row() == dim) {
mat.insert(dim-1, {dim-2, dim-1}, {-1., 2.});
}
mat.complete();
std::vector<std::array<std::string,2>> routines;
if (library=="anasazi")
routines = { {"lobpcg", "largest_real"}, {"block_krylov_schur", "largest"}, {"block_davidson", "largest_real"}, {"rtr", "largest_real"} };
else if (library=="slepc")
routines = { {"krylovschur", "largest"}, {"lanczos", "largest"}, {"lobpcg", "largest_real"}, {"rqcg", "smallest_real"}, {"subspace", "largest"} }; // excludes not converging "power"
for (auto routine : routines) {
std::cout << "routine=" << routine[0] << std::endl;
auto params_tmp = params;
params_tmp.set("routine", routine[0]);
if (routine[0] == "block_davidson") params_tmp.set("block_size", 10);
params_tmp.set("wanted_eigenvalues", routine[1]);
rokko::parameters info = solver.diagonalize(mat, params_tmp);
int num_conv = info.get<int>("num_conv");
if (num_conv == 0)
throw std::runtime_error("num_conv=0: solver did not converge");
double eigval = solver.eigenvalue(0);
double th_eigval = (routine[0] == "rqcg") ? rokko::laplacian_matrix::eigenvalue(dim, 0) // smallest one
: rokko::laplacian_matrix::eigenvalue(dim, dim-1); // largest one
EXPECT_NEAR(eigval, th_eigval, eigval*eps);
}
} // end if comm != MPI_COMM_NULL
solver.finalize();
}
TEST(laplacian_crs, eigenvalue) {
for(auto library : rokko::parallel_sparse_ev::solvers()) {
run_test(library, MPI_COMM_WORLD);
run_test(library, create_even_odd_comm_by_split());
run_test(library, create_even_odd_comm());
run_test(library, create_even_comm()); // MPI_COMM_NULL for odd rank number
}
}
int main(int argc, char** argv) {
int result = 0;
::testing::InitGoogleTest(&argc, argv);
int provided;
MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided);
global_argc = argc;
global_argv = argv;
result = RUN_ALL_TESTS();
MPI_Finalize();
return result;
}
| [
"tatsuyasakashita@eng.tamagawa.ac.jp"
] | tatsuyasakashita@eng.tamagawa.ac.jp |
2633c00cdfd0778552c200ba55a0951e506b4618 | e06da26e05c2c0cb46e0df4eeb4da9731aade122 | /LearnRcpp/euclidean_algorithm.cpp | 0ac6db89115fb86e51d4b60647fddcbc32767f87 | [
"MIT"
] | permissive | m-RezaFahlevi/Mathematica-Works | 54bb8a16f1d945e3135956f63ccb9d652176d2dc | 71bd3751a4cda8947d7f0a42c5956260f55eb174 | refs/heads/master | 2023-04-30T07:15:37.217840 | 2023-04-24T07:28:26 | 2023-04-24T07:28:26 | 254,063,736 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,753 | cpp | #include <bits/stdc++.h>
using namespace std;
vector<int> gcd(int a, int b) {
// if a < b, then swap the value of a and b
// such that a > b
int mod_counter = 0;
if (a < b) {
int temp = a;
a = b;
b = temp;
}
while (b != 0) {
int r = a % b; // i.e., r = a mod b
a = b;
b = r;
mod_counter++;
}
vector<int> gcd_ret = {a, mod_counter};
return gcd_ret;
}
vector<pair<int, int>> generate_intpairs(int given_range) {
vector<pair<int, int>> intpairs;
for (int i = 0; i <= given_range; i++) {
for (int j = 0; j <= given_range; j++) {
if ((i == 0 && j == 0) || (i == 1 && j == 1))
continue;
intpairs.push_back(pair<int, int>(i, j));
}
}
return intpairs;
}
int main(void) {
int created_range = 50; // pair numbers (a, b) such that 0 <= a,b <= created_range
vector<pair<int, int>> integer_pairs = generate_intpairs(created_range);
map<int, pair<int, int>> nmod;
// print the gcd pair as table
vector<pair<int, int>>::iterator ptr_intpairs;
for (ptr_intpairs = integer_pairs.begin(); ptr_intpairs != integer_pairs.end(); ++ptr_intpairs) {
vector<int> calcgcd = gcd(ptr_intpairs->first, ptr_intpairs->second);
if (ptr_intpairs->second == created_range)
cout << calcgcd.at(0) << endl;
else
cout << calcgcd.at(0) << " ";
} cout << "\n";
// print how many times operator mod is executed
for (ptr_intpairs = integer_pairs.begin(); ptr_intpairs != integer_pairs.end(); ++ptr_intpairs) {
vector<int> calcgcd = gcd(ptr_intpairs->first, ptr_intpairs->second);
if (ptr_intpairs->second == created_range)
cout << calcgcd.at(1) << endl;
else
cout << calcgcd.at(1) << " ";
} cout << "\n";
// print the gcd(a, b)
for (ptr_intpairs = integer_pairs.begin(); ptr_intpairs != integer_pairs.end(); ++ptr_intpairs) {
vector<int> calcgcd = gcd(ptr_intpairs->first, ptr_intpairs->second);
cout << "gcd(" << ptr_intpairs->first << ", " << ptr_intpairs->second << ") ";
cout << "= " << calcgcd.at(0) << " ";
cout << "with " << calcgcd.at(1) << " times modulo operate\n";
}
// print the smallest input pair a, b, a > b, that requires
// n modulus operations in the Euclidean algorithm
//
// insert to nmod map
for (ptr_intpairs = integer_pairs.begin(); ptr_intpairs != integer_pairs.end(); ++ptr_intpairs) {
int calcnmod = gcd(ptr_intpairs->first, ptr_intpairs->second).at(1);
nmod.insert(pair<int, pair<int, int>>(calcnmod, pair<int, int>(ptr_intpairs->first, ptr_intpairs->second)));
}
// print the output
cout << "\na\tb\t" << "number of modulus operations\n";
map<int, pair<int, int>>::iterator itrmap;
for (itrmap = nmod.begin(); itrmap != nmod.end(); ++itrmap) {
cout << itrmap->second.second << "\t" << itrmap->second.first << "\t";
cout << itrmap->first << endl;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
fd17d75272c6a91fde28c8df23e36b8eaaeff4b0 | fb930c3c04f1a15a5575a02ffdaab8955688d7ee | /线性表/线性表的顺序表示与实现/main.cpp | cf05e381ee845f731b978297fb294cabfc3b711b | [] | no_license | xfhy/dataStructure | 7238232f4e8a3e0ce62ece2ca55f729d16aac293 | 4d1d6972bedcfd4278aa3ae23e622888f41efe74 | refs/heads/master | 2021-01-22T07:27:04.738875 | 2018-10-14T08:36:11 | 2018-10-14T08:36:11 | 81,815,045 | 7 | 1 | null | null | null | null | GB18030 | C++ | false | false | 661 | cpp | # include "function.h"
int main(void)
{
SqList L; //定义
InitList(L); //初始化
Random(L); //赋一些初值
/*----------------菜单设计-------------*/
cout<<"\t---顺序表---"<<endl;
cout<<"1.显示表内元素"<<endl;
cout<<"2.插入"<<endl;
cout<<"3.删除"<<endl;
cout<<"4.查找"<<endl;
cout<<"请选择您需要的操作(已初始化一定元素):"<<endl;
int temp;
cin>>temp;
if(temp>0 && temp<=4)
{
switch(temp)
{
case 1:
Show(L);
break;
case 2:
ListInsert(L);
break;
case 3:
Listdelete(L);
break;
case 4:
Seek(L);
break;
}
}
system("pause");
return 0;
} | [
"1319504383@qq.com"
] | 1319504383@qq.com |
aa5a6dd844a20bf6e8af6b0594a4f49bd2b08db2 | a2e49e160ecaebb7122b8304143f17df9549c053 | /JZoffer/28.cc | 67ad33475c8a60566d186014ba985fe0034ccc10 | [] | no_license | wangnengjie/leetcode | de47e52dbdc27c5152f38b075418d794167f9fda | 75e2407e00be6a72a9477e4e0c09123dbfeb1997 | refs/heads/master | 2021-06-17T15:22:27.818351 | 2021-03-08T13:24:27 | 2021-03-08T13:24:27 | 181,513,174 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 946 | cc | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode *root) {
if (root == NULL) {
return true;
}
auto q = queue<TreeNode *>();
q.push(root->left);
q.push(root->right);
while (!q.empty()) {
auto n1 = q.front();
q.pop();
auto n2 = q.front();
q.pop();
if (n1 == NULL && n2 == NULL) {
continue;
}
if ((n1 == NULL && n2 != NULL) || (n1 != NULL && n2 == NULL) || (n1->val != n2->val)) {
return false;
}
q.push(n1->left);
q.push(n2->right);
q.push(n1->right);
q.push(n2->left);
}
return true;
}
}; | [
"751614701@qq.com"
] | 751614701@qq.com |
8550833142b3a094b8899c7e365afed50f087c24 | 6f885bc26e67694258a93d7f9ab55b2da5e629dc | /1400A.cpp | d2be1d0b596fb49f67450c61c26c3dbbb0c14731 | [] | no_license | Ashik1704026/codeforce | 644121030b3fdadb5405451f2e3b857acb7203d6 | 04b6d72b739cdf4bc3ce7e68e6dc72ebf983ab20 | refs/heads/master | 2021-11-22T14:23:47.848180 | 2021-08-30T18:18:11 | 2021-08-30T18:18:11 | 223,139,729 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,704 | cpp | // MD. Ashiqur Rahman
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define scn(x) scanf("%d",&x)
#define scnl(x) scanf("%lld",&x)
#define prnt(x) printf("%d\n",x)
#define prntl(x) printf("%lld\n",x)
#define prii pair<int,int>
#define mapii map<int,int>
#define mapll map<ll,ll>
#define mapci map<char,int>
#define mapcl map<char,ll>
#define mapsi map<string,int>
#define mapsl map<string,ll>
#define prll pair<ll,ll>
#define vctri vector<int>
#define vctrl vector<ll>
#define vctrd vector<double,double>
#define all(a) (a).begin(),(a).end()
#define rall(a) (a).rbegin(),(a).rend()
#define F first
#define S second
#define mp make_pair
#define ftc(x) cerr << #x << ": " << x << " " << '\n';
#define PI acos(-1)
#define lcm(a,b) ((a*b)/__gcd(a,b))
#define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define sqr(a) ((a)*(a))
#define memset(x,v) memset(x, v, sizeof(x))
#define ask '\n'
#define negmod(x,y) ((x % y) + y) % y
ll MOD;
inline void modulas(ll a) {MOD = a;}
inline void normal(ll &a) { a %= MOD; (a < 0) && (a += MOD); }
inline ll modMul(ll a, ll b) { a %= MOD, b %= MOD; normal(a), normal(b); return (a*b)%MOD; }
inline ll modAdd(ll a, ll b) { a %= MOD, b %= MOD; normal(a), normal(b); return (a+b)%MOD; }
inline ll modSub(ll a, ll b) { a %= MOD, b %= MOD; normal(a), normal(b); a -= b; normal(a); return a; }
inline ll modPow(ll b, ll p) { ll r = 1; while(p) { if(p&1) r = modMul(r, b); b = modMul(b, b); p >>= 1; } return r; }
inline ll modInverse(ll a) { return modPow(a, MOD-2); }
inline ll modDiv(ll a, ll b) { return modMul(a, modInverse(b)); }
vector<bool> isPrime(10000010, true);
inline void seivePrime(ll L, ll R) { ll lim = sqrt(R);for (ll i = 2; i <= lim; ++i){
for (ll j = max(i * i, (L + i - 1) / i * i); j <= R; j += i)
isPrime[j - L] = false;}if (L == 1)isPrime[0] = false;}
inline ll chckPrime(ll L,ll prme){return isPrime[prme - L];}
inline ll cntPrime(ll L,ll R){return count(isPrime.begin(),isPrime.begin() + R - L + 1,true);}
int main(){
fast;
int t = 1;
cin >> t;
while(t --){
int n;
cin >> n;
string s;
cin >> s;
s = '#' + s;
for(int i = 1;i < 2 * n;i += 2)
cout << s[i];
cout << "\n";
}
return 0;
} | [
"ashiqurr343@gmail.com"
] | ashiqurr343@gmail.com |
555ca9573fa3116f526a8102f9e169d1cf06031d | b254f2fb12a3262fe2ddcbd6c214bcadbba4e0c1 | /interview-master/vector/main.cc | 5abc94217e63ab717f023a0c509464faf8be537a | [] | no_license | hijianding/360Test | 0fca7ef0a0d548d28d2593a58af5b21412fac826 | 7c270d4dac89cb9183085c46090754469c92e55d | refs/heads/master | 2021-01-25T04:10:18.389680 | 2017-06-08T09:45:27 | 2017-06-08T09:45:27 | 93,406,033 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,170 | cc | #include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include "qh_vector.h"
void test1()
{
size_t size = 10;
qh::vector<int> num_vect;
assert(num_vect.empty() == true);
//push_back
for (int i = 0; i < size; i++)
{
num_vect.push_back(i);
}
assert(num_vect.size() == size);
assert(num_vect[0] == 0);
assert(num_vect[4] == 4);
assert(num_vect[9] == 9);
//=
qh::vector<int> num_vect_other;
num_vect_other = num_vect;
assert(num_vect_other.size() == size);
assert(num_vect_other[0] == 0);
assert(num_vect_other[4] == 4);
assert(num_vect_other[9] == 9);
//set
num_vect[9] = 10;
assert(num_vect[9] == 10);
//deep clone
assert(num_vect_other[9] == 9);
//pop_back
num_vect.pop_back();
assert(num_vect.size() == size - 1);
//clear
num_vect.clear();
assert(num_vect.size() == 0);
//resize
num_vect.resize(5);
assert(num_vect.size() == 5);
assert(num_vect[0] == 0);
assert(num_vect[4] == 0);
printf("test1 accept\n");
}
void test2()
{
size_t size = 10;
qh::vector<int> num_vect(size);
assert(num_vect.empty() == false);
//push_back
for (int i = 0; i < size; i++)
{
num_vect[i] = i;
}
assert(num_vect.size() == size);
assert(num_vect[0] == 0);
assert(num_vect[4] == 4);
assert(num_vect[9] == 9);
//=
qh::vector<int> num_vect_other;
num_vect_other = num_vect;
assert(num_vect_other.size() == size);
assert(num_vect_other[0] == 0);
assert(num_vect_other[4] == 4);
assert(num_vect_other[9] == 9);
//set
num_vect[9] = 10;
assert(num_vect[9] == 10);
//deep clone
assert(num_vect_other[9] == 9);
//pop_back
num_vect.pop_back();
assert(num_vect.size() == size - 1);
//clear
num_vect.clear();
assert(num_vect.size() == 0);
//resize
num_vect.resize(5);
assert(num_vect.size() == 5);
assert(num_vect[0] == 0);
assert(num_vect[4] == 0);
printf("test2 accept\n");
}
int main(int argc, char* argv[])
{
//TODO 在这里添加单元测试,越多越好,代码路径覆盖率越全越好
//TODO 单元测试写法请参考INIParser那个项目,不要写一堆printf,要用assert进行断言判断。
test1();
test2();
printf("it is ok!\n");
#ifdef WIN32
system("pause");
#endif
return 0;
}
| [
"dingjian_hn@sina.com"
] | dingjian_hn@sina.com |
324f9de989985196c7284b6152fd548e4859e6ef | 5656f023246d1922833b0198fd5b106009d9d6c8 | /Driver.h | afa18c45d4b255ee87b7329d4f57a68b9aa8c642 | [] | no_license | iblazys/Bluedio | c332116a51c12b34e0eb66aa14830f9f3fb9ccff | 3fa2df957d885288a3a1dabcdb5527a1ed91a35d | refs/heads/master | 2022-12-21T23:28:22.963653 | 2020-02-06T03:14:28 | 2020-02-06T03:14:28 | 238,354,969 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,869 | h | #pragma once
#include "imports.h"
typedef struct _COPY_MEMORY
{
void* bufferAddress; // Buffer address
UINT_PTR address; // Target address
ULONGLONG size; // Buffer size
ULONG pid; // Target process id
BOOLEAN write; // TRUE if write operation, FALSE if read
BOOLEAN ReqBase; // TRUE if request base address, FALSE if not.
ULONG64 BaseAddress; // Base address of the game
void* Output;
BOOLEAN ClearPIDCache;
BOOLEAN PIDCacheCleared;
BOOLEAN Read;
BOOLEAN ReadString;
BOOLEAN WriteString;
const char* moduleName;
ULONG pid_ofSource;
//UINT_PTR process_id; already here
//PVOID address; already here
//SIZE_T size; already here
BOOLEAN change_protection;
ULONG protection;
ULONG protection_old;
}COPY_MEMORY;
extern std::uint32_t process_id;
struct HandleDisposer
{
using pointer = HANDLE;
void operator()(HANDLE handle) const
{
if (handle != NULL || handle != INVALID_HANDLE_VALUE)
{
CloseHandle(handle);
}
}
};
using unique_handle = std::unique_ptr<HANDLE, HandleDisposer>;
static std::uint32_t get_process_id(std::string_view process_name) {
PROCESSENTRY32 processentry;
const unique_handle snapshot_handle(CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0));
if (snapshot_handle.get() == INVALID_HANDLE_VALUE)
return 0;
processentry.dwSize = sizeof(MODULEENTRY32);
while (Process32Next(snapshot_handle.get(), &processentry) == TRUE) {
if (process_name.compare(processentry.szExeFile) == 0)
return processentry.th32ProcessID;
}
return 0;
}
template<typename ... A>
uint64_t call_hook(const A ... arguments)
{
void* control_function = GetProcAddress(LoadLibrary("win32u.dll"), "NtOpenCompositionSurfaceSectionInfo");
const auto control = static_cast<uint64_t(__stdcall*)(A...)>(control_function);
return control(arguments ...);
}
static ULONG64 change_protection(uint64_t pid, uint64_t address, uint32_t page_protection, std::size_t size)
{
COPY_MEMORY m = { 0 };
m.pid = process_id;
m.address = address;
m.protection = page_protection;
m.size = size;
m.change_protection = TRUE;
m.ReqBase = FALSE;
m.ClearPIDCache = FALSE;
m.Read = FALSE;
m.ReadString = FALSE;
m.write = FALSE;
m.WriteString = FALSE;
return call_hook(&m);
}
static ULONG64 get_module_base_address(const char* moduleName) {
COPY_MEMORY m = { 0 };
m.pid = process_id;
m.ReqBase = TRUE;
m.ClearPIDCache = FALSE;
m.Read = FALSE;
m.ReadString = FALSE;
m.write = FALSE;
m.WriteString = FALSE;
m.moduleName = moduleName;
call_hook(&m);
ULONG64 base = NULL;
base = m.BaseAddress;
return base;
}
template <typename T>
T Read(UINT_PTR ReadAddress) {
T response{};
COPY_MEMORY m;
m.pid = process_id;
m.size = sizeof(T);
m.address = ReadAddress;
m.Read = TRUE;
m.ReadString = FALSE;
m.WriteString = FALSE;
m.write = FALSE;
m.ReqBase = FALSE;
m.ClearPIDCache = FALSE;
call_hook(&m);
return *(T*)& m.Output;
}
static bool WriteVirtualMemoryRaw(UINT_PTR WriteAddress, UINT_PTR SourceAddress, SIZE_T WriteSize);
template<typename S>
bool Write(UINT_PTR WriteAddress, const S& value)
{
return WriteVirtualMemoryRaw(WriteAddress, (UINT_PTR)& value, sizeof(S));
}
bool WriteVirtualMemoryRaw(UINT_PTR WriteAddress, UINT_PTR SourceAddress, SIZE_T WriteSize)
{
COPY_MEMORY m;
m.address = WriteAddress;
m.pid = process_id;
m.pid_ofSource = GetCurrentProcessId();
m.write = TRUE;
m.ClearPIDCache = FALSE;
m.Read = FALSE;
m.ReadString = FALSE;
m.ReqBase = FALSE;
m.WriteString = FALSE;
m.bufferAddress = (void*)SourceAddress;
m.size = WriteSize;
call_hook(&m);
return true;
}
static BOOLEAN CleanPIDDBCacheTable() {
COPY_MEMORY m;
m.ClearPIDCache = TRUE;
m.Read = FALSE;
m.WriteString = FALSE;
m.write = FALSE;
m.ReqBase = FALSE;
m.ReadString = FALSE;
call_hook(&m);
return m.PIDCacheCleared;
}
// working
template <typename T> T ReadStruct(uint64_t addr) {
T val = {};
COPY_MEMORY m;
m.pid = process_id;
m.ReadString = TRUE;
m.Read = FALSE;
m.ClearPIDCache = FALSE;
m.ReqBase = FALSE;
m.write = FALSE;
m.WriteString = FALSE;
m.address = addr;
m.bufferAddress = &val;
m.size = sizeof(T);
call_hook(&m);
return val;
}
static void ReadToBuffer(UINT_PTR ReadAddress, void* buffer, SIZE_T size) {
COPY_MEMORY m;
m.pid = process_id;
m.ReadString = TRUE;
m.Read = FALSE;
m.ClearPIDCache = FALSE;
m.ReqBase = FALSE;
m.write = FALSE;
m.WriteString = FALSE;
m.address = ReadAddress;
m.bufferAddress = buffer;
m.size = size;
call_hook(&m);
}
static void WriteString(UINT_PTR String_address, void* buffer, SIZE_T size) {
COPY_MEMORY m;
m.pid = process_id;
m.WriteString = TRUE;
m.ClearPIDCache = FALSE;
m.Read = FALSE;
m.ReadString = FALSE;
m.ReqBase = FALSE;
m.write = FALSE;
m.address = String_address;
m.bufferAddress = buffer;
m.size = size;
call_hook(&m);
} | [
"933056+iblazys@users.noreply.github.com"
] | 933056+iblazys@users.noreply.github.com |
1ffd255db6b714b334d14d89bb48576b6186a7fc | 1db7b0d1abbd860e1ef081e61b5f72dd8079449f | /src/server/gaga_timer.h | 7926afa1abe710be52dd9dc7d096e0f9675d34d9 | [] | no_license | denkisdeng/gaga | 4386348acd85add6d350deab4827799df494503a | 1177fea7ccadb2e5fb5b7f67ad8143b28623fac8 | refs/heads/master | 2020-03-23T20:01:28.426889 | 2017-03-01T01:40:27 | 2017-03-01T01:40:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,326 | h | #ifndef __GAGA_TIMER_H__
#define __GAGA_TIMER_H__
#include <inttypes.h>
#include <functional>
#include <list>
#include <vector>
#include <map>
struct TimerNode {
std::string name;
uint64_t expireTime;
std::function<void()> cb;
};
struct TimerSlot {
std::list<TimerNode*> timerList;
};
class TimerManager {
public:
static TimerManager* GetInstance();
int32_t AddTimeoutTimer(const std::string name, const uint32_t timeoutTicks, const std::function<void()>& cb);
int32_t AddTickTimer(const std::string name, const uint32_t ticks, const std::function<void()>& tick_cb);
void RemoveTimer(const std::string name);
void Tick();
private:
TimerManager();
~TimerManager();
void InitTimerSlots(std::vector<TimerSlot*>& slotVector, uint32_t num);
TimerNode* FindTimerNode(const std::string name);
uint64_t GetOSTime();
void GetTimeInfo(uint64_t milSecond, uint32_t& hour, uint32_t& minute, uint32_t& second, uint32_t& tick);
uint32_t m_maxHour;
uint32_t m_maxMinute;
uint32_t m_maxSecond;
uint32_t m_maxTick;
std::list<TimerNode*> m_tickTimers;
std::vector<TimerSlot*> m_hourSlots;
std::vector<TimerSlot*> m_minuteSlots;
std::vector<TimerSlot*> m_secondSlots;
std::vector<TimerSlot*> m_tickSlots;
std::map<std::string, TimerNode*> m_timerNodeMap;
uint64_t m_totalTicks;
uint32_t m_lastTickSeq;
};
#endif
| [
"letmego163@163.com"
] | letmego163@163.com |
a95d4d9691a06d2f30ab8d6a3c60cd7169551155 | e19427bbcf8a4b899e42e6030c3e17f5d5270245 | /C++Primer5th/C++Primer5th/ListNode.h | 000aede38d39101b8d2526311aa4ba4354d3eb36 | [] | no_license | Brighteststars/C-Primer5th | d5b3aca6285f11068adf3e3848ea75f3bc4e29ab | 3335a14375c7d10083f5408e5b130f5c47dc8cde | refs/heads/master | 2020-03-19T05:50:53.492911 | 2018-06-04T06:22:57 | 2018-06-04T06:22:57 | 135,966,951 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 573 | h | #ifndef LISTNODE_H
#define LISTNODE_H
#define ListNodePosi(T) ListNode<T>*
typedef int Rank;
template< typename T>
struct ListNode{
T data; ListNodePosi(T) pred; ListNodePosi(T) succ;
ListNode(){};
ListNode(T e, ListNodePosi(T) p = NULL, ListNodePosi(T) s = NULL)
: data(e), pred(p), succ(s){}
ListNodePosi(T) insertAsPred(T const& e);
ListNodePosi(T) insertAsSucc(T const& e);
};
template<typename T>
ListNodePosi(T) ListNode<T>::insertAsPred(T const& e){
ListNodePosi(T) x = new ListNode(e, pred, this);
pred->succ = x; pred = x;
return x;
}
#endif | [
"980770546@qq.com"
] | 980770546@qq.com |
27670f8f619d59de5da2f004f9867eb646152706 | 94c6d2cdd9f3bb287f4ddb2dee8bdbf074cc4daf | /arm_compute/core/CL/kernels/CLGEMMLowpQuantizeDownInt32ToUint8ScaleByFloatKernel.h | 900a8c3b5df9399a34fc202342629b3d17446a85 | [
"LicenseRef-scancode-dco-1.1",
"MIT"
] | permissive | styanddty/ComputeLibrary | 60567e42e325808e5f14927f076841c006cc5c69 | 575c81f38edecaa662f3ee45d04ad8efded4fa81 | refs/heads/master | 2022-04-13T22:07:26.520110 | 2020-03-05T16:07:35 | 2020-03-05T16:07:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,699 | h | /*
* Copyright (c) 2018-2019 ARM Limited.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef ARM_COMPUTE_CLGEMMLOWPQUANTIZEDOWNINT32TOUINT8SCALEBYFLOATKERNEL_H
#define ARM_COMPUTE_CLGEMMLOWPQUANTIZEDOWNINT32TOUINT8SCALEBYFLOATKERNEL_H
#include "arm_compute/core/CL/ICLKernel.h"
namespace arm_compute
{
// Forward declarations
class ICLTensor;
/** OpenCL kernel used to quantize down the int32 accumulator values of GEMMLowp to QASYMM8
*
* This kernel takes a final int32 accumulator value (the output of @ref CLGEMMLowpMatrixMultiplyKernel), and processes it to obtain the final QASYMM8 value.
* The following computations will be performed by the kernel:
*
* -# Compute fixed point multiplication between each entry of input by result_fixedpoint_multiplier
* -# Add bias to final result if bias tensor is not a nullptr
* -# Requantize
* -# Add offset to each result
* -# Clamp the value between the specified min and max bounds
* -# Clamp the resulting int32 values to the [0..255] range and cast to QASYMM8.
*/
class CLGEMMLowpQuantizeDownInt32ToUint8ScaleByFloatKernel : public ICLKernel
{
public:
/** Constructor */
CLGEMMLowpQuantizeDownInt32ToUint8ScaleByFloatKernel();
/** Prevent instances of this class from being copied (As this class contains pointers)*/
CLGEMMLowpQuantizeDownInt32ToUint8ScaleByFloatKernel(const CLGEMMLowpQuantizeDownInt32ToUint8ScaleByFloatKernel &) = delete;
/** Prevent instances of this class from being copied (As this class contains pointers)*/
CLGEMMLowpQuantizeDownInt32ToUint8ScaleByFloatKernel &operator=(const CLGEMMLowpQuantizeDownInt32ToUint8ScaleByFloatKernel &) = delete;
/** Allow instances of this class to be moved */
CLGEMMLowpQuantizeDownInt32ToUint8ScaleByFloatKernel(CLGEMMLowpQuantizeDownInt32ToUint8ScaleByFloatKernel &&) = default;
/** Allow instances of this class to be moved */
CLGEMMLowpQuantizeDownInt32ToUint8ScaleByFloatKernel &operator=(CLGEMMLowpQuantizeDownInt32ToUint8ScaleByFloatKernel &&) = default;
/** Initialise the kernel's input and output.
*
* @param[in] input Input tensor. Data type supported: S32
* @param[in] bias Biases tensor. Only shared biases supported and it can be a nullptr if the biases addition is not required.
* Biases are 1D tensor with dimensions [OFM]. Data type supported: Same as @p input.
* @param[out] output Output tensor. Data type supported: Data type supported: QASYMM8
* @param[in] multiplier Float multiplier to be multiplied to each element of the input matrix
* @param[in] offset Offset to be applied to result before converting it back to QASYMM8
* @param[in] min (Optional) Min value used to saturate down the output result before converting back to QASYMM8
* @param[in] max (Optional) Max value used to saturate up the output result before converting back to QASYMM8,
* Along with @p min, this value can be used to implement "rectified linear unit" activation functions
*/
void configure(const ICLTensor *input, const ICLTensor *bias, ICLTensor *output, float multiplier, int offset, int min = 0, int max = 0);
/** Static function to check if given info will lead to a valid configuration of @ref CLGEMMLowpQuantizeDownInt32ToUint8ScaleByFixedPointKernel
*
* @param[in] input Input tensor. Data type supported: S32
* @param[in] bias Biases tensor. Only shared biases supported and it can be a nullptr if the biases addition is not required.
* Biases are 1D tensor with dimensions [OFM]. Data type supported: Same as @p input.
* @param[in] output Output tensor. Data type supported: Data type supported: QASYMM8
* @param[in] min (Optional) Min value used to saturate down the output result before converting back to QASYMM8
* @param[in] max (Optional) Max value used to saturate up the output result before converting back to QASYMM8,
* Along with @p min, this value can be used to implement "rectified linear unit" activation functions
*
* @return a status
*/
static Status validate(const ITensorInfo *input, const ITensorInfo *bias, const ITensorInfo *output, int min = 0, int max = 0);
// Inherited methods overridden:
void run(const Window &window, cl::CommandQueue &queue) override;
private:
const ICLTensor *_input;
const ICLTensor *_bias;
ICLTensor *_output;
};
} // namespace arm_compute
#endif /* ARM_COMPUTE_CLGEMMLOWPQUANTIZEDOWNINT32TOUINT8SCALEBYFLOATKERNEL_H */
| [
"bsgcomp@arm.com"
] | bsgcomp@arm.com |
f18e1fb6b64754d47e20eb1a6dc89313348c1fb1 | 835aa348b329b740bbdc2e26cb07d122248890ce | /include/asio/buffered_write_stream_fwd.hpp | 6cabef81632d33ca781537787858a79a128c3b78 | [
"NCSA"
] | permissive | jayp/Rappel | a81ec6d69fa5242420d6cac253f8e55efe0948c2 | 3ad355fbd3ed82b42e2b108e4eadfc22dd47e425 | refs/heads/master | 2021-01-19T22:02:09.916132 | 2011-10-04T20:24:33 | 2011-10-04T20:24:33 | 2,514,562 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 729 | hpp | //
// buffered_write_stream_fwd.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2006 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_BUFFERED_WRITE_STREAM_FWD_HPP
#define ASIO_BUFFERED_WRITE_STREAM_FWD_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/push_options.hpp"
namespace asio {
template <typename Stream>
class buffered_write_stream;
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_BUFFERED_WRITE_STREAM_FWD_HPP
| [
"jay@patel.org.in"
] | jay@patel.org.in |
99a5122c970fdfe6bab65d8dea7d5041d66af661 | a71582e89e84a4fae2595f034d06af6d8ad2d43a | /tensorflow/lite/kernels/internal/optimized/integer_ops/conv.h | a2fa85bd731e561d4e33501e9b7a06066980da73 | [
"Apache-2.0"
] | permissive | tfboyd/tensorflow | 5328b1cabb3e24cb9534480fe6a8d18c4beeffb8 | 865004e8aa9ba630864ecab18381354827efe217 | refs/heads/master | 2021-07-06T09:41:36.700837 | 2019-04-01T20:21:03 | 2019-04-01T20:26:09 | 91,494,603 | 3 | 0 | Apache-2.0 | 2018-07-17T22:45:10 | 2017-05-16T19:06:01 | C++ | UTF-8 | C++ | false | false | 7,273 | h | /* Copyright 2019 The TensorFlow 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.
==============================================================================*/
#ifndef TENSORFLOW_LITE_KERNELS_INTERNAL_OPTIMIZED_INTEGER_OPS_CONV_H_
#define TENSORFLOW_LITE_KERNELS_INTERNAL_OPTIMIZED_INTEGER_OPS_CONV_H_
#ifdef GEMMLOWP_NEON
#include "fixedpoint/fixedpoint.h"
#include "public/gemmlowp.h"
#include "public/map.h"
#include "tensorflow/lite/kernels/internal/common.h"
#include "tensorflow/lite/kernels/internal/optimized/im2col_utils.h"
#include "tensorflow/lite/kernels/internal/types.h"
namespace tflite {
namespace optimized_integer_ops {
struct GemmlowpOutputPipelineFixedPointPCLhs {
typedef gemmlowp::VectorMap<const int32, gemmlowp::VectorShape::Col>
ColVectorMap;
typedef std::tuple<gemmlowp::OutputStageBiasAddition<ColVectorMap>,
gemmlowp::OutputStageScaleInt32ByFixedPointAndExponentPC<
gemmlowp::VectorShape::Col>,
gemmlowp::OutputStageClamp,
gemmlowp::OutputStageSaturatingCastToInt8>
Pipeline;
static Pipeline MakeExp(const int32* bias_data, int output_rows,
const int32 output_offset,
const int32* output_multiplier,
const int* output_left_shift,
int32 output_activation_min,
int32 output_activation_max) {
ColVectorMap bias_vector(bias_data, output_rows);
gemmlowp::OutputStageBiasAddition<ColVectorMap> bias_addition_stage;
bias_addition_stage.bias_vector = bias_vector;
gemmlowp::OutputStageScaleInt32ByFixedPointAndExponentPC<
gemmlowp::VectorShape::Col>
quantize_down_stage;
quantize_down_stage.result_offset_after_shift = output_offset;
quantize_down_stage.result_fixedpoint_multiplier =
ColVectorMap(output_multiplier, output_rows);
quantize_down_stage.result_exponent =
ColVectorMap(output_left_shift, output_rows);
gemmlowp::OutputStageClamp clamp_stage;
clamp_stage.min = output_activation_min;
clamp_stage.max = output_activation_max;
gemmlowp::OutputStageSaturatingCastToInt8 saturating_cast_stage;
return std::make_tuple(bias_addition_stage, quantize_down_stage,
clamp_stage, saturating_cast_stage);
}
};
// Fixed-point per-channel-quantization convolution reference kernel.
inline void ConvPerChannel(
const ConvParams& params, const int32* output_multiplier,
const int32* output_shift, const RuntimeShape& input_shape,
const int8* input_data, const RuntimeShape& filter_shape,
const int8* filter_data, const RuntimeShape& bias_shape,
const int32* bias_data, const RuntimeShape& output_shape, int8* output_data,
const RuntimeShape& im2col_shape, int8* im2col_data,
gemmlowp::GemmContext* gemm_context) {
gemmlowp::ScopedProfilingLabel label("Conv/8bit");
const int stride_width = params.stride_width;
const int stride_height = params.stride_height;
const int dilation_width_factor = params.dilation_width_factor;
const int dilation_height_factor = params.dilation_height_factor;
const int32 input_offset = params.input_offset;
const int32 output_offset = params.output_offset;
// Set min and max value of the output.
static constexpr int32 output_activation_min =
std::numeric_limits<int8_t>::min();
static constexpr int32 output_activation_max =
std::numeric_limits<int8_t>::max();
TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4);
TFLITE_DCHECK_EQ(filter_shape.DimensionsCount(), 4);
TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4);
const int8* gemm_input_data = nullptr;
const RuntimeShape* gemm_input_shape = nullptr;
const int filter_width = filter_shape.Dims(2);
const int filter_height = filter_shape.Dims(1);
const bool need_dilated_im2col =
dilation_width_factor != 1 || dilation_height_factor != 1;
const bool need_im2col = stride_width != 1 || stride_height != 1 ||
filter_width != 1 || filter_height != 1;
const int8 input_zero_point = -input_offset;
TFLITE_DCHECK_GE(input_zero_point, output_activation_min);
TFLITE_DCHECK_LE(input_zero_point, output_activation_max);
const uint8 zero_point_byte =
*reinterpret_cast<const uint8*>(&input_zero_point);
if (need_dilated_im2col) {
TFLITE_DCHECK(im2col_data);
optimized_ops::DilatedIm2col(params, zero_point_byte, input_shape,
input_data, filter_shape, output_shape,
im2col_data);
gemm_input_data = im2col_data;
gemm_input_shape = &im2col_shape;
} else if (need_im2col) {
TFLITE_DCHECK(im2col_data);
optimized_ops::Im2col(params, filter_height, filter_width, zero_point_byte,
input_shape, input_data, im2col_shape, im2col_data);
gemm_input_data = im2col_data;
gemm_input_shape = &im2col_shape;
} else {
TFLITE_DCHECK(!im2col_data);
gemm_input_data = input_data;
gemm_input_shape = &input_shape;
}
const int gemm_input_rows = gemm_input_shape->Dims(3);
const int gemm_input_cols = FlatSizeSkipDim(*gemm_input_shape, 3);
const int filter_rows = filter_shape.Dims(0);
const int filter_cols = FlatSizeSkipDim(filter_shape, 0);
const int output_rows = output_shape.Dims(3);
// See b/79927784.
// const int output_cols = FlatSizeSkipDim(output_shape, 3);
const int output_cols =
output_shape.Dims(0) * output_shape.Dims(1) * output_shape.Dims(2);
TFLITE_DCHECK_EQ(output_rows, filter_rows);
TFLITE_DCHECK_EQ(output_cols, gemm_input_cols);
TFLITE_DCHECK_EQ(filter_cols, gemm_input_rows);
TFLITE_DCHECK_EQ(bias_shape.FlatSize(), output_rows);
gemmlowp::MatrixMap<const int8, gemmlowp::MapOrder::RowMajor> filter_matrix(
filter_data, filter_rows, filter_cols);
gemmlowp::MatrixMap<const int8, gemmlowp::MapOrder::ColMajor> input_matrix(
gemm_input_data, gemm_input_rows, gemm_input_cols);
gemmlowp::MatrixMap<int8, gemmlowp::MapOrder::ColMajor> output_matrix(
output_data, output_rows, output_cols);
const auto& output_pipeline = GemmlowpOutputPipelineFixedPointPCLhs::MakeExp(
bias_data, output_rows, output_offset, output_multiplier, output_shift,
output_activation_min, output_activation_max);
gemmlowp::GemmWithOutputPipeline<
int8, int8, gemmlowp::SignedL8R8WithLhsNonzeroBitDepthParams>(
gemm_context, filter_matrix, input_matrix, &output_matrix,
/*filter_offset*/ 0, input_offset, output_pipeline);
}
} // namespace optimized_integer_ops
} // namespace tflite
#endif // GEMMLOWP_NEON
#endif // TENSORFLOW_LITE_KERNELS_INTERNAL_OPTIMIZED_INTEGER_OPS_CONV_H_
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
bd74ef1310442f6b076ad4e86573e795391014c3 | 3ed4c2da885a01a4d845088307ff6c241590b294 | /IoT/Assignment_3/Assignment_3_Build_1/Assignment_3_Build_1.ino | bf6fb3069ddd2ff24fd27b1128252a0f7112de2b | [] | no_license | Moltenbrown/Computer-Science-Projects | 033b410fb3b53180b559d82511972994ae247ff8 | 4d09c752004bdd6d04aa0a7f15132dc60d3ac9eb | refs/heads/master | 2021-06-27T00:28:26.504303 | 2020-11-01T03:01:45 | 2020-11-01T03:01:45 | 164,078,244 | 0 | 0 | null | 2020-10-13T21:40:06 | 2019-01-04T08:11:42 | Python | UTF-8 | C++ | false | false | 910 | ino | /*
Code from https://learn.adafruit.com/adafruit-arduino-lesson-15-dc-motor-reversing/arduino-code.
*/
int enablePin = 11;
int in1Pin = 10;
int in2Pin = 9;
int switchPin = 7;
int potPin = A0;
void setup()
{
Serial.begin(9600);
Serial.println("Starting the motor.");
pinMode(in1Pin, OUTPUT);
pinMode(in2Pin, OUTPUT);
pinMode(enablePin, OUTPUT);
pinMode(switchPin, INPUT_PULLUP);
}
void loop()
{
//int speed = analogRead(potPin) / 4;
int speed = analogRead(potPin);
speed = map(speed, 0, 1023, 0, 255);
boolean reverse = digitalRead(switchPin);
setMotor(speed, reverse);
}
void setMotor(int speed, boolean reverse)
{
if(reverse) {
Serial.print("going forward at ");
Serial.println(speed);
} else {
Serial.print("going backwards at ");
Serial.println(speed);
}
analogWrite(enablePin, speed);
digitalWrite(in1Pin, ! reverse);
digitalWrite(in2Pin, reverse);
}
| [
"noreply@github.com"
] | noreply@github.com |
f6e16d186b2c0d9ea9a581e293296277e26e02d5 | 881c3f40f668d1b512d0da396bf306a66b1bb248 | /Chunkhandler/chunkdat.h | 41f567be066358f73b844ae4be5a5f6dcac0fd1d | [] | no_license | seger22/CloudSync | f4349055138c052b9e23924b8d8b0d4acb5c5194 | 3cd49e55b91a3b07766f01a043878c1244c1cce1 | refs/heads/master | 2020-04-04T00:27:49.353670 | 2013-12-07T03:32:29 | 2013-12-07T03:32:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 197 | h | #ifndef CHUNKDAT_H
#define CHUNKDAT_H
class ChunkDat
{
public:
enum{max_length=66000};
char data[max_length]={0};
int chunk_size=0;
ChunkDat();
private:
};
#endif // CHUNKDAT_H
| [
"cloudsync@ymail.com"
] | cloudsync@ymail.com |
b786b9b0a12536c43916a00c6daa8a9672f4a78f | 8e3f3dd878fd7a4866cb7fd42eb827a4ab27052f | /Task5.cpp | a10c3ad7985506e212fdfff3021ea21ad241a38e | [] | no_license | Devang-Shah-49/Codestars | 2563ac2e84a4eeeef3b4ab5fe8a1a5b6ab418d24 | f944daacbc0be8d85e04a5441e88af90b51a42f8 | refs/heads/main | 2023-07-16T02:52:32.451474 | 2021-09-01T19:14:42 | 2021-09-01T19:14:42 | 401,292,614 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 535 | cpp | #include <bits/stdc++.h>
using namespace std;
int A[100], B[100];
int main(){
int n, i, j;
cout << "Enter the number of elements: ";
cin >> n;
cout << "Enter the elements: ";
for (int z=0; z<n; z++){
cin >> A[z];
B[z] = B[z-1]+A[z];
}
cout << "Prefix Sum array is: ";
for (int z=0; z<n; z++){
cout << B[z] << " ";
}
cout << "\nEnter i: ";
cin >> i;
cout << "Enter j: ";
cin >> j;
cout << "Answer: " << B[j]-B[i-1];
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
057b2940780c8e80cbbbc8f85a0805640e5760ef | 6e0b25bf4106b09a103ad7bfeb2fe174e46c9176 | /pr9/re10/8.6/phi | 1c34f600e8de5c73520501782ded672c1669931e | [] | no_license | franterminator/OpenFoamCaminos | 3bc1d207bed77408f31ef1846a35794fab8cd3d5 | 5556bc3ddf9cf8aa5a661cd3af74a2b2d76d3471 | refs/heads/master | 2020-04-16T04:28:19.657010 | 2019-01-11T15:58:00 | 2019-01-11T15:58:00 | 165,268,264 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,933 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 5.x |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class surfaceScalarField;
location "8.6";
object phi;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 3 -1 0 0 0 0];
internalField nonuniform List<scalar>
760
(
0.00134817681
-0.00134817705
0.00245763987
-0.00110946306
0.00313513474
-0.000677494877
0.00355971575
-0.00042458102
0.00383225133
-0.000272535573
0.00400945217
-0.000177200827
0.00412521453
-0.000115762341
0.0041992171
-7.40025769e-05
0.00424243237
-4.32152868e-05
0.00426055358
-1.81212272e-05
0.00425562235
4.93124509e-06
0.00422675779
2.88645828e-05
0.00416938941
5.73683779e-05
0.00407358505
9.58043454e-05
0.00391995093
0.000153634107
0.00367201929
0.000247931652
0.00326316024
0.000408859073
0.00257264078
0.000690519456
0.00140850174
0.00116413902
0.00140850172
-5.46951743e-05
-0.00129348187
0.000412592753
-0.00157675098
0.0010300299
-0.00129493202
0.00157871394
-0.000973265072
0.00201483274
-0.000708654391
0.00234477728
-0.000507145378
0.00258511634
-0.000356101378
0.00275126944
-0.00024015566
0.00285456782
-0.000146513665
0.00290179533
-6.53487576e-05
0.0028953666
1.13599628e-05
0.00283293036
9.13008255e-05
0.00270712575
0.000183173011
0.00250436376
0.000298566342
0.00220410989
0.000453887962
0.00178090171
0.000671139809
0.00121756799
0.000972192814
0.000552812571
0.00135527491
1.30664937e-05
0.00170388511
0.0014215682
-0.000271734622
-0.00102174726
-0.000221026537
-0.00162745905
7.13678719e-05
-0.00158732641
0.000446285719
-0.00134818291
0.000812489733
-0.00107485842
0.00112929929
-0.00082395496
0.00138207833
-0.000608880412
0.0015680079
-0.000426085208
0.001688377
-0.000266882739
0.00174468456
-0.000121656333
0.00173678976
1.92547367e-05
0.00166213441
0.00016595617
0.00151571289
0.000329594556
0.00129125426
0.000523024992
0.000985011706
0.000760130505
0.000605009647
0.00105114184
0.000189850694
0.00138735176
-0.00016004508
0.0017051707
-0.00026164062
0.00180548067
0.00115992757
-0.000227941574
-0.0007938057
-0.0003611973
-0.00149420332
-0.000308328185
-0.0016401955
-0.000134821156
-0.00152168992
8.92094345e-05
-0.00129888902
0.000314971897
-0.00104971745
0.000513263008
-0.000807171541
0.000668300026
-0.000581122211
0.000771990353
-0.000370573033
0.000820036151
-0.000169702122
0.000809727668
2.95631938e-05
0.000739201016
0.000236482797
0.00060793566
0.000460859923
0.000419110886
0.000711849801
0.000184524351
0.000994717052
-6.71911675e-05
0.00130285733
-0.000280617557
0.00160077812
-0.000369418494
0.00179397164
-0.000246993635
0.00168305584
0.000912933951
-0.000168965209
-0.000624840496
-0.000352016185
-0.00131115237
-0.000431557679
-0.001560654
-0.000408908955
-0.00154433862
-0.000319435135
-0.00138836282
-0.000200095146
-0.00116905746
-7.98100728e-05
-0.000927456649
2.15782457e-05
-0.000682510539
9.14287056e-05
-0.000440423462
0.000122135418
-0.000200408802
0.000109757226
4.19413771e-05
5.3645717e-05
0.000292594267
-4.27490253e-05
0.000557254648
-0.000169694039
0.000838794845
-0.000307652412
0.00113267546
-0.000423468605
0.00141867353
-0.00047002487
0.00164733435
-0.000397824839
0.00172177158
-0.000196431042
0.00148166205
0.000716502934
-0.00012419212
-0.000500648363
-0.000308335638
-0.00112700888
-0.000450494113
-0.00141849554
-0.00052320402
-0.00147162869
-0.000535391032
-0.00137617577
-0.000508160778
-0.0011962877
-0.000463156864
-0.000972460594
-0.000418060945
-0.000727606496
-0.000385619022
-0.000472865378
-0.000373912051
-0.000212115727
-0.00038672789
5.47572415e-05
-0.000423459477
0.000329325826
-0.000478356384
0.000612151508
-0.000539178293
0.00089961675
-0.000585818877
0.00117931609
-0.00059051231
0.001423367
-0.000523085111
0.00157990714
-0.000366699085
0.00156538552
-0.000150586
0.00126554894
0.00056591695
-9.45729117e-05
-0.000406075425
-0.000264649729
-0.000956932076
-0.000430738393
-0.00125240691
-0.000556976961
-0.00134539014
-0.000636793215
-0.00129635948
-0.000678141728
-0.00115493914
-0.000693943884
-0.000956658441
-0.00069692923
-0.000724621198
-0.000697274075
-0.000472520565
-0.000701661764
-0.000207728009
-0.000712860683
6.59562168e-05
-0.000729336321
0.000345801475
-0.000744753793
0.000627568932
-0.000747580321
0.000902443231
-0.00072146992
0.0011532057
-0.000647843383
0.00134974051
-0.000512876896
0.00144494068
-0.000321206262
0.00137371487
-0.000116485703
0.00106082835
0.000449431237
-7.53437213e-05
-0.000330731679
-0.00022820679
-0.000804068998
-0.00039835365
-0.00108226008
-0.000550539541
-0.00119320428
-0.000670626472
-0.00117627255
-0.000757578331
-0.00106798723
-0.000816784768
-0.000897451965
-0.00085558741
-0.00068581858
-0.000880624304
-0.000447483732
-0.000896360351
-0.000191991982
-0.000904270087
7.38660037e-05
-0.000902360273
0.000343891721
-0.000884972168
0.000610180822
-0.000843104157
0.000860575159
-0.000765820216
0.00107592172
-0.000643664756
0.00122758507
-0.000475103932
0.00127637991
-0.000276309823
0.00117492079
-9.21328467e-05
0.000876651363
0.000357298364
-6.22883117e-05
-0.000268443362
-0.000198541299
-0.000667815976
-0.000362893625
-0.000917907758
-0.000523850721
-0.00103224723
-0.000664415252
-0.00103570806
-0.000778128938
-0.000954273529
-0.00086481215
-0.000810768689
-0.000927165425
-0.000623465275
-0.000968399659
-0.000406249543
-0.000990721233
-0.000169670475
-0.000994436397
7.75811652e-05
-0.000977525732
0.000326981123
-0.000935694961
0.000568350108
-0.000863101205
0.000787981385
-0.000754123162
0.00096694361
-0.000606626334
0.0010800882
-0.000426950424
0.00109670402
-0.000236038281
0.000984008696
-7.4349004e-05
0.000714962109
0.000282949343
-5.27689939e-05
-0.000215674389
-0.000173812788
-0.000546772141
-0.000327557374
-0.000764163135
-0.000486865953
-0.000872938667
-0.000634380195
-0.000888193873
-0.000760757889
-0.000827895868
-0.000862116673
-0.000709409863
-0.000937654726
-0.00054792715
-0.000987783178
-0.000356121076
-0.00101282395
-0.000144629769
-0.00101222279
7.69799424e-05
-0.000984240728
0.000298999071
-0.000926163054
0.00051027251
-0.000835158774
0.000696977157
-0.000709976063
0.000841760874
-0.000553597336
0.000923709416
-0.000376677004
0.000919783657
-0.000200960062
0.000808291771
-6.08626228e-05
0.000574864704
0.00022208673
-4.52979569e-05
-0.000170376471
-0.000152453995
-0.000439616086
-0.000293299603
-0.000623317475
-0.000444763067
-0.000721475169
-0.00059034582
-0.000742611153
-0.000719473376
-0.000698768382
-0.000826046384
-0.000602836876
-0.000906878216
-0.000467095257
-0.000960347536
-0.000302651681
-0.000985403107
-0.000119574201
-0.000980963157
7.25399148e-05
-0.000945732148
0.000263768001
-0.000878480058
0.000443020444
-0.000778855047
0.000597352223
-0.000648784017
0.00071168989
-0.000494403527
0.000769328903
-0.000328204161
0.000753584237
-0.000170678388
0.000650765969
-5.02806697e-05
0.000454466997
0.000171806085
-3.90621942e-05
-0.000131314307
-0.00013340383
-0.000345274474
-0.000260349986
-0.000496371288
-0.000400388949
-0.000581436144
-0.000538431153
-0.000604568924
-0.000663692768
-0.00057350682
-0.000768938078
-0.00049759164
-0.000849523118
-0.000386510222
-0.000902500933
-0.00024967379
-0.000925934052
-9.61410106e-05
-0.000918488838
6.50946839e-05
-0.000879356201
0.000224635281
-0.000808535371
0.00037219956
-0.000707505294
0.000496322174
-0.00058026168
0.000584446346
-0.000434588308
0.000623655571
-0.000283248276
0.000602244186
-0.000144573371
0.000512091021
-4.17552014e-05
0.000351648807
0.0001300509
-3.36093945e-05
-9.7704908e-05
-0.000115973521
-0.000262910398
-0.00022868592
-0.000383658907
-0.000355331155
-0.000454790864
-0.00048244846
-0.00047745155
-0.000599656604
-0.000456298664
-0.000699324725
-0.000397923587
-0.000776050516
-0.000309784503
-0.000826127664
-0.000199596634
-0.000847124127
-7.51444634e-05
-0.000837646043
5.56166643e-05
-0.000797332171
0.000184321385
-0.000727102537
0.000301969847
-0.000629656464
0.000398876054
-0.000510163492
0.000464953399
-0.000377005131
0.00049049727
-0.000242314842
0.00046755393
-0.000121978222
0.000391754388
-3.47332198e-05
0.000264403776
9.53176738e-05
-2.86574594e-05
-6.90474094e-05
-9.96602183e-05
-0.00019190768
-0.000198117032
-0.000285202149
-0.000310357597
-0.000342550309
-0.000424616069
-0.000363193018
-0.000531265853
-0.00034964881
-0.000622765411
-0.000306424029
-0.000693446631
-0.00023910336
-0.00073925885
-0.000153784481
-0.000757558065
-5.68452298e-05
-0.000747003437
4.50621195e-05
-0.000707597896
0.000144915899
-0.000640884371
0.000235256296
-0.000550277073
0.000308268686
-0.000441462375
0.000356138661
-0.000322745872
0.000371780787
-0.000205166577
0.000349974681
-0.000102185424
0.000288773262
-2.88024077e-05
0.000191020753
6.65152475e-05
-2.39811818e-05
-4.50661794e-05
-8.39974065e-05
-0.000131891454
-0.000168257095
-0.000200942513
-0.000265595521
-0.000245211939
-0.000365935626
-0.000262852911
-0.000460594493
-0.000254989874
-0.000542423492
-0.000224594965
-0.000605821281
-0.000175705583
-0.000646681734
-0.000112924106
-0.000662339419
-4.11876037e-05
-0.000651561355
3.42840799e-05
-0.000614612929
0.000107967549
-0.000553400601
0.000174044015
-0.000471663873
0.000226531936
-0.00037515401
0.000259628743
-0.000271701973
0.000268328718
-0.000171058868
0.000249331589
-8.44170632e-05
0.000202131489
-2.35998541e-05
0.000130203562
4.29153825e-05
-1.93492222e-05
-2.5716935e-05
-6.84700061e-05
-8.27706278e-05
-0.000138506726
-0.000130905801
-0.000220638079
-0.000163080644
-0.000306428445
-0.000177062599
-0.000388228785
-0.000173189524
-0.000459474166
-0.000153349512
-0.000514859768
-0.000120319923
-0.000550429761
-7.73541309e-05
-0.000563627571
-2.7989866e-05
-0.000553348457
2.40049181e-05
-0.00052001645
7.46355647e-05
-0.000465682602
0.00011971023
-0.000394114886
0.000154964257
-0.000310822969
0.00017633681
-0.000222941269
0.000180446977
-0.000138894636
0.000165284933
-6.78135248e-05
0.000131050386
-1.87621101e-05
8.11521667e-05
2.41532762e-05
-1.45055542e-05
-1.12114e-05
-5.25211019e-05
-4.47550267e-05
-0.000108122784
-7.53040806e-05
-0.00017468777
-9.65156702e-05
-0.000245343247
-0.000106407182
-0.00031352085
-0.000105011971
-0.000373387925
-9.3482422e-05
-0.000420129415
-7.35783667e-05
-0.000450116039
-4.73674575e-05
-0.00046100906
-1.70968634e-05
-0.000451841642
1.48374393e-05
-0.000423096931
4.58908154e-05
-0.000376775984
7.33893001e-05
-0.000316426443
9.4614765e-05
-0.00024707953
0.000106989926
-0.000175030342
0.000108397779
-0.000107403064
9.7657628e-05
-5.14858554e-05
7.5133162e-05
-1.3914627e-05
4.35809426e-05
1.02386593e-05
-9.20283588e-06
-2.00860815e-06
-3.56847556e-05
-1.82730748e-05
-7.6435518e-05
-3.4553267e-05
-0.000126810996
-4.61401568e-05
-0.000181408049
-5.18101444e-05
-0.000234817156
-5.16029204e-05
-0.000282132256
-4.61673643e-05
-0.000319263558
-3.64470487e-05
-0.000343116501
-2.35144577e-05
-0.000351700018
-8.51330858e-06
-0.000344207001
7.34440738e-06
-0.000321084438
2.27682048e-05
-0.000284086178
3.63910112e-05
-0.000236279544
4.68081434e-05
-0.000181958568
5.26689846e-05
-0.000126403734
5.28429655e-05
-7.54285342e-05
4.66824239e-05
-3.46816303e-05
3.43862421e-05
-8.71391418e-06
1.7613218e-05
1.52475007e-06
-3.43755172e-06
1.42890714e-06
-1.80439009e-05
-3.66672205e-06
-4.34060499e-05
-9.19109018e-06
-7.64336588e-05
-1.31125018e-05
-0.000113187135
-1.50566374e-05
-0.0001496651
-1.51249662e-05
-0.000182251554
-1.35809543e-05
-0.000207952868
-1.07457653e-05
-0.000224514106
-6.95320722e-06
-0.000230484751
-2.54262287e-06
-0.000225272626
2.13230938e-06
-0.000209197071
6.69263943e-06
-0.000183535362
1.07292715e-05
-0.000150536822
1.38095841e-05
-0.000113368299
1.55004685e-05
-7.59397556e-05
1.54144421e-05
-4.25472146e-05
1.32898957e-05
-1.7276734e-05
9.11575985e-06
-3.10385901e-06
3.4403364e-06
-1.57911009e-06
1.4288938e-06
-2.23785904e-06
-1.14289795e-05
-2.4541484e-05
-3.95980926e-05
-5.47230255e-05
-6.8303974e-05
-7.90497651e-05
-8.60030016e-05
-8.85456284e-05
-8.64132967e-05
-7.97206327e-05
-6.89913563e-05
-5.51817863e-05
-3.9681334e-05
-2.42668962e-05
-1.09769942e-05
-1.86122745e-06
1.57911133e-06
)
;
boundaryField
{
walls
{
type calculated;
value uniform 0;
}
mov_wall
{
type calculated;
value uniform 0;
}
empty
{
type empty;
value nonuniform 0();
}
}
// ************************************************************************* //
| [
"franterminator@hotmail.com"
] | franterminator@hotmail.com | |
908cd8a75a36766d98bca99d0b2dfa8c36e81223 | fc1cdf47bbebea45cd324ff6f4064cc74ebf1ff7 | /media/src/speex/speexcodec.cpp | 1840a39080ec0a2dde948679e2cec24ce1b438b5 | [] | no_license | omusico/mcumediaserver | 66e9439388b0618768e11f04a1b5bd098828805f | e83c51655bd97a4c4b023a28f463259b0d8aa268 | refs/heads/master | 2020-11-30T01:46:29.517067 | 2012-08-05T06:53:49 | 2012-08-05T06:53:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,864 | cpp | #include <string.h>
#include <libavcodec/avcodec.h>
#include "log.h"
#include "speexcodec.h"
SpeexCodec::SpeexCodec(): AudioCodec()
{
//Set number of input frames for codec
numFrameSamples = 160;
///Set type
type = SPEEX16;
//+------+---------------+-------------------+------------------------+
//| mode | Speex quality | wideband bit-rate | ultra wideband |
//| | | | bit-rate |
//+------+---------------+-------------------+------------------------+
//| 0 | 0 | 3.95 kbit/s | 5.75 kbit/s |
//| 1 | 1 | 5.75 kbit/s | 7.55 kbit/s |
//| 2 | 2 | 7.75 kbit/s | 9.55 kbit/s |
//| 3 | 3 | 9.80 kbit/s | 11.6 kbit/s |
//| 4 | 4 | 12.8 kbit/s | 14.6 kbit/s |
//| 5 | 5 | 16.8 kbit/s | 18.6 kbit/s |
//| 6 | 6 | 20.6 kbit/s | 22.4 kbit/s |
//| 7 | 7 | 23.8 kbit/s | 25.6 kbit/s |
//| 8 | 8 | 27.8 kbit/s | 29.6 kbit/s |
//| 9 | 9 | 34.2 kbit/s | 36.0 kbit/s |
//| 10 | 10 | 42.2 kbit/s | 44.0 kbit/s |
//+------+---------------+-------------------+------------------------+
int quality = 5;
enc_frame_size = 160;
int err = 0;
// init encoder in wide band
encoder = speex_encoder_init(&speex_wb_mode);
//Set quality
speex_encoder_ctl(encoder, SPEEX_SET_QUALITY, &quality);
//The resampler to convert to WB
resampler = speex_resampler_init(1, 8000, 16000, 10, &err);
//The resampler to convert from WB
wbresampler = speex_resampler_init(1, 16000, 8000, 10, &err);
//Init bits
speex_bits_init(&encbits);
// get frame sizes
speex_mode_query(&speex_wb_mode, SPEEX_MODE_FRAME_SIZE, &enc_frame_size);
int rate = 16000;
speex_encoder_ctl(encoder, SPEEX_SET_SAMPLING_RATE, &rate);
// init decoder
decoder = speex_decoder_init(&speex_wb_mode);
speex_bits_init(&decbits);
speex_bits_reset(&decbits);
// get frame sizes
speex_mode_query(&speex_wb_mode, SPEEX_MODE_FRAME_SIZE, &enc_frame_size);
speex_decoder_ctl(decoder, SPEEX_GET_FRAME_SIZE, &dec_frame_size);
}
SpeexCodec::~SpeexCodec()
{
speex_bits_destroy(&decbits);
speex_bits_destroy(&encbits);
speex_encoder_destroy(encoder);
speex_decoder_destroy(decoder);
}
int SpeexCodec::Encode (WORD *in,int inLen,BYTE* out,int outLen)
{
WORD wbBuffer[512];
DWORD wblen = 512;
//check lengths
if ((inLen != enc_frame_size/2) || (outLen < enc_frame_size))
return Error("-speex encode ((inLen[%d] != numFrameSamples[%d]) || (outLen[%d] < enc_frame_size[%d]))\n", inLen, enc_frame_size/2, outLen, enc_frame_size);
//Reset
speex_bits_reset(&encbits);
//Transrate
speex_resampler_process_int(resampler,0,(spx_int16_t*)in,(spx_uint32_t*)&inLen,(spx_int16_t*)wbBuffer,(spx_uint32_t*)&wblen);
//Encode
speex_encode_int(encoder, (spx_int16_t*)wbBuffer, &encbits);
///Paste
return speex_bits_write_whole_bytes(&encbits, (char*)out, outLen);
}
int SpeexCodec::Decode (BYTE *in, int inLen, WORD* out, int outLen)
{
WORD wbBuffer[512];
DWORD wbSize = 512;
DWORD wbLen = dec_frame_size;
//Nothing to decode
if (!inLen)
//Exit
return 0;
//check lengths
if (outLen < dec_frame_size)
return Error("-speex decode outLen[%d] < dec_frame_size[%d] * 2\n", outLen, dec_frame_size);
//Read bits
speex_bits_read_from(&decbits, (char*)in, inLen);
//Decode
if (speex_decode_int(decoder, &decbits, (spx_int16_t*)wbBuffer)<0)
return Error("-speex speex_decode_int error");
//Transrate
speex_resampler_process_int(wbresampler,0,(spx_int16_t*)wbBuffer,(spx_uint32_t*)&wbLen,(spx_int16_t*)out,(spx_uint32_t*)&outLen);
//Exit
return outLen;
}
| [
"myoldman@163.com"
] | myoldman@163.com |
6b3d6b69a9162b655cbee2a918b0bf8a2762dc2c | a35b30a7c345a988e15d376a4ff5c389a6e8b23a | /boost/asio/ssl/context_base.hpp | eee2279b1360428eac659698cffbd3ab02c1f8c3 | [] | no_license | huahang/thirdparty | 55d4cc1c8a34eff1805ba90fcbe6b99eb59a7f0b | 07a5d64111a55dda631b7e8d34878ca5e5de05ab | refs/heads/master | 2021-01-15T14:29:26.968553 | 2014-02-06T07:35:22 | 2014-02-06T07:35:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 67 | hpp | #include "thirdparty/boost_1_55_0/boost/asio/ssl/context_base.hpp"
| [
"liuhuahang@xiaomi.com"
] | liuhuahang@xiaomi.com |
fac716f26e8f78cf27f36ba15b976893c08d6376 | f4a2a403284ddbcc560d8ac4afb4747feb09cebe | /Data Structures/TREES/DELETION IN BINARY SEARCH TREE.cpp | 8ff0567d4b24c6474f764d66d9fe0b5a33dc8b2b | [] | no_license | Sanil15/Data-Structures-and-Fundamental-Programs | d17db01c7a183da718c9abd34826eded643b5882 | b6a0096a55f17079269ae13f46f29d0f7367247f | refs/heads/master | 2021-01-22T01:21:54.232806 | 2016-08-17T22:36:22 | 2016-08-17T22:36:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,686 | cpp | #include<iostream>
#include<stdlib.h>
using namespace std;
struct node{
node* left;
node* right;
int value;
};
node *glob=NULL;
node* search(node *start,int val)
{
node *tem;
if(glob==NULL)
{ glob=start; }
if(start== NULL){
return NULL;
}
else if(start->value==val)
return start;
else
{
if(start->value < val){
glob=start;
tem = search(start->right, val);
}
else{
glob=start;
tem = search(start->left, val);
}
return tem;
}
}
int del(node **start, int val)
{
int chk=0;
node* temp;
node* temp1;
node* p;
temp=search((*start),val);
cout<<temp->value<<endl;
cout<<glob->value;
if(temp->left==NULL && temp->right==NULL)
{
if(glob->left==temp)
glob->left=NULL;
else
glob->right=NULL;
delete temp; //start will be covered in same case \
return 1;
}
else if(temp->right!=NULL && temp->left!=NULL)
{
p=temp->right;
if(p->left!=NULL)
{
while(p!=NULL)
{
glob=temp1;
temp1=p;
p=p->left;
}
temp->value=temp1->value;
glob->left=NULL;
delete temp1;
return 1;
}
else
chk++;
p=temp->left;
if(p->right!=NULL)
{
while(p!=NULL)
{
glob=temp1;
temp1=p;
p=p->right;
}
temp->value=temp1->value;
glob->right=NULL;
delete temp1;
return 1;
}
else
chk++;
if(chk==2 )//SKEWED CASE
{
p=temp->right;
temp->value=p->value;
temp->right=p->right;
delete p;
return 1;
}
}
else if(temp->left==NULL)
{
if(temp==(*start))
{
*start=temp->right;
delete temp;
}
else
{
p=temp->right;
temp->value=p->value;
temp->right=p;
delete p;
}
return 1;
}
else if(temp->right==NULL)
{
if(temp==(*start))
{
*start=temp->left;
delete temp;
}
else
{
p=temp->left;
temp->value=p->value;
temp->left=p;
delete p;
}
return 1;
}
return 0;
}
void insert(node **start)
{
node* temp=new node;
cout<<"ENTER THE VALUE OF NODE";
cin>>temp->value;
temp->right = NULL;
temp->left = NULL;
if((*start)==NULL)
{
(*start)=temp;
}
else if(temp->value > (*start)->value)
{
if( (*start)->right==NULL )
(*start)->right=temp;
else
insert(&(*start)->right);
}
else
{
if((*start)->left==NULL)
(*start)->left=temp;
else
insert(&(*start)->left);
}
}
void display(node* start)
{
if(start!=NULL)
{
display(start->left);
cout<<start->value<<" ";
display(start->right);
}
}
int main()
{
node* start=NULL;
int a;
while(a!=0)
{
cout<<"\n\n\nENTER 1 TO INSERT A NODE\n";
cout<<"\nENTER 2 TO DISPLAY INFIX\n";
cout<<"\nENTER 3 TO DELETE\n";
cout<<"\nENTER 4 TO SEARCH\n";
cout<<"\nENTER 0 TO EXIT\n";
cin>>a;
if(a==1)
insert(&start);
else if(a==2)
display(start);
else if(a==3)
{
int d;
cout<<"ENTER VALUE TO DELETE ";
cin>>d;
del(&start,d);
}
else if(a==4)
{
int d;
cout<<"ENTER VALUE TO SEARCH ";
cin>>d;
node* t=search(start,d);
cout<<t->value<<endl;
cout<<glob->value;
}
}
return 0;
}
| [
"sanil.jain15@gmail.com"
] | sanil.jain15@gmail.com |
ab3f60249b25c88f1269f79480eb66459d74b632 | 8f50c262f89d3dc4f15f2f67eb76e686b8f808f5 | /PhysicsAnalysis/AnalysisCommon/HDF5Utils/Root/common.cxx | 5e41130d7adfffcd945ad94603dea8b08869f1c6 | [
"Apache-2.0"
] | permissive | strigazi/athena | 2d099e6aab4a94ab8b636ae681736da4e13ac5c9 | 354f92551294f7be678aebcd7b9d67d2c4448176 | refs/heads/master | 2022-12-09T02:05:30.632208 | 2020-09-03T14:03:18 | 2020-09-03T14:03:18 | 292,587,480 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,173 | cxx | // this is -*- C++ -*-
/*
Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration
*/
#include "HDF5Utils/Writer.h"
#include "H5Cpp.h"
#include <cassert>
#include <iostream> // for printing errors in the destructor
namespace H5Utils {
namespace internal {
// packing utility
H5::CompType packed(H5::CompType in) {
// TODO: Figure out why a normal copy constructor doesn't work here.
// The normal one seems to create shallow copies.
H5::CompType out(H5Tcopy(in.getId()));
out.pack();
return out;
}
void printDestructorError(const std::string& msg) {
std::cerr << "ERROR: an exception was thrown in the destructor of an "
"HDF5 file, the output buffer may be corrupted";
std::cerr << " (error message: " << msg << ")" << std::endl;
}
// new functions
H5::DataSpace getUnlimitedSpace(const std::vector<hsize_t>& extent) {
std::vector<hsize_t> initial{0};
initial.insert(initial.end(), extent.begin(), extent.end());
std::vector<hsize_t> eventual{H5S_UNLIMITED};
eventual.insert(eventual.end(), extent.begin(), extent.end());
return H5::DataSpace(eventual.size(), initial.data(), eventual.data());
}
H5::DSetCreatPropList getChunckedDatasetParams(
const std::vector<hsize_t>& extent,
hsize_t batch_size) {
H5::DSetCreatPropList params;
std::vector<hsize_t> chunk_size{batch_size};
chunk_size.insert(chunk_size.end(), extent.begin(), extent.end());
params.setChunk(chunk_size.size(), chunk_size.data());
params.setDeflate(7);
return params;
}
std::vector<hsize_t> getStriding(std::vector<hsize_t> extent) {
// calculate striding
extent.push_back(1);
for (size_t iii = extent.size(); iii - 1 != 0; iii--) {
extent.at(iii-2) = extent.at(iii-2) * extent.at(iii-1);
}
return extent;
}
void throwIfExists(const std::string& name, const H5::Group& in_group) {
if (H5Lexists(in_group.getLocId(), name.c_str(), H5P_DEFAULT)) {
throw std::logic_error("tried to overwrite '" + name + "'");
}
}
}
}
| [
"walter.lampl@cern.ch"
] | walter.lampl@cern.ch |
a9401ebddd3b6a1f41c5ae1a9740b6d3f6b9d3ed | b1247300a12c1d19158580d691adb27be50383e1 | /Target_Sum.cpp | 652de1b7f60927c32c976fe83b8df9629fc6e045 | [] | no_license | pizisuan/Algorithm-Problem | dc0b7adbe2418796c049b499208512a1532b5f39 | 92dae1769eaa8f9b451e403de1c74a5d64ed5dfd | refs/heads/master | 2021-06-24T15:44:55.132589 | 2021-01-07T06:24:30 | 2021-01-07T06:24:30 | 136,305,851 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,152 | cpp | /*
* Problem DescriptionYou are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Reverse a singly linked list.
* Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol.
* Find out how many ways to assign symbols to make sum of integers equal to target S.
*
* Input: nums is [1, 1, 1, 1, 1], S is 3.
* Output: 5
*
* Explanation:
* -1+1+1+1+1 = 3
* +1-1+1+1+1 = 3
* +1+1-1+1+1 = 3
* +1+1+1-1+1 = 3
* +1+1+1+1-1 = 3
*
* There are 5 ways to assign symbols to make the sum of nums be target 3.
*/
// 动态规划:需仔细揣摩!!!
class Solution
{
public:
int findTargetSumWays(vector<int>& nums, int S)
{
int sum = 0;
for (auto n : nums)
sum += n;
if ((sum + S) % 2 == 1 || S > sum || S < -sum)
return 0;
int new_s = (sum + S) / 2;
vector<int> dp(new_s + 1, 0);
dp[0] = 1;
for (int var : nums)
{
for (int j = new_s; j >=var; --j)
{
dp[j] += dp[j - var];
}
}
return dp[new_s];
}
};
| [
"noreply@github.com"
] | noreply@github.com |
113d70af0ea5f65408c9eb3b7fd804181d1b5c0f | bcf77f6dc8c5f808beec4b2abab5c5a701cee046 | /mainwindow.h | ad9fb1c02be64757962278cd4d217b11d17f04d1 | [] | no_license | thepalakjain/Axelrod-take-2 | 4afd001533c71e4c1b6bb55cde4b654cb7a1b273 | c5cf4384a1cbdb80b1f332721e584663c71518d5 | refs/heads/master | 2021-01-20T10:16:26.950221 | 2017-04-29T06:16:51 | 2017-04-29T06:16:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 440 | h | #pragma once
#include <QMainWindow>
#include "simulationmanager.h"
#include "simulationsession.h"
#include "saveManager.h"
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0); /* creates the display window */
private:
SimulationManager simulationManager; /* adds a simulation manager object to the window */
SaveManager saveManager;
SimulationSession session;
bool shouldSimulate;
};
| [
"szabogmatyas@yahoo.com"
] | szabogmatyas@yahoo.com |
388477f9a79f0ef3a4847d3012422559f93d0892 | 8d6afcef0053f2100139ac942ce9859a27bd18e9 | /Proyecto/Mouse.cpp | 91af0174365d497b4ddc6668ca82d6f4387fd07b | [] | no_license | dfjpmosh/JuegoCubos | c29dc1b162a00146461ee3106d39c6d721b03bb2 | 588f586a85e489c3152f3c8ae9c86c872467616f | refs/heads/master | 2022-11-10T00:13:32.928224 | 2020-06-30T22:02:15 | 2020-06-30T22:02:15 | 276,217,638 | 1 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 5,791 | cpp | #include <winbgim.h>
#define ANCHO 10
#define PROF ANCHO/2
void dibuja_cubo(int x, int y, int color);
void linea_cubos_mouse();
void paraboloide_mouse();
void circulos_mouse();
void menu();
int main()
{
initwindow(648,486);
linea_cubos_mouse();
paraboloide_mouse();
circulos_mouse();
menu();
do
{
if(ismouseclick(WM_LBUTTONDBLCLK) ) /* checa si se presionó dos veces botón derecho */
{
if(mousex()>213 && mousey()>100 && mousex()<435 && mousey()<128)
{
setfillstyle(1, 2);
bar(213, 100, 435, 128);
setfillstyle(1, 11);
bar(213, 128, 435, 124);
bar(431, 128, 435, 100);
setcolor(7);
rectangle(213, 100, 435, 128);
setcolor(14);
settextstyle(1,0,1);
outtextxy(273, 102,"JUEGO");
delay(100);
menu();
}
if(mousex()>213 && mousey()>180 && mousex()<435 && mousey()<208)
{
setfillstyle(1, 2);
bar(213, 180, 435, 208);
setfillstyle(1, 11);
bar(213, 208, 435, 204);
bar(431, 208, 435, 180);
setcolor(7);
rectangle(213, 180, 435, 208);
setcolor(14);
settextstyle(1,0,1);
outtextxy(265, 182,"AYUDA");
delay(100);
menu();
}
if(mousex()>213 && mousey()>260 && mousex()<435 && mousey()<288)
{
setfillstyle(1, 2);
bar(213, 260, 435, 288);
setfillstyle(1, 11);
bar(213, 288, 435, 284);
bar(431, 288, 435, 260);
setcolor(7);
rectangle(213, 260, 435, 288);
setcolor(14);
settextstyle(1,0,1);
outtextxy(256, 262,"RECORDS");
delay(100);
menu();
}
if(mousex()>213 && mousey()>340 && mousex()<435 && mousey()<368)
{
setfillstyle(1, 2);
bar(213, 340, 435, 368);
setfillstyle(1, 11);
bar(213, 368, 435, 364);
bar(431, 368, 435, 340);
setcolor(7);
rectangle(213, 340, 435, 368);
setcolor(14);
settextstyle(1,0,1);
outtextxy(275, 342,"SALIR");
delay(100);
menu();
}
clearmouseclick(WM_LBUTTONDBLCLK); /* limpia la bandera que indica si se presionó un botón */
}
}while (!ismouseclick(WM_RBUTTONDBLCLK) && !kbhit()); /* checa si se presionó boton derecho dos veces o una tecla */
closegraph();
return 0;
}
void menu()
{
setfillstyle(1, 2);
bar(213, 100, 435, 128);
setfillstyle(1, 11);
bar(213, 100, 435, 104);
bar(213, 100, 217, 128);
setcolor(7);
rectangle(213, 100, 435, 128);
setcolor(14);
settextstyle(1,0,1);
outtextxy(275, 106,"JUEGO");
setfillstyle(1, 2);
bar(213, 180, 435, 208);
setfillstyle(1, 11);
bar(213, 180, 435, 184);
bar(213, 180, 217, 208);
setcolor(7);
rectangle(213, 180, 435, 208);
setcolor(14);
settextstyle(1,0,1);
outtextxy(267, 186,"AYUDA");
setfillstyle(1, 2);
bar(213, 260, 435, 288);
setfillstyle(1, 11);
bar(213, 260, 435, 264);
bar(213, 260, 217, 288);
setcolor(7);
rectangle(213, 260, 435, 288);
setcolor(14);
settextstyle(1,0,1);
outtextxy(258, 266,"RECORDS");
setfillstyle(1, 2);
bar(213, 340, 435, 368);
setfillstyle(1, 11);
bar(213, 340, 435, 344);
bar(213, 340, 217, 368);
setcolor(7);
rectangle(213, 340, 435, 368);
setcolor(14);
settextstyle(1,0,1);
outtextxy(277, 346,"SALIR");
}
// DIBUJA UN CUBO
void dibuja_cubo(int x, int y, int color)
{
int poly[8];
setcolor(9);
poly[0]=x; // x1
poly[1]=y; // y1
poly[2]=x+ANCHO/2; // x2
poly[3]=y-PROF; // y2
poly[4]=x+ANCHO+ANCHO/2; // x3
poly[5]=y-PROF; // y3
poly[6]=x+ANCHO; // x4
poly[7]=y; // y4
setfillstyle(1,color);
fillpoly(4,poly);
bar(x,y,x+ANCHO,y+ANCHO);
rectangle(x,y,x+ANCHO,y+ANCHO);
poly[0]=x+ANCHO; // x1
poly[1]=y; // y1
poly[2]=x+ANCHO; // x2
poly[3]=y+ANCHO; // y2
poly[4]=x+ANCHO*3/2; // x3
poly[5]=y+ANCHO-PROF; // y3
poly[6]=x+ANCHO*3/2; // x4
poly[7]=y-PROF; // y4
setfillstyle(1,color);
fillpoly(4,poly);
}
//DIBUJA 4 LINEAS DE CUBOS
void linea_cubos_mouse()
{
int i, ncy=36, nc=52;
int x1=63, x2=6, x3=620;
int y1=10, y2=462, y3=64;
// CUBOS HORIZONTALES
for(i=0;i<nc;i+=2)
{
dibuja_cubo(x1+i*ANCHO, y1, 4);
dibuja_cubo(x1+i*ANCHO, y2, 4);
}
//CUBOS VERTICALES
for(i=0;i<ncy;i+=2)
{
dibuja_cubo(x2, y3+i*ANCHO, 4);
dibuja_cubo(x3, y3+i*ANCHO, 4);
}
}
// DIBUJA LINEAS LA PARABOLOIDE HIPERBOLICA
void paraboloide_mouse()
{
int i=0, j=0;
int x=110, y=240, x1=320, y1=30, nl=441;
setcolor(1);
line(110, 240, 530, 240);//linea horizontal
line(320, 30, 320, 450);//linea vertical
while(i<221)
{
line(320, 30+i, 320+j, 240);
line(320, 30+i, 320-j, 240);
line(320+i, 240, 320, 450-j);
line(320-i, 240, 320, 450-j);
j+=7;
i+=7;
}
}
//DIBUJO SEMICIRCULOS EN LA ESQUINAS
void circulos_mouse()
{
int x=0, y=0, rad=4, ncc=15;
int i;
setcolor(1);
rectangle(0, 0, 639, 479);
for(i=0;i<ncc;i++)
{
circle(x, y, rad*i);
circle(x, y+479, rad*i);
circle(x+639, y, rad*i);
circle(x+639, y+479, rad*i);
}
line(28, 50, 28, 429);
line(50, 28, 589, 28);
line(50, 451, 589, 451);
line(611, 50, 611, 429);
}
| [
"DFJP_MOSH@hotmail.com"
] | DFJP_MOSH@hotmail.com |
2fa98875d0d3f90c2043c0561ce5a2c604c6308f | d26db3039b3778f66ce502e2ad61572ce9823ae9 | /third_party/kallisto_kmer_lookup/src/ProcessReads.cpp | 59c7121d9b68b0065d725b34c59173ebcbefd1b0 | [
"BSD-2-Clause"
] | permissive | COMBINE-lab/pufferfish_experiments | 288af173f8fa3c99b3bb4e0d882be3d44c4c3a5f | e764943ac200e4646b328d2ca25acde7c4b16aa2 | refs/heads/master | 2021-03-27T19:33:17.322824 | 2018-02-05T01:34:21 | 2018-02-05T01:34:21 | 95,398,962 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 23,197 | cpp | /*
#include <zlib.h>
#include "kseq.h"
#include <string>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <iostream>
#include <fstream>
#include "MinCollector.h"
#include "common.h"
*/
#include "ProcessReads.h"
#include "kseq.h"
#include "PseudoBam.h"
void printVector(const std::vector<int>& v, std::ostream& o) {
o << "[";
int i = 0;
for (auto x : v) {
if (i>0) {
o << ", ";
}
o << x;
i++;
}
o << "]";
}
bool isSubset(const std::vector<int>& x, const std::vector<int>& y) {
auto a = x.begin();
auto b = y.begin();
while (a != x.end() && b != y.end()) {
if (*a < *b) {
return false;
} else if (*b < *a) {
++b;
} else {
++a;
++b;
}
}
return (a==x.end());
}
int findFirstMappingKmer(const std::vector<std::pair<KmerEntry,int>> &v,KmerEntry &val) {
int p = -1;
if (!v.empty()) {
val = v[0].first;
p = v[0].second;
for (auto &x : v) {
if (x.second < p) {
val = x.first;
p = x.second;
}
}
}
return p;
}
int ProcessBatchReads(KmerIndex& index, const ProgramOptions& opt, MinCollector& tc, std::vector<std::vector<int>> &batchCounts) {
int limit = 1048576;
std::vector<std::pair<const char*, int>> seqs;
seqs.reserve(limit/50);
// need to receive an index map
std::ios_base::sync_with_stdio(false);
//int tlencount = (opt.fld == 0.0) ? 10000 : 0;
size_t numreads = 0;
size_t nummapped = 0;
bool paired = !opt.single_end;
if (paired) {
std::cerr << "[quant] running in paired-end mode" << std::endl;
} else {
std::cerr << "[quant] running in single-end mode" << std::endl;
}
for (const auto& fs : opt.batch_files) {
for (int i = 0; i < fs.size(); i += (paired) ? 2 : 1) {
if (paired) {
std::cerr << "[quant] will process pair " << (i/2 +1) << ": " << fs[i] << std::endl
<< " " << fs[i+1] << std::endl;
} else {
std::cerr << "[quant] will process file " << i+1 << ": " << fs[i] << std::endl;
}
}
}
std::cerr << "[quant] finding pseudoalignments for all files ..."; std::cerr.flush();
MasterProcessor MP(index, opt, tc);
MP.processReads();
numreads = MP.numreads;
nummapped = MP.nummapped;
batchCounts = std::move(MP.batchCounts);
std::cerr << " done" << std::endl;
if (opt.bias) {
std::cerr << "[quant] learning parameters for sequence specific bias" << std::endl;
}
std::cerr << "[quant] processed " << pretty_num(numreads) << " reads, "
<< pretty_num(nummapped) << " reads pseudoaligned";
if (!opt.umi) {
std::cerr << std::endl;
} else {
std::cerr << ", " << pretty_num(MP.num_umi) << " unique UMIs mapped" << std::endl;
}
return numreads;
}
int ProcessReads(KmerIndex& index, const ProgramOptions& opt, MinCollector& tc) {
int limit = 1048576;
std::vector<std::pair<const char*, int>> seqs;
seqs.reserve(limit/50);
//SequenceReader SR(opt);
// need to receive an index map
std::ios_base::sync_with_stdio(false);
//int tlencount = (opt.fld == 0.0) ? 10000 : 0;
size_t numreads = 0;
size_t nummapped = 0;
bool paired = !opt.single_end;
/*
std::vector<std::pair<KmerEntry,int>> v1, v2;
v1.reserve(1000);
v2.reserve(1000);
*/
if (paired) {
std::cerr << "[quant] running in paired-end mode" << std::endl;
} else {
std::cerr << "[quant] running in single-end mode" << std::endl;
}
for (int i = 0; i < opt.files.size(); i += (paired) ? 2 : 1) {
if (paired) {
std::cerr << "[quant] will process pair " << (i/2 +1) << ": " << opt.files[i] << std::endl
<< " " << opt.files[i+1] << std::endl;
} else {
std::cerr << "[quant] will process file " << i+1 << ": " << opt.files[i] << std::endl;
}
}
// for each file
std::cerr << "[quant] finding pseudoalignments for the reads ..."; std::cerr.flush();
if (opt.pseudobam) {
index.writePseudoBamHeader(std::cout);
}
MasterProcessor MP(index, opt, tc);
MP.processReads();
numreads = MP.numreads;
nummapped = MP.nummapped;
std::cerr << " done" << std::endl;
//std::cout << "betterCount = " << betterCount << ", out of betterCand = " << betterCand << std::endl;
if (opt.bias) {
std::cerr << "[quant] learning parameters for sequence specific bias" << std::endl;
}
std::cerr << "[quant] processed " << pretty_num(numreads) << " reads, "
<< pretty_num(nummapped) << " reads pseudoaligned" << std::endl;
/*
for (int i = 0; i < 4096; i++) {
std::cout << i << " " << tc.bias5[i] << " " << tc.bias3[i] << "\n";
}*/
// write output to outdir
if (opt.write_index) {
std::string outfile = opt.output + "/counts.txt";
std::ofstream of;
of.open(outfile.c_str(), std::ios::out);
tc.write(of);
of.close();
}
return numreads;
}
/** -- read processors -- **/
void MasterProcessor::processReads() {
// start worker threads
if (!opt.batch_mode) {
std::vector<std::thread> workers;
for (int i = 0; i < opt.threads; i++) {
workers.emplace_back(std::thread(ReadProcessor(index,opt,tc,*this)));
}
// let the workers do their thing
for (int i = 0; i < opt.threads; i++) {
workers[i].join(); //wait for them to finish
}
// now handle the modification of the mincollector
for (auto &t : newECcount) {
if (t.second <= 0) {
continue;
}
int ec = tc.increaseCount(t.first); // modifies the ecmap
if (ec != -1 && t.second > 1) {
tc.counts[ec] += (t.second-1);
}
}
} else {
std::vector<std::thread> workers;
int num_ids = opt.batch_ids.size();
int id =0;
while (id < num_ids) {
// TODO: put in thread pool
workers.clear();
int nt = std::min(opt.threads, (num_ids - id));
for (int i = 0; i < nt; i++,id++) {
workers.emplace_back(std::thread(ReadProcessor(index, opt, tc, *this, id)));
}
for (int i = 0; i < nt; i++) {
workers[i].join();
}
if (opt.umi) {
// process the regular EC umi now
for (int i = 0; i < nt; i++) {
int l_id = id - nt + i;
auto &umis = batchUmis[l_id];
std::sort(umis.begin(), umis.end());
size_t sz = umis.size();
nummapped += sz;
if (sz > 0) {
++batchCounts[l_id][umis[0].first];
}
for (int j = 1; j < sz; j++) {
if (umis[j-1] != umis[j]) {
++batchCounts[l_id][umis[j].first];
}
}
umis.clear();
}
}
}
int num_newEcs = 0;
if (!opt.umi) {
// for each cell
for (int id = 0; id < num_ids; id++) {
// for each new ec
for (auto &t : newBatchECcount[id]) {
// add the ec and count number of new ecs
if (t.second <= 0) {
continue;
}
int ecsize = index.ecmap.size();
int ec = tc.increaseCount(t.first);
if (ec != -1 && ecsize < index.ecmap.size()) {
num_newEcs++;
}
}
}
// for each cell
for (int id = 0; id < num_ids; id++) {
auto& c = batchCounts[id];
c.resize(c.size() + num_newEcs,0);
// for each new ec
for (auto &t : newBatchECcount[id]) {
// count the ec
if (t.second <= 0) {
continue;
}
int ec = tc.findEC(t.first);
assert(ec != -1);
++c[ec];
}
}
} else {
// UMI case
// for each cell
for (int id = 0; id < num_ids; id++) {
// for each new ec
for (auto &t : newBatchECumis[id]) {
// add the new ec
int ecsize = index.ecmap.size();
int ec = tc.increaseCount(t.first);
if (ec != -1 && ecsize < index.ecmap.size()) {
num_newEcs++;
}
}
}
// for each cell
for (int id = 0; id < num_ids; id++) {
auto& c = batchCounts[id];
c.resize(c.size() + num_newEcs,0);
std::vector<std::pair<int, std::string>> umis;
umis.reserve(newBatchECumis[id].size());
// for each new ec
for (auto &t : newBatchECumis[id]) {
// record the ec,umi
int ec = tc.findEC(t.first);
umis.push_back({ec, std::move(t.second)});
}
// find unique umis per ec
std::sort(umis.begin(), umis.end());
size_t sz = umis.size();
if (sz > 0) {
++batchCounts[id][umis[0].first];
}
for (int j = 1; j < sz; j++) {
if (umis[j-1] != umis[j]) {
++batchCounts[id][umis[j].first];
}
}
for (auto x : c) {
num_umi += x;
}
}
}
}
}
void MasterProcessor::update(const std::vector<int>& c, const std::vector<std::vector<int> > &newEcs,
std::vector<std::pair<int, std::string>>& ec_umi, std::vector<std::pair<std::vector<int>, std::string>> &new_ec_umi,
int n, std::vector<int>& flens, std::vector<int> &bias, int id) {
// acquire the writer lock
std::lock_guard<std::mutex> lock(this->writer_lock);
if (!opt.batch_mode) {
for (int i = 0; i < c.size(); i++) {
tc.counts[i] += c[i]; // add up ec counts
nummapped += c[i];
}
} else {
if (!opt.umi) {
for (int i = 0; i < c.size(); i++) {
batchCounts[id][i] += c[i];
nummapped += c[i];
}
} else {
for (auto &t : ec_umi) {
batchUmis[id].push_back(std::move(t));
}
}
}
if (!opt.batch_mode) {
for(auto &u : newEcs) {
++newECcount[u];
}
} else {
if (!opt.umi) {
for(auto &u : newEcs) {
++newBatchECcount[id][u];
}
} else {
for (auto &u : new_ec_umi) {
newBatchECumis[id].push_back(std::move(u));
}
}
}
if (!opt.umi) {
nummapped += newEcs.size();
} else {
nummapped += new_ec_umi.size();
}
if (!flens.empty()) {
int local_tlencount = 0;
for (int i = 0; i < flens.size(); i++) {
tc.flens[i] += flens[i];
local_tlencount += flens[i];
}
tlencount += local_tlencount;
}
if (!bias.empty()) {
int local_biasCount = 0;
for (int i = 0; i < bias.size(); i++) {
tc.bias5[i] += bias[i];
local_biasCount += bias[i];
}
biasCount += local_biasCount;
}
numreads += n;
// releases the lock
}
ReadProcessor::ReadProcessor(const KmerIndex& index, const ProgramOptions& opt, const MinCollector& tc, MasterProcessor& mp, int _id) :
paired(!opt.single_end), tc(tc), index(index), mp(mp), id(_id) {
// initialize buffer
bufsize = 1ULL<<23;
buffer = new char[bufsize];
if (opt.batch_mode) {
assert(id != -1);
batchSR.files = opt.batch_files[id];
if (opt.umi) {
batchSR.umi_files = {opt.umi_files[id]};
}
batchSR.paired = !opt.single_end;
}
seqs.reserve(bufsize/50);
if (opt.umi) {
umis.reserve(bufsize/50);
}
newEcs.reserve(1000);
counts.reserve((int) (tc.counts.size() * 1.25));
clear();
}
ReadProcessor::ReadProcessor(ReadProcessor && o) :
paired(o.paired),
tc(o.tc),
index(o.index),
mp(o.mp),
id(o.id),
bufsize(o.bufsize),
numreads(o.numreads),
seqs(std::move(o.seqs)),
names(std::move(o.names)),
quals(std::move(o.quals)),
umis(std::move(o.umis)),
newEcs(std::move(o.newEcs)),
flens(std::move(o.flens)),
bias5(std::move(o.bias5)),
batchSR(std::move(o.batchSR)),
counts(std::move(o.counts)) {
buffer = o.buffer;
o.buffer = nullptr;
o.bufsize = 0;
}
ReadProcessor::~ReadProcessor() {
if (buffer != nullptr) {
delete[] buffer;
buffer = nullptr;
}
}
void ReadProcessor::operator()() {
while (true) {
// grab the reader lock
if (mp.opt.batch_mode) {
if (batchSR.empty()) {
return;
} else {
batchSR.fetchSequences(buffer, bufsize, seqs, names, quals, umis, false);
}
} else {
std::lock_guard<std::mutex> lock(mp.reader_lock);
if (mp.SR.empty()) {
// nothing to do
return;
} else {
// get new sequences
mp.SR.fetchSequences(buffer, bufsize, seqs, names, quals, umis, mp.opt.pseudobam);
}
// release the reader lock
}
// process our sequences
processBuffer();
// update the results, MP acquires the lock
mp.update(counts, newEcs, ec_umi, new_ec_umi, paired ? seqs.size()/2 : seqs.size(), flens, bias5, id);
clear();
}
}
void ReadProcessor::processBuffer() {
// set up thread variables
std::vector<std::pair<KmerEntry,int>> v1, v2;
std::vector<int> vtmp;
std::vector<int> u;
u.reserve(1000);
v1.reserve(1000);
v2.reserve(1000);
vtmp.reserve(1000);
const char* s1 = 0;
const char* s2 = 0;
int l1,l2;
bool findFragmentLength = (mp.opt.fld == 0) && (mp.tlencount < 10000);
int flengoal = 0;
flens.clear();
if (findFragmentLength) {
flengoal = (10000 - mp.tlencount);
if (flengoal <= 0) {
findFragmentLength = false;
flengoal = 0;
} else {
flens.resize(tc.flens.size(), 0);
}
}
int maxBiasCount = 0;
bool findBias = mp.opt.bias && (mp.biasCount < mp.maxBiasCount);
int biasgoal = 0;
bias5.clear();
if (findBias) {
biasgoal = (mp.maxBiasCount - mp.biasCount);
if (biasgoal <= 0) {
findBias = false;
} else {
bias5.resize(tc.bias5.size(),0);
}
}
// actually process the sequences
for (int i = 0; i < seqs.size(); i++) {
s1 = seqs[i].first;
l1 = seqs[i].second;
if (paired) {
i++;
s2 = seqs[i].first;
l2 = seqs[i].second;
}
numreads++;
v1.clear();
v2.clear();
u.clear();
// process read
index.match(s1,l1, v1);
if (paired) {
index.match(s2,l2, v2);
}
// collect the target information
int ec = -1;
int r = tc.intersectKmers(v1, v2, !paired, u);
/* -- possibly modify the pseudoalignment -- */
// If we have paired end reads where one end maps or single end reads, check if some transcsripts
// are not compatible with the mean fragment length
if (!mp.opt.umi && !u.empty() && (!paired || v1.empty() || v2.empty()) && tc.has_mean_fl) {
vtmp.clear();
// inspect the positions
int fl = (int) tc.get_mean_frag_len();
int p = -1;
KmerEntry val;
Kmer km;
if (!v1.empty()) {
p = findFirstMappingKmer(v1,val);
km = Kmer((s1+p));
}
if (!v2.empty()) {
p = findFirstMappingKmer(v2,val);
km = Kmer((s2+p));
}
// for each transcript in the pseudoalignment
for (auto tr : u) {
auto x = index.findPosition(tr, km, val, p);
// if the fragment is within bounds for this transcript, keep it
if (x.second && x.first + fl <= index.target_lens_[tr]) {
vtmp.push_back(tr);
} else {
//pass
}
if (!x.second && x.first - fl >= 0) {
vtmp.push_back(tr);
} else {
//pass
}
}
if (vtmp.size() < u.size()) {
u = vtmp; // copy
}
}
if (mp.opt.strand_specific && !u.empty()) {
int p = -1;
Kmer km;
KmerEntry val;
if (!v1.empty()) {
vtmp.clear();
bool firstStrand = (mp.opt.strand == ProgramOptions::StrandType::FR); // FR have first read mapping forward
p = findFirstMappingKmer(v1,val);
km = Kmer((s1+p));
bool strand = (val.isFw() == (km == km.rep())); // k-mer maps to fw strand?
// might need to optimize this
const auto &c = index.dbGraph.contigs[val.contig];
for (auto tr : u) {
for (auto ctx : c.transcripts) {
if (tr == ctx.trid) {
if ((strand == ctx.sense) == firstStrand) {
// swap out
vtmp.push_back(tr);
}
break;
}
}
}
if (vtmp.size() < u.size()) {
u = vtmp; // copy
}
}
if (!v2.empty()) {
vtmp.clear();
bool secondStrand = (mp.opt.strand == ProgramOptions::StrandType::RF);
p = findFirstMappingKmer(v2,val);
km = Kmer((s2+p));
bool strand = (val.isFw() == (km == km.rep())); // k-mer maps to fw strand?
// might need to optimize this
const auto &c = index.dbGraph.contigs[val.contig];
for (auto tr : u) {
for (auto ctx : c.transcripts) {
if (tr == ctx.trid) {
if ((strand == ctx.sense) == secondStrand) {
// swap out
vtmp.push_back(tr);
}
break;
}
}
}
if (vtmp.size() < u.size()) {
u = vtmp; // copy
}
}
}
// find the ec
if (!u.empty()) {
ec = tc.findEC(u);
if (!mp.opt.umi) {
// count the pseudoalignment
if (ec == -1 || ec >= counts.size()) {
// something we haven't seen before
newEcs.push_back(u);
} else {
// add to count vector
++counts[ec];
}
} else {
if (ec == -1 || ec >= counts.size()) {
new_ec_umi.emplace_back(u, std::move(umis[i]));
} else {
ec_umi.emplace_back(ec, std::move(umis[i]));
}
}
/* -- collect extra information -- */
// collect bias info
if (findBias && !u.empty() && biasgoal > 0) {
// collect sequence specific bias info
if (tc.countBias(s1, (paired) ? s2 : nullptr, v1, v2, paired, bias5)) {
biasgoal--;
}
}
// collect fragment length info
if (findFragmentLength && flengoal > 0 && paired && 0 <= ec && ec < index.num_trans && !v1.empty() && !v2.empty()) {
// try to map the reads
int tl = index.mapPair(s1, l1, s2, l2, ec);
if (0 < tl && tl < flens.size()) {
flens[tl]++;
flengoal--;
}
}
}
// pseudobam
if (mp.opt.pseudobam) {
if (paired) {
outputPseudoBam(index, u,
s1, names[i-1].first, quals[i-1].first, l1, names[i-1].second, v1,
s2, names[i].first, quals[i].first, l2, names[i].second, v2,
paired);
} else {
outputPseudoBam(index, u,
s1, names[i].first, quals[i].first, l1, names[i].second, v1,
nullptr, nullptr, nullptr, 0, 0, v2,
paired);
}
}
/*
if (opt.verbose && numreads % 100000 == 0 ) {
std::cerr << "[quant] Processed " << pretty_num(numreads) << std::endl;
}*/
}
}
void ReadProcessor::clear() {
numreads=0;
memset(buffer,0,bufsize);
newEcs.clear();
counts.clear();
counts.resize(tc.counts.size(),0);
ec_umi.clear();
new_ec_umi.clear();
}
/** -- sequence reader -- **/
SequenceReader::~SequenceReader() {
if (fp1) {
gzclose(fp1);
}
if (paired && fp2) {
gzclose(fp2);
}
kseq_destroy(seq1);
if (paired) {
kseq_destroy(seq2);
}
// check if umi stream is open, then close
}
// returns true if there is more left to read from the files
bool SequenceReader::fetchSequences(char *buf, const int limit, std::vector<std::pair<const char *, int> > &seqs,
std::vector<std::pair<const char *, int> > &names,
std::vector<std::pair<const char *, int> > &quals,
std::vector<std::string> &umis,
bool full) {
std::string line;
std::string umi;
seqs.clear();
umis.clear();
if (full) {
names.clear();
quals.clear();
}
bool usingUMIfiles = !umi_files.empty();
int umis_read = 0;
int bufpos = 0;
int pad = (paired) ? 2 : 1;
while (true) {
if (!state) { // should we open a file
if (current_file >= files.size()) {
// nothing left
return false;
} else {
// close the current file
if(fp1) {
gzclose(fp1);
}
if (paired && fp2) {
gzclose(fp2);
}
// close current umi file
if (usingUMIfiles) {
// read up the rest of the files
f_umi->close();
}
// open the next one
fp1 = gzopen(files[current_file].c_str(),"r");
seq1 = kseq_init(fp1);
l1 = kseq_read(seq1);
state = true;
if (paired) {
current_file++;
fp2 = gzopen(files[current_file].c_str(),"r");
seq2 = kseq_init(fp2);
l2 = kseq_read(seq2);
}
if (usingUMIfiles) {
// open new umi file
f_umi->open(umi_files[current_file]);
}
}
}
// the file is open and we have read into seq1 and seq2
if (l1 > 0 && (!paired || l2 > 0)) {
int bufadd = l1 + l2 + pad;
// fits into the buffer
if (full) {
nl1 = seq1->name.l;
if (paired) {
nl2 = seq2->name.l;
}
bufadd += (l1+l2) + pad + (nl1+nl2)+ pad;
}
if (bufpos+bufadd< limit) {
char *p1 = buf+bufpos;
memcpy(p1, seq1->seq.s, l1+1);
bufpos += l1+1;
seqs.emplace_back(p1,l1);
if (usingUMIfiles) {
std::stringstream ss;
std::getline(*f_umi, line);
ss.str(line);
ss >> umi;
umis.emplace_back(std::move(umi));
}
if (full) {
p1 = buf+bufpos;
memcpy(p1, seq1->qual.s,l1+1);
bufpos += l1+1;
quals.emplace_back(p1,l1);
p1 = buf+bufpos;
memcpy(p1, seq1->name.s,nl1+1);
bufpos += nl1+1;
names.emplace_back(p1,nl1);
}
if (paired) {
char *p2 = buf+bufpos;
memcpy(p2, seq2->seq.s,l2+1);
bufpos += l2+1;
seqs.emplace_back(p2,l2);
if (full) {
p2 = buf+bufpos;
memcpy(p2,seq2->qual.s,l2+1);
bufpos += l2+1;
quals.emplace_back(p2,l2);
p2 = buf + bufpos;
memcpy(p2,seq2->name.s,nl2+1);
bufpos += nl2+1;
names.emplace_back(p2,nl2);
}
}
} else {
return true; // read it next time
}
// read for the next one
l1 = kseq_read(seq1);
if (paired) {
l2 = kseq_read(seq2);
}
} else {
current_file++; // move to next file
state = false; // haven't opened file yet
}
}
}
bool SequenceReader::empty() {
return (!state && current_file >= files.size());
}
SequenceReader::SequenceReader(SequenceReader&& o) :
fp1(o.fp1),
fp2(o.fp2),
seq1(o.seq1),
seq2(o.seq2),
l1(o.l1),
l2(o.l2),
nl1(o.nl1),
nl2(o.nl2),
paired(o.paired),
files(std::move(o.files)),
umi_files(std::move(o.umi_files)),
f_umi(std::move(o.f_umi)),
current_file(o.current_file),
state(o.state) {
o.fp1 = nullptr;
o.fp2 = nullptr;
o.seq1 = nullptr;
o.seq2 = nullptr;
o.state = false;
} | [
"rob@newton"
] | rob@newton |
c3b3388367528ce9467512f8665f76fee87701a5 | 625d7326db0aeac19af8c97b0f39d00a1322dba4 | /libs/AntTweakBar/src/TwOpenGLCore.cpp | 66beef355935dafe37a2c36c91b3421cea1edcf9 | [] | no_license | jonyrock/RabbitDemo | ed5caa0ba0daaf7f866d884a79415ce10f01a8b0 | 5bb0056ca5305a5fe21f63752801014411c231ba | refs/heads/master | 2016-09-05T10:02:02.801324 | 2014-04-03T22:21:39 | 2014-04-03T22:21:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 33,389 | cpp | // ---------------------------------------------------------------------------
//
// @file TwOpenGLCore.cpp
// @author Philippe Decaudin
// @license This file is part of the AntTweakBar library.
// For conditions of distribution and use, see License.txt
//
// ---------------------------------------------------------------------------
/*
#pragma warning GL3 //// used for development
#define GL3_PROTOTYPES 1 ////
#include <GL3/gl3.h> ////
#define ANT_OGL_HEADER_INCLUDED ////
*/
#if defined ANT_OSX
# include <OpenGL/gl3.h>
# define ANT_OGL_HEADER_INCLUDED
#endif
#include "TwPrecomp.h"
#include "LoadOGLCore.h"
#include "TwOpenGLCore.h"
#include "TwMgr.h"
using namespace std;
extern const char *g_ErrCantLoadOGL;
extern const char *g_ErrCantUnloadOGL;
// ---------------------------------------------------------------------------
#ifdef _DEBUG
static void CheckGLCoreError(const char *file, int line, const char *func)
{
int err=0;
char msg[256];
while( (err=_glGetError())!=0 )
{
sprintf(msg, "%s(%d) : [%s] GL_CORE_ERROR=0x%x\n", file, line, func, err);
#ifdef ANT_WINDOWS
OutputDebugString(msg);
#endif
fprintf(stderr, msg);
}
}
# ifdef __FUNCTION__
# define CHECK_GL_ERROR CheckGLCoreError(__FILE__, __LINE__, __FUNCTION__)
# else
# define CHECK_GL_ERROR CheckGLCoreError(__FILE__, __LINE__, "")
# endif
#else
# define CHECK_GL_ERROR ((void)(0))
#endif
// ---------------------------------------------------------------------------
static GLuint BindFont(const CTexFont *_Font)
{
GLuint TexID = 0;
_glGenTextures(1, &TexID);
_glBindTexture(GL_TEXTURE_2D, TexID);
_glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_FALSE);
_glPixelStorei(GL_UNPACK_LSB_FIRST, GL_FALSE);
_glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
_glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
_glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
_glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
_glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, _Font->m_TexWidth, _Font->m_TexHeight, 0, GL_RED, GL_UNSIGNED_BYTE, _Font->m_TexBytes);
_glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
_glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
_glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_NEAREST);
_glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_NEAREST);
_glBindTexture(GL_TEXTURE_2D, 0);
return TexID;
}
static void UnbindFont(GLuint _FontTexID)
{
if( _FontTexID>0 )
_glDeleteTextures(1, &_FontTexID);
}
// ---------------------------------------------------------------------------
static GLuint CompileShader(GLuint shader)
{
_glCompileShader(shader); CHECK_GL_ERROR;
GLint status;
_glGetShaderiv(shader, GL_COMPILE_STATUS, &status); CHECK_GL_ERROR;
if (status == GL_FALSE)
{
GLint infoLogLength;
_glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength); CHECK_GL_ERROR;
GLchar strInfoLog[256];
_glGetShaderInfoLog(shader, sizeof(strInfoLog), NULL, strInfoLog); CHECK_GL_ERROR;
#ifdef ANT_WINDOWS
OutputDebugString("Compile failure: ");
OutputDebugString(strInfoLog);
OutputDebugString("\n");
#endif
fprintf(stderr, "Compile failure: %s\n", strInfoLog);
shader = 0;
}
return shader;
}
static GLuint LinkProgram(GLuint program)
{
_glLinkProgram(program); CHECK_GL_ERROR;
GLint status;
_glGetProgramiv(program, GL_LINK_STATUS, &status); CHECK_GL_ERROR;
if (status == GL_FALSE)
{
GLint infoLogLength;
_glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLogLength); CHECK_GL_ERROR;
GLchar strInfoLog[256];
_glGetProgramInfoLog(program, sizeof(strInfoLog), NULL, strInfoLog); CHECK_GL_ERROR;
#ifdef ANT_WINDOWS
OutputDebugString("Linker failure: ");
OutputDebugString(strInfoLog);
OutputDebugString("\n");
#endif
fprintf(stderr, "Linker failure: %s\n", strInfoLog);
program = 0;
}
return program;
}
// ---------------------------------------------------------------------------
void CTwGraphOpenGLCore::ResizeTriBuffers(size_t _NewSize)
{
m_TriBufferSize = _NewSize;
_glBindVertexArray(m_TriVArray);
_glBindBuffer(GL_ARRAY_BUFFER, m_TriVertices);
_glBufferData(GL_ARRAY_BUFFER, m_TriBufferSize*sizeof(Vec2), 0, GL_DYNAMIC_DRAW);
_glBindBuffer(GL_ARRAY_BUFFER, m_TriUVs);
_glBufferData(GL_ARRAY_BUFFER, m_TriBufferSize*sizeof(Vec2), 0, GL_DYNAMIC_DRAW);
_glBindBuffer(GL_ARRAY_BUFFER, m_TriColors);
_glBufferData(GL_ARRAY_BUFFER, m_TriBufferSize*sizeof(color32), 0, GL_DYNAMIC_DRAW);
CHECK_GL_ERROR;
}
// ---------------------------------------------------------------------------
int CTwGraphOpenGLCore::Init()
{
m_Drawing = false;
m_FontTexID = 0;
m_FontTex = NULL;
if( LoadOpenGLCore()==0 )
{
g_TwMgr->SetLastError(g_ErrCantLoadOGL);
return 0;
}
// Create line/rect shaders
const GLchar *lineRectVS[] = {
"#version 140\n"
"in vec3 vertex;"
"in vec4 color;"
"out vec4 fcolor;"
"void main() { gl_Position = vec4(vertex, 1); fcolor = color; }"
};
m_LineRectVS = _glCreateShader(GL_VERTEX_SHADER);
_glShaderSource(m_LineRectVS, 1, lineRectVS, NULL);
CompileShader(m_LineRectVS);
const GLchar *lineRectFS[] = {
"#version 140\n"
"precision highp float;"
"in vec4 fcolor;"
"out vec4 outColor;"
"void main() { outColor = fcolor; }"
};
m_LineRectFS = _glCreateShader(GL_FRAGMENT_SHADER);
_glShaderSource(m_LineRectFS, 1, lineRectFS, NULL);
CompileShader(m_LineRectFS);
m_LineRectProgram = _glCreateProgram();
_glAttachShader(m_LineRectProgram, m_LineRectVS);
_glAttachShader(m_LineRectProgram, m_LineRectFS);
_glBindAttribLocation(m_LineRectProgram, 0, "vertex");
_glBindAttribLocation(m_LineRectProgram, 1, "color");
LinkProgram(m_LineRectProgram);
// Create line/rect vertex buffer
const GLfloat lineRectInitVertices[] = { 0,0,0, 0,0,0, 0,0,0, 0,0,0 };
const color32 lineRectInitColors[] = { 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff };
_glGenVertexArrays(1, &m_LineRectVArray);
_glBindVertexArray(m_LineRectVArray);
_glGenBuffers(1, &m_LineRectVertices);
_glBindBuffer(GL_ARRAY_BUFFER, m_LineRectVertices);
_glBufferData(GL_ARRAY_BUFFER, sizeof(lineRectInitVertices), lineRectInitVertices, GL_DYNAMIC_DRAW);
_glGenBuffers(1, &m_LineRectColors);
_glBindBuffer(GL_ARRAY_BUFFER, m_LineRectColors);
_glBufferData(GL_ARRAY_BUFFER, sizeof(lineRectInitColors), lineRectInitColors, GL_DYNAMIC_DRAW);
// Create triangles shaders
const GLchar *triVS[] = {
"#version 140\n"
"uniform vec2 offset;"
"uniform vec2 wndSize;"
"in vec2 vertex;"
"in vec4 color;"
"out vec4 fcolor;"
"void main() { gl_Position = vec4(2.0*(vertex.x+offset.x-0.5)/wndSize.x - 1.0, 1.0 - 2.0*(vertex.y+offset.y-0.5)/wndSize.y, 0, 1); fcolor = color; }"
};
m_TriVS = _glCreateShader(GL_VERTEX_SHADER);
_glShaderSource(m_TriVS, 1, triVS, NULL);
CompileShader(m_TriVS);
const GLchar *triUniVS[] = {
"#version 140\n"
"uniform vec2 offset;"
"uniform vec2 wndSize;"
"uniform vec4 color;"
"in vec2 vertex;"
"out vec4 fcolor;"
"void main() { gl_Position = vec4(2.0*(vertex.x+offset.x-0.5)/wndSize.x - 1.0, 1.0 - 2.0*(vertex.y+offset.y-0.5)/wndSize.y, 0, 1); fcolor = color; }"
};
m_TriUniVS = _glCreateShader(GL_VERTEX_SHADER);
_glShaderSource(m_TriUniVS, 1, triUniVS, NULL);
CompileShader(m_TriUniVS);
m_TriFS = m_TriUniFS = m_LineRectFS;
m_TriProgram = _glCreateProgram();
_glAttachShader(m_TriProgram, m_TriVS);
_glAttachShader(m_TriProgram, m_TriFS);
_glBindAttribLocation(m_TriProgram, 0, "vertex");
_glBindAttribLocation(m_TriProgram, 1, "color");
LinkProgram(m_TriProgram);
m_TriLocationOffset = _glGetUniformLocation(m_TriProgram, "offset");
m_TriLocationWndSize = _glGetUniformLocation(m_TriProgram, "wndSize");
m_TriUniProgram = _glCreateProgram();
_glAttachShader(m_TriUniProgram, m_TriUniVS);
_glAttachShader(m_TriUniProgram, m_TriUniFS);
_glBindAttribLocation(m_TriUniProgram, 0, "vertex");
_glBindAttribLocation(m_TriUniProgram, 1, "color");
LinkProgram(m_TriUniProgram);
m_TriUniLocationOffset = _glGetUniformLocation(m_TriUniProgram, "offset");
m_TriUniLocationWndSize = _glGetUniformLocation(m_TriUniProgram, "wndSize");
m_TriUniLocationColor = _glGetUniformLocation(m_TriUniProgram, "color");
const GLchar *triTexFS[] = {
"#version 140\n"
"precision highp float;"
"uniform sampler2D tex;"
"in vec2 fuv;"
"in vec4 fcolor;"
"out vec4 outColor;"
// texture2D is deprecated and replaced by texture with GLSL 3.30 but it seems
// that on Mac Lion backward compatibility is not ensured.
#if defined(ANT_OSX) && (MAC_OS_X_VERSION_MAX_ALLOWED >= 1070)
"void main() { outColor.rgb = fcolor.bgr; outColor.a = fcolor.a * texture(tex, fuv).r; }"
#else
"void main() { outColor.rgb = fcolor.bgr; outColor.a = fcolor.a * texture2D(tex, fuv).r; }"
#endif
};
m_TriTexFS = _glCreateShader(GL_FRAGMENT_SHADER);
_glShaderSource(m_TriTexFS, 1, triTexFS, NULL);
CompileShader(m_TriTexFS);
const GLchar *triTexVS[] = {
"#version 140\n"
"uniform vec2 offset;"
"uniform vec2 wndSize;"
"in vec2 vertex;"
"in vec2 uv;"
"in vec4 color;"
"out vec2 fuv;"
"out vec4 fcolor;"
"void main() { gl_Position = vec4(2.0*(vertex.x+offset.x-0.5)/wndSize.x - 1.0, 1.0 - 2.0*(vertex.y+offset.y-0.5)/wndSize.y, 0, 1); fuv = uv; fcolor = color; }"
};
m_TriTexVS = _glCreateShader(GL_VERTEX_SHADER);
_glShaderSource(m_TriTexVS, 1, triTexVS, NULL);
CompileShader(m_TriTexVS);
const GLchar *triTexUniVS[] = {
"#version 140\n"
"uniform vec2 offset;"
"uniform vec2 wndSize;"
"uniform vec4 color;"
"in vec2 vertex;"
"in vec2 uv;"
"out vec4 fcolor;"
"out vec2 fuv;"
"void main() { gl_Position = vec4(2.0*(vertex.x+offset.x-0.5)/wndSize.x - 1.0, 1.0 - 2.0*(vertex.y+offset.y-0.5)/wndSize.y, 0, 1); fuv = uv; fcolor = color; }"
};
m_TriTexUniVS = _glCreateShader(GL_VERTEX_SHADER);
_glShaderSource(m_TriTexUniVS, 1, triTexUniVS, NULL);
CompileShader(m_TriTexUniVS);
m_TriTexUniFS = m_TriTexFS;
m_TriTexProgram = _glCreateProgram();
_glAttachShader(m_TriTexProgram, m_TriTexVS);
_glAttachShader(m_TriTexProgram, m_TriTexFS);
_glBindAttribLocation(m_TriTexProgram, 0, "vertex");
_glBindAttribLocation(m_TriTexProgram, 1, "uv");
_glBindAttribLocation(m_TriTexProgram, 2, "color");
LinkProgram(m_TriTexProgram);
m_TriTexLocationOffset = _glGetUniformLocation(m_TriTexProgram, "offset");
m_TriTexLocationWndSize = _glGetUniformLocation(m_TriTexProgram, "wndSize");
m_TriTexLocationTexture = _glGetUniformLocation(m_TriTexProgram, "tex");
m_TriTexUniProgram = _glCreateProgram();
_glAttachShader(m_TriTexUniProgram, m_TriTexUniVS);
_glAttachShader(m_TriTexUniProgram, m_TriTexUniFS);
_glBindAttribLocation(m_TriTexUniProgram, 0, "vertex");
_glBindAttribLocation(m_TriTexUniProgram, 1, "uv");
_glBindAttribLocation(m_TriTexUniProgram, 2, "color");
LinkProgram(m_TriTexUniProgram);
m_TriTexUniLocationOffset = _glGetUniformLocation(m_TriTexUniProgram, "offset");
m_TriTexUniLocationWndSize = _glGetUniformLocation(m_TriTexUniProgram, "wndSize");
m_TriTexUniLocationColor = _glGetUniformLocation(m_TriTexUniProgram, "color");
m_TriTexUniLocationTexture = _glGetUniformLocation(m_TriTexUniProgram, "tex");
// Create tri vertex buffer
_glGenVertexArrays(1, &m_TriVArray);
_glGenBuffers(1, &m_TriVertices);
_glGenBuffers(1, &m_TriUVs);
_glGenBuffers(1, &m_TriColors);
ResizeTriBuffers(16384); // set initial size
CHECK_GL_ERROR;
return 1;
}
// ---------------------------------------------------------------------------
int CTwGraphOpenGLCore::Shut()
{
assert(m_Drawing==false);
UnbindFont(m_FontTexID);
CHECK_GL_ERROR;
_glDeleteProgram(m_LineRectProgram); m_LineRectProgram = 0;
_glDeleteShader(m_LineRectVS); m_LineRectVS = 0;
_glDeleteShader(m_LineRectFS); m_LineRectFS = 0;
_glDeleteProgram(m_TriProgram); m_TriProgram = 0;
_glDeleteShader(m_TriVS); m_TriVS = 0;
_glDeleteProgram(m_TriUniProgram); m_TriUniProgram = 0;
_glDeleteShader(m_TriUniVS); m_TriUniVS = 0;
_glDeleteProgram(m_TriTexProgram); m_TriTexProgram = 0;
_glDeleteShader(m_TriTexVS); m_TriTexVS = 0;
_glDeleteShader(m_TriTexFS); m_TriTexFS = 0;
_glDeleteProgram(m_TriTexUniProgram); m_TriTexUniProgram = 0;
_glDeleteShader(m_TriTexUniVS); m_TriTexUniVS = 0;
_glDeleteBuffers(1, &m_LineRectVertices); m_LineRectVertices = 0;
_glDeleteBuffers(1, &m_LineRectColors); m_LineRectColors = 0;
_glDeleteVertexArrays(1, &m_LineRectVArray); m_LineRectVArray = 0;
_glDeleteBuffers(1, &m_TriVertices); m_TriVertices = 0;
_glDeleteBuffers(1, &m_TriColors); m_TriColors = 0;
_glDeleteBuffers(1, &m_TriUVs); m_TriUVs = 0;
_glDeleteVertexArrays(1, &m_TriVArray); m_TriVArray = 0;
CHECK_GL_ERROR;
int Res = 1;
if( UnloadOpenGLCore()==0 )
{
g_TwMgr->SetLastError(g_ErrCantUnloadOGL);
Res = 0;
}
return Res;
}
// ---------------------------------------------------------------------------
void CTwGraphOpenGLCore::BeginDraw(int _WndWidth, int _WndHeight)
{
CHECK_GL_ERROR;
assert(m_Drawing==false && _WndWidth>0 && _WndHeight>0);
m_Drawing = true;
m_WndWidth = _WndWidth;
m_WndHeight = _WndHeight;
m_OffsetX = 0;
m_OffsetY = 0;
_glGetIntegerv(GL_VIEWPORT, m_PrevViewport); CHECK_GL_ERROR;
if( _WndWidth>0 && _WndHeight>0 )
{
GLint Vp[4];
Vp[0] = 0;
Vp[1] = 0;
Vp[2] = _WndWidth-1;
Vp[3] = _WndHeight-1;
_glViewport(Vp[0], Vp[1], Vp[2], Vp[3]);
}
m_PrevVArray = 0;
_glGetIntegerv(GL_VERTEX_ARRAY_BINDING, (GLint*)&m_PrevVArray); CHECK_GL_ERROR;
_glBindVertexArray(0); CHECK_GL_ERROR;
m_PrevLineWidth = 1;
_glGetFloatv(GL_LINE_WIDTH, &m_PrevLineWidth); CHECK_GL_ERROR;
_glLineWidth(1); CHECK_GL_ERROR;
m_PrevLineSmooth = _glIsEnabled(GL_LINE_SMOOTH);
_glDisable(GL_LINE_SMOOTH); CHECK_GL_ERROR;
m_PrevCullFace = _glIsEnabled(GL_CULL_FACE);
_glDisable(GL_CULL_FACE); CHECK_GL_ERROR;
m_PrevDepthTest = _glIsEnabled(GL_DEPTH_TEST);
_glDisable(GL_DEPTH_TEST); CHECK_GL_ERROR;
m_PrevBlend = _glIsEnabled(GL_BLEND);
_glEnable(GL_BLEND); CHECK_GL_ERROR;
m_PrevScissorTest = _glIsEnabled(GL_SCISSOR_TEST);
_glDisable(GL_SCISSOR_TEST); CHECK_GL_ERROR;
_glGetIntegerv(GL_SCISSOR_BOX, m_PrevScissorBox); CHECK_GL_ERROR;
_glGetIntegerv(GL_BLEND_SRC, &m_PrevSrcBlend); CHECK_GL_ERROR;
_glGetIntegerv(GL_BLEND_DST, &m_PrevDstBlend); CHECK_GL_ERROR;
_glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); CHECK_GL_ERROR;
m_PrevTexture = 0;
_glGetIntegerv(GL_TEXTURE_BINDING_2D, &m_PrevTexture); CHECK_GL_ERROR;
_glBindTexture(GL_TEXTURE_2D, 0); CHECK_GL_ERROR;
m_PrevProgramObject = 0;
_glGetIntegerv(GL_CURRENT_PROGRAM, (GLint*)&m_PrevProgramObject); CHECK_GL_ERROR;
_glBindVertexArray(0); CHECK_GL_ERROR;
_glUseProgram(0); CHECK_GL_ERROR;
m_PrevActiveTexture = 0;
_glGetIntegerv(GL_ACTIVE_TEXTURE, (GLint*)&m_PrevActiveTexture); CHECK_GL_ERROR;
_glActiveTexture(GL_TEXTURE0);
CHECK_GL_ERROR;
}
// ---------------------------------------------------------------------------
void CTwGraphOpenGLCore::EndDraw()
{
assert(m_Drawing==true);
m_Drawing = false;
_glLineWidth(m_PrevLineWidth); CHECK_GL_ERROR;
if( m_PrevLineSmooth )
{
_glEnable(GL_LINE_SMOOTH); CHECK_GL_ERROR;
}
else
{
_glDisable(GL_LINE_SMOOTH); CHECK_GL_ERROR;
}
if( m_PrevCullFace )
{
_glEnable(GL_CULL_FACE); CHECK_GL_ERROR;
}
else
{
_glDisable(GL_CULL_FACE); CHECK_GL_ERROR;
}
if( m_PrevDepthTest )
{
_glEnable(GL_DEPTH_TEST); CHECK_GL_ERROR;
}
else
{
_glDisable(GL_DEPTH_TEST); CHECK_GL_ERROR;
}
if( m_PrevBlend )
{
_glEnable(GL_BLEND); CHECK_GL_ERROR;
}
else
{
_glDisable(GL_BLEND); CHECK_GL_ERROR;
}
if( m_PrevScissorTest )
{
_glEnable(GL_SCISSOR_TEST); CHECK_GL_ERROR;
}
else
{
_glDisable(GL_SCISSOR_TEST); CHECK_GL_ERROR;
}
_glScissor(m_PrevScissorBox[0], m_PrevScissorBox[1], m_PrevScissorBox[2], m_PrevScissorBox[3]); CHECK_GL_ERROR;
_glBlendFunc(m_PrevSrcBlend, m_PrevDstBlend); CHECK_GL_ERROR;
_glBindTexture(GL_TEXTURE_2D, m_PrevTexture); CHECK_GL_ERROR;
_glUseProgram(m_PrevProgramObject); CHECK_GL_ERROR;
_glBindVertexArray(m_PrevVArray); CHECK_GL_ERROR;
_glViewport(m_PrevViewport[0], m_PrevViewport[1], m_PrevViewport[2], m_PrevViewport[3]); CHECK_GL_ERROR;
CHECK_GL_ERROR;
}
// ---------------------------------------------------------------------------
bool CTwGraphOpenGLCore::IsDrawing()
{
return m_Drawing;
}
// ---------------------------------------------------------------------------
void CTwGraphOpenGLCore::Restore()
{
UnbindFont(m_FontTexID);
m_FontTexID = 0;
m_FontTex = NULL;
}
// ---------------------------------------------------------------------------
static inline float ToNormScreenX(float x, int wndWidth)
{
return 2.0f*((float)x-0.5f)/wndWidth - 1.0f;
}
static inline float ToNormScreenY(float y, int wndHeight)
{
return 1.0f - 2.0f*((float)y-0.5f)/wndHeight;
}
// ---------------------------------------------------------------------------
void CTwGraphOpenGLCore::DrawLine(int _X0, int _Y0, int _X1, int _Y1, color32 _Color0, color32 _Color1, bool _AntiAliased)
{
CHECK_GL_ERROR;
assert(m_Drawing==true);
//const GLfloat dx = +0.0f;
const GLfloat dx = 0;
//GLfloat dy = -0.2f;
const GLfloat dy = -0.5f;
if( _AntiAliased )
_glEnable(GL_LINE_SMOOTH);
else
_glDisable(GL_LINE_SMOOTH);
_glBindVertexArray(m_LineRectVArray);
GLfloat x0 = ToNormScreenX(_X0+dx + m_OffsetX, m_WndWidth);
GLfloat y0 = ToNormScreenY(_Y0+dy + m_OffsetY, m_WndHeight);
GLfloat x1 = ToNormScreenX(_X1+dx + m_OffsetX, m_WndWidth);
GLfloat y1 = ToNormScreenY(_Y1+dy + m_OffsetY, m_WndHeight);
GLfloat vertices[] = { x0,y0,0, x1,y1,0 };
_glBindBuffer(GL_ARRAY_BUFFER, m_LineRectVertices);
_glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
_glVertexAttribPointer(0, 3, GL_FLOAT, GL_TRUE, 0, NULL);
_glEnableVertexAttribArray(0);
color32 colors[] = { _Color0, _Color1 };
_glBindBuffer(GL_ARRAY_BUFFER, m_LineRectColors);
_glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(colors), colors);
_glVertexAttribPointer(1, GL_BGRA, GL_UNSIGNED_BYTE, GL_TRUE, 0, NULL);
_glEnableVertexAttribArray(1);
_glUseProgram(m_LineRectProgram);
_glDrawArrays(GL_LINES, 0, 2);
if( _AntiAliased )
_glDisable(GL_LINE_SMOOTH);
CHECK_GL_ERROR;
}
// ---------------------------------------------------------------------------
void CTwGraphOpenGLCore::DrawRect(int _X0, int _Y0, int _X1, int _Y1, color32 _Color00, color32 _Color10, color32 _Color01, color32 _Color11)
{
CHECK_GL_ERROR;
assert(m_Drawing==true);
// border adjustment
if(_X0<_X1)
++_X1;
else if(_X0>_X1)
++_X0;
if(_Y0<_Y1)
--_Y0;
else if(_Y0>_Y1)
--_Y1;
_glBindVertexArray(m_LineRectVArray);
GLfloat x0 = ToNormScreenX((float)_X0 + m_OffsetX, m_WndWidth);
GLfloat y0 = ToNormScreenY((float)_Y0 + m_OffsetY, m_WndHeight);
GLfloat x1 = ToNormScreenX((float)_X1 + m_OffsetX, m_WndWidth);
GLfloat y1 = ToNormScreenY((float)_Y1 + m_OffsetY, m_WndHeight);
GLfloat vertices[] = { x0,y0,0, x1,y0,0, x0,y1,0, x1,y1,0 };
_glBindBuffer(GL_ARRAY_BUFFER, m_LineRectVertices);
_glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
_glVertexAttribPointer(0, 3, GL_FLOAT, GL_TRUE, 0, NULL);
_glEnableVertexAttribArray(0);
GLuint colors[] = { _Color00, _Color10, _Color01, _Color11 };
_glBindBuffer(GL_ARRAY_BUFFER, m_LineRectColors);
_glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(colors), colors);
_glVertexAttribPointer(1, GL_BGRA, GL_UNSIGNED_BYTE, GL_TRUE, 0, NULL);
_glEnableVertexAttribArray(1);
_glUseProgram(m_LineRectProgram);
_glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
CHECK_GL_ERROR;
}
// ---------------------------------------------------------------------------
void *CTwGraphOpenGLCore::NewTextObj()
{
return new CTextObj;
}
// ---------------------------------------------------------------------------
void CTwGraphOpenGLCore::DeleteTextObj(void *_TextObj)
{
assert(_TextObj!=NULL);
delete static_cast<CTextObj *>(_TextObj);
}
// ---------------------------------------------------------------------------
void CTwGraphOpenGLCore::BuildText(void *_TextObj, const std::string *_TextLines, color32 *_LineColors, color32 *_LineBgColors, int _NbLines, const CTexFont *_Font, int _Sep, int _BgWidth)
{
assert(m_Drawing==true);
assert(_TextObj!=NULL);
assert(_Font!=NULL);
if( _Font != m_FontTex )
{
UnbindFont(m_FontTexID);
m_FontTexID = BindFont(_Font);
m_FontTex = _Font;
}
CTextObj *TextObj = static_cast<CTextObj *>(_TextObj);
TextObj->m_TextVerts.resize(0);
TextObj->m_TextUVs.resize(0);
TextObj->m_BgVerts.resize(0);
TextObj->m_Colors.resize(0);
TextObj->m_BgColors.resize(0);
int x, x1, y, y1, i, Len;
unsigned char ch;
const unsigned char *Text;
color32 LineColor = COLOR32_RED;
for( int Line=0; Line<_NbLines; ++Line )
{
x = 0;
y = Line * (_Font->m_CharHeight+_Sep);
y1 = y+_Font->m_CharHeight;
Len = (int)_TextLines[Line].length();
Text = (const unsigned char *)(_TextLines[Line].c_str());
if( _LineColors!=NULL )
LineColor = (_LineColors[Line]&0xff00ff00) | GLubyte(_LineColors[Line]>>16) | (GLubyte(_LineColors[Line])<<16);
for( i=0; i<Len; ++i )
{
ch = Text[i];
x1 = x + _Font->m_CharWidth[ch];
TextObj->m_TextVerts.push_back(Vec2(x , y ));
TextObj->m_TextVerts.push_back(Vec2(x1, y ));
TextObj->m_TextVerts.push_back(Vec2(x , y1));
TextObj->m_TextVerts.push_back(Vec2(x1, y ));
TextObj->m_TextVerts.push_back(Vec2(x1, y1));
TextObj->m_TextVerts.push_back(Vec2(x , y1));
TextObj->m_TextUVs.push_back(Vec2(_Font->m_CharU0[ch], _Font->m_CharV0[ch]));
TextObj->m_TextUVs.push_back(Vec2(_Font->m_CharU1[ch], _Font->m_CharV0[ch]));
TextObj->m_TextUVs.push_back(Vec2(_Font->m_CharU0[ch], _Font->m_CharV1[ch]));
TextObj->m_TextUVs.push_back(Vec2(_Font->m_CharU1[ch], _Font->m_CharV0[ch]));
TextObj->m_TextUVs.push_back(Vec2(_Font->m_CharU1[ch], _Font->m_CharV1[ch]));
TextObj->m_TextUVs.push_back(Vec2(_Font->m_CharU0[ch], _Font->m_CharV1[ch]));
if( _LineColors!=NULL )
{
TextObj->m_Colors.push_back(LineColor);
TextObj->m_Colors.push_back(LineColor);
TextObj->m_Colors.push_back(LineColor);
TextObj->m_Colors.push_back(LineColor);
TextObj->m_Colors.push_back(LineColor);
TextObj->m_Colors.push_back(LineColor);
}
x = x1;
}
if( _BgWidth>0 )
{
TextObj->m_BgVerts.push_back(Vec2(-1 , y ));
TextObj->m_BgVerts.push_back(Vec2(_BgWidth+1, y ));
TextObj->m_BgVerts.push_back(Vec2(-1 , y1));
TextObj->m_BgVerts.push_back(Vec2(_BgWidth+1, y ));
TextObj->m_BgVerts.push_back(Vec2(_BgWidth+1, y1));
TextObj->m_BgVerts.push_back(Vec2(-1 , y1));
if( _LineBgColors!=NULL )
{
color32 LineBgColor = (_LineBgColors[Line]&0xff00ff00) | GLubyte(_LineBgColors[Line]>>16) | (GLubyte(_LineBgColors[Line])<<16);
TextObj->m_BgColors.push_back(LineBgColor);
TextObj->m_BgColors.push_back(LineBgColor);
TextObj->m_BgColors.push_back(LineBgColor);
TextObj->m_BgColors.push_back(LineBgColor);
TextObj->m_BgColors.push_back(LineBgColor);
TextObj->m_BgColors.push_back(LineBgColor);
}
}
}
}
// ---------------------------------------------------------------------------
void CTwGraphOpenGLCore::DrawText(void *_TextObj, int _X, int _Y, color32 _Color, color32 _BgColor)
{
CHECK_GL_ERROR;
assert(m_Drawing==true);
assert(_TextObj!=NULL);
CTextObj *TextObj = static_cast<CTextObj *>(_TextObj);
if( TextObj->m_TextVerts.size()<4 && TextObj->m_BgVerts.size()<4 )
return; // nothing to draw
// draw character background triangles
if( (_BgColor!=0 || TextObj->m_BgColors.size()==TextObj->m_BgVerts.size()) && TextObj->m_BgVerts.size()>=4 )
{
size_t numBgVerts = TextObj->m_BgVerts.size();
if( numBgVerts > m_TriBufferSize )
ResizeTriBuffers(numBgVerts + 2048);
_glBindVertexArray(m_TriVArray);
_glBindBuffer(GL_ARRAY_BUFFER, m_TriVertices);
_glBufferSubData(GL_ARRAY_BUFFER, 0, numBgVerts*sizeof(Vec2), &(TextObj->m_BgVerts[0]));
_glVertexAttribPointer(0, 2, GL_FLOAT, GL_TRUE, 0, NULL);
_glEnableVertexAttribArray(0);
_glDisableVertexAttribArray(1);
_glDisableVertexAttribArray(2);
if( TextObj->m_BgColors.size()==TextObj->m_BgVerts.size() && _BgColor==0 )
{
_glBindBuffer(GL_ARRAY_BUFFER, m_TriColors);
_glBufferSubData(GL_ARRAY_BUFFER, 0, numBgVerts*sizeof(color32), &(TextObj->m_BgColors[0]));
_glVertexAttribPointer(1, GL_BGRA, GL_UNSIGNED_BYTE, GL_TRUE, 0, NULL);
_glEnableVertexAttribArray(1);
_glUseProgram(m_TriProgram);
_glUniform2f(m_TriLocationOffset, (float)_X, (float)_Y);
_glUniform2f(m_TriLocationWndSize, (float)m_WndWidth, (float)m_WndHeight);
}
else
{
_glUseProgram(m_TriUniProgram);
_glUniform4f(m_TriUniLocationColor, GLfloat((_BgColor>>16)&0xff)/256.0f, GLfloat((_BgColor>>8)&0xff)/256.0f, GLfloat(_BgColor&0xff)/256.0f, GLfloat((_BgColor>>24)&0xff)/256.0f);
_glUniform2f(m_TriUniLocationOffset, (float)_X, (float)_Y);
_glUniform2f(m_TriUniLocationWndSize, (float)m_WndWidth, (float)m_WndHeight);
}
_glDrawArrays(GL_TRIANGLES, 0, (GLsizei)TextObj->m_BgVerts.size());
}
// draw character triangles
if( TextObj->m_TextVerts.size()>=4 )
{
_glActiveTexture(GL_TEXTURE0);
_glBindTexture(GL_TEXTURE_2D, m_FontTexID);
size_t numTextVerts = TextObj->m_TextVerts.size();
if( numTextVerts > m_TriBufferSize )
ResizeTriBuffers(numTextVerts + 2048);
_glBindVertexArray(m_TriVArray);
_glDisableVertexAttribArray(2);
_glBindBuffer(GL_ARRAY_BUFFER, m_TriVertices);
_glBufferSubData(GL_ARRAY_BUFFER, 0, numTextVerts*sizeof(Vec2), &(TextObj->m_TextVerts[0]));
_glVertexAttribPointer(0, 2, GL_FLOAT, GL_TRUE, 0, NULL);
_glEnableVertexAttribArray(0);
_glBindBuffer(GL_ARRAY_BUFFER, m_TriUVs);
_glBufferSubData(GL_ARRAY_BUFFER, 0, numTextVerts*sizeof(Vec2), &(TextObj->m_TextUVs[0]));
_glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, NULL);
_glEnableVertexAttribArray(1);
if( TextObj->m_Colors.size()==TextObj->m_TextVerts.size() && _Color==0 )
{
_glBindBuffer(GL_ARRAY_BUFFER, m_TriColors);
_glBufferSubData(GL_ARRAY_BUFFER, 0, numTextVerts*sizeof(color32), &(TextObj->m_Colors[0]));
_glVertexAttribPointer(2, GL_BGRA, GL_UNSIGNED_BYTE, GL_TRUE, 0, NULL);
_glEnableVertexAttribArray(2);
_glUseProgram(m_TriTexProgram);
_glUniform2f(m_TriTexLocationOffset, (float)_X, (float)_Y);
_glUniform2f(m_TriTexLocationWndSize, (float)m_WndWidth, (float)m_WndHeight);
_glUniform1i(m_TriTexLocationTexture, 0);
}
else
{
_glUseProgram(m_TriTexUniProgram);
_glUniform4f(m_TriTexUniLocationColor, GLfloat((_Color>>16)&0xff)/256.0f, GLfloat((_Color>>8)&0xff)/256.0f, GLfloat(_Color&0xff)/256.0f, GLfloat((_Color>>24)&0xff)/256.0f);
_glUniform2f(m_TriTexUniLocationOffset, (float)_X, (float)_Y);
_glUniform2f(m_TriTexUniLocationWndSize, (float)m_WndWidth, (float)m_WndHeight);
_glUniform1i(m_TriTexUniLocationTexture, 0);
}
_glDrawArrays(GL_TRIANGLES, 0, (GLsizei)TextObj->m_TextVerts.size());
}
CHECK_GL_ERROR;
}
// ---------------------------------------------------------------------------
void CTwGraphOpenGLCore::ChangeViewport(int _X0, int _Y0, int _Width, int _Height, int _OffsetX, int _OffsetY)
{
// glViewport impacts the NDC; use glScissor instead
m_OffsetX = _X0 + _OffsetX;
m_OffsetY = _Y0 + _OffsetY;
SetScissor(_X0, _Y0, _Width, _Height);
}
// ---------------------------------------------------------------------------
void CTwGraphOpenGLCore::RestoreViewport()
{
m_OffsetX = m_OffsetY = 0;
SetScissor(0, 0, 0, 0);
}
// ---------------------------------------------------------------------------
void CTwGraphOpenGLCore::SetScissor(int _X0, int _Y0, int _Width, int _Height)
{
if( _Width>0 && _Height>0 )
{
_glScissor(_X0-1, m_WndHeight-_Y0-_Height, _Width-1, _Height);
_glEnable(GL_SCISSOR_TEST);
}
else
_glDisable(GL_SCISSOR_TEST);
}
// ---------------------------------------------------------------------------
void CTwGraphOpenGLCore::DrawTriangles(int _NumTriangles, int *_Vertices, color32 *_Colors, Cull _CullMode)
{
assert(m_Drawing==true);
const GLfloat dx = +0.0f;
const GLfloat dy = +0.0f;
// Backup states
GLint prevCullFaceMode, prevFrontFace;
_glGetIntegerv(GL_CULL_FACE_MODE, &prevCullFaceMode);
_glGetIntegerv(GL_FRONT_FACE, &prevFrontFace);
GLboolean prevCullEnable = _glIsEnabled(GL_CULL_FACE);
_glCullFace(GL_BACK);
_glEnable(GL_CULL_FACE);
if( _CullMode==CULL_CW )
_glFrontFace(GL_CCW);
else if( _CullMode==CULL_CCW )
_glFrontFace(GL_CW);
else
_glDisable(GL_CULL_FACE);
_glUseProgram(m_TriProgram);
_glBindVertexArray(m_TriVArray);
_glUniform2f(m_TriLocationOffset, (float)m_OffsetX+dx, (float)m_OffsetY+dy);
_glUniform2f(m_TriLocationWndSize, (float)m_WndWidth, (float)m_WndHeight);
_glDisableVertexAttribArray(2);
size_t numVerts = 3*_NumTriangles;
if( numVerts > m_TriBufferSize )
ResizeTriBuffers(numVerts + 2048);
_glBindBuffer(GL_ARRAY_BUFFER, m_TriVertices);
_glBufferSubData(GL_ARRAY_BUFFER, 0, numVerts*2*sizeof(int), _Vertices);
_glVertexAttribPointer(0, 2, GL_INT, GL_FALSE, 0, NULL);
_glEnableVertexAttribArray(0);
_glBindBuffer(GL_ARRAY_BUFFER, m_TriColors);
_glBufferSubData(GL_ARRAY_BUFFER, 0, numVerts*sizeof(color32), _Colors);
_glVertexAttribPointer(1, GL_BGRA, GL_UNSIGNED_BYTE, GL_TRUE, 0, NULL);
_glEnableVertexAttribArray(1);
_glDrawArrays(GL_TRIANGLES, 0, (GLsizei)numVerts);
// Reset states
_glCullFace(prevCullFaceMode);
_glFrontFace(prevFrontFace);
if( prevCullEnable )
_glEnable(GL_CULL_FACE);
else
_glDisable(GL_CULL_FACE);
CHECK_GL_ERROR;
}
// ---------------------------------------------------------------------------
| [
"ilms@live.ru"
] | ilms@live.ru |
74b4cef1ab9c6df7f9240672033b8883d64885e8 | e5dc90655caa598fae65f95a14bc2a93084cf854 | /src/cpu/reorder/cpu_reorder_regular_s8.cpp | 4e9b5ac75181f4a50b87eba2723c74910c72c610 | [
"Apache-2.0",
"BSD-3-Clause",
"BSL-1.0",
"BSD-2-Clause"
] | permissive | dongxiao92/ZenDNN | d4bedf41c2166f63f55eea4b08e1801be04a8404 | 99e79349fe4bd512711ebc4d63deba69a732a18e | refs/heads/main | 2023-07-10T01:30:57.527781 | 2021-08-11T13:30:35 | 2021-08-11T13:30:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,674 | cpp | /*******************************************************************************
* Modifications Copyright (c) 2021 Advanced Micro Devices, Inc. All rights reserved.
* Notified per clause 4(b) of the license.
*******************************************************************************/
/*******************************************************************************
* Copyright 2020 Intel Corporation
*
* 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 "cpu/reorder/cpu_reorder.hpp"
namespace zendnn {
namespace impl {
namespace cpu {
// clang-format off
const impl_list_map_t regular_s8_impl_list_map {
// s8 ->
{{s8, data_type::undef, 0}, {
rnn_weights_reorder_s8_t<s8>::pd_t::create,
rnn_brgemm_weights_reorder_s8_t<s8, s8>::pd_t::create,
REG_FAST_DIRECT_COPY_COMMA(s8, f32)
REG_FAST_DIRECT_COPY_COMMA(s8, s32)
REG_FAST_DIRECT_COPY_COMMA(s8, bf16)
REG_FAST_DIRECT_COPY_COMMA(s8, s8)
REG_FAST_DIRECT_COPY_COMMA(s8, u8)
ZENDNN_X64_ONLY(x64::jit_uni_reorder_create,)
ZENDNN_AARCH64_ONLY(aarch64::jit_uni_reorder_create,)
REG_SR_BIDIR(s8, any, f32, nChw16c),
REG_SR_BIDIR(s8, any, s32, nChw16c),
REG_SR_BIDIR(s8, any, bf16, nChw16c),
REG_SR_BIDIR(s8, any, s8, nChw16c),
REG_SR_BIDIR(s8, any, u8, nChw16c),
REG_SR_BIDIR(s8, any, f32, OIhw4i16o4i),
REG_SR_BIDIR(s8, any, bf16, OIhw4i16o4i),
REG_SR_BIDIR(s8, any, s8, OIhw4i16o4i),
REG_SR_BIDIR(s8, any, f32, gOIhw4i16o4i),
REG_SR_BIDIR(s8, any, bf16, gOIhw4i16o4i),
REG_SR_BIDIR(s8, any, s8, gOIhw4i16o4i),
REG_SR(s8, any, f32, any, fmt_order::any, spec::reference),
REG_SR(s8, any, s32, any, fmt_order::any, spec::reference),
REG_SR(s8, any, bf16, any, fmt_order::any, spec::reference),
REG_SR(s8, any, s8, any, fmt_order::any, spec::reference),
REG_SR(s8, any, u8, any, fmt_order::any, spec::reference),
nullptr,
}},
};
// clang-format on
} // namespace cpu
} // namespace impl
} // namespace zendnn
| [
"ratan.prasad2@amd.com"
] | ratan.prasad2@amd.com |
f8e6394c72986a80f343026705b718ac42b03ccf | 1de03df18ac8ea95cfd1ca90ea433343bd467708 | /hw1/hw1_3_4/hw1_3.cpp | 5f69e5ef806273190e3bf2364b9da467327af8ac | [] | no_license | wangzhucent/AEROSP552 | 971d522ece2a32341cbf4f1a1653ceb4fac2e68b | 858ee5f0ac4df96f661d19253c784b4cd45b362c | refs/heads/master | 2020-09-11T18:27:44.406686 | 2019-11-16T20:14:55 | 2019-11-16T20:14:55 | 222,152,779 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 201 | cpp | #include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include "life.h"
using namespace std;
//Try a life_cur.dat for updating the input data
int main()
{
life();
return 1;
}
| [
"you@example.com"
] | you@example.com |
d5c87dde2eaeebadd4d65e9ffa3fee4a95b303a6 | d1de10aead5ccf25b3eb94feefa60f90fc7454ee | /Microformatter/MicroformatterDlg.cpp | 5836184d97874434a4181a4e57de3d986e7cfda8 | [
"Unlicense"
] | permissive | mjohne/Cpp-Apps | 3f9d838a120843dc0ac87cc81b1c3ae29282c51c | 0d386f4a76a3aa4676a11d0e1e3cc87e91e9b96f | refs/heads/master | 2020-09-09T03:51:54.553623 | 2019-11-25T23:45:37 | 2019-11-25T23:45:37 | 221,339,592 | 0 | 0 | Unlicense | 2019-11-25T23:45:38 | 2019-11-13T00:35:36 | C++ | UTF-8 | C++ | false | false | 13,278 | cpp | // MicroformatterDlg.cpp : implementation file
//
#include "stdafx.h"
#include "resource.h"
#include "AddressDlg.h"
#include "CodeDlg.h"
#include "GeolocationDlg.h"
#include "hAtomDlg.h"
#include "hCalenderDlg.h"
#include "hCardDlg.h"
#include "hResumeDlg.h"
#include "hReviewDlg.h"
#include "relTagDlg.h"
#include "XFNDlg.h"
#include "xFolkDlg.h"
#include "MicroformatterDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CMicroformatterDlg dialog
CMicroformatterDlg::CMicroformatterDlg(CWnd* pParent /*=NULL*/)
: CDialog(CMicroformatterDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CMicroformatterDlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CMicroformatterDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CMicroformatterDlg)
DDX_Control(pDX, IDC_TAB, m_tcRegister);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CMicroformatterDlg, CDialog)
//{{AFX_MSG_MAP(CMicroformatterDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_NOTIFY(TCN_SELCHANGE, IDC_TAB, OnSelchangeTab)
ON_BN_CLICKED(IDC_BUTTON_EXIT, OnButtonExit)
ON_BN_CLICKED(IDC_BUTTON_CREATE, OnButtonCreate)
ON_BN_CLICKED(IDC_BUTTON_SAVE, OnButtonSave)
ON_BN_CLICKED(IDC_BUTTON_COPY, OnButtonCopy)
ON_BN_CLICKED(IDC_BUTTON_PRINT, OnButtonPrint)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CMicroformatterDlg message handlers
BOOL CMicroformatterDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
VERIFY(m_dlg_Address.Create(CAddressDlg::IDD,this));
VERIFY(m_dlg_Geolocation.Create(CGeolocationDlg::IDD,this));
VERIFY(m_dlg_hAtom.Create(ChAtomDlg::IDD,this));
VERIFY(m_dlg_hCalender.Create(ChCalenderDlg::IDD,this));
VERIFY(m_dlg_hCard.Create(ChCardDlg::IDD,this));
VERIFY(m_dlg_hResume.Create(ChResumeDlg::IDD,this));
VERIFY(m_dlg_hReview.Create(ChReviewDlg::IDD,this));
VERIFY(m_dlg_relTag.Create(CrelTagDlg::IDD,this));
VERIFY(m_dlg_XFN.Create(CXFNDlg::IDD,this));
VERIFY(m_dlg_xFolk.Create(CxFolkDlg::IDD,this));
VERIFY(m_dlg_Code.Create(CCodeDlg::IDD,this));
CString strText;
m_dlg_Address.GetWindowText(strText);
VERIFY(m_tcRegister.InsertItem(TCIF_TEXT,0,strText,0,0,0,0) == 0);
m_dlg_Geolocation.GetWindowText(strText);
VERIFY(m_tcRegister.InsertItem(TCIF_TEXT,1,strText,0,0,0,0) == 0);
m_dlg_hAtom.GetWindowText(strText);
VERIFY(m_tcRegister.InsertItem(TCIF_TEXT,2,strText,0,0,0,0) == 0);
m_dlg_hCalender.GetWindowText(strText);
VERIFY(m_tcRegister.InsertItem(TCIF_TEXT,3,strText,0,0,0,0) == 0);
m_dlg_hCard.GetWindowText(strText);
VERIFY(m_tcRegister.InsertItem(TCIF_TEXT,4,strText,0,0,0,0) == 0);
m_dlg_hResume.GetWindowText(strText);
VERIFY(m_tcRegister.InsertItem(TCIF_TEXT,5,strText,0,0,0,0) == 0);
m_dlg_hReview.GetWindowText(strText);
VERIFY(m_tcRegister.InsertItem(TCIF_TEXT,6,strText,0,0,0,0) == 0);
m_dlg_relTag.GetWindowText(strText);
VERIFY(m_tcRegister.InsertItem(TCIF_TEXT,7,strText,0,0,0,0) == 0);
m_dlg_XFN.GetWindowText(strText);
VERIFY(m_tcRegister.InsertItem(TCIF_TEXT,8,strText,0,0,0,0) == 0);
m_dlg_xFolk.GetWindowText(strText);
VERIFY(m_tcRegister.InsertItem(TCIF_TEXT,9,strText,0,0,0,0) == 0);
m_dlg_Code.GetWindowText(strText);
VERIFY(m_tcRegister.InsertItem(TCIF_TEXT,10,strText,0,0,0,0) == 0);
VERIFY(m_dlg_Address.SetWindowPos(GetDlgItem(IDC_TAB),8,77,0,0,SWP_SHOWWINDOW | SWP_NOSIZE));
VERIFY(m_dlg_Geolocation.SetWindowPos(GetDlgItem(IDC_TAB),8,77,0,0,SWP_SHOWWINDOW | SWP_NOSIZE));
VERIFY(m_dlg_hAtom.SetWindowPos(GetDlgItem(IDC_TAB),8,77,0,0,SWP_SHOWWINDOW | SWP_NOSIZE));
VERIFY(m_dlg_hCalender.SetWindowPos(GetDlgItem(IDC_TAB),8,77,100,100,SWP_SHOWWINDOW | SWP_NOSIZE));
VERIFY(m_dlg_hCard.SetWindowPos(GetDlgItem(IDC_TAB),8,77,100,100,SWP_SHOWWINDOW | SWP_NOSIZE));
VERIFY(m_dlg_hResume.SetWindowPos(GetDlgItem(IDC_TAB),8,77,100,100,SWP_SHOWWINDOW | SWP_NOSIZE));
VERIFY(m_dlg_hReview.SetWindowPos(GetDlgItem(IDC_TAB),8,77,100,100,SWP_SHOWWINDOW | SWP_NOSIZE));
VERIFY(m_dlg_relTag.SetWindowPos(GetDlgItem(IDC_TAB),8,77,100,100,SWP_SHOWWINDOW | SWP_NOSIZE));
VERIFY(m_dlg_XFN.SetWindowPos(GetDlgItem(IDC_TAB),8,77,100,100,SWP_SHOWWINDOW | SWP_NOSIZE));
VERIFY(m_dlg_xFolk.SetWindowPos(GetDlgItem(IDC_TAB),8,77,100,100,SWP_SHOWWINDOW | SWP_NOSIZE));
VERIFY(m_dlg_Code.SetWindowPos(GetDlgItem(IDC_TAB),8,77,100,100,SWP_SHOWWINDOW | SWP_NOSIZE));
UpdateVisibleWindow();
return TRUE; // return TRUE unless you set the focus to a control
}
void CMicroformatterDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CMicroformatterDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CMicroformatterDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
void CMicroformatterDlg::OnSelchangeTab(NMHDR* pNMHDR, LRESULT* pResult)
{
UpdateVisibleWindow();
*pResult = 0;
}
void CMicroformatterDlg::UpdateVisibleWindow()
{
int nCurrentTab = m_tcRegister.GetCurSel();
m_dlg_Address.ShowWindow(nCurrentTab == 0 ? SW_SHOW : SW_HIDE);
m_dlg_Geolocation.ShowWindow(nCurrentTab == 1 ? SW_SHOW : SW_HIDE);
m_dlg_hAtom.ShowWindow(nCurrentTab == 2 ? SW_SHOW : SW_HIDE);
m_dlg_hCalender.ShowWindow(nCurrentTab == 3 ? SW_SHOW : SW_HIDE);
m_dlg_hCard.ShowWindow(nCurrentTab == 4 ? SW_SHOW : SW_HIDE);
m_dlg_hResume.ShowWindow(nCurrentTab == 5 ? SW_SHOW : SW_HIDE);
m_dlg_hReview.ShowWindow(nCurrentTab == 6 ? SW_SHOW : SW_HIDE);
m_dlg_relTag.ShowWindow(nCurrentTab == 7 ? SW_SHOW : SW_HIDE);
m_dlg_XFN.ShowWindow(nCurrentTab == 8 ? SW_SHOW : SW_HIDE);
m_dlg_xFolk.ShowWindow(nCurrentTab == 9 ? SW_SHOW : SW_HIDE);
m_dlg_Code.ShowWindow(nCurrentTab == 10 ? SW_SHOW : SW_HIDE);
}
void CMicroformatterDlg::OnButtonExit()
{
CDialog::OnCancel();
}
void CMicroformatterDlg::OnButtonCreate()
{
int nCurrentRegister = m_tcRegister.GetCurSel();
m_tcRegister.SetCurSel(10);
m_dlg_Address.ShowWindow(SW_HIDE);
m_dlg_Geolocation.ShowWindow(SW_HIDE);
m_dlg_hAtom.ShowWindow(SW_HIDE);
m_dlg_hCalender.ShowWindow(SW_HIDE);
m_dlg_hCard.ShowWindow(SW_HIDE);
m_dlg_hResume.ShowWindow(SW_HIDE);
m_dlg_hReview.ShowWindow(SW_HIDE);
m_dlg_relTag.ShowWindow(SW_HIDE);
m_dlg_XFN.ShowWindow(SW_HIDE);
m_dlg_xFolk.ShowWindow(SW_HIDE);
m_dlg_Code.ShowWindow(SW_SHOW);
switch(nCurrentRegister)
{
default :
{
}
case 0:
{
m_dlg_Address.UpdateData(true);
int nCurrentRegister2 = m_dlg_Address.m_cmbxElementTemplate.GetCurSel();
switch(nCurrentRegister2)
{
default :
{
break;
}
case 0:
{
m_dlg_Code.m_strCode = _T("<div class=\"adr\">\x0D\x0A");
m_dlg_Code.m_strCodeCompact = _T("<div class=\"adr\">");
if (m_dlg_Address.m_strStreetAddress != _T(""))
{
m_dlg_Code.m_strCode += _T(" <div class=\"street-address\">");
m_dlg_Code.m_strCode += m_dlg_Address.m_strStreetAddress;
m_dlg_Code.m_strCode += _T("</div>\x0D\x0A");
m_dlg_Code.m_strCodeCompact += _T("<div class=\"street-address\">");
m_dlg_Code.m_strCodeCompact += m_dlg_Address.m_strStreetAddress;
m_dlg_Code.m_strCodeCompact += _T("</div>");
}
if (m_dlg_Address.m_strExtendedAddress != _T(""))
{
m_dlg_Code.m_strCode += _T(" <div class=\"extended-address\">");
m_dlg_Code.m_strCode += m_dlg_Address.m_strExtendedAddress;
m_dlg_Code.m_strCode += _T("</div>\x0D\x0A");
m_dlg_Code.m_strCodeCompact += _T("<div class=\"extended-address\">");
m_dlg_Code.m_strCodeCompact += m_dlg_Address.m_strExtendedAddress;
m_dlg_Code.m_strCodeCompact += _T("</div>");
}
if (m_dlg_Address.m_strLocality != _T(""))
{
m_dlg_Code.m_strCode += _T(" <span class=\"locality\">");
m_dlg_Code.m_strCode += m_dlg_Address.m_strLocality;
m_dlg_Code.m_strCode += _T("</span>\x0D\x0A");
m_dlg_Code.m_strCodeCompact += _T("<span class=\"locality\">");
m_dlg_Code.m_strCodeCompact += m_dlg_Address.m_strLocality;
m_dlg_Code.m_strCodeCompact += _T("</span>");
}
if (m_dlg_Address.m_strRegion != _T(""))
{
m_dlg_Code.m_strCode += _T(" <span class=\"region\">");
m_dlg_Code.m_strCode += m_dlg_Address.m_strRegion;
m_dlg_Code.m_strCode += _T("</span>\x0D\x0A");
m_dlg_Code.m_strCodeCompact += _T("<span class=\"region\">");
m_dlg_Code.m_strCodeCompact += m_dlg_Address.m_strRegion;
m_dlg_Code.m_strCodeCompact += _T("</span>");
}
if (m_dlg_Address.m_strPostalCode != _T(""))
{
m_dlg_Code.m_strCode += _T(" <span class=\"postal-code\">");
m_dlg_Code.m_strCode += m_dlg_Address.m_strPostalCode;
m_dlg_Code.m_strCode += _T("</span>\x0D\x0A");
m_dlg_Code.m_strCodeCompact += _T("<span class=\"postal-code\">");
m_dlg_Code.m_strCodeCompact += m_dlg_Address.m_strPostalCode;
m_dlg_Code.m_strCodeCompact += _T("</span>");
}
if (m_dlg_Address.m_strCountryName != _T(""))
{
m_dlg_Code.m_strCode += _T(" <div class=\"country-name\">");
m_dlg_Code.m_strCode += m_dlg_Address.m_strCountryName;
m_dlg_Code.m_strCode += _T("</div>\x0D\x0A");
m_dlg_Code.m_strCodeCompact += _T("<div class=\"country-name\">");
m_dlg_Code.m_strCodeCompact += m_dlg_Address.m_strCountryName;
m_dlg_Code.m_strCodeCompact += _T("</div>");
}
m_dlg_Code.m_strCode += _T("</div>");
m_dlg_Code.m_strCodeCompact += _T("</div>");
break;
}
}
break;
}
}
m_dlg_Code.UpdateData(false);
}
void CMicroformatterDlg::OnButtonSave()
{
// TODO: Add your control notification handler code here
}
void CMicroformatterDlg::OnButtonCopy()
{
// TODO: Add your control notification handler code here
}
void CMicroformatterDlg::OnButtonPrint()
{
// TODO: Add your control notification handler code here
}
| [
"noreply@github.com"
] | noreply@github.com |
5846ce2f691a075769bbbbeba1e0e71f803a935e | 96e7934b1721ecbee5bc9feb23fd8b717fb7e135 | /nexus_robot_2wd/firmware/Nexus_Firmware/src/main.cpp | d554c965c2e0817be33ab6acd5b45eca615d8250 | [] | no_license | yagoliz/nexus_robot_autonomous_navigation | 47985513a838949d1d0cd6543962064a7377bc3d | 895a77df3f0d29189a526800fdd877e80e74238f | refs/heads/master | 2021-05-10T00:32:09.731384 | 2018-08-19T18:18:04 | 2018-08-19T18:18:04 | 118,835,401 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,397 | cpp | #include <Arduino.h>
#include <PID_v1.h>
#include <Timer.h>
#include <Event.h>
#include <ros.h>
#include <geometry_msgs/Vector3.h>
#include <geometry_msgs/Vector3Stamped.h>
#include <std_msgs/Float64.h>
#include <ArduinoHardware.h>
#include "nexus_robot_specs.h"
// Robot variables
double rpsLeft = 0, pwmLeft = 0, Enc_rpsLeft = 0;
double encoderL0 = 0;
double encoderL1 = 0;
double rpsRight = 0, pwmRight = 0, Enc_rpsRight = 0;
double encoderR0 = 0;
double encoderR1 = 0;
unsigned long past_time = 0;
// ROS variables
ros::NodeHandle nh;
// Callback function
void get_speed(const geometry_msgs::Vector3& msg)
{
rpsLeft = abs(msg.x);
rpsRight = abs(msg.y);
if (msg.x>0){digitalWrite(M1, HIGH);}
else {digitalWrite(M1, LOW);}
if (msg.y>0){digitalWrite(M2, LOW);}
else {digitalWrite(M2, HIGH);}
}
ros::Subscriber<geometry_msgs::Vector3> sub("rps", get_speed);
geometry_msgs::Vector3Stamped Encoder_Count;
ros::Publisher pub("encoder_count", &Encoder_Count);
geometry_msgs::Vector3 debug_msg;
ros::Publisher debug("debug_node", &debug_msg);
Timer vel_timer;
Timer ros_publisher;
// PID objects
double Kpl=70.0, Kil=60.0, Kdl=0.4;
double Kpr=60.0, Kir=60.0, Kdr=0.4;
PID myPIDL(&Enc_rpsLeft, &pwmLeft, &rpsLeft, Kpl, Kil, Kdl, DIRECT);
PID myPIDR(&Enc_rpsRight, &pwmRight, &rpsRight, Kpr, Kir, Kdr, DIRECT);
// Interrupts and Timers
void publish_rps();
void obtain_encoder_count();
void doEncoderlA();
void doEncoderlB();
void doEncoderrA();
void doEncoderrB();
// Main fucntions
void setup()
{
TCCR4B &= 0xF8;
TCCR4B |= 0x01;
// Left Wheel setup
pinMode(M1,OUTPUT); //M1 direction control
pinMode(E1,OUTPUT); analogWrite(E1, 0);
pinMode(ELA, INPUT_PULLUP);
pinMode(ELB, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(ELA), doEncoderlA, CHANGE);
attachInterrupt(digitalPinToInterrupt(ELB), doEncoderlB, CHANGE);
// Right Wheel setup
pinMode(M2,OUTPUT); //M2 direction control
pinMode(E2,OUTPUT); analogWrite(E2, 0);
pinMode(ERA, INPUT_PULLUP);
pinMode(ERB, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(ERA), doEncoderrA, CHANGE);
attachInterrupt(digitalPinToInterrupt(ERB), doEncoderrB, CHANGE);
vel_timer.every(50, obtain_encoder_count);
ros_publisher.every(50, publish_rps);
myPIDL.SetSampleTime(10);
myPIDL.SetMode(AUTOMATIC);
myPIDR.SetSampleTime(10);
myPIDR.SetMode(AUTOMATIC);
nh.initNode();
nh.subscribe(sub);
nh.advertise(pub);
nh.advertise(debug);
}
void loop() {
myPIDL.Compute();
myPIDR.Compute();
analogWrite(E1, abs(pwmLeft));
analogWrite(E2, abs(pwmRight));
vel_timer.update();
ros_publisher.update();
nh.spinOnce();
}
void obtain_encoder_count()
{
unsigned long current_time = millis();
double dt = (current_time - past_time)/1000.0;
past_time = current_time;
Enc_rpsLeft = abs((encoderL1-encoderL0) / PPR / dt);
encoderL0 = encoderL1;
Enc_rpsRight = abs((encoderR1-encoderR0) / PPR / dt);
encoderR0 = encoderR1;
debug_msg.x = pwmLeft;
debug_msg.y = pwmRight;
debug_msg.z = dt;
}
void publish_rps()
{
Encoder_Count.header.stamp = nh.now();
Encoder_Count.vector.x = (double) encoderL1/1.0;
Encoder_Count.vector.y = (double) encoderR1/1.0;
pub.publish(&Encoder_Count);
debug.publish(&debug_msg);
}
void doEncoderlA()
{
if (digitalRead(ELA)==HIGH){
if (digitalRead(ELB)==LOW) encoderL1 = encoderL1 - 1; //CCW -
else encoderL1 = encoderL1 + 1; //CW
}
else{
if (digitalRead(ELB)==LOW) encoderL1 = encoderL1 + 1; //CW
else encoderL1 = encoderL1 - 1; //CCW -
}
}
void doEncoderlB()
{
if (digitalRead(ELB)==HIGH){
if (digitalRead(ELA)==LOW) encoderL1 = encoderL1 + 1; //CW
else encoderL1 = encoderL1 - 1; //CCW -
}
else{
if (digitalRead(ELA)==LOW) encoderL1 = encoderL1 - 1; //CCW -
else encoderL1 = encoderL1 + 1; //CW
}
}
void doEncoderrA()
{
if (digitalRead(ERA)==HIGH){
if (digitalRead(ERB)==LOW) encoderR1 = encoderR1 + 1; //CCW
else encoderR1 = encoderR1 - 1; //CW
}
else{
if (digitalRead(ERB)==LOW) encoderR1 = encoderR1 - 1; //CW
else encoderR1 = encoderR1 + 1; //CCW
}
}
void doEncoderrB()
{
if (digitalRead(ERB)==HIGH){
if (digitalRead(ERA)==LOW) encoderR1 = encoderR1 - 1; //CCW
else encoderR1 = encoderR1 + 1; //CCW
}
else{
if (digitalRead(ERA)==LOW) encoderR1 = encoderR1 + 1; //CCW
else encoderR1 = encoderR1 - 1; //CW
}
}
| [
"yagol@mit.edu"
] | yagol@mit.edu |
9be4152e2a2edafe2fd13ea93725d93c6234cbaf | c3894a22b8dde5b92cc36f3bc84135bc58c5b74d | /core/psi/cuckoo_hash.cc | 47522b404b00ea2cf146a7e2e4372ff1a428bc6d | [] | no_license | poloholmes/PaddleFL | 25f4a2ce46b6e8428aa0e22d249642c4e0b3a65b | 8140ad95693b668578ec7918b2e1b0a44dbee6e9 | refs/heads/master | 2023-01-22T01:37:53.997353 | 2020-11-11T12:11:04 | 2020-11-11T12:11:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,305 | cc | // Copyright (c) 2020 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 "cuckoo_hash.h"
namespace psi {
CuckooHasher::CuckooHasher(size_t input_size)
: _bin_num(1.2 * input_size), _cuckoo_size(input_size) {
_bins.resize(_bin_num);
}
void CuckooHasher::insert_item(
size_t item_idx, const std::array<std::vector<block>, 4> &hash_tab,
size_t hash_idx, size_t tried) {
size_t hashval =
*reinterpret_cast<const size_t *>(&hash_tab[hash_idx][item_idx]);
size_t addr = hashval % _bin_num;
if (_bins[addr].is_empty()) {
_bins[addr].item_idx = item_idx;
_bins[addr].hash_idx = hash_idx;
} else if (tried < _cuckoo_size) {
size_t evict_item_idx = _bins[addr].item_idx;
size_t evict_hash_idx = _bins[addr].hash_idx;
_bins[addr].item_idx = item_idx;
_bins[addr].hash_idx = hash_idx;
// use block[0,1,2] as hash val
insert_item(evict_item_idx, hash_tab, (evict_hash_idx + 1) % 3, tried + 1);
} else {
_stash.emplace_back(item_idx, hash_idx);
}
}
void CuckooHasher::insert_all(
const std::array<std::vector<block>, 4> &hash_tab) {
for (size_t idx = 0; idx < hash_tab[0].size(); ++idx) {
insert_item(idx, hash_tab);
}
}
SimpleHasher::SimpleHasher(size_t other_size) : _bin_num(1.2 * other_size) {
_table.resize(_bin_num);
}
void SimpleHasher::insert_all(
const std::array<std::vector<block>, 4> &hash_tab) {
for (size_t item_idx = 0; item_idx < hash_tab[0].size(); ++item_idx) {
for (size_t hash_idx = 0; hash_idx < 3; ++hash_idx) {
size_t hashval =
*reinterpret_cast<const size_t *>(&hash_tab[hash_idx][item_idx]);
size_t addr = hashval % _bin_num;
_table[addr].emplace_back(item_idx, hash_idx);
}
}
}
} // namespace psi
| [
"jingqinghe@baidu.com"
] | jingqinghe@baidu.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.