blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
98c42b39afe13714349b7861415206e8dc3529ac | ea47e149922214f3b8f3cbb700b8e0898978b084 | /torch/csrc/jit/passes/quantization.cpp | ff23b510ec872d7767155417695139e9bef1b481 | [
"BSD-2-Clause",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | permissive | kikaitech/pytorch | 8030c074ac4dfa055b2108f7052bd0a5d947a9c0 | 860790de8805856342a1bee37103184f47a0c26d | refs/heads/master | 2021-05-18T02:44:31.407362 | 2020-03-29T09:06:51 | 2020-03-29T09:09:00 | 251,065,731 | 0 | 0 | NOASSERTION | 2020-03-29T15:29:44 | 2020-03-29T15:29:43 | null | UTF-8 | C++ | false | false | 102,670 | cpp | #include <torch/csrc/jit/passes/quantization.h>
#include <torch/csrc/jit/passes/constant_pooling.h>
#include <torch/csrc/jit/passes/constant_propagation.h>
#include <torch/csrc/jit/passes/freeze_module.h>
#include <torch/csrc/jit/passes/fuse_linear.h>
#include <torch/csrc/jit/passes/graph_rewrite_helper.h>
#include <torch/csrc/jit/passes/inliner.h>
#include <torch/csrc/jit/passes/prepack_folding.h>
#include <torch/csrc/jit/passes/quantization_patterns.h>
#include <torch/csrc/jit/passes/subgraph_rewrite.h>
#include <torch/csrc/jit/frontend/schema_matching.h>
#include <torch/csrc/jit/ir/ir.h>
#include <torch/csrc/jit/ir/irparser.h>
#include <torch/csrc/jit/ir/node_hashing.h>
#include <torch/csrc/jit/ir/subgraph_matcher.h>
#include <torch/csrc/jit/jit_log.h>
#include <torch/csrc/jit/runtime/operator.h>
#include <c10/core/QScheme.h>
#include <algorithm>
#include <stack>
namespace torch {
namespace jit {
namespace {
using OptionalModuleVector = std::vector<c10::optional<Module>>;
using ModuleMethodVector = std::vector<std::pair<Module, std::string>>;
using NameModuleVector = std::vector<std::pair<std::string, Module>>;
using graph_rewrite_helper::getFuncName;
using graph_rewrite_helper::getIValue;
using graph_rewrite_helper::getValue;
using graph_rewrite_helper::replaceConvolutionWithConv2d;
// Map of quantization parameter name and value
// for example _scale, _zero_point,
// _scalar_type and _axis(for per channel quantization)
using QParamVector = std::vector<std::pair<std::string, IValue>>;
// This struct contains a compiled IR patterns slated for use in the
// findPatternMatches function. The struct encapsulates the common
// information from parseIR that is used in conjunction with the
// pattern matching facility. A const instance of this struct can
// also be stored away to cache the compiled IR pattern and reduce
// runtime cost
struct PatternInfo {
std::string pattern_string;
std::unique_ptr<Graph> pattern_graph;
std::unordered_map<std::string, Value*> vmap;
static PatternInfo parse_from_str(std::string pattern_string) {
PatternInfo rv{
std::move(pattern_string), std::make_unique<Graph>(), decltype(vmap){}};
parseIR(rv.pattern_string, rv.pattern_graph.get(), rv.vmap);
return rv;
}
};
struct PatternsAndModules {
bool is_conv;
bool is_per_channel;
const PatternInfo& pattern;
Module packed_params_module;
};
// These are the prim::CallFunctions that doesn't require observation and
// have a single input Tensor
// example: `prim::CallFunction(%dropout, %input_tensor, ...)
// so we propagate observed property from %input_tensor to the
// output of the `prim::CallFunction`
std::vector<std::string> _single_input_general_call_funcs = {
"adaptive_avg_pool2d",
"_max_pool2d",
"dropout",
"interpolate",
"upsample",
"upsample_bilinear",
"upsample_nearest",
"relu",
};
std::vector<std::string> _quantizable_call_funcs = {
"conv2d",
"linear",
};
void fillQConfigMap(
const Module& module,
const QConfigDict& qconfig_dict,
ModuleQConfigMap& map,
const std::string& key = "",
const c10::optional<QConfig>& parent_qconfig = c10::nullopt) {
c10::optional<QConfig> qconfig;
if (qconfig_dict.find(key) != qconfig_dict.end()) {
qconfig = qconfig_dict.at(key);
} else {
qconfig = parent_qconfig;
}
map[module._ivalue()] = qconfig;
for (const NameModule& s : module.named_children()) {
std::string child_key;
if (key == "") {
child_key = s.name;
} else {
child_key = key + "." + s.name;
}
fillQConfigMap(s.value._ivalue(), qconfig_dict, map, child_key, qconfig);
}
}
bool isFunctionNode(
Node* n,
const std::vector<std::string>& call_funcs,
const std::vector<std::string>& aten_funcs) {
std::vector<Symbol> aten_func_symbols;
std::transform(
aten_funcs.begin(),
aten_funcs.end(),
std::back_inserter(aten_func_symbols),
[](const std::string& s) { return Symbol::aten(s); });
bool is_quantizable =
std::find(
aten_func_symbols.begin(), aten_func_symbols.end(), n->kind()) !=
aten_func_symbols.end();
if (n->kind() == prim::CallFunction) {
auto func_name = getFuncName(n->inputs()[0]);
is_quantizable |=
std::find(call_funcs.begin(), call_funcs.end(), func_name) !=
call_funcs.end();
}
return is_quantizable;
}
// checks if a block will always raise an Exception
bool alwaysRaisesException(Block* block) {
for (Node* n : block->nodes()) {
if (n->kind() == prim::RaiseException) {
return true;
}
if (n->kind() == prim::If) {
bool exception = true;
for (Block* b : n->blocks()) {
exception &= alwaysRaisesException(b);
}
if (exception) {
return true;
}
}
}
return false;
}
bool isAddScalar(Node* n) {
return (n->kind() == Symbol::aten("add") ||
n->kind() == Symbol::aten("add_")) &&
n->input(0)->type()->isSubtypeOf(TensorType::get()) &&
n->input(1)->type()->isSubtypeOf(NumberType::get());
}
// If the op doesn't require observation, return
// the the list of input `Value`s that we should check to see
// if they are observed/quantized, if so, we can say the output
// of this op is observed/quantized as well, since for these ops we can derive
// the quantization parameters for output given inputs
std::vector<Value*> getGeneralOpTensorInputs(Node* n) {
std::vector<std::string> single_input_aten_funcs = {
"max_pool2d",
"avg_pool2d",
"flatten",
"max",
"min",
"mean",
"upsample_nearest1d",
"upsample_nearest2d",
"upsample_nearest3d",
"adaptive_avg_pool1d",
"adaptive_avg_pool2d",
"adaptive_avg_pool3d",
"upsample_linear1d",
"upsample_bilinear2d",
"upsample_trilinear3d",
"upsample_bicubic2d",
"dropout",
"reshape",
"chunk",
"view",
"transpose",
"contiguous",
"permute",
"repeat_interleave",
"relu",
// TODO: sort returns a tuple of Tensors, we have
// to extend the API to support that
// "sort",
};
if (isFunctionNode(
n,
// We don't have call functions
// after inline
/* call_funcs = */ _single_input_general_call_funcs,
/* aten_funcs = */ {})) {
return {n->input(1)};
} else if (isFunctionNode(
n,
// We don't have call functions
// after inline
/* call_funcs = */ {},
/* aten_funcs = */ single_input_aten_funcs)) {
return {n->input(0)};
} else if (n->kind() == prim::If && n->outputs().size() == 1) {
std::vector<Value*> inputs;
for (Block* subblock : n->blocks()) {
if (alwaysRaisesException(subblock)) {
continue;
}
auto* output = subblock->outputs()[0];
inputs.push_back(output);
}
return inputs;
} else if (n->kind() == prim::ListUnpack) {
return {n->input(0)};
} else if (n->kind() == prim::ListConstruct) {
std::vector<Value*> inputs;
for (auto* v : n->inputs()) {
inputs.push_back(v);
}
return inputs;
}
return {};
}
bool mayRequireObservation(Value* v) {
return !isAddScalar(v->node());
}
bool nodeQuantizable(Node* n) {
return isFunctionNode(
n,
/* call_funcs = */
_quantizable_call_funcs,
/* aten_funcs = */
{
"conv2d",
"linear",
"addmm",
"matmul",
"add_",
"add",
"cat",
});
}
// We don't want to analyze the graph for some `builtin` CallFunctions
// like `linear` because we want to preserve the op boundary
bool userDefinedCallFunction(Node* n) {
return n->kind() == prim::CallFunction &&
!isFunctionNode(n, _single_input_general_call_funcs, {}) &&
!isFunctionNode(n, _quantizable_call_funcs, {});
}
std::shared_ptr<Graph> getCallFunctionGraph(Node* n) {
auto* func_node = n->input(0)->node();
auto func = func_node->output()->type()->expect<FunctionType>()->function();
TORCH_CHECK(
func->isGraphFunction(), "Quantization only works for graph function");
return func->graph();
}
Module findChildModule(
const Module& module,
const std::vector<std::string>& path) {
Module m = module;
for (const auto& p : path) {
m = m.attr(p).toModule();
}
return m;
}
// Check if value is the input of the graph
bool hitGraphInput(Value* value) {
Graph* graph = value->owningGraph();
const auto& inputs = graph->inputs();
return std::find(inputs.begin(), inputs.end(), value) != inputs.end();
}
// Get the module access path for a Value representing a module instance
// by tracing back the GetAttr nodes and recording all the attribute
// names along the way.
// For example, the module access path will be ['conv1', 'basic_block', 'sub']
// for `self.sub.basic_block.conv1`
std::vector<std::string> getModuleAccessPath(Value* instance, Value* self) {
std::vector<std::string> path;
// Iterator to traverse back the GetAttr calls
Value* iter = instance;
// trace back the instance to recover the path of the submodule
while (!hitGraphInput(iter) && iter->node()->kind() == prim::GetAttr) {
Node* get_attr = iter->node();
// record the name of GetAttr
path.push_back(get_attr->s(attr::name));
// trace back the chain of GetAttr
iter = get_attr->inputs()[0];
}
TORCH_CHECK(
iter == self,
"Can't handle the access pattern of GetAttr "
" in getModuleAccessPath, traced back to:",
iter->debugName(),
" which is not self:",
self->debugName());
return path;
}
Module getInvokedModule(Module& module, Node* n, Value* self) {
auto* instance = n->inputs()[0];
auto path = getModuleAccessPath(instance, self);
return findChildModule(module, path);
}
bool isPerChannel(at::QScheme qscheme) {
return qscheme == c10::kPerChannelAffine ||
qscheme == c10::kPerChannelSymmetric;
}
class ModuleCloneHelper {
public:
/** Clone according to module qconfig map, this is for handling the case
* where we have two module instances sharing the same ClassType
* but configured with different QConfig
* code is copied and modified from
* https://github.com/pytorch/pytorch/blob/master/torch/csrc/jit/api/module.cpp
*/
Module clone(
const Module& module,
const ModuleQConfigMap& module_qconfig_map) {
std::unordered_map<TypePtr, QConfigTypePtrMap> type_remap;
return clone_impl(module, module_qconfig_map, type_remap);
}
private:
Module clone_impl(
const Module& module,
const ModuleQConfigMap& module_qconfig_map,
std::unordered_map<TypePtr, QConfigTypePtrMap>& type_remap) {
auto qconfig = module_qconfig_map.at(module._ivalue());
auto type = module.type();
// Create a new _ivalue in the same compilation unit.
// Since now we have shared ClassType, we need to preserve the shared
// ClassType during cloning, so we first use type and qconfig to check if
// the type is already cloned, if so, we'll create a new module with the
// cloned ClassType, if not, we'll create a new module and a new ClassType.
bool type_already_cloned = type_remap.find(type) != type_remap.end() &&
type_remap.at(type).find(qconfig) != type_remap.at(type).end();
Module r;
if (type_already_cloned) {
// if we cloned the class type before, we'll reuse it
Module new_module(
module._ivalue()->compilation_unit(),
type_remap.at(type).at(qconfig)->cast<ClassType>());
r = new_module;
} else {
Module new_module(
*type->name(), module._ivalue()->compilation_unit(), true);
r = new_module;
type_remap[type][module_qconfig_map.at(module._ivalue())] = r.type();
}
// Copy slots. If a slot is a module - recursively clone it.
size_t N = type->numAttributes();
for (size_t i = 0; i < N; ++i) {
IValue s = module._ivalue()->getSlot(i);
if (type->getAttribute(i)->is_module()) {
const Module& orig = Module(s.toObject());
Module cloned = clone_impl(orig, module_qconfig_map, type_remap);
r.register_module(type->getAttributeName(i), cloned);
} else {
r.register_attribute(
type->getAttributeName(i),
type->getAttribute(i),
s,
type->is_parameter(i));
}
}
// only clone the methods and constants if the ClassType is not cloned
// before
if (!type_already_cloned) {
for (size_t i = 0; i < type->numConstants(); ++i) {
r.type()->addConstant(type->getConstantName(i), type->getConstant(i));
}
// Clone methods remapping the types to the cloned ones.
for (auto& fn : type->methods()) {
clone_method(module, r, *fn, module_qconfig_map, type_remap);
}
}
return r;
}
void remapTypes(
Block* block,
Value* self,
const Module& source,
Module& target,
const ModuleQConfigMap& module_qconfig_map,
const std::function<TypePtr(TypePtr, c10::optional<QConfig>)>&
type_remap_fn) {
// remap of %self will be done outside of the function
// and we don't support the case when people pass in
// module as argument of the method because in that case
// we need to do more comprehensive analysis to decide the
// QConfig for the module
for (size_t i = 1; i < block->inputs().size(); ++i) {
TORCH_CHECK(
!block->inputs()[i]->type()->cast<ClassType>(),
"We don't support quantizing methods that has Object as arguments");
}
for (Node* node : block->nodes()) {
// remapping type for module instance
if (node->kind() == prim::CallMethod) {
Value* instance = node->inputs()[0];
auto path = getModuleAccessPath(instance, self);
auto child = findChildModule(source, path);
auto qconfig = module_qconfig_map.at(child._ivalue());
instance->setType(type_remap_fn(instance->type(), qconfig));
}
// We don't remap output and the remapping of module type
// will be done in CallMethod, we don't support type remapping
// for modules returned from methods or functions
for (Block* sub_block : node->blocks()) {
remapTypes(
sub_block, self, source, target, module_qconfig_map, type_remap_fn);
}
for (Symbol name : node->attributeNames()) {
if (node->kindOf(name) == AttributeKind::g) {
remapTypes(
node->g(name).get(),
source,
target,
module_qconfig_map,
type_remap_fn);
} else if (node->kindOf(name) == AttributeKind::gs) {
for (const auto& g : node->gs(name)) {
remapTypes(
g.get(), source, target, module_qconfig_map, type_remap_fn);
}
}
}
}
}
void remapTypes(
Graph* graph,
const Module& source,
Module& target,
const ModuleQConfigMap& module_qconfig_map,
const std::function<TypePtr(TypePtr, c10::optional<QConfig>)>&
type_remap_fn) {
remapTypes(
graph->block(),
graph->inputs()[0],
source,
target,
module_qconfig_map,
type_remap_fn);
}
void clone_method(
const Module& source,
Module& target,
const Function& method,
const ModuleQConfigMap& module_qconfig_map,
const std::unordered_map<TypePtr, QConfigTypePtrMap>& type_remap) {
auto type_remap_fn = [&](TypePtr type_ptr,
const c10::optional<QConfig>& qconfig) {
if (type_remap.find(type_ptr) != type_remap.end()) {
const auto& qconfig_map = type_remap.at(type_ptr);
if (qconfig_map.find(qconfig) != qconfig_map.end()) {
return qconfig_map.at(qconfig);
}
}
return type_ptr;
};
auto graph = method.graph()->copy();
remapTypes(graph.get(), source, target, module_qconfig_map, type_remap_fn);
// remap self
graph->inputs()[0]->setType(target.type());
const auto this_method_name =
c10::QualifiedName(*target.type()->name(), method.name());
auto copied = target._ivalue()->compilation_unit()->create_function(
this_method_name, graph);
target.type()->addMethod(copied);
// we'll use default schema for cloned method
}
};
class InsertObserversHelper {
public:
explicit InsertObserversHelper(const ModuleQConfigMap& map)
: module_qconfig_map_(map) {}
void preprocess(Module& module, const std::string& method_name);
/**
* Recursively insert observers for the method, also we'll process
* the nodes in the graph in the order of execution of these nodes
* since we need the context information to decide whether we want to
* observe/quantize a value a not, we don't want to observe a value multiple
* times.
*
* arguemnt: is_entry_point means whether the current method is the forward
* method of the top level module.
*
* Since we want to insert observers in the call site instead of in the called
* graph, we'll postpone inserting observer to caller as much as possible, if
* we know the current method is the outer most method, then
* we will insert all observers in the graph instead of postpone this to the
* parent, note that this assumes we don't have recursive method
* calls
*
* returns a tuple of vectors of observer modules for input and output, these
* are used for inserting observers for the input/output values
* since we need to insert these values at call site.
* And a vector of indexes of outputs that indicates whether the output value
* is already observed or not, this is used for propagating the observed
* property of a value through CallMethods, because we should skip inserting
* observers for ops that don't require observation
*/
std::tuple<OptionalModuleVector, OptionalModuleVector, std::vector<size_t>>
insertObservers(
Module& module,
const std::string& method_name,
bool is_entry_point = false,
std::unordered_set<Value*> graph_observed_values =
std::unordered_set<Value*>());
void setDynamicFlag(bool is_dynamic_);
private:
std::tuple<OptionalModuleVector, OptionalModuleVector, std::vector<size_t>>
insertObserversFor(
Block* block,
script::Module& module,
// this is a reference because when we insert observer for a value
// in one block it is also observed in another block, we don't want to
// insert multiple observers for the same value
std::unordered_set<Value*>& block_observed_values,
bool is_entry_point = false,
bool is_user_defined_function = false);
void recordObserved(
Value* v,
Module observer_module,
std::unordered_map<Value*, Module>& values_to_observe,
std::unordered_set<Value*>& block_observed_values);
ModuleMethodVector getInvokedMethods(
Module& module,
const std::string& method_name);
bool valueNeedsToBeQuantized(Value* v);
bool isObserved(
Value* v,
const std::unordered_set<Value*>& block_observed_values) {
return block_observed_values.count(v) || observed_values_.count(v);
}
// Fill the map between the caller input/output to input/output
// of called graph, this is used to navigate through the graph
// to find the observer for a given value
void fillBoundaryValueMap(Module& module, const std::string& method_name);
// Fill the map from value to the corresponding observer module
// this map is used in insertObservers to actually insert
// observers to the module
void fillValueObserverMap(Module& module, const std::string& method_name);
// Clone observer module and add it to the original module,
// and insert a call to observer forward function
void insertObserverFor(
Value* v,
Module& module,
const Module& observer_module,
NameModuleVector& observer_name_and_modules);
c10::optional<Module> getObserverFor(Value* v);
void propagateObservedProperty(
Value* output,
std::unordered_set<Value*>& block_observed_values);
void delayObservingValuesInPattern(
Graph& graph,
const PatternInfo& pattern);
void addValuesToDelayObservation(
const Module& module,
const std::string& method_name);
// Fill the map from values to the list of values that can pass the observed
// property to it
void fillPassThroughValueMap(const std::shared_ptr<Graph>& graph);
const ModuleQConfigMap& module_qconfig_map_;
// Values we want to delay observation, used to delay the observation for
// values in the middle of the ops that are supposed to be fused, e.g.
// the output value of conv in the conv - relu pattern
// the key is the intermediate output, e.g. output of conv
// the value is the value we want to observe, e.g. output of relu
std::unordered_map<Value*, Value*> delay_observation_map_;
std::unordered_set<Graph*> visited_graph_of_observer_map_;
std::unordered_map<Value*, Module> observer_for_value_;
// Map from values from callsite into the values in the CallMethod graph
std::unordered_map<Value*, std::unordered_set<Value*>> boundary_value_map_;
std::unordered_set<Value*> observed_values_;
// This is used for the observed values to pass through the ops like flatten,
// so that output value of platten do not need to be observed
// key of the map is the value from caller graph, and the value of the map
// is the list of values in the callee graph (the graph
// corresponding to the called method),
// the reason it is a vector is that a value in the caller graph
// can both correspond to the output of one callee graph and input of another
// callee graph.
std::unordered_map<Value*, std::vector<Value*>> pass_through_value_map_;
// Unique id generator for observer module, used for generating
// unique observer names when we insert observer module, we
// record the current unique id used to avoid incrementing from 0
// every time to find a unique id.
int uid_ = 0;
// Set of observer forward call nodes
std::unordered_set<Node*> observer_nodes_;
// Map from block to a vector of observer name and observer modules we
// want to add to the module instance that has the block
std::unordered_map<Block*, NameModuleVector> block_observer_map_;
// Is dynamic quantization enabled for the observer pass.
bool is_dynamic = false;
// These are the IR patterns we match to skip inserting observers.
// They are compiled once on construction and used repeatedly within
// the pass.
const PatternInfo conv_functional_relu = PatternInfo::parse_from_str(R"(
graph(%self, %input, %inplace):
%relu = prim::Constant[name="relu"]()
%first_module = match::module[name="Conv2d"](%self)
%first_output = prim::CallMethod[name="forward"](%first_module, %input)
%second_output = prim::CallFunction(%relu, %first_output, %inplace)
return (%second_output) )");
const PatternInfo conv_relu = PatternInfo::parse_from_str(R"(
graph(%self, %input):
%first_module = match::module[name="Conv2d"](%self)
%first_output = prim::CallMethod[name="forward"](%first_module, %input)
%second_module = match::module[name="ReLU"](%self)
%second_output = prim::CallMethod[name="forward"](%second_module, %first_output)
return (%second_output) )");
const PatternInfo matmul_add = PatternInfo::parse_from_str(R"(
graph(%input, %weight, %bias, %4):
%weight_t = aten::t(%weight)
%first_output = aten::matmul(%input, %weight_t)
%second_output = aten::add_(%first_output, %bias, %4)
return (%second_output) )");
const PatternInfo add_module_relu = PatternInfo::parse_from_str(R"(
graph(%self, %a, %b):
%one = prim::Constant[value=1]()
%first_output = aten::add_(%a, %b, %one)
%second_module = match::module[name="ReLU"](%self)
%second_output = prim::CallMethod[name="forward"](%second_module, %first_output)
return (%second_output) )");
const PatternInfo add_functional_relu = PatternInfo::parse_from_str(R"(
graph(%self, %a, %b, %inplace):
%one = prim::Constant[value=1]()
%first_output = aten::add_(%a, %b, %one)
%relu = prim::Constant[name="relu"]()
%second_output = prim::CallFunction(%relu, %first_output, %inplace)
return (%second_output) )");
const std::vector<std::reference_wrapper<const PatternInfo>> delay_patterns = {
conv_functional_relu,
conv_relu,
matmul_add,
add_module_relu,
add_functional_relu,
};
};
// Check if `use` is an aten function of name `func_name` and if value
// `v` is the nth argument of the function
bool isAtenFuncNthArg(
Value* v,
Node* use,
const std::string& func_name,
int n) {
return use->kind() == Symbol::aten(func_name) && v == use->inputs().at(n);
}
// Check if `use` is a CallFunction of name `func_name` and if value
// `v` is the nth argument of the function
bool isCallFunctionNthArg(
Value* v,
Node* use,
const std::string& func_name,
int n) {
return use->kind() == prim::CallFunction &&
getFuncName(use->inputs()[0]) == func_name && v == use->inputs().at(n);
}
struct FuncArg {
std::string func_name;
int arg_index;
};
using AtenFuncArgs = std::vector<FuncArg>;
using CallFuncArgs = std::vector<FuncArg>;
// Check any use of `v` matches the aten function call
// or CallFunction patterns
bool matchArgPattern(
Value* v,
const AtenFuncArgs& aten_func_args,
const CallFuncArgs& call_func_args) {
for (const Use& u : v->uses()) {
for (const auto& func_arg : aten_func_args) {
if (isAtenFuncNthArg(v, u.user, func_arg.func_name, func_arg.arg_index)) {
return true;
}
}
for (const auto& func_arg : call_func_args) {
if (isCallFunctionNthArg(
v, u.user, func_arg.func_name, func_arg.arg_index)) {
return true;
}
}
}
return false;
}
bool isBiasOfConvOrLinear(Value* v) {
bool result = matchArgPattern(
v,
AtenFuncArgs({{"conv2d", 2}, {"linear", 2}}),
CallFuncArgs({{"linear", 3}}));
return result;
}
bool isWeightOfConvOrLinear(Value* v) {
bool result = matchArgPattern(
v,
AtenFuncArgs({{"conv2d", 1}, {"linear", 1}}),
CallFuncArgs({{"linear", 2}}));
return result;
}
Module getObserverModuleFor(Value* v, const QConfig& qconfig) {
return isWeightOfConvOrLinear(v) ? std::get<1>(qconfig)
: std::get<0>(qconfig);
}
ModuleMethodVector InsertObserversHelper::getInvokedMethods(
Module& module,
const std::string& method_name) {
ModuleMethodVector invoked_methods;
Method method = module.get_method(method_name);
auto graph = method.graph();
std::stack<Block*> blocks_to_visit;
blocks_to_visit.push(graph->block());
while (!blocks_to_visit.empty()) {
Block* b = blocks_to_visit.top();
blocks_to_visit.pop();
for (Node* n : b->nodes()) {
// Skip observer nodes
if (observer_nodes_.count(n)) {
continue;
}
if (n->kind() == prim::CallMethod) {
invoked_methods.push_back(std::make_pair(
getInvokedModule(module, n, graph->inputs()[0]), n->s(attr::name)));
}
for (Block* subblock : n->blocks()) {
blocks_to_visit.push(subblock);
}
}
}
return invoked_methods;
}
void InsertObserversHelper::insertObserverFor(
Value* v,
Module& module,
const Module& observer_module,
NameModuleVector& observer_name_and_modules) {
if (observed_values_.count(v)) {
return;
}
Module observer = observer_module.clone_instance();
std::string observer_name = "_observer_" + c10::to_string(uid_++);
while (module.hasattr(observer_name)) {
observer_name = "_observer_" + c10::to_string(uid_++);
}
module.register_module(observer_name, observer);
observer_name_and_modules.push_back(std::make_pair(observer_name, observer));
auto* g = v->owningGraph();
// Get handle of observer module
Node* observer_instance =
g->createGetAttr(g->inputs()[0], observer_name)->insertAfter(v->node());
observer_instance->output()->setDebugName(observer_name);
{
WithInsertPoint guard(observer_instance->next());
// Match arguments to types of observer's arguments
MatchedSchema forward_matched_schema = matchSchema(
observer.get_method("forward").function().getSchema(),
v->node()->sourceRange(),
*g,
{observer_instance->output(), v},
{});
// Insert call to observer's forward
Node* call = g->insertMethodCall("forward", forward_matched_schema)->node();
call->output()->copyMetadata(v);
// Replace v with the output of observer
v->replaceAllUsesWith(call->output());
// The above also replaced the input to `call`, so switch it back to
// the correct value
call->replaceInput(1, v);
observer_nodes_.emplace(call);
observed_values_.insert(call->output());
}
}
void InsertObserversHelper::delayObservingValuesInPattern(
Graph& graph,
const PatternInfo& pattern) {
const Graph& pattern_graph = *pattern.pattern_graph;
const std::unordered_map<std::string, Value*>& vmap = pattern.vmap;
const auto& matches = findPatternMatches(pattern_graph, graph);
for (const auto& match : matches) {
auto first_output = match.values_map.at(vmap.at("first_output"));
auto second_output = match.values_map.at(vmap.at("second_output"));
GRAPH_DEBUG("Delay observation for value in function pattern:",
first_output->debugName(),
" to ",
second_output->debugName());
delay_observation_map_[first_output] = second_output;
}
}
void InsertObserversHelper::addValuesToDelayObservation(
const Module& module,
const std::string& method_name) {
Method method = module.get_method(method_name);
auto graph = method.graph();
for (const auto& pattern : delay_patterns) {
delayObservingValuesInPattern(*graph, pattern);
}
}
void InsertObserversHelper::fillPassThroughValueMap(
const std::shared_ptr<Graph>& graph) {
std::stack<Block*> blocks_to_visit;
blocks_to_visit.push(graph->block());
while (!blocks_to_visit.empty()) {
Block* b = blocks_to_visit.top();
blocks_to_visit.pop();
for (Node* n : b->nodes()) {
if (userDefinedCallFunction(n)) {
auto g = getCallFunctionGraph(n);
blocks_to_visit.push(g->block());
}
auto inputs = getGeneralOpTensorInputs(n);
for (auto* input : inputs) {
for (auto* output : n->outputs()) {
pass_through_value_map_[output].push_back(input);
}
}
for (Block* subblock : n->blocks()) {
blocks_to_visit.push(subblock);
}
}
}
}
void InsertObserversHelper::fillBoundaryValueMap(
Module& module,
const std::string& method_name) {
auto graph = module.get_method(method_name).graph();
std::stack<Block*> blocks_to_visit;
blocks_to_visit.push(graph->block());
auto* self = graph->inputs()[0];
while (!blocks_to_visit.empty()) {
Block* b = blocks_to_visit.top();
blocks_to_visit.pop();
for (Node* n : b->nodes()) {
if (n->kind() == prim::CallMethod || userDefinedCallFunction(n)) {
std::shared_ptr<Graph> g;
// offset of input for the caller node, since the first
// input of CallFunction is the function node and the graph
// for CallFunction start with actual input
size_t input_offset;
if (n->kind() == prim::CallMethod) {
auto m = getInvokedModule(module, n, self);
g = m.get_method(n->s(attr::name)).graph();
input_offset = 0;
} else {
g = getCallFunctionGraph(n);
input_offset = 1;
}
// add mapping from callsite value to value in called graph
for (auto i = 0U; i < g->outputs().size(); ++i) {
auto* return_val = g->outputs()[i];
boundary_value_map_[n->output(i)].insert(return_val);
}
for (auto i = 0U; i < g->inputs().size(); ++i) {
auto caller_input_index = i + input_offset;
auto* caller_input = n->input(caller_input_index);
auto* input_val = g->inputs()[i];
boundary_value_map_[caller_input].insert(input_val);
}
} else if (n->kind() == prim::If) {
for (Block* subblock : n->blocks()) {
blocks_to_visit.push(subblock);
for (Value* v : n->outputs()) {
boundary_value_map_[v].insert(subblock->outputs()[v->offset()]);
}
}
} else {
for (Block* subblock : n->blocks()) {
blocks_to_visit.push(subblock);
}
}
}
}
}
void InsertObserversHelper::setDynamicFlag(bool is_dynamic_) {
is_dynamic = is_dynamic_;
}
void InsertObserversHelper::preprocess(
Module& module,
const std::string& method_name) {
Method method = module.get_method(method_name);
auto graph = method.graph();
// TODO: remove constant prop, add separate graph
// cleanup step before insert observers
// To cleanup traced graph
ConstantPooling(graph);
ConstantPropagation(graph);
// must do constant propagation first before replacement
replaceConvolutionWithConv2d(graph);
// fuse decomposed linear into aten::linear
FuseLinear(graph);
addValuesToDelayObservation(module, method_name);
fillValueObserverMap(module, method_name);
fillBoundaryValueMap(module, method_name);
fillPassThroughValueMap(graph);
for (auto& invoked_method : getInvokedMethods(module, method_name)) {
auto& invoked_module = std::get<0>(invoked_method);
const auto& invoked_method_name = std::get<1>(invoked_method);
preprocess(invoked_module, invoked_method_name);
}
}
// TODO: remove this as a class method
bool InsertObserversHelper::valueNeedsToBeQuantized(Value* v) {
if (isBiasOfConvOrLinear(v) ||
!(v->type()->isSubtypeOf(TensorType::get()) ||
v->type()->isSubtypeOf(ListType::ofTensors()))) {
return false;
}
// For dynamic quantization we only insert observers at the input
// of the quantizable function.
if (!is_dynamic) {
// Check whether producer is quantizable
if (mayRequireObservation(v) &&
nodeQuantizable(v->node())) {
return true;
}
}
// Check whether user is quantizable
for (const auto& use : v->uses()) {
if (nodeQuantizable(use.user)) {
return true;
}
}
return false;
}
void InsertObserversHelper::fillValueObserverMap(
Module& module,
const std::string& method_name) {
Method method = module.get_method(method_name);
auto graph = method.graph();
if (visited_graph_of_observer_map_.count(graph.get())) {
return;
}
visited_graph_of_observer_map_.insert(graph.get());
std::stack<Block*> blocks_to_visit;
auto qconfig_opt = module_qconfig_map_.at(module._ivalue());
if (!qconfig_opt) {
return;
}
auto qconfig = *qconfig_opt;
for (auto* v : graph->inputs()) {
if (valueNeedsToBeQuantized(v)) {
observer_for_value_[v] = getObserverModuleFor(v, qconfig);
}
}
blocks_to_visit.push(graph->block());
while (!blocks_to_visit.empty()) {
Block* b = blocks_to_visit.top();
blocks_to_visit.pop();
for (Node* n : b->nodes()) {
for (Value* v : n->outputs()) {
if (valueNeedsToBeQuantized(v)) {
observer_for_value_[v] = getObserverModuleFor(v, qconfig);
}
}
for (Block* subblock : n->blocks()) {
blocks_to_visit.push(subblock);
}
}
}
}
c10::optional<Module> InsertObserversHelper::getObserverFor(Value* v) {
if (observer_for_value_.count(v)) {
auto observer = observer_for_value_.at(v);
return observer;
}
c10::optional<Module> result;
if (boundary_value_map_.count(v)) {
for (Value* next : boundary_value_map_.at(v)) {
auto observer_opt = getObserverFor(next);
if (observer_opt) {
// Need to make sure all values are
// configured with same observer
if (result) {
TORCH_CHECK(
*observer_opt == *result,
"Expecting all values in the graph only configured with one observer");
} else {
result = observer_opt;
}
}
}
}
return result;
}
std::tuple<OptionalModuleVector, OptionalModuleVector, std::vector<size_t>>
InsertObserversHelper::insertObservers(
Module& module,
const std::string& method_name,
bool is_entry_point,
std::unordered_set<Value*> graph_observed_values) {
auto graph = module.get_method(method_name).graph();
return insertObserversFor(
graph->block(), module, graph_observed_values, is_entry_point);
}
void InsertObserversHelper::recordObserved(
Value* v,
Module observer_module,
std::unordered_map<Value*, Module>& values_to_observe,
std::unordered_set<Value*>& block_observed_values) {
Value* to_observe = v;
if (delay_observation_map_.count(v)) {
to_observe = delay_observation_map_.at(v);
}
values_to_observe[to_observe] = observer_module;
block_observed_values.insert(to_observe);
}
std::tuple<OptionalModuleVector, OptionalModuleVector, std::vector<size_t>>
InsertObserversHelper::insertObserversFor(
Block* block,
script::Module& module,
std::unordered_set<Value*>& block_observed_values,
bool is_entry_point,
bool is_user_defined_function) {
// input/output values, used to skip inserting observers
// for input and output of the block and the owning graph,
// we have to insert the observers at call site because
// the graph itself can be shared
std::unordered_set<Value*> inputs_outputs;
// list of observer modules for input values
std::vector<c10::optional<Module>> block_input_observers;
// list of observer modules for output values
std::vector<c10::optional<Module>> block_output_observers;
// if the current block is the block for entry point graph(the forward graph
// of the top level module), we can insert observers in the block directly
if (!is_entry_point) {
auto* graph = block->owningGraph();
// graph inputs/outputs
for (auto list : {graph->inputs(), graph->outputs()}) {
for (auto* v : list) {
inputs_outputs.insert(v);
}
}
// block outputs
for (auto* v : block->outputs()) {
inputs_outputs.insert(v);
}
for (auto* v : block->inputs()) {
block_input_observers.push_back(getObserverFor(v));
}
for (auto* v : block->outputs()) {
block_output_observers.push_back(getObserverFor(v));
}
}
// This means the block is been processed before, we just
// need to attach observer modules and construct the information
// needed by call site here
bool visited = block_observer_map_.count(block);
if (visited) {
// instance clone of observer module and setAttr
for (const auto& observer_attrs : block_observer_map_.at(block)) {
const auto& name = std::get<0>(observer_attrs);
const auto& observer = std::get<1>(observer_attrs);
module._ivalue()->setAttr(name, observer.clone_instance()._ivalue());
}
}
// NB: Why do we need to process the graph even if it's visited?
// Reason is `graph_observed_values` can
// change depending on where the method is called, and
// outputs that's been observed(third item of the returned result)
// can change depending on that, so for each graph we'll need to go through
// the whole process of inserting observers
std::stack<Block*> blocks_to_visit;
blocks_to_visit.push(block);
auto* self = block->owningGraph()->inputs()[0];
// We first construct a map from value to the module, then
// insert observers for them later, this is to avoid interference
// of the inserted observers with the analysis to decide where
// to insert observers, also we only insert observers for
// "intermediate values" that is not the input/output of the
// graph
std::unordered_map<Value*, Module> values_to_observe;
for (auto* v : block->inputs()) {
if (!inputs_outputs.count(v) && !values_to_observe.count(v)) {
if (auto observer_opt = getObserverFor(v)) {
recordObserved(v, *observer_opt, values_to_observe, block_observed_values);
}
}
}
while (!blocks_to_visit.empty()) {
Block* b = blocks_to_visit.top();
blocks_to_visit.pop();
for (Node* n : b->nodes()) {
if (observer_nodes_.count(n)) {
continue;
}
if (n->kind() == prim::CallMethod || userDefinedCallFunction(n)) {
script::Module m;
std::shared_ptr<Graph> g;
size_t input_offset;
bool is_udf_for_subblock = is_user_defined_function;
if (n->kind() == prim::CallMethod) {
m = getInvokedModule(module, n, self);
g = m.get_method(n->s(attr::name)).graph();
input_offset = 0;
} else { // CallFunction
m = module;
g = getCallFunctionGraph(n);
input_offset = 1;
is_udf_for_subblock = true;
}
std::unordered_set<Value*> callee_observed_inputs;
for (auto i = 0U; i < g->inputs().size(); ++i) {
auto* node_input = n->input(i + input_offset);
if (isObserved(node_input, block_observed_values)) {
callee_observed_inputs.insert(g->inputs()[i]);
}
}
auto* subblock = g->block();
auto info_from_callee = insertObserversFor(
subblock, m, callee_observed_inputs, false, is_udf_for_subblock);
auto input_observers = std::get<0>(info_from_callee);
auto output_observers = std::get<1>(info_from_callee);
auto callee_observed_outputs = std::get<2>(info_from_callee);
for (auto idx : callee_observed_outputs) {
block_observed_values.insert(n->outputs()[idx]);
}
for (auto i = 0U; i < g->inputs().size(); ++i) {
auto* node_input = n->input(i + input_offset);
if (input_observers[i] && !inputs_outputs.count(node_input) &&
!isObserved(node_input, block_observed_values)) {
recordObserved(node_input, *input_observers[i],
values_to_observe, block_observed_values);
}
}
for (auto i = 0U; i < n->outputs().size(); ++i) {
if (output_observers[i] && !inputs_outputs.count(n->output(i)) &&
!isObserved(n->output(i), block_observed_values)) {
recordObserved(n->output(i), *output_observers[i],
values_to_observe, block_observed_values);
}
}
} else if (n->kind() == prim::If) {
std::vector<size_t> aggregated_observed_outputs;
std::vector<c10::optional<script::Module>> aggregated_output_observers;
for (Block* subblock : n->blocks()) {
// subblock has access to all the values in the scope of prim::If,
// so subblock_observed_values == block_observed_values
auto info_from_subblock =
insertObserversFor(subblock, module, block_observed_values);
auto output_observers = std::get<1>(info_from_subblock);
auto subblock_observed_outputs = std::get<2>(info_from_subblock);
// subblock for prim::If doesn't have inputs
if (aggregated_observed_outputs.size() > 0) {
TORCH_CHECK(
aggregated_observed_outputs == subblock_observed_outputs,
"quantization doesn't work for the case where branches "
"of `if` doesn't both return quantized/non-quantized "
"values");
} else {
for (auto idx : subblock_observed_outputs) {
block_observed_values.insert(n->output(idx));
}
aggregated_observed_outputs = subblock_observed_outputs;
}
if (aggregated_output_observers.size() > 0) {
TORCH_CHECK(
aggregated_output_observers == output_observers,
"quantization doesn't work for the case where branches "
"of `if` doesn't both return values quantized the same "
"way");
} else {
for (auto i = 0; i < n->outputs().size(); ++i) {
if (output_observers[i] && !inputs_outputs.count(n->output(i)) &&
!block_observed_values.count(n->output(i)) &&
!observed_values_.count(n->output(i))) {
recordObserved(n->output(i), *output_observers[i],
values_to_observe, block_observed_values);
}
}
aggregated_output_observers = output_observers;
}
}
} else {
for (Value* v : n->outputs()) {
propagateObservedProperty(v, block_observed_values);
if (!inputs_outputs.count(v) &&
!isObserved(v, block_observed_values)) {
if (auto observer_opt = getObserverFor(v)) {
recordObserved(v, *observer_opt, values_to_observe, block_observed_values);
}
}
}
for (Block* subblock : n->blocks()) {
blocks_to_visit.push(subblock);
}
}
}
}
std::vector<size_t> output_idxs;
for (auto i = 0U; i < block->outputs().size(); ++i) {
if (isObserved(block->outputs()[i], block_observed_values)) {
output_idxs.push_back(i);
}
}
if (!visited) {
NameModuleVector observer_name_and_modules;
for (const auto& item : values_to_observe) {
auto* v = item.first;
auto observer = item.second;
TORCH_CHECK(!is_user_defined_function,
"Inserting observers for user defined functions is not "
"supported right now");
insertObserverFor(v, module, observer, observer_name_and_modules);
}
block_observer_map_[block] = observer_name_and_modules;
}
return std::make_tuple(
block_input_observers, block_output_observers, output_idxs);
}
void InsertObserversHelper::propagateObservedProperty(
Value* output,
std::unordered_set<Value*>& block_observed_values) {
if (pass_through_value_map_.count(output)) {
// since the vector is always non-empty, we will
// not return the initial value
bool all_observed = true;
for (Value* v : pass_through_value_map_.at(output)) {
all_observed &=
observed_values_.count(v) || block_observed_values.count(v);
}
if (all_observed) {
// This is to propagate observed property through
// all ops that doesn't require observation
block_observed_values.insert(output);
}
}
}
void insertDeQuantCall(
Graph* graph,
Value* quantized_val,
Value* original_val,
const std::vector<Use>& uses) {
for (size_t i = 0; i < uses.size(); ++i) {
auto* user = uses[i].user;
// Insert dequantize node right before use node, because
// we want to make sure use node and dequantize node reside
// in the same block so that quant fusion can happen
WithInsertPoint ins(user);
Node* dequant = graph->create(Symbol::aten("dequantize"), {quantized_val});
dequant->output()
->setDebugName(
original_val->debugName() + ".dequant." + c10::guts::to_string(i))
->setType(original_val->type());
user->replaceInputWith(original_val, dequant->output());
graph->insertNode(dequant);
}
}
void insertQuantDeQuantCall(
Value* self,
Node* observer,
bool is_per_channel,
const std::vector<std::string>& qparam_names) {
Graph* g = observer->owningGraph();
// Original value that is observed
Value* v = observer->input(1);
// Inserting before insert point
WithInsertPoint ins(v->node()->next());
std::vector<Value*> inputs = {v};
// Insert GetAttr nodes for quantization parameters
for (const auto& qparam_name : qparam_names) {
inputs.push_back(g->insertGetAttr(self, qparam_name));
}
std::string quantize_func;
if (is_per_channel) {
quantize_func = "quantize_per_channel";
} else {
quantize_func = "quantize_per_tensor";
}
Node* quant = g->create(at::Symbol::aten(quantize_func), inputs);
quant->output()->setDebugName(v->debugName() + ".quant");
g->insertNode(quant);
// two passes to insert the dequant for every usage
// in first pass, identify all the nodes using "v"
std::vector<Use> uses;
for (const auto& use : v->uses()) {
// Skip quant node and observer node (we need to keep
// observer nodes around since we need them to
// find the quantization parameters)
if (use.user != quant && use.user != observer) {
uses.push_back(use);
}
}
// in second pass, replace the input "v" with dequant output
insertDeQuantCall(g, quant->output(), v, uses);
}
// find the observer for Value `v` and return the name of the observer
c10::optional<std::string> findObserverName(Value* v) {
// Note that here we just check for the name of observer, but the ideally
// we should be comparing the type of observer, this is a temporary
// work around until data only clone of module.clone is supported.
Node* n = v->node();
if (n->kind() == prim::CallMethod && n->s(attr::name) == "forward") {
auto module_instance = n->inputs().at(0);
if (module_instance->node()->kind() == prim::GetAttr &&
module_instance->node()->s(attr::name).find("_observer_") !=
std::string::npos) {
return module_instance->node()->s(attr::name);
}
}
return c10::nullopt;
}
c10::QScheme toAffine(c10::QScheme qscheme) {
switch (qscheme) {
case c10::kPerTensorAffine:
case c10::kPerTensorSymmetric:
return c10::kPerTensorAffine;
case c10::kPerChannelAffine:
case c10::kPerChannelSymmetric:
return c10::kPerChannelAffine;
default:
return qscheme;
}
}
class InsertQuantDeQuantHelper {
public:
InsertQuantDeQuantHelper() {}
void run(Module& module, const std::string& method_name);
ModuleMethodVector getInvokedMethods(
Module& module,
const std::string& method_name);
// Get quantization parameter map of the given Value in Graph
// by searching for observer module of the value and extract the
// quantization parameters from the observer module
std::tuple<c10::QScheme, QParamVector> getQSchemeAndQParamVector(
script::Module& module,
Node* n);
void checkQScheme(Graph* g, c10::QScheme qscheme) {
if (qscheme_for_graph_.count(g)) {
TORCH_CHECK(
qscheme_for_graph_.at(g) == qscheme ||
"Quantizing same graph with different types of "
"QSchemes is not supported.\n",
" Expecting:",
c10::toString(qscheme_for_graph_.at(g)),
" Got:",
c10::toString(qscheme));
} else {
qscheme_for_graph_[g] = toAffine(qscheme);
}
}
c10::optional<Module> findChildModuleToQuantize(
Module& module,
Value* child_instance);
void collectObserverNodesAndValueToQuantize(Module& module, Value*);
// Cleanup observer nodes from graph and observer modules
// from module object and ClassType
void cleanup(Module& module);
void cleanup(Module& module, Graph* g);
void quantizeTensors(Module& module, Graph* g, Value* self);
private:
std::unordered_map<Graph*, std::vector<std::string>>
observer_modules_to_remove_;
// We only remove observer module attributes from type in the
// first encounter of the graph, after that since the attributes
// is already removed from the ClassType, we'll use the list of slot index to
// replay this removal
std::unordered_map<Graph*, std::vector<int>> removed_observer_slots_;
std::unordered_map<Graph*, std::vector<Node*>> nodes_to_destroy_;
// Map from Graph to observer node, we can use observer node to
// get the information of original value that's been observed and
// the quantization parameters
std::unordered_map<Graph*, std::vector<Node*>> observer_nodes_for_graph_;
// A map from qparam name (e.g. _scale) to the attribute name in
// the module(e.g. weight_scale_0)
std::unordered_map<Node*, std::unordered_map<std::string, std::string>>
qparam_name_map_for_node_;
// Record qscheme for every graph, this is for checking
// each graph is only quantized with one type of QScheme
std::unordered_map<Graph*, c10::QScheme> qscheme_for_graph_;
};
void InsertQuantDeQuantHelper::collectObserverNodesAndValueToQuantize(
Module& module,
Value* v) {
auto* g = v->owningGraph();
auto observer_name = findObserverName(v);
if (!observer_name) {
return;
}
observer_modules_to_remove_[g].push_back(observer_name.value());
Node* observer = v->node();
TORCH_INTERNAL_ASSERT(
observer->kind() == prim::CallMethod &&
observer->s(attr::name) == "forward" &&
observer->inputs()[0]->node()->kind() == prim::GetAttr &&
observer->inputs()[0]->node()->s(attr::name) == observer_name);
// Observer forward call node
nodes_to_destroy_[g].push_back(observer);
// GetAttr node for observer module
nodes_to_destroy_[g].push_back(observer->inputs()[0]->node());
Value* original_value = observer->input(1);
v->replaceAllUsesWith(original_value);
observer_nodes_for_graph_[g].push_back(observer);
}
void InsertQuantDeQuantHelper::cleanup(Module& module) {
for (auto& method : module.get_methods()) {
cleanup(module, method.graph().get());
}
for (Module m : module.children()) {
cleanup(m);
}
}
void InsertQuantDeQuantHelper::cleanup(Module& module, Graph* g) {
GRAPH_DUMP("Before Remove Observers:", g);
if (nodes_to_destroy_.count(g)) {
for (auto& n : nodes_to_destroy_.at(g)) {
n->removeAllInputs();
}
for (auto& n : nodes_to_destroy_.at(g)) {
n->destroy();
}
nodes_to_destroy_.at(g).clear();
}
// 1. If we have seen this graph before, this means the observer
// attributes has been removed from the type(see step 2) but the slot
// index of these attributes are kept in the list, we'll replay the observer
// slots removal using these slot indexes
if (removed_observer_slots_.count(g)) {
for (auto slot : removed_observer_slots_.at(g)) {
module._ivalue()->unsafeRemoveSlot(slot);
}
}
// 2. Remove observer modules from last one to first one in order to
// reduce the time complexity, assuming all the observer modules
// are added after the existing modules, we'll have complexity of
// O(N) where N is number of observer modules with this optimization
if (observer_modules_to_remove_.count(g)) {
auto& observers = observer_modules_to_remove_.at(g);
for (int64_t i = observers.size() - 1; i >= 0; --i) {
auto observer_name = observers[i];
GRAPH_DEBUG("Trying to remove: ", observer_name);
if (module.type()->hasAttribute(observer_name)) {
// We record the slot index here in order to replay the
// slot removal in other objects that's sharing the ClassType
// since we're going to remove attribute in the ClassType here
removed_observer_slots_[g].push_back(
module.type()->getAttributeSlot(observer_name));
module._ivalue()->unsafeRemoveAttr(observer_name);
module.type()->unsafeRemoveAttribute(observer_name);
}
}
observers.clear();
}
GRAPH_DUMP("After remove observers :", g);
}
void InsertQuantDeQuantHelper::quantizeTensors(
Module& module,
Graph* g,
Value* self) {
if (!observer_nodes_for_graph_.count(g)) {
return;
}
for (auto* n : observer_nodes_for_graph_.at(g)) {
auto* original_value = n->input(1);
auto tp = getQSchemeAndQParamVector(module, n);
auto qscheme = std::get<0>(tp);
auto qparam_map = std::get<1>(tp);
checkQScheme(g, qscheme);
std::vector<std::string> qparam_names;
for (auto& pr : qparam_map) {
const auto& name = pr.first;
const auto& qparam = pr.second;
size_t uid = 0;
auto qparam_name =
original_value->debugName() + name + "_" + c10::to_string(uid++);
while (module.hasattr(qparam_name)) {
qparam_name =
original_value->debugName() + name + "_" + c10::to_string(uid++);
}
qparam_name_map_for_node_[n][name] = qparam_name;
module.register_attribute(qparam_name, qparam.type(), qparam);
qparam_names.push_back(qparam_name);
}
insertQuantDeQuantCall(self, n, isPerChannel(qscheme), qparam_names);
}
}
void checkGetQParamsResult(const IValue& qparams) {
TORCH_CHECK(
qparams.isTuple(),
"`get_qparams` function is expected to return a "
"Tuple, but got:",
qparams.tagKind());
auto tp = qparams.toTuple();
TORCH_CHECK(
tp->elements().size() == 2 || tp->elements().size() == 3,
"`get_qparams` function is expected to return a "
"Tuple of size 2 or 3, got Tuple of size ",
tp->elements().size());
// Expect first two elements of the tuple to be Tensor
for (size_t i = 0; i < 2; ++i) {
TORCH_CHECK(
tp->elements()[i].isTensor(),
"Element of Tuple is expected to be Tensor, but element ",
i,
" has type: ",
tp->elements()[i].tagKind());
}
// Expect the third elements of the tuple to be int
if (tp->elements().size() == 3) {
TORCH_CHECK(
tp->elements()[2].isInt(),
"Element of Tuple is expected to be int, but element ",
2,
" has type: ",
tp->elements()[2].tagKind());
}
}
std::tuple<c10::QScheme, QParamVector> InsertQuantDeQuantHelper::
getQSchemeAndQParamVector(script::Module& module, Node* n) {
// TODO: refactor findObserverName to take Node* as input
Value* v = n->output();
TORCH_INTERNAL_ASSERT(
v->type()->isSubtypeOf(TensorType::get()),
"Expected output of observer node to be Tensor");
auto observer_name = findObserverName(v);
TORCH_INTERNAL_ASSERT(
observer_name,
"getQSchemeAndParamMap expects the corresponding observer for ",
v->debugName(),
" exists.");
auto observer_module = module.attr(observer_name.value()).toModule();
auto get_qparams = observer_module.get_method("get_qparams");
IValue result = get_qparams(std::vector<IValue>());
checkGetQParamsResult(result);
auto scalar_type = observer_module.attr("dtype");
TORCH_CHECK(
scalar_type.toScalarType() != at::ScalarType::Undefined,
"dtype of observer can't be undefined");
auto tp = result.toTuple();
at::Tensor scale = tp->elements()[0].toTensor().to(at::kFloat);
at::Tensor zero_point = tp->elements()[1].toTensor().to(at::kInt);
// quantization parameters should appear in the same order as
// the argument for quantize_per_tensor/quantize_per_channel function
QParamVector qparams;
auto qscheme = observer_module.attr("qscheme").toQScheme();
if (isPerChannel(qscheme)) {
qparams.push_back(std::make_pair("_scale", scale));
qparams.push_back(std::make_pair("_zero_point", zero_point));
qparams.push_back(std::make_pair("_axis", tp->elements()[2].toInt()));
} else {
qparams.push_back(std::make_pair("_scale", scale.item<double>()));
qparams.push_back(
std::make_pair("_zero_point", zero_point.item<int64_t>()));
}
qparams.push_back(std::make_pair("_scalar_type", scalar_type));
return std::make_tuple(qscheme, qparams);
}
c10::optional<Module> InsertQuantDeQuantHelper::findChildModuleToQuantize(
Module& module,
Value* child_instance) {
TORCH_INTERNAL_ASSERT(
child_instance->node()->kind() == prim::GetAttr,
"Child instance should come from GetAttr.");
auto child_module_name = child_instance->node()->s(attr::name);
if (child_module_name.find("_observer_") == std::string::npos) {
return module.attr(child_module_name).toModule();
}
return c10::nullopt;
}
ModuleMethodVector InsertQuantDeQuantHelper::getInvokedMethods(
Module& module,
const std::string& method_name) {
auto graph = module.get_method(method_name).graph();
ModuleMethodVector invoked_methods;
std::stack<Block*> blocks_to_visit;
blocks_to_visit.push(graph->block());
while (!blocks_to_visit.empty()) {
Block* b = blocks_to_visit.top();
blocks_to_visit.pop();
for (Node* n : b->nodes()) {
if (n->kind() == prim::CallMethod) {
auto module_instance = n->inputs()[0];
auto module_method_name = n->s(attr::name);
c10::optional<Module> m;
// calling method on self
if (module_instance == graph->inputs()[0]) {
m = module;
} else {
m = findChildModuleToQuantize(module, module_instance);
}
if (m) {
invoked_methods.push_back({*m, module_method_name});
}
}
for (Block* subblock : n->blocks()) {
blocks_to_visit.push(subblock);
}
}
}
return invoked_methods;
}
void InsertQuantDeQuantHelper::run(
Module& module,
const std::string& method_name) {
for (auto& invoked_methods : getInvokedMethods(module, method_name)) {
auto& invoked_module = std::get<0>(invoked_methods);
const auto& invoked_method_name = std::get<1>(invoked_methods);
run(invoked_module, invoked_method_name);
}
Method method = module.get_method(method_name);
auto graph = method.graph();
// We only need to register new parameters if the graph has
// been quantized before
// TODO: dedup this part with code in quantizeTensors
if (observer_nodes_for_graph_.count(graph.get())) {
for (auto* n : observer_nodes_for_graph_.at(graph.get())) {
auto tp = getQSchemeAndQParamVector(module, n);
checkQScheme(graph.get(), std::get<0>(tp));
auto qparam_map = std::get<1>(tp);
TORCH_INTERNAL_ASSERT(
qparam_name_map_for_node_.count(n),
"Expected to have a qparam_name_map for node:",
*n);
auto qparam_name_map = qparam_name_map_for_node_.at(n);
for (auto& pr : qparam_map) {
const auto& name = pr.first;
const auto& qparam = pr.second;
module._ivalue()->setAttr(qparam_name_map.at(name), qparam);
}
}
return;
}
// prim::Param nodes do not belong to the graph. Hence the Insert
// point is the beginning of graph node. This also safe guards against
// observing a potentially mutated value due to some in-place operation
std::vector<Value*> input_values;
for (size_t idx = 1; idx < method.num_inputs(); ++idx) {
auto& v = graph->inputs()[idx];
if (v->type()->isSubtypeOf(TensorType::get())) {
input_values.push_back(v);
}
}
std::stack<Block*> blocks_to_visit;
blocks_to_visit.push(graph->block());
while (!blocks_to_visit.empty()) {
Block* b = blocks_to_visit.top();
blocks_to_visit.pop();
for (auto it = b->nodes().begin(), end = b->nodes().end(); it != end;) {
Node* n = *it++;
for (Value* v : n->outputs()) {
if (!v->type()->isSubtypeOf(TensorType::get())) {
continue;
}
collectObserverNodesAndValueToQuantize(module, v);
}
for (Block* subblock : n->blocks()) {
blocks_to_visit.push(subblock);
}
}
}
for (Value* v : input_values) {
collectObserverNodesAndValueToQuantize(module, v);
}
GRAPH_DUMP("Before Quantize Tensors:", graph);
Value* self = graph->inputs()[0];
quantizeTensors(module, graph.get(), self);
GRAPH_DUMP("After Quantize Tensors:", graph);
}
void insertPrepackUnpackForLinear(std::shared_ptr<Graph>& graph) {
std::string linear_with_quant = R"(
graph(%a_dequant, %w_quant, %b):
%w_dequant = aten::dequantize(%w_quant)
%r = aten::linear(%a_dequant, %w_dequant, %b)
return (%r) )";
std::string linear_with_quant_prepack = R"(
graph(%a_dequant, %w_quant, %b):
%packed_params = quantized::linear_prepack(%w_quant, %b)
%w_quant_unpacked : Tensor, %b_unpacked : Tensor? = quantized::linear_unpack(%packed_params)
%w_dequant = aten::dequantize(%w_quant_unpacked)
%r = aten::linear(%a_dequant, %w_dequant, %b_unpacked)
return (%r) )";
SubgraphRewriter rewriter;
rewriter.RegisterRewritePattern(linear_with_quant, linear_with_quant_prepack);
rewriter.runOnGraph(graph);
}
void insertPrepackUnpackForConv2d(std::shared_ptr<Graph>& graph) {
std::string conv_with_quant = R"(
graph(%a_dequant, %w_quant, %b, %stride, %padding, %dilation, %groups):
%w_dequant = aten::dequantize(%w_quant)
%r = aten::conv2d(%a_dequant, %w_dequant, %b, %stride, %padding, %dilation, %groups)
return (%r) )";
std::string conv_with_quant_prepack = R"(
graph(%a_dequant, %w_quant, %b, %stride, %padding, %dilation, %groups):
%packed_params = quantized::conv2d_prepack(%w_quant, %b, %stride, %padding, %dilation, %groups)
%w_quant_unpacked : Tensor, %b_unpacked : Tensor? = quantized::conv2d_unpack(%packed_params)
%w_dequant = aten::dequantize(%w_quant_unpacked)
%r = aten::conv2d(%a_dequant, %w_dequant, %b_unpacked, %stride, %padding, %dilation, %groups)
return (%r) )";
SubgraphRewriter rewriter;
rewriter.RegisterRewritePattern(conv_with_quant, conv_with_quant_prepack);
rewriter.runOnGraph(graph);
}
c10::optional<IValue> toTwoElementIntList(Value* v) {
auto* n = v->node();
if (n->kind() == prim::Constant) {
auto iv = toIValue(v);
if (iv && iv.value().isIntList() && iv.value().toIntList().size() == 2) {
return iv;
}
}
if (n->kind() == prim::ListConstruct && n->inputs().size() == 2) {
auto e0 = toIValue(n->inputs()[0]);
auto e1 = toIValue(n->inputs()[1]);
if (!e0 || !e1 || !e0.value().isInt() || !e1.value().isInt()) {
return c10::nullopt;
}
return IValue(c10::List<int64_t>({e0.value().toInt(), e1.value().toInt()}));
}
return c10::nullopt;
}
// A helper class to make uses of module unique
class ModuleUseDeduper {
public:
ModuleUseDeduper(Module& module) : module_(module) {}
void dedup() {
for (auto& method : module_.get_methods()) {
const auto& graph = method.graph();
findModuleUses(graph.get());
}
dedupModuleUses();
}
private:
// Analyze the code to record information represents
// uses of the module, which we'll use later to actually perform the dedup
// operation Please see the comments of member variables of the class for more
// information
void findModuleUses(Graph* graph) {
GRAPH_DUMP("Finding module uses for ", graph);
std::stack<Block*> blocks_to_visit;
blocks_to_visit.push(graph->block());
Value* self = graph->inputs()[0];
while (!blocks_to_visit.empty()) {
Block* b = blocks_to_visit.top();
blocks_to_visit.pop();
for (Node* n : b->nodes()) {
for (Block* subblock : n->blocks()) {
blocks_to_visit.push(subblock);
}
if (n->kind() != prim::CallMethod) {
continue;
}
Value* instance = n->inputs()[0];
// boundary_val is the value we get when we trace back
// the GetAttr access chain until we hit the input of graph
// or a node that is not prim::GetAttr
auto path = getModuleAccessPath(instance, self);
// path.size() == 0 means we're calling a method
// on self, we don't need to dedup uses of self
if (path.size() == 0) {
continue;
}
value_to_path_map_[instance] = path;
auto m = findChildModule(module_, path);
// If we fail to insert the module to the unique_modules_ set,
// which means there are uses of this module before this point,
// we'll have to rewrite the use
if (!unique_modules_.insert(m._ivalue()).second) {
uses_to_rewrite_.push_back(instance);
GRAPH_DEBUG("Found use to rewrite: ", instance->debugName());
}
}
}
}
// Deduplicate module uses given the information we recorded before
void dedupModuleUses() {
for (Value* v : uses_to_rewrite_) {
const auto& path = value_to_path_map_.at(v);
const auto& m = findChildModule(module_, path);
// add a clone of the child module to the parent of the duplicated module
const auto& child_name = addChildModule(module_, m, path);
TORCH_INTERNAL_ASSERT(v->node()->kind() == prim::GetAttr);
// change the name in GetAttr call
auto original_name = v->node()->s(attr::name);
v->node()->s_(attr::name, child_name);
GRAPH_UPDATE(
"Module use dedup: changing use of original module ",
original_name,
" to ",
child_name);
}
}
std::string addChildModule(
Module& module,
const Module& child_module,
const std::vector<std::string>& path) {
TORCH_INTERNAL_ASSERT(
path.size() > 0, "path must have at least one element.");
// Parent module of the leaf child module corresponding to
// the path
auto parent_of_leaf = findChildModule(
module, std::vector<std::string>(path.begin(), path.end() - 1));
// Original name of the child module
std::string original_name = path[path.size() - 1];
int uid = 0;
std::string child_name = original_name + "_" + c10::to_string(uid++);
while (parent_of_leaf.hasattr(child_name)) {
child_name = original_name + "_" + c10::to_string(uid++);
}
parent_of_leaf.register_module(child_name, child_module.clone_instance());
return child_name;
}
Module module_;
// Map from value of module instance to the list of names of submodules
// starting from the top level module, e.g. ["sub1", "sub2", "relu"]
// Also this is a cache of calling `getModuleAccessPath` of the value
std::unordered_map<Value*, std::vector<std::string>> value_to_path_map_;
// Set of unique modules that are used in the graphs
std::unordered_set<ModulePtr> unique_modules_;
// Values that represent the module instance(the use of the module)
// that we'll need to rewrite as a use of a cloned module
// instance
std::vector<Value*> uses_to_rewrite_;
};
struct ConvBNParameters {
at::Tensor conv_w;
at::Tensor conv_b;
at::Tensor bn_rm;
at::Tensor bn_rv;
double bn_eps = 0.0;
at::Tensor bn_w;
at::Tensor bn_b;
};
static bool hastensor(Module& m, const char* name) {
return m.hasattr(name) && m.attr(name).isTensor();
}
class FoldConvBatchNorm2dHelper {
public:
/**
* In this step we find all Conv2d - BatchNorm2d patterns in the graph
* and extract the corresponding parameters for these two modules,
* and record informations for the modifications of the graph without
* actually performing these modifications.
*/
void analyze(Module& module);
/**
* In this step we perform all the modifications including
* setting the attributes for conv module, rewriting values
* and deleting nodes in the graph
*/
void transform();
private:
bool tryExtractingConvBNParameters(
Module& conv,
Module& bn,
ConvBNParameters& r);
/**
* Given the current weight and bias tensors of a Conv2d module and parameters
* of the BatchNorm2d module we're folding with, compute the updated values
* for the weight and bias.
*
* The function is basically copied from torch/nn/utils/fusion.py
*/
std::tuple<at::Tensor, at::Tensor> computeUpdatedConvWeightAndBias(
const ConvBNParameters& p);
std::unordered_map<ModulePtr, std::tuple<at::Tensor, at::Tensor>>
conv_module_and_params_;
std::unordered_map<Graph*, std::vector<std::tuple<std::string, std::string>>>
conv_bn_names_;
std::unordered_map<Value*, Value*> rewrite_map_;
std::vector<Value*> values_to_rewrite_;
std::unordered_set<Node*> nodes_to_delete_;
};
std::tuple<at::Tensor, at::Tensor> FoldConvBatchNorm2dHelper::
computeUpdatedConvWeightAndBias(const ConvBNParameters& p) {
at::Tensor bn_var_rsqrt = at::rsqrt(p.bn_rv + p.bn_eps);
at::Tensor new_w = p.conv_w * (p.bn_w * bn_var_rsqrt).reshape({-1, 1, 1, 1});
at::Tensor new_b = (p.conv_b - p.bn_rm) * bn_var_rsqrt * p.bn_w + p.bn_b;
return std::make_tuple(new_w, new_b);
}
bool extractOptionalBNParams(const script::Module& bn, ConvBNParameters& r) {
auto bn_forward = bn.get_method("forward");
auto graph = bn_forward.graph();
const PatternInfo& pattern_bn = PatternInfo::parse_from_str(R"(
graph(%a, %weight, %bias, %running_mean, %running_var,
%training, %momentum, %eps, %cudnn_enabled):
%bn_out = aten::batch_norm(%a, %weight, %bias, %running_mean,
%running_var, %training, %momentum, %eps, %cudnn_enabled)
return (%bn_out) )");
const Graph& pattern_bn_graph = *pattern_bn.pattern_graph;
const auto& bn_vmap = pattern_bn.vmap;
const auto& matches = findPatternMatches(pattern_bn_graph, *graph);
if (matches.size() > 1) {
return false;
}
if (bn.hasattr("eps")) {
r.bn_eps = bn.attr("eps").toDouble();
} else {
auto optional_eps = toIValue(matches[0].values_map.at(bn_vmap.at("eps")));
if (!optional_eps) {
return false;
}
r.bn_eps = optional_eps.value().toDouble();
}
r.bn_w = at::ones_like(bn.attr("running_mean").toTensor());
if (bn.hasattr("weight")) {
if (bn.attr("weight").isTensor()) {
r.bn_w = bn.attr("weight").toTensor();
}
} else {
auto optional_bn_weight =
toIValue(matches[0].values_map.at(bn_vmap.at("weight")));
if (!optional_bn_weight) {
return false;
}
if (optional_bn_weight.value().isTensor()) {
r.bn_w = optional_bn_weight.value().toTensor();
}
}
r.bn_b = at::zeros_like(bn.attr("running_mean").toTensor());
if (bn.hasattr("bias")) {
if (bn.attr("bias").isTensor()) {
r.bn_b = bn.attr("bias").toTensor();
}
} else {
auto optional_bn_bias =
toIValue(matches[0].values_map.at(bn_vmap.at("bias")));
if (!optional_bn_bias) {
return false;
}
if (optional_bn_bias.value().isTensor()) {
r.bn_b = optional_bn_bias.value().toTensor();
}
}
return true;
}
bool FoldConvBatchNorm2dHelper::tryExtractingConvBNParameters(
Module& conv,
Module& bn,
ConvBNParameters& r) {
if (!hastensor(conv, "weight") || !conv.hasattr("bias") ||
!hastensor(bn, "running_mean") || !hastensor(bn, "running_var")) {
return false;
}
r.bn_rm = bn.attr("running_mean").toTensor();
r.bn_rv = bn.attr("running_var").toTensor();
if (!extractOptionalBNParams(bn, r)) {
return false;
}
r.conv_w = conv.attr("weight").toTensor();
r.conv_b = at::zeros_like(r.bn_rm);
auto bias_opt = conv.attr("bias").toOptional<at::Tensor>();
if (bias_opt) {
r.conv_b = *bias_opt;
}
return true;
}
void FoldConvBatchNorm2dHelper::analyze(Module& module) {
// Dot in the ".Conv2d" and ".BatchNorm2d" is an attempt to
// prevent matching module's whose name might end with Conv2d
// But are user defined modules.
const PatternInfo pattern = PatternInfo::parse_from_str(R"IR(
graph(%self, %x):
%conv_submodule = match::module[name=".Conv2d"](%self)
%conv_out = prim::CallMethod[name="forward"](%conv_submodule, %x)
%bn_submodule = match::module[name=".BatchNorm2d"](%self)
%bn_out = prim::CallMethod[name="forward"](%bn_submodule, %conv_out)
return (%bn_out))IR");
const Graph& pattern_graph = *pattern.pattern_graph;
const auto& vmap = pattern.vmap;
Value* pattern_conv_out = vmap.at("conv_out");
Value* pattern_bn_out = vmap.at("bn_out");
Value* pattern_conv_submodule = vmap.at("conv_submodule");
Value* pattern_bn_submodule = vmap.at("bn_submodule");
Node* pattern_conv = pattern_conv_out->node();
Node* pattern_bn = pattern_bn_out->node();
// We will put submodules into this worklist and keep processing items from it
// one by one. We start by just putting the top module there.
std::stack<Module> worklist({module});
while (!worklist.empty()) {
Module current = worklist.top();
worklist.pop();
// Queue submodules for processing
for (const Module& submodule : current.children()) {
worklist.push(submodule);
}
// Process all method of the current module
for (auto& method : current.get_methods()) {
GRAPH_DUMP(
current.type()->name()->name() + "::" + method.name() +
"() before Conv2d-BatchNorm2d folding",
method.graph());
const auto& matches = findPatternMatches(pattern_graph, *method.graph());
GRAPH_DEBUG("number of Conv2d-BatchNorm2d matches: ", matches.size());
Graph* g = method.graph().get();
if (!conv_bn_names_.count(g)) {
// This is to make sure we don't visit one graph multiple times
conv_bn_names_[g] = {};
for (const Match& match : matches) {
GRAPH_DEBUG("Checking next match...");
Node* matched_conv = match.nodes_map.at(pattern_conv);
Node* matched_bn = match.nodes_map.at(pattern_bn);
Node* matched_conv_submodule =
match.values_map.at(pattern_conv_submodule)->node();
Node* matched_bn_submodule =
match.values_map.at(pattern_bn_submodule)->node();
TORCH_INTERNAL_ASSERT(
matched_conv_submodule->kind() == prim::GetAttr);
TORCH_INTERNAL_ASSERT(matched_bn_submodule->kind() == prim::GetAttr);
const auto& conv_module_name =
matched_conv_submodule->s(Symbol::attr("name"));
const auto& bn_module_name =
matched_bn_submodule->s(Symbol::attr("name"));
Module conv_submodule = current.attr(conv_module_name).toModule();
Module bn_submodule = current.attr(bn_module_name).toModule();
ConvBNParameters params;
if (!tryExtractingConvBNParameters(
conv_submodule, bn_submodule, params)) {
GRAPH_DEBUG(
"Conv and BN modules didn't have all required parameters or attributes...");
continue;
}
conv_bn_names_[g].push_back(
std::make_tuple(conv_module_name, bn_module_name));
// We are using a separate vector for saving Values we want to rewrite
// to make sure that the order in which we perform these
// transformations is deterministic. Iterating through keys of
// rewrite_map would result in non-determinism that might not manifest
// as a bug now, but can bite us later.
values_to_rewrite_.push_back(matched_bn->output());
rewrite_map_[matched_bn->output()] = matched_conv->output();
GRAPH_UPDATE(
"Rewriting %",
matched_bn->output()->debugName(),
" with %",
matched_conv->output()->debugName());
nodes_to_delete_.insert(matched_bn);
nodes_to_delete_.insert(matched_bn_submodule);
GRAPH_UPDATE("Deleting ", *matched_bn);
GRAPH_UPDATE("Deleting ", *matched_bn_submodule);
auto slot = conv_submodule.type()->getAttributeSlot("bias");
TORCH_CHECK(
conv_submodule.type()->is_parameter(slot),
"Expected conv module to have a bias parameter");
} // matches
}
for (const auto& conv_bn : conv_bn_names_.at(g)) {
Module conv_submodule = current.attr(std::get<0>(conv_bn)).toModule();
Module bn_submodule = current.attr(std::get<1>(conv_bn)).toModule();
ConvBNParameters params;
TORCH_INTERNAL_ASSERT(tryExtractingConvBNParameters(
conv_submodule, bn_submodule, params));
auto new_w_b = computeUpdatedConvWeightAndBias(params);
conv_module_and_params_[conv_submodule._ivalue()] = new_w_b;
} // conv_bn module
} // methods
} // while
}
void FoldConvBatchNorm2dHelper::transform() {
for (const auto& item : conv_module_and_params_) {
Module conv(item.first);
auto w_b = item.second;
conv.setattr("weight", std::get<0>(w_b));
conv.setattr("bias", std::get<1>(w_b));
}
// Perform planned rewritings
for (auto v : values_to_rewrite_) {
v->replaceAllUsesWith(rewrite_map_.at(v));
}
// Perform planned deletions
for (auto n : nodes_to_delete_) {
n->removeAllInputs();
}
for (auto n : nodes_to_delete_) {
n->destroy();
}
}
void replaceConv2dBiasWithGetAttr(Module& module) {
auto graph = module.get_method("forward").graph();
// Only looks fors _convolution pattern.
// Thus assumes that tracing will have always gotten rid of aten::conv2d.
// If it did not, BN folding will fail.
const PatternInfo& pattern_convolution = PatternInfo::parse_from_str(R"(
graph(%a, %w, %b, %stride:int[], %padding:int[], %dilation:int[],
%transposed:bool, %output_padding:int[], %groups:int, %benchmark:bool,
%deterministic:bool, %cudnn_enabled:bool):
%conv_out = aten::_convolution(%a, %w, %b, %stride, %padding, %dilation,
%transposed, %output_padding, %groups, %benchmark, %deterministic, %cudnn_enabled)
return (%conv_out) )");
const Graph& pattern_convolution_graph = *pattern_convolution.pattern_graph;
const auto& convolution_vmap = pattern_convolution.vmap;
const auto& matches = findPatternMatches(pattern_convolution_graph, *graph);
for (const auto& match : matches) {
// We come here only if the bias was not present in the module.
// In that case, the corresponding graph will not have getAttr("bias")
// Insert that in the graph.
// And change _convolution to take the new value.
auto conv_node =
match.values_map.at(convolution_vmap.at("conv_out"))->node();
WithInsertPoint ins(conv_node);
Value* bias_attr_val = graph->insertGetAttr(graph->inputs()[0], "bias")
->setType(TensorType::get());
constexpr size_t conv_bias_index = 2;
conv_node->replaceInput(conv_bias_index, bias_attr_val);
}
}
void addBiasForConv2dIfNone(Module& module) {
auto t = module.type()->expect<ClassType>();
auto real_typename = t->name()->qualifiedName();
const std::string pattern_name("Conv2d");
if (real_typename.size() >= pattern_name.size() &&
(0 ==
real_typename.compare(
real_typename.size() - pattern_name.size(),
pattern_name.size(),
pattern_name))) {
if (!t->hasAttribute("bias")) {
auto optional_tensor_type = OptionalType::create(TensorType::get());
t->addAttribute("bias", optional_tensor_type, true);
auto optional_tensor = c10::optional<at::Tensor>();
module.setattr("bias", optional_tensor);
replaceConv2dBiasWithGetAttr(module);
}
}
for (Module m : module.children()) {
addBiasForConv2dIfNone(m);
}
}
void swapDeQuant(Block* block) {
auto graph = block->owningGraph();
for (Node* n : block->nodes()) {
if (n->kind() == prim::If) {
for (Block* subblock : n->blocks()) {
swapDeQuant(subblock);
}
if (n->outputs().size() == 0) {
continue;
}
if (n->outputs().size() > 1) {
// Factoring out dequantize for if blocks with multiple outputs
// is not supported right now
continue;
}
}
auto inputs = getGeneralOpTensorInputs(n);
if (inputs.size() > 0) {
bool is_dequantized = true;
for (auto* input : inputs) {
// note that we don't need to recursively check for prim::If
// here because if all inputs of a prim::If is dequantized
// the dequantize will be factored out before we get to this
// point
is_dequantized &= input->node()->kind() == Symbol::aten("dequantize");
}
if (!is_dequantized) {
continue;
}
// Delete dequantize node, we have one dequantize
// for each use of the value
for (auto* dequantized_val : inputs) {
auto* dequantize_node = dequantized_val->node();
TORCH_INTERNAL_ASSERT(
dequantized_val->uses().size() == 1,
"Expect to have one dequantize node for each use");
// Replace useses of dequantized_val with the input of
// dequantize node
dequantized_val->replaceAllUsesWith(dequantize_node->inputs()[0]);
dequantize_node->removeAllInputs();
dequantize_node->destroy();
}
for (auto* output : n->outputs()) {
std::vector<Use> uses = output->uses();
// Insert new dequantize node for each use of the output
insertDeQuantCall(graph, output, output, uses);
}
}
}
}
} // namespace
TORCH_API Module InsertObservers(
Module& input_module,
const std::string& method_name,
const QConfigDict& qconfig_dict,
bool inplace,
bool is_dynamic) {
ModuleQConfigMap map_before_clone;
fillQConfigMap(input_module, qconfig_dict, map_before_clone);
ModuleCloneHelper mh;
Module module =
inplace ? input_module : mh.clone(input_module, map_before_clone);
ModuleQConfigMap module_qconfig_map;
// Since the types are changed after clone, we need to fill
// the qconfig map again
fillQConfigMap(module, qconfig_dict, module_qconfig_map);
InsertObserversHelper helper(module_qconfig_map);
helper.setDynamicFlag(is_dynamic);
helper.preprocess(module, method_name);
helper.insertObservers(module, method_name, true);
return module;
}
Module InsertQuantDeQuant(
Module& input_module,
const std::string& method_name,
bool inplace) {
Module module = inplace ? input_module : input_module.clone();
InsertQuantDeQuantHelper h;
h.run(module, method_name);
h.cleanup(module);
return module;
}
void FoldQuantNodesIntoInputsOutputs(std::shared_ptr<Graph>& graph) {
throw std::runtime_error("Pass not implemented yet!");
}
void SwapFunctionalLinear(Module& module) {
for (auto& method : module.get_methods()) {
std::shared_ptr<Graph> g = method.graph();
SwapFunctionalLinear(g);
}
for (Module m : module.children()) {
SwapFunctionalLinear(m);
}
}
void SwapFunctionalLinear(std::shared_ptr<Graph>& graph) {
std::string functional_linear = R"(
graph(%linear, %input, %weight, %bias):
%r = prim::CallFunction(%linear, %input, %weight, %bias)
return (%r) )";
std::string aten_linear = R"(
graph(%linear, %input, %weight, %bias):
%r = aten::linear(%input, %weight, %bias)
return (%r) )";
auto filter = [](const Match& match,
const std::unordered_map<std::string, Value*>& vmap) {
const auto& match_vmap = match.values_map;
auto linear = getValue("linear", match_vmap, vmap);
auto func_name = getFuncName(linear);
return func_name == "linear";
};
SubgraphRewriter rewriter;
rewriter.RegisterRewritePattern(functional_linear, aten_linear);
// TODO: runOnGraph takes const ref?
rewriter.runOnGraph(graph, filter);
}
void ReplicateQuant(std::shared_ptr<Graph>& graph) {
std::stack<Block*> blocks_to_visit;
std::vector<Node*> quant_nodes_to_rewrite;
blocks_to_visit.push(graph->block());
while (!blocks_to_visit.empty()) {
Block* b = blocks_to_visit.top();
blocks_to_visit.pop();
for (Node* n : b->nodes()) {
// find quantize node that quantizes the output of if
if ((n->kind() == Symbol::aten("quantize_per_tensor") ||
n->kind() == Symbol::aten("quantize_per_channel")) &&
n->input(0)->node()->kind() == prim::If) {
quant_nodes_to_rewrite.push_back(n);
}
for (Block* subblock : n->blocks()) {
blocks_to_visit.push(subblock);
}
}
}
for (Node* n : quant_nodes_to_rewrite) {
Node* if_node = n->input(0)->node();
// move the nodes that produces the quantization parameters before
// prim::If
for (auto i = 1; i < n->inputs().size(); ++i) {
n->input(i)->node()->moveBefore(if_node);
}
// replace all uses of the quantized node with the output of if node
n->output()->replaceAllUsesWith(if_node->output());
// add quantize nodes to the end of all blocks
for (Block* if_block : if_node->blocks()) {
TORCH_CHECK(
if_block->outputs().size() == 1,
"replicate quantize only works for `if` node with one output right now");
// the original return value of the block
Value* ret_val = if_block->outputs()[0];
std::vector<Value*> quantize_inputs = n->inputs().vec();
quantize_inputs[0] = ret_val;
WithInsertPoint ins(if_block->return_node());
Node* quant = graph->create(n->kind(), quantize_inputs);
if_block->replaceOutput(0, quant->output());
quant->output()->copyMetadata(ret_val);
graph->insertNode(quant);
}
}
for (Node* n : quant_nodes_to_rewrite) {
n->removeAllInputs();
}
for (Node* n : quant_nodes_to_rewrite) {
n->destroy();
}
}
void ReplicateDeQuant(std::shared_ptr<Graph>& graph) {
std::stack<Block*> blocks_to_visit;
std::vector<Node*> dequant_nodes_to_rewrite;
blocks_to_visit.push(graph->block());
while (!blocks_to_visit.empty()) {
Block* b = blocks_to_visit.top();
blocks_to_visit.pop();
for (Node* n : b->nodes()) {
if (n->kind() == Symbol::aten("dequantize") &&
n->output()->uses().size() > 1) {
dequant_nodes_to_rewrite.push_back(n);
}
for (Block* subblock : n->blocks()) {
blocks_to_visit.push(subblock);
}
}
}
for (Node* n : dequant_nodes_to_rewrite) {
auto* quantized_val = n->inputs()[0];
auto* dequantized_val = n->output();
// copy uses to vector since value->uses() is a reference
// and changing the graph will also change the uses() list
std::vector<Use> uses = dequantized_val->uses();
insertDeQuantCall(graph.get(), quantized_val, dequantized_val, uses);
}
for (Node* n : dequant_nodes_to_rewrite) {
n->removeAllInputs();
}
for (Node* n : dequant_nodes_to_rewrite) {
n->destroy();
}
}
// This is the pass to handle ops that does not require observation
// for example: flatten, average_pool, upsample
// This is called after inline and before graph execution
void SwapDeQuant(std::shared_ptr<Graph>& graph) {
swapDeQuant(graph->block());
}
void QuantFusion(std::shared_ptr<Graph>& graph) {
for (const auto& info : quant_fusion_pattern_and_replacements()) {
SubgraphRewriter rewriter;
rewriter.RegisterRewritePattern(info.pattern, info.replacement);
rewriter.runOnGraph(graph, info.filter);
}
}
Module FoldConvBatchNorm2d(const Module& module) {
FoldConvBatchNorm2dHelper h;
Module m = module.clone();
addBiasForConv2dIfNone(m);
h.analyze(m);
h.transform();
return m;
}
void FoldQuantizeCallIntoBuffer(
Module& module,
const std::string& method_name) {
const PatternInfo& pattern = PatternInfo::parse_from_str(R"(
graph(%self, %scale, %zero_point, %dtype):
%weight = prim::GetAttr[name="weight"](%self)
%weight_quant = aten::quantize_per_tensor(%weight, %scale, %zero_point, %dtype)
return (%weight_quant) )");
const Graph& pattern_graph = *pattern.pattern_graph;
const auto& vmap = pattern.vmap;
auto method = module.get_method(method_name);
auto graph = method.graph();
const auto& matches = findPatternMatches(pattern_graph, *graph);
// Extra filter on scale/zero_point/dtype to make sure they are Constant
auto filter = [](const Match& match,
const std::unordered_map<std::string, Value*>& vmap) {
const auto& match_vmap = match.values_map;
auto scale_node = match_vmap.at(vmap.at("scale"))->node();
auto zero_point_node = match_vmap.at(vmap.at("zero_point"))->node();
auto dtype_node = match_vmap.at(vmap.at("dtype"))->node();
return scale_node->kind() == prim::Constant &&
zero_point_node->kind() == prim::Constant &&
dtype_node->kind() == prim::Constant;
};
std::unordered_set<Node*> nodes_to_delete;
for (const auto& match : matches) {
if (!filter(match, vmap)) {
continue;
}
auto match_vmap = match.values_map;
auto float_weight = module.attr("weight").toTensor().data();
auto scale = toIValue(match_vmap.at(vmap.at("scale"))).value().toDouble();
auto zero_point =
toIValue(match_vmap.at(vmap.at("zero_point"))).value().toInt();
auto dtype =
toIValue(match_vmap.at(vmap.at("dtype"))).value().toScalarType();
module.register_buffer(
"_quantized_weight",
at::quantize_per_tensor(float_weight, scale, zero_point, dtype));
// Replace the GetAttr[weight]->quantize_per_tensor sequence
// with a simple GetAttr[_quantized_weight] node.
Value* orig_weight = match_vmap.at(vmap.at("weight"));
Value* orig_weight_quant = match_vmap.at(vmap.at("weight_quant"));
orig_weight->node()->s_(attr::name, "_quantized_weight");
orig_weight_quant->replaceAllUsesWith(orig_weight);
nodes_to_delete.insert(orig_weight_quant->node());
}
for (Node* n : nodes_to_delete) {
n->destroy();
}
}
void InsertPrepackUnpack(std::shared_ptr<Graph>& graph) {
insertPrepackUnpackForLinear(graph);
insertPrepackUnpackForConv2d(graph);
}
void InsertPrepackUnpack(Module& module) {
for (auto& method : module.get_methods()) {
auto graph = method.graph();
InsertPrepackUnpack(graph);
}
for (Module m : module.children()) {
InsertPrepackUnpack(m);
}
}
struct FoldPrepackedWeightIntoModuleHelper {
void run(
Module& module,
const std::string& method_name,
const Module& linear_params_module,
const Module& conv_params_module) {
auto method = module.get_method(method_name);
auto graph = method.graph();
GRAPH_DUMP("Before FoldPrepackWeightIntoModule: ", graph);
// (is_conv, is_per_channel, pattern, packed_params_module)
std::vector<PatternsAndModules> pattern_and_modules = {
{false, false, linear_prepack_per_tensor, linear_params_module},
{false, true, linear_prepack_per_channel, linear_params_module},
{true, false, conv2d_prepack, conv_params_module},
{true, true, conv2d_prepack_per_channel, conv_params_module}};
for (const auto& pm : pattern_and_modules) {
const Graph& pattern_graph = *pm.pattern.pattern_graph;
const auto& vmap = pm.pattern.vmap;
const auto& matches = findPatternMatches(pattern_graph, *graph);
TORCH_INTERNAL_ASSERT(
matches.size() <= 1, "We only support at most one match right now");
for (const auto& match : matches) {
const auto& match_vmap = match.values_map;
auto w_dtype_opt = getIValue("w_dtype", match_vmap, vmap);
auto w_scale_opt = getIValue("w_scale", match_vmap, vmap);
auto w_zero_point_opt = getIValue("w_zero_point", match_vmap, vmap);
if (!w_dtype_opt || !w_scale_opt || !w_zero_point_opt) {
GRAPH_DEBUG(
"dtype, scale or zero_point for weight(",
getValue("w_dtype", match_vmap, vmap)->debugName(),
", ",
getValue("w_scale", match_vmap, vmap)->debugName(),
", ",
getValue("w_zero_point", match_vmap, vmap)->debugName(),
") is not constant, skipping the match.");
continue;
}
auto w_dtype = w_dtype_opt.value().toScalarType();
auto w = module.attr("weight").toTensor().data();
at::Tensor w_quant;
if (pm.is_per_channel) {
auto w_axis_opt = getIValue("w_axis", match_vmap, vmap);
if (!w_axis_opt) {
GRAPH_DEBUG(
"axis for weight ",
getValue("w_axis", match_vmap, vmap)->debugName(),
" is non-constant, skipping the match");
continue;
}
auto w_scale = w_scale_opt.value().toTensor().to(at::kFloat);
auto w_zero_point = w_zero_point_opt.value().toTensor().to(at::kInt);
int w_axis = w_axis_opt.value().toInt();
TORCH_CHECK(
w_scale.sizes() == w_zero_point.sizes(),
"scale and zero_point must have the same size");
w_quant = at::quantize_per_channel(
w, w_scale, w_zero_point, w_axis, w_dtype);
} else {
auto w_scale = w_scale_opt.value().toDouble();
auto w_zero_point = w_zero_point_opt.value().toInt();
w_quant = at::quantize_per_tensor(w, w_scale, w_zero_point, w_dtype);
}
c10::optional<at::Tensor> b = c10::nullopt;
if (hastensor(module, "bias")) {
b = module.attr("bias").toTensor().data();
}
Module wrapper_module = pm.packed_params_module.clone();
auto set_weight_bias = wrapper_module.get_method("set_weight_bias");
std::string module_name_prefix;
if (pm.is_conv) {
module_name_prefix = "_conv_packed_params_module_for_";
auto stride_opt =
toTwoElementIntList(getValue("stride", match_vmap, vmap));
auto padding_opt =
toTwoElementIntList(getValue("padding", match_vmap, vmap));
auto dilation_opt =
toTwoElementIntList(getValue("dilation", match_vmap, vmap));
auto groups_opt = getIValue("groups", match_vmap, vmap);
auto set_conv_params = wrapper_module.get_method("set_conv_params");
if (!stride_opt || !padding_opt || !dilation_opt) {
GRAPH_DEBUG(
"Failed to extract two element IntList for stride/padding/dilation, (",
getValue("stride", match_vmap, vmap)->debugName(),
", ",
getValue("padding", match_vmap, vmap)->debugName(),
", ",
getValue("dilation", match_vmap, vmap)->debugName(),
") skipping the match");
continue;
}
set_conv_params(std::vector<IValue>{stride_opt.value(),
padding_opt.value(),
dilation_opt.value(),
groups_opt.value()});
} else {
module_name_prefix = "_linear_packed_params_module_for_";
}
set_weight_bias(std::vector<IValue>{IValue(w_quant), IValue(b)});
auto w_quant_val = getValue("w_quant", match_vmap, vmap);
// unique name for the module based on %w_quant
int uid = 0;
auto module_name = module_name_prefix + c10::to_string(uid++);
while (module.hasattr(module_name)) {
module_name_prefix + c10::to_string(uid++);
}
GRAPH_UPDATE("Adding new module: ", module_name);
module.register_module(module_name, wrapper_module);
// Add GetAttr of the packed module
auto packed_params_val = getValue("packed_params", match_vmap, vmap);
WithInsertPoint ins(packed_params_val->node());
// wrapper_module =
// self.{_conv,_linear}_packed_params_module_for_{unique_id}
Value* packed_params_module =
graph->insertGetAttr(graph->inputs()[0], module_name)
->setType(wrapper_module.type());
GRAPH_UPDATE("Adding GetAttr node for the wrapper module");
// packed_params = wrapper_module._packed_params
Value* packed_params_from_attr =
graph->insertGetAttr(packed_params_module, "_packed_params");
GRAPH_UPDATE(
"Adding GetAttr node for _packed_params: ",
packed_params_from_attr->debugName());
packed_params_val->replaceAllUsesWith(packed_params_from_attr);
// Delete nodes
std::vector<Node*> nodes_to_delete = {w_quant_val->node(),
packed_params_val->node()};
for (auto n : nodes_to_delete) {
n->removeAllInputs();
}
for (auto n : nodes_to_delete) {
GRAPH_UPDATE("Deleting node: ", n);
n->destroy();
}
}
}
}
void run(
Module& module,
const Module& linear_params_module,
const Module& conv_params_module) {
for (auto& method : module.get_methods()) {
run(module, method.name(), linear_params_module, conv_params_module);
}
for (Module m : module.children()) {
run(m, linear_params_module, conv_params_module);
}
}
const PatternInfo linear_prepack_per_tensor = PatternInfo::parse_from_str(R"(
graph(%a_dequant, %w, %b, %w_scale, %w_zero_point, %w_dtype):
%w_quant = aten::quantize_per_tensor(%w, %w_scale, %w_zero_point, %w_dtype)
%packed_params = quantized::linear_prepack(%w_quant, %b)
return (%packed_params) )");
const PatternInfo linear_prepack_per_channel = PatternInfo::parse_from_str(R"(
graph(%a_dequant, %w, %b, %w_scale, %w_zero_point, %w_axis, %w_dtype):
%w_quant = aten::quantize_per_channel(%w, %w_scale, %w_zero_point, %w_axis, %w_dtype)
%packed_params = quantized::linear_prepack(%w_quant, %b)
return (%packed_params) )");
const PatternInfo conv2d_prepack = PatternInfo::parse_from_str(R"(
graph(%a_dequant, %w, %b, %w_scale, %w_zero_point, %w_dtype, %stride, %padding, %dilation, %groups):
%w_quant = aten::quantize_per_tensor(%w, %w_scale, %w_zero_point, %w_dtype)
%packed_params = quantized::conv2d_prepack(%w_quant, %b, %stride, %padding, %dilation, %groups)
return (%packed_params) )");
const PatternInfo conv2d_prepack_per_channel = PatternInfo::parse_from_str(R"(
graph(%a_dequant, %w, %b, %w_scale, %w_zero_point, %w_axis, %w_dtype, %stride, %padding, %dilation, %groups):
%w_quant = aten::quantize_per_channel(%w, %w_scale, %w_zero_point, %w_axis, %w_dtype)
%packed_params = quantized::conv2d_prepack(%w_quant, %b, %stride, %padding, %dilation, %groups)
return (%packed_params) )");
};
void FoldPrepackedWeightIntoModule(
Module& module,
const Module& linear_params_module,
const Module& conv_params_module) {
FoldPrepackedWeightIntoModuleHelper h;
h.run(module, linear_params_module, conv_params_module);
}
void DedupModuleUses(Module& module) {
ModuleUseDeduper d(module);
d.dedup();
}
void FoldQuantizedPrepackingOps(Module& module) {
auto filter_fn = [](const Node* n) -> bool {
return (
(n->kind() == Symbol::fromQualString("quantized::linear_prepack")) ||
n->kind() == Symbol::fromQualString("quantized::conv2d_prepack"));
};
PrePackingOpsFolder(module, filter_fn, "quantized");
}
script::Module Finalize(script::Module& module) {
SwapFunctionalLinear(module);
auto graph = module.get_method("forward").graph();
Inline(*graph);
ConstantPropagation(graph);
ReplicateQuant(graph);
ReplicateDeQuant(graph);
SwapDeQuant(graph);
InsertPrepackUnpack(graph);
ConstantPropagation(graph);
QuantFusion(graph);
auto frozen = freeze_module(module);
FoldQuantizedPrepackingOps(frozen);
return frozen;
}
} // namespace jit
} // namespace torch
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
2ed775db1a2600f67ed3dc15848a73d8bc3323ae | dba127f8a88db95386cbe21b221760d782cbdf67 | /IOCP_1/JIocp.cpp | 35feecbf50b491080d189073c3285a0eda5b166c | [] | no_license | 15831944/DirectX_Study | c1bd6fe1b8eb891bf49a5a3954234adf59abdb46 | e4832a079936dc1aa893b098375a1d228c7cc02b | refs/heads/master | 2021-10-20T09:19:15.305146 | 2019-02-27T06:30:56 | 2019-02-27T06:30:56 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 3,187 | cpp | #include "JIocp.h"
#define SAFE_HANDLE_KILL(h) {if (h != INVALID_HANDLE_VALUE) { CloseHandle(h); }}
DWORD WINAPI JIocp::WorkThread(LPVOID pParam)
{
JIocp* iocp = (JIocp*)pParam;
DWORD Trans;
ULONG_PTR Key;
OVERLAPPED* Ov;
BOOL Ret;
while (TRUE)
{
if (WaitForSingleObject(iocp->m_ThreadKillEvent,1) == WAIT_OBJECT_0)
{
break;
}
Ret = GetQueuedCompletionStatus(iocp->m_IOCP, &Trans, &Key, &Ov, 5000);
if (Ret == TRUE)
{
if (Trans != 0)
{
if (Key != 0 && Ov != 0)
{
if (Key == 1111)
{
iocp->DispatchRead(Trans);
}
if (Key == 2222)
{
iocp->DispatchWrite(Trans);
}
}
}
else
{
SetEvent(iocp->m_ThreadKillEvent);
}
}
else
{
if (GetLastError() == WAIT_TIMEOUT)
{
continue;
}
else
{
if (Ov != NULL)
{
if (GetLastError() == ERROR_HANDLE_EOF)
{
SetEvent(iocp->m_ThreadKillEvent);
}
else
{
cout << "ERROR!" << endl;
}
}
}
}
}
return 0;
}
bool JIocp::DispatchRead(DWORD Trans)
{
cout << Trans << "Bytes Read" << endl;
DWORD WriteByte = 0;
WriteFile(m_hWriteFile, m_szBuffer, Trans, &WriteByte, &m_WriteOv);
LARGE_INTEGER LI;
LI.QuadPart = Trans;
m_ReadOv.Offset += LI.LowPart;
m_ReadOv.OffsetHigh += LI.HighPart;
if (WaitForRead() == false)
{
SetEvent(m_ThreadKillEvent);
return false;
}
return true;
}
bool JIocp::DispatchWrite(DWORD Trans)
{
cout << Trans << "Bytes Write" << endl;
LARGE_INTEGER LI;
LI.QuadPart = Trans;
m_WriteOv.Offset += LI.LowPart;
m_WriteOv.OffsetHigh += LI.HighPart;
return true;
}
bool JIocp::WaitForRead()
{
DWORD ReadBytes = 0;
DWORD Ret = ReadFile(m_hReadFile, m_szBuffer, MAX_BUFFER_SIZE, &ReadBytes, &m_ReadOv);
if (Ret == FALSE)
{
if (GetLastError() == ERROR_IO_PENDING)
{
return true;
}
// ÆÄÀÏÀÇ ³¡
if (GetLastError() == ERROR_HANDLE_EOF)
{
return false;
}
return false;
}
else
{
if (ReadBytes == 0 || GetLastError() == ERROR_HANDLE_EOF)
{
return false;
}
}
return true;
}
bool JIocp::Init()
{
m_hReadFile = CreateFile(L"Sample.mp4",GENERIC_READ, 0, 0,OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, 0);
m_hWriteFile = CreateFile(L"SampleCopy.mp4", GENERIC_WRITE, 0, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, 0);
DWORD id = 0;
for (int iThread = 0; iThread < MAX_THREAD_COUNT; iThread++)
{
m_Thread[iThread] = CreateThread(0, 0, WorkThread,this, 0, &id);
}
m_ThreadKillEvent = CreateEvent(0, TRUE, FALSE, 0);
m_IOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE,0,0,0);
CreateIoCompletionPort(m_hReadFile, m_IOCP, 1111, 0);
CreateIoCompletionPort(m_hWriteFile, m_IOCP,2222, 0);
return true;
}
bool JIocp::Frame()
{
WaitForRead();
WaitForMultipleObjects(MAX_THREAD_COUNT, m_Thread, TRUE, INFINITE);
return true;
}
bool JIocp::Release()
{
SAFE_HANDLE_KILL(m_hReadFile);
SAFE_HANDLE_KILL(m_hWriteFile);
SAFE_HANDLE_KILL(m_ThreadKillEvent);
SAFE_HANDLE_KILL(m_IOCP);
_getch();
return true;
}
JIocp::JIocp()
{
ZeroMemory(&m_ReadOv,sizeof(OVERLAPPED));
ZeroMemory(&m_WriteOv, sizeof(OVERLAPPED));
m_hReadFile = 0;
m_hWriteFile = 0;
}
JIocp::~JIocp()
{
} | [
"kgcaschool@outlook.kr"
] | kgcaschool@outlook.kr |
a98fec7dc828c3093ec62b458791d5854ad476e4 | a1618f92a071589f60f39918f96df6c3abe7b4b2 | /tests/unit_tests/test_peerlist.cpp | 1f2144c03b81891b106e12b36531fbcbc6025708 | [
"BSD-3-Clause"
] | permissive | techqc/SiZ | f41b920aacfbef5c3a85ff15939e71b1fdba4a59 | bdf290705b2d553b4253df4ca97e4367c78f5a27 | refs/heads/master | 2021-09-10T09:30:39.193726 | 2018-03-23T19:35:18 | 2018-03-23T19:35:18 | 125,059,630 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,996 | cpp | // Copyright (c) 2018, SiZ, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 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.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
#include "gtest/gtest.h"
#include "common/util.h"
#include "p2p/net_peerlist.h"
#include "net/net_utils_base.h"
TEST(peer_list, peer_list_general)
{
nodetool::peerlist_manager plm;
plm.init(false);
#define ADD_GRAY_NODE(ip_, port_, id_, last_seen_) { nodetool::peerlist_entry ple; ple.last_seen=last_seen_;ple.adr.ip = ip_; ple.adr.port = port_; ple.id = id_;plm.append_with_peer_gray(ple);}
#define ADD_WHITE_NODE(ip_, port_, id_, last_seen_) { nodetool::peerlist_entry ple;ple.last_seen=last_seen_; ple.adr.ip = ip_; ple.adr.port = port_; ple.id = id_;plm.append_with_peer_white(ple);}
#define PRINT_HEAD(step) {std::list<nodetool::peerlist_entry> bs_head; bool r = plm.get_peerlist_head(bs_head, 100);std::cout << "step " << step << ": " << bs_head.size() << std::endl;}
ADD_GRAY_NODE(MAKE_IP(123,43,12,1), 8080, 121241, 34345);
ADD_GRAY_NODE(MAKE_IP(123,43,12,2), 8080, 121241, 34345);
ADD_GRAY_NODE(MAKE_IP(123,43,12,3), 8080, 121241, 34345);
ADD_GRAY_NODE(MAKE_IP(123,43,12,4), 8080, 121241, 34345);
ADD_GRAY_NODE(MAKE_IP(123,43,12,5), 8080, 121241, 34345);
ADD_WHITE_NODE(MAKE_IP(123,43,12,1), 8080, 121241, 34345);
ADD_WHITE_NODE(MAKE_IP(123,43,12,2), 8080, 121241, 34345);
ADD_WHITE_NODE(MAKE_IP(123,43,12,3), 8080, 121241, 34345);
ADD_WHITE_NODE(MAKE_IP(123,43,12,4), 8080, 121241, 34345);
size_t gray_list_size = plm.get_gray_peers_count();
ASSERT_EQ(gray_list_size, 1);
std::list<nodetool::peerlist_entry> bs_head;
bool r = plm.get_peerlist_head(bs_head, 100);
std::cout << bs_head.size() << std::endl;
ASSERT_TRUE(r);
ASSERT_EQ(bs_head.size(), 4);
ADD_GRAY_NODE(MAKE_IP(123,43,12,5), 8080, 121241, 34345);
ASSERT_EQ(plm.get_gray_peers_count(), 1);
ASSERT_EQ(plm.get_white_peers_count(), 4);
}
TEST(peer_list, merge_peer_lists)
{
//([^ \t]*)\t([^ \t]*):([^ \t]*) \tlast_seen: d(\d+)\.h(\d+)\.m(\d+)\.s(\d+)\n
//ADD_NODE_TO_PL("\2", \3, 0x\1, (1353346618 -(\4*60*60*24+\5*60*60+\6*60+\7 )));\n
nodetool::peerlist_manager plm;
plm.init(false);
std::list<nodetool::peerlist_entry> outer_bs;
#define ADD_NODE_TO_PL(ip_, port_, id_, timestamp_) { nodetool::peerlist_entry ple; epee::string_tools::get_ip_int32_from_string(ple.adr.ip, ip_); ple.last_seen = timestamp_; ple.adr.port = port_; ple.id = id_;outer_bs.push_back(ple);}
}
| [
"37153171+techqc@users.noreply.github.com"
] | 37153171+techqc@users.noreply.github.com |
98d0e0086c76bbed179abc7dcdbb6656d0541caf | 89bf6936934cd22263842a68a81ffdfd2afc46fa | /utils.cpp | ecc8d876fd224c6c3354b51e972f6ccc35467b27 | [] | no_license | serhatgun/licence-plate-recognition | 5124a6f2f853d541ad6c2a765f540b7b2ace6d25 | 6b25ead02236489fd3360eaaa8e5bcf29dc9ffa6 | refs/heads/master | 2023-07-20T18:04:15.629260 | 2023-07-17T12:10:38 | 2023-07-17T12:10:38 | 265,976,151 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,878 | cpp | #include "utils.h"
void Utils::adaptiveCalc(const Mat& im, int row, int col, const Mat& mask, int& A1, int& A2, int& zmin, int& zmax, int& zmed, int& zxy) {
int u = mask.rows;
int v = mask.cols;
for (int s = -(u - u / 2); s <= u - u / 2; ++s) {
for (int t = -(v - v / 2); t <= v - v / 2; ++t) {
mask.at<double>(s + u / 2, t + v / 2) = static_cast<double>(im.at<uchar>(row + s, col + t));
}
}
zmin = static_cast<int>(min(mask)[0]);
zmax = static_cast<int>(max(mask)[0]);
zmed = static_cast<int>(median(mask)[0]);
zxy = static_cast<int>(im.at<uchar>(row, col));
A1 = zmed - zmin;
A2 = zmed - zmax;
}
void Utils::histogramEqualization(const Mat& im, Mat& finalResult, vector<double>& histogram) {
int rows = im.rows;
int cols = im.cols;
int pixelNumber = rows * cols;
finalResult = Mat(rows, cols, CV_8UC1);
histogram = vector<double>(256, 0.0);
frequency = vector<int>(256, 0);
parallel_for_(Range(0, rows), [&](const Range& range) {
for (int im_rows = range.start; im_rows < range.end; ++im_rows) {
for (int im_cols = 0; im_cols < cols; ++im_cols) {
int gray_level = im.at<uchar>(im_rows, im_cols);
frequency[gray_level]++;
}
}
});
pdf = vector<double>(256);
cdf = vector<double>(256);
cumulative = vector<double>(256);
out = vector<int>(256);
reduce(frequency, pdf, 0, REDUCE_SUM);
int sum = 0;
int L = 255;
for (int i = 0; i < pdf.size(); ++i) {
sum += static_cast<int>(pdf[i]);
cumulative[i] = static_cast<double>(sum);
cdf[i] = cumulative[i] / pixelNumber;
out[i] = static_cast<int>(round(cdf[i] * L));
}
parallel_for_(Range(0, rows), [&](const Range& range) {
for (int im_rows = range.start; im_rows < range.end; ++im_rows) {
for (int im_cols = 0; im_cols < cols; ++im_cols) {
finalResult.at<uchar>(im_rows, im_cols) = static_cast<uchar>(out[im.at<uchar>(im_rows, im_cols)]);
}
}
});
parallel_for_(Range(0, rows), [&](const Range& range) {
for (int im_rows = range.start; im_rows < range.end; ++im_rows) {
for (int im_cols = 0; im_cols < cols; ++im_cols) {
int gray_level = finalResult.at<uchar>(im_rows, im_cols);
atomicAdd(&frequency[gray_level], 1);
}
}
});
reduce(frequency, histogram, 0, REDUCE_SUM);
histogram /= pixelNumber;
}
Mat Utils::imgThresholding(const Mat& im, double T) {
int x = im.rows;
int y = im.cols;
vector<uchar> G1;
vector<uchar> G2;
double meanGL = mean(im)[0];
double th;
if (T < 0)
th = meanGL;
else
th = T;
double newTh = 0;
int it = 0;
while (abs(th - newTh) > 0.1) {
th = newTh;
G1.clear();
G2.clear();
parallel_for_(Range(0, x), [&](const Range& range) {
for (int row = range.start; row < range.end; ++row) {
for (int col = 0; col < y; ++col) {
if (static_cast<double>(im.at<uchar>(row, col)) > th)
G1.push_back(im.at<uchar>(row, col));
else
G2.push_back(im.at<uchar>(row, col));
}
}
});
double u1 = mean(G1)[0];
double u2 = mean(G2)[0];
newTh = (u1 + u2) / 2;
it++;
}
Mat new_im(x, y, CV_8UC1);
parallel_for_(Range(0, x), [&](const Range& range) {
for (int row = range.start; row < range.end; ++row) {
for (int col = 0; col < y; ++col) {
if (im.at<uchar>(row, col) <= static_cast<uchar>(round(newTh)))
new_im.at<uchar>(row, col) = 0;
else
new_im.at<uchar>(row, col) = 255;
}
}
});
cout << "Number of iterations: " << it << endl;
return new_im;
}
void Utils::preProcessing(const Mat& im, Mat& resized_im, Mat& gray_im, Mat& eq_im, Mat& filtered_im, Mat& bin_im, bool show) {
// Resize image
resize(im, resized_im, Size(1024, 768), 0, 0, INTER_CUBIC);
// Convert to grayscale
cvtColor(resized_im, gray_im, COLOR_BGR2GRAY);
// Apply histogram equalization
my_histogram_equalization(gray_im, eq_im);
// Apply median filter
Mat filtered_im_temp;
medianBlur(eq_im, filtered_im_temp, 3);
// Apply local Laplacian filter
filtered_im = locallapfilt(filtered_im_temp, 0.2, 0.5);
// Binarize the image
double level = threshold(filtered_im, bin_im, 0, 255, THRESH_BINARY | THRESH_OTSU);
if (show) {
// Display the images
vector<Mat> images = {resized_im, gray_im, eq_im, bin_im};
vector<string> titles = {"Resized Image", "Gray Level", "Histogram Equalized", "Binary Image"};
int numImages = images.size();
for (int i = 0; i < numImages; ++i) {
namedWindow(titles[i], WINDOW_NORMAL);
imshow(titles[i], images[i]);
}
waitKey(0);
}
}
void Utils::extractPlateRegion(const Mat& eq_im, const Mat& bin_im, Mat& extracted_im, bool show) {
Mat edges, filled;
Canny(bin_im, edges, 100, 200);
morphologyEx(edges, filled, MORPH_CLOSE, Mat(), Point(-1, -1), 3);
vector<vector<Point>> contours;
findContours(filled, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
vector<Rect> boundRect(contours.size());
for (size_t i = 0; i < contours.size(); i++) {
if (contourArea(contours[i]) < 5000 && contourArea(contours[i]) > 250) {
boundRect[i] = boundingRect(contours[i]);
rectangle(extracted_im, boundRect[i].tl(), boundRect[i].br(), Scalar(0, 255, 0), 2);
}
}
if (show) {
namedWindow("Bounding Boxes", WINDOW_NORMAL);
imshow("Bounding Boxes", extracted_im);
waitKey(0);
}
}
void Utils::extractCharacters(const Mat& extracted_plate, const Size& charSize, Mat& characters, bool show) {
Mat gray_plate;
cvtColor(extracted_plate, gray_plate, COLOR_BGR2GRAY);
threshold(gray_plate, gray_plate, 0, 255, THRESH_BINARY | THRESH_OTSU);
Mat element = getStructuringElement(MORPH_RECT, Size(3, 3));
dilate(gray_plate, gray_plate, element);
vector<vector<Point>> contours;
findContours(gray_plate, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
characters = Mat::zeros(charSize, CV_8UC1);
for (size_t i = 0; i < contours.size(); i++) {
Rect boundRect = boundingRect(contours[i]);
Mat charImage = gray_plate(boundRect);
resize(charImage, charImage, charSize);
characters.col(i) = charImage.reshape(1, 1);
if (show) {
imshow("Extracted Characters", charImage);
waitKey(0);
}
}
}
| [
"noreply@github.com"
] | serhatgun.noreply@github.com |
9be90c84d11ce82425724bd00dd201605d419358 | c603aa4b0f31526e2ccf8652a4d9e7ad8327ec6b | /object-detect/src/main.cpp | 8f1a8fd032fc1859738dfb34859218cc4ecd4928 | [] | no_license | Robotics-DAI-FMFI-UK/cu-lIllI | 75cc654b1fb328eff1a04ed1ee32699e7bc91d40 | 40df0269c72ec3912f75807d9727aae6b3c5e67f | refs/heads/master | 2023-06-07T21:12:53.499916 | 2023-06-01T21:33:10 | 2023-06-01T21:33:10 | 159,908,225 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,928 | cpp | #include <stdio.h>
#include <string.h>
#include <sl/Camera.hpp>
#include <opencv2/opencv.hpp>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "objdet.h"
//#include "arm.cpp"
using namespace std;
using namespace sl;
cv::Mat slMat2cvMat(Mat& input);
string type2str(int type);
float compare(uchar L, uchar a, uchar b, float d, uchar L2, uchar a2, uchar b2, float d2);
int findCompMap(int* compMap, int comp);
int mapSize = 200000;
float wLight = 10;
float wColor = 250;
float wDepth = 400;
float thresh = 50;
float redThresh = 145;
float unit = 10;
// camera calibration constants
float fx = 347.542;
float fy = 347.542;
float cx = 325.756;
float cy = 184.519;
void printInfo() {
printf("Unit:\t%.2f [,/.]\nLight:\t%.2f [A/Z]\nColor:\t%.2f [S/X]\nDepth:\t%.2f [D/C]\nThresh:\t%.2f [F/V]\nRed:\t%.2f [G/B]\n\n", unit, wLight, wColor, wDepth, thresh, redThresh);
}
int main(int argc, char **argv) {
// calculate angle limits
// for (int i = 0; i < 6; i++) {
// angleMin[i] = step2rad * (stepMin[i] - stepZero[i]);
// angleMax[i] = step2rad * (stepMax[i] - stepZero[i]);
// printf("%d %f %f\n", i, angleMin[i], angleMax[i]);
// }
int serial = open("/dev/ttyUSB0", O_WRONLY);
if (serial < 0) printf("Not connected to arduino\n");
float angles[] = {0, 0, 0, 0, 0, 0};
int steps[6];
memcpy(steps, stepZero, 6 * sizeof(int));
char cmd[20];
Camera zed;
InitParameters init;
init.sdk_verbose = false;
init.camera_resolution = RESOLUTION_VGA;
init.camera_fps = 30;
init.depth_mode = DEPTH_MODE_ULTRA;//MEDIUM;
init.coordinate_units = UNIT_MILLIMETER;
RuntimeParameters runtime;
runtime.sensing_mode = SENSING_MODE_FILL;
ERROR_CODE err = zed.open(init);
if (err != SUCCESS) exit(-1);
sl::Mat zed_img(zed.getResolution(), MAT_TYPE_8U_C4);
sl::Mat zed_dep(zed.getResolution(), MAT_TYPE_32F_C1);
cv::Mat img = slMat2cvMat(zed_img);
cv::Mat dep = slMat2cvMat(zed_dep);
cv::Mat comp, lab, seg, isRed;
// values pixel for comparison
uchar L, a, b, L2, a2, b2;
float d, d2, pr, pc;
int compMap[mapSize];
int lMap[mapSize];
int aMap[mapSize];
int bMap[mapSize];
int sMap[mapSize];
float x = 0, y = 0, z = 0;
printInfo();
char key = ' ';
while (key != 'q') {
if (zed.grab(runtime) == SUCCESS) {
// retrieve image and depth maps
zed.retrieveImage(zed_img, VIEW_LEFT);
zed.retrieveMeasure(zed_dep, MEASURE_DEPTH);
cv::threshold(dep, dep, 5000, 0, cv::THRESH_TRUNC);
double min, max;
cv::minMaxLoc(dep, &min, &max);
cv::imshow("dep", dep / max);
cv::imshow("img", img);
// convert to L*a*b for better color comparison
cv::cvtColor(img, lab, CV_BGR2Lab);
//cv::imshow("lab", lab);
// === SEGMENTATION ===
// init component matrix
int rows = lab.rows;
int cols = lab.cols;
comp = cv::Mat::zeros(rows, cols, CV_32SC1);
int newComp = 1;
// clear arrays
fill_n(compMap, mapSize, 0);
fill_n(lMap, mapSize, 0);
fill_n(aMap, mapSize, 0);
fill_n(bMap, mapSize, 0);
fill_n(sMap, mapSize, 0);
// our matrices are continuous - 1 long row - only 1 pointer needed
// row pointers
uchar* lPtr = lab.ptr<uchar>(0);
int* cPtr = comp.ptr<int>(0);
float* dPtr = dep.ptr<float>(0);
// channel counts
int lChan = lab.channels(), dChan = dep.channels(), cChan = comp.channels();
// iterate
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
pr = 0;
pc = 0;
// get data for this pixel
L = lPtr[(r * cols + c) * lChan];
a = lPtr[(r * cols + c) * lChan + 1];
b = lPtr[(r * cols + c) * lChan + 2];
d = dPtr[(r * cols + c) * dChan];
if (r > 0) { // compare with neighbor in previous row
L2 = lPtr[((r-1) * cols + c) * lChan];
a2 = lPtr[((r-1) * cols + c) * lChan + 1];
b2 = lPtr[((r-1) * cols + c) * lChan + 2];
d2 = dPtr[((r-1) * cols + c) * dChan];
pr = compare(L, a, b, d, L2, a2, b2, d2);
}
if (c > 0) { // compare with neighbor in previous column
L2 = lPtr[(r * cols + c-1) * lChan];
a2 = lPtr[(r * cols + c-1) * lChan + 1];
b2 = lPtr[(r * cols + c-1) * lChan + 2];
d2 = dPtr[(r * cols + c-1) * dChan];
pc = compare(L, a, b, d, L2, a2, b2, d2);
}
//cPtr[(r * cols + c) * cChan] = (uchar) (pr < pc? pr : pc);
int compToSet = 0;
if (r > 0) {
if (c > 0) {
// inside image
if (pr < thresh) {
if (pc < thresh) {
// both similar
int compR = cPtr[((r-1) * cols + c) * cChan];
int compC = cPtr[(r * cols + c - 1) * cChan];
if (compR == compC) {
// both previous row and colum are in the same component
compToSet = compR;
} else {
// different components, need to mark as same
// check if they are merged already
int mR = findCompMap(compMap, compR);
int mC = findCompMap(compMap, compC);
if (mR < mC) {
compToSet = mR;
compMap[compC] = mR;
} else {
compToSet = mC;
compMap[compR] = mC;
}
}
} else {
// only previous row similar
compToSet = cPtr[((r-1) * cols + c) * cChan];
}
} else {
if (pc < thresh) {
// only previous column similar
compToSet = cPtr[(r * cols + c - 1) * cChan];
} else {
// neither similar
compToSet = newComp++;
}
}
} else {
// first column - check only previous row
if (pr < thresh) compToSet = cPtr[((r-1) * cols) * cChan]; // similar - same component
else compToSet = newComp++;
}
} else {
if (c > 0) {
// first row - check only previous column
if (pc < thresh) compToSet = cPtr[(c-1) * cChan]; // similar - same component
else compToSet = newComp++; // else - new component
} else {
// first corner - new component
compToSet = newComp++;
}
}
cPtr[(r * cols + c) * cChan] = compToSet;
if (newComp >= mapSize) break;
}
if (newComp >= mapSize) break;
}
// iterate over segment image, merging and collecting segment stats
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
// replace using map if needed
int comp = cPtr[(r * cols + c) * cChan];
comp = findCompMap(compMap, comp);
cPtr[(r * cols + c) * cChan] = comp;
// set data
lMap[comp] += lPtr[(r * cols + c) * lChan];
aMap[comp] += lPtr[(r * cols + c) * lChan + 1];
bMap[comp] += lPtr[(r * cols + c) * lChan + 2];
sMap[comp] += 1;
}
}
//cv::imshow("comp", comp);
// create colored component image
seg = cv::Mat::zeros(rows, cols, CV_8UC3);
lPtr = seg.ptr<uchar>(0);
lChan = seg.channels();
int bestRedId = 0;
int bestRedSize = 0;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
int comp = cPtr[(r * cols + c) * cChan];
lPtr[(r * cols + c) * lChan] = lMap[comp] / sMap[comp];
lPtr[(r * cols + c) * lChan + 1] = aMap[comp] / sMap[comp];
lPtr[(r * cols + c) * lChan + 2] = bMap[comp] / sMap[comp];
if (lPtr[(r * cols + c) * lChan + 2] > redThresh && lPtr[(r * cols + c) * lChan + 1] > redThresh) {
if (sMap[comp] > bestRedSize) {
bestRedSize = sMap[comp];
bestRedId = comp;
}
}
}
}
int tx = 0, ty = 0;
isRed = cv::Mat::zeros(rows, cols, CV_8UC1);
uchar* rPtr = isRed.ptr<uchar>(0);
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
int comp = cPtr[(r * cols + c) * cChan];
if (comp == bestRedId) {
rPtr[r * cols + c] = 255;
tx += c;
ty += r;
}
}
}
tx /= bestRedSize;
ty /= bestRedSize;
cv::imshow("red", isRed);
cv::Mat seg2;
//cv::imshow("seg_lab", seg);
cv::cvtColor(seg, seg2, CV_Lab2BGR);
cv::imshow("seg", seg2);
key = cv::waitKey(1);
if (key != 255) {
if (key == ',') unit /= 10;
if (key == '.') unit *= 10;
if (key == 'a') wLight += unit;
if (key == 'z') wLight -= unit;
if (key == 's') wColor += unit;
if (key == 'x') wColor -= unit;
if (key == 'd') wDepth += unit;
if (key == 'c') wDepth -= unit;
if (key == 'f') thresh += unit;
if (key == 'v') thresh -= unit;
if (key == 'g') redThresh += unit;
if (key == 'b') redThresh -= unit;
printInfo();
if (key == ' ') {
}
}
if (bestRedSize > 1000) {
z = dPtr[(ty * cols + tx) * dChan];
x = (tx - cx) * z / fx;
y = (ty - cy) * z / fy;
float alpha = 0.01;
int stepCount = 1000;
//fill_n(angles, 6, 0);
cv::Mat target = (cv::Mat_<float>(3,1) << x, y, z);
for (int i = 1; i <= stepCount; i++) {
gradientDescent(angles, target, alpha);
}
cout << "target " << target.t() << endl;
cout << "arm " << calculateArm(angles).t() << endl << endl;
anglesToSteps(angles, steps);
for (int i = 0; i < 6; i++) {
printf("%f %d\n", angles[i], steps[i]);
sprintf(cmd, "#%d,%d,1*", angleIdx[i], steps[i]);
if (serial > 0) {
if (write(serial, cmd, strlen(cmd)) < 0) printf("error\n");
}
}
}
}
}
close(serial);
}
int findCompMap(int* compMap, int comp) {
if (compMap[comp] == 0) {
// not in map yet
return comp;
} else {
// return found
return compMap[comp];
}
}
float compare(uchar L, uchar a, uchar b, float d, uchar L2, uchar a2, uchar b2, float d2) {
// 4D euclidean distance
return sqrt(wLight*(L-L2)*(L-L2) + wColor*(a-a2)*(a-a2) + wColor*(b-b2)*(b-b2) + wDepth*(d-d2)*(d-d2));
}
/**
* Conversion function between sl::Mat and cv::Mat
**/
cv::Mat slMat2cvMat(Mat& input) {
// Mapping between MAT_TYPE and CV_TYPE
int cv_type = -1;
switch (input.getDataType()) {
case MAT_TYPE_32F_C1: cv_type = CV_32FC1; break;
case MAT_TYPE_32F_C2: cv_type = CV_32FC2; break;
case MAT_TYPE_32F_C3: cv_type = CV_32FC3; break;
case MAT_TYPE_32F_C4: cv_type = CV_32FC4; break;
case MAT_TYPE_8U_C1: cv_type = CV_8UC1; break;
case MAT_TYPE_8U_C2: cv_type = CV_8UC2; break;
case MAT_TYPE_8U_C3: cv_type = CV_8UC3; break;
case MAT_TYPE_8U_C4: cv_type = CV_8UC4; break;
default: break;
}
// Since cv::Mat data requires a uchar* pointer, we get the uchar1 pointer from sl::Mat (getPtr<T>())
// cv::Mat and sl::Mat will share a single memory structure
return cv::Mat(input.getHeight(), input.getWidth(), cv_type, input.getPtr<sl::uchar1>(MEM_CPU));
}
// openCV mat type debug
string type2str(int type) {
string r;
uchar depth = type & CV_MAT_DEPTH_MASK;
uchar chans = 1 + (type >> CV_CN_SHIFT);
switch ( depth ) {
case CV_8U: r = "8U"; break;
case CV_8S: r = "8S"; break;
case CV_16U: r = "16U"; break;
case CV_16S: r = "16S"; break;
case CV_32S: r = "32S"; break;
case CV_32F: r = "32F"; break;
case CV_64F: r = "64F"; break;
default: r = "User"; break;
}
r += "C";
r += (chans+'0');
return r;
}
| [
"pavel.petrovic@gmail.com"
] | pavel.petrovic@gmail.com |
9b34fa832460f0ee2632123e6ace536a4223d2bc | 2fda9e8e3cce71f0b11c72df92d1b931b57ba572 | /tests/pxScene2d/test_pxPixel_h.cpp | 5fc033e7687cd7d96c27420d592ea26ea473d15b | [
"Apache-2.0"
] | permissive | mateusz-hobgarski-red/pxCore | 519385eabd37e23818c37b73577d232356001a22 | dddf99ed360c7fa4a98a40c92fc3d0ded864e841 | refs/heads/master | 2020-08-09T19:59:56.287360 | 2019-11-20T13:37:18 | 2019-11-20T13:37:18 | 214,161,586 | 1 | 0 | NOASSERTION | 2019-10-10T11:11:26 | 2019-10-10T11:11:23 | null | UTF-8 | C++ | false | false | 1,821 | cpp | /*
pxCore Copyright 2005-2018 John Robinson
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 "pxCore.h"
#include "pxPixel.h"
#include "test_includes.h" // Needs to be included last
using namespace std;
class pxPixelTest : public testing::Test
{
public:
virtual void SetUp()
{
}
virtual void TearDown()
{
}
void pxPixelParam0()
{
pxPixel p = pxPixel();
EXPECT_TRUE(sizeof(p) == sizeof(pxPixel));
}
void pxPixelParam1()
{
uint32_t u = 1;
pxPixel p = pxPixel(u);
EXPECT_TRUE(1 == p.u);
}
void pxPixelParam1Struct()
{
uint32_t u = 2;
pxPixel p = pxPixel(u);
EXPECT_TRUE(2 == p.u);
p = pxPixel((const pxPixel&)p);
}
void pxPixelParam4()
{
uint32_t r= 1;
uint32_t g= 1;
uint32_t b= 1;
uint32_t a= 1;
pxPixel p = pxPixel(r, g, b, a);
EXPECT_TRUE(1 == p.r);
EXPECT_TRUE(1 == p.g);
EXPECT_TRUE(1 == p.b);
EXPECT_TRUE(1 == p.a);
p = pxPixel(r, g, b);
EXPECT_TRUE(1 == p.r);
EXPECT_TRUE(1 == p.g);
EXPECT_TRUE(1 == p.b);
EXPECT_TRUE(255 == p.a);
}
};
TEST_F(pxPixelTest, pxPixelCompleteTest)
{
pxPixelParam0();
pxPixelParam1();
pxPixelParam1Struct();
pxPixelParam4();
}
| [
"mfiess@comcast.net"
] | mfiess@comcast.net |
084c0ce501acc98a35bbd7cc4ef35a5dd34d3608 | 45c59e5f456f11f1714b2ddf976b62dfebecfa7d | /Case10/0/cz_solid_33/k | 5bdc2c107d57d224e03d7bf5e090e06046d917eb | [] | no_license | JoelWright24/Masters-Thesis-in-OpenFOAM | 9224f71cdb38e96a378996996c5c86235db9ee13 | b6c420b5054494a26a7d65a34835b27be9e0da4a | refs/heads/main | 2023-02-20T17:18:13.067439 | 2021-01-22T19:30:36 | 2021-01-22T19:30:36 | 332,039,823 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 890 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0/cz_solid_33";
object k;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 2 -2 0 0 0 0];
internalField uniform 6.51042;
boundaryField
{
cz_solid_33_to_fluid
{
type calculated;
value uniform 0;
}
}
// ************************************************************************* //
| [
"67100764+JoelWright24@users.noreply.github.com"
] | 67100764+JoelWright24@users.noreply.github.com | |
8eb1152b6289fd98a9827e066ed2ad544761904e | abe3240cfb598f3898f1009dba57de56a99ce8ff | /tests/raycast_test.cpp | f3a2570179b39b1b948da9ea43774dbf519a3588 | [] | no_license | patrickhadlaw/RGLEngine | 632cc4613d0a7156b6882c7b1cbc58702e01f79b | ced4c60d6d3f0442cfd13da92372315137d4f594 | refs/heads/master | 2022-10-28T13:58:55.406813 | 2022-09-06T02:12:36 | 2022-09-06T02:12:36 | 201,550,102 | 0 | 0 | null | 2022-09-06T02:12:37 | 2019-08-09T22:46:38 | C++ | UTF-8 | C++ | false | false | 4,904 | cpp | #include "rgle.h"
int main() {
return rgle::util::Tester::run([](rgle::util::Tester& tester) {
tester.expect("point clip should be inside", []() {
auto point = glm::vec3(1.0f, 1.0f, 1.0f);
auto plane = rgle::ray::Plane(glm::vec3(), glm::vec3(0.0f, 0.0f, 1.0f));
return plane.clip(point) == rgle::ray::ClipResult(rgle::ray::Inside { .point = glm::vec3(1.0f, 1.0f, 1.0f) });
});
tester.expect("point clip should be outside", []() {
auto point = glm::vec3(1.0f, 1.0f, -1.0f);
auto plane = rgle::ray::Plane(glm::vec3(), glm::vec3(0.0f, 0.0f, 1.0f));
return plane.clip(point) == rgle::ray::ClipResult(rgle::ray::Outside { .point = glm::vec3(1.0f, 1.0f, 0.0f) });
});
tester.expect("ray transform should be correct", []() {
auto ray = rgle::ray::Ray {
.eye = glm::vec3(),
.target = glm::vec3(0.0f, 0.0f, 5.0f)
};
auto transformed = ray.transform(glm::translate(glm::mat4(1.0f), glm::vec3(1.0f, 1.0f, 1.0f)));
return transformed.eye == glm::vec3(1.0f, 1.0f, 1.0f) && transformed.target == glm::vec3(1.0f, 1.0f, 6.0f);
});
tester.expect("plane intersect should be a miss", []() {
auto plane = rgle::ray::Plane(glm::vec3(), glm::vec3(0.0f, 0.0f, 1.0f));
auto ray = rgle::ray::Ray {
.eye = glm::vec3(0.0f, 0.0f, 1.0f),
.target = glm::vec3(0.0f, 0.0f, 2.0f)
};
return plane.intersect(ray) == rgle::ray::IntersectResult(rgle::ray::Miss {});
});
tester.expect("plane intersect should be a hit", []() {
auto plane = rgle::ray::Plane(glm::vec3(), glm::vec3(0.0f, 0.0f, 1.0f));
auto ray = rgle::ray::Ray {
.eye = glm::vec3(0.0f, 0.0f, -1.0f),
.target = glm::vec3(0.0f, 0.0f, 0.0f)
};
return plane.intersect(ray) == rgle::ray::IntersectResult(rgle::ray::HitOnce {
.hit = rgle::ray::Intersection {
.position = glm::vec3(),
.normal = glm::vec3(0.0f, 0.0f, -1.0f)
}
});
});
tester.expect("ball intersect should be a double hit", []() {
auto ball = rgle::ray::Ball(5.0f);
auto ray = rgle::ray::Ray {
.eye = glm::vec3(0.0f, 0.0f, -10.0f),
.target = glm::vec3(0.0f, 0.0f, 0.0f)
};
auto result = rgle::ray::IntersectResult(rgle::ray::HitTwice {
.closer = rgle::ray::Intersection {
.position = glm::vec3(0.0f, 0.0f, -5.0f),
.normal = glm::vec3(0.0f, 0.0f, -1.0f)
},
.farther = rgle::ray::Intersection {
.position = glm::vec3(0.0f, 0.0f, 5.0f),
.normal = glm::vec3(0.0f, 0.0f, 1.0f)
}
});
return ball.intersect(ray) == result;
});
tester.expect("ball intersect should be a single hit", []() {
auto ball = rgle::ray::Ball(5.0f);
auto ray = rgle::ray::Ray {
.eye = glm::vec3(5.0f, 0.0f, -10.0f),
.target = glm::vec3(5.0f, 0.0f, 0.0f)
};
auto result = rgle::ray::IntersectResult(rgle::ray::HitOnce {
.hit = rgle::ray::Intersection {
.position = glm::vec3(5.0f, 0.0f, 0.0f),
.normal = glm::vec3(1.0f, 0.0f, 0.0f)
}
});
return ball.intersect(ray) == result;
});
tester.expect("model intersect should be a hit", []() {
auto model = rgle::ray::Model(rgle::ray::Transform {
.transform = rgle::ray::RayTransform(glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 5.0f))),
.model = std::make_unique<rgle::ray::Model>(rgle::ray::Model(rgle::ray::And {
.lhs = rgle::ray::transform(rgle::ray::Ball(1.0f), glm::translate(glm::mat4(1.0f), glm::vec3(-1.0f, 0.0f, 0.0f))),
.rhs = rgle::ray::transform(rgle::ray::Ball(1.0f), glm::translate(glm::mat4(1.0f), glm::vec3(1.0f, 0.0f, 0.0f))),
}))
});
auto ray = rgle::ray::Ray {
.eye = glm::vec3(-5.0f, 0.0f, 5.0f),
.target = glm::vec3(-4.0f, 0.0f, 5.0f)
};
return model.intersect(ray) == std::make_optional(rgle::ray::Intersection {
.position = glm::vec3(-2.0f, 0.0f, 5.0f),
.normal = glm::vec3(-1.0f, 0.0f, 0.0f)
});
});
tester.expect("model intersect should be a miss", []() {
auto model = rgle::ray::Model(rgle::ray::Transform {
.transform = rgle::ray::RayTransform(glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 5.0f))),
.model = std::make_unique<rgle::ray::Model>(rgle::ray::Model(rgle::ray::And {
.lhs = rgle::ray::transform(rgle::ray::Ball(1.0f), glm::translate(glm::mat4(1.0f), glm::vec3(-1.0f, 0.0f, 0.0f))),
.rhs = rgle::ray::transform(rgle::ray::Ball(1.0f), glm::translate(glm::mat4(1.0f), glm::vec3(1.0f, 0.0f, 0.0f))),
}))
});
auto ray = rgle::ray::Ray {
.eye = glm::vec3(-2.0f, 0.0f, 0.0f),
.target = glm::vec3(-2.0f, 0.0f, 1.0f)
};
return model.intersect(ray) == std::nullopt;
});
});
}
| [
"patrickhadlaw@gmail.com"
] | patrickhadlaw@gmail.com |
4c7766b6d26079880dc21810252a657efff85d17 | e01f1c3c5f3a0c421306f19649767a6722ac3e19 | /entitydisplay.h | 1dc9f4ead12141e2f22ef06d89a7b9cc7ad33e3b | [] | no_license | algogr/AlgoIceDroid | edde0ef7c39ce108294bdd7c396a64e888fbf626 | e47670aadfe245a3104a3707c3b0adc6336016f7 | refs/heads/master | 2021-01-20T11:00:37.547452 | 2014-10-11T16:12:21 | 2014-10-11T16:12:21 | 24,685,938 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 954 | h | #ifndef ENTITYDISPLAY_H
#define ENTITYDISPLAY_H
#include <QObject>
class EntityDisplay : public QObject
{
Q_OBJECT
Q_PROPERTY(QString title READ title WRITE setTitle)
Q_PROPERTY(QString value READ value WRITE setValue)
Q_PROPERTY(QString fieldname READ fieldname WRITE setFieldname)
Q_PROPERTY(QString relatedentity READ relatedentity WRITE setRelatedentity)
Q_PROPERTY(bool editable READ editable WRITE setEditable)
public:
explicit EntityDisplay(QObject *parent = 0);
QString title();
QString value();
QString fieldname();
QString relatedentity();
bool editable();
void setTitle(QString title);
void setValue(QString value);
void setFieldname(QString fieldname);
void setEditable(bool editable);
void setRelatedentity(QString relatedentity);
protected:
QString mtitle,mvalue,mfieldname,mrelatedentity;
bool meditable;
signals:
public slots:
};
#endif // ENTITYDISPLAY_H
| [
"jimpar@algo.gr"
] | jimpar@algo.gr |
cf0f9caa68819d43777fa389c4819fe616ffcbb7 | 9c48a0af704d3a49b0b57d0689d91bac8542c5af | /practice/04/c++/4/4/4.cpp | 5581bf1b349d728e9234c51366f384b6bf32aa40 | [] | no_license | emfortress/programming | e9cf105e12608f3c27c69d0c201490493f91cd6c | a36694b297360dfe421f4a73c7f7745e2972dedb | refs/heads/main | 2023-03-18T04:09:00.912656 | 2021-03-14T17:56:46 | 2021-03-14T17:56:46 | 306,659,040 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 751 | cpp | #include <iostream>
int main() {
setlocale(LC_ALL, "Russian");
int a, b;
std::cout << "Введите два целых числа, разделённых пробелом или новой строкой." << std::endl;
std::cin >> a >> b;
// Обмен без дополнительной переменной
a = a - b;
b = b + a;
a = b - a;
std::cout << "Значение a = " << a << std::endl;
std::cout << "Значение b = " << b << std::endl;
// Обмен с дополнительной переменной
int temp;
temp = a;
a = b;
b = temp;
std::cout << "Значение a = " << a << std::endl;
std::cout << "Значение b = " << b << std::endl;
} | [
"timur_trofanchuk@mail.ru"
] | timur_trofanchuk@mail.ru |
fe0b59a04385eefb169261f32283ea8a771f99ec | 30fd2d0e910b9b4339ea5a1f2d4ef079285d3bd7 | /Lib/Include/PersistentData.h | 8704e7a22fdfdeb6839baf4d1b5ce2359ba0c54b | [] | no_license | kiar40k/Big-Numbers | 3452c33902f0e63781139541552a2c2e14776839 | 7c4d6dc52deeeac2ac0cdded5a3b3c2ee510b327 | refs/heads/master | 2021-06-20T01:46:18.860052 | 2017-08-05T16:04:58 | 2017-08-05T16:04:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 927 | h | #pragma once
#include <XmlDoc.h>
class PersistentData {
private:
String m_name;
protected:
static const TCHAR *s_defaultName;
public:
PersistentData() : m_name(s_defaultName) {
}
void load(const String &fileName);
void save(const String &fileName);
static void checkTag(XMLNodePtr node, const TCHAR *expectedTag);
static XMLNodePtr getChild(XMLDoc &doc, XMLNodePtr n, const TCHAR *tag);
virtual void putDataToDoc(XMLDoc &doc) = 0;
virtual void getDataFromDoc(XMLDoc &doc) = 0;
inline const String &getName() const {
return m_name;
}
inline void setName(const String &name) {
m_name = name;
}
inline void setDefaultName() {
setName(s_defaultName);
}
inline bool hasName() const {
return m_name.length() > 0;
}
inline bool hasDefaultName() const {
return m_name == s_defaultName;
}
String getDisplayName() const;
virtual int getType() const = 0;
};
| [
"jesper.gr.mikkelsen@gmail.com"
] | jesper.gr.mikkelsen@gmail.com |
41fae9aaf46292f80672df8b5d3b3f923beba258 | 22f57701df31b3182f3bcb83da729ecc584f8fb6 | /December-29/c++_kumaran_cupstring.cpp | e93f9ff633f572740fe89ba47b14d79fec0edafb | [] | no_license | Prashant-Bharaj/A-December-of-Algorithms | e88640c711abbe2e6cac71cb4652dac243984484 | 7bbd56572f4ddc9648e90615ee810765544c56e4 | refs/heads/master | 2023-08-05T15:37:20.362561 | 2021-09-19T05:51:53 | 2021-09-19T05:51:53 | 287,055,360 | 0 | 0 | null | 2020-08-12T15:53:05 | 2020-08-12T15:53:04 | null | UTF-8 | C++ | false | false | 185 | cpp | #include<iostream>
using namespace std;
main()
{
int n,m,res;
cout<<"enter no of friends";
cin>>n;
m=n-1;
res=m*(m+1)/2
cout<<"The no.of strings required are "<<res;
}
| [
"noreply@github.com"
] | Prashant-Bharaj.noreply@github.com |
b69338d398dfcd9800f875772da7d4a5e84c5771 | 1c9678ef5867d68999ce4fd358f545d68cd1c550 | /CPP-HW2/District.cpp | 9667681bb6b1ba49e2b6e9ba60962963739899fe | [] | no_license | Idokah/CPP-HW2 | 598dbe9efe71795a4f44f1399fa4b62b4884c448 | 2eb32be4e7c21ba8def432771d6aac02cee393df | refs/heads/master | 2023-02-08T22:27:33.689924 | 2020-12-29T18:09:23 | 2020-12-29T18:09:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,893 | cpp | #include "District.h"
#include "Citizen.h"
#include <math.h>
#include <iostream>
using namespace std;
char* getString(const char* input);
District::District(): votersPercentage(0), electionResultsSize(0), voteCount(0), citizenNum(0) {
this->name = nullptr;
this->id = -1;
this->representativeNum = 0;
this->electionResults = nullptr;
}
District::District(char *name, int representativeNum):
votersPercentage(0), electionResultsSize(1), voteCount(0), citizenNum(0) {
this->name = getString(name);
this->id = this-> generateID();
this->representativeNum = representativeNum;
this->electionResults = new int[electionResultsSize];
for (int i = 0; i < this->electionResultsSize ; ++i) {
this->electionResults[i]=0;
}
}
int District::getID() { return this->id; }
char* District::getName() { return this->name; }
char* District::getName() const { return this->name; }
int District::getElectionResultsSize() { return this->electionResultsSize; }
int District::getRepresentativeNum(){return this->representativeNum; }
int District::getRepresentativeNum() const { return this->representativeNum; }
int* District::getElectionResults(){ return this->electionResults; }
void District::printType(std::ostream& os) const{}
District::District(const District& other)
{
*this = other;
}
void District::operator=(const District& other)
{
this->voteCount=other.voteCount;
if (this->name!=nullptr) delete[] name;
this->name = getString(other.name);
this->id = other.id;
this->citizenNum=other.citizenNum;
this->votersPercentage = other.votersPercentage;
this->electionResults = new int[other.electionResultsSize];
this->electionResultsSize=other.electionResultsSize;
memcpy(this->electionResults, other.electionResults, sizeof(int) * other.electionResultsSize);
this->representativeNum = other.representativeNum;
}
District::~District()
{
delete[] name;
delete[] this->electionResults;
}
int District::generateID(int val)
{
static int id = 0;
if (val != 0)
{
id = val;
return id;
}
return ++id;
}
void District::addVote(Citizen* voter, const int partyNum)
{
if (! voter->getIsAlreadyVote()) {
this->addToElectionResult(partyNum);
voter->setIsAlreadyVote();
this->voteCount ++;
this->votersPercentage= (static_cast<float>(this->voteCount) / static_cast<float>(this->citizenNum)) * 100;
} else {
cout << "already voted!" << endl;
}
}
void District::addToElectionResult(const int partyNum)
{
if (this->electionResultsSize < partyNum ){
this->increaseArrSize(this->electionResults,this->electionResultsSize, partyNum);
}
this->electionResults[partyNum-1]++;
}
void District::increaseArrSize(int*& arr, int &currSize, const int newSize) {
int* newArr = new int[newSize];
for (int i = 0; i < currSize; i++)
{
newArr[i] = arr[i];
}
for (int i = currSize; i<newSize; i++)
{
newArr[i]=0;
}
delete[] arr;
currSize = newSize;
arr = newArr;
}
void District::increaseCitizenNum()
{
this->citizenNum++;
}
int District::getWinningParty(){
int maxIndex = 0, max = 0;
for (int i = 0; i < this->electionResultsSize; ++i) {
if (this->electionResults[i] > max){
max = this->electionResults[i];
maxIndex = i;
}
}
return (maxIndex + 1);
}
int *District::getNumOfRepresantivesPerParty(int& numOfExistsPartiesInDistrict){
float *percentagePerParty = this->getPercentagePerParty();
int *numOfRepresantivesPerParty = new int[electionResultsSize];
for (int i = 0; i < this->electionResultsSize; ++i) {
numOfRepresantivesPerParty[i] = round(percentagePerParty[i] * this->representativeNum / 100);
}
numOfExistsPartiesInDistrict = this->electionResultsSize;
return numOfRepresantivesPerParty;
}
float* District::getPercentagePerParty()
{
float *percentagePerParty = new float[electionResultsSize]; //// the index represent the (party ID - 1) and the value is the percentage.
for (int i = 0; i < electionResultsSize; ++i)
{
percentagePerParty[i] = (this->voteCount == 0) ? 0 : (static_cast<float>(this->electionResults[i]) / static_cast<float>(this->voteCount)) * 100;
}
return percentagePerParty;
}
float District::getVotePercentage()
{
return ((this->citizenNum==0)? 0 : static_cast<float>(this->voteCount) / static_cast<float>(this->citizenNum)) * 100;
}
ostream& operator<<(ostream& os, const District& district)
{
os << "District ID "<<district.id << " District Name: " << district.getName() << ", num of representative: " << district.getRepresentativeNum()<<" ";
district.printType(os);
return os;
}
void District::printElectionResult(int partiesLogSize, Party** parties)
{
Party* party;
char* headName;
int numOfExistsPartiesInDistrict, * numOfRepresantivesPerParty = nullptr, * electionResults , partyIndex;
float* percentagePerParty = nullptr;
int numOfParties = this->getElectionResultsSize();
electionResults = this->getElectionResults();
percentagePerParty = this->getPercentagePerParty();
numOfRepresantivesPerParty = this->getNumOfRepresantivesPerParty(numOfExistsPartiesInDistrict);
cout << "total voters percentage- " << this->votersPercentage << "%" << endl;
cout << "--- parties results --- " << endl;
votesPerParty* votersPerParty = this->getPartiesSortedByVotes(this->getElectionResults(), numOfParties);
for (int j = 0; j < partiesLogSize; ++j) {
partyIndex = votersPerParty->size > j ? votersPerParty[j].partyIndex : j;
cout << " Party " << (parties[partyIndex]->getName()) <<":"<< endl;
if (j < numOfExistsPartiesInDistrict)
{
cout << " number of voters- " << electionResults[partyIndex] << endl
<< " percentage of all votes - " << percentagePerParty[partyIndex] << "%" << endl;
if (numOfRepresantivesPerParty[j] > 0) {
cout << " represantives - " << endl;
party = parties[j];
party->printNRepresantive(this->getID(), numOfRepresantivesPerParty[partyIndex]);
}
}
else {
cout << " number of voters" << " - 0" << endl
<< " percentage of all votes - 0%" << endl;
}
}
}
votesPerParty* District::getPartiesSortedByVotes(int* electionResult, int electionResultLogSize)
{
votesPerParty* votesPerPartyArr = new votesPerParty[electionResultLogSize];
votesPerPartyArr->size = electionResultLogSize;
for (int i = 0; i < electionResultLogSize; i++)
{
votesPerPartyArr[i] = { i,electionResult[i] };
}
mergeSort(votesPerPartyArr, electionResultLogSize);
return votesPerPartyArr;
}
void District::setGenerateIDtoValue(int val)
{
this->generateID(val);
}
void District::mergeSort(votesPerParty* indexesArr, int size) {
votesPerParty* temp;
if (size <= 1) return;
else {
mergeSort(indexesArr, size / 2);
mergeSort(indexesArr + size / 2, size - size / 2);
temp = new votesPerParty[size];
merge(indexesArr, indexesArr + size / 2, size / 2, size - size / 2, temp);
for (int i = 0; i < size; i++) {
indexesArr[i] = temp[i];
}
delete[] temp;
}
}
void District::merge(votesPerParty* indexesArr1, votesPerParty* indexesArr2, int size1, int size2, votesPerParty* res)
{
votesPerParty currentValue1;
votesPerParty currentValue2;
int i1 = 0, i2 = 0, iRes = 0;
while (i1 < size1 && i2 < size2)
{
currentValue1 = *(indexesArr1 + i1);
currentValue2 = *(indexesArr2 + i2);
if (currentValue1.numOfVotes > currentValue2.numOfVotes)
{
res[iRes] = indexesArr1[i1];
iRes++;
i1++;
}
else
{
res[iRes] = indexesArr2[i2];
iRes++;
i2++;
}
}
while (i1 < size1)
{
res[iRes] = indexesArr1[i1];
iRes++;
i1++;
}
while (i2 < size2)
{
res[iRes] = indexesArr2[i2];
iRes++;
i2++;
}
}
void District::save(ostream& out) const
{
int nameLen = strlen(this->name);
out.write(rcastcc(&nameLen), sizeof(nameLen));
out.write(rcastcc(this->name), sizeof(char) * nameLen);
out.write(rcastcc(&this->id), sizeof(this->id));
out.write(rcastcc(&this->citizenNum), sizeof(this->citizenNum));
out.write(rcastcc(&this->votersPercentage), sizeof(this->votersPercentage));
out.write(rcastcc(&this->voteCount), sizeof(this->voteCount));
int electionResultsLen = this->electionResultsSize;
out.write(rcastcc(&electionResultsLen), sizeof(electionResultsLen));
out.write(rcastcc(this->electionResults), sizeof(int) * electionResultsLen);
out.write(rcastcc(&this->representativeNum), sizeof(this->representativeNum));
}
void District::load(istream& in)
{
int nameLen;
in.read(rcastc(&nameLen), sizeof(nameLen));
this->name = new char[nameLen + 1];
this->name[nameLen] = '\0';
in.read(rcastc(this->name), sizeof(char) * nameLen);
in.read(rcastc(&this->id), sizeof(this->id));
in.read(rcastc(&this->citizenNum), sizeof(this->citizenNum));
in.read(rcastc(&this->votersPercentage), sizeof(this->votersPercentage));
in.read(rcastc(&this->voteCount), sizeof(this->voteCount));
int electionResultsLen;
in.read(rcastc(&electionResultsLen), sizeof(electionResultsLen));
this->electionResultsSize = electionResultsLen;
this->electionResults = new int[electionResultsLen];
in.read(rcastc(this->electionResults), sizeof(int) * electionResultsLen);
in.read(rcastc(&this->representativeNum), sizeof(this->representativeNum));
}
| [
"idokh@mta.ac.il"
] | idokh@mta.ac.il |
f81a1df9709d95e5145cd1b3b0ec26add599c567 | 68984cbb4191be1192daa6e7de3e3ff6b1acc4ce | /settings.cpp | 9fbd42236893b1cf656fa386f1b09964d8fa59ee | [] | no_license | xibeilang524/AntScope2 | 6699ef351c0d30f1d0649ed6d0b2823a53271c8a | 017bb23a5e58166f21358bf721a5f03db1c97ff0 | refs/heads/master | 2020-07-03T11:03:33.446503 | 2019-06-15T19:27:53 | 2019-06-15T19:27:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 33,490 | cpp | #include "settings.h"
#include "ui_settings.h"
#include "popupindicator.h"
#include "analyzer/customanalyzer.h"
#include "fqinputvalidator.h"
extern QString appendSpaces(const QString& number);
QString Settings::iniFilePath;
Settings::Settings(QWidget *parent) :
QDialog(parent),
ui(new Ui::Settings),
m_analyzer(NULL),
m_calibration(NULL),
m_isComplete(false),
m_generalTimer(NULL),
m_markersHintEnabled(true),
m_graphHintEnabled(true),
m_graphBriefHintEnabled(true),
m_onlyOneCalib(false),
m_metricChecked(false),
m_farEndMeasurement(0)
{
ui->setupUi(this);
PopUpIndicator::setIndicatorVisible(false);
QString style = "QPushButton:disabled{"
"background-color: rgb(59, 59, 59);"
"color: rgb(119, 119, 119);}";
ui->openOpenFileBtn->setStyleSheet(style);
ui->openCalibBtn->setStyleSheet(style);
ui->shortOpenFileBtn->setStyleSheet(style);
ui->shortCalibBtn->setStyleSheet(style);
ui->loadOpenFileBtn->setStyleSheet(style);
ui->loadCalibBtn->setStyleSheet(style);
ui->calibWizard->setStyleSheet(style);
style = "QGroupBox {border: 2px solid rgb(100,100,100); margin-top: 1ex;}";
style += "QGroupBox::title {color: rgb(1, 178, 255);}";
ui->groupBox_10->setStyleSheet(style);
ui->groupBox_11->setStyleSheet(style);
ui->browseLine->setText(tr("Choose file"));
ui->updateProgressBar->hide();
ui->checkUpdatesBtn->setEnabled(false);
ui->openProgressBar->hide();
ui->shortProgressBar->hide();
ui->loadProgressBar->hide();
QString path = Settings::setIniFile();
m_settings = new QSettings(path, QSettings::IniFormat);
m_settings->beginGroup("Settings");
m_markersHintEnabled = m_settings->value("markersHintEnabled", true).toBool();
m_graphHintEnabled = m_settings->value("graphHintEnabled", true).toBool();
m_graphBriefHintEnabled = m_settings->value("graphBriefHintEnabled", true).toBool();
ui->tabWidget->setCurrentIndex(m_settings->value("currentIndex",0).toInt());
ui->markersHintCheckBox->setChecked(m_markersHintEnabled);
ui->graphHintCheckBox->setChecked(m_graphHintEnabled);
ui->graphBriefHintCheckBox->setChecked(m_graphBriefHintEnabled);
m_settings->endGroup();
ui->cableComboBox->addItem(tr("Change parameters or choose from list..."));
ui->cableComboBox->setStyleSheet("QComboBox { combobox-popup: 0; }");
ui->cableComboBox->setMaxVisibleItems(20);
connect(ui->lineEditMin, &QLineEdit::editingFinished, this, &Settings::on_fqMinFinished);
connect(ui->lineEditMax, &QLineEdit::editingFinished, this, &Settings::on_fqMaxFinished);
ui->lineEditPoints->setText("500");
connect(ui->lineEditPoints, &QLineEdit::editingFinished, this, &Settings::on_PointsFinished);
//{
// TODO Bug #2247: update doesn't work from Antscope2
ui->tabWidget->removeTab(4);
//}
//{
// TODO Analyzer customization is not fully implemented yet
extern bool g_developerMode;
if (!g_developerMode) {
ui->tabWidget->removeTab(3);
} else {
initCustomizeTab();
}
//}
QString cablesPath = Settings::programDataPath("cables.txt");
openCablesFile(cablesPath);
foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
{
ui->serialPortComboBox->addItem(info.portName());
}
connect(ui->closeBtn, SIGNAL(pressed()), this, SLOT(close()));
}
Settings::~Settings()
{
emit paramsChanged();
double Z0 = ui->lineEdit_systemImpedance->text().toDouble();
if((Z0 > 0) && (Z0 <= 1000))
{
emit Z0Changed(Z0);
}
CustomAnalyzer::save();
m_settings->beginGroup("Settings");
m_settings->setValue("markersHintEnabled", m_markersHintEnabled);
m_settings->setValue("graphHintEnabled", m_graphHintEnabled);
m_settings->setValue("graphBriefHintEnabled", m_graphBriefHintEnabled);
m_settings->setValue("currentIndex",ui->tabWidget->currentIndex());
m_settings->endGroup();
if(m_analyzer != NULL)
{
m_analyzer->setIsMeasuring(false);
}
if(m_generalTimer)
{
m_generalTimer->stop();
delete m_generalTimer;
m_generalTimer = NULL;
}
delete ui;
}
void Settings::setZ0(double _Z0)
{
ui->lineEdit_systemImpedance->setText(QString::number(_Z0));
}
void Settings::on_browseBtn_clicked()
{
QFileInfo info;
QString path;
QString fileName = QFileDialog::getOpenFileName(this, tr("Open firmware file"),
"","*.bin");
m_path = fileName;
ui->browseLine->setText(fileName);
if (!fileName.isEmpty()) {
info.setFile(fileName);
path = info.absolutePath();
m_isComplete = m_analyzer->checkFile(m_path);
if (m_isComplete) {
m_pathToFw = fileName;
ui->updateBtn->setEnabled(true);
}
} else {
ui->browseLine->setText(tr("Choose file"));
m_isComplete = false;
}
}
void Settings::on_checkUpdatesBtn_clicked()
{
ui->checkUpdatesBtn->setText(tr("Checking"));
if(m_generalTimer)
{
m_generalTimer->stop();
delete m_generalTimer;
}
m_generalTimer = new QTimer(this);
connect(m_generalTimer, SIGNAL(timeout()), this, SLOT(on_generalTimerTick()));
m_generalTimer->start(200);
emit checkUpdatesBtn();
}
void Settings::on_generalTimerTick()
{
static qint32 state = 0;
static qint32 ticks = 0;
ticks++;
if(ticks >= 25)
{
ui->checkUpdatesBtn->setText(tr("Check Updates"));
ticks = 0;
m_generalTimer->stop();
return;
}
QString strChecking = tr("Checking");
switch(state)
{
case 0 :
state++;
ui->checkUpdatesBtn->setText(strChecking);
break;
case 1 :
state++;
ui->checkUpdatesBtn->setText(strChecking + ".");
break;
case 2 :
state++;
ui->checkUpdatesBtn->setText(strChecking + "..");
break;
case 3 :
state = 0;
ui->checkUpdatesBtn->setText(strChecking + "...");
break;
default:
state = 0;
break;
}
}
void Settings::setAnalyzer(Analyzer * analyzer)
{
if(analyzer)
{
m_analyzer = analyzer;
qint32 num = m_analyzer->getModel();
if(num != 0)
{
ui->checkUpdatesBtn->setEnabled(true);
ui->analyzerModelLabel->setText(m_analyzer->getModelString());
ui->serialLabel->setText(m_analyzer->getSerialNumber());
QString version = QString::number(m_analyzer->getVersion());
if(version.length() == 3)
{
version.insert(1,".");
}
ui->versionLabel->setText(version);
}else
{
ui->checkUpdatesBtn->setEnabled(false);
m_analyzer->closeComPort();
findBootloader();
}
}
}
void Settings::setCalibration(Calibration * calibration)
{
if(calibration)
{
m_calibration = calibration;
ui->labelOpenState->setText(m_calibration->getOpenFileName());
ui->labelShortState->setText(m_calibration->getShortFileName());
ui->labelLoadState->setText(m_calibration->getLoadFileName());
ui->lineEditPoints->setText(QString::number(m_calibration->dotsNumber()));
if(m_calibration->getCalibrationPerformed())
{
if(m_calibration->getCalibrationEnabled())
{
emit calibrationEnabled(true);
}
else
{
emit calibrationEnabled(false);
}
}
}
}
void Settings::setGraphHintChecked(bool checked)
{
ui->graphHintCheckBox->setChecked(checked);
}
void Settings::setGraphBriefHintChecked(bool checked)
{
ui->graphBriefHintCheckBox->setChecked(checked);
}
void Settings::setMarkersHintChecked(bool checked)
{
ui->markersHintCheckBox->setChecked(checked);
}
void Settings::findBootloader (void)
{
static qint32 counter = 0;
QList<ReDeviceInfo> list;
list = ReDeviceInfo::availableDevices(ReDeviceInfo::Serial);
for(int n = 0; n < list.length(); ++n)
{
QString name = ReDeviceInfo::deviceName(list.at(n));
for(int i = QUANTITY-1; i > 0; i--)
{
if(names[i].indexOf(name) >= 0 )
{
m_analyzer->setComAnalyzerFound(true);
m_analyzer->setAnalyzerModel(i);
m_analyzer->openComPort(list.at(n).portName(),115200);
ui->analyzerModelLabel->setText(name);
ui->checkUpdatesBtn->setEnabled(true);
break;
}
}
}
if (list.length() == 0)
{
int model = m_analyzer->getHidModel();
if( model != 0)
{
m_analyzer->setHidAnalyzerFound(true);
m_analyzer->setAnalyzerModel(model);
ui->analyzerModelLabel->setText(names[model]);
ui->checkUpdatesBtn->setEnabled(true);
}else
{
counter++;
if(counter < 5)
{
QTimer::singleShot(300,this, SLOT(findBootloader()));
}
ui->checkUpdatesBtn->setEnabled(false);
}
}
if((m_analyzer->getAnalyzerModel() == 0) && (counter == 5))
{
counter = 0;
QTimer::singleShot( 1, m_analyzer, SLOT(on_findAA30ZERO()));
}
}
void Settings::on_autoUpdatesCheckBox_clicked(bool checked)
{
emit autoUpdatesCheckBox(checked);
}
void Settings::on_updateBtn_clicked()
{
ui->updateBtn->setEnabled(false);
ui->updateBtn->setText("Updating...");
ui->updateProgressBar->show();
emit updateBtn(m_pathToFw);
}
void Settings::on_percentChanged(qint32 percent)
{
if(percent == 100)
{
ui->updateBtn->setText("Update");
ui->updateBtn->setEnabled(true);
ui->updateProgressBar->hide();
ui->updateProgressBar->setValue(0);
}
ui->updateProgressBar->setValue(percent);
}
void Settings::on_graphHintCheckBox_clicked(bool checked)
{
emit graphHintChecked(checked);
m_graphHintEnabled = checked;
}
void Settings::on_graphBriefHintCheckBox_clicked(bool checked)
{
emit graphBriefHintChecked(checked);
m_graphBriefHintEnabled = checked;
}
void Settings::on_markersHintCheckBox_clicked(bool checked)
{
emit markersHintChecked(checked);
m_markersHintEnabled = checked;
}
void Settings::on_calibWizard_clicked()
{
enableButtons(false);
QMessageBox::information(NULL, tr("Open"),
tr("Please connect OPEN standard and press OK."));
emit startCalibration();
}
void Settings::on_percentCalibrationChanged(qint32 state, qint32 percent)
{
switch (state) {
case 1:
ui->openProgressBar->setValue(percent);
if(percent == 100)
{
if(m_onlyOneCalib)
{
ui->openProgressBar->hide();
ui->labelOpenState->setText("cal_open.s1p");
m_onlyOneCalib = false;
enableButtons(true);
}
}else
{
ui->openProgressBar->show();
}
break;
case 2:
ui->shortProgressBar->show();
ui->shortProgressBar->setValue(percent);
if(percent == 100)
{
if(m_onlyOneCalib)
{
ui->shortProgressBar->hide();
ui->labelShortState->setText("cal_short.s1p");
m_onlyOneCalib = false;
enableButtons(true);
}
}
break;
case 3:
ui->loadProgressBar->show();
ui->loadProgressBar->setValue(percent);
if(percent == 100)
{
if(m_onlyOneCalib)
{
ui->loadProgressBar->hide();
ui->labelLoadState->setText("cal_load.s1p");
m_onlyOneCalib = false;
}else
{
ui->openProgressBar->hide();
ui->shortProgressBar->hide();
ui->loadProgressBar->hide();
ui->labelOpenState->setText("cal_open.s1p");
ui->labelShortState->setText("cal_short.s1p");
ui->labelLoadState->setText("cal_load.s1p");
}
enableButtons(true);
}
break;
default:
break;
}
}
void Settings::on_openCalibBtn_clicked()
{
enableButtons(false);
m_onlyOneCalib = true;
if (QMessageBox::information(NULL, tr("Open"),
tr("Please connect OPEN standard and press OK.")) == QMessageBox::Ok)
emit startCalibrationOpen();
}
void Settings::on_shortCalibBtn_clicked()
{
enableButtons(false);
m_onlyOneCalib = true;
QMessageBox::information(NULL, tr("Short"),
tr("Please connect SHORT standard and press OK."));
emit startCalibrationShort();
}
void Settings::on_loadCalibBtn_clicked()
{
enableButtons(false);
m_onlyOneCalib = true;
QMessageBox::information(NULL, tr("Load"),
tr("Please connect LOAD standard and press OK."));
emit startCalibrationLoad();
}
void Settings::enableButtons(bool enabled)
{
ui->openOpenFileBtn->setEnabled(enabled);
ui->openCalibBtn->setEnabled(enabled);
ui->shortOpenFileBtn->setEnabled(enabled);
ui->shortCalibBtn->setEnabled(enabled);
ui->loadOpenFileBtn->setEnabled(enabled);
ui->loadCalibBtn->setEnabled(enabled);
ui->calibWizard->setEnabled(enabled);
}
void Settings::on_openOpenFileBtn_clicked()
{
QString dir = localDataPath("Calibration");
QString path = QFileDialog::getOpenFileName(this, tr("Open 'open calibration' file"),
dir,"*.s1p");
QStringList list;
list = path.split("/");
if(list.length() == 1)
{
list.clear();
list = path.split("\\");
}
ui->labelOpenState->setText(list.last());
emit openOpenFile(path);
}
void Settings::on_shortOpenFileBtn_clicked()
{
QString dir = localDataPath("Calibration");
QString path = QFileDialog::getOpenFileName(this, tr("Open 'short calibration' file"),
dir,"*.s1p");
QStringList list;
list = path.split("/");
if(list.length() == 1)
{
list.clear();
list = path.split("\\");
}
ui->labelShortState->setText(list.last());
emit shortOpenFile(path);
}
void Settings::on_loadOpenFileBtn_clicked()
{
QString dir = localDataPath("Calibration");
QString path = QFileDialog::getOpenFileName(this, tr("Open 'load calibration' file"),
dir,"*.s1p");
QStringList list;
list = path.split("/");
if(list.length() == 1)
{
list.clear();
list = path.split("\\");
}
ui->labelLoadState->setText(list.last());
emit loadOpenFile(path);
}
void Settings::setMeasureSystemMetric(bool state)
{
ui->measureSystemMetric->setChecked(state);
m_metricChecked = state;
ui->measureSystemAmerican->setChecked(!state);
m_americanChecked = !state;
}
void Settings::on_measureSystemMetric_clicked(bool checked)
{
if(!checked)
{
if(m_metricChecked)
{
ui->measureSystemMetric->setChecked(true);
}else
{
m_metricChecked = checked;
}
}else
{
emit changeMeasureSystemMetric(checked);
m_metricChecked = checked;
m_americanChecked = !checked;
ui->measureSystemAmerican->setChecked(!checked);
}
}
void Settings::on_measureSystemAmerican_clicked(bool checked)
{
if(!checked)
{
if(m_americanChecked)
{
ui->measureSystemAmerican->setChecked(true);
}else
{
m_americanChecked = checked;
}
}else
{
emit changeMeasureSystemMetric(!checked);
m_americanChecked = checked;
m_metricChecked = !checked;
ui->measureSystemMetric->setChecked(!checked);
}
}
void Settings::on_doNothingBtn_clicked(bool checked)
{
if( !checked )
{
if(m_farEndMeasurement == 0)
{
ui->doNothingBtn->setChecked(true);
}
}else
{
m_farEndMeasurement = 0;
ui->addCableBtn->setChecked(false);
ui->subtractCableBtn->setChecked(false);
emit paramsChanged();
cableActionEnableButtons(false);
}
}
void Settings::on_subtractCableBtn_clicked(bool checked)
{
if( !checked )
{
if(m_farEndMeasurement == 1)
{
ui->subtractCableBtn->setChecked(true);
}
}else
{
m_farEndMeasurement = 1;
ui->addCableBtn->setChecked(false);
ui->doNothingBtn->setChecked(false);
emit paramsChanged();
cableActionEnableButtons(true);
}
}
void Settings::on_addCableBtn_clicked(bool checked)
{
if( !checked )
{
if(m_farEndMeasurement == 2)
{
ui->addCableBtn->setChecked(true);
}
}else
{
m_farEndMeasurement = 2;
ui->subtractCableBtn->setChecked(false);
ui->doNothingBtn->setChecked(false);
emit paramsChanged();
cableActionEnableButtons(true);
}
}
void Settings::cableActionEnableButtons(bool enabled)
{
ui->cableR0->setEnabled(enabled);
ui->cableLossComboBox->setEnabled(enabled);
ui->cableLen->setEnabled(enabled);
ui->conductiveLoss->setEnabled(enabled);
ui->dielectricLoss->setEnabled(enabled);
ui->atFq->setEnabled(enabled);
ui->anyFq->setEnabled(enabled);
}
//Cable-------------------------------------------------------------------------
void Settings::setCableVelFactor(double value)
{
ui->velocityFactor->setText(QString::number(value,'f',2));
}
double Settings::getCableVelFactor(void)const
{
return ui->velocityFactor->text().toDouble();
}
//------------------------------------------------------------------------------
void Settings::setCableResistance(double value)
{
ui->cableR0->setText(QString::number(value));
}
double Settings::getCableResistance(void)const
{
return ui->cableR0->text().toDouble();
}
//------------------------------------------------------------------------------
void Settings::setCableLossConductive(double value)
{
ui->conductiveLoss->setText(QString::number(value));
}
double Settings::getCableLossConductive(void)const
{
return ui->conductiveLoss->text().toDouble();
}
//------------------------------------------------------------------------------
void Settings::setCableLossDielectric(double value)
{
ui->dielectricLoss->setText(QString::number(value));
}
double Settings::getCableLossDielectric(void)const
{
return ui->dielectricLoss->text().toDouble();
}
//------------------------------------------------------------------------------
void Settings::setCableLossFqMHz(double value)
{
ui->atMHz->setText(QString::number(value));
}
double Settings::getCableLossFqMHz(void)const
{
return ui->atMHz->text().toDouble();
}
//------------------------------------------------------------------------------
void Settings::setCableLossUnits(int value)
{
ui->cableLossComboBox->setCurrentIndex(value);
}
int Settings::getCableLossUnits(void)const
{
return ui->cableLossComboBox->currentIndex();
}
//------------------------------------------------------------------------------
void Settings::setCableLossAtAnyFq(bool value)
{
if(value)
{
ui->anyFq->setChecked(value);
}else
{
ui->atFq->setChecked(!value);
}
}
bool Settings::getCableLossAtAnyFq(void)const
{
return ui->anyFq->isChecked();
}
//------------------------------------------------------------------------------
void Settings::setCableLength(double value)
{
ui->cableLen->setText(QString::number(value));
}
double Settings::getCableLength(void)const
{
return ui->cableLen->text().toDouble();
}
//------------------------------------------------------------------------------
void Settings::setCableFarEndMeasurement(int value)
{
m_farEndMeasurement = value;
if(m_farEndMeasurement == 0)
{
ui->doNothingBtn->setChecked(true);
cableActionEnableButtons(false);
}else if(m_farEndMeasurement == 1)
{
ui->subtractCableBtn->setChecked(true);
}else if(m_farEndMeasurement == 2)
{
ui->addCableBtn->setChecked(true);
}
}
int Settings::getCableFarEndMeasurement(void)const
{
return m_farEndMeasurement;
}
//------------------------------------------------------------------------------
void Settings::setCableIndex(int value)
{
if(value >= 0)
ui->cableComboBox->setCurrentIndex(value);
}
int Settings::getCableIndex(void)const
{
return ui->cableComboBox->currentIndex();
}
//------------------------------------------------------------------------------
void Settings::openCablesFile(QString path)
{
m_cablesList.clear();
ui->cableComboBox->addItem(tr("Ideal 50-Ohm cable"));
m_cablesList.append(tr("Ideal 50-Ohm cable, 50, 0.66, 0.0, 0.0, 0, 0"));
ui->cableComboBox->addItem(tr("Ideal 75-Ohm cable"));
m_cablesList.append(tr("Ideal 75-Ohm cable, 75, 0.66, 0.0, 0.0, 0, 0"));
ui->cableComboBox->addItem(tr("Ideal 25-Ohm cable"));
m_cablesList.append(tr("Ideal 25-Ohm cable, 25, 0.66, 0.0, 0.0, 0, 0"));
ui->cableComboBox->addItem(tr("Ideal 37.5-Ohm cable"));
m_cablesList.append(tr("Ideal 37.5-Ohm cable, 37.5, 0.66, 0.0, 0.0, 0, 0"));
if (path.isEmpty())
return;
QFile file(path);
bool res = file.open(QFile::ReadOnly);
if(!res)
{
QMessageBox::information(this, tr("Can't open file"), path, QMessageBox::Close);
return;
}
QTextStream in(&file);
QString line;
do
{
line = in.readLine();
if( (line == "") || (line.at(0) == ';'))
{
continue;
}else
{
QList <QString> list;
list = line.split(',');
if(list.length() == 7)
{
ui->cableComboBox->addItem(list.at(0));
m_cablesList.append(line);
}else
{
qDebug() << "Settings::openCablesFile: Error: Len != 7";
}
}
} while (!line.isNull());
}
void Settings::on_cableComboBox_currentIndexChanged(int index)
{
if(index > 0)
{
QString str = m_cablesList.at(index-1);
QList <QString> paramsList = str.split(',');
//1. Cable name
ui->cableR0->setText( paramsList.at(1));//2. R0 in Ohm
ui->velocityFactor->setText(paramsList.at(2));//3. Velocity factor
ui->conductiveLoss->setText(paramsList.at(3));//4. Conductive loss
ui->dielectricLoss->setText(paramsList.at(4));//5. Dielectric loss
ui->cableLossComboBox->setCurrentIndex(paramsList.at(5).toInt());//6. Loss units (0=dB/100ft, 1=dB/ft, 2=dB/100m, 3=dB/m)
bool anyFq = (bool)paramsList.at(6).toInt();//7. Frequency in MHz at which loss is specified (or 0 for any frequency)
if(!anyFq)
{
ui->anyFq->setChecked(true);
}else
{
ui->atFq->setChecked(true);
}
}
}
void Settings::on_updateGraphsBtn_clicked()
{
emit paramsChanged();
}
QString Settings::setIniFile()
{
//iniFilePath = Settings::localDataPath() + "AntScope2.ini";
iniFilePath = Settings::localDataPath("AntScope2.ini");
return iniFilePath;
}
QString Settings::localDataPath(QString _fileName)
{
// Mac OS X and iOS
#ifdef Q_OS_DARWIN
QDir dir_ini3 = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
return dir_ini3.absoluteFilePath("RigExpert/AntScope2/" + _fileName);
#else
QDir dir_ini3 = QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation);
return dir_ini3.absoluteFilePath("RigExpert/AntScope2/" + _fileName);
#endif
qDebug("TODO Settings::localDataPath");
return QString();
}
QString Settings::programDataPath(QString _fileName)
{
// Mac OS X and iOS
#ifdef Q_OS_DARWIN
QDir dir = QCoreApplication::applicationDirPath();
return dir.absoluteFilePath("Resources/" + _fileName);
#endif
// win32 and win64
#ifdef Q_OS_WIN
QStringList list = QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation);
qDebug() << list;
for (int idx=0; idx<list.size(); idx++)
{
QDir dir = list[idx];
QString path = dir.absoluteFilePath("RigExpert/AntScope2/" + _fileName);
if (QFile::exists(path))
return path;
}
return QString();
#endif
//qDebug("TODO Settings::programDataPath");
return QString();
}
void Settings::on_aa30bootFound()
{
ui->serialLabel->setText(m_analyzer->getSerialNumber());
ui->analyzerModelLabel->setText(m_analyzer->getModelString());
QString version = QString::number(m_analyzer->getVersion());
ui->versionLabel->setText(version);
ui->checkUpdatesBtn->setEnabled(true);
}
void Settings::on_aa30updateComplete()
{
this->close();
}
void Settings::on_autoUpdatesCheckBox(bool checked)
{
emit firmwareAutoUpdateStateChanged(checked);
}
void Settings::on_checkBox_AntScopeAutoUpdate_clicked(bool checked)
{
emit antScopeAutoUpdateStateChanged(checked);
}
void Settings::setFirmwareAutoUpdate(bool checked)
{
ui->autoUpdatesCheckBox->setChecked(checked);
}
void Settings::setAntScopeAutoUpdate(bool checked)
{
ui->checkBox_AntScopeAutoUpdate->setChecked(checked);
}
void Settings::setAntScopeVersion(QString version)
{
ui->antScopeVersion->setText(version);
}
void Settings::setAutoDetectMode(bool state, QString portName)
{
ui->autoDetect->setChecked(state);
m_autoDetectChecked = state;
ui->manualDetect->setChecked(!state);
m_manualDetectChecked = !state;
ui->serialPortComboBox->setEnabled(!state);
int found = -1;
for(int i = 0; i < ui->serialPortComboBox->count(); ++i)
{
if( portName == ui->serialPortComboBox->itemText(i))
{
found = i;
break;
}
}
if(found >= 0)
{
ui->serialPortComboBox->setCurrentIndex(found);
}else
{
ui->serialPortComboBox->addItem(portName);
ui->serialPortComboBox->setCurrentText(portName);
}
}
void Settings::on_autoDetect_clicked(bool checked)
{
if(!checked)
{
if(m_autoDetectChecked)
{
ui->autoDetect->setChecked(true);
}else
{
m_manualDetectChecked = checked;
}
}else
{
emit changedAutoDetectMode(true);
m_autoDetectChecked = checked;
m_manualDetectChecked = !checked;
ui->manualDetect->setChecked(!checked);
}
ui->serialPortComboBox->setEnabled(false);
}
void Settings::on_manualDetect_clicked(bool checked)
{
if(!checked)
{
if(m_manualDetectChecked)
{
ui->manualDetect->setChecked(true);
}else
{
m_autoDetectChecked = checked;
}
}else
{
emit changedAutoDetectMode(false);
m_manualDetectChecked = checked;
m_autoDetectChecked = !checked;
ui->autoDetect->setChecked(!checked);
}
ui->serialPortComboBox->setEnabled(true);
}
void Settings::on_serialPortComboBox_activated(const QString &arg1)
{
emit changedSerialPort(arg1);
}
void Settings::setLanguages(QStringList list, int number)
{
ui->languageComboBox->addItems(list);
ui->languageComboBox->setCurrentIndex(number);
}
void Settings::on_translate()
{
ui->retranslateUi(this);
ui->cableComboBox->setItemText(0, tr("Change parameters or choose from list..."));
}
void Settings::on_languageComboBox_currentIndexChanged(int index)
{
emit languageChanged(index);
}
void Settings::on_closeButton_clicked()
{
accept();
}
void Settings::on_bandsComboBox_currentIndexChanged(int index)
{
QString band = ui->bandsCombobox->itemText(index);
m_settings->beginGroup("Settings");
m_settings->setValue("current_band", band);
m_settings->endGroup();
emit bandChanged(band);
}
void Settings::setBands(QList<QString> list)
{
foreach (QString band, list) {
ui->bandsCombobox->addItem(band);
}
m_settings->beginGroup("Settings");
QString current_band = m_settings->value("current_band", "").toString();
m_settings->endGroup();
connect(ui->bandsCombobox, SIGNAL(currentIndexChanged(int)), this, SLOT(on_bandsComboBox_currentIndexChanged(int)));
ui->bandsCombobox->setCurrentText(current_band);
}
void Settings::initCustomizeTab()
{
ui->comboBoxPrototype->hide();
ui->label_19->hide();
ui->comboBoxPrototype->clear();
ui->comboBoxName->clear();
ui->comboBoxName->blockSignals(true);
ui->comboBoxPrototype->blockSignals(true);
//CustomAnalyzer::load(m_settings);
QString curAlias = CustomAnalyzer::currentAlias();
for (int idx=0; idx<QUANTITY; idx++) {
ui->comboBoxPrototype->addItem(names[idx]);
}
const QMap<QString, CustomAnalyzer>& map = CustomAnalyzer::getMap();
QStringList keys = map.keys();
for (int idx=0; idx<keys.size(); idx++) {
ui->comboBoxName->addItem(map[keys[idx]].alias());
}
CustomAnalyzer::setCurrent(curAlias);
CustomAnalyzer* ca = CustomAnalyzer::getCurrent();
if (ca != nullptr) {
ui->comboBoxName->setCurrentText(ca->alias());
ui->lineEditMin->setText(ca->minFq());
ui->lineEditMax->setText(ca->maxFq());
ui->spinBoxWidth->setValue(ca->width());
ui->spinBoxHeight->setValue(ca->height());
ui->comboBoxPrototype->setCurrentText(ca->prototype());
} else {
on_comboBoxName_currentIndexChanged(ui->comboBoxName->currentIndex());
}
connect(ui->customizeCheckBox, &QCheckBox::toggled, this, &Settings::on_enableCustomizeControls);
connect(ui->btnAdd, &QPushButton::clicked, this, &Settings::on_addButton);
connect(ui->btnRemove, &QPushButton::clicked, this, &Settings::on_removeButton);
connect(ui->btnAply, &QPushButton::clicked, this, &Settings::onApplyButton);
connect(ui->comboBoxPrototype, SIGNAL(currentIndexChanged(int)), this, SLOT(on_comboBoxPrototype_currentIndexChanged(int)));
connect(ui->comboBoxName, SIGNAL(currentIndexChanged(int)), this, SLOT(on_comboBoxName_currentIndexChanged(int)));
ui->customizeCheckBox->setChecked(CustomAnalyzer::customized());
ui->comboBoxName->blockSignals(false);
ui->comboBoxPrototype->blockSignals(false);
on_enableCustomizeControls(CustomAnalyzer::customized());
}
void Settings::on_enableCustomizeControls(bool enable)
{
ui->comboBoxName->setEnabled(enable);
ui->comboBoxPrototype->setEnabled(enable);
ui->lineEditMin->setEnabled(enable);
ui->lineEditMax->setEnabled(enable);
ui->spinBoxWidth->setEnabled(enable);
ui->spinBoxHeight->setEnabled(enable);
ui->btnAdd->setEnabled(enable);
ui->btnRemove->setEnabled(enable);
CustomAnalyzer::customize(enable);
}
void Settings::on_comboBoxPrototype_currentIndexChanged(int index)
{
ui->lineEditMin->setText(minFq[index]);
ui->lineEditMax->setText(maxFq[index]);
ui->spinBoxWidth->setValue(lcdWidth[index]);
ui->spinBoxHeight->setValue(lcdHeight[index]);
}
void Settings::on_comboBoxName_currentIndexChanged(int index)
{
Q_UNUSED(index)
QString key = ui->comboBoxName->currentText();
if (!key.isEmpty()) {
CustomAnalyzer::setCurrent(key);
CustomAnalyzer* ca = CustomAnalyzer::get(key);
if (ca != nullptr) {
ui->comboBoxName->setCurrentText(ca->alias());
ui->lineEditMin->setText(ca->minFq());
ui->lineEditMax->setText(ca->maxFq());
ui->spinBoxWidth->setValue(ca->width());
ui->spinBoxHeight->setValue(ca->height());
ui->comboBoxPrototype->setCurrentText(ca->prototype());
}
}
}
void Settings::onApplyButton()
{
if (ui->comboBoxName->currentText().isEmpty())
return;
CustomAnalyzer ca;
ca.setAlias(ui->comboBoxName->currentText());
ca.setPrototype(ui->comboBoxPrototype->currentText());
ca.setMinFq(ui->lineEditMin->text());
ca.setMaxFq(ui->lineEditMax->text());
ca.setWidth(ui->spinBoxWidth->value());
ca.setHeight(ui->spinBoxHeight->value());
CustomAnalyzer::add(ca);
CustomAnalyzer::setCurrent(ca.alias());
CustomAnalyzer::save();
initCustomizeTab();
}
void Settings::on_removeButton()
{
if (ui->comboBoxName->currentText().isEmpty())
return;
CustomAnalyzer::remove(ui->comboBoxName->currentText());
CustomAnalyzer::save();
initCustomizeTab();
}
void Settings::on_addButton()
{
ui->comboBoxName->setCurrentText("");
ui->comboBoxPrototype->setCurrentText("names[0]");
ui->lineEditMin->setText("0");
ui->lineEditMax->setText("0");
ui->spinBoxWidth->setValue(0);
ui->spinBoxHeight->setValue(0);
}
void Settings::on_fqMinFinished()
{
QString str = ui->lineEditMin->text();
str.remove(' ');
ui->lineEditMin->setText(appendSpaces(str));
}
void Settings::on_fqMaxFinished()
{
QString str = ui->lineEditMax->text();
str.remove(' ');
ui->lineEditMax->setText(appendSpaces(str));
}
void Settings::on_PointsFinished()
{
QString str = ui->lineEditPoints->text();
m_calibration->setDotsNumber(str.toInt());
}
| [
"serg.butenko@gmail.com"
] | serg.butenko@gmail.com |
fb4bbfcc8e8ba71b72d604e4e7e55abd95d1d2cc | 367ae0f777042c1c4760aa15279ef5f53bff3e23 | /pmlc/dialect/pxa/transforms/resize_tmps.cc | 1f0cb42d7bfebc85f71046230928c9e0416173dc | [
"Apache-2.0"
] | permissive | Flex-plaidml-team/plaidml | e47535bda63b82bfc936296c2c3eaae9481e0ce9 | 1070411a87b3eb3d94674d4d041ed904be3e7d87 | refs/heads/plaidml-v1 | 2023-06-26T21:24:38.800462 | 2021-07-19T04:29:24 | 2021-07-19T04:29:24 | 287,434,263 | 0 | 0 | Apache-2.0 | 2020-08-14T03:28:50 | 2020-08-14T03:26:35 | C++ | UTF-8 | C++ | false | false | 10,554 | cc | // Copyright 2020 Intel Corporation
#include "mlir/Dialect/Affine/IR/AffineOps.h"
#include "mlir/Dialect/Affine/IR/AffineValueMap.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/Support/DebugStringHelper.h"
#include "pmlc/dialect/pxa/analysis/strides.h"
#include "pmlc/dialect/pxa/analysis/uses.h"
#include "pmlc/dialect/pxa/ir/ops.h"
#include "pmlc/dialect/pxa/transforms/pass_detail.h"
#include "pmlc/dialect/stdx/ir/ops.h"
#include "pmlc/util/logging.h"
using namespace mlir; // NOLINT
namespace pmlc::dialect::pxa {
namespace {
struct ResizeTmpsPass : public ResizeTmpsBase<ResizeTmpsPass> {
explicit ResizeTmpsPass(bool onlyParallelNested) {
this->onlyParallelNested = onlyParallelNested;
}
void runOnFunction() final {
auto func = getFunction();
func.walk([&](memref::AllocOp op) { runOnAlloc(op); });
}
AffineValueMap computeInnerValueMap(AffineMap orig, ValueRange operands,
Block *block) {
SmallVector<StrideInfo> strides;
LogicalResult ok = computeMultiDimStrideInfo(orig, operands, strides);
(void)ok; // Silence warning in release builds
assert(succeeded(ok) && "Could not compute stride info");
SmallVector<StrideInfo, 4> inner;
for (size_t i = 0; i < strides.size(); i++) {
auto innerStride = strides[i].inner(block);
inner.push_back(innerStride);
}
return convertToValueMap(orig.getContext(), inner);
}
void runOnAlloc(memref::AllocOp op) {
Block *opBlock = op.getOperation()->getBlock();
IVLOG(2, "Considering: " << debugString(*op.getOperation()));
for (auto &use : getIndirectUses(op)) {
if (isa<ReturnOp>(use.getOwner())) {
IVLOG(2, "Found ReturnOp user, cannot resize allocation");
return;
} else if (isa<pmlc::dialect::stdx::ReshapeOp>(use.getOwner())) {
IVLOG(2, "Found ReshapeOp user, cannot resize allocation");
return;
}
}
// Resize only nested ops option
if (onlyParallelNested && !dyn_cast<AffineParallelOp>(op->getParentOp())) {
return;
}
SmallVector<StrideInfo, 4> outer;
SmallVector<StrideRange, 4> inner;
auto vectorSize = 0;
for (auto &use : getIndirectAccessUses(op)) {
IVLOG(2, "Found use: " << debugString(*use.getOwner()));
SmallVector<StrideInfo> strides;
if (auto lop = dyn_cast<PxaReadOpInterface>(use.getOwner())) {
if (failed(computeMultiDimStrideInfo(lop.getAffineMap(),
lop.getMapOperands(), strides))) {
lop.emitRemark("Unable to compute strides for access");
return;
}
// Get vector size value. For scalar ops vec size is set to 1.
// For now this value can be optimized only when all sizes match.
// TODO: investigate if different values can be used here and how to
// set the indices afterwards
if (auto vecOp = dyn_cast<PxaVectorLoadOp>(use.getOwner())) {
auto vecShape = vecOp.getVectorType().getShape();
// Accept only vectors with dim size 1
if (vecShape.size() != 1)
return;
// Check if size is the same as for previous op
vectorSize =
(vectorSize == 0 || vectorSize == vecShape[0]) ? vecShape[0] : 0;
} else if (auto scalarOp = dyn_cast<PxaLoadOp>(use.getOwner())) {
vectorSize = (vectorSize == 0 || vectorSize == 1) ? 1 : 0;
}
if (!vectorSize) {
use.getOwner()->emitRemark(
"Users of Alloc ops have different vector/scalar sizes");
return;
}
} else if (auto rop = dyn_cast<PxaReduceOpInterface>(use.getOwner())) {
if (failed(computeMultiDimStrideInfo(rop.getAffineMap(),
rop.getMapOperands(), strides))) {
rop.emitRemark("Unable to compute strides for access");
return;
}
// Get vector size value. For scalar ops vec size is set to 1.
// For now this value can be optimized only when all sizes match.
// TODO: investigate if different values can be used here and how to
// set the indices afterwards
if (auto vecOp = dyn_cast<PxaVectorReduceOp>(use.getOwner())) {
auto vecShape = vecOp.getVectorType().getShape();
// Accept only vectors with dim size 1
if (vecShape.size() != 1)
return;
// Check if size is the same as for previous op
vectorSize =
(vectorSize == 0 || vectorSize == vecShape[0]) ? vecShape[0] : 0;
} else if (auto scalarOp = dyn_cast<PxaReduceOp>(use.getOwner())) {
vectorSize = (vectorSize == 0 || vectorSize == 1) ? 1 : 0;
}
if (!vectorSize) {
use.getOwner()->emitRemark(
"Users of Alloc ops have different vector/scalar sizes");
return;
}
}
SmallVector<StrideInfo, 4> curOuter;
SmallVector<StrideRange, 4> curInner;
for (size_t i = 0; i < strides.size(); i++) {
auto dimStride = strides[i];
auto dimStrideOuter = dimStride.outer(opBlock);
auto dimStrideInner = dimStride.inner(opBlock);
curOuter.push_back(dimStrideOuter);
curInner.push_back(dimStrideInner.range());
if (!curInner.back().valid) {
use.getOwner()->emitRemark("Invalid inner range");
return;
}
}
// If we have set outer strides, make sure we match them
if (outer.size()) {
assert(curOuter.size() == outer.size() &&
"All accesses should have the same rank");
assert(curInner.size() == inner.size() &&
"All accesses should have the same rank");
if (outer != curOuter) {
use.getOwner()->emitRemark("Mismatched out access");
return;
}
for (size_t i = 0; i < inner.size(); i++) {
inner[i].unionEquals(curInner[i]);
}
} else {
// Otherwise, define new outer strides
outer = curOuter;
inner = curInner;
}
}
assert(outer.size() == inner.size() &&
"All accesses should have the same rank");
// Check for lots of kinds of failures and compute new size
bool sizeChanged = false;
SmallVector<int64_t, 4> newShape;
auto oldShape = op.getType().getShape();
for (size_t i = 0; i < outer.size(); i++) {
auto outerRange = outer[i].range();
auto innerRange = inner[i];
if (!outerRange.valid) {
op.emitRemark("Invalid outer range");
return;
}
if (innerRange.minVal != 0) {
op.emitRemark("Inner range has non-trivial lower bound");
return;
}
if (innerRange.stride < 0) {
op.emitRemark("Negative strides not handled");
return;
}
if (outerRange.stride && innerRange.maxVal + 1 > outerRange.stride) {
op.emitRemark("Inner and outer ranges overlap");
return;
}
newShape.push_back(innerRange.maxVal + 1);
IVLOG(2, "Original size:" << oldShape[i]);
IVLOG(2, "Computed size:" << newShape[i]);
// if you assume that incoming IR is sane
// then there is no need to expand
if (newShape[i] > oldShape[i]) {
IVLOG(2, "Expansion not allowed, resetting to original size");
newShape[i] = oldShape[i];
}
// Expand the last size for vector ops
if (i == oldShape.size() - 1)
newShape[i] *= vectorSize;
if (newShape[i] != oldShape[i]) {
sizeChanged = true;
}
}
// If it's already sized right, don't bother
if (!sizeChanged) {
return;
}
// Compute new memref type
auto newType = MemRefType::get(newShape, op.getType().getElementType());
op.getResult().setType(newType);
// Update type on all definitions
for (auto value : getIndirectValues(op.getResult())) {
value.setType(newType);
}
// Update all of the access maps
// Get ops first and then replace since we modify use-def chain during
// mutation.
SmallVector<Operation *, 4> ops;
for (auto &use : getIndirectAccessUses(op.getResult())) {
ops.push_back(use.getOwner());
}
// Now do the actual changes. Note, we don't bother erasing the original
// instructions, but they get cleaned up via canonicalization
for (Operation *op : ops) {
if (auto rop = dyn_cast<PxaReduceOpInterface>(op)) {
// TODO: This probably should move into some sort of utility transform,
// but I need another example or two to generalize from
auto vm = computeInnerValueMap(rop.getAffineMap(), rop.getMapOperands(),
opBlock);
OpBuilder replace(rop.getOperation());
if (auto ropOp = dyn_cast<PxaReduceOp>(rop.getOperation())) {
auto nrop = replace.create<PxaReduceOp>(
ropOp.getLoc(), ropOp.agg(), ropOp.val(), ropOp.getMemRef(),
vm.getAffineMap(), vm.getOperands());
ropOp.replaceAllUsesWith(nrop.result());
} else if (auto ropOp =
dyn_cast<PxaVectorReduceOp>(rop.getOperation())) {
auto nrop = replace.create<PxaVectorReduceOp>(
ropOp.getLoc(), ropOp.agg(), ropOp.val(), ropOp.getMemRef(),
vm.getAffineMap(), vm.getOperands());
ropOp.replaceAllUsesWith(nrop.result());
}
}
if (auto lop = dyn_cast<PxaReadOpInterface>(op)) {
auto vm = computeInnerValueMap(lop.getAffineMap(), lop.getMapOperands(),
opBlock);
OpBuilder replace(lop.getOperation());
if (auto lopOp = dyn_cast<PxaLoadOp>(lop.getOperation())) {
auto nlop =
replace.create<PxaLoadOp>(lopOp.getLoc(), lopOp.getMemRef(),
vm.getAffineMap(), vm.getOperands());
lopOp.replaceAllUsesWith(nlop.result());
} else if (auto lopOp = dyn_cast<PxaVectorLoadOp>(lop.getOperation())) {
auto nlop = replace.create<PxaVectorLoadOp>(
lopOp.getLoc(), lopOp.getVectorType(), lopOp.getMemRef(),
vm.getAffineMap(), vm.getOperands());
lopOp.replaceAllUsesWith(nlop.result());
}
}
}
}
};
} // namespace
std::unique_ptr<Pass> createResizeTmpsPass(bool onlyParallelNested) {
return std::make_unique<ResizeTmpsPass>(onlyParallelNested);
}
} // namespace pmlc::dialect::pxa
| [
"noreply@github.com"
] | Flex-plaidml-team.noreply@github.com |
5ad25e6eb9cd709fc99196eef8873a387a9c6111 | 616d9e83ac7b0dafc37bb0a753da79bc10c9bd6d | /week--04/day--01/airCraftCarrier/F35.cpp | 20b5a8ae480075ae068247533eddffd7a76be554 | [] | no_license | green-fox-academy/Teleeeee | 7c8428922497a9bd76ea43de903e840a9cbdeaa5 | b7b8eff32c79e1ee03684096ee0ca246db389079 | refs/heads/master | 2020-07-19T06:58:07.323979 | 2020-01-30T21:18:02 | 2020-01-30T21:18:02 | 206,396,188 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 153 | cpp | //
// Created by User on 30/09/2019.
//
#include "F35.h"
F35::F35() {
setMaxAmmo(12);
setAmmo(0);
setType("F35");
setBaseDamage(50);
}
| [
"lev9433@gmail.com"
] | lev9433@gmail.com |
69047c0b3a5a2d99becc206f330b3818d1206882 | ddfd906f4e2fd42b7162a96529af858fdf478dff | /4sem/saod/Курсовая/Includes/UsersList.h | 53c5f17df01dbf5cbe49e70f761c42394c6e1774 | [] | no_license | teploe-odealko/univer | 1627ecd714215cadf30538e16a94d06a9dc335b2 | 48aea299181ee73f4164a4eeba06014745de6c3b | refs/heads/master | 2021-01-03T20:31:59.679594 | 2020-06-08T12:27:42 | 2020-06-08T12:27:42 | 240,226,356 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 632 | h | #pragma once
#define UsersList_h
#include <string>
using namespace std;
struct UserNode
{
string last_name;
string phone_model;
};
class UsersList
{
private:
UserNode *users;
int max_num_of_users;
int current_num_of_users = 0;
public:
string operator_name;
UsersList(int, string);
int get_current_num_of_users() { return current_num_of_users; }
int get_max_num_of_users() {return max_num_of_users; }
void add_user(string, string);
void show_all_users();
void to_file(ofstream&);
bool remove_user(string);
bool isEmpty();
int findByData(string);
~UsersList();
};
| [
"din.latypov@gmail.com"
] | din.latypov@gmail.com |
7470c77548b3b47a5e8a8b31524d31759a4046d9 | 18d0216007a6e89bf10a6ad18349950b24ed13f4 | /sicily_code/old/1231.cpp | 9716f1c2aee868fee8e7a1e9c0540381bfa52437 | [] | no_license | cuiweixie/soj_water_codes | 895e73bf0271854771551b2c4d764f8f4c3c3b8e | c3539ac875d4012ccb9243b7cca11557a4587666 | refs/heads/master | 2016-08-03T00:16:14.316397 | 2012-05-10T07:47:44 | 2012-05-10T07:47:44 | 4,281,555 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,909 | cpp | #include <iostream>
#include <string>
#include <cstring>
#include <stdio.h>
using namespace std;
long long int prime[500000];
bool isPrime[1000001];
void getPrime()
{
memset(isPrime,1,sizeof(isPrime));
prime[0] = 0;
for(long long int i=2;i<1000000;i++)
{
if(isPrime[i])prime[++prime[0]] = i;
for(long long int j =1;j<=prime[0]&&i*prime[j]<=1000000;j++)
{
isPrime[i*prime[j]] = 0;
if(i%prime[j]==0)break;
}
}
}
string str;
int L;
int len;
int num[50];
void initialized()
{
len = (str.length()-1)/3+1;
memset(num,0,sizeof(num));
if(str.length()%3==0)
{
for(int i=0;i<len;i++)
for(int j=i*3,k=0;k<3;k++,j++)
{
num[i]=num[i]*10+str[j]-'0';
}
}
else
{
int first_index=str.length()%3-1;
for(int i=0;i<=first_index;i++)
{
num[0] = num[0]*10+str[i]-'0';
}
for(int i=1;i<len;i++)
{
for(int j=first_index+(i-1)*3+1,k=0;k<3;k++,j++)
{
num[i]=num[i]*10+str[j]-'0';
}
}
}
}
int mod(const int &prime)
{
int x = 1000%prime;
int res=num[0];
for(int i=1;i<len;i++)
{
res = (res*x+num[i])%prime;
}
res=res%prime;
return res;
}
void littleNum()
{
long long int K =0;
for(int i=0;i<str.length();i++)
K = K*10+str[i]-'0';
int ans =0;
for(int i=1;prime[i]<L;i++)
{
if(K%prime[i] ==0)
{
ans = prime[i];
break;
}
}
if(ans ==0)
cout << "GOOD"<<endl;
else
cout << "BAD "<< ans << endl;
}
int main()
{
getPrime();
while(cin >>str >> L)
{
if(str == "0") return 0;
initialized();
L++;
if(str.length()<19)
littleNum();
else
{
int ans =0; int temp;
for(int i=1;prime[i]<L;i++)
{
temp = mod(prime[i]);
if(temp == 0)
{
ans = prime[i];
break;
}
}
if(ans==0)
cout<<"GOOD"<<endl;
else
cout<<"BAD "<< ans << endl;
}
}
}
| [
"cuiweixie@gmail.com"
] | cuiweixie@gmail.com |
3bf751a5cfcd091d5784030dce4b3eb89aefb944 | 73e5d2812ec4aa07dc9eacf11decb6a73e907d64 | /src/MIT_alice/MUILineCircleVisual.h | 17f6045b1f9d1bebb3b5e195d6fe92a2d4b3914e | [
"MIT"
] | permissive | midasitdev/aliceui | cdf781f84e2d488d0cc7083aa3c783937459ba76 | 3693018021892bcccbc66f29b931d9736db6f9dc | refs/heads/master | 2020-04-24T06:51:27.386806 | 2020-03-05T23:55:48 | 2020-03-05T23:55:48 | 171,779,938 | 10 | 5 | NOASSERTION | 2019-03-08T00:07:41 | 2019-02-21T01:44:39 | C++ | UTF-8 | C++ | false | false | 706 | h | #pragma once
#define MIDAS_SDK
#include "MUILinesVisual.h"
#include "MUICircleDef.h"
#include "HeaderPre.h"
namespace mit
{
namespace ui
{
class __MY_EXT_CLASS__ MUILineCircleVisual : public MUILinesVisual
{
MRUNTIME_DECL_KINDOF( MUILineCircleVisual );
public:
MUILineCircleVisual();
virtual ~MUILineCircleVisual();
//////////////////////////////////////////////////////////////////////////
// Rendering data
public:
const std::vector< Circle >& GetCircles() const;
float GetLineWidth() const;
SkColor GetLineColor() const;
};
}
}
#include "HeaderPost.h"
| [
"skwoo@midasit.com"
] | skwoo@midasit.com |
52a7768d1bb0fce02b20b348aac40f498ccbdea1 | b400ea725f0f6d6cbb59fa801d56c8513c851993 | /include/hpp/foot/solvers/LPQPsolver.hh | 1348050561afe11167af74f850b3e99fdbedbad8 | [] | no_license | ggory15/HPP_foottrajectory | db43718ee5715573ca5e79d2d2b18d2645cb9560 | 11d136ce7234c6d437e0a8b8ddbd8ce9f7854da5 | refs/heads/master | 2020-03-28T17:04:42.451964 | 2018-10-19T14:42:04 | 2018-10-19T14:42:04 | 148,756,293 | 0 | 1 | null | 2018-09-14T15:31:05 | 2018-09-14T08:04:11 | CMake | UTF-8 | C++ | false | false | 1,828 | hh | #pragma once
#include <iostream>
#include <fstream>
// #include <eigenqp/LSSOL.h>
// #include <eigenqp/LSSOL_QP.h>
// #include <eigenqp/LSSOL_LP.h>
#include <qpOASES.hpp>
#include <hpp/foot/TrajectoryProblem.hh> // done
#include <hpp/foot/utils/defs.hh> // done
#include <hpp/foot/solvers/QP.hh>
#include <hpp/foot/solvers/QPPlanesFixed.hh> //done
#include <hpp/foot/solvers/QPBoxesFixed.hh> // done
#include <hpp/foot/solvers/QPBoxesFixedIndividual.hh> //done
namespace hpp{
namespace foot
{
class LPQPSolver
{
public:
LPQPSolver(const TrajectoryProblem& pb, const size_t& maxIter, const double& precision = 1e-8);
virtual ~LPQPSolver();
void init(const Eigen::VectorXd& xInit);
void solve();
void logAllX(const std::string& fileName) const;
const QPPlanesFixed& qpPlanesFixed() const { return qpPlanesFixed_; }
const QPBoxesFixed& qpBoxesFixed() const { return qpBoxesFixed_; }
void formAndSolveQPPlanesFixed(RefVec x);
void formAndSolveLPBoxesFixed(RefVec x);
void formAndSolveIndividualLPBoxesFixed(RefVec x);
Eigen::VectorXd res() const { return res_; }
const size_t& totalIter() const { return totalIter_; }
private:
const TrajectoryProblem& pb_;
QPPlanesFixed qpPlanesFixed_;
QPBoxesFixed qpBoxesFixed_;
QPBoxesFixedIndividual qpBoxesFixedIndividual_;
Eigen::VectorXd res_;
size_t maxIter_, totalIter_;
std::vector<Eigen::VectorXd> resHistory_;
double precision_;
/// @brief QP solver
qpOASES::SQProblem* QPSolver_;
qpOASES::SQProblem* LPSolver_;
qpOASES::SQProblem* LPSolverIndiv_;
bool m_init_QP, m_init_LP, m_init_LPInd;
qpOASES::returnValue m_status_QP, m_status_LP, m_status_LPInd;
qpOASES::Options m_options;
Eigen::VectorXd x_sol_;
};
} /* feettrajectory */
} | [
"ggory15@snu.ac.kr"
] | ggory15@snu.ac.kr |
18770ac11be62bcb3961356de9772c23f58e7b6b | 5146ef95cf61da886d565b292553f54ba5dc7b4e | /Assignment2/JUDGE_AND_SOLUTION/JUDGE/test_disjoint_set.cpp | ce4d4c42cabbb1ddd1065d15938a73f06f9d6ac7 | [] | no_license | dongyi-kim/ajou.datastructure.2018.spring | 3f4eb578abafce93509ec27573fd6f0978032263 | 8ab1cbcaa7218d14198970a6572e77e2ee77a10e | refs/heads/master | 2021-09-17T03:40:22.062900 | 2018-06-27T12:25:30 | 2018-06-27T12:25:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 738 | cpp | #include "main.h"
#include "graph.h"
#include "heap.h"
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include<memory.h>
int main(int argc, char *argv[]){
int i;
int j;
char DATA_FOLDER[2048];
strcpy(DATA_FOLDER, argv[1]);
graph* g = read_graph(DATA_FOLDER);
disjoint_set* set = init_set(g->V);
graph* spanning_tree = init_graph(g->V, g->V - 1);
for (i = 0, j = 0; i < g->E; i += 1){
int u = g->edges[i].origin;
int v = g->edges[i].dest;
if (find_set(set, u) == find_set(set, v)){
continue;
}
spanning_tree->edges[j++] = g->edges[i];
union_set(set, u, v);
}
write_graph(DATA_FOLDER, spanning_tree);
release_set(set);
release_graph(g);
release_graph(spanning_tree);
return 0;
} | [
"waps12b@naver.com"
] | waps12b@naver.com |
175b3062783e4402c8a7fd160591e5cbc515735e | cf8ddfc720bf6451c4ef4fa01684327431db1919 | /SDK/ARKSurvivalEvolved_StorageBox_IndustrialGrinder_parameters.hpp | 47222abfa33c8578f7964c3a2e913626b587df9c | [
"MIT"
] | permissive | git-Charlie/ARK-SDK | 75337684b11e7b9f668da1f15e8054052a3b600f | c38ca9925309516b2093ad8c3a70ed9489e1d573 | refs/heads/master | 2023-06-20T06:30:33.550123 | 2021-07-11T13:41:45 | 2021-07-11T13:41:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,039 | hpp | #pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_StorageBox_IndustrialGrinder_classes.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function StorageBox_IndustrialGrinder.StorageBox_IndustrialGrinder_C.GrindAllItems
struct AStorageBox_IndustrialGrinder_C_GrindAllItems_Params
{
class APlayerController* ForPC; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function StorageBox_IndustrialGrinder.StorageBox_IndustrialGrinder_C.IsValidForGrindingAll
struct AStorageBox_IndustrialGrinder_C_IsValidForGrindingAll_Params
{
bool IsValid; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function StorageBox_IndustrialGrinder.StorageBox_IndustrialGrinder_C.BPPreGetMultiUseEntries
struct AStorageBox_IndustrialGrinder_C_BPPreGetMultiUseEntries_Params
{
class APlayerController** ForPC; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function StorageBox_IndustrialGrinder.StorageBox_IndustrialGrinder_C.HasCraftingRequirementsGreaterThanOne
struct AStorageBox_IndustrialGrinder_C_HasCraftingRequirementsGreaterThanOne_Params
{
class UPrimalItem* InItem; // (Parm, ZeroConstructor, IsPlainOldData)
bool TRUE; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function StorageBox_IndustrialGrinder.StorageBox_IndustrialGrinder_C.GetReplacementItem
struct AStorageBox_IndustrialGrinder_C_GetReplacementItem_Params
{
class UClass* InItemClass; // (Parm, ZeroConstructor, IsPlainOldData)
class UClass* OutItemClass; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function StorageBox_IndustrialGrinder.StorageBox_IndustrialGrinder_C.IsValidGrindingItem
struct AStorageBox_IndustrialGrinder_C_IsValidGrindingItem_Params
{
class UPrimalItem* ItemToCheck; // (Parm, ZeroConstructor, IsPlainOldData)
bool IsValid; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function StorageBox_IndustrialGrinder.StorageBox_IndustrialGrinder_C.GrindItem
struct AStorageBox_IndustrialGrinder_C_GrindItem_Params
{
class UPrimalItem* ItemToGrind; // (Parm, ZeroConstructor, IsPlainOldData)
class AShooterPlayerController* ForPC; // (Parm, ZeroConstructor, IsPlainOldData)
bool grindStack; // (Parm, ZeroConstructor, IsPlainOldData)
bool MuteSound; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function StorageBox_IndustrialGrinder.StorageBox_IndustrialGrinder_C.BPServerHandleNetExecCommand
struct AStorageBox_IndustrialGrinder_C_BPServerHandleNetExecCommand_Params
{
class APlayerController** FromPC; // (Parm, ZeroConstructor, IsPlainOldData)
struct FName* CommandName; // (Parm, ZeroConstructor, IsPlainOldData)
struct FBPNetExecParams ExecParams; // (Parm, OutParm, ReferenceParm)
bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function StorageBox_IndustrialGrinder.StorageBox_IndustrialGrinder_C.BPClientDoMultiUse
struct AStorageBox_IndustrialGrinder_C_BPClientDoMultiUse_Params
{
class APlayerController** ForPC; // (Parm, ZeroConstructor, IsPlainOldData)
int* ClientUseIndex; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function StorageBox_IndustrialGrinder.StorageBox_IndustrialGrinder_C.BPGetMultiUseEntries
struct AStorageBox_IndustrialGrinder_C_BPGetMultiUseEntries_Params
{
class APlayerController** ForPC; // (Parm, ZeroConstructor, IsPlainOldData)
TArray<struct FMultiUseEntry> MultiUseEntries; // (Parm, OutParm, ZeroConstructor, ReferenceParm)
TArray<struct FMultiUseEntry> ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm)
};
// Function StorageBox_IndustrialGrinder.StorageBox_IndustrialGrinder_C.UserConstructionScript
struct AStorageBox_IndustrialGrinder_C_UserConstructionScript_Params
{
};
// Function StorageBox_IndustrialGrinder.StorageBox_IndustrialGrinder_C.ExecuteUbergraph_StorageBox_IndustrialGrinder
struct AStorageBox_IndustrialGrinder_C_ExecuteUbergraph_StorageBox_IndustrialGrinder_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"sergey.2bite@gmail.com"
] | sergey.2bite@gmail.com |
44abd5774a1e12f49162f70b97c47115d5056451 | 27c1cb57c1608b65639c6194dc945a440df25473 | /cg_exercise_04/cglib/lib/glm/glm/gtx/optimum_pow.inl | b4f12cb7b217e44b265a1b03d2d4698fbf517ebe | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"LicenseRef-scancode-happy-bunny"
] | permissive | brankyy/CG | 41c7de721ffdba2aefda48db823521fb0d409710 | 217960504e0c723b73dab664e6ca0ccf3aeeeec8 | refs/heads/master | 2020-04-05T00:36:27.888286 | 2019-01-06T22:02:49 | 2019-01-06T22:02:49 | 156,395,913 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 494 | inl | /// @ref gtx_optimum_pow
/// @file glm/gtx/optimum_pow.inl
namespace glm
{
template<typename genType>
GLM_FUNC_QUALIFIER genType pow2(genType const& x)
{
return x * x;
}
template<typename genType>
GLM_FUNC_QUALIFIER genType pow3(genType const& x)
{
return x * x * x;
}
template<typename genType>
GLM_FUNC_QUALIFIER genType pow4(genType const& x)
{
return (x * x) * (x * x);
}
}//namespace glm
// CG_REVISION 4ad3af6a3d282d95a68e54f217347edc0b637413
| [
"brankyy@gmail.com"
] | brankyy@gmail.com |
b632f39229a96dd9634c1624a0e1b3348c8ebd53 | 00fc56cab43c3eba4e3d6f724a2754466bf6312f | /mod5/project/src/calcBandI.cpp | c8157f0cf2a3801dc4d1cbd8964b6c42f92868a0 | [] | no_license | JohnJ-Led/cpp_based_projects | b6ec697f03172dc7bc41aac9ddaa341ca7367d31 | 3b9d990edab33dec9b25cc26516af7fb1a243553 | refs/heads/master | 2023-06-21T01:19:18.802716 | 2020-08-23T22:47:26 | 2020-08-23T22:47:26 | 289,593,078 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,177 | cpp | #include <iostream>
#include <iomanip>
#include <ios>
#include "calcBandI.h"
void calBandINoAddDeposits(double openAmt, double interestRate, int yearCount ){
//int monthCount = yearCount * 12;
double earnedInterest;
double totalEarned;
double totalInterest = 0;
int i;
int j;
double temp = openAmt;
for(j = 0; j < yearCount; ++j){
for(i = 0; i < 12; ++i){
earnedInterest = temp * ((interestRate/100)/12);
totalEarned = temp + earnedInterest;
totalInterest = totalInterest + earnedInterest;
temp = totalEarned;
}
std::cout << std::fixed << std::setprecision(2) << std::setw(6) << std::right << j + 1;
std::cout << std::setw(22 - std::to_string(int(totalEarned)).length() -1) << std::right << "$";
std::cout << totalEarned;
std::cout << std::setw(27 - std::to_string(int(totalInterest)).length()) << std::right << "$" << totalInterest << std::endl;
std::cout << std::endl;
temp = totalEarned;
totalInterest =0;
}
}
void calBandIAddDeposits(double openAmt, double depAmt, double interestRate, int yearCount){
//int monthCount = yearCount * 12;
double earnedInterest;
double totalEarned;
double totalInterest = 0;
int i;
int j;
double temp = openAmt;
for(j = 0; j < yearCount; ++j){
for(i = 0; i < 12; ++i){
earnedInterest = (temp + depAmt) * ((interestRate/100)/12);
totalEarned = temp + depAmt + earnedInterest;
//std::cout << earnedInterest << "<--Earned Interest" << std::endl;;
totalInterest = totalInterest + earnedInterest;
temp = totalEarned;
}
std::cout << std::fixed << std::setprecision(2) << std::setw(6) << std::right << j + 1;
std::cout << std::setw(22 - std::to_string(int(totalEarned)).length() -1) << std::right << "$";
std::cout << totalEarned;
std::cout << std::setw(27 - std::to_string(int(totalInterest)).length()) << std::right << "$" << totalInterest << std::endl;
std::cout << std::endl;
temp = totalEarned;
totalInterest =0;
}
} | [
"jacob.ledthebox@gmail.com"
] | jacob.ledthebox@gmail.com |
565a84d14033fc78aa3ba310f573d4e2a419a3dc | 5d01a2a16078b78fbb7380a6ee548fc87a80e333 | /ETS/Components/MM/EtsMmRisks/_IMmRvGrpAtomEvents_CP.H | 5ee06bb22200a034047d4cd4eef8b282f0c88c44 | [] | no_license | WilliamQf-AI/IVRMstandard | 2fd66ae6e81976d39705614cfab3dbfb4e8553c5 | 761bbdd0343012e7367ea111869bb6a9d8f043c0 | refs/heads/master | 2023-04-04T22:06:48.237586 | 2013-04-17T13:56:40 | 2013-04-17T13:56:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,947 | h |
// Wizard-generated connection point proxy class
// WARNING: This file may be regenerated by the wizard
#pragma once
template<class T>
class CProxy_IMmRvGrpAtomEvents :
public IConnectionPointImpl<T, &__uuidof(_IMmRvGrpAtomEvents)>
{
public:
HRESULT Fire_OnError( LONG ErrorCode, BSTR Symbol, BSTR ErrorDescription)
{
HRESULT hr = S_OK;
T * pThis = static_cast<T *>(this);
int cConnections = m_vec.GetSize();
for (int iConnection = 0; iConnection < cConnections; iConnection++)
{
pThis->Lock();
CComPtr<IUnknown> punkConnection = m_vec.GetAt(iConnection);
pThis->Unlock();
IDispatch * pConnection = static_cast<IDispatch *>(punkConnection.p);
if (pConnection)
{
CComVariant avarParams[3];
avarParams[2] = ErrorCode; avarParams[2].vt = VT_I4;
avarParams[1] = Symbol; avarParams[1].vt = VT_BSTR;
avarParams[0] = ErrorDescription; avarParams[0].vt = VT_BSTR;
CComVariant varResult;
DISPPARAMS params = { avarParams, NULL, 3, 0 };
hr = pConnection->Invoke(1, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, ¶ms, &varResult, NULL, NULL);
}
}
return hr;
}
HRESULT Fire_OnCalculation( LONG PositionNumber)
{
HRESULT hr = S_OK;
T * pThis = static_cast<T *>(this);
int cConnections = m_vec.GetSize();
for (int iConnection = 0; iConnection < cConnections; iConnection++)
{
pThis->Lock();
CComPtr<IUnknown> punkConnection = m_vec.GetAt(iConnection);
pThis->Unlock();
IDispatch * pConnection = static_cast<IDispatch *>(punkConnection.p);
if (pConnection)
{
CComVariant avarParams[1];
avarParams[0] = PositionNumber; avarParams[0].vt = VT_I4;
CComVariant varResult;
DISPPARAMS params = { avarParams, NULL, 1, 0 };
hr = pConnection->Invoke(2, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, ¶ms, &varResult, NULL, NULL);
}
}
return hr;
}
};
| [
"chuchev@egartech.com"
] | chuchev@egartech.com |
8607856aac8e3fbea08d2adf0c61c33ca35b8c5e | c9e3a15a9df784dd6e97334dd465e437726dd31c | /sources/prgm sol/traitement images/essai1.cpp | 938bed29ce03503ebcb8adc726f9b6aee216e503 | [] | no_license | thriller91/Cansat-SupOp | 75964e5484f88620f4b3468b5a8c526d2fcd9829 | 3fecc6433ff6a0d22d82ba238558d97c6c233fb4 | refs/heads/master | 2020-05-30T18:30:46.153984 | 2017-02-20T17:51:01 | 2017-02-20T17:51:01 | 2,622,802 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,469 | cpp | #include "highgui.h"
#include "cxcore.h"
#include <iostream>
#include <vector>
using namespace std;
using namespace cv;
int main( int argc, char** argv )
{
int rows,cols;
cv::Mat img3;
IplImage *img1,*img2,image;
std::vector<Mat> planes1,planes2;
if(argc<2){
std::cout<<"Usage: main <image-file-name>"<<std::endl;
exit(0);
}
img1=cvLoadImage(argv[1]);
img2=cvLoadImage(argv[2]);
/*if(!img1){
std::cout<<"Could not load image file:"<<argv[1])<<std::endl;
exit(0);
}
if(!img2){
std::cout<<"Could not load image file:"<<argv[2])<<std::endl;
exit(0);
}*/
split(img1,planes1);
split(img2,planes2);
cvReleaseImage(&img1);
cvReleaseImage(&img2);
cols=planes1[2].cols;
rows=planes1[2].rows;
if ((planes2[2].cols!=cols)|(planes2[2].rows!=rows)){
std::cout<<"Images should have the same size"<<std::endl;
}
img3=1.1*planes1[2]-1.09*planes2[2];
for (int k=0;k<3;k++)
{
planes1[k].release();
planes2[k].release();
}
/*img3=Mat(rows,cols,CV_8UC1);
MatIterator_<uchar> it1 = planes1[2].begin<uchar>(),it_end1 = planes1[2].end<uchar>();
MatIterator_<uchar> it2 = planes2[2].begin<uchar>(),it_end2 = planes2[2].end<uchar>();
MatIterator_<uchar> it3 = img3.begin<uchar>(),it_end3 = img3.end<uchar>();
for(; it1 != it_end1; ++it1)
{
if (*it1>*it2)
{
*it3=*it1-*it2;
}
else
{
*it3=0;
}
++it2;
++it3;
}*/
image=IplImage(img3);
//cvShowImage("test",&image);
cvSaveImage("test10039.jpg",&image);
}
| [
"zubair91@hotmail.fr"
] | zubair91@hotmail.fr |
4e22c4f7a4fe690c83ff43a530f220b787ae7782 | a932933fc4cb848e7b3484e90cf8a6d26216cb09 | /Module03/ex01/ScavTrap.cpp | 1d1c9018fe126b7ffb3e1d1c7316d32556c41aca | [] | no_license | robijnvh/CPP | 77c0d3e8db475c2fd0596fa2eda99e50bc8e6d59 | 52b0b958453df484b276c5306db6d6f3c7b62c99 | refs/heads/master | 2023-05-03T11:07:45.368207 | 2021-05-26T09:44:44 | 2021-05-26T09:44:44 | 283,137,046 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,013 | cpp | /* ************************************************************************** */
/* */
/* :::::::: */
/* ScavTrap.cpp :+: :+: */
/* +:+ */
/* By: rvan-hou <rvan-hou@student.42.fr> +#+ */
/* +#+ */
/* Created: 2020/08/01 17:38:06 by robijnvanho #+# #+# */
/* Updated: 2020/09/29 11:29:00 by rvan-hou ######## odam.nl */
/* */
/* ************************************************************************** */
#include "ScavTrap.hpp"
ScavTrap::ScavTrap(std::string name)
{
std::cout << "Hi! I'm ScavTrap " << name << "!" << std::endl;
this->_name = name;
this->hit_points = 100;
this->max_hit_points = 100;
this->energy_points = 50;
this->max_energy_points = 50;
this->level = 1;
this->melee_att_damage = 20;
this->ranged_att_damage = 15;
this->armour_damage_red = 3;
return ;
}
ScavTrap::ScavTrap()
{
std::cout << "Creating ScavTrap... Jo-88" << std::endl;
this->_name = "Jo-88";
this->hit_points = 100;
this->max_hit_points = 100;
this->energy_points = 50;
this->max_energy_points = 50;
this->level = 1;
this->melee_att_damage = 20;
this->ranged_att_damage = 15;
this->armour_damage_red = 3;
}
ScavTrap::ScavTrap(const ScavTrap& scavTrap)
{
*this = scavTrap;
}
ScavTrap::~ScavTrap()
{
std::cout << this->_name << " has excited the game..." << std::endl;
}
ScavTrap& ScavTrap::operator=(ScavTrap const &obj)
{
this->_name = obj._name;
this->hit_points = obj.hit_points;
this->max_hit_points = obj.max_hit_points;
this->energy_points = obj.energy_points;
this->max_energy_points = obj.max_energy_points;
this->level = obj.level;
this->melee_att_damage = obj.melee_att_damage;
this->ranged_att_damage = obj.ranged_att_damage;
this->armour_damage_red = obj.armour_damage_red;
return (*this);
}
void ScavTrap::meleeAttack(std::string const &target)
{
std::cout << "SCAV-TP " << this->_name << " attacks " << target \
<< " with melee, causing " << this->melee_att_damage \
<< " points of EXTREME damage !" << std::endl;
return ;
}
void ScavTrap::rangedAttack(std::string const & target)
{
std::cout << "SCAV-TP " << this->_name << " attacks " << target \
<< " at range, causing " << this->ranged_att_damage \
<< " points of EXTREME damage !" << std::endl;
return ;
}
void ScavTrap::takeDamage(unsigned int amount)
{
unsigned int damage;
if (amount <= armour_damage_red)
damage = 0;
else
damage = amount - armour_damage_red;
if (damage > hit_points)
{
hit_points = 0;
std::cout << _name << ">> Game over..." << std::endl;
}
else
{
hit_points -= damage;
std::cout << _name << " >> That's all?! Try again!" << std::endl;
std::cout << "Armour reduction: " << armour_damage_red << std::endl;
std::cout << "Damage: " << damage << std::endl;
std::cout << "Hit Points: " << hit_points << "|" \
<< max_hit_points << std::endl;
}
return ;
}
void ScavTrap::beRepaired(unsigned int amount)
{
if (energy_points < amount)
{
std::cout << _name << " >> Not enough energy..." << std::endl;
}
else
{
energy_points -= amount;
hit_points += amount;
std::cout << _name << " >> Busy repairing..." << std::endl;
std::cout << "Hit Points: " << hit_points << std::endl;
}
std::cout << "Energy Points: " << energy_points << std::endl;
return ;
}
void ScavTrap::challengeNewcomer(std::string const & target)
{
int index;
std::string challenge[] =
{
"Go for a nice relaxing walk",
"Go find another opponent, you'll never win",
"Give me 100+% during the eval",
"Just keep going",
"You're lucky, you're dismissed"
};
srand(time(NULL));
index = rand() % 5;
this->challenge = challenge[index];
std::cout << this->_name << ": Your challenge is: " << this->challenge \
<< "! Have fun " << target << std::endl;
return ;
}
std::string ScavTrap::getName()
{
return (this->_name);
}
unsigned int ScavTrap::getMeleeAttackDamage()
{
return (this->melee_att_damage);
}
unsigned int ScavTrap::getRangedAttackDamage()
{
return (this->ranged_att_damage);
}
unsigned int ScavTrap::getArmourDamageReduction()
{
return (this->armour_damage_red);
}
std::string ScavTrap::getChallenge(void)
{
return (this->challenge);
}
| [
"rvan-hou@f0r3s26.codam.nl"
] | rvan-hou@f0r3s26.codam.nl |
62ead62335fc6bfbbae4acea668c57793c0ea5f8 | f0ed8efeb82a6e2c3c23df405689a8e58e78e197 | /Offline-2/BookShop.cpp | 974fb40a00a66599299eebc73ccf13821f466adf | [] | no_license | sabahcsxgawd/LEVEL-1_TERM-2_CSE-108 | fbdd3d00d38e11e01066b6fde243e6c7521b1836 | 3d9c774beac3df5f40f51860d84f067887c80f72 | refs/heads/main | 2023-06-09T20:21:34.373087 | 2021-07-03T11:01:00 | 2021-07-03T11:01:00 | 351,215,656 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,296 | cpp | /*******************************Offline 2****************************************/
/* Implement the functions of the class BookShop below as per the instructions */
/* given inline the class definition. Make sure the output of the code in the */
/* main function matches the given sample output. You may add/delete codes in */
/* the main function during your testing. But before submission remove all your */
/* modifications from the main function and submit it as provided initially. */
/********************************************************************************/
#include<iostream>
#include<cstring>
#include<cmath>
#include "Book.cpp"
using namespace std;
class BookShop {
char name[100];
Book * books; //List of books in the shop
int size; //maximum number of books the shop can keep
int count; //tracks currently how many numbers in the shop
public:
void setName(char * name) {
/*Set the name of the bookshop to the given name*/
strcpy(this -> name, name);
}
BookShop() { //Default constructor
/*Initialize with size 5 and name to empty string ""*/
this -> size = 5;
strcpy(this -> name, "");
this -> count = 0;
this -> books = new Book[size];
}
BookShop(char * name, int size) { //Parameterized constructor
/*Initialize with the given name and size*/
this -> size = size;
strcpy(this -> name, name);
this -> count = 0;
this -> books = new Book[size];
}
BookShop(const BookShop & bs) { //Copy constructor
/*Write necessary code for the copy constructor*/
this -> count = bs.count;
this -> size = bs.size;
strcpy(this -> name, bs.name);
this -> books = new Book[bs.size];
for (int i = 0; i < bs.count; i++) {
this -> books[i] = bs.books[i];
}
}
~BookShop() { //Destructor
/*Free memory as applicable*/
delete[] books;
}
void addBook(Book b) {
/*Add book b to the end of the list*/
if (this -> count < size) {
this -> books[this -> count] = b;
this -> count++;
} else {
cout << "Books cannot be added\n";
}
}
void addBook(Book * ba, int count) {
/*Add the given array of books ba to the end of the list*/
if ((this -> count) + count < (this -> size)) {
for (int i = 0; i < count; i++) {
this -> addBook(ba[i]);
}
} else {
cout << "Books can not be added to the bookshop" << '\n';
}
}
Book getBookInfo(char * title) {
/*Return the **first** book that has the given title. Assume there is atleast one book in the list with the given title*/
for (int i = 0; i < (this -> count); i++) {
if (strcmp(title, this -> books[i].getTitle()) == 0) {
Book temp(this -> books[i]);
return temp;
}
}
}
void updateBookPrice(int isbn, int price) {
/*Update the price of the book with given isbn to the given price*/
for (int i = 0; i < (this -> count); i++) {
if (isbn == this -> books[i].getISBN()) {
this -> books[i].setPrice(price);
break;
}
}
}
void removeBook(int isbn) {
/*Remove the book with the given isbn from the list. After removing a book all the books below the removed book will be shifted up, i.e, there will be no hole in the list*/
int pos = -1;
for (int i = 0; i < (this -> count); i++) {
if (isbn == this -> books[i].getISBN()) {
pos = i;
break;
}
}
for (int i = pos; i < (this -> count) - 1; i++) {
this -> books[i] = (this -> books[i + 1]);
}
this -> count = (this -> count) - 1;
}
int totalPrice() {
/*Return the sum of the prices of all the books in the list*/
int tp = 0;
for (int i = 0; i < (this -> count); i++) {
tp += this -> books[i].getPrice();
}
return tp;
}
void print() {
/*Print the bookshop's name followed by information of all the books in the bookshop*/
cout << "Bookshop Name: " << this -> name << '\n';
for (int i = 0; i < (this -> count); i++) {
this -> books[i].print();
}
}
BookShop mergeShop(BookShop b) {
/* Return a new bookshop object that will contain all the books of this bookshop and the given bookshop b*/
/* Use the title **MergedShop** of the new bookshop */
BookShop notun("MergedShop", b.size + this -> size);
notun.count = b.count + this -> count;
for (int i = 0; i < this -> count; i++) {
notun.books[i] = this -> books[i];
}
for (int i = this -> count; i < notun.count; i++) {
notun.books[i] = b.books[i - (this -> count)];
}
return notun;
}
};
int main() {
BookShop bs1;
bs1.setName("Boimela");
Book b1(101, "Teach Yourself C++", 100);
Book b2(102, "Teach Yourself C", 200);
Book b3(103, "Java For Dummies", 300);
bs1.addBook(b1);
bs1.addBook(b2);
bs1.addBook(b3);
bs1.print();
/*Output:
Bookshop Name: Boimela
ISBN: 101, Title: Teach Yourself C++, Price: 100
ISBN: 102, Title: Teach Yourself C, Price: 200
ISBN: 103, Title: Java For Dummies, Price: 300
*/
cout << endl;
cout << "Total price of books: " << bs1.totalPrice() << endl;
/*Output:
Total price of books: 600
*/
cout << endl;
bs1.removeBook(102);
bs1.print();
/*Output:
Bookshop Name: Boimela
ISBN: 101, Title: Teach Yourself C++, Price: 100
ISBN: 103, Title: Java For Dummies, Price: 300
*/
cout << endl;
bs1.updateBookPrice(101, 500);
bs1.print();
/*Output:
Bookshop Name: Boimela
ISBN: 101, Title: Teach Yourself C++, Price: 500
ISBN: 103, Title: Java For Dummies, Price: 300
*/
cout << endl;
Book jfd = bs1.getBookInfo("Java For Dummies");
jfd.print();
/*Output:
ISBN: 103, Title: Java For Dummies, Price: 300
*/
cout << endl;
Book ba[3] = {
Book(201, "Operating Systems", 1000),
Book(202, "Compilers", 2000),
Book(203, "Computer Networks", 1500)
};
BookShop bs2("Puthighor", 5);
bs2.addBook(ba, 3);
bs2.print();
/*Output:
Bookshop Name: Puthighor
ISBN: 201, Title: Operating Systems, Price: 1000
ISBN: 202, Title: Compilers, Price: 2000
ISBN: 203, Title: Computer Networks, Price: 1500
*/
cout << endl;
BookShop bs3 = bs1.mergeShop(bs2);
bs3.setName("Mullick Brothers");
bs3.print();
/*Output:
Bookshop Name: Mullick Brothers
ISBN: 101, Title: Teach Yourself C++, Price: 500
ISBN: 103, Title: Java For Dummies, Price: 300
ISBN: 201, Title: Operating Systems, Price: 1000
ISBN: 202, Title: Compilers, Price: 2000
ISBN: 203, Title: Computer Networks, Price: 1500
*/
}
| [
"noreply@github.com"
] | sabahcsxgawd.noreply@github.com |
266edb5921ee1e456427f24f2764e57d9f09c646 | 90d2a91fd4931c6e0c8aca344c11dc43d7c00ebc | /3rd-party/yaml-cpp/src/exceptions.cpp | f298e54aa00e8ec053c977c7929baaed8fb2985a | [
"MIT",
"OML"
] | permissive | NavInfoNC/ncserver | 7fc412f967f9ccf15d2b6fc34513e6be57581d75 | 6713e6b78ea21d03d144652b48afe8b46db1e63c | refs/heads/master | 2022-01-02T05:25:40.615189 | 2021-12-29T10:03:41 | 2021-12-29T10:03:41 | 196,983,258 | 15 | 9 | MIT | 2021-12-02T09:42:49 | 2019-07-15T11:12:00 | C++ | UTF-8 | C++ | false | false | 2,147 | cpp | /*
Copyright (c) 2008-2015 Jesse Beder.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "yaml-cpp/exceptions.h"
// This is here for compatibility with older versions of Visual Studio
// which don't support noexcept
#if defined(_MSC_VER) && _MSC_VER < 1900
#define YAML_CPP_NOEXCEPT _NOEXCEPT
#else
#define YAML_CPP_NOEXCEPT noexcept
#endif
namespace YAML {
// These destructors are defined out-of-line so the vtable is only emitted once.
Exception::~Exception() YAML_CPP_NOEXCEPT {}
ParserException::~ParserException() YAML_CPP_NOEXCEPT {}
RepresentationException::~RepresentationException() YAML_CPP_NOEXCEPT {}
InvalidScalar::~InvalidScalar() YAML_CPP_NOEXCEPT {}
KeyNotFound::~KeyNotFound() YAML_CPP_NOEXCEPT {}
InvalidNode::~InvalidNode() YAML_CPP_NOEXCEPT {}
BadConversion::~BadConversion() YAML_CPP_NOEXCEPT {}
BadDereference::~BadDereference() YAML_CPP_NOEXCEPT {}
BadSubscript::~BadSubscript() YAML_CPP_NOEXCEPT {}
BadPushback::~BadPushback() YAML_CPP_NOEXCEPT {}
BadInsert::~BadInsert() YAML_CPP_NOEXCEPT {}
EmitterException::~EmitterException() YAML_CPP_NOEXCEPT {}
BadFile::~BadFile() YAML_CPP_NOEXCEPT {}
}
#undef YAML_CPP_NOEXCEPT
| [
"zhangjs@mailbar.com"
] | zhangjs@mailbar.com |
8f08e50e077817fcbdbce65db8da26f5867dc267 | d32b701f6ccd833293c8571b5411fa55a57b0cb9 | /src/orient_module.cpp | bd53a3b6f28475f71e0a511d8913f6caee31f5e2 | [] | no_license | mitchellgordon95/GraphicsFromScratch | d0108795d50eb500a3d166602f761cad102e4ea7 | 30b678f713597a95370411eaf48450737a3d2399 | refs/heads/master | 2020-05-29T21:14:59.508395 | 2015-05-05T05:14:45 | 2015-05-05T05:14:45 | 35,078,624 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 952 | cpp | #include "orient_module.h"
#include "cli_pipeline.h"
#include <armadillo>
CLI_Orient::~CLI_Orient()
{
}
using namespace CLI_Pipeline;
using namespace arma;
void CLI_Orient::execute(std::vector<char *> ¶ms)
{
float a = CLI_Module::parseNumericalArg(params[0]);
float b = CLI_Module::parseNumericalArg(params[1]);
float c = CLI_Module::parseNumericalArg(params[2]);
float d = CLI_Module::parseNumericalArg(params[3]);
float e = CLI_Module::parseNumericalArg(params[4]);
float f = CLI_Module::parseNumericalArg(params[5]);
float g = CLI_Module::parseNumericalArg(params[6]);
float h = CLI_Module::parseNumericalArg(params[7]);
float i = CLI_Module::parseNumericalArg(params[8]);
fmat trans = eye<fmat>(4,4);
fmat smaller;
smaller << a << b << c
<< d << e << f
<< g << h << i;
trans.submat(0,0,2,2) = smaller;
fmat current = transform_stack.back();
transform_stack.pop_back();
transform_stack.push_back(current * trans);
}
| [
"mitchell.gordon95@gmail.com"
] | mitchell.gordon95@gmail.com |
da25ac7845cd82a3613baceebe9a0d02e08766fe | 7619eda583a979c6078c38d57b0fbeaaff44cc0a | /Pods/MMKVCore/Core/MemoryFile.cpp | e581dcb95f178bff38f8561b9b4e68d22a920f83 | [
"BSD-3-Clause",
"Zlib",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-ssleay-windows",
"OpenSSL",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | mohsinalimat/WeChatSwift | f6ca421a4222b14016d2fe67dccf933788c287d0 | 574d0fd2b95d5fb79d978b9cd8652570fd42b3e8 | refs/heads/master | 2021-11-22T23:08:25.764547 | 2021-10-08T08:47:48 | 2021-10-08T08:47:48 | 217,524,779 | 1 | 0 | MIT | 2019-10-25T12:03:40 | 2019-10-25T12:03:40 | null | UTF-8 | C++ | false | false | 8,309 | cpp | /*
* Tencent is pleased to support the open source community by making
* MMKV available.
*
* Copyright (C) 2018 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.
*/
#include "MemoryFile.h"
#ifndef MMKV_WIN32
# include "InterProcessLock.h"
# include "MMBuffer.h"
# include "MMKVLog.h"
# include "ScopedLock.hpp"
# include <cerrno>
# include <fcntl.h>
# include <sys/mman.h>
# include <sys/stat.h>
# include <unistd.h>
using namespace std;
namespace mmkv {
static bool getFileSize(int fd, size_t &size);
# ifdef MMKV_ANDROID
extern size_t ASharedMemory_getSize(int fd);
# else
MemoryFile::MemoryFile(const MMKVPath_t &path) : m_name(path), m_fd(-1), m_ptr(nullptr), m_size(0) {
reloadFromFile();
}
# endif // MMKV_ANDROID
# ifdef MMKV_IOS
void tryResetFileProtection(const string &path);
# endif
bool MemoryFile::truncate(size_t size) {
if (m_fd < 0) {
return false;
}
if (size == m_size) {
return true;
}
# ifdef MMKV_ANDROID
if (m_fileType == MMFILE_TYPE_ASHMEM) {
if (size > m_size) {
MMKVError("ashmem %s reach size limit:%zu, consider configure with larger size", m_name.c_str(), m_size);
} else {
MMKVInfo("no way to trim ashmem %s from %zu to smaller size %zu", m_name.c_str(), m_size, size);
}
return false;
}
# endif // MMKV_ANDROID
auto oldSize = m_size;
m_size = size;
// round up to (n * pagesize)
if (m_size < DEFAULT_MMAP_SIZE || (m_size % DEFAULT_MMAP_SIZE != 0)) {
m_size = ((m_size / DEFAULT_MMAP_SIZE) + 1) * DEFAULT_MMAP_SIZE;
}
if (::ftruncate(m_fd, static_cast<off_t>(m_size)) != 0) {
MMKVError("fail to truncate [%s] to size %zu, %s", m_name.c_str(), m_size, strerror(errno));
m_size = oldSize;
return false;
}
if (m_size > oldSize) {
if (!zeroFillFile(m_fd, oldSize, m_size - oldSize)) {
MMKVError("fail to zeroFile [%s] to size %zu, %s", m_name.c_str(), m_size, strerror(errno));
m_size = oldSize;
return false;
}
}
if (m_ptr) {
if (munmap(m_ptr, oldSize) != 0) {
MMKVError("fail to munmap [%s], %s", m_name.c_str(), strerror(errno));
}
}
auto ret = mmap();
if (!ret) {
doCleanMemoryCache(true);
}
return ret;
}
bool MemoryFile::msync(SyncFlag syncFlag) {
if (m_ptr) {
auto ret = ::msync(m_ptr, m_size, syncFlag ? MS_SYNC : MS_ASYNC);
if (ret == 0) {
return true;
}
MMKVError("fail to msync [%s], %s", m_name.c_str(), strerror(errno));
}
return false;
}
bool MemoryFile::mmap() {
m_ptr = (char *) ::mmap(m_ptr, m_size, PROT_READ | PROT_WRITE, MAP_SHARED, m_fd, 0);
if (m_ptr == MAP_FAILED) {
MMKVError("fail to mmap [%s], %s", m_name.c_str(), strerror(errno));
m_ptr = nullptr;
return false;
}
return true;
}
void MemoryFile::reloadFromFile() {
# ifdef MMKV_ANDROID
if (m_fileType == MMFILE_TYPE_ASHMEM) {
return;
}
# endif
if (isFileValid()) {
MMKVWarning("calling reloadFromFile while the cache [%s] is still valid", m_name.c_str());
MMKV_ASSERT(0);
clearMemoryCache();
}
m_fd = open(m_name.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, S_IRWXU);
if (m_fd < 0) {
MMKVError("fail to open:%s, %s", m_name.c_str(), strerror(errno));
} else {
FileLock fileLock(m_fd);
InterProcessLock lock(&fileLock, ExclusiveLockType);
SCOPED_LOCK(&lock);
mmkv::getFileSize(m_fd, m_size);
// round up to (n * pagesize)
if (m_size < DEFAULT_MMAP_SIZE || (m_size % DEFAULT_MMAP_SIZE != 0)) {
size_t roundSize = ((m_size / DEFAULT_MMAP_SIZE) + 1) * DEFAULT_MMAP_SIZE;
truncate(roundSize);
} else {
auto ret = mmap();
if (!ret) {
doCleanMemoryCache(true);
}
}
# ifdef MMKV_IOS
tryResetFileProtection(m_name);
# endif
}
}
void MemoryFile::doCleanMemoryCache(bool forceClean) {
# ifdef MMKV_ANDROID
if (m_fileType == MMFILE_TYPE_ASHMEM && !forceClean) {
return;
}
# endif
if (m_ptr && m_ptr != MAP_FAILED) {
if (munmap(m_ptr, m_size) != 0) {
MMKVError("fail to munmap [%s], %s", m_name.c_str(), strerror(errno));
}
}
m_ptr = nullptr;
if (m_fd >= 0) {
if (::close(m_fd) != 0) {
MMKVError("fail to close [%s], %s", m_name.c_str(), strerror(errno));
}
}
m_fd = -1;
m_size = 0;
}
size_t MemoryFile::getActualFileSize() {
# ifdef MMKV_ANDROID
if (m_fileType == MMFILE_TYPE_ASHMEM) {
return ASharedMemory_getSize(m_fd);
}
# endif
size_t size = 0;
mmkv::getFileSize(m_fd, size);
return size;
}
bool isFileExist(const string &nsFilePath) {
if (nsFilePath.empty()) {
return false;
}
struct stat temp = {};
return lstat(nsFilePath.c_str(), &temp) == 0;
}
extern bool mkPath(const MMKVPath_t &str) {
char *path = strdup(str.c_str());
struct stat sb = {};
bool done = false;
char *slash = path;
while (!done) {
slash += strspn(slash, "/");
slash += strcspn(slash, "/");
done = (*slash == '\0');
*slash = '\0';
if (stat(path, &sb) != 0) {
if (errno != ENOENT || mkdir(path, 0777) != 0) {
MMKVWarning("%s : %s", path, strerror(errno));
free(path);
return false;
}
} else if (!S_ISDIR(sb.st_mode)) {
MMKVWarning("%s: %s", path, strerror(ENOTDIR));
free(path);
return false;
}
*slash = '/';
}
free(path);
return true;
}
MMBuffer *readWholeFile(const MMKVPath_t &path) {
MMBuffer *buffer = nullptr;
int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
if (fd >= 0) {
auto fileLength = lseek(fd, 0, SEEK_END);
if (fileLength > 0) {
buffer = new MMBuffer(static_cast<size_t>(fileLength));
lseek(fd, 0, SEEK_SET);
auto readSize = read(fd, buffer->getPtr(), static_cast<size_t>(fileLength));
if (readSize != -1) {
//fileSize = readSize;
} else {
MMKVWarning("fail to read %s: %s", path.c_str(), strerror(errno));
delete buffer;
buffer = nullptr;
}
}
close(fd);
} else {
MMKVWarning("fail to open %s: %s", path.c_str(), strerror(errno));
}
return buffer;
}
bool zeroFillFile(int fd, size_t startPos, size_t size) {
if (fd < 0) {
return false;
}
if (lseek(fd, static_cast<off_t>(startPos), SEEK_SET) < 0) {
MMKVError("fail to lseek fd[%d], error:%s", fd, strerror(errno));
return false;
}
static const char zeros[4096] = {};
while (size >= sizeof(zeros)) {
if (write(fd, zeros, sizeof(zeros)) < 0) {
MMKVError("fail to write fd[%d], error:%s", fd, strerror(errno));
return false;
}
size -= sizeof(zeros);
}
if (size > 0) {
if (write(fd, zeros, size) < 0) {
MMKVError("fail to write fd[%d], error:%s", fd, strerror(errno));
return false;
}
}
return true;
}
static bool getFileSize(int fd, size_t &size) {
struct stat st = {};
if (fstat(fd, &st) != -1) {
size = (size_t) st.st_size;
return true;
}
return false;
}
size_t getPageSize() {
return static_cast<size_t>(getpagesize());
}
} // namespace mmkv
#endif // MMKV_WIN32
| [
"xshf87@126.com"
] | xshf87@126.com |
ddbbcaa30874c15f8ec4f8fb4ee8f4fdccda485b | e1c054f36ea1eb0b2205d1dcfba2fc971731cb23 | /doublesetting.h | eab52bd00e4e718e93547475f0d95b94054454cd | [] | no_license | 62ocean/Qlink | fbc0c9ac69982786977e6e12e984d0db757aff64 | 56c9ea0013669c1061f8eb26aef86860d9cf8bae | refs/heads/master | 2023-08-25T19:43:13.509283 | 2021-09-17T05:54:08 | 2021-09-17T05:54:08 | 407,416,557 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 491 | h | #ifndef DOUBLESETTING_H
#define DOUBLESETTING_H
#include <QDialog>
#include <QButtonGroup>
namespace Ui {
class DoubleSetting;
}
class DoubleSetting : public QDialog
{
Q_OBJECT
public:
explicit DoubleSetting(QWidget *parent = nullptr);
~DoubleSetting();
private slots:
void startGame();
void cancel();
private:
Ui::DoubleSetting *ui;
QButtonGroup *bgDensity, *bgCharacter1, *bgCharacter2;
QButtonGroup *bg1,*bg2,*bg3,*bg4;
};
#endif // DOUBLESETTING_H
| [
"ocean62yjl@gmail.com"
] | ocean62yjl@gmail.com |
3aeebfc2aceb1adbf1a5481edbe7afed3b715f42 | b7f3edb5b7c62174bed808079c3b21fb9ea51d52 | /chromeos/components/camera_app_ui/url_constants.cc | 96894c1d8bab757e4aa201eee81af9010c9cbb84 | [
"BSD-3-Clause"
] | permissive | otcshare/chromium-src | 26a7372773b53b236784c51677c566dc0ad839e4 | 64bee65c921db7e78e25d08f1e98da2668b57be5 | refs/heads/webml | 2023-03-21T03:20:15.377034 | 2020-11-16T01:40:14 | 2020-11-16T01:40:14 | 209,262,645 | 18 | 21 | BSD-3-Clause | 2023-03-23T06:20:07 | 2019-09-18T08:52:07 | null | UTF-8 | C++ | false | false | 389 | cc | // Copyright 2020 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 "chromeos/components/camera_app_ui/url_constants.h"
namespace chromeos {
const char kChromeUICameraAppHost[] = "camera-app";
const char kChromeUICameraAppURL[] = "chrome://camera-app/";
} // namespace chromeos
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
777e87fe8fb1dccae1690c003f971c2ec9379754 | f153b04464e0bbe7c2db57f7b6c2d64d87f8953b | /leetcode/NumberOfBoomerangs.cpp | 13b52ebaee4fb4f7bb3bc88104b59f47c5527bbb | [] | no_license | alvas/ms_interview_100 | 82f4f7222db775c68b035dc616d812c63f3127a7 | 8587116a3c4227f71783e7dac42517b6561d17b0 | refs/heads/master | 2022-03-18T10:48:46.834899 | 2022-02-24T04:10:05 | 2022-02-24T04:10:05 | 16,854,684 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 10,617 | cpp | #include <iostream>
#include <map>
#include <unordered_map>
#include <vector>
using namespace std;
class Solution {
public:
int numberOfBoomerangs(vector<pair<int, int>>& points) {
int res = 0;
int sz = points.size();
for (int i = 0; i < sz; ++i) {
unordered_map<long, int> m;
for (int j = 0; j < sz; ++j) {
if (i == j) {
continue;
}
// for each new pair with distance, it could form 2 new boomerang
// with each exising of m[dis] pair with distance.
long dis = distance(points[i], points[j]);
res += m[dis] * 2;
m[dis]++;
}
}
return res;
}
long distance(pair<int, int> &p1, pair<int, int> &p2) {
int d1 = p1.first - p2.first;
int d2 = p1.second - p2.second;
return d1 * d1 + d2 * d2;
}
int numberOfBoomerangs_slow(vector<pair<int, int>>& points) {
int sz = points.size();
int res = 0;
vector<vector<long>> v(500, vector<long>(500, LONG_MIN));
//map<pair<int, int>, long> m;
for (int i = 0; i < sz; ++i) {
for (int j = 0; j < sz; ++j) {
if (i == j) {
continue;
}
long len1 = 0;
//pair<int, int> p1(i, j), p2(j, i);
//auto itr = m.find(p1), itr2 = m.find(p2);
//if (itr != m.end()) {
//len1 = itr->second;
//}
//else if (itr2 != m.end()) {
//len1 = itr2->second;
//}
//else {
//long a = points[i].first - points[j].first, b = points[i].second - points[j].second;
//len1 = a * a + b * b;
//m.insert(make_pair(p1, len1));
//m.insert(make_pair(p2, len1));
//}
if (v[i][j] != LONG_MIN) {
len1 = v[i][j];
}
else if (v[j][i] != LONG_MIN) {
len1 = v[j][i];
}
else {
long a = points[i].first - points[j].first, b = points[i].second - points[j].second;
len1 = a * a + b * b;
v[i][j] = len1;
v[j][i] = len1;
}
for (int k = 0; k < sz; ++k) {
if (k == i || k == j) {
continue;
}
long len2 = 0;
//pair<int, int> p3(i, k), p4(k, i);
//itr = m.find(p3), itr2 = m.find(p4);
//if (itr != m.end()) {
//len2 = itr->second;
//}
//else if (itr2 != m.end()) {
//len2 = itr2->second;
//}
//else {
//long c = points[i].first - points[k].first, d = points[i].second - points[k].second;
//len2 = c * c + d * d;
//m.insert(make_pair(p3, len2));
//m.insert(make_pair(p4, len2));
//}
if (v[i][k] != LONG_MIN) {
len2 = v[i][k];
}
else if (v[k][i] != LONG_MIN) {
len2 = v[k][i];
}
else {
long c = points[i].first - points[k].first, d = points[i].second - points[k].second;
len2 = c * c + d * d;
v[i][k] = len2;
v[k][i] = len2;
}
if (len1 == len2)
{
res++;
}
}
}
}
return res;
}
};
int main() {
Solution sln;
//vector<pair<int, int>> points = {{0, 0}, {1, 0}, {2, 0}};
//vector<pair<int, int>> points = {{1, 1}, {2, 2}, {3, 3}};
//vector<pair<int, int>> points = {{0, 0}, {1, 0}, {-1, 0}, {0, 1}, {0, -1}};
//vector<pair<int, int>> points = {{1, 8}, {7, 9}, {2, 0}, {2, 3}, {7, 5}, {9, 2}, {2, 8}, {9, 7}, {3, 6}, {1, 2}};
vector<pair<int, int>> points = {{3327,-549},{9196,-8118},{7610,-9506},{5098,8392},{8582,7953},{1053,5802},{3847,2652},{7654,8355},{1614,-9409},{9986,5538},{4660,2944},{4528,-9512},{7483,-1455},{3422,-3966},{2037,-4456},{5107,-4635},{4996,655},{7247,2606},{1149,8697},{7350,6083},{3002,8403},{8238,6850},{1055,5892},{5205,9021},{2835,5191},{911,-2505},{4488,-4561},{7983,-1677},{336,-2243},{4358,-1274},{3302,9465},{4091,-5350},{120,7690},{3608,7622},{6388,-9042},{57,-610},{9361,8295},{6240,-3232},{540,7797},{2141,-6625},{9341,3053},{7223,3829},{4844,1558},{2152,-8467},{9316,6510},{259,-1030},{2327,-5650},{9972,8800},{2040,-6420},{2774,4780},{4538,-7169},{4171,-6101},{7479,-3237},{7019,-1981},{4561,-4488},{7746,254},{4917,4969},{4083,-238},{6528,-7413},{1295,-7804},{5450,-8446},{1166,-5871},{2256,-8862},{2929,-5704},{4718,2055},{5429,-4392},{4887,9600},{9507,-1282},{2715,2878},{6737,-6372},{8390,-9165},{3882,3308},{5805,4317},{9422,8685},{3257,-2931},{881,-1293},{8623,-1601},{2836,879},{5889,2118},{1527,607},{4173,-3044},{6215,5412},{2908,-7926},{4130,-8024},{1304,7219},{1956,-3954},{8055,5839},{5706,212},{6508,5128},{8897,9765},{2197,-3870},{8472,-2828},{4529,7661},{4403,-9582},{6131,-7717},{7377,-3344},{5591,9944},{2069,-5148},{8370,-7449},{6828,-3974},{6123,-1216},{2072,530},{975,-2221},{7094,-2516},{9259,-4009},{7249,7809},{8473,2074},{4981,-6998},{9735,5737},{9772,5866},{8020,-6499},{8874,-6389},{3445,-9057},{4815,8167},{9847,1643},{4193,2322},{6780,2617},{9204,4107},{396,6298},{1591,6008},{2289,-4807},{3817,762},{7267,5150},{116,-6646},{887,-3760},{5572,-4741},{9741,4446},{5223,-462},{1742,38},{7705,1589},{1682,-1750},{263,4814},{867,9467},{8921,7616},{5765,-3135},{3624,4406},{2058,-2559},{1520,-675},{2591,-2012},{2679,-169},{4228,-1749},{5090,-6031},{2697,-9687},{9859,791},{352,3916},{8732,-1614},{2166,8995},{3200,9385},{4814,-1527},{7001,579},{5338,-3023},{1337,-2604},{4418,-7143},{3073,3362},{845,-7896},{3193,-8575},{6707,4635},{1746,-595},{4949,1605},{6548,-8347},{1873,5281},{39,-5961},{4276,-409},{9777,-909},{8064,3130},{6022,-245},{108,7360},{7151,4526},{6569,-3423},{4240,-2585},{8681,-2567},{5192,5389},{2069,-3061},{1146,3370},{4896,7694},{5023,6770},{2975,-8586},{7161,-6396},{1005,6938},{2695,-4579},{69,-4931},{5176,177},{2429,-1320},{1055,8999},{5257,-4704},{2766,-6062},{9081,-2042},{5679,-2498},{1249,6825},{7224,-3854},{872,2247},{2916,-6153},{3661,-9923},{7451,-8982},{7016,6498},{6440,-6563},{1568,-8384},{9966,-9651},{296,1021},{9348,-8095},{2669,8466},{2196,-8249},{2777,7875},{5605,4026},{1053,-7170},{172,-8075},{1429,-6912},{5772,-8557},{9518,-424},{2461,2886},{2426,-1099},{6323,-6006},{6870,-3711},{696,3518},{3662,6396},{5424,-3668},{4863,7620},{4435,7640},{1847,-3608},{8018,-7100},{9222,-5457},{4825,7004},{3983,-3050},{8447,-6499},{2878,-9092},{6387,5304},{6162,-938},{5651,3032},{5351,6347},{2902,-4634},{2743,8326},{8050,-6042},{2298,-1163},{7950,-9502},{5229,-4031},{3398,-9196},{512,-5424},{7808,847},{7878,6255},{4349,7108},{7163,736},{8764,9677},{6151,-5585},{2709,-2146},{7114,5612},{3220,-3790},{290,-8730},{168,8941},{107,-5529},{9439,-8311},{440,9189},{2493,7304},{117,6653},{8151,-5653},{2908,8852},{1455,-3577},{5941,-3428},{6101,-7908},{7339,5162},{9946,-5546},{7126,9519},{7016,3769},{789,7184},{2710,-2751},{1655,-1499},{5290,-1553},{4042,-2217},{2103,-9488},{788,-3393},{1211,3696},{1811,9019},{6471,-2248},{5591,8924},{6196,2930},{4087,6143},{3736,7565},{5662,-9248},{1334,2803},{4289,-9604},{6404,2296},{8897,-8306},{7096,-708},{5829,9199},{6156,-3383},{2158,-2633},{6665,-9678},{6386,3137},{8074,1977},{2061,4271},{4908,-7500},{6766,4996},{66,8780},{5749,1400},{7935,38},{1797,-5660},{2334,7046},{2386,9430},{2690,-1784},{4982,-1154},{1185,3492},{6214,-2149},{3814,8952},{7340,8241},{930,-4247},{8864,2190},{8254,5630},{7186,-5328},{762,9287},{6072,8697},{9325,-5779},{9389,1660},{7620,-8224},{7442,-9690},{9992,-7576},{5509,7529},{2269,8075},{5380,-3917},{7027,-7280},{4324,-5691},{8474,3188},{6499,3080},{5170,-9962},{7752,5932},{9325,176},{982,-1349},{4398,371},{6663,-1630},{2147,-9543},{5032,8491},{9234,541},{6021,1503},{8616,7753},{3938,-8004},{6826,8263},{6305,-8348},{7803,9157},{4732,-674},{9195,-1164},{5258,8520},{9012,2592},{3523,-238},{2964,6538},{8132,1463},{3348,-6835},{6307,2582},{58,-7672},{437,5027},{6433,4375},{7023,3259},{8990,-6672},{4911,3146},{2485,-4005},{2472,8032},{4831,-5918},{2905,196},{6675,6428},{9958,9639},{9319,4443},{7454,-7333},{3960,3761},{1601,-9630},{2441,2038},{5397,-1125},{6413,2420},{8486,1756},{2101,3398},{4902,938},{5745,-2626},{5323,-3071},{1456,8228},{7125,-1869},{1008,3435},{4122,6679},{4230,1577},{9346,8190},{1690,947},{4913,4132},{9337,310},{3007,-4249},{9083,-8507},{7507,-2464},{1243,-7591},{4826,-3011},{6135,-9851},{3918,7591},{8377,-2605},{5723,-4262},{830,-3803},{2417,-8587},{7774,8116},{5955,9465},{5415,868},{9949,-5247},{1179,2956},{6856,6614},{801,-9285},{4150,8397},{9476,8976},{1738,-4389},{9126,2008},{3202,3855},{9403,-4723},{9593,6585},{1475,-7989},{7998,-4399},{127,306},{1418,-4458},{1174,1367},{6647,-7647},{4323,3503},{8967,1477},{4218,9469},{6226,3694},{8446,-2036},{9305,3924},{9972,8860},{7779,5727},{4137,-6275},{8664,1964},{5736,-6985},{7566,-7785},{3321,8984},{4109,4495},{352,757},{3201,1027},{4260,-1480},{8856,4831},{7990,-4918},{8525,-7212},{3046,-5817},{6712,-630},{3043,-5509},{1449,-6468},{8216,-3534},{5497,304},{9481,3063},{8871,9154},{8399,2981},{1,8751},{90,-6798},{6131,-9298},{8075,-5013},{5533,6065},{70,-9589},{5205,9468},{946,1917},{5191,-6011},{2760,-7008},{3873,7329},{9458,9370},{7633,5291},{8785,2857},{797,3537},{2190,-9201},{2288,-7720},{353,4771},{9334,-1572},{9759,1220},{845,-3819},{7983,6050},{2001,-1071},{4319,-2808},{9270,7080},{6537,3143},{4409,2347},{8866,8394},{7639,4003},{7603,4788},{7540,-207},{5587,6181},{8425,5941},{952,-5888},{721,-2937},{5332,-8433},{3244,-6685},{3969,5246},{2244,8289},{8790,-8486},{1721,-4673},{1009,-3870},{7675,9875},{876,-8334},{231,-1520},{6454,7771},{4625,2042},{304,9403},{4335,-8743},{3515,-4944},{4672,8847},{2975,7917},{8514,6945},{3163,758},{1586,1953},{8624,-6693},{7281,9633},{5789,1308},{5861,-6983},{2974,-3908},{7849,-572},{215,-7525}};
cout << sln.numberOfBoomerangs(points) << endl;
return 0;
}
| [
"qingyun.oracle@gmail.com"
] | qingyun.oracle@gmail.com |
dd5ee657c673eb566f9cdc8dd4de35f69c1d6c29 | 025b6f6daa885a43705876b0401b32d1713ca7ad | /roamfree/ROAMestimation/include/ROAMestimation/SpatialIndex/SpatialIndex.h | 33ad1bee41da895dd52f348db180b1dc167d14ac | [] | no_license | AIRLab-POLIMI/ROAMFREE | dcd1c3e1ff7de7905e4bad2a018178d1a8d6263a | a0f875a4e30455758b33b8dde2b13bdddd7302e6 | refs/heads/master | 2023-03-10T02:31:39.737671 | 2022-09-23T08:53:24 | 2022-09-23T08:53:24 | 39,181,027 | 33 | 12 | null | null | null | null | UTF-8 | C++ | false | false | 2,415 | h | /*
Copyright (c) 2013-2016 Politecnico di Milano.
All rights reserved. This program and the accompanying materials
are made available under the terms of the GNU Lesser Public License v3
which accompanies this distribution, and is available at
https://www.gnu.org/licenses/lgpl.html
Contributors:
Davide A. Cucci (davide.cucci@epfl.ch)
*/
/*
* SpatialIndex.h
*
* Created on: Mar 20, 2014
* Author: davide
*/
#ifndef SPATIALINDEX_H_
#define SPATIALINDEX_H_
#include "types.h"
namespace ROAMestimation {
class SpatialIndex {
public:
/**
* \brief builds a spatial index
*
* @param poses the set of poses among which there are the ones which have to go into the spatial index
*
* NOTES:
*
* how to test if a vertex has to be kept into the spatial index or not
*
* PoseVertex *v; // a pose vertex
* PoseVertexWrapper w(v);
* if (w.getKeepSpatialIndex() == true) ...
*
* how to get the {x, y, z, qw, qx, qy, qz} estimate of a pose vertex
*
* PoseVertex *v;
* const Eigen::Vector &x = v->estimate();
* if (std::sqrt( x(0)*x(0) + x(1)*x(1) ) < d ) ...
*
*/
void build(const PoseMap &poses);
/**
* \brief performs a rande search query to the spatial index
*
* by means of the provided output iterator, this method fills a collection of the PoseVertex which are
* within d distance from x, with respect to a certain metric. The metric is to be defined in sublcasses.
*
* @param x a vector of 7 elements {x, y, z, qw, qx, qy, qz} encoding pose and orientation of the sample
* @param d max distance
* @param outIter the output_iterator by means of which this methods fills the output collection
*
* NOTES:
*
* how to add a PoseVertex to the output collection
*
* PoseVertex *toadd;
* OutputIterator outIter
* *(outIter++) = toadd;
*/
template <typename OutputIterator>
void rangeSearch(const Eigen::VectorXd &x1, double d, OutputIterator outIter) {
assert(x1.size() == 7); // people has to give me pose samples
for (PoseMap::const_iterator it = _index.begin(); it !=_index.end(); ++it) {
const Eigen::VectorXd &x2 = it->second->estimate();
if (euclidean2DDistance(x1,x2) < d) {
*(outIter++) = it->second;
}
}
}
protected:
PoseMap _index;
double euclidean2DDistance(const Eigen::VectorXd &x1,
const Eigen::VectorXd &x2) const ;
};
} /* namespace ROAMestimation */
#endif /* SPATIALINDEX_H_ */
| [
"davide.cucci@epfl.ch"
] | davide.cucci@epfl.ch |
1a14cdf902e9c1fdb0f9ce8ef307201dc843e365 | 2b31b6a58a6677f23422a07b9aebbc0ae89e8cb0 | /libvis/src/libvis/image_io_netpbm.h | d409e7ae857a51df465ee92b2c49a4d9e58d97d1 | [
"BSD-3-Clause"
] | permissive | SnowCarter/surfelmeshing | eef27c8d8797432f0706502e8507e45adee7323b | 5b1c8d160c1d64f5144b58309b725812d8e6e3ab | refs/heads/master | 2020-04-03T06:25:35.202401 | 2018-10-02T12:31:55 | 2018-10-02T12:31:55 | 155,074,298 | 1 | 0 | BSD-3-Clause | 2018-10-28T13:30:43 | 2018-10-28T13:30:42 | null | UTF-8 | C++ | false | false | 2,830 | h | // Copyright 2018 ETH Zürich, Thomas Schöps
//
// 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.
//
// 3. Neither the name of the copyright holder nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#pragma once
#include "libvis/image_io.h"
namespace vis {
// Image IO for netpbm formats (pbm, pgm, ppm, pnm).
class ImageIONetPBM : public ImageIO {
public:
virtual ImageFormatSupport GetSupportForFormat(ImageFormat format) const override {
if (format == ImageFormat::kPBM || format == ImageFormat::kPGM || format == ImageFormat::kPPM || format == ImageFormat::kPNM) {
return ImageFormatSupport::kComplete;
} else {
return ImageFormatSupport::kNone;
}
}
virtual bool Read(const std::string& image_file_name, Image<u8>* image) const override;
virtual bool Read(const std::string& image_file_name, Image<u16>* image) const override;
virtual bool Read(const std::string& image_file_name, Image<Vec3u8>* image) const override;
virtual bool Read(const std::string& image_file_name, Image<Vec4u8>* image) const override;
virtual bool Write(const std::string& image_file_name, const Image<u8>& image) const override;
virtual bool Write(const std::string& image_file_name, const Image<u16>& image) const override;
virtual bool Write(const std::string& image_file_name, const Image<Vec3u8>& image) const override;
virtual bool Write(const std::string& image_file_name, const Image<Vec4u8>& image) const override;
};
}
| [
"tom.schoeps@gmail.com"
] | tom.schoeps@gmail.com |
44f9bf7a3a5eb18bba1fb618925fe289fcdf7dac | 4d8941141571cca0b67f9d232bc29a3808029982 | /winter training/winter training day 3 A/main.cpp | f8d848028b3e0e54acbe989e0d33651a27f2404d | [] | no_license | 2003pro/code-of-acm | 38a10bf7504f895bffc74b82b3940d659008dedd | 6797ab837c9d41ed4db2faf0e0e57f7afb2de5ae | refs/heads/master | 2021-01-19T21:58:08.533594 | 2017-04-27T10:47:34 | 2017-04-27T10:47:34 | 88,726,025 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,129 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef pair<int ,int> pii;
vector<pii> sk;
queue <string> p;
stack <char> p1;
stack <int> pp;
string tt;
char s1[1003];
int main()
{
string s,s2;
while(cin >> s){
if(s[0] == '(') s = s.substr(1,s.length()-2);
int l = s.length(),i,vis=0,flag = 0;
strcpy(s1,s.c_str());
for(int i = 0;i < l;i++){
if(s1[i] != '(' && s1[i] != ')') p1.push(s1[i]);
else {
if(s1[i] == '(') pp.push(i);
else {
pii t;t.first = pp.top();t.second = i;pp.pop();
sk.push_back(t);
}
}
}
for(int i = 0;i < sk.size();i++){
if(sk[i-1].first - sk[i].first == 1 && sk[i].second - sk[i-1].second == 1){
int t1 = sk[i].first,t2 = sk[i].second;
s1[t1] = '0';s1[t2] = '0';
}
// printf("%d %d\n",sk[i].first,sk[i].second);
}
for(int i = 0;i < l;i++) {
if(s1[i] != '0') s2 += s1[i];
}
strcpy(s1,s2.c_str());
}
return 0;
}
| [
"张骥鹏"
] | 张骥鹏 |
e9bf8053dff7b2f3f06ebc5e0bc4f3a9be953313 | d0fb46aecc3b69983e7f6244331a81dff42d9595 | /live/include/alibabacloud/live/model/StopPlaylistResult.h | 26e6860e298ba280f15084b205cd8b0914cc25db | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-cpp-sdk | 3d8d051d44ad00753a429817dd03957614c0c66a | e862bd03c844bcb7ccaa90571bceaa2802c7f135 | refs/heads/master | 2023-08-29T11:54:00.525102 | 2023-08-29T03:32:48 | 2023-08-29T03:32:48 | 115,379,460 | 104 | 82 | NOASSERTION | 2023-09-14T06:13:33 | 2017-12-26T02:53:27 | C++ | UTF-8 | C++ | false | false | 1,362 | 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_LIVE_MODEL_STOPPLAYLISTRESULT_H_
#define ALIBABACLOUD_LIVE_MODEL_STOPPLAYLISTRESULT_H_
#include <string>
#include <vector>
#include <utility>
#include <alibabacloud/core/ServiceResult.h>
#include <alibabacloud/live/LiveExport.h>
namespace AlibabaCloud
{
namespace Live
{
namespace Model
{
class ALIBABACLOUD_LIVE_EXPORT StopPlaylistResult : public ServiceResult
{
public:
StopPlaylistResult();
explicit StopPlaylistResult(const std::string &payload);
~StopPlaylistResult();
std::string getProgramId()const;
protected:
void parse(const std::string &payload);
private:
std::string programId_;
};
}
}
}
#endif // !ALIBABACLOUD_LIVE_MODEL_STOPPLAYLISTRESULT_H_ | [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
af94524548bdfa8575170bba049307e89f429301 | 627d4d432c86ad98f669214d9966ae2db1600b31 | /unprocessed/tools/designer/src/lib/sdk/abstractwidgetfactory.cpp | a82d34e43835c43e43716588b8d4df85745883e8 | [] | no_license | fluxer/copperspice | 6dbab905f71843b8a3f52c844b841cef17f71f3f | 07e7d1315d212a4568589b0ab1bd6c29c06d70a1 | refs/heads/cs-1.1 | 2021-01-17T21:21:54.176319 | 2015-08-26T15:25:29 | 2015-08-26T15:25:29 | 39,802,091 | 6 | 0 | null | 2015-07-27T23:04:01 | 2015-07-27T23:04:00 | null | UTF-8 | C++ | false | false | 3,037 | cpp | /***********************************************************************
*
* Copyright (c) 2012-2015 Barbara Geller
* Copyright (c) 2012-2015 Ansel Sermersheim
* Copyright (c) 2012-2014 Digia Plc and/or its subsidiary(-ies).
* Copyright (c) 2008-2012 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
*
* This file is part of CopperSpice.
*
* CopperSpice is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* CopperSpice 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with CopperSpice. If not, see
* <http://www.gnu.org/licenses/>.
*
***********************************************************************/
#include <QtDesigner/abstractwidgetfactory.h>
#include "abstractformeditor.h"
#include "abstractwidgetdatabase.h"
QT_BEGIN_NAMESPACE
/*!
\class QDesignerWidgetFactoryInterface
\brief The QDesignerWidgetFactoryInterface class provides an interface that is used to control
the widget factory used by Qt Designer.
\inmodule QtDesigner
\internal
*/
/*!
\fn QDesignerWidgetFactoryInterface::QDesignerWidgetFactoryInterface(QObject *parent)
Constructs an interface to a widget factory with the given \a parent.
*/
QDesignerWidgetFactoryInterface::QDesignerWidgetFactoryInterface(QObject *parent)
: QObject(parent)
{
}
/*!
\fn virtual QDesignerWidgetFactoryInterface::~QDesignerWidgetFactoryInterface()
*/
QDesignerWidgetFactoryInterface::~QDesignerWidgetFactoryInterface()
{
}
/*!
\fn virtual QDesignerFormEditorInterface *QDesignerWidgetFactoryInterface::core() const = 0
Returns the core form editor interface associated with this interface.
*/
/*!
\fn virtual QWidget* QDesignerWidgetFactoryInterface::containerOfWidget(QWidget *child) const = 0
Returns the widget that contains the specified \a child widget.
*/
/*!
\fn virtual QWidget* QDesignerWidgetFactoryInterface::widgetOfContainer(QWidget *container) const = 0
*/
/*!
\fn virtual QWidget *QDesignerWidgetFactoryInterface::createWidget(const QString &name, QWidget *parent) const = 0
Returns a new widget with the given \a name and \a parent widget. If no parent is specified,
the widget created will be a top-level widget.
*/
/*!
\fn virtual QLayout *QDesignerWidgetFactoryInterface::createLayout(QWidget *widget, QLayout *layout, int type) const = 0
Returns a new layout of the specified \a type for the given \a widget or \a layout.
*/
/*!
\fn virtual bool QDesignerWidgetFactoryInterface::isPassiveInteractor(QWidget *widget) = 0
*/
/*!
\fn virtual void QDesignerWidgetFactoryInterface::initialize(QObject *object) const = 0
*/
QT_END_NAMESPACE
| [
"ansel@copperspice.com"
] | ansel@copperspice.com |
0fc664c413a14a57916edfe97d57e740344a6756 | ea13d60ca2b530a339d48e677723d35492d9177c | /02_module/ABKCommon/src/mmapStreamBuf.cxx | 9c733e0b8c0b30f6f4c426433fa48ad0f8c73923 | [
"MIT"
] | permissive | gledr/SMT_MacroPlacer | dab3e929b3edbb6bc346f9b9f9a44d76fd258239 | b5b25f0ce9094553167ffd4985721f86414ceddc | refs/heads/master | 2023-01-31T09:11:25.763888 | 2020-12-18T08:52:00 | 2020-12-18T08:52:00 | 251,312,468 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,808 | cxx | /**************************************************************************
***
*** Copyright (c) 1995-2000 Regents of the University of California,
*** Andrew E. Caldwell, Andrew B. Kahng and Igor L. Markov
*** Copyright (c) 2000-2010 Regents of the University of Michigan,
*** Saurabh N. Adya, Jarrod A. Roy, David A. Papa and
*** Igor L. Markov
***
*** Contact author(s): abk@cs.ucsd.edu, imarkov@umich.edu
*** Original Affiliation: UCLA, Computer Science Department,
*** Los Angeles, CA 90095-1596 USA
***
*** Permission is hereby granted, free of charge, to any person obtaining
*** a copy of this software and associated documentation files (the
*** "Software"), to deal in the Software without restriction, including
*** without limitation
*** the rights to use, copy, modify, merge, publish, distribute, sublicense,
*** and/or sell copies of the Software, and to permit persons to whom the
*** Software is furnished to do so, subject to the following conditions:
***
*** The above copyright notice and this permission notice shall be included
*** in all copies or substantial portions of the Software.
***
*** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
*** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
*** OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
*** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
*** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
*** OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
*** THE USE OR OTHER DEALINGS IN THE SOFTWARE.
***
***
***************************************************************************/
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <iostream>
#include <unistd.h>
#include <cmath>
#include "mmapStreamBuf.h"
#include "uofm_alloc.h"
using std::cout;
using std::endl;
using uofm::string;
MMapStreamBuf::MMapStreamBuf(const char *inputFileName)
{
_fileName = string(inputFileName);
struct stat s;
if (stat(_fileName.c_str(), &s)) {
cout << "[MMapStreamBuf] " << "stat failed" << endl;
throw;
}
_fileSize = s.st_size;
int fd;
if ((fd = open(_fileName.c_str(), O_RDONLY)) < 0) {
cout << "[MMapStreamBuf] " << "open failed" << endl;
throw;
}
int pageSize = getpagesize();
_mapSize = unsigned(ceil(double(_fileSize)/double(pageSize))) * pageSize;
unsigned offset = 0;
void *buf = mmap(NULL, _mapSize, PROT_READ, MAP_PRIVATE, fd, offset);
close(fd);
if (buf == MAP_FAILED) {
cout << "[MMapStreamBuf] " << "mmap failed" << endl;
throw;
}
setbuf((char *)buf, _fileSize);
}
MMapStreamBuf::~MMapStreamBuf()
{
munmap(_M_buf, _mapSize);
}
| [
"sebastian.pointner@jku.at"
] | sebastian.pointner@jku.at |
a7fbd7755ef80f281f66d4420049f5c32586ea2d | 0fccd1748ee7be55039e7bbfb4820197b5a85f0b | /2D Game Engine/2D Game Engine/LevelManager.h | 971927bedf7486504c9856c7319e2b485fa904ea | [] | no_license | AustinChayka/C-Game | 11d297ac5fd38a280da4701ec16c5e18f8680c58 | 56bd96fddc38cb4bfca6f69c37748b1417a51d8a | refs/heads/master | 2022-02-13T02:39:14.724679 | 2019-05-30T22:10:43 | 2019-05-30T22:10:43 | 167,856,869 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 960 | h | #ifndef LevelManager_h
#define LevelManager_h
#include "StateManager.h"
#include <vector>
#include "ImageTile.h"
class StateManager;
class GameObject;
class ImageTile;
class Room;
class LevelManager {
public:
LevelManager();
~LevelManager();
void LoadLevel(int n);
void GenerateLevel(int size, int seed);
void Update(StateManager * sm);
void Render();
void AddObject(GameObject * go);
std::vector<GameObject *> * GetObjects();
void AddTile(ImageTile * it);
std::vector<Room *> * GetRooms();
void NextLevel();
static GameObject * player;
void AddItemRoom(float roomOffsetX, float roomOffsetY);
private:
std::vector<GameObject *> * objects;
std::vector<ImageTile *> * tiles;
std::vector<Room *> * rooms;
std::vector<GameObject *> * allObjects;
std::vector<int> specialRoomsBlacklist;
int currentLevel = 0, leftOverEnemies = 0, specialRoomSkips = 0, activeRoom = 0;
bool reloaded;
bool IsBlacklisted(int r);
};
#endif | [
"austinchayka@gmail.com"
] | austinchayka@gmail.com |
59cbfc7165a8e55e41184e69a9d93bd41550a2e1 | 2b5c710c9b372ad7e4d49e16852944aaf8926a07 | /DerivedSources/WebCore/JSSVGViewSpec.cpp | cb1ff2282fd125dafd649a69cadd0d615f5056fc | [
"Apache-2.0"
] | permissive | FMSoftCN/mdolphin-core | 8ce68f1055d3a38f6e46bd311f2c20b7afc183b8 | 48ffdcf587a48a7bb4345ae469a45c5b64ffad0e | refs/heads/master | 2022-04-09T22:16:12.602078 | 2020-02-11T10:06:11 | 2020-02-11T10:06:11 | 92,716,592 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,790 | cpp | /*
This file is part of the WebKit open source project.
This file has been generated by generate-bindings.pl. DO NOT MODIFY!
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "config.h"
#if ENABLE(SVG)
#include "JSSVGViewSpec.h"
#include "JSSVGAnimatedPreserveAspectRatio.h"
#include "JSSVGAnimatedRect.h"
#include "JSSVGElement.h"
#include "JSSVGTransformList.h"
#include "KURL.h"
#include "SVGElement.h"
#include "SVGTransformList.h"
#include "SVGViewSpec.h"
#include <runtime/JSString.h>
#include <wtf/GetPtr.h>
using namespace JSC;
namespace WebCore {
ASSERT_CLASS_FITS_IN_CELL(JSSVGViewSpec);
/* Hash table */
#if ENABLE(JIT)
#define THUNK_GENERATOR(generator) , generator
#else
#define THUNK_GENERATOR(generator)
#endif
static const HashTableValue JSSVGViewSpecTableValues[10] =
{
{ "transform", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGViewSpecTransform), (intptr_t)0 THUNK_GENERATOR(0) },
{ "viewTarget", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGViewSpecViewTarget), (intptr_t)0 THUNK_GENERATOR(0) },
{ "viewBoxString", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGViewSpecViewBoxString), (intptr_t)0 THUNK_GENERATOR(0) },
{ "preserveAspectRatioString", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGViewSpecPreserveAspectRatioString), (intptr_t)0 THUNK_GENERATOR(0) },
{ "transformString", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGViewSpecTransformString), (intptr_t)0 THUNK_GENERATOR(0) },
{ "viewTargetString", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGViewSpecViewTargetString), (intptr_t)0 THUNK_GENERATOR(0) },
{ "viewBox", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGViewSpecViewBox), (intptr_t)0 THUNK_GENERATOR(0) },
{ "preserveAspectRatio", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGViewSpecPreserveAspectRatio), (intptr_t)0 THUNK_GENERATOR(0) },
{ "constructor", DontEnum | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGViewSpecConstructor), (intptr_t)0 THUNK_GENERATOR(0) },
{ 0, 0, 0, 0 THUNK_GENERATOR(0) }
};
#undef THUNK_GENERATOR
static JSC_CONST_HASHTABLE HashTable JSSVGViewSpecTable = { 33, 31, JSSVGViewSpecTableValues, 0 };
/* Hash table for constructor */
#if ENABLE(JIT)
#define THUNK_GENERATOR(generator) , generator
#else
#define THUNK_GENERATOR(generator)
#endif
static const HashTableValue JSSVGViewSpecConstructorTableValues[1] =
{
{ 0, 0, 0, 0 THUNK_GENERATOR(0) }
};
#undef THUNK_GENERATOR
static JSC_CONST_HASHTABLE HashTable JSSVGViewSpecConstructorTable = { 1, 0, JSSVGViewSpecConstructorTableValues, 0 };
class JSSVGViewSpecConstructor : public DOMConstructorObject {
public:
JSSVGViewSpecConstructor(JSC::ExecState*, JSDOMGlobalObject*);
virtual bool getOwnPropertySlot(JSC::ExecState*, const JSC::Identifier&, JSC::PropertySlot&);
virtual bool getOwnPropertyDescriptor(JSC::ExecState*, const JSC::Identifier&, JSC::PropertyDescriptor&);
static const JSC::ClassInfo s_info;
static PassRefPtr<JSC::Structure> createStructure(JSC::JSGlobalData& globalData, JSC::JSValue prototype)
{
return JSC::Structure::create(globalData, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), AnonymousSlotCount, &s_info);
}
protected:
static const unsigned StructureFlags = JSC::OverridesGetOwnPropertySlot | JSC::ImplementsHasInstance | DOMConstructorObject::StructureFlags;
};
const ClassInfo JSSVGViewSpecConstructor::s_info = { "SVGViewSpecConstructor", &DOMConstructorObject::s_info, &JSSVGViewSpecConstructorTable, 0 };
JSSVGViewSpecConstructor::JSSVGViewSpecConstructor(ExecState* exec, JSDOMGlobalObject* globalObject)
: DOMConstructorObject(JSSVGViewSpecConstructor::createStructure(globalObject->globalData(), globalObject->objectPrototype()), globalObject)
{
ASSERT(inherits(&s_info));
putDirect(exec->globalData(), exec->propertyNames().prototype, JSSVGViewSpecPrototype::self(exec, globalObject), DontDelete | ReadOnly);
}
bool JSSVGViewSpecConstructor::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
return getStaticValueSlot<JSSVGViewSpecConstructor, DOMObject>(exec, &JSSVGViewSpecConstructorTable, this, propertyName, slot);
}
bool JSSVGViewSpecConstructor::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)
{
return getStaticValueDescriptor<JSSVGViewSpecConstructor, DOMObject>(exec, &JSSVGViewSpecConstructorTable, this, propertyName, descriptor);
}
/* Hash table for prototype */
#if ENABLE(JIT)
#define THUNK_GENERATOR(generator) , generator
#else
#define THUNK_GENERATOR(generator)
#endif
static const HashTableValue JSSVGViewSpecPrototypeTableValues[1] =
{
{ 0, 0, 0, 0 THUNK_GENERATOR(0) }
};
#undef THUNK_GENERATOR
static JSC_CONST_HASHTABLE HashTable JSSVGViewSpecPrototypeTable = { 1, 0, JSSVGViewSpecPrototypeTableValues, 0 };
const ClassInfo JSSVGViewSpecPrototype::s_info = { "SVGViewSpecPrototype", &JSC::JSObjectWithGlobalObject::s_info, &JSSVGViewSpecPrototypeTable, 0 };
JSObject* JSSVGViewSpecPrototype::self(ExecState* exec, JSGlobalObject* globalObject)
{
return getDOMPrototype<JSSVGViewSpec>(exec, globalObject);
}
const ClassInfo JSSVGViewSpec::s_info = { "SVGViewSpec", &JSSVGZoomAndPan::s_info, &JSSVGViewSpecTable, 0 };
JSSVGViewSpec::JSSVGViewSpec(NonNullPassRefPtr<Structure> structure, JSDOMGlobalObject* globalObject, PassRefPtr<SVGViewSpec> impl)
: JSSVGZoomAndPan(structure, globalObject, impl)
{
ASSERT(inherits(&s_info));
}
JSObject* JSSVGViewSpec::createPrototype(ExecState* exec, JSGlobalObject* globalObject)
{
return new (exec) JSSVGViewSpecPrototype(globalObject, JSSVGViewSpecPrototype::createStructure(exec->globalData(), JSSVGZoomAndPanPrototype::self(exec, globalObject)));
}
bool JSSVGViewSpec::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
return getStaticValueSlot<JSSVGViewSpec, Base>(exec, &JSSVGViewSpecTable, this, propertyName, slot);
}
bool JSSVGViewSpec::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)
{
return getStaticValueDescriptor<JSSVGViewSpec, Base>(exec, &JSSVGViewSpecTable, this, propertyName, descriptor);
}
JSValue jsSVGViewSpecTransform(ExecState* exec, JSValue slotBase, const Identifier&)
{
JSSVGViewSpec* castedThis = static_cast<JSSVGViewSpec*>(asObject(slotBase));
UNUSED_PARAM(exec);
SVGViewSpec* imp = static_cast<SVGViewSpec*>(castedThis->impl());
JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(SVGTransformListPropertyTearOff::create(imp->transform())));
return result;
}
JSValue jsSVGViewSpecViewTarget(ExecState* exec, JSValue slotBase, const Identifier&)
{
JSSVGViewSpec* castedThis = static_cast<JSSVGViewSpec*>(asObject(slotBase));
UNUSED_PARAM(exec);
SVGViewSpec* imp = static_cast<SVGViewSpec*>(castedThis->impl());
JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(imp->viewTarget()));
return result;
}
JSValue jsSVGViewSpecViewBoxString(ExecState* exec, JSValue slotBase, const Identifier&)
{
JSSVGViewSpec* castedThis = static_cast<JSSVGViewSpec*>(asObject(slotBase));
UNUSED_PARAM(exec);
SVGViewSpec* imp = static_cast<SVGViewSpec*>(castedThis->impl());
JSValue result = jsString(exec, imp->viewBoxString());
return result;
}
JSValue jsSVGViewSpecPreserveAspectRatioString(ExecState* exec, JSValue slotBase, const Identifier&)
{
JSSVGViewSpec* castedThis = static_cast<JSSVGViewSpec*>(asObject(slotBase));
UNUSED_PARAM(exec);
SVGViewSpec* imp = static_cast<SVGViewSpec*>(castedThis->impl());
JSValue result = jsString(exec, imp->preserveAspectRatioString());
return result;
}
JSValue jsSVGViewSpecTransformString(ExecState* exec, JSValue slotBase, const Identifier&)
{
JSSVGViewSpec* castedThis = static_cast<JSSVGViewSpec*>(asObject(slotBase));
UNUSED_PARAM(exec);
SVGViewSpec* imp = static_cast<SVGViewSpec*>(castedThis->impl());
JSValue result = jsString(exec, imp->transformString());
return result;
}
JSValue jsSVGViewSpecViewTargetString(ExecState* exec, JSValue slotBase, const Identifier&)
{
JSSVGViewSpec* castedThis = static_cast<JSSVGViewSpec*>(asObject(slotBase));
UNUSED_PARAM(exec);
SVGViewSpec* imp = static_cast<SVGViewSpec*>(castedThis->impl());
JSValue result = jsString(exec, imp->viewTargetString());
return result;
}
JSValue jsSVGViewSpecViewBox(ExecState* exec, JSValue slotBase, const Identifier&)
{
JSSVGViewSpec* castedThis = static_cast<JSSVGViewSpec*>(asObject(slotBase));
UNUSED_PARAM(exec);
SVGViewSpec* imp = static_cast<SVGViewSpec*>(castedThis->impl());
RefPtr<SVGAnimatedRect> obj = imp->viewBoxAnimated();
JSValue result = toJS(exec, castedThis->globalObject(), obj.get());
return result;
}
JSValue jsSVGViewSpecPreserveAspectRatio(ExecState* exec, JSValue slotBase, const Identifier&)
{
JSSVGViewSpec* castedThis = static_cast<JSSVGViewSpec*>(asObject(slotBase));
UNUSED_PARAM(exec);
SVGViewSpec* imp = static_cast<SVGViewSpec*>(castedThis->impl());
RefPtr<SVGAnimatedPreserveAspectRatio> obj = imp->preserveAspectRatioAnimated();
JSValue result = toJS(exec, castedThis->globalObject(), obj.get());
return result;
}
JSValue jsSVGViewSpecConstructor(ExecState* exec, JSValue slotBase, const Identifier&)
{
JSSVGViewSpec* domObject = static_cast<JSSVGViewSpec*>(asObject(slotBase));
return JSSVGViewSpec::getConstructor(exec, domObject->globalObject());
}
JSValue JSSVGViewSpec::getConstructor(ExecState* exec, JSGlobalObject* globalObject)
{
return getDOMConstructor<JSSVGViewSpecConstructor>(exec, static_cast<JSDOMGlobalObject*>(globalObject));
}
}
#endif // ENABLE(SVG)
| [
"vincent@minigui.org"
] | vincent@minigui.org |
03efdc18375eb6352b14aa2e2efdaf4c371dc309 | 00685c116da5169abda9c0fdd57a4dc20434e239 | /virtual_clay_2/virtual_clay_2/src/d3d/D3DSphere.h | c1c67750ce94aa75833a9efa84afe5e368db1b1b | [
"MIT"
] | permissive | RythBlade/virtual_clay_2 | 4af41972d634925e11d2769808a00ba48738064e | 987eeebe24521d7f3d8b38235121bb3f9c464b10 | refs/heads/master | 2020-06-29T11:52:40.807066 | 2019-08-11T09:39:03 | 2019-08-11T09:39:03 | 200,527,736 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 926 | h | // LCCREDIT start of LunaDX10.2
#pragma once
#include <d3d11.h>
#include <vector>
#include <dxerr.h>
#include "Utility.h"
#include "DataTypes.h"
#include "Debug.h"
class D3DSphere
{
private:
float mRadius;
UINT mNumSlices;
UINT mNumStacks;
DWORD mNumVertices;
DWORD mNumFaces;
ID3D11Device* md3dDevice;
ID3D11DeviceContext *pDevcon;
ID3D11Buffer* mVB;
ID3D11Buffer* mIB;
public:
D3DSphere();
~D3DSphere();
HRESULT init(ID3D11Device* device, ID3D11DeviceContext *pDeviceContext, float radius, UINT numSlices, UINT numStacks);
void setBuffers(); // function to set the dx11 buffers before rendering - so that they aren't constantly set if the sphere is drawn multiple times
void draw();
private:
typedef std::vector<VERTEX> VertexList;
typedef std::vector<DWORD> IndexList;
void buildStacks(VertexList& vertices, IndexList& indices);
};
// end of LunaDX10.2 | [
"noreply@github.com"
] | RythBlade.noreply@github.com |
89b70c6d1b80b2e67426fc40d80305b4d9dfdf1f | 25f1a35e2802ddab82f97c570491b9ad3599831e | /src/Deliverables/DediPro/MiscSettings.cpp | 609a01f228e164a9c5715d288b510769b9a96497 | [] | no_license | rockonedege/dediprog-SF1xx | 1a8f35378e08a49dca7fc21474bfef00a43c162a | de57583ea3ec90ac90132c08258bbe1bebf3cc3f | refs/heads/master | 2020-09-16T20:25:06.077225 | 2019-11-25T06:57:41 | 2019-11-25T06:57:41 | 223,880,292 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,024 | cpp | // MiscSettings.cpp : implementation file
//
#include "stdafx.h"
#include "DediPro.h"
#include "MiscSettings.h"
#include "PreferenceEx.h"
#include "dedicontext.h"
#include <boost/array.hpp>
// CMiscSettings dialog
IMPLEMENT_DYNAMIC(CMiscSettings, CPropertyPage)
CMiscSettings::CMiscSettings(Context::CDediContext& context)
: CPropertyPage(CMiscSettings::IDD)
, m_context(context)
{
}
CMiscSettings::~CMiscSettings()
{
}
void CMiscSettings::DoDataExchange(CDataExchange* pDX)
{
CPropertyPage::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CMiscSettings, CPropertyPage)
ON_CONTROL_RANGE(BN_CLICKED, IDC_VCC3_5, IDC_VCC1_8, &CMiscSettings::OnSelectVcc)
END_MESSAGE_MAP()
// CMiscSettings message handlers
BOOL CMiscSettings::OnInitDialog()
{
CPropertyPage::OnInitDialog();
// TODO: Add extra initialization here
initVpp();
initVcc();
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CMiscSettings::OnOK()
{
// TODO: Add your specialized code here and/or call the base class
m_context.power.Misc_ApplyVpp = IsDlgButtonChecked(IDC_CHK_VPP) == BST_CHECKED;
CPropertyPage::OnOK();
}
void CMiscSettings::OnSelectVcc(UINT id)
{
// TODO: Add your control notification handler code here
boost::array<power::VCC_VALUE, 2> vcc =
{
power::vcc3_5V,
power::vcc1_8V
};
m_context.power.vcc = vcc[id - IDC_VCC3_5];
}
void CMiscSettings::initVcc()
{
if(power::vcc3_5V == m_context.power.vcc)
{
CheckRadioButton(IDC_VCC3_5, IDC_VCC1_8, IDC_VCC3_5);
}
else if (power::vcc1_8V == m_context.power.vcc)
{
CheckRadioButton(IDC_VCC3_5, IDC_VCC1_8, IDC_VCC1_8);
}
else
{}
}
void CMiscSettings::initVpp()
{
bool applyVpp = m_context.power.Misc_ApplyVpp;
CheckDlgButton(IDC_CHK_VPP, applyVpp ? BST_CHECKED : BST_UNCHECKED);
}
| [
"rockonedge@live.com"
] | rockonedge@live.com |
c62f80492f255988842e2647148eb7bac44a3aef | 3a4f120f3211a1482b8ba826f4922fa741c5586e | /ip/Pmods/PmodWIFI_v1_0/drivers/PmodWIFI_v1_0/examples/HTTPServer/ProcessClient.cpp | 9fb794141743739c3b41ae26131800ede7ea66a1 | [
"MIT"
] | permissive | Digilent/vivado-library | 7135129c7e4fec84d17e1fe037598bd2124085eb | cbfde215a27053004cb41d85535c4a1bd1673e14 | refs/heads/master | 2023-09-05T22:04:31.189589 | 2023-08-22T17:23:00 | 2023-08-22T17:23:46 | 46,139,497 | 512 | 327 | MIT | 2023-08-22T17:23:47 | 2015-11-13T18:23:02 | C | UTF-8 | C++ | false | false | 23,728 | cpp | /************************************************************************/
/* */
/* ProcessClient.cpp */
/* */
/* A chipKIT WiFi HTTP Web Server implementation */
/* This processes connected clients */
/* This sketch is designed to work with web browsers */
/* */
/************************************************************************/
/* Author: Keith Vogel */
/* Copyright 2013, Digilent Inc. */
/************************************************************************/
/*
*
* Copyright (c) 2013-2014, Digilent <www.digilentinc.com>
* Contact Digilent for the latest version.
*
* This program is free software; distributed under the terms of
* BSD 3-clause license ("Revised BSD License", "New BSD License", or "Modified BSD License")
*
* 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.
* 3. Neither the name(s) of the above-listed copyright holder(s) nor the names
* of its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/************************************************************************/
/* Revision History: */
/* 2/1/2013(KeithV): Created */
/************************************************************************/
#include "HTTPServer.h"
// The HTML Redering page list
typedef struct
{
const char * szMatchString;
uint32_t cbMatch;
FNRENDERHTML ComposeHTMLPage;
} HTTPCMD;
static HTTPCMD rgHttpCmd[CNTHTTPCMD];
static FNRENDERHTML DefaultHTMLPage = ComposeHTTP404Error;
typedef enum
{
START = 0,
READINPUT,
PARSENEXTLINE,
WAITCMD,
DEFAULTCMD,
DISPLAYTIME,
PROCESSHTML,
WRITEBUFFER,
STOPCLIENT, // any state after the connection is lost must be placed below here
EXIT, // just finishing up the client processing
RESTART, // want to restart the server
TERMINATE, // want to terminate the server
REBOOT // reboot the processor; MCLR
} CLIENTSTATE;
/*** GCMD::ACTION ProcessClient(CLIENTINFO * pClientInfo)
*
* Parameters:
* pClientInfo - a pointer to CLIENTINFO structure with the socket and local data used by the connection
*
* Return Values:
* GCMD::ACTION - Generally GCMD::CONTINUE is returned to keep the server running
* However if GCMD::RESTART is returned, the server is restarted
* And if GCMD::TERMINATE is returned, the server is cleanly shutdown and loops forever doing nothing.
*
* Description:
*
* In the CLINTINFO structure there is an fInUse flag, and this is what tells the server
* that the CLINTINFO has an active connection. Only active connections are processed by the server
* so this function is only called with pClientInfo->fInUse == true. This function sets it false when the connection
* is closed or lost.
*
* Having said that, there are a few cases when the connection will be dropped. For example if the other side
* unexpectedly drops the connection, or the network goes down.
*
* When the connection is closed (state == STOPCLIENT) for whatever reason, the HTML rendering function will be called with
* pClientInfo->htmlState == HTTPDISCONNECT. This is the only intential time the HTML Rendering function will
* be called with the connection closed. This is to allow the Rendering page to deinitialize any state.
* So if a file is open, or hardware is process, the rendering page function will have an opertunity to close
* resources. This is particularly useful if the connection is unexpectedly dropped, this will allow
* for cleanup. When the HTML rendering function is called with HTTPDISCONNECT, GCMD::DONE is expected to be returned.
*
* ------------------------------------------------------------ */
GCMD::ACTION ProcessClient(CLIENTINFO * pClientInfo)
{
GCMD::ACTION action = GCMD::CONTINUE;
IPSTATUS status = ipsSuccess;
uint32_t tCur = SYSGetMilliSecond();
// timeout occured, get out
if(pClientInfo->clientState != START && (tCur - pClientInfo->tStartClient) >= (secClientTO * 1000))
{
xil_printf("Timeout on client: 0x%X\r\n", pClientInfo);
pClientInfo->nextClientState = EXIT;
// if no data came in at all, then just close the connection
if(pClientInfo->cbRead == 0)
{
pClientInfo->clientState = STOPCLIENT;
}
// if some data came in, then give the data to the default HTML page.
else if(pClientInfo->ComposeHTMLPage == NULL)
{
pClientInfo->clientState = DEFAULTCMD;
}
else
{
pClientInfo->clientState = PROCESSHTML;
pClientInfo->htmlState = HTTPTIMEOUT;
}
}
// lost the connection, get out
if(((CLIENTSTATE) pClientInfo->clientState < STOPCLIENT) && !pClientInfo->pTCPClient->isEstablished())
{
xil_printf("Connection Lost\r\n");
pClientInfo->clientState = STOPCLIENT;
pClientInfo->tStartClient = tCur;
pClientInfo->nextClientState = EXIT;
}
switch((CLIENTSTATE) pClientInfo->clientState)
{
case START:
xil_printf("New Client detected\r\n");
// we know for the most part, the CLIENTINFO is zero'ed
// so only set non-zero values
pClientInfo->pbOut = pClientInfo->rgbOut;
pClientInfo->htmlState = HTTPSTART; // forces the initialization state to be executed
pClientInfo->tStartClient = tCur;
pClientInfo->clientState = READINPUT;
pClientInfo->nextClientState = WAITCMD;
break;
case READINPUT:
// read in the HTTP URL, any additional data.
if(pClientInfo->pTCPClient->available() > 0 && pClientInfo->cbRead < sizeof(pClientInfo->rgbIn))
{
pClientInfo->cbRead += pClientInfo->pTCPClient->readStream(&pClientInfo->rgbIn[pClientInfo->cbRead], sizeof(pClientInfo->rgbIn) - pClientInfo->cbRead);
}
pClientInfo->clientState = pClientInfo->nextClientState;
break;
case WAITCMD:
// until we read something, match, or timeout, we keep reading and waiting.
pClientInfo->clientState = READINPUT;
pClientInfo->nextClientState = WAITCMD;
// check the match strings, only if we have something to compare against
if(pClientInfo->cbRead > 0)
{
bool fPartialMatch = false;
// now look to see if HTML redering pages matches this URL
for(uint32_t i = 0; i < CNTHTTPCMD; i++)
{
// does this entry have anything in it?
if(rgHttpCmd[i].cbMatch > 0)
{
uint32_t cbCmp = rgHttpCmd[i].cbMatch > pClientInfo->cbRead ? pClientInfo->cbRead : rgHttpCmd[i].cbMatch;
// see if we found a matching URL
if(memcmp(pClientInfo->rgbIn, rgHttpCmd[i].szMatchString, cbCmp) == 0)
{
// we either have a partial or full match
fPartialMatch = true;
// we have a full match; we know what dynamic page to call
if(cbCmp == rgHttpCmd[i].cbMatch)
{
pClientInfo->ComposeHTMLPage = rgHttpCmd[i].ComposeHTMLPage;
pClientInfo->clientState = DISPLAYTIME;
pClientInfo->tStartClient = tCur;
// fournd it, get out.
break;
}
}
}
}
// if we didn't find a perfect match, then lets see if we are done anyway
if(pClientInfo->clientState == READINPUT)
{
// only quit if we can't read anymore; our input buffer is full
// otherwise keep reading, we may get more bytes to give us a full match
if(!fPartialMatch || pClientInfo->cbRead == sizeof(pClientInfo->rgbIn) ||
(pClientInfo->cbRead >= 4 &&
pClientInfo->rgbIn[pClientInfo->cbRead-4] == '\r' && pClientInfo->rgbIn[pClientInfo->cbRead-3] == '\n' &&
pClientInfo->rgbIn[pClientInfo->cbRead-2] == '\r' && pClientInfo->rgbIn[pClientInfo->cbRead-1] == '\n' ) )
{
pClientInfo->clientState = DEFAULTCMD;
pClientInfo->tStartClient = tCur;
}
}
}
break;
case DEFAULTCMD:
xil_printf("Default page called\r\n");
pClientInfo->ComposeHTMLPage = DefaultHTMLPage;
pClientInfo->tStartClient = tCur;
pClientInfo->clientState = DISPLAYTIME;
break;
case DISPLAYTIME:
{
#ifndef NOTIME
unsigned int epochTime = 0;
char szTemp[256];
epochTime = deIPcK.secondsSinceEpoch();
GetDayAndTime(epochTime, szTemp);
Serial.println(szTemp);
#endif
pClientInfo->clientState = PROCESSHTML;
pClientInfo->tStartClient = tCur;
}
break;
case PROCESSHTML:
// process the HTML page
switch((action = pClientInfo->ComposeHTMLPage(pClientInfo)))
{
// just come back to this state
case GCMD::CONTINUE:
pClientInfo->clientState = PROCESSHTML;
break;
// TODO, read more from the input.
case GCMD::READ:
pClientInfo->nextClientState = PROCESSHTML;
pClientInfo->clientState = READINPUT;
break;
// we have data to write out
case GCMD::WRITE:
pClientInfo->nextClientState = PROCESSHTML;
pClientInfo->clientState = WRITEBUFFER;
break;
// Done processing the client, close the client and get out
case GCMD::DONE:
pClientInfo->nextClientState = EXIT; // we are done!
pClientInfo->clientState = STOPCLIENT;
break;
case GCMD::RESTART:
pClientInfo->nextClientState = RESTART; // we want to terminate the server
pClientInfo->clientState = STOPCLIENT;
break;
case GCMD::TERMINATE:
pClientInfo->nextClientState = TERMINATE; // we want to terminate the server
pClientInfo->clientState = STOPCLIENT;
break;
case GCMD::REBOOT:
pClientInfo->nextClientState = REBOOT; // we want to reboot the server
pClientInfo->clientState = STOPCLIENT;
break;
case GCMD::GETLINE:
pClientInfo->clientState = PARSENEXTLINE;
break;
default:
xil_printf("Unsupported compose command detected: %d\r\n",action);
pClientInfo->nextClientState = EXIT; // we are done!
pClientInfo->clientState = STOPCLIENT;
break;
}
pClientInfo->cbWritten = 0;
pClientInfo->tStartClient = tCur;
break;
case PARSENEXTLINE:
{
uint32_t i = 0;
bool fFoundNewLine = false;
bool fNullTerminator = false;
// we are looking for either a /r/n or a /0.
// if we find the /r/n first, than replace the /r/n with /0 and that is our first line
// otherwise if we find the /0, go find the next /r/n
for(i = 0; i < pClientInfo->cbRead; i++)
{
if( (fFoundNewLine = pClientInfo->rgbIn[i] == '\n') ||
(fNullTerminator = pClientInfo->rgbIn[i] == '\0') )
{
break;
}
}
// found the line end, terminate it and return.
if(fFoundNewLine)
{
pClientInfo->rgbIn[i] = '\0';
if(i > 0 && pClientInfo->rgbIn[i-1] == '\r')
{
pClientInfo->rgbIn[i-1] = '\0';
}
pClientInfo->clientState = PROCESSHTML;
}
else if(fNullTerminator)
{
// go to beyond the \0
for( ; i < pClientInfo->cbRead && pClientInfo->rgbIn[i] == '\0'; i++);
if(i == pClientInfo->cbRead)
{
// nothing left in the buffer to read, so we can reset it.
pClientInfo->cbRead = 0;
pClientInfo->clientState = READINPUT;
pClientInfo->nextClientState = PARSENEXTLINE;
if(pClientInfo->rgbOverflow[0] != '\0')
{
pClientInfo->rgbIn[0] = pClientInfo->rgbOverflow[0];
pClientInfo->rgbOverflow[0] = '\0';
pClientInfo->cbRead = 1;
}
}
// copy the end of the buffer to the front of the buffer
// memcpy should be a safe overlapping copy.
else
{
pClientInfo->cbRead -= i;
memcpy(pClientInfo->rgbIn, &pClientInfo->rgbIn[i], pClientInfo->cbRead);
// stay at this state to go find the end of line
}
}
// this is a hard condition, our input buffer is full, and it doesn't even contain a full line.
else if(i == sizeof(pClientInfo->rgbIn))
{
// save away the last byte and return it as a line, even though there is a line break.
pClientInfo->rgbOverflow[0] = pClientInfo->rgbIn[sizeof(pClientInfo->rgbIn)-1];
pClientInfo->rgbIn[sizeof(pClientInfo->rgbIn)-1] = '\0';
pClientInfo->clientState = PROCESSHTML;
}
// we need to read more data.
else
{
pClientInfo->clientState = READINPUT;
pClientInfo->nextClientState = PARSENEXTLINE;
}
}
break;
case WRITEBUFFER:
// see if we are done
if(pClientInfo->cbWritten == pClientInfo->cbWrite)
{
pClientInfo->clientState = pClientInfo->nextClientState;
pClientInfo->nextClientState = STOPCLIENT;
break;
}
// otherwise we have data to write
pClientInfo->cbWritten += pClientInfo->pTCPClient->writeStream(&pClientInfo->pbOut[pClientInfo->cbWritten], pClientInfo->cbWrite - pClientInfo->cbWritten, &status);
//xil_printf("%s", pClientInfo->pbOut);
// got an error, terminate the connection
if(IsIPStatusAnError(status))
{
xil_printf("Error writing\r\n");
pClientInfo->clientState = STOPCLIENT;
pClientInfo->nextClientState = EXIT;
}
// or we are done now after the write
else if(pClientInfo->cbWritten == pClientInfo->cbWrite)
{
pClientInfo->clientState = pClientInfo->nextClientState;
pClientInfo->nextClientState = STOPCLIENT;
}
pClientInfo->tStartClient = tCur;
break;
case STOPCLIENT:
xil_printf("Closing connection for client: 0x%X\r\n", pClientInfo);
pClientInfo->pTCPClient->close();
if(pClientInfo->ComposeHTMLPage != NULL)
{
pClientInfo->htmlState = HTTPDISCONNECT;
pClientInfo->ComposeHTMLPage(pClientInfo);
}
pClientInfo->clientState = pClientInfo->nextClientState;
pClientInfo->tStartClient = tCur;
return(GCMD::ADDSOCKET);
break;
case EXIT:
break;
case RESTART:
xil_printf("Restart Commanded\r\n");
return(GCMD::RESTART);
break;
case TERMINATE:
xil_printf("Termination Commanded\r\n");
return(GCMD::TERMINATE);
break;
case REBOOT:
xil_printf("Reboot Commanded\r\n");
return(GCMD::REBOOT);
break;
default:
xil_printf("Unknown client state: %d\r\n", pClientInfo->clientState);
pClientInfo->clientState = STOPCLIENT;
pClientInfo->nextClientState = EXIT;
pClientInfo->tStartClient = tCur;
break;
}
return(GCMD::CONTINUE);
}
/*** bool AddHTMLPage(const char * szMatchStr, FNRENDERHTML FnComposeHTMLPage)
*
* Parameters:
* szMatchStr - A pointer to a constant string; this string MUST exist for the life of the sketch
* typically this is a string stored in flash like -- static const char szHTMLFavicon[] = "GET /favicon.ico "; --
*
* FnComposeHTMLPage - A pointer to the HTML Rendering page, for example: -- GCMD::ACTION ComposeHTMLRestartPage(CLIENTINFO * pClientInfo) --
*
* Return Values:
* true if it was added, false if there was no room to add the page search string
*
* Description:
*
* In the simple case this searchs for HTTP GET commands and matches on the URL and then calls the associated Compose function. It is intentional that GET / is
* part of the match string as this will also allow you to repond to POST. Also, you can do partial matches. For example if you have "GET /filesystem/" as your
* match string, the associated compose function would be called for GET commands like "GET /filesystem/dir1/object.x" because the first part of the string matches.
* This allows you to have some URL call dynamically generated pages like taking a realtime picture, OR you could have another URL access a filesystem by filename.
* The Compose function will get the full input string, so the compose function can independently parse the GET line.
*
*
* ------------------------------------------------------------ */
bool AddHTMLPage(const char * szMatchStr, FNRENDERHTML FnComposeHTMLPage)
{
for(uint32_t i = 0; i < CNTHTTPCMD; i++)
{
if(rgHttpCmd[i].cbMatch == 0)
{
rgHttpCmd[i].szMatchString = szMatchStr;
rgHttpCmd[i].cbMatch = strlen(szMatchStr);
rgHttpCmd[i].ComposeHTMLPage = FnComposeHTMLPage;
return(true);
}
}
return(false);
}
/*** void SetDefaultHTMLPage(FNRENDERHTML FnDefaultHTMLPage)
*
* Parameters:
* FnComposeHTMLPage - A pointer to the HTML Rendering page, for example: -- GCMD::ACTION ComposeHTMLDefaultPage(CLIENTINFO * pClientInfo) --
*
* Return Values:
* None
*
* Description:
*
* If no match strings match, than the default compose HTML page is called. This is optional as the HTTP 404 file not found page
* is initialized as the default page. Function allows you to replace the default.
*
*
* ------------------------------------------------------------ */
void SetDefaultHTMLPage(FNRENDERHTML FnDefaultHTMLPage)
{
DefaultHTMLPage = FnDefaultHTMLPage;
}
/*** GCMD::ACTION JumpToComposeHTMLPage(CLIENTINFO * pClientInfo, FNRENDERHTML FnJumpComposeHTMLPage)
*
* Parameters:
* pClientInfo - a pointer to your current CLIENTINFO structure
* FnJumpComposeHTMLPage - The page compose function you want to jump to
*
* Return Values:
* GCMD::ACTION - GCMD::CONTINUE is returned to start executing in the new compose page
*
* Description:
* You MUST pass your current pClientInfo as this will get processed.
* You MUST be prepared to leave your current compose page; you must be fully cleaned up
* as this compose function will NOT be called again. Cleanup all mutexes as if you
* got a HTTPDISCONNECT state; but your connection is NOT disconnecting, it will
* be used in the jumped to compose page.
*
* ------------------------------------------------------------ */
GCMD::ACTION JumpToComposeHTMLPage(CLIENTINFO * pClientInfo, FNRENDERHTML FnJumpComposeHTMLPage)
{
pClientInfo->htmlState = HTTPSTART;
pClientInfo->ComposeHTMLPage = FnJumpComposeHTMLPage;
return(GCMD::CONTINUE);
}
| [
"tom.kappenman@wsu.edu"
] | tom.kappenman@wsu.edu |
824429cee4c8330dcf833c5cd8e3c8a63bea3b41 | a58ac1d4f118050f758281b72fb51f6fd37d8bd5 | /src/fsync.hpp | f62f90b9848a2da6e81e042a96971cb691609e54 | [
"MIT"
] | permissive | hilbix/mergerfs | cd9264908d478b5a1d801d1a0250ce4f812df0ee | 0165fb24d40c5aa28eadf450df5d40f7c554c52e | refs/heads/master | 2021-01-13T06:49:34.416501 | 2015-12-08T04:57:24 | 2015-12-08T04:57:24 | 47,934,663 | 0 | 0 | null | 2015-12-13T20:15:18 | 2015-12-13T20:15:17 | null | UTF-8 | C++ | false | false | 1,346 | hpp | /*
The MIT License (MIT)
Copyright (c) 2014 Antonio SJ Musumeci <trapexit@spawn.link>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <fuse.h>
namespace mergerfs
{
namespace fuse
{
int
fsync(const char *fusepath,
int isdatasync,
fuse_file_info *fi);
}
}
| [
"trapexit@spawn.link"
] | trapexit@spawn.link |
5ce09bd348593139b714480c538bf1dcb165d861 | 4ec84d397a741bef5d390a638046086577461900 | /game/model/message_processor/message_processor.h | e4c6250e456b5217c3df93a17ed6daa4f585ebb3 | [] | no_license | luchengbiao/xqs_game | 186934d41b10a085650bf45bc0a496fb52d44582 | ce447bb923188a3ae13710033bcb074529a0d2e4 | refs/heads/master | 2020-04-05T06:17:55.699468 | 2019-03-21T10:40:26 | 2019-03-21T10:40:26 | 156,632,557 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,713 | h | #ifndef __GAME_MODEL_MESSAGE_PROCESSOR_MESSAGE_PROCESSOR_H__
#define __GAME_MODEL_MESSAGE_PROCESSOR_MESSAGE_PROCESSOR_H__
#include <stdint.h>
#include <memory>
#include <string>
#include <QObject>
#include "base/framework/observer_list.h"
#include "game/macros.h"
#include "channel_manager/channel_manager_global.h"
#include "protocol/command/base/command_fwd.h"
GAME_NAMESPACE_BEGIN
class MessageProcessor : public QObject
{
Q_OBJECT
using CommandFactoryPtr = std::shared_ptr<proto::CommandFactory>;
public:
class CommandObserver
{
public:
virtual ~CommandObserver() = default;
virtual void OnCommand(const CommandSharedPtr& cmd_ptr, bool sender_is_self) = 0;
};
using CommandObserverList = ObserverList<CommandObserver>;
public:
MessageProcessor(const std::string& msg_channel_account, NetworkServiceType msg_channel_service, const CommandFactoryPtr& cmd_factory);
~MessageProcessor();
MessageProcessor(const MessageProcessor&) = delete;
MessageProcessor& operator=(const MessageProcessor&) = delete;
void AddCommandObserver(CommandObserver*);
void RemoveCommandObserver(CommandObserver*);
private:
bool ChannelMessageIsEncoded() const { return msg_channel_service_ != SWITCH_NETWORK_NETEASE; }
void DecodeMessageIfEncoded(std::string& msg);
void HandleCommandGroup(const proto::CommandGroup& cmd_group, bool sender_is_self);
private slots:
void SlotAgoraMessageChannel(std::string channel_id, std::string account, uint32_t uid, std::string msg);
private:
std::string msg_channel_account_;
NetworkServiceType msg_channel_service_{ SWITCH_NETWORK_AGORA };
CommandFactoryPtr cmd_factory_;
CommandObserverList cmd_observers_;
};
GAME_NAMESPACE_END
#endif | [
"993925668@qq.com"
] | 993925668@qq.com |
275f4010861020409695a95f979e876e1f5fb323 | e8ab6a8108801dfedb694557626fd847651564e2 | /Dragon/include/operators/arithmetic/mul_op.h | 395b1d58ae91d1c057e426b4d3bd786acdbf0d51 | [
"BSD-2-Clause"
] | permissive | Spark001/Dragon-1 | 87f722bcb0feaec7fad29d923c60681cf9584267 | 310bcb5f6d9a6623bb58ed3d1ad02d1f440da474 | refs/heads/master | 2020-03-09T22:52:08.171500 | 2018-04-01T10:13:50 | 2018-04-01T10:13:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,108 | h | // ------------------------------------------------------------
// Copyright (c) 2017-preseent, SeetaTech, Co.,Ltd.
//
// Licensed under the BSD 2-Clause License.
// You should have received a copy of the BSD 2-Clause License
// along with the software. If not, See,
//
// <https://opensource.org/licenses/BSD-2-Clause>
//
// ------------------------------------------------------------
#ifndef DRAGON_OPERATORS_ARITHMETIC_MUL_OP_H_
#define DRAGON_OPERATORS_ARITHMETIC_MUL_OP_H_
#include "core/operator.h"
namespace dragon {
template <class Context>
class MulOp final : public Operator<Context> {
public:
USE_SIMPLE_CTOR_DTOR(MulOp);
USE_OPERATOR_FUNCTIONS(Context);
void RunOnDevice() override;
template <typename T> void EltwiseRunWithType();
template <typename T> void BroadcastRunWithType(int type);
protected:
Tensor* bcast_multiplier;
};
template <class Context>
class MulGradientOp final : public Operator<Context> {
public:
USE_SIMPLE_CTOR_DTOR(MulGradientOp);
USE_OPERATOR_FUNCTIONS(Context);
void ShareGradient() override;
void RunOnDevice() override;
template <typename T> void EltwiseRunWithType();
template <typename T> void BroadcastRunWithType(int type);
protected:
Tensor* bcast_multiplier;
};
template <class Context>
class RMulOp final : public Operator<Context> {
public:
USE_SIMPLE_CTOR_DTOR(RMulOp);
USE_OPERATOR_FUNCTIONS(Context);
void RunOnDevice() override;
template <typename T> void EltwiseRunWithType();
template <typename T> void BroadcastRunWithType(int type);
protected:
Tensor* bcast_multiplier;
};
template <class Context>
class RMulGradientOp final : public Operator<Context> {
public:
USE_SIMPLE_CTOR_DTOR(RMulGradientOp);
USE_OPERATOR_FUNCTIONS(Context);
void ShareGradient() override;
void RunOnDevice() override;
template <typename T> void EltwiseRunWithType();
template <typename T> void BroadcastRunWithType(int type);
protected:
Tensor* bcast_multiplier;
};
} // namespace dragon
#endif // DRAGON_OPERATORS_ARITHMETIC_MUL_OP_H_ | [
"ting.pan@seetatech.com"
] | ting.pan@seetatech.com |
738864566d92b9a12f711be5579328f925b9608b | 19765034e3c1e8968b4108c621e39b5bd509675e | /nuevo/automata-01pares/main.cpp | 176329ca660dee3e750d9c63f39eff325a745102 | [] | no_license | marco-gallegos/estructura-de-datos-2 | e30086c2606c033187cad24d8b46053598a1b0d5 | e85589705c1dbed4f7cc9728991407fc94b68780 | refs/heads/master | 2022-07-06T16:51:13.937772 | 2022-06-24T08:52:07 | 2022-06-24T08:52:07 | 32,251,992 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,187 | cpp | #include <QCoreApplication>
#include<iostream>
using namespace std;
// automata finito determinista que reconoce ceros y unos pares.
int tipoSimbolo(char c); //funcion para regresar el tipo de simbolo
int main()
{
//QCoreApplication a(argc, argv);
int matriz [][3]={//matriz de transiciones
{2,1,4},//q0
{3,0,4},//q1
{0,3,4},//q2
{1,2,4},//q3
{4,4,4}//q4
};
int estado;
string cadena;
while (1) {
cout<<"AFD para reconocer palabras de la forma {w|w tiene cantidad par de 0's y 1's'}"<<endl;
cout<<"ingresa la palabra -> ";
getline(cin,cadena);
estado =0;
for (unsigned int i = 0; i < cadena.length(); ++i) {
estado = matriz[estado][tipoSimbolo(cadena.at(i))];
if(estado == 4)
{
break;
}
}
if(estado == 0)
{
cout<<"la cadena es valida"<<endl<<endl;
}
else
{
cout<<"la cadena es invalida"<<endl<<endl;
}
}
return 1;//a.exec();
}
int tipoSimbolo(char c)
{
if(c == '0')
{
return 0;
}
else if(c == '1')
{
return 1;
}
else
{
return 4;
}
}
| [
"ma_galeza@hotmail.com"
] | ma_galeza@hotmail.com |
ca8a006d7dbed76702828783db00a35317d6f5e6 | 1763177bd131827bb6e2c8377fd429dca1d30f02 | /pathmet/firmware/source/pc.hpp | 76b8e030c48c8295cc7fe0b49c07944b9e4cd78d | [] | no_license | pathVu/pathmetarcgis | 79d3cd66aeefb30b457eac656299c8e923262499 | ec48e834a2e13de4af2ad3a31ef7a660a5a49a18 | refs/heads/master | 2023-03-16T06:16:32.945099 | 2021-03-11T17:51:26 | 2021-03-11T17:51:26 | 267,865,641 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,197 | hpp | #pragma once
#include <cstdint>
#include "circular_buffer.hpp"
extern "C" void pc_on_rx(const uint8_t*, uint32_t);
extern "C" uint32_t pc_tx_pending(void);
extern "C" void pc_get_tx(uint8_t* data, uint32_t size);
class PC {
public:
PC();
void init();
void update();
void write(const uint8_t* data, size_t size);
private:
friend void pc_on_rx(const uint8_t*, uint32_t);
friend uint32_t pc_tx_pending(void);
friend void pc_get_tx(uint8_t*, uint32_t);
/* interface to USB VCOM */
void on_rx(const uint8_t* data, uint32_t size);
uint32_t tx_pending();
void get_tx(uint8_t* data, uint32_t size);
pa::circular_buffer<uint8_t, 256> tx_buffer;
pa::circular_buffer<uint8_t, 256> rx_buffer;
enum class RxState {
wait_for_start_delimiter,
read_length,
read_command,
read_data,
read_end_delimiter
};
enum class Command : uint8_t {
start = 0x53
};
static const uint8_t start_delimiter = 0x01;
static const uint8_t end_delimiter = 0x04;
RxState rx_state_;
uint8_t message_length_;
uint8_t message_command_;
uint8_t message_index_;
};
extern PC pc;
| [
"cjr105@case.edu"
] | cjr105@case.edu |
e1f8ad89e29e2b00c2733d0764fcea9c099022ca | 8730ff90ba4d16476f8c2da6de34d8e8817bd5b4 | /OOP345/W3_Class Templates/345_w3.cpp | 20627c4d7476a0f30bee75bda1bc1a7ab753252d | [] | no_license | muratbir/Seneca_College | 1d0da9c3845426dd761e510fe942c0d0c97add19 | b8f718123dbc9915a17c03821a2a10ec26136ace | refs/heads/master | 2020-08-01T11:10:23.163943 | 2019-04-17T21:37:59 | 2019-04-17T21:37:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,726 | cpp | // Workshop 3 - Class Templates
// 345_w3.cpp
// Chris Szalwinski
// 2018.05.17
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
#include "KVList.h"
//#define CONSOLE
#ifndef CONSOLE
#define SOURCE input
#else
#define SOURCE std::cin
#endif
// display list of key-value pairs
//
template <typename K, typename V, int N>
void display(const std::string& msg, const KVList<K, V, N>& list, int w) {
std::cout << msg;
for (size_t i = 0; i < list.size(); i++)
std::cout << std::setw(w) << list.key(i)
<< " : " << list.value(i) << std::endl;
}
// prompt for user input
//
void prompt(const char* str) {
#ifndef CONSOLE
std::cout << ". ";
#else
std::cout << str;
#endif
}
int main(int argc, char** argv) {
std::cout << "Command Line : ";
for (int i = 0; i < argc; i++) {
std::cout << argv[i] << ' ';
}
std::cout << std::endl;
#ifndef CONSOLE
if (argc == 1) {
std::cerr << "\n*** Insufficient number of arguments ***\n";
std::cerr << "Usage: " << argv[0] << " fileName \n";
return 1;
}
else if (argc != 2) {
std::cerr << "\n*** Too many arguments ***\n";
std::cerr << "Usage: " << argv[0] << " fileName \n";
return 2;
}
std::ifstream input(argv[1]);
if (!input) {
std::cerr << "*** Failed to open file " << argv[1] << " successfully ***\n";
return 3;
}
#endif
bool keepreading;
std::cout << std::fixed << std::setprecision(2);
std::cout << "\nInventory\n=========\n";
KVList <std::string, double, 5> inventory;
std::string str;
double price;
keepreading = true;
do {
prompt("Product : ");
getline(SOURCE, str);
if (str.compare("quit") == 0) {
keepreading = false;
}
else {
prompt("Price : ");
SOURCE >> price;
SOURCE.ignore();
inventory.add(str, price);
}
} while (keepreading);
display("\nPrice List\n-----------\n", inventory, 13);
std::cout << "\nCorrections\n-----------\n";
keepreading = true;
do {
prompt("Product : ");
getline(SOURCE, str);
if (str.compare("quit") == 0) {
keepreading = false;
}
else {
int i = inventory.find(str);
if (i != -1) {
prompt("Price : ");
SOURCE >> price;
SOURCE.ignore();
inventory.replace(i, str, price);
}
}
} while (keepreading);
display("\nPrice List\n-----------\n", inventory, 13);
std::cout << "\nGlossary\n========\n";
KVList <std::string, std::string, 5> glossary;
std::string key, definition;
keepreading = true;
do {
prompt("Key : ");
getline(SOURCE, key);
if (key.compare("quit") == 0) {
keepreading = false;
}
else {
prompt("Definition : ");
getline(SOURCE, definition);
glossary.add(key, definition);
}
} while (keepreading);
display("\nEntries\n-------\n", glossary, 5);
} | [
"nickyoon89@gmail.com"
] | nickyoon89@gmail.com |
acb1c79617ba4d2a9f928ef6efb7b0951d68fff2 | 4efd3bf53b563d06d98a5938fea0f9d758b006ad | /src/SynthLib2ParserExceptions.cpp | 0d44c8b0855d0ac662b649f885c2cdf836a81187 | [
"BSD-2-Clause"
] | permissive | sygus-tools/synthlib2parser | 7004903eec704138568b749414d2e0b8a5a0f3bd | a1e409024d7c9d64b5e986c9ef34242005c68250 | refs/heads/master | 2020-07-15T00:19:27.233199 | 2017-07-03T09:15:52 | 2017-07-03T09:15:52 | 94,301,766 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,271 | cpp | // SynthLib2ParserExceptions.cpp ---
//
// Filename: SynthLib2ParserExceptions.cpp
// Author: Abhishek Udupa
// Created: Sat Jan 18 16:42:40 2014 (-0500)
//
//
// Copyright (c) 2013, Abhishek Udupa, University of Pennsylvania
// 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.
// 3. All advertising materials mentioning features or use of this software
// must display the following acknowledgement:
// This product includes software developed by The University of Pennsylvania
// 4. Neither the name of the University of Pennsylvania nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.
//
//
// Code:
#include "include/SynthLib2ParserExceptions.hpp"
using namespace std;
namespace SynthLib2Parser {
SynthLib2ParserException::SynthLib2ParserException()
: ExceptionInfo("Unspecified")
{
// Nothing here
}
SynthLib2ParserException::SynthLib2ParserException(const string& ExceptionInfo)
: ExceptionInfo(ExceptionInfo)
{
// Nothing here
}
SynthLib2ParserException::~SynthLib2ParserException() noexcept (true)
{
// Nothing here
}
const char* SynthLib2ParserException::what() const throw()
{
return ExceptionInfo.c_str();
}
MalformedLiteralException::MalformedLiteralException(const string& LiteralString,
const string& Suffix)
{
ostringstream sstr;
sstr << "The literal \"" << LiteralString << "\" is malformed" << endl;
sstr << "Details: " << Suffix;
ExceptionInfo = sstr.str();
}
MalformedLiteralException::~MalformedLiteralException() noexcept (true)
{
// Nothing here
}
ostream& operator << (ostream& str, const SynthLib2ParserException& Exc)
{
str << Exc.what();
return str;
}
} /* End namespace */
//
// SynthLib2ParserExceptions.cpp ends here
| [
"ammarbenkhadra@gmail.com"
] | ammarbenkhadra@gmail.com |
d8ff64d8a35a2a3b012b947ef940caf2bcd9ad74 | 98ef9f82f45320df070f670eac258c8365113642 | /nowcoder/剑指offer/和为s的两个数.cc | 463c49195bf09011126b28db94a1e86c0135ffc6 | [] | no_license | FrankWork/LeetCode | abbf6125b57e143073f89daf5cbcbd8ff67bb78b | 6ec0c0d43cf4e8ef968051a4d125c4965d58e4f5 | refs/heads/master | 2021-01-22T07:27:43.963950 | 2018-11-12T08:44:18 | 2018-11-12T08:44:18 | 39,978,490 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 562 | cc | #include <iostream>
#include <vector>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<int> FindNumbersWithSum(vector<int> &nums,int sum) {
int l=0,r=nums.size()-1;
vector<int> res;
while(l<r){
int t=nums[l]+nums[r];
if(t==sum){
res.push_back(nums[l]);
res.push_back(nums[r]);
return res;
}else if(t<sum){
++l;
}else{
--r;
}
}
return res;
}
}; | [
"lzh00776@163.com"
] | lzh00776@163.com |
ea0529d8fa404e5568bbc788a930e7ea91bd550c | e59209be58bde8224b287a36d9a55b6c4adeac8c | /A_Perfectly_Imperfect_Array.cpp | 94215bc4efa8b5edf44329bc967b84bd540f2b0e | [] | no_license | believe-that-23/random-practise | 133379758a94408f5b1e4951cdfac302f2bd3d87 | c708e511c44d42b113fcc8b3fd6008942835e081 | refs/heads/main | 2023-05-03T00:35:01.536271 | 2021-05-28T13:32:05 | 2021-05-28T13:32:05 | 371,705,852 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,410 | cpp | #include <bits/stdc++.h>
#include <cmath>
#include <regex>
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define ll long long
#define all(x) (x).begin(),(x).end()
#define vll vector<long long int>
#define FAST ios_base :: sync_with_stdio (false); cin.tie (NULL)
using namespace std;
#define endl "\n"
ll C(ll n, ll k) {
double res = 1;
for (int i = 1; i <= k; ++i)
res = res * (n - k + i) / i;
return (ll)(res + 0.01);
}
vector<vll> readGraph(ll n,ll m){
vector<vll> g(n);
for(ll i=0;i<m;i++){
ll a,b;
cin>>a>>b;
//sc.read(a,b);
//a--;b--;
g[a].pb(b);
g[b].pb(a);
}
return g;
}
vector<vll> readTree(int n){
return readGraph(n,n-1);
}
//----------------------------------------------------------------------------
bool check(ll n){
ll temp=sqrt(n);
while(temp*temp>n)temp--;
while(temp*temp<n)temp++;
if(temp*temp==n){
return true;
}
return false;
}
void solve()
{
ll n;
cin>>n;
vll a(n);
for(ll i=0;i<n;i++)cin>>a[i];
bool flag =false;
for(ll i=0;i<n;i++){
if(!check(a[i])){
flag=true;
break;
}
}
if(flag==false)cout<<"NO"<<endl;
else cout<<"YES"<<endl;
}
int main() {
FAST;
ll t;
cin>>t;
while(t--){
solve();
}
return 0;
} | [
"noreply@github.com"
] | believe-that-23.noreply@github.com |
6cf8759f99479d0502629df24bada59371f70329 | 907ed11cf4d9b01483a31b582dd1fc9e739d5801 | /include/donutbreakdownchart.h | 1b4162703da3ab3034f5e936912b25e45e75d240 | [] | no_license | YmiR1710/BachelorWork | beacc265a102f345e47f1b99e481c3157bac712c | ae7449196a79c1cca9ae72e2d16f3c254fa55a1d | refs/heads/master | 2023-04-30T07:44:33.034982 | 2021-06-01T07:41:26 | 2021-06-01T07:41:26 | 337,137,522 | 0 | 0 | null | 2021-04-10T09:40:36 | 2021-02-08T16:29:06 | C++ | UTF-8 | C++ | false | false | 485 | h | #ifndef DONUTBREAKDOWNCHART_H
#define DONUTBREAKDOWNCHART_H
#include <QtCharts/QChart>
#include <QtCharts/QPieSeries>
QT_CHARTS_USE_NAMESPACE
class DonutBreakdownChart : public QChart
{
Q_OBJECT
public:
DonutBreakdownChart(QGraphicsItem *parent = nullptr, Qt::WindowFlags wFlags = {});
void addBreakdownSeries(QPieSeries *series, QColor color);
private:
void recalculateAngles() const;
void updateLegendMarkers() const;
QPieSeries *m_mainSeries;
};
#endif
| [
"volianskyi@ucu.edu.ua"
] | volianskyi@ucu.edu.ua |
4f82b2e7cb0c29608f1433c6d267f4f3355501e1 | e1402bc56b5eba90bcdd956a04f5571d89a7d100 | /skgrader/maxflow.cxx | 43c7076893fdb80bf626c60d12e64701615c04bc | [] | no_license | markverick/ioi-training | 5dc9248ad394de0272abafb54d52d90c5073fb27 | 57a15aa332a908b6044a8cb90b3c0b660ff13ae4 | refs/heads/master | 2018-12-13T01:28:01.326534 | 2018-10-23T18:26:04 | 2018-10-23T18:26:04 | 148,653,348 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,416 | cxx | #include<bits/stdc++.h>
#define X first
#define Y second
#define MP make_pair
#define EB emplace_back
#define MI 1000000000
using namespace std;
vector<int> adj[50135];
int s,t,n;
int state[50135];
int hsh[50135],result[50135];
vector<pair<int,int> > v;
inline void dfs(int idx,int cot,int p,int mul)
{
int i;
if(idx==t)
{
for(i=1;i<cot;i++)
{
hsh[result[i]]+=mul;
}
return;
}
state[idx]=1;
for(i=0;i<adj[idx].size();i++)
{
if(p==adj[idx][i])
continue;
result[cot]=adj[idx][i];
dfs(adj[idx][i],cot+1,idx,mul);
}
}
int main()
{
// freopen("maxflow.in","r",stdin);
// freopen("maxflow.out","w",stdout);
int i,j,k;
int m,a,b;
scanf("%d %d",&n,&m);
for(i=1;i<n;i++)
{
scanf("%d %d",&a,&b);
adj[a].EB(b);
adj[b].EB(a);
}
for(i=1;i<=m;i++)
{
scanf("%d %d",&s,&t);
v.emplace_back(min(s,t),max(s,t));
}
sort(v.begin(),v.end());
int cot=1;
for(i=0;i<m;i++)
{
if(i==0||(v[i-1]!=v[i]) )
{
dfs(s,1,0,cot);
hsh[s]+=cot;
cot=1;
}
else
{
cot++;
}
}
int mc=0;
for(i=1;i<=n;i++)
{
mc=max(mc,hsh[i]);
}
printf("%d",mc);
}
| [
"sirapop741@gmail.com"
] | sirapop741@gmail.com |
7f1eb5d6903b82883f90e5c0b9fd33bd6e69f481 | 4130b36e09feb24f16bdbbc1fa3e1d6659c0d439 | /congcongclient/Classes/ClientHN_THJ/Game/MENJI/Setting/TLJSettingPanel.h | 573b82f7e119e1d5240753b0752ef0ea1b85d526 | [
"MIT"
] | permissive | cnceo/18_TTL | b48eaf46f93b289047769a89bbdb749c14720a42 | c8fc3fe7b7a0acad2b2cb5e80e96219b6257f0e4 | refs/heads/master | 2020-04-09T04:01:14.354570 | 2018-12-01T06:44:23 | 2018-12-01T06:44:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 752 | h | #pragma once
#include "CommonHeader/CommonHeader.h"
#include "GUI/CCControlExtension/CCControl.h"
#include "SimpleAudioEngine.h"
#include "Game/Script/SoundFun.h"
USING_NS_CC_EXT;
class TLJSettingPanel
: public cocos2d::Node
, public FvSingleton<TLJSettingPanel>
{
public:
TLJSettingPanel();
~TLJSettingPanel();
bool init();
void initButton();
void show();
void hide();
void Button_ChangeAccount(cocos2d::Ref*, WidgetUserInfo*);
void Button_Close(cocos2d::Ref*, WidgetUserInfo*);
void Slider_Sound(cocos2d::Ref* ref, cocos2d::extension::Control::EventType eventType);
void Slider_Effect(cocos2d::Ref* ref, cocos2d::extension::Control::EventType eventType);
private:
ControlSlider* m_SoundSlider;
ControlSlider* m_EffectSlider;
};
| [
"taotingfu819@163.com"
] | taotingfu819@163.com |
ab2ff198ba858ac5148f30d91b4873afed2c1081 | 1dbf007249acad6038d2aaa1751cbde7e7842c53 | /cdn/include/huaweicloud/cdn/v1/model/CreateDomainResponseBodyContent.h | b43487ca7ac9481e6648218291e7981de8579dbf | [] | permissive | huaweicloud/huaweicloud-sdk-cpp-v3 | 24fc8d93c922598376bdb7d009e12378dff5dd20 | 71674f4afbb0cd5950f880ec516cfabcde71afe4 | refs/heads/master | 2023-08-04T19:37:47.187698 | 2023-08-03T08:25:43 | 2023-08-03T08:25:43 | 324,328,641 | 11 | 10 | Apache-2.0 | 2021-06-24T07:25:26 | 2020-12-25T09:11:43 | C++ | UTF-8 | C++ | false | false | 7,041 | h |
#ifndef HUAWEICLOUD_SDK_CDN_V1_MODEL_CreateDomainResponseBodyContent_H_
#define HUAWEICLOUD_SDK_CDN_V1_MODEL_CreateDomainResponseBodyContent_H_
#include <huaweicloud/cdn/v1/CdnExport.h>
#include <huaweicloud/core/utils/ModelBase.h>
#include <huaweicloud/core/http/HttpResponse.h>
#include <huaweicloud/cdn/v1/model/Sources.h>
#include <huaweicloud/cdn/v1/model/DomainOriginHost.h>
#include <string>
#include <vector>
namespace HuaweiCloud {
namespace Sdk {
namespace Cdn {
namespace V1 {
namespace Model {
using namespace HuaweiCloud::Sdk::Core::Utils;
using namespace HuaweiCloud::Sdk::Core::Http;
/// <summary>
/// 创建域名返回信息。
/// </summary>
class HUAWEICLOUD_CDN_V1_EXPORT CreateDomainResponseBodyContent
: public ModelBase
{
public:
CreateDomainResponseBodyContent();
virtual ~CreateDomainResponseBodyContent();
/////////////////////////////////////////////
/// ModelBase overrides
void validate() override;
web::json::value toJson() const override;
bool fromJson(const web::json::value& json) override;
/////////////////////////////////////////////
/// CreateDomainResponseBodyContent members
/// <summary>
/// 加速域名ID。
/// </summary>
std::string getId() const;
bool idIsSet() const;
void unsetid();
void setId(const std::string& value);
/// <summary>
/// 加速域名。
/// </summary>
std::string getDomainName() const;
bool domainNameIsSet() const;
void unsetdomainName();
void setDomainName(const std::string& value);
/// <summary>
/// 域名业务类型: - web:网站加速; - download:文件下载加速; - video:点播加速; - wholeSite:全站加速。
/// </summary>
std::string getBusinessType() const;
bool businessTypeIsSet() const;
void unsetbusinessType();
void setBusinessType(const std::string& value);
/// <summary>
/// 域名服务范围,若为mainland_china,则表示服务范围为中国大陆;若为outside_mainland_china,则表示服务范围为中国大陆境外;若为global,则表示服务范围为全球。
/// </summary>
std::string getServiceArea() const;
bool serviceAreaIsSet() const;
void unsetserviceArea();
void setServiceArea(const std::string& value);
/// <summary>
/// 域名所属用户的domain_id。
/// </summary>
std::string getUserDomainId() const;
bool userDomainIdIsSet() const;
void unsetuserDomainId();
void setUserDomainId(const std::string& value);
/// <summary>
/// 加速域名状态。取值意义: - online表示“已开启” - offline表示“已停用” - configuring表示“配置中” - configure_failed表示“配置失败” - checking表示“审核中” - check_failed表示“审核未通过” - deleting表示“删除中”。
/// </summary>
std::string getDomainStatus() const;
bool domainStatusIsSet() const;
void unsetdomainStatus();
void setDomainStatus(const std::string& value);
/// <summary>
/// 加速域名对应的CNAME。
/// </summary>
std::string getCname() const;
bool cnameIsSet() const;
void unsetcname();
void setCname(const std::string& value);
/// <summary>
/// 源站信息。
/// </summary>
std::vector<Sources>& getSources();
bool sourcesIsSet() const;
void unsetsources();
void setSources(const std::vector<Sources>& value);
/// <summary>
///
/// </summary>
DomainOriginHost getDomainOriginHost() const;
bool domainOriginHostIsSet() const;
void unsetdomainOriginHost();
void setDomainOriginHost(const DomainOriginHost& value);
/// <summary>
/// 是否开启HTTPS加速。
/// </summary>
int32_t getHttpsStatus() const;
bool httpsStatusIsSet() const;
void unsethttpsStatus();
void setHttpsStatus(int32_t value);
/// <summary>
/// 域名创建时间,相对于UTC 1970-01-01到当前时间相隔的毫秒数。
/// </summary>
int64_t getCreateTime() const;
bool createTimeIsSet() const;
void unsetcreateTime();
void setCreateTime(int64_t value);
/// <summary>
/// 域名修改时间,相对于UTC 1970-01-01到当前时间相隔的毫秒数。
/// </summary>
int64_t getModifyTime() const;
bool modifyTimeIsSet() const;
void unsetmodifyTime();
void setModifyTime(int64_t value);
/// <summary>
/// 封禁状态(0代表未禁用;1代表禁用)。
/// </summary>
int32_t getDisabled() const;
bool disabledIsSet() const;
void unsetdisabled();
void setDisabled(int32_t value);
/// <summary>
/// 锁定状态(0代表未锁定;1代表锁定)。
/// </summary>
int32_t getLocked() const;
bool lockedIsSet() const;
void unsetlocked();
void setLocked(int32_t value);
/// <summary>
/// range状态,off:关闭,on:开启。
/// </summary>
std::string getRangeStatus() const;
bool rangeStatusIsSet() const;
void unsetrangeStatus();
void setRangeStatus(const std::string& value);
/// <summary>
/// follow302状态,off:关闭,on:开启。
/// </summary>
std::string getFollowStatus() const;
bool followStatusIsSet() const;
void unsetfollowStatus();
void setFollowStatus(const std::string& value);
/// <summary>
/// 是否暂停源站回源(off代表关闭 on代表开启)。
/// </summary>
std::string getOriginStatus() const;
bool originStatusIsSet() const;
void unsetoriginStatus();
void setOriginStatus(const std::string& value);
/// <summary>
/// 自动刷新预热(0代表关闭;1代表打开)。
/// </summary>
int32_t getAutoRefreshPreheat() const;
bool autoRefreshPreheatIsSet() const;
void unsetautoRefreshPreheat();
void setAutoRefreshPreheat(int32_t value);
protected:
std::string id_;
bool idIsSet_;
std::string domainName_;
bool domainNameIsSet_;
std::string businessType_;
bool businessTypeIsSet_;
std::string serviceArea_;
bool serviceAreaIsSet_;
std::string userDomainId_;
bool userDomainIdIsSet_;
std::string domainStatus_;
bool domainStatusIsSet_;
std::string cname_;
bool cnameIsSet_;
std::vector<Sources> sources_;
bool sourcesIsSet_;
DomainOriginHost domainOriginHost_;
bool domainOriginHostIsSet_;
int32_t httpsStatus_;
bool httpsStatusIsSet_;
int64_t createTime_;
bool createTimeIsSet_;
int64_t modifyTime_;
bool modifyTimeIsSet_;
int32_t disabled_;
bool disabledIsSet_;
int32_t locked_;
bool lockedIsSet_;
std::string rangeStatus_;
bool rangeStatusIsSet_;
std::string followStatus_;
bool followStatusIsSet_;
std::string originStatus_;
bool originStatusIsSet_;
int32_t autoRefreshPreheat_;
bool autoRefreshPreheatIsSet_;
};
}
}
}
}
}
#endif // HUAWEICLOUD_SDK_CDN_V1_MODEL_CreateDomainResponseBodyContent_H_
| [
"hwcloudsdk@huawei.com"
] | hwcloudsdk@huawei.com |
e1fd04e20dc1b10808c6f81fdb6131150365118a | 9e4a00de1ec07e7e88872ef60c42a49bf65dc2b0 | /Code/Libraries/Audio/src/soloudaudiosystem.h | 906a0b9468f16f3c257eafb887e9076749ae976a | [
"Zlib"
] | permissive | ptitSeb/Eldritch | 6a5201949b13f6cd95d3d75928e375bdf785ffca | 3cd6831a4eebb11babec831e2fc59361411ad57f | refs/heads/master | 2021-07-10T18:45:05.892756 | 2021-04-25T14:16:19 | 2021-04-25T14:16:19 | 39,091,718 | 6 | 4 | NOASSERTION | 2021-04-25T14:16:20 | 2015-07-14T18:03:07 | C | UTF-8 | C++ | false | false | 2,705 | h | #ifndef SOLOUDAUDIOSYSTEM_H
#define SOLOUDAUDIOSYSTEM_H
#include "audiosystemcommon.h"
#include "map.h"
#include "set.h"
#include "list.h"
#include "hashedstring.h"
#include "array.h"
#include "interpolator.h"
#include "simplestring.h"
#include "soloud.h"
#include "soloud_echofilter.h"
struct SoLoudPropCache
{
SoLoudPropCache()
: m_Channels( 0 )
, m_SampleRate( 0.0f )
, m_SampleCount( 0 )
{
}
uint m_Channels;
float m_SampleRate;
uint m_SampleCount;
};
class SoLoudAudioSystem : public AudioSystemCommon
{
public:
SoLoudAudioSystem();
virtual ~SoLoudAudioSystem();
virtual void Tick( const float DeltaTime, bool GamePaused );
virtual ISound* CreateSound( const SSoundInit& SoundInit );
virtual ISoundInstance* Play( const SimpleString& DefinitionName, const Vector& Location );
virtual void SetReverbParams( const SimpleString& DefinitionName ) const;
virtual void ConditionalApplyReverb( ISoundInstance* const pSoundInstance ) const { Unused( pSoundInstance ); /*not needed for SoLoud, all done with buses*/ }
#if BUILD_DEV
virtual void ReverbTest_Toggle();
virtual void ReverbTest_Update();
virtual bool ReverbTest_IsActive() const;
virtual void ReverbTest_Print() const;
virtual void ReverbTest_Export() const;
virtual void ReverbTest_PrevSetting();
virtual void ReverbTest_NextSetting();
virtual void ReverbTest_IncrementSetting( const float Scalar );
virtual void ReverbTest_DecrementSetting( const float Scalar );
#endif
SoLoud::Soloud* GetSoLoudEngine() const { return m_SoLoudEngine; }
SoLoud::Bus* GetSoLoudEchoBus() const { return m_SoLoudEchoBus; }
bool IsReverbCategory( const HashedString& Category ) const { return m_ReverbCategories.Find( Category ); }
const SoLoudPropCache* GetPropCache( const HashedString& Filename ) const;
void SetPropCache( const HashedString& Filename, const SoLoudPropCache& PropCache );
private:
void ApplyReverb( const float EchoTime, const float DecayTime, const float LowPassFilter, const float WetDryMix ) const;
SoLoud::Soloud* m_SoLoudEngine;
SoLoud::Bus* m_SoLoudEchoBus;
SoLoud::EchoFilter* m_SoLoudEchoFilter;
SoLoud::handle m_SoLoudEchoBusHandle;
SimpleString m_DefaultReverb;
Array<HashedString> m_ReverbCategories; // Categories that has teh reverbs (probably generally the same as pause)
// Optimization for SoLoud to bypass stb_vorbis_stream_length_in_samples each time a file is reopened
Map<HashedString, SoLoudPropCache> m_PropCache;
#if BUILD_DEV
bool m_ReverbTest_IsActive;
uint m_ReverbTest_SettingIndex;
#endif
};
#endif // SOLOUDAUDIOSYSTEM_H | [
"rajdakin@gmail.com"
] | rajdakin@gmail.com |
b7579e4cad8fbd259e5d5ee0cb9b61d6f66fb2a0 | 99cfd2020e2984f2d463978b5a134a2f1081d094 | /shashank/prime_till_n.cpp | f7350454f60dfaa406fb4b2ff0254e4b33954b5c | [
"MIT"
] | permissive | sekharkaredla/Cpp_Programs | 5e33ff5ee7a15fa6582d7d9319a78b3c19071b2a | e026d3322da5913e327033cb5d4787665998aef3 | refs/heads/master | 2021-05-09T07:07:51.674806 | 2018-01-29T08:12:23 | 2018-01-29T08:12:23 | 119,348,800 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 768 | cpp | #include<iostream>
using namespace std;
class num
{
int n,i,r,j,flag;
public:
void getdata()
{
cout<<"enter a number :";
cin>>n;
}
void loop()
{
for(i=1;i<=n;i++)
if(prime(i)==1)
cout<<" "<<i;
}
int prime(int i)
{flag=1;
for(j=2;j<i;j++)
{
if(i%j==0)
{
flag=0;break;
}
return flag;
}
}
};
int main()
{
num s;
s.getdata();
s.loop();
return 1;
} | [
"sekhar.karedla@gmail.com"
] | sekhar.karedla@gmail.com |
baa4a7b7aed99f3503fdbb87f14ea0cec2d195dd | 64c6a76143ee2cbef6568865c032805d1536da60 | /sources/Bitmap.h | 78acaa8f01497a097b7895eb92b7379b4c326937 | [] | no_license | HaikuArchives/DwarfEngine | 5a6c2a2fbf7ff00191b26a261be146c7b21934ae | 51d772c23fba96c335a0de95c6dd40a3daa1ed28 | refs/heads/master | 2021-05-07T15:35:25.346098 | 2017-11-08T21:26:09 | 2017-11-08T21:26:09 | 110,032,368 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,159 | h | #ifndef D_BITMAP_H_
#define D_BITMAP_H_
/*
* The Dwarf Engine 3D Library
* copyright (c) 2000
*
* #include <license.txt>
*
*/
#include "Defs.h"
#include "Array.h"
#include "String.h"
#include "Buffer.h"
#include "Serializable.h"
#ifdef WIN32
// IGNORE is defined in winbase.h
#undef IGNORE
#endif
namespace dwarf
{
class File;
class FileSystem;
class String;
class Bitmap;
/*!
\brief This class has not been fully documented yet.
\todo document Bitmap.
*/
class Bitmap : public Serializable
{
public:
enum ResizeMode
{
IGNORE = 0, //!< Ignores the bitmap, after the resize the bitmap will contain undefined data
CROP, //!< The bitmap will be cropped or the extended areas will be filled with the color black (no rescaling at all)
SCALE //!< The bitmap will be scaled to match the new size
};
enum ColorSpace
{
STENCIL_INDEX = 0,
DEPTH_COMPONENT,
RED,
GREEN,
BLUE,
ALPHA,
RGB,
RGBA,
GRAYSCALE,
GRAYSCALE_ALPHA,
BGR,
BGRA
};
Bitmap();
// Bitmap(const File &image);
// Bitmap(int32 width, int32 height, dwarf::core::Bitmap::ColorSpace space = RGB);
Bitmap(FileSystem* dir, String const& name);
Bitmap(int32 width, int32 height, ColorSpace space = RGB);
Bitmap(const Array<uint8> &bitmap,int32 width,int32 height,ColorSpace space = RGB);
Bitmap(const uint8 *bitmap,int32 width,int32 height,ColorSpace space = RGB);
virtual ~Bitmap();
int32 Width() const;
int32 Height() const;
uint8* Data() const;
int32 DataSize() const;
ColorSpace Space() const;
void SetSpace(Bitmap::ColorSpace space, bool convert);
void SetSize(int32 width, int32 height, Bitmap::ColorSpace space);
void SetSize(int32 width, int32 height, Bitmap::ResizeMode mode = IGNORE);
uint8 BytesPerPixel() const;
void PrintToLog() const;
virtual void Restore(InStream& buffer);
virtual void Serialize(OutStream& buffer) const;
private:
uint8 BytesPerPixel(Bitmap::ColorSpace space) const;
int32 m_width;
int32 m_height;
ColorSpace m_color_space;
Array<uint8> m_buffer;
};
// inline definitions
inline uint8 Bitmap::BytesPerPixel() const
{
return BytesPerPixel(m_color_space);
}
inline Bitmap::Bitmap():
m_width(0),
m_height(0),
m_color_space(RGB),
m_buffer(0)
{
}
inline Bitmap::Bitmap(int32 width, int32 height, Bitmap::ColorSpace space):
m_width(width),
m_height(height),
m_color_space(space),
m_buffer(m_width * m_height * BytesPerPixel())
{
}
inline int32 Bitmap::Width() const
{
return m_width;
}
inline int32 Bitmap::Height() const
{
return m_height;
}
inline uint8* Bitmap::Data() const
{
return *m_buffer;
}
inline int32 Bitmap::DataSize() const
{
return m_buffer.Length();
}
inline Bitmap::ColorSpace Bitmap::Space() const
{
return m_color_space;
}
inline void Bitmap::PrintToLog() const
{
logger(TEXT("Bitmap: m_width: %d m_height: %d m_bpp: %d"), m_width, m_height, BytesPerPixel());
}
} // dwarf
#endif // D_BITMAP_H_
| [
"waddlesplash@gmail.com"
] | waddlesplash@gmail.com |
ceabd88f700a98ebf520193f2f77ab05b38c406e | 494fd6214560ce59db881f2614b7820bd092349f | /Source/ZTGame/ZTGameProjectile.cpp | d8714ff37725e66f2af00a34397b1c301c5ef391 | [] | no_license | ShuTheWise/ZTGame | 4d0437feb1a76244879c2fa42e73f84bb304ccef | 8d32f4b4dba4a47624513326589accb22b8ec721 | refs/heads/master | 2020-06-24T08:21:09.085098 | 2019-07-30T08:55:46 | 2019-07-30T08:55:46 | 198,910,886 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,857 | cpp | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
#include "ZTGameProjectile.h"
#include "DestructibleCube.h"
#include "GameFramework/ProjectileMovementComponent.h"
#include "Components/SphereComponent.h"
AZTGameProjectile::AZTGameProjectile()
{
// Use a sphere as a simple collision representation
CollisionComp = CreateDefaultSubobject<USphereComponent>(TEXT("SphereComp"));
CollisionComp->InitSphereRadius(5.0f);
CollisionComp->BodyInstance.SetCollisionProfileName("Projectile");
CollisionComp->OnComponentHit.AddDynamic(this, &AZTGameProjectile::OnHit); // set up a notification for when this component hits something blocking
// Players can't walk on it
CollisionComp->SetWalkableSlopeOverride(FWalkableSlopeOverride(WalkableSlope_Unwalkable, 0.f));
CollisionComp->CanCharacterStepUpOn = ECB_No;
// Set as root component
RootComponent = CollisionComp;
// Use a ProjectileMovementComponent to govern this projectile's movement
ProjectileMovement = CreateDefaultSubobject<UProjectileMovementComponent>(TEXT("ProjectileComp"));
ProjectileMovement->UpdatedComponent = CollisionComp;
ProjectileMovement->InitialSpeed = 3000.f;
ProjectileMovement->MaxSpeed = 3000.f;
ProjectileMovement->bRotationFollowsVelocity = true;
ProjectileMovement->bShouldBounce = true;
// Die after 3 seconds by default
InitialLifeSpan = 3.0f;
//networking
bReplicates = true;
bReplicateMovement = true;
}
void AZTGameProjectile::OnHit(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit)
{
// Only add impulse and destroy projectile if we hit a physics
if ((OtherActor != NULL) && (OtherActor != this) && (OtherComp != NULL) && OtherComp->IsSimulatingPhysics())
{
OtherComp->AddImpulseAtLocation(GetVelocity() * 100.0f, GetActorLocation());
Destroy();
}
} | [
"wookie.kandziora@gmail.com"
] | wookie.kandziora@gmail.com |
3bc0053c231a2be9bbe66e04124b9e0bc133993b | c7d44569192c48c84b9cca6d62286c04e9cb6468 | /include/process.h | 50a7758eb956b1d7cf967e7cb396a0e9710c678e | [
"MIT"
] | permissive | ddonco/CppND-System-Monitor | 5efb6be93dd385ddfdd8b436c036b32f798d5d7e | 45e54aacdce1838d3ebe1cadf9df603f5d9c85a1 | refs/heads/master | 2021-01-03T17:48:18.402566 | 2020-02-17T00:10:33 | 2020-02-17T00:10:33 | 240,176,500 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 491 | h | #ifndef PROCESS_H
#define PROCESS_H
#include <iostream>
#include <string>
/*
Basic class for Process representation
It contains relevant attributes as shown below
*/
class Process {
public:
Process(int pid = 0) : pid_(pid) { cpuUtil_ = this->CpuUtilization(); }
int Pid();
std::string User();
std::string Command();
float CpuUtilization();
std::string Ram();
long int UpTime();
bool operator<(Process const& a) const;
private:
int pid_;
float cpuUtil_{0};
};
#endif | [
"donohue.d.f@gmail.com"
] | donohue.d.f@gmail.com |
d97aa36e36fb812d4f7e70d1d6e32c9d5b85a952 | 3d0021b222ddd65b36e61207a8382e841d13e3df | /adpcm.cpp | d6f3f0672247e4dfbbfcf3a6b9cefed8f550a0a5 | [] | no_license | default0/zeldablackmagic | 1273f5793c4d5bbb594b6da07cf70b52de499392 | f12078b4c3b22d80077e485657538398e8db3b0f | refs/heads/master | 2021-01-10T11:54:31.897192 | 2010-02-10T19:23:04 | 2010-02-10T19:23:04 | 51,330,005 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,127 | cpp |
/*
#include "common.h"
#include "adpcm.h"
// <pSXAuthor> you use the decoder class like:
// <pSXAuthor> adpcm::decoder d;
// <pSXAuthor> signed short buffer[...number of pcm bytes....];
// <pSXAuthor> packet *p=... pointer to start of adpcm data ...;
// <pSXAuthor> signed short *ptr=buffer; while ((p->flags&flag_end)==0) ptr=d.decode_packet(p++,ptr);
//
//
//
const int adpcm::filter_coef[5][2]=
{
{ 0,0 },
{ 60,0 },
{ 115,-52 },
{ 98,-55 },
{ 122,-60 },
};
//
//
//
signed short *adpcm::decoder::decode_packet(adpcm::packet *ap, signed short *dp)
{
int shift=ap->info&0xf,
filter=ap->info>>4,
f0=filter_coef[filter][0],
f1=filter_coef[filter][1];
for (int i=0; i<14; i++)
{
unsigned char b=ap->data[i];
short bl=(b&0xf)<<12,
bh=(b>>4)<<12;
bl=(bl>>shift)+(((l0*f0)+(l1*f1)+32)>>6);
if (bl<-32768) bl=-32768; else if (bl>32767) bl=32767;
*dp++=bl;
l1=l0;
l0=bl;
bh=(bh>>shift)+(((l0*f0)+(l1*f1)+32)>>6);
if (bh<-32768) bh=-32768; else if (bh>32767) bh=32767;
*dp++=bh;
l1=l0;
l0=bh;
}
return dp;
} */ | [
"MathOnNapkins@99ff0a3e-ee68-11de-8de6-035db03795fd"
] | MathOnNapkins@99ff0a3e-ee68-11de-8de6-035db03795fd |
3586587aa1a3a2bc352c177a3dea740ac705451b | 7a572c43d35f9f5bf026268ea36493f82e206846 | /jsoncpp/json_reader.cpp | e6d620e83ec266d072d6f15d9439b355a13957d0 | [] | no_license | xu561865/Test_Mac | f674cbd5c484b90135b8e5b46e951dc5f4cc6c09 | ff51c667d7f88ca976e948761e37ff329a4eb4b3 | refs/heads/master | 2021-01-10T01:20:38.259352 | 2016-09-09T09:22:43 | 2016-09-09T09:22:43 | 47,551,617 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,319 | cpp | #include "json/reader.h"
#include "json/value.h"
#include <utility>
#include <cstdio>
#include <cassert>
#include <cstring>
#include <iostream>
#include <stdexcept>
#if _MSC_VER >= 1400 // VC++ 8.0
#pragma warning( disable : 4996 ) // disable warning about strdup being deprecated.
#endif
namespace Json {
// Implementation of class Features
// ////////////////////////////////
Features::Features() : allowComments_( true ) , strictRoot_( false )
{
}
Features Features::all()
{
return Features();
}
Features Features::strictMode()
{
Features features;
features.allowComments_ = false;
features.strictRoot_ = true;
return features;
}
// Implementation of class Reader
// ////////////////////////////////
static inline bool in( Reader::Char c, Reader::Char c1, Reader::Char c2, Reader::Char c3, Reader::Char c4 )
{
return c == c1 || c == c2 || c == c3 || c == c4;
}
static inline bool in( Reader::Char c, Reader::Char c1, Reader::Char c2, Reader::Char c3, Reader::Char c4, Reader::Char c5 )
{
return c == c1 || c == c2 || c == c3 || c == c4 || c == c5;
}
static bool containsNewLine( Reader::Location begin, Reader::Location end )
{
for ( ;begin < end; ++begin )
if ( *begin == '\n' || *begin == '\r' )
return true;
return false;
}
static std::string codePointToUTF8(unsigned int cp)
{
std::string result;
// based on description from http://en.wikipedia.org/wiki/UTF-8
if (cp <= 0x7f)
{
result.resize(1);
result[0] = static_cast<char>(cp);
}
else if (cp <= 0x7FF)
{
result.resize(2);
result[1] = static_cast<char>(0x80 | (0x3f & cp));
result[0] = static_cast<char>(0xC0 | (0x1f & (cp >> 6)));
}
else if (cp <= 0xFFFF)
{
result.resize(3);
result[2] = static_cast<char>(0x80 | (0x3f & cp));
result[1] = 0x80 | static_cast<char>((0x3f & (cp >> 6)));
result[0] = 0xE0 | static_cast<char>((0xf & (cp >> 12)));
}
else if (cp <= 0x10FFFF)
{
result.resize(4);
result[3] = static_cast<char>(0x80 | (0x3f & cp));
result[2] = static_cast<char>(0x80 | (0x3f & (cp >> 6)));
result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 12)));
result[0] = static_cast<char>(0xF0 | (0x7 & (cp >> 18)));
}
return result;
}
// Class Reader
// //////////////////////////////////////////////////////////////////
Reader::Reader() : features_( Features::all() )
{
}
Reader::Reader( const Features &features ) : features_( features )
{
}
bool Reader::parse( const std::string &document, Value &root, bool collectComments )
{
document_ = document;
const char *begin = document_.c_str();
const char *end = begin + document_.length();
return parse( begin, end, root, collectComments );
}
bool Reader::parse( std::istream& sin, Value &root, bool collectComments )
{
//std::istream_iterator<char> begin(sin);
//std::istream_iterator<char> end;
// Those would allow streamed input from a file, if parse() were a
// template function.
// Since std::string is reference-counted, this at least does not
// create an extra copy.
std::string doc;
std::getline(sin, doc, (char)EOF);
return parse( doc, root, collectComments );
}
bool Reader::parse( const char *beginDoc, const char *endDoc, Value &root, bool collectComments )
{
if ( !features_.allowComments_ )
{
collectComments = false;
}
begin_ = beginDoc;
end_ = endDoc;
collectComments_ = collectComments;
current_ = begin_;
lastValueEnd_ = 0;
lastValue_ = 0;
commentsBefore_ = "";
errors_.clear();
while ( !nodes_.empty() )
nodes_.pop();
nodes_.push( &root );
bool successful = readValue();
Token token;
skipCommentTokens( token );
if ( collectComments_ && !commentsBefore_.empty() )
root.setComment( commentsBefore_, commentAfter );
if ( features_.strictRoot_ )
{
if ( !root.isArray() && !root.isObject() )
{
// Set error location to start of doc, ideally should be first token found in doc
token.type_ = tokenError;
token.start_ = beginDoc;
token.end_ = endDoc;
addError( "A valid JSON document must be either an array or an object value.",
token );
return false;
}
}
return successful;
}
bool Reader::readValue()
{
Token token;
skipCommentTokens( token );
bool successful = true;
if ( collectComments_ && !commentsBefore_.empty() )
{
currentValue().setComment( commentsBefore_, commentBefore );
commentsBefore_ = "";
}
switch ( token.type_ )
{
case tokenObjectBegin:
successful = readObject( token );
break;
case tokenArrayBegin:
successful = readArray( token );
break;
case tokenNumber:
successful = decodeNumber( token );
break;
case tokenString:
successful = decodeString( token );
break;
case tokenTrue:
currentValue() = true;
break;
case tokenFalse:
currentValue() = false;
break;
case tokenNull:
currentValue() = Value();
break;
default:
return addError( "Syntax error: value, object or array expected.", token );
}
if ( collectComments_ )
{
lastValueEnd_ = current_;
lastValue_ = ¤tValue();
}
return successful;
}
void Reader::skipCommentTokens( Token &token )
{
if ( features_.allowComments_ )
{
do
{
readToken( token );
}
while ( token.type_ == tokenComment );
}
else
{
readToken( token );
}
}
bool Reader::expectToken( TokenType type, Token &token, const char *message )
{
readToken( token );
if ( token.type_ != type )
return addError( message, token );
return true;
}
bool Reader::readToken( Token &token )
{
skipSpaces();
token.start_ = current_;
Char c = getNextChar();
bool ok = true;
switch ( c )
{
case '{':
token.type_ = tokenObjectBegin;
break;
case '}':
token.type_ = tokenObjectEnd;
break;
case '[':
token.type_ = tokenArrayBegin;
break;
case ']':
token.type_ = tokenArrayEnd;
break;
case '"':
token.type_ = tokenString;
ok = readString();
break;
case '/':
token.type_ = tokenComment;
ok = readComment();
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
token.type_ = tokenNumber;
readNumber();
break;
case 't':
token.type_ = tokenTrue;
ok = match( "rue", 3 );
break;
case 'f':
token.type_ = tokenFalse;
ok = match( "alse", 4 );
break;
case 'n':
token.type_ = tokenNull;
ok = match( "ull", 3 );
break;
case ',':
token.type_ = tokenArraySeparator;
break;
case ':':
token.type_ = tokenMemberSeparator;
break;
case 0:
token.type_ = tokenEndOfStream;
break;
default:
ok = false;
break;
}
if ( !ok )
token.type_ = tokenError;
token.end_ = current_;
return true;
}
void Reader::skipSpaces()
{
while ( current_ != end_ )
{
Char c = *current_;
if ( c == ' ' || c == '\t' || c == '\r' || c == '\n' )
++current_;
else
break;
}
}
bool Reader::match( Location pattern, int patternLength )
{
if ( end_ - current_ < patternLength )
return false;
int index = patternLength;
while ( index-- )
if ( current_[index] != pattern[index] )
return false;
current_ += patternLength;
return true;
}
bool Reader::readComment()
{
Location commentBegin = current_ - 1;
Char c = getNextChar();
bool successful = false;
if ( c == '*' )
successful = readCStyleComment();
else if ( c == '/' )
successful = readCppStyleComment();
if ( !successful )
return false;
if ( collectComments_ )
{
CommentPlacement placement = commentBefore;
if ( lastValueEnd_ && !containsNewLine( lastValueEnd_, commentBegin ) )
{
if ( c != '*' || !containsNewLine( commentBegin, current_ ) )
placement = commentAfterOnSameLine;
}
addComment( commentBegin, current_, placement );
}
return true;
}
void Reader::addComment( Location begin, Location end, CommentPlacement placement )
{
assert( collectComments_ );
if ( placement == commentAfterOnSameLine )
{
assert( lastValue_ != 0 );
lastValue_->setComment( std::string( begin, end ), placement );
}
else
{
if ( !commentsBefore_.empty() )
commentsBefore_ += "\n";
commentsBefore_ += std::string( begin, end );
}
}
bool Reader::readCStyleComment()
{
while ( current_ != end_ )
{
Char c = getNextChar();
if ( c == '*' && *current_ == '/' )
break;
}
return getNextChar() == '/';
}
bool Reader::readCppStyleComment()
{
while ( current_ != end_ )
{
Char c = getNextChar();
if ( c == '\r' || c == '\n' )
break;
}
return true;
}
void Reader::readNumber()
{
while ( current_ != end_ )
{
if ( !(*current_ >= '0' && *current_ <= '9') &&
!in( *current_, '.', 'e', 'E', '+', '-' ) )
break;
++current_;
}
}
bool Reader::readString()
{
Char c = 0;
while ( current_ != end_ )
{
c = getNextChar();
if ( c == '\\' )
getNextChar();
else if ( c == '"' )
break;
}
return c == '"';
}
bool Reader::readObject( Token &tokenStart )
{
Token tokenName;
std::string name;
currentValue() = Value( objectValue );
while ( readToken( tokenName ) )
{
bool initialTokenOk = true;
while ( tokenName.type_ == tokenComment && initialTokenOk )
initialTokenOk = readToken( tokenName );
if ( !initialTokenOk )
break;
if ( tokenName.type_ == tokenObjectEnd && name.empty() ) // empty object
return true;
if ( tokenName.type_ != tokenString )
break;
name = "";
if ( !decodeString( tokenName, name ) )
return recoverFromError( tokenObjectEnd );
Token colon;
if ( !readToken( colon ) || colon.type_ != tokenMemberSeparator )
{
return addErrorAndRecover( "Missing ':' after object member name",
colon,
tokenObjectEnd );
}
Value &value = currentValue()[ name ];
nodes_.push( &value );
bool ok = readValue();
nodes_.pop();
if ( !ok ) // error already set
return recoverFromError( tokenObjectEnd );
Token comma;
if ( !readToken( comma )
|| ( comma.type_ != tokenObjectEnd &&
comma.type_ != tokenArraySeparator &&
comma.type_ != tokenComment ) )
{
return addErrorAndRecover( "Missing ',' or '}' in object declaration",
comma,
tokenObjectEnd );
}
bool finalizeTokenOk = true;
while ( comma.type_ == tokenComment &&
finalizeTokenOk )
finalizeTokenOk = readToken( comma );
if ( comma.type_ == tokenObjectEnd )
return true;
}
return addErrorAndRecover( "Missing '}' or object member name",
tokenName,
tokenObjectEnd );
}
bool Reader::readArray( Token &tokenStart )
{
currentValue() = Value( arrayValue );
skipSpaces();
if ( *current_ == ']' ) // empty array
{
Token endArray;
readToken( endArray );
return true;
}
int index = 0;
while ( true )
{
Value &value = currentValue()[ index++ ];
nodes_.push( &value );
bool ok = readValue();
nodes_.pop();
if ( !ok ) // error already set
return recoverFromError( tokenArrayEnd );
Token token;
// Accept Comment after last item in the array.
ok = readToken( token );
while ( token.type_ == tokenComment && ok )
{
ok = readToken( token );
}
bool badTokenType = ( token.type_ == tokenArraySeparator &&
token.type_ == tokenArrayEnd );
if ( !ok || badTokenType )
{
return addErrorAndRecover( "Missing ',' or ']' in array declaration",
token,
tokenArrayEnd );
}
if ( token.type_ == tokenArrayEnd )
break;
}
return true;
}
bool Reader::decodeNumber( Token &token )
{
bool isDouble = false;
for ( Location inspect = token.start_; inspect != token.end_; ++inspect )
{
isDouble = isDouble
|| in( *inspect, '.', 'e', 'E', '+' )
|| ( *inspect == '-' && inspect != token.start_ );
}
if ( isDouble )
return decodeDouble( token );
Location current = token.start_;
bool isNegative = *current == '-';
if ( isNegative )
++current;
Value::UInt threshold = (isNegative ? Value::UInt(-Value::minInt)
: Value::maxUInt) / 10;
Value::UInt value = 0;
while ( current < token.end_ )
{
Char c = *current++;
if ( c < '0' || c > '9' )
return addError( "'" + std::string( token.start_, token.end_ ) + "' is not a number.", token );
if ( value >= threshold )
return decodeDouble( token );
value = value * 10 + Value::UInt(c - '0');
}
if ( isNegative )
currentValue() = -Value::Int( value );
else if ( value <= Value::UInt(Value::maxInt) )
currentValue() = Value::Int( value );
else
currentValue() = value;
return true;
}
bool Reader::decodeDouble( Token &token )
{
double value = 0;
const int bufferSize = 32;
int count;
int length = int(token.end_ - token.start_);
if ( length <= bufferSize )
{
Char buffer[bufferSize];
memcpy( buffer, token.start_, length );
buffer[length] = 0;
count = sscanf( buffer, "%lf", &value );
}
else
{
std::string buffer( token.start_, token.end_ );
count = sscanf( buffer.c_str(), "%lf", &value );
}
if ( count != 1 )
return addError( "'" + std::string( token.start_, token.end_ ) + "' is not a number.", token );
currentValue() = value;
return true;
}
bool Reader::decodeString( Token &token )
{
std::string decoded;
if ( !decodeString( token, decoded ) )
return false;
currentValue() = decoded;
return true;
}
bool Reader::decodeString( Token &token, std::string &decoded )
{
decoded.reserve( token.end_ - token.start_ - 2 );
Location current = token.start_ + 1; // skip '"'
Location end = token.end_ - 1; // do not include '"'
while ( current != end )
{
Char c = *current++;
if ( c == '"' )
break;
else if ( c == '\\' )
{
if ( current == end )
return addError( "Empty escape sequence in string", token, current );
Char escape = *current++;
switch ( escape )
{
case '"': decoded += '"'; break;
case '/': decoded += '/'; break;
case '\\': decoded += '\\'; break;
case 'b': decoded += '\b'; break;
case 'f': decoded += '\f'; break;
case 'n': decoded += '\n'; break;
case 'r': decoded += '\r'; break;
case 't': decoded += '\t'; break;
case 'u':
{
unsigned int unicode;
if ( !decodeUnicodeCodePoint( token, current, end, unicode ) )
return false;
decoded += codePointToUTF8(unicode);
}
break;
default:
return addError( "Bad escape sequence in string", token, current );
}
}
else
{
decoded += c;
}
}
return true;
}
bool Reader::decodeUnicodeCodePoint( Token &token, Location ¤t, Location end, unsigned int &unicode )
{
if ( !decodeUnicodeEscapeSequence( token, current, end, unicode ) )
return false;
if (unicode >= 0xD800 && unicode <= 0xDBFF)
{
// surrogate pairs
if (end - current < 6)
return addError( "additional six characters expected to parse unicode surrogate pair.", token, current );
unsigned int surrogatePair;
if (*(current++) == '\\' && *(current++)== 'u')
{
if (decodeUnicodeEscapeSequence( token, current, end, surrogatePair ))
{
unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF);
}
else
return false;
}
else
return addError( "expecting another \\u token to begin the second half of a unicode surrogate pair", token, current );
}
return true;
}
bool Reader::decodeUnicodeEscapeSequence( Token &token, Location ¤t, Location end, unsigned int &unicode )
{
if ( end - current < 4 )
return addError( "Bad unicode escape sequence in string: four digits expected.", token, current );
unicode = 0;
for ( int index =0; index < 4; ++index )
{
Char c = *current++;
unicode *= 16;
if ( c >= '0' && c <= '9' )
unicode += c - '0';
else if ( c >= 'a' && c <= 'f' )
unicode += c - 'a' + 10;
else if ( c >= 'A' && c <= 'F' )
unicode += c - 'A' + 10;
else
return addError( "Bad unicode escape sequence in string: hexadecimal digit expected.", token, current );
}
return true;
}
bool Reader::addError( const std::string &message, Token &token, Location extra )
{
ErrorInfo info;
info.token_ = token;
info.message_ = message;
info.extra_ = extra;
errors_.push_back( info );
return false;
}
bool Reader::recoverFromError( TokenType skipUntilToken )
{
int errorCount = int(errors_.size());
Token skip;
while ( true )
{
if ( !readToken(skip) )
errors_.resize( errorCount ); // discard errors caused by recovery
if ( skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream )
break;
}
errors_.resize( errorCount );
return false;
}
bool Reader::addErrorAndRecover( const std::string &message, Token &token, TokenType skipUntilToken )
{
addError( message, token );
return recoverFromError( skipUntilToken );
}
Value & Reader::currentValue()
{
return *(nodes_.top());
}
Reader::Char Reader::getNextChar()
{
if ( current_ == end_ )
return 0;
return *current_++;
}
void Reader::getLocationLineAndColumn( Location location, int &line, int &column ) const
{
Location current = begin_;
Location lastLineStart = current;
line = 0;
while ( current < location && current != end_ )
{
Char c = *current++;
if ( c == '\r' )
{
if ( *current == '\n' )
++current;
lastLineStart = current;
++line;
}
else if ( c == '\n' )
{
lastLineStart = current;
++line;
}
}
// column & line start at 1
column = int(location - lastLineStart) + 1;
++line;
}
std::string Reader::getLocationLineAndColumn( Location location ) const
{
int line, column;
getLocationLineAndColumn( location, line, column );
char buffer[18+16+16+1];
sprintf( buffer, "Line %d, Column %d", line, column );
return buffer;
}
std::string Reader::getFormatedErrorMessages() const
{
std::string formattedMessage;
for ( Errors::const_iterator itError = errors_.begin();
itError != errors_.end();
++itError )
{
const ErrorInfo &error = *itError;
formattedMessage += "* " + getLocationLineAndColumn( error.token_.start_ ) + "\n";
formattedMessage += " " + error.message_ + "\n";
if ( error.extra_ )
formattedMessage += "See " + getLocationLineAndColumn( error.extra_ ) + " for detail.\n";
}
return formattedMessage;
}
std::istream& operator>>( std::istream &sin, Value &root )
{
Json::Reader reader;
bool ok = reader.parse(sin, root, true);
//JSON_ASSERT( ok );
if (!ok) throw std::runtime_error(reader.getFormatedErrorMessages());
return sin;
}
} // namespace Json
| [
"xuyi561865@sina.com"
] | xuyi561865@sina.com |
233a9057287fa14ee25d091c2763ef9015a7285a | 889eeb8faad7f6e35d836ab353962b9202b47cd2 | /other/CppAlgs/mLib/mLibBinaryTree.cpp | 4c123c8f2b3b51270b90454ae945d9d6f707c811 | [] | no_license | blacksea3/Cpp-STL-test | 36e6bfb066b0a489796f002f83da8afa6ccc50d7 | 897a54149a8a84262b890505f400dcfb2938876f | refs/heads/master | 2020-06-08T12:26:53.438569 | 2020-02-12T03:17:16 | 2020-02-12T03:17:16 | 193,228,023 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 793 | cpp | #include "mLibBinaryTree.hpp"
#include <map>
namespace mLib
{
void mLibBinaryTreeClassTest()
{
mbinary_searchtree<int> mbs;
cout << mbs.remove(3) << endl;
mbs.inorder();
cout << endl;
cout << mbs.insert(3) << endl;
cout << mbs.insert(2) << endl;
cout << mbs.insert(1) << endl;
cout << mbs.insert(4) << endl;
cout << mbs.insert(1) << endl;
cout << mbs.insert(3) << endl;
cout << mbs.insert(1) << endl;
mbs.inorder();
cout << endl;
cout << mbs.find(3) << endl;
cout << mbs.find(5) << endl;
cout << mbs.find(1) << endl;
mLib::mvector<int> res = mbs.RangeSearch(2, 4);
for (size_t i = 0; i < res.getSize(); ++i) cout << res[i] << " ";
cout << endl;
cout << mbs.remove(3) << endl;
mbs.inorder();
cout << endl;
cout << mbs.find(3) << endl;
}
}
| [
"17865191779@163.com"
] | 17865191779@163.com |
b9bea305b321d407fdd4a5ee31c9dc448c024b2a | 4b9637a5dfbc9c435e7f80ecd3ee0928a36e89b1 | /Minigin/EMatrix3.h | eda720535c59fcd7e1efd8b179146f1ea357fa3f | [] | no_license | VincentVanZele/MiniginQBert | 5661d9db77e8526b17de196ebaa0cab440863502 | f5059f89e6485f4a35dbd9439b97d3c8a7696848 | refs/heads/master | 2023-05-28T20:21:32.533080 | 2021-06-06T19:01:46 | 2021-06-06T19:01:46 | 356,696,769 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,670 | h | /*=============================================================================*/
// Copyright Matthieu Delaere
/*=============================================================================*/
// EMatrix3.h: Column Major Matrix3x3 struct
/*=============================================================================*/
#ifndef ELITE_MATH_MATRIX3
#define ELITE_MATH_MATRIX3
#include "EMatrix.h"
#include "EVector.h"
#include "EMathUtilities.h"
namespace Elite
{
//=== MATRIX3x3 SPECIALIZATION ===
template<typename T>
struct Matrix<3, 3, T>
{
//=== Data ===
T data[3][3];
//=== Constructors ===
#pragma region Constructors
Matrix<3, 3, T>() = default;
//Every "row" of values passed here is a row in our matrix!
Matrix<3, 3, T>(T _00, T _01, T _02,
T _10, T _11, T _12,
T _20, T _21, T _22)
{
data[0][0] = _00; data[0][1] = _10; data[0][2] = _20;
data[1][0] = _01; data[1][1] = _11; data[1][2] = _21;
data[2][0] = _02; data[2][1] = _12; data[2][2] = _22;
}
//Every vector passed here is a column in our matrix!
Matrix<3, 3, T>(const Vector<3, T>& a, const Vector<3, T>& b, const Vector<3, T>& c)
{
data[0][0] = a.x; data[0][1] = a.y; data[0][2] = a.z;
data[1][0] = b.x; data[1][1] = b.y; data[1][2] = b.z;
data[2][0] = c.x; data[2][1] = c.y; data[2][2] = c.z;
}
Matrix<3, 3, T>(const Matrix<2, 2, T>& m)
{
data[0][0] = m.data[0][0]; data[0][1] = m.data[0][1]; data[0][2] = 0;
data[1][0] = m.data[1][0]; data[1][1] = m.data[1][1]; data[1][2] = 0;
data[2][0] = 0; data[2][1] = 0; data[2][2] = 1;
}
Matrix<3, 3, T>(const Matrix<3, 3, T>& m)
{
data[0][0] = m.data[0][0]; data[0][1] = m.data[0][1]; data[0][2] = m.data[0][2];
data[1][0] = m.data[1][0]; data[1][1] = m.data[1][1]; data[1][2] = m.data[1][2];
data[2][0] = m.data[2][0]; data[2][1] = m.data[2][1]; data[2][2] = m.data[2][2];
}
Matrix<3, 3, T>(const Matrix<4, 4, T>& m)
{
data[0][0] = m.data[0][0]; data[0][1] = m.data[0][1]; data[0][2] = m.data[0][2];
data[1][0] = m.data[1][0]; data[1][1] = m.data[1][1]; data[1][2] = m.data[1][2];
data[2][0] = m.data[2][0]; data[2][1] = m.data[2][1]; data[2][2] = m.data[2][2];
}
Matrix<3, 3, T>(Matrix<3, 3, T>&& m) noexcept
{
data[0][0] = std::move(m.data[0][0]); data[0][1] = std::move(m.data[0][1]); data[0][2] = std::move(m.data[0][2]);
data[1][0] = std::move(m.data[1][0]); data[1][1] = std::move(m.data[1][1]); data[1][2] = std::move(m.data[1][2]);
data[2][0] = std::move(m.data[2][0]); data[2][1] = std::move(m.data[2][1]); data[2][2] = std::move(m.data[2][2]);
}
Matrix<3, 3, T>(Matrix<4, 4, T>&& m) noexcept
{
data[0][0] = std::move(m.data[0][0]); data[0][1] = std::move(m.data[0][1]); data[0][2] = std::move(m.data[0][2]);
data[1][0] = std::move(m.data[1][0]); data[1][1] = std::move(m.data[1][1]); data[1][2] = std::move(m.data[1][2]);
data[2][0] = std::move(m.data[2][0]); data[2][1] = std::move(m.data[2][1]); data[2][2] = std::move(m.data[2][2]);
}
#pragma endregion
//=== Arithmetic Operators ===
#pragma region ArithmeticOperators
inline Matrix<3, 3, T> operator+(const Matrix<3, 3, T>& m) const
{
return Matrix<3, 3, T>(
data[0][0] + m.data[0][0], data[0][1] + m.data[0][1], data[0][2] + m.data[0][2],
data[1][0] + m.data[1][0], data[1][1] + m.data[1][1], data[1][2] + m.data[1][2],
data[2][0] + m.data[2][0], data[2][1] + m.data[2][1], data[2][2] + m.data[2][2]);
}
inline Matrix<3, 3, T> operator-(const Matrix<3, 3, T>& m) const
{
return Matrix<3, 3, T>(
data[0][0] - m.data[0][0], data[0][1] - m.data[0][1], data[0][2] - m.data[0][2],
data[1][0] - m.data[1][0], data[1][1] - m.data[1][1], data[1][2] - m.data[1][2],
data[2][0] - m.data[2][0], data[2][1] - m.data[2][1], data[2][2] - m.data[2][2]);
}
template<typename U>
inline Matrix<3, 3, T> operator*(U scale) const
{
const T s = static_cast<T>(scale);
return Matrix<3, 3, T>(
data[0][0] * s, data[0][1] * s, data[0][2] * s,
data[1][0] * s, data[1][1] * s, data[1][2] * s,
data[2][0] * s, data[2][1] * s, data[2][2] * s);
}
template<typename U>
inline Matrix<3, 3, T> operator/(U scale) const
{
const T revS = static_cast<T>(1.0f / scale);
return Matrix<3, 3, T>(
data[0][0] * revS, data[0][1] * revS, data[0][2] * revS,
data[1][0] * revS, data[1][1] * revS, data[1][2] * revS,
data[2][0] * revS, data[2][1] * revS, data[2][2] * revS);
}
inline Matrix<3, 3, T> operator*(const Matrix<3, 3, T>& rm)
{
const Matrix<3, 3, T>& lm = (*this);
return Matrix<3, 3, T>(
lm(0, 0) * rm(0, 0) + lm(0, 1) * rm(1, 0) + lm(0, 2) * rm(2, 0),
lm(0, 0) * rm(0, 1) + lm(0, 1) * rm(1, 1) + lm(0, 2) * rm(2, 1),
lm(0, 0) * rm(0, 2) + lm(0, 1) * rm(1, 2) + lm(0, 2) * rm(2, 2),
lm(1, 0) * rm(0, 0) + lm(1, 1) * rm(1, 0) + lm(1, 2) * rm(2, 0),
lm(1, 0) * rm(0, 1) + lm(1, 1) * rm(1, 1) + lm(1, 2) * rm(2, 1),
lm(1, 0) * rm(0, 2) + lm(1, 1) * rm(1, 2) + lm(1, 2) * rm(2, 2),
lm(2, 0) * rm(0, 0) + lm(2, 1) * rm(1, 0) + lm(2, 2) * rm(2, 0),
lm(2, 0) * rm(0, 1) + lm(2, 1) * rm(1, 1) + lm(2, 2) * rm(2, 1),
lm(2, 0) * rm(0, 2) + lm(2, 1) * rm(1, 2) + lm(2, 2) * rm(2, 2));
}
inline Vector<3, T> operator*(const Vector<3, T>& v)
{
const Matrix<3, 3, T>& m = (*this);
return Vector<3, T>(
m(0, 0) * v.x + m(0, 1) * v.y + m(0, 2) * v.z,
m(1, 0) * v.x + m(1, 1) * v.y + m(1, 2) * v.z,
m(2, 0) * v.x + m(2, 1) * v.y + m(2, 2) * v.z);
}
inline Point<3, T> operator*(const Point<3, T>& p)
{
const Matrix<3, 3, T>& m = (*this);
return Point<3, T>(
m(0, 0) * p.x + m(0, 1) * p.y + m(0, 2),
m(1, 0) * p.x + m(1, 1) * p.y + m(1, 2), 1);
}
#pragma endregion
//=== Compound Assignment Operators ===
#pragma region CompoundAssignmentOperators
inline Matrix<3, 3, T>& operator=(const Matrix<3, 3, T>& m)
{
data[0][0] = m.data[0][0]; data[0][1] = m.data[0][1]; data[0][2] = m.data[0][2];
data[1][0] = m.data[1][0]; data[1][1] = m.data[1][1]; data[1][2] = m.data[1][2];
data[2][0] = m.data[2][0]; data[2][1] = m.data[2][1]; data[2][2] = m.data[2][2];
return *this;
}
inline Matrix<3, 3, T>& operator+=(const Matrix<3, 3, T>& m)
{
data[0][0] += m.data[0][0]; data[0][1] += m.data[0][1]; data[0][2] += m.data[0][2];
data[1][0] += m.data[1][0]; data[1][1] += m.data[1][1]; data[1][2] += m.data[1][2];
data[2][0] += m.data[2][0]; data[2][1] += m.data[2][1]; data[2][2] += m.data[2][2];
return *this;
}
inline Matrix<3, 3, T>& operator-=(const Matrix<3, 3, T>& m)
{
data[0][0] -= m.data[0][0]; data[0][1] -= m.data[0][1]; data[0][2] -= m.data[0][2];
data[1][0] -= m.data[1][0]; data[1][1] -= m.data[1][1]; data[1][2] -= m.data[1][2];
data[2][0] -= m.data[2][0]; data[2][1] -= m.data[2][1]; data[2][2] -= m.data[2][2];
return *this;
}
template<typename U>
inline Matrix<3, 3, T>& operator*=(U scale)
{
const T s = static_cast<T>(scale);
data[0][0] *= s; data[0][1] *= s; data[0][2] *= s;
data[1][0] *= s; data[1][1] *= s; data[1][2] *= s;
data[2][0] *= s; data[2][1] *= s; data[2][2] *= s;
return *this;
}
template<typename U>
inline Matrix<3, 3, T>& operator/=(U scale)
{
const T revS = static_cast<T>(1.0f / scale);
data[0][0] *= revS; data[0][1] *= revS; data[0][2] *= revS;
data[1][0] *= revS; data[1][1] *= revS; data[1][2] *= revS;
data[2][0] *= revS; data[2][1] *= revS; data[2][2] *= revS;
return *this;
}
inline Matrix<3, 3, T>& operator*=(const Matrix<3, 3, T>& m)
{
//Copy is necessary! :(
*this = *this * m;
return *this;
}
#pragma endregion
//=== Relational Operators ===
#pragma region RelationalOperators
inline bool operator==(const Matrix<3, 3, T>& m) const
{ return ((*this)[0] == m[0]) && ((*this)[1] == m[1]) && ((*this)[2] == m[2]); }
inline bool operator!=(const Matrix<3, 3, T>& m) const
{ return !(*this == m); }
#pragma endregion
//=== Member Access Operators ===
#pragma region MemberAccessOperators
//Access parameter order still happens as row,column indexing (standard in programming)
inline T operator()(uint8_t r, uint8_t c) const
{
assert((r < 3 && c < 3) && "ERROR: indices of Matrix3x3 () const operator are out of bounds!");
return (data[c][r]);
}
inline T& operator()(uint8_t r, uint8_t c)
{
assert((r < 3 && c < 3) && "ERROR: indices of Matrix3x3 () operator are out of bounds!");
return (data[c][r]);
}
//Get a vector representation of a column (usage), but internally returns one of the rows
inline const Vector<3, T>& operator[](uint8_t c) const
{
assert((c < 3) && "ERROR: index of Matrix3x3 [] operator is out of bounds!");
return *((Vector<3, T>*)data[c]);
}
inline Vector<3, T>& operator[](uint8_t c)
{
assert((c < 3) && "ERROR: index of Matrix3x3 [] operator is out of bounds!");
return *((Vector<3, T>*)data[c]);
}
#pragma endregion
//=== Static Functions ===
static Matrix<3, 3, T> Identity();
};
//--- VECMATRIX3 FUNCTIONS ---
#pragma region GlobalOperators
#pragma endregion
#pragma region GlobalFunctions
template<typename T>
inline Matrix<3, 3, T> Matrix<3, 3, T>::Identity()
{
return Matrix<3, 3, T>(
1,0,0,
0,1,0,
0,0,1);
}
template<typename T>
inline Matrix<3, 3, T> Transpose(const Matrix<3, 3, T>& m)
{
Matrix<3, 3, T> t = {};
t(0, 0) = m(0, 0);
t(0, 1) = m(1, 0);
t(0, 2) = m(2, 0);
t(1, 0) = m(0, 1);
t(1, 1) = m(1, 1);
t(1, 2) = m(2, 1);
t(2, 0) = m(0, 2);
t(2, 1) = m(1, 2);
t(2, 2) = m(2, 2);
return t;
}
template<typename T>
inline T Determinant(const Matrix<3, 3, T>& m)
{
return
+ m(0, 0) * (m(1, 1) * m(2, 2) - m(1, 2) * m(2, 1))
- m(0, 1) * (m(1, 0) * m(2, 2) - m(1, 2) * m(2, 0))
+ m(0, 2) * (m(1, 0) * m(2, 1) - m(1, 1) * m(2, 0));
}
template<typename T>
inline Matrix<3, 3, T> Inverse(const Matrix<3, 3, T>& m)
{
//Optimized Inverse as explained in FGED1 - used widely in other libraries too.
//This avoids the unnecessary calculation of all the cofactors as for the determinant! -> See below in comment
const Vector<3, T>& a = m[0];
const Vector<3, T>& b = m[1];
const Vector<3, T>& c = m[2];
Vector<3, T> r0 = Cross(b, c);
Vector<3, T> r1 = Cross(c, a);
Vector<3, T> r2 = Cross(a, b);
T det = Dot(r2, c);
assert((!AreEqual(det, static_cast<T>(0))) && "ERROR: determinant is 0, there is no INVERSE!");
T invDet = static_cast<T>(1.0f / det);
return Matrix<3, 3, T>(
r0.x * invDet, r0.y * invDet, r0.z * invDet,
r1.x * invDet, r1.y * invDet, r1.z * invDet,
r2.x * invDet, r2.y * invDet, r2.z * invDet);
/* //----- Approach with cofactors ------
T invDet = static_cast<T>(1.0f / Determinant(m));
Matrix<3, 3, T> inv = {};
inv(0, 0) = +(m(1, 1) * m(2, 2) - m(1, 2) * m(2, 1)) * invDet;
inv(0, 1) = -(m(0, 1) * m(2, 2) - m(0, 2) * m(2, 1)) * invDet;
inv(0, 2) = +(m(0, 1) * m(1, 2) - m(0, 2) * m(1, 1)) * invDet;
inv(1, 0) = -(m(1, 0) * m(2, 2) - m(1, 2) * m(2, 0)) * invDet;
inv(1, 1) = +(m(0, 0) * m(2, 2) - m(0, 2) * m(2, 0)) * invDet;
inv(1, 2) = -(m(0, 0) * m(1, 2) - m(0, 2) * m(1, 0)) * invDet;
inv(2, 0) = +(m(1, 0) * m(2, 1) - m(1, 1) * m(2, 0)) * invDet;
inv(2, 1) = -(m(0, 0) * m(2, 1) - m(0, 1) * m(2, 0)) * invDet;
inv(2, 2) = +(m(0, 0) * m(1, 1) - m(0, 1) * m(1, 0)) * invDet;
return inv;
*/
}
//Rotations with a positive angle are considered a counterclockwise rotations around the axis pointing towards
//the viewer. Think of the axis as the "normal" of the planes (x -> yz-plane, y -> xz-plane , z -> xy-plane)!
template<typename T>
inline Matrix<3, 3, T> MakeRotationX(T t)
{
T c = static_cast<T>(cos(t));
T s = static_cast<T>(sin(t));
return Matrix<3, 3, T>(
static_cast<T>(1), static_cast<T>(0), static_cast<T>(0),
static_cast<T>(0), c, -s,
static_cast<T>(0), s, c);
}
template<typename T>
inline Matrix<3, 3, T> MakeRotationY(T t)
{
T c = static_cast<T>(cos(t));
T s = static_cast<T>(sin(t));
return Matrix<3, 3, T>(
c, static_cast<T>(0), s,
static_cast<T>(0), static_cast<T>(1), static_cast<T>(0),
-s, static_cast<T>(0), c);
}
template<typename T>
inline Matrix<3, 3, T> MakeRotationZ(T t)
{
T c = static_cast<T>(cos(t));
T s = static_cast<T>(sin(t));
return Matrix<3, 3, T>(
c, -s, static_cast<T>(0),
s, c, static_cast<T>(0),
static_cast<T>(0), static_cast<T>(0), static_cast<T>(1));
}
template<typename T>
inline Matrix<3, 3, T> MakeRotationZYX(T x, T y, T z)
{
Matrix<3, 3, T> mX = MakeRotationX(x);
Matrix<3, 3, T> mY = MakeRotationY(y);
Matrix<3, 3, T> mZ = MakeRotationZ(z);
return mZ * mY * mX;
}
template<typename T>
inline Matrix<3, 3, T> MakeRotation(T t, const Vector<3, T>& axis)
{
T c = static_cast<T>(cos(t));
T s = static_cast<T>(sin(t));
T oneMinusC = static_cast<T>(1 - c);
T xy = axis.x * axis.y;
T yz = axis.y * axis.z;
T xz = axis.x * axis.z;
T sx = s * axis.x;
T sy = s * axis.y;
T sz = s * axis.z;
return Matrix<3, 3, T>(
c + oneMinusC * (axis.x * axis.x), oneMinusC * xy - sz, oneMinusC * xz + sy,
oneMinusC * xy + sz, c + oneMinusC * (axis.y * axis.y), oneMinusC * yz - sx,
oneMinusC * xz - sy, oneMinusC * yz + sx, c + oneMinusC * (axis.z * axis.z));
}
template<typename T>
inline Matrix<3, 3, T> MakeScale(T x, T y, T z)
{
return Matrix<3, 3, T>(
x, static_cast<T>(0), static_cast<T>(0),
static_cast<T>(0), y, static_cast<T>(0),
static_cast<T>(0), static_cast<T>(0), z);
}
template<typename T>
inline Matrix<3, 3, T> MakeScale(T s, const Vector<3, T>& axis)
{
T sMinusOne = s - static_cast<T>(1);
T xy = axis.x * axis.y;
T yz = axis.y * axis.z;
T xz = axis.x * axis.z;
return Matrix<3, 3, T>(
sMinusOne * (axis.x * axis.x) + 1, sMinusOne * xy, sMinusOne * xz,
sMinusOne * xy, sMinusOne * (axis.y * axis.y) + 1, sMinusOne * yz,
sMinusOne * xz, sMinusOne * yz, sMinusOne * (axis.z * axis.z) + 1);
}
template<typename T>
inline Matrix<3, 3, T> MakeTranslation(const Vector<2, T>& v)
{
return Matrix<3, 3, T>(
1, 0, v.x,
0, 1, v.y,
0, 0, 1);
}
//Can be used to change from right-handed coordinate system (the "assumption" of these rotation matrices is
//a right-handed system) to a left-handed coordinate system.
template<typename T>
inline Matrix<3, 3, T> MakeReflection(const Vector<3, T>& axis)
{
T xy = axis.x * axis.y;
T yz = axis.y * axis.z;
T xz = axis.x * axis.z;
return Matrix<3, 3, T>(
1 - 2 * (axis.x * axis.x), -2 * xy, -2 * xz,
-2 * xy, 1 - 2 * (axis.y * axis.y), -2 * yz,
-2 * xz, -2 * yz, 1 - 2 * (axis.z * axis.z));
}
#pragma endregion
}
#endif | [
"vincent.van.zele@student.howest.be"
] | vincent.van.zele@student.howest.be |
cc7fc05529d4280deda0c015110013d2af4c5b8b | ed1cd6b5bf756de2ae9e10e0a50b8a5908b7bbae | /src/PotThrowingApp.cpp | 7d894a099c3df1d8caec086b515f4dd6e6afb14b | [] | no_license | benthejack/PotThrowing | d5ae00f6f5fde78a0617262cf1df1be0b8e4936b | c69c5af6faa67eee5cf4718b8612058420f361e1 | refs/heads/master | 2020-04-15T22:48:00.882328 | 2013-07-16T04:46:30 | 2013-07-16T04:46:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,651 | cpp | #include "cinder/app/AppBasic.h"
#include "cinder/gl/gl.h"
#include "TubeGenerator.h"
#include "GeometryRenderer.h"
#include "LayerManager.h"
using namespace ci;
using namespace ci::app;
using namespace std;
using namespace EyeCandy::GeomUtils;
using namespace EyeCandy::GfxUtils;
class PotThrowingApp : public AppBasic {
public:
void setup();
void mouseDown( MouseEvent event );
void mouseUp( MouseEvent event );
void update();
void draw();
private:
GeometryGenerator_ptr tube;
LayerManager_ptr layers;
GeomRenderer_ptr rend;
float rotation;
bool mousePressed;
};
void PotThrowingApp::setup()
{
mousePressed = false;
rotation = 0;
layers = LayerManager_ptr(new LayerManager(getWindowWidth(), getWindowHeight()));
Layer_ptr tubeLayer = layers->pushLayer();
tube = GeometryGenerator_ptr(new TubeGenerator(200,150,50, Vec3i(40,50,2)));
tube->generate();
rend = GeomRenderer_ptr(new GeometryRenderer(tube));
rend->setPosition(Vec3f(getWindowWidth()/2, getWindowHeight()/2, 0));
rend->renderWireFrame();
tubeLayer->addRenderable(rend);
}
void PotThrowingApp::mouseDown( MouseEvent event )
{
mousePressed = true;
}
void PotThrowingApp::mouseUp( MouseEvent event )
{
mousePressed = false;
}
void PotThrowingApp::update()
{
if(mousePressed){
rotation += 0.01;
}
}
void PotThrowingApp::draw()
{
// clear out the window with black
gl::clear( Color( 0, 0, 0 ) );
ci::Quaternion<float> rot(ci::Vec3f(0,1,0), rotation);
rend->setRotation(rot);
layers->render();
}
CINDER_APP_BASIC( PotThrowingApp, RendererGl )
| [
"benthejack@gmail.com"
] | benthejack@gmail.com |
a80a15d278aca86cd9e17408ca6f24dcf61045b6 | 74d322a09045ff67f2c5f6897719543ed66bea67 | /src/gens-sdl/Options.hpp | 935d1834e1dab8d02ae2d496ee15707e1f74c33a | [] | no_license | LasDesu/gens-gs-ii | 6eb73e7dfe6b2f21d74658eef4e1c1a33e3629e7 | af19f8eadf64b6f2fe07347869d1fb9f9e9de2ef | refs/heads/master | 2021-05-07T00:13:35.880499 | 2017-11-27T08:01:35 | 2017-11-27T08:01:35 | 110,127,163 | 1 | 1 | null | 2017-11-09T14:43:53 | 2017-11-09T14:43:53 | null | UTF-8 | C++ | false | false | 4,622 | hpp | /***************************************************************************
* gens-sdl: Gens/GS II basic SDL frontend. *
* Options.hpp: Command line option parser. *
* *
* Copyright (c) 2015 by David Korth. *
* *
* 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., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
#ifndef __GENS_SDL_OPTIONS_HPP__
#define __GENS_SDL_OPTIONS_HPP__
// LibGens
#include "libgens/Util/MdFb.hpp"
#include "libgens/EmuContext/SysVersion.hpp"
// C++ includes.
#include <string>
namespace GensSdl {
class OptionsPrivate;
class Options
{
public:
Options();
~Options();
private:
friend class OptionsPrivate;
OptionsPrivate *const d;
private:
// Q_DISABLE_COPY() equivalent.
// TODO: Add GensSdl-specific version of Q_DISABLE_COPY().
Options(const Options &);
Options &operator=(const Options &);
public:
/**
* Reset all options to their default values.
*/
void reset(void);
/**
* Parse command line arguments.
* @param argc
* @param argv
* @return 0 on success; non-zero on error.
*/
int parse(int argc, const char *argv[]);
public:
/** Options set by the caller. **/
/**
* Is a ROM filename required?
* @return True if a ROM filename is required; false if not.
*/
bool is_rom_filename_required(void) const;
/**
* Set if a ROM filename should be required.
* @param rom_filename_required True if a ROM filename is required; false if not.
*/
void set_rom_filename_required(bool rom_filename_required);
public:
/** Command line parameters. **/
/**
* Get the filename of the ROM to load.
*/
std::string rom_filename(void) const;
/**
* Get the filename of the TMSS ROM to load.
*/
std::string tmss_rom_filename(void) const;
/**
* Is TMSS enabled?
* This option is implied by the presence of a TMSS ROM filename.
* @return True if TMSS is enabled; false if not.
*/
bool is_tmss_enabled(void) const;
/** Audio options. **/
/**
* Get the requested sound frequency.
* @return Sound frequency.
*/
int sound_freq(void) const;
/**
* Use stereo audio?
* @return True for stereo; false for monaural.
*/
bool stereo(void) const;
/** Emulation options. **/
/**
* Enable sprite limits?
* @return True to enable; false to disable.
*/
bool sprite_limits(void) const;
/**
* Automatically fix checksums?
* @return True to auto-fix; false to not.
*/
bool auto_fix_checksum(void) const;
/**
* Region code.
* @return Region code.
*/
LibGens::SysVersion::RegionCode_t region(void) const;
/** UI options. **/
/**
* Enable the FPS counter?
* @return True to enable; false to disable.
*/
bool fps_counter(void) const;
/**
* Automatically pause the emulator when focus is lost?
* @return True to automatically pause; false to not.
*/
bool auto_pause(void) const;
/**
* Use the paused effect when the emulator is manually paused?
* @return True to use the paused effect; false to not.
*/
bool paused_effect(void) const;
/**
* Color depth to use.
* @return Color depth.
*/
LibGens::MdFb::ColorDepth bpp(void) const;
/** Special run modes. **/
/**
* Run the Crazy Effect instead of loading a ROM?
* @return True to run the Crazy Effect.
*/
bool run_crazy_effect(void) const;
};
}
#endif /* __GENS_SDL_OPTIONS_HPP__ */
| [
"gerbilsoft@gerbilsoft.com"
] | gerbilsoft@gerbilsoft.com |
f8a930c697a783125e73425e9ca1398bd82652e5 | 9f9660f318732124b8a5154e6670e1cfc372acc4 | /Case_save/Case20/case7/1400/p | be244323a5e84bb7f3e6d60a1d03c4bbf2f240c1 | [] | no_license | mamitsu2/aircond5 | 9a6857f4190caec15823cb3f975cdddb7cfec80b | 20a6408fb10c3ba7081923b61e44454a8f09e2be | refs/heads/master | 2020-04-10T22:41:47.782141 | 2019-09-02T03:42:37 | 2019-09-02T03:42:37 | 161,329,638 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,908 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "1400";
object p;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [1 -1 -2 0 0 0 0];
internalField nonuniform List<scalar>
459
(
101324
101324
101324
101324
101324
101324
101324
101324
101324
101324
101324
101324
101324
101324
101324
101324
101324
101324
101324
101324
101324
101324
101324
101324
101324
101324
101324
101324
101324
101324
101324
101324
101324
101324
101321
101321
101321
101321
101321
101321
101321
101321
101321
101321
101321
101321
101321
101321
101321
101322
101322
101322
101322
101322
101322
101322
101322
101322
101322
101322
101322
101322
101322
101322
101322
101322
101322
101322
101322
101322
101319
101319
101319
101319
101319
101319
101319
101319
101319
101319
101319
101319
101319
101319
101319
101319
101319
101319
101319
101319
101319
101319
101319
101319
101319
101319
101319
101319
101319
101319
101319
101319
101319
101319
101319
101319
101317
101317
101317
101317
101317
101317
101317
101317
101317
101317
101317
101317
101317
101317
101317
101317
101317
101317
101317
101317
101317
101317
101317
101317
101317
101317
101317
101317
101317
101317
101317
101317
101317
101317
101317
101317
101317
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101315
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101312
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101310
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101308
101305
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101306
101305
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101303
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101301
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
101299
)
;
boundaryField
{
floor
{
type zeroGradient;
}
ceiling
{
type zeroGradient;
}
sWall
{
type zeroGradient;
}
nWall
{
type zeroGradient;
}
sideWalls
{
type empty;
}
glass1
{
type zeroGradient;
}
glass2
{
type zeroGradient;
}
sun
{
type zeroGradient;
}
heatsource1
{
type zeroGradient;
}
heatsource2
{
type zeroGradient;
}
Table_master
{
type zeroGradient;
}
Table_slave
{
type zeroGradient;
}
inlet
{
type zeroGradient;
}
outlet
{
type fixedValue;
value uniform 101325;
}
}
// ************************************************************************* //
| [
"mitsuaki.makino@tryeting.jp"
] | mitsuaki.makino@tryeting.jp | |
eaa9993880434448fdb31f9b2d44a66bd02d15d3 | 6922a01cd66db8303dddbcedc76d6217bf3462ae | /blimp/client/app/session/blimp_client_session.h | 4d46a068db4bc55d2ba4b1eab512b64f9b63ee12 | [
"BSD-3-Clause"
] | permissive | gowinder/chromium | 7c86a4d3adb63fa3127a23f5cbf3c104927ccb34 | caffce579a5c78540e15a0a280f029abb1781818 | refs/heads/master | 2023-02-21T00:46:39.614680 | 2016-12-01T21:26:16 | 2016-12-01T21:29:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,727 | h | // Copyright 2015 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.
#ifndef BLIMP_CLIENT_APP_SESSION_BLIMP_CLIENT_SESSION_H_
#define BLIMP_CLIENT_APP_SESSION_BLIMP_CLIENT_SESSION_H_
#include <memory>
#include <string>
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/threading/thread.h"
#include "blimp/client/core/compositor/blob_image_serialization_processor.h"
#include "blimp/client/core/session/assignment_source.h"
#include "blimp/client/core/session/network_event_observer.h"
#include "blimp/client/public/session/assignment.h"
#include "blimp/common/proto/blimp_message.pb.h"
#include "blimp/net/blimp_message_processor.h"
namespace blimp {
class BlobChannelReceiver;
class HeliumBlobReceiverDelegate;
class ThreadPipeManager;
namespace client {
class ClientNetworkComponents;
class GeolocationFeature;
class NavigationFeature;
class ImeFeature;
class RenderWidgetFeature;
class TabControlFeature;
// BlimpClientSession represents a single active session of Blimp on the client
// regardless of whether or not the client application is in the background or
// foreground. The only time this session is invalid is during initialization
// and shutdown of this particular client process (or Activity on Android).
//
// This session glues together the feature proxy components and the network
// layer. The network components must be interacted with on the IO thread. The
// feature proxies must be interacted with on the UI thread.
class BlimpClientSession
: public NetworkEventObserver,
public BlobImageSerializationProcessor::ErrorDelegate {
public:
explicit BlimpClientSession(const GURL& assigner_endpoint);
// Uses the AssignmentSource to get an Assignment and then uses the assignment
// configuration to connect to the Blimplet.
// |client_auth_token| is the OAuth2 access token to use when querying
// for an assignment. This token needs the OAuth2 scope of userinfo.email and
// only needs to be an access token, not a refresh token.
void Connect(const std::string& client_auth_token);
TabControlFeature* GetTabControlFeature() const;
NavigationFeature* GetNavigationFeature() const;
ImeFeature* GetImeFeature() const;
RenderWidgetFeature* GetRenderWidgetFeature() const;
// The AssignmentCallback for when an assignment is ready. This will trigger
// a connection to the engine.
virtual void ConnectWithAssignment(AssignmentRequestResult result,
const Assignment& assignment);
protected:
~BlimpClientSession() override;
// Notified every time the AssignmentSource returns the result of an attempted
// assignment request.
virtual void OnAssignmentConnectionAttempted(AssignmentRequestResult result,
const Assignment& assignment);
private:
void RegisterFeatures();
// Terminates the active connection held by |net_connections_| on the IO
// thread. Should be called on the main thread.
void DropConnection();
// NetworkEventObserver implementation.
void OnConnected() override;
void OnDisconnected(int result) override;
// BlobImageSerializationProcessor::ErrorDelegate implementation.
void OnImageDecodeError() override;
base::Thread io_thread_;
// Receives blob BlimpMessages and relays them to BlobChannelReceiver.
// Owned by BlobChannelReceiver, therefore stored as a raw pointer here.
HeliumBlobReceiverDelegate* blob_delegate_ = nullptr;
// Retrieves and decodes image data from |blob_receiver_|. Must outlive
// |blob_receiver_|.
BlobImageSerializationProcessor blob_image_processor_;
std::unique_ptr<BlobChannelReceiver> blob_receiver_;
std::unique_ptr<GeolocationFeature> geolocation_feature_;
std::unique_ptr<TabControlFeature> tab_control_feature_;
std::unique_ptr<NavigationFeature> navigation_feature_;
std::unique_ptr<ImeFeature> ime_feature_;
std::unique_ptr<RenderWidgetFeature> render_widget_feature_;
// The AssignmentSource is used when the user of BlimpClientSession calls
// Connect() to get a valid assignment and later connect to the engine.
std::unique_ptr<AssignmentSource> assignment_source_;
// Container struct for network components.
// Must be deleted on the IO thread.
std::unique_ptr<ClientNetworkComponents> net_components_;
std::unique_ptr<ThreadPipeManager> thread_pipe_manager_;
base::WeakPtrFactory<BlimpClientSession> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(BlimpClientSession);
};
} // namespace client
} // namespace blimp
#endif // BLIMP_CLIENT_APP_SESSION_BLIMP_CLIENT_SESSION_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
3f224af4b5bf0f52b14e68f64488e3662b7c703b | c62ee3eb86a86457daf7eb64cf5a52c3f68b5957 | /GLEngine/Renderer/VertexBuffer.cpp | 87611cb99d7e94d76df9bb6d4d4ab961cb3c2561 | [] | no_license | pawel02/GLEngine | c52b4d5de43ed014c0e7165cf35018dfc57474a9 | da18a89f1b7e9422eeec4983850d03c2160bf54e | refs/heads/master | 2021-07-15T01:10:41.427553 | 2021-01-24T11:41:33 | 2021-01-24T11:41:33 | 231,371,082 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 804 | cpp | #include <glad/glad.h>
#include "VertexBuffer.h"
VertexBuffer::VertexBuffer(unsigned int count) noexcept
:count{count}
{
glGenBuffers(1, &id);
glBindBuffer(GL_ARRAY_BUFFER, id);
glBufferData(GL_ARRAY_BUFFER, count, nullptr, GL_DYNAMIC_DRAW);
}
VertexBuffer::VertexBuffer(unsigned int count, const void* data) noexcept
:count{count}
{
glGenBuffers(1, &id);
glBindBuffer(GL_ARRAY_BUFFER, id);
glBufferData(GL_ARRAY_BUFFER, count, data, GL_STATIC_DRAW);
}
VertexBuffer::~VertexBuffer() noexcept
{
glDeleteBuffers(1, &id);
}
void VertexBuffer::sub_data(unsigned int data_size, const void* data)
{
//setting the dynamic vertex buffer
glBindBuffer(GL_ARRAY_BUFFER, id);
glBufferSubData(GL_ARRAY_BUFFER, 0, data_size, data);
}
void VertexBuffer::bind()
{
glBindBuffer(GL_ARRAY_BUFFER, id);
}
| [
"pawel.bes13@gmail.com"
] | pawel.bes13@gmail.com |
c071ec092a93db5e350434d854126c483f1387b6 | a0a8224b9f737a64fe0d096c38212f1d4c23eaf4 | /Level 1/1.5/1.5.2.cpp | 624570e10500edad3e1439f8353f4a03873675c5 | [] | no_license | HanSong3233/Baruch-Cplusplus-programming-for-FE-Certificate | cb5582eaf1f0beb0710c81f49b8629ba01a16c54 | 83625ae892c50b389755428306ef57ed5ec796b3 | refs/heads/main | 2023-07-15T15:28:56.513042 | 2021-08-31T03:54:52 | 2021-08-31T03:54:52 | 400,758,339 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 342 | cpp | //Exercise 2: write a recursive function that prints the factorials of a number.
#include <stdio.h>
//recieve one value, a, return the factorial.
long factorial(int a)
{
if (a == 0 || a == 1) {
return 1;
}
else
{
return a*factorial(a - 1);
}
}
int main()
{
printf("The value of 6! is %i\n", factorial(6));
} | [
"noreply@github.com"
] | HanSong3233.noreply@github.com |
fd81423e5d98e354edcecf6b0da04c20a4bf9820 | f45198a4daaaff3f98870e3bc7aff1f38bd4f851 | /sort/sort_test.cpp | dc5a94619e67aaa0b0f26c16f90d1c3b387037a6 | [] | no_license | zhsun/neu-cs5800 | da69669d69d09a471746ca968e89b20ea4a56c0f | c8580687ddf8678fdea1c0eb058ef2033d10447d | refs/heads/master | 2020-12-24T13:18:15.754445 | 2016-04-27T01:14:24 | 2016-04-27T01:14:24 | 25,142,755 | 5 | 10 | null | null | null | null | UTF-8 | C++ | false | false | 1,134 | cpp | #include <vector>
#include "gmock/gmock.h"
#include "sort/sort.hpp"
using namespace testing;
TEST(SortTest, ThreeWayPartition) {
std::vector<int> arr = {2,1,2,3,1,2,3,1,2,3,2};
auto itrs = ThreeWayPartition(arr.begin(), arr.end(), std::less<int>());
EXPECT_THAT(*itrs.first, Eq(2));
EXPECT_THAT(*std::prev(itrs.first), Eq(1));
EXPECT_THAT(*itrs.second, Eq(3));
EXPECT_THAT(*std::prev(itrs.second), Eq(2));
arr = {1,1,1,1,1};
itrs = ThreeWayPartition(arr.begin(), arr.end(), std::less<int>());
EXPECT_THAT(itrs.first, Eq(arr.begin()));
EXPECT_THAT(itrs.second, Eq(arr.end()));
}
TEST(SortTest, NullList) {
std::vector<int> arr;
Sort(arr.begin(), arr.end());
EXPECT_THAT(arr, SizeIs(0));
}
TEST(SortTest, SingleElementList) {
std::vector<int> arr = {1};
Sort(arr.begin(), arr.end());
EXPECT_THAT(arr, ElementsAre(1));
}
TEST(SortTest, GeneralCase) {
std::vector<int> arr = {3,2,6,5,1,8,7,9,4,10};
Sort(arr.begin(), arr.end());
EXPECT_THAT(arr, ElementsAre(1,2,3,4,5,6,7,8,9,10));
Sort(arr.begin(), arr.end(), std::greater<int>());
EXPECT_THAT(arr, ElementsAre(10,9,8,7,6,5,4,3,2,1));
}
| [
"austin.zhifeng.sun@gmail.com"
] | austin.zhifeng.sun@gmail.com |
711ece853d3b92e98e9c3022aa53d02f135a52cb | c9ee04b6f891c9aec01ce78b0ce939e4188e0c48 | /ping-pong/pong/pong.ino | ebd2e72dcddb6e2efcc45591f80298e40f64ae09 | [] | no_license | grzsud13/tinybrd-examples | 9ca6a6be897939e9fd919ffe6f1cad17bcf859e6 | 5243be51d079bcb2eed7f1e5443f8e01d5ac7f87 | refs/heads/master | 2021-01-18T02:15:05.427511 | 2016-07-29T15:33:30 | 2016-07-29T15:33:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 720 | ino | #include <SPI.h>
#include <Radio.h>
#define LED 1
void lightOn(unsigned tme = 1000) {
digitalWrite(LED, LOW);
delay(tme);
digitalWrite(LED, HIGH);
delay(tme);
}
void setup() {
// put your setup code here, to run once:
byte address[3] = {1, 0, 0};
Radio.begin(address, 100);
pinMode(LED, OUTPUT);
digitalWrite(LED, HIGH);
for (byte i = 0; i < 5; i++) {
lightOn(100);
}
}
byte pingAddr[3] = { 0, 0, 1 };
byte payload;
void loop() {
// put your main code here, to run repeatedly:
if (Radio.available()) {
lightOn(100);
Radio.read(&payload);
if (payload == 66) {
payload = 99;
Radio.write(pingAddr, payload);
Radio.flush();
lightOn(400);
}
}
}
| [
"rugowski@nhw.pl"
] | rugowski@nhw.pl |
7ddebac618800ed5775e4b2800cefb38c8025d58 | 8a87f5b889a9ce7d81421515f06d9c9cbf6ce64a | /3rdParty/boost/1.78.0/boost/thread/detail/thread_group.hpp | 4105c7346885f46f984fa1f5714e55c22c3565c6 | [
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause",
"ICU",
"Zlib",
"GPL-1.0-or-later",
"OpenSSL",
"ISC",
"LicenseRef-scancode-gutenberg-2020",
"MIT",
"GPL-2.0-only",
"CC0-1.0",
"LicenseRef-scancode-autoconf-simple-exception",
"LicenseRef-scancode-pcre",
"Bison-exception-2.2",
"LicenseRef-scancode... | permissive | arangodb/arangodb | 0980625e76c56a2449d90dcb8d8f2c485e28a83b | 43c40535cee37fc7349a21793dc33b1833735af5 | refs/heads/devel | 2023-08-31T09:34:47.451950 | 2023-08-31T07:25:02 | 2023-08-31T07:25:02 | 2,649,214 | 13,385 | 982 | Apache-2.0 | 2023-09-14T17:02:16 | 2011-10-26T06:42:00 | C++ | UTF-8 | C++ | false | false | 4,279 | hpp | #ifndef BOOST_THREAD_DETAIL_THREAD_GROUP_HPP
#define BOOST_THREAD_DETAIL_THREAD_GROUP_HPP
// 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)
// (C) Copyright 2007-9 Anthony Williams
#include <list>
#include <boost/thread/csbl/memory/unique_ptr.hpp>
#include <boost/thread/shared_mutex.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/lock_guard.hpp>
#include <boost/config/abi_prefix.hpp>
#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable:4251)
#endif
namespace boost
{
class thread_group
{
private:
thread_group(thread_group const&);
thread_group& operator=(thread_group const&);
public:
thread_group() {}
~thread_group()
{
for(std::list<thread*>::iterator it=threads.begin(),end=threads.end();
it!=end;
++it)
{
delete *it;
}
}
bool is_this_thread_in()
{
thread::id id = this_thread::get_id();
boost::shared_lock<shared_mutex> guard(m);
for(std::list<thread*>::iterator it=threads.begin(),end=threads.end();
it!=end;
++it)
{
if ((*it)->get_id() == id)
return true;
}
return false;
}
bool is_thread_in(thread* thrd)
{
if(thrd)
{
thread::id id = thrd->get_id();
boost::shared_lock<shared_mutex> guard(m);
for(std::list<thread*>::iterator it=threads.begin(),end=threads.end();
it!=end;
++it)
{
if ((*it)->get_id() == id)
return true;
}
return false;
}
else
{
return false;
}
}
template<typename F>
thread* create_thread(F threadfunc)
{
boost::lock_guard<shared_mutex> guard(m);
boost::csbl::unique_ptr<thread> new_thread(new thread(threadfunc));
threads.push_back(new_thread.get());
return new_thread.release();
}
void add_thread(thread* thrd)
{
if(thrd)
{
BOOST_THREAD_ASSERT_PRECONDITION( ! is_thread_in(thrd) ,
thread_resource_error(static_cast<int>(system::errc::resource_deadlock_would_occur), "boost::thread_group: trying to add a duplicated thread")
);
boost::lock_guard<shared_mutex> guard(m);
threads.push_back(thrd);
}
}
void remove_thread(thread* thrd)
{
boost::lock_guard<shared_mutex> guard(m);
std::list<thread*>::iterator const it=std::find(threads.begin(),threads.end(),thrd);
if(it!=threads.end())
{
threads.erase(it);
}
}
void join_all()
{
BOOST_THREAD_ASSERT_PRECONDITION( ! is_this_thread_in() ,
thread_resource_error(static_cast<int>(system::errc::resource_deadlock_would_occur), "boost::thread_group: trying joining itself")
);
boost::shared_lock<shared_mutex> guard(m);
for(std::list<thread*>::iterator it=threads.begin(),end=threads.end();
it!=end;
++it)
{
if ((*it)->joinable())
(*it)->join();
}
}
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
void interrupt_all()
{
boost::shared_lock<shared_mutex> guard(m);
for(std::list<thread*>::iterator it=threads.begin(),end=threads.end();
it!=end;
++it)
{
(*it)->interrupt();
}
}
#endif
size_t size() const
{
boost::shared_lock<shared_mutex> guard(m);
return threads.size();
}
private:
std::list<thread*> threads;
mutable shared_mutex m;
};
}
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif
#include <boost/config/abi_suffix.hpp>
#endif
| [
"frank@arangodb.com"
] | frank@arangodb.com |
877a6543eb81dd20377918dccda685f363e64b2d | 7a01fb04eda4110409e65f8880520bc4fcb8f4a6 | /Volume_100/10009.cpp | b7a5d23c38a3015d821685ffddd4d2e0626c48fc | [] | no_license | rawsk/AOJ | 392ee01226181163bc947645adc1e3cc70ca71ac | 2fbfd8cff3a824e539ed9896971ccdfa862a2d51 | refs/heads/master | 2021-05-31T22:25:32.637611 | 2016-06-23T08:24:40 | 2016-06-23T08:24:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 177 | cpp | #include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main(){
double r;
cin>>r;
cout<<fixed<<setprecision(5)<<r*r*M_PI<<" "<<2*r*M_PI<<endl;
}
| [
"jumpei@MacBook-Air.local"
] | jumpei@MacBook-Air.local |
fcee90bccd34e19f7d36e39579312b3810db89e0 | b7e6a21bf7b070306ad14feb3f98ceeee1991230 | /Classes/EntityContainer.h | c56774f512a5f8bf311c141f8db020ec6d1ef029 | [] | no_license | Cookrin/Circle | f3e146f1749ec7b1c44cd95c6e41b53e9b282f47 | bc23d59b8e286b9b5161199f40d7eb917eb11f19 | refs/heads/master | 2021-01-16T00:12:06.028736 | 2015-08-08T23:13:03 | 2015-08-08T23:13:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,301 | h | //
// EntityContainer.h
// DotWar
//
// Created by ryutamaki on 2015/08/07.
//
//
#ifndef __DotWar__EntityContainer__
#define __DotWar__EntityContainer__
#include "cocos2d.h"
#include "Entity.h"
#include "EntityAI.h"
class EntityContainer
{
public:
EntityContainer();
~EntityContainer();
std::map<EntityIdentifier, Entity*> getAllEnemies();
Entity* findEntity(EntityIdentifier identifier);
Entity* findMyself();
EntityAI* findAi(EntityIdentifier identifier);
void addFriend(EntityIdentifier identifier, Entity* entity);
void addEnemy(EntityIdentifier identifier, Entity* entity);
void addAi(EntityIdentifier identifier, EntityAI* entity);
void moveEnemyToCemetery(EntityIdentifier identifier);
void pauseAllEntity();
void resumeAllEntity();
private:
// These are formed for frineds VS enemies
std::map<EntityIdentifier, Entity*> friends;
std::map<EntityIdentifier, Entity*> enemies;
// aiList have all of AIs running whether friends or enemies
std::map<EntityIdentifier, EntityAI*> aiList;
// Body list
std::map<EntityIdentifier, Entity*> cemetery;
Entity* findFriend(EntityIdentifier identifier);
Entity* findEnemy(EntityIdentifier identifier);
};
#endif /* defined(__DotWar__EntityContainer__) */
| [
"ryu.mochi@gmail.com"
] | ryu.mochi@gmail.com |
649caf5f2e1c7319a1bac818f1f0e82552d49a94 | 961c752035c24deb76deeb14499b104abb96e9d7 | /ios/chrome/browser/web_data_service_factory.cc | 882958ebd18b40d5b9384e07cd5baf2af27f657d | [
"BSD-3-Clause"
] | permissive | saosir/chromium | cb7697cb5093d896c8d8ac96dd6cedf7e2aa656c | 9915270eef5f81db061d13fe61f804c54c6a59aa | refs/heads/master | 2023-02-28T21:18:34.554780 | 2018-02-23T09:21:42 | 2018-02-23T09:21:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,203 | cc | // Copyright 2015 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 "ios/chrome/browser/web_data_service_factory.h"
#include "base/bind.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/memory/singleton.h"
#include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
#include "components/keyed_service/core/service_access_type.h"
#include "components/keyed_service/ios/browser_state_dependency_manager.h"
#include "components/search_engines/keyword_web_data_service.h"
#include "components/signin/core/browser/webdata/token_web_data.h"
#include "components/webdata_services/web_data_service_wrapper.h"
#include "ios/chrome/browser/application_context.h"
#include "ios/chrome/browser/browser_state/browser_state_otr_helper.h"
#include "ios/chrome/browser/browser_state/chrome_browser_state.h"
#include "ios/chrome/browser/sync/glue/sync_start_util.h"
#include "ios/web/public/web_thread.h"
namespace ios {
namespace {
void DoNothingOnErrorCallback(WebDataServiceWrapper::ErrorType error_type,
sql::InitStatus status,
const std::string& diagnostics) {}
} // namespace
// static
WebDataServiceWrapper* WebDataServiceFactory::GetForBrowserState(
ios::ChromeBrowserState* browser_state,
ServiceAccessType access_type) {
DCHECK(access_type == ServiceAccessType::EXPLICIT_ACCESS ||
!browser_state->IsOffTheRecord());
return static_cast<WebDataServiceWrapper*>(
GetInstance()->GetServiceForBrowserState(browser_state, true));
}
// static
WebDataServiceWrapper* WebDataServiceFactory::GetForBrowserStateIfExists(
ios::ChromeBrowserState* browser_state,
ServiceAccessType access_type) {
DCHECK(access_type == ServiceAccessType::EXPLICIT_ACCESS ||
!browser_state->IsOffTheRecord());
return static_cast<WebDataServiceWrapper*>(
GetInstance()->GetServiceForBrowserState(browser_state, false));
}
// static
scoped_refptr<autofill::AutofillWebDataService>
WebDataServiceFactory::GetAutofillWebDataForBrowserState(
ios::ChromeBrowserState* browser_state,
ServiceAccessType access_type) {
WebDataServiceWrapper* wrapper =
GetForBrowserState(browser_state, access_type);
return wrapper ? wrapper->GetAutofillWebData() : nullptr;
}
// static
scoped_refptr<KeywordWebDataService>
WebDataServiceFactory::GetKeywordWebDataForBrowserState(
ios::ChromeBrowserState* browser_state,
ServiceAccessType access_type) {
WebDataServiceWrapper* wrapper =
GetForBrowserState(browser_state, access_type);
return wrapper ? wrapper->GetKeywordWebData() : nullptr;
}
// static
scoped_refptr<TokenWebData>
WebDataServiceFactory::GetTokenWebDataForBrowserState(
ios::ChromeBrowserState* browser_state,
ServiceAccessType access_type) {
WebDataServiceWrapper* wrapper =
GetForBrowserState(browser_state, access_type);
return wrapper ? wrapper->GetTokenWebData() : nullptr;
}
// static
WebDataServiceFactory* WebDataServiceFactory::GetInstance() {
return base::Singleton<WebDataServiceFactory>::get();
}
WebDataServiceFactory::WebDataServiceFactory()
: BrowserStateKeyedServiceFactory(
"WebDataService",
BrowserStateDependencyManager::GetInstance()) {
}
WebDataServiceFactory::~WebDataServiceFactory() {
}
std::unique_ptr<KeyedService> WebDataServiceFactory::BuildServiceInstanceFor(
web::BrowserState* context) const {
const base::FilePath& browser_state_path = context->GetStatePath();
return std::make_unique<WebDataServiceWrapper>(
browser_state_path, GetApplicationContext()->GetApplicationLocale(),
web::WebThread::GetTaskRunnerForThread(web::WebThread::UI),
ios::sync_start_util::GetFlareForSyncableService(browser_state_path),
base::BindRepeating(&DoNothingOnErrorCallback));
}
web::BrowserState* WebDataServiceFactory::GetBrowserStateToUse(
web::BrowserState* context) const {
return GetBrowserStateRedirectedInIncognito(context);
}
bool WebDataServiceFactory::ServiceIsNULLWhileTesting() const {
return true;
}
} // namespace ios
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
14a521804f2cdbb3e381f37c643e00325b950051 | 13500b849db6d62ac7ee94e32ddd76681af79d6b | /1022/1032.cpp | 1ddc71812cc914269ea68f9c7c8da8328599f494 | [] | no_license | syjsu/noip-with-vue.js | 055a90d13dedd2c00b2d449a39fa4f3128270480 | 6076cd41b5343dd3ff18b4c4afec207021f8c78b | refs/heads/master | 2020-03-17T20:15:42.362689 | 2018-05-24T05:10:27 | 2018-05-24T05:10:27 | 133,900,801 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 261 | cpp | #include<iostream>
#include<iomanip>
using namespace std;
int main(){
int n,age[105];
float avage=0;
cin>>n;
for(int i=0;i<n;i++) {
cin>>age[i];
avage=avage+age[i];
}
avage=avage/n;
cout<<setprecision(2)<<fixed<<avage;
return 0;
}
| [
"syjsu@qq.com"
] | syjsu@qq.com |
cb764bfd2eec20b5dae8f71932b1bb51f0503c29 | 5e1ee2224baa53af579f54eb5c0d5c7a872d5594 | /ch12/prog12_7.cpp | 0801f35cff9f5a010da907ad68d6bcf805c90f29 | [] | no_license | PengYuHsiang/cpp_practice | 8f347675f5336ff43b01f1ed4e9c750a44ef83dd | 82446c591b2158814fb0035b12541a4b57bf7fbb | refs/heads/main | 2023-06-18T23:44:58.296154 | 2021-07-18T13:19:18 | 2021-07-18T13:19:18 | 387,179,494 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 485 | cpp | // prog12_7, 將函數定義於類別之外
# include <iostream>
# include <cstdlib>
using namespace std;
class CWin
{
public:
char id;
int width;
int height;
int area(void); // 成員函數 area() 的原型
};
int CWin::area(void)
{
return width * height;
}
int main(void)
{
CWin win1;
win1.id = 'A';
win1.width = 50;
win1.height = 40;
cout << "Window " << win1.id << ":" << endl;
cout << "Area = " << win1.area() << endl;
system("pause");
return 0;
}
| [
"shan599603@163.com"
] | shan599603@163.com |
e2da300f7affcc1b99aacb28666c63872e923650 | 0d4045acc9f0efc2cf38e8b9dee4f178d5e77f06 | /test/unit/map/test_split_michael_rcu.h | c2b12533edbc37f713950f1c1d483c017b3d8dfa | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | Tsiannian/libcds | f69b32840ae87fe195915cb59421fdbffb856320 | 1223f3c790581a0f741cffdd46fa20ed1a3da498 | refs/heads/master | 2021-01-11T06:10:32.821647 | 2016-10-17T11:50:10 | 2016-10-17T11:50:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,318 | h | /*
This file is a part of libcds - Concurrent Data Structures library
(C) Copyright Maxim Khizhinsky (libcds.dev@gmail.com) 2006-2016
Source code repo: http://github.com/khizmax/libcds/
Download: http://sourceforge.net/projects/libcds/files/
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CDSUNIT_MAP_TEST_SPLIT_LIST_MICHAEL_RCU_H
#define CDSUNIT_MAP_TEST_SPLIT_LIST_MICHAEL_RCU_H
#include "test_map_rcu.h"
#include <cds/container/michael_list_rcu.h>
#include <cds/container/split_list_map_rcu.h>
#include <cds/intrusive/free_list.h>
namespace cc = cds::container;
template <class RCU>
class SplitListMichaelMap: public cds_test::container_map_rcu
{
typedef cds_test::container_map_rcu base_class;
public:
typedef cds::urcu::gc<RCU> rcu_type;
protected:
void SetUp()
{
RCU::Construct();
cds::threading::Manager::attachThread();
}
void TearDown()
{
cds::threading::Manager::detachThread();
RCU::Destruct();
}
};
TYPED_TEST_CASE_P( SplitListMichaelMap );
TYPED_TEST_P( SplitListMichaelMap, compare )
{
typedef typename TestFixture::rcu_type rcu_type;
typedef typename TestFixture::key_type key_type;
typedef typename TestFixture::value_type value_type;
typedef typename TestFixture::hash1 hash1;
typedef cc::SplitListMap< rcu_type, key_type, value_type,
typename cc::split_list::make_traits<
cc::split_list::ordered_list< cc::michael_list_tag >
, cds::opt::hash< hash1 >
, cc::split_list::ordered_list_traits<
typename cc::michael_list::make_traits<
cds::opt::compare< typename TestFixture::cmp >
>::type
>
>::type
> map_type;
map_type m( TestFixture::kSize, 2 );
this->test( m );
}
TYPED_TEST_P( SplitListMichaelMap, less )
{
typedef typename TestFixture::rcu_type rcu_type;
typedef typename TestFixture::key_type key_type;
typedef typename TestFixture::value_type value_type;
typedef typename TestFixture::hash1 hash1;
typedef cc::SplitListMap< rcu_type, key_type, value_type,
typename cc::split_list::make_traits<
cc::split_list::ordered_list< cc::michael_list_tag >
, cds::opt::hash< hash1 >
, cc::split_list::ordered_list_traits<
typename cc::michael_list::make_traits<
cds::opt::less< typename TestFixture::less >
>::type
>
>::type
> map_type;
map_type m( TestFixture::kSize, 2 );
this->test( m );
}
TYPED_TEST_P( SplitListMichaelMap, cmpmix )
{
typedef typename TestFixture::rcu_type rcu_type;
typedef typename TestFixture::key_type key_type;
typedef typename TestFixture::value_type value_type;
typedef typename TestFixture::hash1 hash1;
typedef cc::SplitListMap< rcu_type, key_type, value_type,
typename cc::split_list::make_traits<
cc::split_list::ordered_list< cc::michael_list_tag >
, cds::opt::hash< hash1 >
, cc::split_list::ordered_list_traits<
typename cc::michael_list::make_traits<
cds::opt::less< typename TestFixture::less >
, cds::opt::compare< typename TestFixture::cmp >
>::type
>
>::type
> map_type;
map_type m( TestFixture::kSize, 3 );
this->test( m );
}
TYPED_TEST_P( SplitListMichaelMap, item_counting )
{
typedef typename TestFixture::rcu_type rcu_type;
typedef typename TestFixture::key_type key_type;
typedef typename TestFixture::value_type value_type;
typedef typename TestFixture::hash1 hash1;
struct map_traits: public cc::split_list::traits
{
typedef cc::michael_list_tag ordered_list;
typedef hash1 hash;
typedef cds::atomicity::item_counter item_counter;
struct ordered_list_traits: public cc::michael_list::traits
{
typedef typename TestFixture::cmp compare;
typedef typename TestFixture::less less;
typedef cds::backoff::empty back_off;
};
};
typedef cc::SplitListMap< rcu_type, key_type, value_type, map_traits > map_type;
map_type m( TestFixture::kSize, 8 );
this->test( m );
}
TYPED_TEST_P( SplitListMichaelMap, stat )
{
typedef typename TestFixture::rcu_type rcu_type;
typedef typename TestFixture::key_type key_type;
typedef typename TestFixture::value_type value_type;
typedef typename TestFixture::hash1 hash1;
struct map_traits: public cc::split_list::traits
{
typedef cc::michael_list_tag ordered_list;
typedef hash1 hash;
typedef cds::atomicity::item_counter item_counter;
typedef cc::split_list::stat<> stat;
struct ordered_list_traits: public cc::michael_list::traits
{
typedef typename TestFixture::less less;
typedef cds::opt::v::sequential_consistent memory_model;
};
};
typedef cc::SplitListMap< rcu_type, key_type, value_type, map_traits > map_type;
map_type m( TestFixture::kSize, 4 );
this->test( m );
}
TYPED_TEST_P( SplitListMichaelMap, back_off )
{
typedef typename TestFixture::rcu_type rcu_type;
typedef typename TestFixture::key_type key_type;
typedef typename TestFixture::value_type value_type;
typedef typename TestFixture::hash1 hash1;
struct map_traits: public cc::split_list::traits
{
typedef cc::michael_list_tag ordered_list;
typedef hash1 hash;
typedef cds::atomicity::item_counter item_counter;
typedef cds::backoff::yield back_off;
typedef cds::opt::v::sequential_consistent memory_model;
struct ordered_list_traits: public cc::michael_list::traits
{
typedef typename TestFixture::cmp compare;
typedef cds::backoff::pause back_off;
};
};
typedef cc::SplitListMap< rcu_type, key_type, value_type, map_traits > map_type;
map_type m( TestFixture::kSize, 2 );
this->test( m );
}
TYPED_TEST_P( SplitListMichaelMap, free_list )
{
typedef typename TestFixture::rcu_type rcu_type;
typedef typename TestFixture::key_type key_type;
typedef typename TestFixture::value_type value_type;
typedef typename TestFixture::hash1 hash1;
struct map_traits: public cc::split_list::traits
{
typedef cc::michael_list_tag ordered_list;
typedef hash1 hash;
typedef cds::intrusive::FreeList free_list;
struct ordered_list_traits: public cc::michael_list::traits
{
typedef typename TestFixture::cmp compare;
typedef cds::backoff::pause back_off;
};
};
typedef cc::SplitListMap< rcu_type, key_type, value_type, map_traits > map_type;
map_type m( TestFixture::kSize, 2 );
this->test( m );
}
namespace {
struct set_static_traits: public cc::split_list::traits
{
static bool const dynamic_bucket_table = false;
};
}
TYPED_TEST_P( SplitListMichaelMap, static_bucket_table )
{
typedef typename TestFixture::rcu_type rcu_type;
typedef typename TestFixture::key_type key_type;
typedef typename TestFixture::value_type value_type;
typedef typename TestFixture::hash1 hash1;
struct map_traits: public set_static_traits
{
typedef cc::michael_list_tag ordered_list;
typedef hash1 hash;
typedef cds::atomicity::item_counter item_counter;
struct ordered_list_traits: public cc::michael_list::traits
{
typedef typename TestFixture::cmp compare;
typedef cds::backoff::pause back_off;
};
};
typedef cc::SplitListMap< rcu_type, key_type, value_type, map_traits > map_type;
map_type m( TestFixture::kSize, 4 );
this->test( m );
}
TYPED_TEST_P( SplitListMichaelMap, static_bucket_table_free_list )
{
typedef typename TestFixture::rcu_type rcu_type;
typedef typename TestFixture::key_type key_type;
typedef typename TestFixture::value_type value_type;
typedef typename TestFixture::hash1 hash1;
struct map_traits: public set_static_traits
{
typedef cc::michael_list_tag ordered_list;
typedef hash1 hash;
typedef cds::atomicity::item_counter item_counter;
typedef cds::intrusive::FreeList free_list;
struct ordered_list_traits: public cc::michael_list::traits
{
typedef typename TestFixture::cmp compare;
typedef cds::backoff::pause back_off;
};
};
typedef cc::SplitListMap< rcu_type, key_type, value_type, map_traits > map_type;
map_type m( TestFixture::kSize, 4 );
this->test( m );
}
REGISTER_TYPED_TEST_CASE_P( SplitListMichaelMap,
compare, less, cmpmix, item_counting, stat, back_off, free_list, static_bucket_table, static_bucket_table_free_list
);
#endif // CDSUNIT_MAP_TEST_SPLIT_LIST_MICHAEL_RCU_H
| [
"libcds.dev@gmail.com"
] | libcds.dev@gmail.com |
d77554abdc4fd685ce166eaedb780692b57ba425 | baaffedc8e424d7cdba5581e530875f03d284c90 | /OpenMP/par_omp_sort.cpp | 0e421a3e1744c56cf82f7526bd3d6e7a1cdf47eb | [] | no_license | 0xfff/Multithreading | d0d7fc4ea95224803871de5bf64b82ed167f2999 | ec3ca836b1a980956676f4374b7c7c12f54724fe | refs/heads/master | 2021-01-13T01:04:39.669251 | 2016-01-29T23:27:10 | 2016-01-29T23:27:10 | 50,697,110 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,891 | cpp | /*
OpenMP sort
Albert Szmigielski
alberts@alumni.sfu.ca
to compile: g++ -g par_omp_sort.cpp -o par_omp_sort -fopenmp
usage: ./par_omp_sort <number of threads> <size of list>
**<number of threads> must be power of two
*/
#include <algorithm>
#include <math.h>
#include <iostream>
#include <omp.h>
using namespace std;
int Num_Threads=4; //default is 4 can be changed via argument
int size =1000000; //default is 1M can be chaged via argument
/************************** PAR MERGE ******************************/
void par_merge(float * Array, int num_lists, int mul, int interval){
//merge until 1 list left
//merge list 1&2, 3&4, ... (n-1 & n)
mul = mul*2;
int par_merge_threads = num_lists/2;
if (num_lists > 1){
#pragma omp parallel num_threads(par_merge_threads)
{
int start = interval * omp_get_thread_num() *mul;
int end = interval * (omp_get_thread_num()+1) *mul ;
int middle = floor(start+ (end - start)/2);
if (omp_get_thread_num() == par_merge_threads-1)
{ end=size; }
inplace_merge(&Array[start], &Array[middle], &Array[end]);
}
num_lists = ceil(num_lists/2);
par_merge (Array, num_lists, mul, interval);
}
}
/************************** PAR SORT ******************************/
void par_sort (float * Array) {
// break into num_threads chunks, sort each chunk
int interval = floor(size/Num_Threads);
#pragma omp parallel num_threads(Num_Threads)
{
int start = interval * omp_get_thread_num();
int end = interval * (omp_get_thread_num()+1) ;
if (omp_get_thread_num() == Num_Threads-1)
{end=size;}
sort (&Array[start], &Array[end]);
}
par_merge(Array, Num_Threads, 1, interval);
}
/**************************** MAIN **********************************/
int main (int argc, char** argv) {
double start_s, start_p, end_s, end_p;
float * Array, * Array1;
if (argc>1) Num_Threads= atoi(argv[1]);
if (argc>2) size = atoi(argv[2]);
int range = 100, error=0;
Array = new float [size];
Array1 = new float [size];
#pragma omp parallel for
for (int i=0; i<size; i++){
Array[i] = (rand()/(RAND_MAX +1.0));
Array1[i] = Array[i];
}
//time sequential sort
start_s = omp_get_wtime( );
sort(&Array1[0], &Array1[size]);
end_s = omp_get_wtime( );
//time parallel sort
start_p = omp_get_wtime( );
par_sort(Array);
end_p = omp_get_wtime( );
//check correctness
#pragma omp parallel for
for (int i=0; i<size;i++){
if (Array[i] != Array1[i]){
cout << " Error " << "position "<< i ;
error = 1;
}
}
if (error) cout << "ERROR \n ";
else cout << "OK \n";
cout << "Sorted " << size << " numbers with seq. sort in "<< end_s - start_s << " seconds\n" ;
cout << "Sorted " << size << " numbers with par. sort in "<< end_p - start_p << " seconds\n" ;
//cout << Num_Threads << ", " << size << ", " << (end_s - start_s) << ", " << (end_p - start_p) <<"\n";
return 0;
}
| [
"aws.htc@gmail.com"
] | aws.htc@gmail.com |
936606a1b839e927e0fcd86cd4c9b754c4d0fc61 | 838caca7c7370b1bae4ea93d5f191bfc6e87f008 | /10DaysOfStatistics/Day5/Day5_Normal_Distribution_II/main.cpp | f4c0b45a0cefefaf45c72363656c11bae3326fc8 | [] | no_license | gonzrubio/HackerRank- | 2da265df5ea253a63f16be955e2a0f651b55a7b2 | 68744f6f7e17344857d7975e7abce5848dd1448f | refs/heads/master | 2023-08-15T07:50:46.822636 | 2021-09-22T18:13:02 | 2021-09-22T18:13:02 | 259,689,015 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,358 | cpp | /*
The final grades for a Physics exam taken by a large group of students has a mean of 70 and a standard deviation of 10.
If we can approximate the distribution of these grades by a normal distribution, what percentage of the students:
1) Scored higher than 80 (i.e., have a grade>80)?
2) Passed the test (i.e., have a grade>=60)?
3) Failed the test (i.e., have a grade<60)?
*/
#include <iostream>
#include <array>
#include <cmath>
float cum_prob_normal(float x, float mu, float stdev)
{
return 0.5 * (1 + std::erf( (x-mu) / (stdev*std::sqrt(2)) ) ) ;
}
int main()
{
/// Hard coded for testing.
//const int mu = 70 ; // Mean.
//const int sigma = 10 ; // Standard deviation.
//const int grade = 80 ; // First test score.
//const int pass = 60 ; // Minumum passing score.
/// Read input from STDIN.
float mu, sigma, grade, pass ;
std::cin >> mu ;
std::cin >> sigma ;
std::cin >> grade ;
std::cin >> pass ;
/// 1) Percentage of students with 100*P(grade>80)=100*(F(inf)-F(80)).
printf("%.2f\n",100*(1-cum_prob_normal(grade,mu,sigma))) ;
/// 2) Percentage of students with 100*P(grade>=60).
printf("%.2f\n",100*(1-cum_prob_normal(pass,mu,sigma))) ;
/// 3) Percentage of students with 100*P(grade<60).
printf("%.2f\n",100*cum_prob_normal(pass,mu,sigma)) ;
return 0 ;
}
| [
"gonzrubio95@gmail.com"
] | gonzrubio95@gmail.com |
5237e85a2d206b3dad248a1a09c1789fd0045892 | 0e7f8e0f00761aa8d67f7a506c0077f81c378a2f | /src/algorithms/tests/test_tree_brl.cc~ | 9a802e523a9f7d03d8a70a87c997599699ad53d9 | [] | no_license | revorg7/beliefbox | afbad4e0721df69ea211bce4d80b57214c3f7cc5 | ba974b17fbb46ac98960f31dea66115be470000e | refs/heads/master | 2022-09-11T05:23:53.823017 | 2018-07-01T00:32:26 | 2018-07-01T00:32:26 | 127,618,545 | 0 | 1 | null | 2018-04-01T10:19:12 | 2018-04-01T10:19:12 | null | UTF-8 | C++ | false | false | 6,639 | /* -*- Mode: C++; -*- */
// copyright (c) 2006-2017 by Christos Dimitrakakis <christos.dimitrakakis@gmail.com>
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#ifdef MAKE_MAIN
/// Other things
#include "MersenneTwister.h"
/// Bayesian RL includes
#include "DiscreteMDPCounts.h"
/// The main thing to test
#include "TreeBRL.h"
//for comparision
#include "MDPModel.h"
#include "SampleBasedRL.h"
/// The basic environments
#include "ContextBandit.h"
#include "DiscreteChain.h"
#include "Blackjack.h"
#include "InventoryManagement.h"
#include "RandomMDP.h"
/// STD
#include <iostream>
#include <memory>
#include <algorithm> //for shuffle
using namespace std;
real RunExperiment(shared_ptr<DiscreteEnvironment> environment,
TreeBRL& tree,
int n_steps, SampleBasedRL* sampling,unordered_map<int,int> rotator);
int main(int argc, char** argv) {
// use a high-quality RNG for the main program
RandomNumberGenerator* rng;
MersenneTwisterRNG mersenne_twister;
rng = (RandomNumberGenerator*) &mersenne_twister;
// use some arbitrary sequence (e.g. a fixed file) for generating environments, to ensure consistency across runs
DefaultRandomNumberGenerator default_rng;
RandomNumberGenerator* env_rng = (RandomNumberGenerator*) &default_rng;
rng->seed();
env_rng->manualSeed(982374523);
int n_states = 5;
int n_actions = 2;
real discounting = 0.999;
int n_steps = 1000;
// To remove any indexing bias
std::vector<int> action_list;
for (int i=0;i<n_actions;++i) action_list.push_back(i);
std::random_shuffle(action_list.begin(),action_list.end());
std::unordered_map<int, int> randomizer;
for (int i=0;i<n_actions;++i) randomizer[i]=action_list[i];
for (int i=0;i<n_actions;++i) printf("action %d is %d\n",i,randomizer[i]);
///
// int n_samples = 2; ///< number of state samples when branching
//int n_mdp_samples = 2; ///< number of MDP samples at leaf nodes
// ---- user options ---- //
int planning_horizon = 3;
int leaf_value = 0;
int n_experiments = 1;
if (argc > 1) {
planning_horizon = atoi(argv[1]);
}
if (argc > 2) {
leaf_value = atoi(argv[2]);
}
if (argc > 3) {
n_experiments = atoi(argv[3]);
}
if (argc > 4) {
n_steps = atoi(argv[4]);
}
if (argc > 5) {
discounting = atof(argv[5]);
}
printf("# Making environment\n");
shared_ptr<DiscreteEnvironment> environment;
environment = make_shared<DiscreteChain>(n_states);
//environment = make_shared<ContextBandit>(n_states, n_actions, env_rng, false);
//environment = make_shared<Blackjack>(env_rng);
//environment = make_shared<RandomMDP>(n_states, n_actions, 0.1, -0.1, -1, 1, env_rng);
// environment = make_shared<InventoryManagement>(10, 5, 0.2, 0.1);-= n_states = environment->getNStates();
n_actions = environment->getNActions();
#if 0
//simplify things by fixing the rewards
printf("# Setting up belief\n");
Matrix rewards(n_states, n_actions);
for (int s=0; s<n_states; ++s) {
for (int a=0; a<n_actions; ++a) {
rewards(s,a) = environment->getExpectedReward(s, a);
}
}
belief.setFixedRewards(rewards);
#endif
printf("# full sampling\n");
real dirichlet_mass = 0.5;
enum DiscreteMDPCounts::RewardFamily reward_prior = DiscreteMDPCounts::BETA;
DiscreteMDPCounts belief(n_states, n_actions, dirichlet_mass, reward_prior);
//NullMDPModel belief(n_states, n_actions);
// Adding for comparision to USAMPLING
DiscreteMDPCounts* discrete_mdp = new DiscreteMDPCounts(n_states, n_actions,
dirichlet_mass,
reward_prior);
MDPModel* model= (MDPModel*) discrete_mdp;
int max_samples = 2;
real epsilon = 0.01;
SampleBasedRL* sampling = new SampleBasedRL(n_states,
n_actions,
discounting,
epsilon,
model,
rng,
max_samples,
true);
// if (use_sampling_threshold) {
// sampling->setSamplingThreshold(sampling_threshold);
// }
////
Vector U(n_experiments);
for (int experiment=0;
experiment<n_experiments;
experiment++) {
TreeBRL tree (n_states, n_actions, discounting, &belief, rng, planning_horizon, (TreeBRL::LeafNodeValue) leaf_value);
// Set state to 0
real total_reward = RunExperiment(environment, tree, n_steps,sampling,randomizer);
printf("H:%d,\tV:%d,\tR:%f\n", planning_horizon, leaf_value,total_reward);
U(experiment) = total_reward;
}
printf("L:%f,\tM:%f,\tU:%f\n",
Min(U),
U.Sum() / (real) U.Size(),
Max(U));
return 0;
}
real RunExperiment(shared_ptr<DiscreteEnvironment> environment,
TreeBRL& tree,
int n_steps,SampleBasedRL* sampling,unordered_map<int,int> rotater )
{
environment->Reset();
tree.Reset(environment->getState());
real reward = environment->getReward();
real total_reward = 0;
for (int t=0; t<n_steps; ++t) {
int state = environment->getState();
int action = tree.Act(reward, state);
//int action = sampling->Act(reward,state);
action = rotater[action];
bool action_OK = environment->Act(action);
reward = environment->getReward();
total_reward += reward;
printf("%d %d %f # reward\n", state, action, reward);
if (!action_OK) {
state = environment->getState();
reward = environment->getReward();
tree.Act(reward, state);
environment->Reset();
tree.Reset(environment->getState());
}
}
return total_reward;
}
#endif
| [
"revorg7@gmail.com"
] | revorg7@gmail.com | |
12f2d95f5d5ffbb2228f2d183adc3177510da47a | fc1a35d05497f7d9fee41850379dfd526635bc9a | /OI/纪中刘远哲/2015/10.17/4.cpp | 7f56911798f26ea93998390081c4fd67984107a7 | [] | no_license | lyz05/Sources | addf71b9f40bb52233f12e84e2f7bdbb4d3db9a7 | 20939b1aca08af49498f56468af025aaf7a18594 | refs/heads/master | 2023-04-30T15:14:09.157298 | 2022-04-24T05:06:24 | 2022-04-24T05:06:24 | 52,012,937 | 5 | 0 | null | 2023-04-21T20:45:23 | 2016-02-18T14:27:04 | HTML | UTF-8 | C++ | false | false | 542 | cpp | #include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
const int N = 55;
int n,m,ans,tmp,a[N];
void dfs(int dep,int last)
{
if (dep>a[0])
{
ans += tmp;
return;
}
for (int i=1;i<=n;i ++)
{
if (a[i]==0 || i==last) continue;
a[i] --;
dfs(dep+1,i);
a[i] ++;
}
}
int main()
{
freopen("photo.in","r",stdin);
freopen("photo.out","w",stdout);
tmp = 1;
scanf("%d",&n);
for (int i=1;i<=n;i ++)
scanf("%d",a+i), a[0]+=a[i] ,tmp*=a[i];
dfs(1,0);
printf("%d\n",ans);
return 0;
}
| [
"liuyuanzhe0515@gmail.com"
] | liuyuanzhe0515@gmail.com |
81d7ac9ccb2dfe96b126fa0ebe7eee36a654958f | 5fd58852ea5be79c65d8fcb86c8661c4a1fe7fb9 | /Gem.h | 35a830fe2d1fee828bbcd371deb4ab94a5f45fe5 | [] | no_license | dunco64/dunco64 | 7b2f1cf841fb55c48ef151ddad763695ad04e38d | 0dec54bf649abf80c51016af0c26db4c151e29cb | refs/heads/master | 2020-05-16T00:54:20.088355 | 2019-04-21T22:53:31 | 2019-04-21T22:53:31 | 182,590,180 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 443 | h | #pragma once
#include "GameObject.h"
#include "Constants.h"
namespace GameDev2D
{
class Gem : public GameObject
{
public:
Gem(const Vector2& startingPosition);
~Gem();
void Update(double delta) override;
void Draw(SpriteBatch* spriteBatch) override;
void Reset() override;
float GetWidth() override;
float GetHeight() override;
private:
SpriteAtlas* m_Gem;
Vector2 m_StartingPosition;
};
} | [
"noreply@github.com"
] | dunco64.noreply@github.com |
cb4c582623a6f749d345c14799b31cd778e16630 | d84bc44c45e20737fd65fddc6e2b135da7494922 | /bench/sv6/bin/countbench.cc | 46d0a91efebe9326b88b70bcaa27f533c7fdcb78 | [
"MIT"
] | permissive | yunshengtw/scftl | 6693584cfc07d9aed200eb6adc0e3729bed75a7c | c3ea3347071461241e3799e2cac46859e0bb64da | refs/heads/master | 2023-02-21T09:46:45.707790 | 2021-01-21T06:49:24 | 2021-01-21T06:49:24 | 289,423,994 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,941 | cc | // Benchmark physical page reference counting in the VM system by
// repeatedly duplicating and unmapping a physical page in several
// threads. Ideally, we would have a unified buffer cache and we
// could use that to duplicate this page, but we don't, so we use a
// hack in the VM system that lets us directly duplicate a page.
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include "libutil.h"
#include "compiler.h"
#include "types.h"
#include "user.h"
#include "amd64.h"
#include "pthread.h"
#include "bits.hh"
#include "kstats.hh"
#include "xsys.h"
#include <xv6/perf.h>
#define PGSIZE 4096
#define XSTR(x) #x
#define STR(x) XSTR(x)
enum { verbose = 0 };
enum { duration = 5 };
// XXX(Austin) Do this right. Put these in a proper PMC library.
#if defined(HW_tom)
#define PERF_amd
#elif defined(HW_josmp) || defined(HW_ben)
#define PERF_intel
#endif
// PMCs
enum {
pmc_llc_misses = 0x2e|(0x41<<8),
#if defined(PERF_intel)
pmc_l2_cache_misses = 0x24|(0xAA<<8), // L2_RQSTS.MISS
pmc_l2_prefetch_misses = 0x24|(0x80<<8), // L2_RQSTS.PREFETCH_MISS
pmc_mem_load_retired_other_core_l2_hit_hitm = 0xcb|(0x08<<8),
pmc_mem_load_retired_l3_miss = 0xcb|(0x10<<8),
#elif defined(PERF_amd)
pmc_l2_cache_misses = 0x7e|((0x2|0x8)<<8),
#endif
};
#if !defined(LINUX) && !defined(HW_qemu) && !defined(HW_codex) && !defined(HW_mtrace)
#define RECORD_PMC pmc_l2_cache_misses
#define PMCNO 0
#endif
char * const base = (char*)0x100000000UL;
static int nthread;
static pthread_barrier_t bar;
static volatile bool stop __mpalign__;
static __padout__ __attribute__((unused));
static uint64_t start_tscs[NCPU], stop_tscs[NCPU];
static std::atomic<uint64_t> iters;
#ifdef RECORD_PMC
static std::atomic<uint64_t> pmcs;
#endif
static char src[4096] __attribute__((aligned(4096)));
void*
timer_thread(void *)
{
sleep(duration);
stop = true;
return NULL;
}
#ifdef LINUX
static inline uint64_t
rdpmc(uint32_t ecx)
{
uint32_t hi, lo;
__asm volatile("rdpmc" : "=a" (lo), "=d" (hi) : "c" (ecx));
return ((uint64_t) lo) | (((uint64_t) hi) << 32);
}
#endif
#ifndef XV6_USER
struct kstats
{
kstats operator-(const kstats &o) {
return kstats{};
}
};
#endif
static void
read_kstats(kstats *out)
{
#ifdef XV6_USER
int fd = open("/dev/kstats", O_RDONLY);
if (fd < 0)
die("Couldn't open /dev/kstats");
int r = xread(fd, out, sizeof *out);
if (r != sizeof *out)
die("Short read from /dev/kstats");
close(fd);
#endif
}
void*
thr(void *arg)
{
const uintptr_t cpu = (uintptr_t)arg;
if (setaffinity(cpu) < 0)
die("setaffinity err");
pthread_barrier_wait(&bar);
start_tscs[cpu] = rdtsc();
uint64_t myiters = 0;
#ifdef RECORD_PMC
uint64_t pmc1 = rdpmc(PMCNO);
#endif
void *p = base + cpu * 0x100000000;
while (!stop) {
if (dup_page(p, src) < 0)
die("dup_page failed");
if (munmap(p, PGSIZE) < 0)
die("munmap failed");
++myiters;
}
stop_tscs[cpu] = rdtsc();
#ifdef RECORD_PMC
pmcs += rdpmc(PMCNO) - pmc1;
#endif
iters += myiters;
return nullptr;
}
uint64_t
summarize_tsc(const char *label, uint64_t tscs[], unsigned count)
{
uint64_t min = tscs[0], max = tscs[0], total = 0;
for (unsigned i = 0; i < count; ++i) {
if (tscs[i] < min)
min = tscs[i];
if (tscs[i] > max)
max = tscs[i];
total += tscs[i];
}
printf("%lu cycles %s skew\n", max - min, label);
return total/count;
}
template<class T>
T
sum(T v[], unsigned count)
{
T res{};
for (unsigned i = 0; i < count; ++i)
res += v[i];
return res;
}
int
main(int argc, char **argv)
{
if (argc < 2)
die("usage: %s nthreads", argv[0]);
nthread = atoi(argv[1]);
printf("# --cores=%d --duration=%ds",
nthread, duration);
printf("\n");
#ifdef RECORD_PMC
perf_start(PERF_SEL_USR|PERF_SEL_OS|PERF_SEL_ENABLE|RECORD_PMC, 0);
#endif
assert((uintptr_t)src % PGSIZE == 0);
// Fault it in
src[0] = 0;
pthread_t timer;
pthread_create(&timer, NULL, timer_thread, NULL);
pthread_t* tid = (pthread_t*) malloc(sizeof(*tid)*nthread);
pthread_barrier_init(&bar, 0, nthread);
for(int i = 0; i < nthread; i++)
xthread_create(&tid[i], 0, thr, (void*)(uintptr_t) i);
struct kstats kstats_before, kstats_after;
read_kstats(&kstats_before);
xpthread_join(timer);
for(int i = 0; i < nthread; i++)
xpthread_join(tid[i]);
read_kstats(&kstats_after);
// Summarize
uint64_t start_avg = summarize_tsc("start", start_tscs, nthread);
uint64_t stop_avg = summarize_tsc("stop", stop_tscs, nthread);
printf("%lu cycles\n", stop_avg - start_avg);
printf("%lu iterations\n", iters.load());
#ifdef RECORD_PMC
printf("%lu total %s\n", pmcs.load(), STR(RECORD_PMC)+4);
#endif
printf("%lu cycles/iteration\n",
(sum(stop_tscs, nthread) - sum(start_tscs, nthread))/iters);
printf("\n");
sleep(5);
return 0;
}
| [
"jiungsen@gmail.com"
] | jiungsen@gmail.com |
4e1f0903e256b4cf2e49e83839f5b0da2279972a | f38ffaf7849095d8062917b991cd2d2cf1334a1a | /src/sdl/imgui_impl_sdl.cpp | afef287e2cdd4a0e2d3e58e1ce0f969b9a54d114 | [
"MIT"
] | permissive | UnsafePointer/imgui | ddb3742371ff4eca1bad342c8fb4fcf081d9dece | 37f99e5dc45ee2e956eaff52e6327ff48e4d390b | refs/heads/master | 2022-11-21T20:37:01.593189 | 2020-06-30T18:01:37 | 2020-06-30T18:01:37 | 272,255,918 | 0 | 0 | MIT | 2020-06-14T17:59:24 | 2020-06-14T17:59:23 | null | UTF-8 | C++ | false | false | 18,060 | cpp | // dear imgui: Platform Binding for SDL2
// This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..)
// (Info: SDL2 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.)
// (Requires: SDL 2.0. Prefer SDL 2.0.4+ for full feature support.)
// Implemented features:
// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
// [X] Platform: Clipboard support.
// [X] Platform: Keyboard arrays indexed using SDL_SCANCODE_* codes, e.g. ImGui::IsKeyPressed(SDL_SCANCODE_SPACE).
// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
// Missing features:
// [ ] Platform: SDL2 handling of IME under Windows appears to be broken and it explicitly disable the regular Windows IME. You can restore Windows IME by compiling SDL with SDL_DISABLE_WINDOWS_IME.
// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp.
// https://github.com/ocornut/imgui
// CHANGELOG
// (minor and older changes stripped away, please see git history for details)
// 2020-05-25: Misc: Report a zero display-size when window is minimized, to be consistent with other backends.
// 2020-02-20: Inputs: Fixed mapping for ImGuiKey_KeyPadEnter (using SDL_SCANCODE_KP_ENTER instead of SDL_SCANCODE_RETURN2).
// 2019-12-17: Inputs: On Wayland, use SDL_GetMouseState (because there is no global mouse state).
// 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor.
// 2019-07-21: Inputs: Added mapping for ImGuiKey_KeyPadEnter.
// 2019-04-23: Inputs: Added support for SDL_GameController (if ImGuiConfigFlags_NavEnableGamepad is set by user application).
// 2019-03-12: Misc: Preserve DisplayFramebufferScale when main window is minimized.
// 2018-12-21: Inputs: Workaround for Android/iOS which don't seem to handle focus related calls.
// 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window.
// 2018-11-14: Changed the signature of ImGui_ImplSDL2_ProcessEvent() to take a 'const SDL_Event*'.
// 2018-08-01: Inputs: Workaround for Emscripten which doesn't seem to handle focus related calls.
// 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor.
// 2018-06-08: Misc: Extracted imgui_impl_sdl.cpp/.h away from the old combined SDL2+OpenGL/Vulkan examples.
// 2018-06-08: Misc: ImGui_ImplSDL2_InitForOpenGL() now takes a SDL_GLContext parameter.
// 2018-05-09: Misc: Fixed clipboard paste memory leak (we didn't call SDL_FreeMemory on the data returned by SDL_GetClipboardText).
// 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag.
// 2018-02-16: Inputs: Added support for mouse cursors, honoring ImGui::GetMouseCursor() value.
// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
// 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
// 2018-02-05: Misc: Using SDL_GetPerformanceCounter() instead of SDL_GetTicks() to be able to handle very high framerate (1000+ FPS).
// 2018-02-05: Inputs: Keyboard mapping is using scancodes everywhere instead of a confusing mixture of keycodes and scancodes.
// 2018-01-20: Inputs: Added Horizontal Mouse Wheel support.
// 2018-01-19: Inputs: When available (SDL 2.0.4+) using SDL_CaptureMouse() to retrieve coordinates outside of client area when dragging. Otherwise (SDL 2.0.3 and before) testing for SDL_WINDOW_INPUT_FOCUS instead of SDL_WINDOW_MOUSE_FOCUS.
// 2018-01-18: Inputs: Added mapping for ImGuiKey_Insert.
// 2017-08-25: Inputs: MousePos set to -FLT_MAX,-FLT_MAX when mouse is unavailable/missing (instead of -1,-1).
// 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers.
#include <imgui/imgui.h>
#include <imgui/sdl/imgui_impl_sdl.h>
// SDL
#include <SDL2/SDL.h>
#include <SDL2/SDL_syswm.h>
#if defined(__APPLE__)
#include "TargetConditionals.h"
#endif
#define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE SDL_VERSION_ATLEAST(2,0,4)
#define SDL_HAS_VULKAN SDL_VERSION_ATLEAST(2,0,6)
// Data
static SDL_Window* g_Window = NULL;
static Uint64 g_Time = 0;
static bool g_MousePressed[3] = { false, false, false };
static SDL_Cursor* g_MouseCursors[ImGuiMouseCursor_COUNT] = {};
static char* g_ClipboardTextData = NULL;
static bool g_MouseCanUseGlobalState = true;
static const char* ImGui_ImplSDL2_GetClipboardText(void*)
{
if (g_ClipboardTextData)
SDL_free(g_ClipboardTextData);
g_ClipboardTextData = SDL_GetClipboardText();
return g_ClipboardTextData;
}
static void ImGui_ImplSDL2_SetClipboardText(void*, const char* text)
{
SDL_SetClipboardText(text);
}
// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
// If you have multiple SDL events and some of them are not meant to be used by dear imgui, you may need to filter events based on their windowID field.
bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)
{
ImGuiIO& io = ImGui::GetIO();
switch (event->type)
{
case SDL_MOUSEWHEEL:
{
if (event->wheel.x > 0) io.MouseWheelH += 1;
if (event->wheel.x < 0) io.MouseWheelH -= 1;
if (event->wheel.y > 0) io.MouseWheel += 1;
if (event->wheel.y < 0) io.MouseWheel -= 1;
return true;
}
case SDL_MOUSEBUTTONDOWN:
{
if (event->button.button == SDL_BUTTON_LEFT) g_MousePressed[0] = true;
if (event->button.button == SDL_BUTTON_RIGHT) g_MousePressed[1] = true;
if (event->button.button == SDL_BUTTON_MIDDLE) g_MousePressed[2] = true;
return true;
}
case SDL_TEXTINPUT:
{
io.AddInputCharactersUTF8(event->text.text);
return true;
}
case SDL_KEYDOWN:
case SDL_KEYUP:
{
int key = event->key.keysym.scancode;
IM_ASSERT(key >= 0 && key < IM_ARRAYSIZE(io.KeysDown));
io.KeysDown[key] = (event->type == SDL_KEYDOWN);
io.KeyShift = ((SDL_GetModState() & KMOD_SHIFT) != 0);
io.KeyCtrl = ((SDL_GetModState() & KMOD_CTRL) != 0);
io.KeyAlt = ((SDL_GetModState() & KMOD_ALT) != 0);
#ifdef _WIN32
io.KeySuper = false;
#else
io.KeySuper = ((SDL_GetModState() & KMOD_GUI) != 0);
#endif
return true;
}
}
return false;
}
static bool ImGui_ImplSDL2_Init(SDL_Window* window)
{
g_Window = window;
// Setup back-end capabilities flags
ImGuiIO& io = ImGui::GetIO();
io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
io.BackendPlatformName = "imgui_impl_sdl";
// Keyboard mapping. ImGui will use those indices to peek into the io.KeysDown[] array.
io.KeyMap[ImGuiKey_Tab] = SDL_SCANCODE_TAB;
io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = SDL_SCANCODE_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = SDL_SCANCODE_UP;
io.KeyMap[ImGuiKey_DownArrow] = SDL_SCANCODE_DOWN;
io.KeyMap[ImGuiKey_PageUp] = SDL_SCANCODE_PAGEUP;
io.KeyMap[ImGuiKey_PageDown] = SDL_SCANCODE_PAGEDOWN;
io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME;
io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END;
io.KeyMap[ImGuiKey_Insert] = SDL_SCANCODE_INSERT;
io.KeyMap[ImGuiKey_Delete] = SDL_SCANCODE_DELETE;
io.KeyMap[ImGuiKey_Backspace] = SDL_SCANCODE_BACKSPACE;
io.KeyMap[ImGuiKey_Space] = SDL_SCANCODE_SPACE;
io.KeyMap[ImGuiKey_Enter] = SDL_SCANCODE_RETURN;
io.KeyMap[ImGuiKey_Escape] = SDL_SCANCODE_ESCAPE;
io.KeyMap[ImGuiKey_KeyPadEnter] = SDL_SCANCODE_KP_ENTER;
io.KeyMap[ImGuiKey_A] = SDL_SCANCODE_A;
io.KeyMap[ImGuiKey_C] = SDL_SCANCODE_C;
io.KeyMap[ImGuiKey_V] = SDL_SCANCODE_V;
io.KeyMap[ImGuiKey_X] = SDL_SCANCODE_X;
io.KeyMap[ImGuiKey_Y] = SDL_SCANCODE_Y;
io.KeyMap[ImGuiKey_Z] = SDL_SCANCODE_Z;
io.SetClipboardTextFn = ImGui_ImplSDL2_SetClipboardText;
io.GetClipboardTextFn = ImGui_ImplSDL2_GetClipboardText;
io.ClipboardUserData = NULL;
// Load mouse cursors
g_MouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW);
g_MouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_IBEAM);
g_MouseCursors[ImGuiMouseCursor_ResizeAll] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEALL);
g_MouseCursors[ImGuiMouseCursor_ResizeNS] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENS);
g_MouseCursors[ImGuiMouseCursor_ResizeEW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEWE);
g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENESW);
g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENWSE);
g_MouseCursors[ImGuiMouseCursor_Hand] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_HAND);
g_MouseCursors[ImGuiMouseCursor_NotAllowed] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NO);
// Check and store if we are on Wayland
g_MouseCanUseGlobalState = strncmp(SDL_GetCurrentVideoDriver(), "wayland", 7) != 0;
#ifdef _WIN32
SDL_SysWMinfo wmInfo;
SDL_VERSION(&wmInfo.version);
SDL_GetWindowWMInfo(window, &wmInfo);
io.ImeWindowHandle = wmInfo.info.win.window;
#else
(void)window;
#endif
return true;
}
bool ImGui_ImplSDL2_InitForOpenGL(SDL_Window* window, void* sdl_gl_context)
{
(void)sdl_gl_context; // Viewport branch will need this.
return ImGui_ImplSDL2_Init(window);
}
bool ImGui_ImplSDL2_InitForVulkan(SDL_Window* window)
{
#if !SDL_HAS_VULKAN
IM_ASSERT(0 && "Unsupported");
#endif
return ImGui_ImplSDL2_Init(window);
}
bool ImGui_ImplSDL2_InitForD3D(SDL_Window* window)
{
#if !defined(_WIN32)
IM_ASSERT(0 && "Unsupported");
#endif
return ImGui_ImplSDL2_Init(window);
}
bool ImGui_ImplSDL2_InitForMetal(SDL_Window* window)
{
return ImGui_ImplSDL2_Init(window);
}
void ImGui_ImplSDL2_Shutdown()
{
g_Window = NULL;
// Destroy last known clipboard data
if (g_ClipboardTextData)
SDL_free(g_ClipboardTextData);
g_ClipboardTextData = NULL;
// Destroy SDL mouse cursors
for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++)
SDL_FreeCursor(g_MouseCursors[cursor_n]);
memset(g_MouseCursors, 0, sizeof(g_MouseCursors));
}
static void ImGui_ImplSDL2_UpdateMousePosAndButtons()
{
ImGuiIO& io = ImGui::GetIO();
// Set OS mouse position if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user)
if (io.WantSetMousePos)
SDL_WarpMouseInWindow(g_Window, (int)io.MousePos.x, (int)io.MousePos.y);
else
io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
int mx, my;
Uint32 mouse_buttons = SDL_GetMouseState(&mx, &my);
io.MouseDown[0] = g_MousePressed[0] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0; // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame.
io.MouseDown[1] = g_MousePressed[1] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0;
io.MouseDown[2] = g_MousePressed[2] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0;
g_MousePressed[0] = g_MousePressed[1] = g_MousePressed[2] = false;
#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE && !defined(__EMSCRIPTEN__) && !defined(__ANDROID__) && !(defined(__APPLE__) && TARGET_OS_IOS)
SDL_Window* focused_window = SDL_GetKeyboardFocus();
if (g_Window == focused_window)
{
if (g_MouseCanUseGlobalState)
{
// SDL_GetMouseState() gives mouse position seemingly based on the last window entered/focused(?)
// The creation of a new windows at runtime and SDL_CaptureMouse both seems to severely mess up with that, so we retrieve that position globally.
// Won't use this workaround when on Wayland, as there is no global mouse position.
int wx, wy;
SDL_GetWindowPosition(focused_window, &wx, &wy);
SDL_GetGlobalMouseState(&mx, &my);
mx -= wx;
my -= wy;
}
io.MousePos = ImVec2((float)mx, (float)my);
}
// SDL_CaptureMouse() let the OS know e.g. that our imgui drag outside the SDL window boundaries shouldn't e.g. trigger the OS window resize cursor.
// The function is only supported from SDL 2.0.4 (released Jan 2016)
bool any_mouse_button_down = ImGui::IsAnyMouseDown();
SDL_CaptureMouse(any_mouse_button_down ? SDL_TRUE : SDL_FALSE);
#else
if (SDL_GetWindowFlags(g_Window) & SDL_WINDOW_INPUT_FOCUS)
io.MousePos = ImVec2((float)mx, (float)my);
#endif
}
static void ImGui_ImplSDL2_UpdateMouseCursor()
{
ImGuiIO& io = ImGui::GetIO();
if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
return;
ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None)
{
// Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
SDL_ShowCursor(SDL_FALSE);
}
else
{
// Show OS mouse cursor
SDL_SetCursor(g_MouseCursors[imgui_cursor] ? g_MouseCursors[imgui_cursor] : g_MouseCursors[ImGuiMouseCursor_Arrow]);
SDL_ShowCursor(SDL_TRUE);
}
}
static void ImGui_ImplSDL2_UpdateGamepads()
{
ImGuiIO& io = ImGui::GetIO();
memset(io.NavInputs, 0, sizeof(io.NavInputs));
if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0)
return;
// Get gamepad
SDL_GameController* game_controller = SDL_GameControllerOpen(0);
if (!game_controller)
{
io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
return;
}
// Update gamepad inputs
#define MAP_BUTTON(NAV_NO, BUTTON_NO) { io.NavInputs[NAV_NO] = (SDL_GameControllerGetButton(game_controller, BUTTON_NO) != 0) ? 1.0f : 0.0f; }
#define MAP_ANALOG(NAV_NO, AXIS_NO, V0, V1) { float vn = (float)(SDL_GameControllerGetAxis(game_controller, AXIS_NO) - V0) / (float)(V1 - V0); if (vn > 1.0f) vn = 1.0f; if (vn > 0.0f && io.NavInputs[NAV_NO] < vn) io.NavInputs[NAV_NO] = vn; }
const int thumb_dead_zone = 8000; // SDL_gamecontroller.h suggests using this value.
MAP_BUTTON(ImGuiNavInput_Activate, SDL_CONTROLLER_BUTTON_A); // Cross / A
MAP_BUTTON(ImGuiNavInput_Cancel, SDL_CONTROLLER_BUTTON_B); // Circle / B
MAP_BUTTON(ImGuiNavInput_Menu, SDL_CONTROLLER_BUTTON_X); // Square / X
MAP_BUTTON(ImGuiNavInput_Input, SDL_CONTROLLER_BUTTON_Y); // Triangle / Y
MAP_BUTTON(ImGuiNavInput_DpadLeft, SDL_CONTROLLER_BUTTON_DPAD_LEFT); // D-Pad Left
MAP_BUTTON(ImGuiNavInput_DpadRight, SDL_CONTROLLER_BUTTON_DPAD_RIGHT); // D-Pad Right
MAP_BUTTON(ImGuiNavInput_DpadUp, SDL_CONTROLLER_BUTTON_DPAD_UP); // D-Pad Up
MAP_BUTTON(ImGuiNavInput_DpadDown, SDL_CONTROLLER_BUTTON_DPAD_DOWN); // D-Pad Down
MAP_BUTTON(ImGuiNavInput_FocusPrev, SDL_CONTROLLER_BUTTON_LEFTSHOULDER); // L1 / LB
MAP_BUTTON(ImGuiNavInput_FocusNext, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER); // R1 / RB
MAP_BUTTON(ImGuiNavInput_TweakSlow, SDL_CONTROLLER_BUTTON_LEFTSHOULDER); // L1 / LB
MAP_BUTTON(ImGuiNavInput_TweakFast, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER); // R1 / RB
MAP_ANALOG(ImGuiNavInput_LStickLeft, SDL_CONTROLLER_AXIS_LEFTX, -thumb_dead_zone, -32768);
MAP_ANALOG(ImGuiNavInput_LStickRight, SDL_CONTROLLER_AXIS_LEFTX, +thumb_dead_zone, +32767);
MAP_ANALOG(ImGuiNavInput_LStickUp, SDL_CONTROLLER_AXIS_LEFTY, -thumb_dead_zone, -32767);
MAP_ANALOG(ImGuiNavInput_LStickDown, SDL_CONTROLLER_AXIS_LEFTY, +thumb_dead_zone, +32767);
io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
#undef MAP_BUTTON
#undef MAP_ANALOG
}
void ImGui_ImplSDL2_NewFrame(SDL_Window* window)
{
ImGuiIO& io = ImGui::GetIO();
IM_ASSERT(io.Fonts->IsBuilt() && "Font atlas not built! It is generally built by the renderer back-end. Missing call to renderer _NewFrame() function? e.g. ImGui_ImplOpenGL3_NewFrame().");
// Setup display size (every frame to accommodate for window resizing)
int w, h;
int display_w, display_h;
SDL_GetWindowSize(window, &w, &h);
if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED)
w = h = 0;
SDL_GL_GetDrawableSize(window, &display_w, &display_h);
io.DisplaySize = ImVec2((float)w, (float)h);
if (w > 0 && h > 0)
io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h);
// Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution)
static Uint64 frequency = SDL_GetPerformanceFrequency();
Uint64 current_time = SDL_GetPerformanceCounter();
io.DeltaTime = g_Time > 0 ? (float)((double)(current_time - g_Time) / frequency) : (float)(1.0f / 60.0f);
g_Time = current_time;
ImGui_ImplSDL2_UpdateMousePosAndButtons();
ImGui_ImplSDL2_UpdateMouseCursor();
// Update game controllers (if enabled and available)
ImGui_ImplSDL2_UpdateGamepads();
}
| [
"renzo@crisostomo.me"
] | renzo@crisostomo.me |
fd709ae747bd243713222a513fa28d8997364d7d | 3a7c1ef392ea8654033886ea4f608c46de16c9a2 | /Source/Views/PolytempoNetwork/Polytempo_AnnotationView.cpp | 2ff5cf0212d4d2811b79338e8e2143ea7fc32a67 | [] | no_license | michaseidenberg/polytempo | ad585a692827cbbb65e94ef03c7b65f65783a084 | cea853d6f47c678228e418b9126baa9ac5b8d3e9 | refs/heads/master | 2023-04-01T23:18:06.066886 | 2021-04-07T15:46:27 | 2021-04-07T15:46:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,985 | cpp | #include "Polytempo_AnnotationView.h"
#include "Polytempo_GraphicsAnnotationManager.h"
#include "Polytempo_GraphicsPalette.h"
Polytempo_AnnotationView::Polytempo_AnnotationView()
{
Image imageSettings = ImageCache::getFromMemory(BinaryData::settings_png, BinaryData::settings_pngSize);
addAndMakeVisible(annotationModeComboBox = new ComboBox());
annotationModeComboBox->addItem("Read only", Polytempo_GraphicsAnnotationManager::ReadOnly);
annotationModeComboBox->addItem("Standard", Polytempo_GraphicsAnnotationManager::Standard);
annotationModeComboBox->addItem("Edit mode", Polytempo_GraphicsAnnotationManager::Edit);
annotationModeComboBox->addListener(this);
annotationModeComboBox->setWantsKeyboardFocus(false);
addAndMakeVisible(annotationMasterToggle = new ToggleButton("Annotations"));
annotationMasterToggle->addListener(this);
annotationMasterToggle->setWantsKeyboardFocus(false);
addAndMakeVisible(buttonSettings = new ImageButton("Settings"));
buttonSettings->setImages(false, false, false, imageSettings, 1.0f, Colours::transparentWhite, Image(), 1.0, Colour(Colours::purple.getRed(), Colours::purple.getGreen(), Colours::purple.getBlue(), uint8(80)), Image(), 1.0, Colours::green);
buttonSettings->setBounds(0, 0, BUTTON_SIZE, BUTTON_SIZE);
buttonSettings->addListener(this);
displayMode();
addMouseListener(this, true);
Polytempo_GraphicsAnnotationManager::getInstance()->addChangeListener(this);
Polytempo_GraphicsPalette::getInstance()->initialize(this);
}
Polytempo_AnnotationView::~Polytempo_AnnotationView()
{
deleteAllChildren();
}
void Polytempo_AnnotationView::paint(Graphics&)
{
}
void Polytempo_AnnotationView::resized()
{
annotationMasterToggle->setBounds(0, 5, getWidth(), 18);
annotationModeComboBox->setBounds(0, 24, getWidth() - 30, 22);
buttonSettings->setBounds(getWidth() - 22, 24, 22, 22);
int paletteHeight = Polytempo_GraphicsPalette::getInstance()->resize(Point<int>(0, 60));
setSize(getWidth(), 60 + paletteHeight);
getParentComponent()->resized();
}
void Polytempo_AnnotationView::updateState() const
{
annotationModeComboBox->setEnabled(annotationMasterToggle->getToggleState());
buttonSettings->setEnabled(annotationMasterToggle->getToggleState());
if (annotationMasterToggle->getToggleState())
{
Polytempo_GraphicsAnnotationManager::getInstance()->setAnnotationMode(Polytempo_GraphicsAnnotationManager::eAnnotationMode(annotationModeComboBox->getSelectedId()));
}
else
{
Polytempo_GraphicsAnnotationManager::getInstance()->setAnnotationMode(Polytempo_GraphicsAnnotationManager::Off);
}
}
void Polytempo_AnnotationView::buttonClicked(Button* btn)
{
if (btn == annotationMasterToggle)
{
updateState();
}
else if (btn == buttonSettings)
{
Polytempo_GraphicsAnnotationManager::getInstance()->showSettingsDialog();
}
}
void Polytempo_AnnotationView::comboBoxChanged(ComboBox* comboBoxThatHasChanged)
{
if (comboBoxThatHasChanged == annotationModeComboBox)
{
updateState();
}
}
void Polytempo_AnnotationView::changeListenerCallback(ChangeBroadcaster* /*source*/)
{
displayMode();
}
void Polytempo_AnnotationView::mouseEnter(const MouseEvent&)
{
Polytempo_GraphicsPalette::getInstance()->mouseEntered();
}
void Polytempo_AnnotationView::mouseExit(const MouseEvent&)
{
Polytempo_GraphicsPalette::getInstance()->mouseLeft();
}
void Polytempo_AnnotationView::displayMode() const
{
Polytempo_GraphicsAnnotationManager::eAnnotationMode mode = Polytempo_GraphicsAnnotationManager::getInstance()->getAnnotationMode();
annotationModeComboBox->setSelectedId(mode == Polytempo_GraphicsAnnotationManager::Off ? Polytempo_GraphicsAnnotationManager::eAnnotationMode::ReadOnly : mode, sendNotification);
annotationMasterToggle->setToggleState(mode != Polytempo_GraphicsAnnotationManager::Off, sendNotification);
}
| [
"christian@schweizerweb.ch"
] | christian@schweizerweb.ch |
0bb315b29224a305f8c7cb6217ba7181f609c8a5 | 55b57e8c1bc1c4362a52705a31b0ee92da1624a2 | /Table.h | fa76cb9e2a09a53af18a6d34bd8b2778e8f1796e | [] | no_license | Jiang5/highcard-game | fc94f15a7f9504827f517c3758b54dfc7f9c1fa6 | 079cfee9604d796e2ada51447c98d4c3b89c54b8 | refs/heads/master | 2021-01-21T06:42:27.934791 | 2017-02-27T05:29:24 | 2017-02-27T05:29:24 | 83,271,613 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,928 | h | #include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cassert>
#include <ctime>
#include <cstdlib>
#include <climits>
#ifndef TABLE_H
#define TABLE_H
class Table{
private:
std::vector<Player> table,losers;
int numSeats = 0, ante = 0,seat = 0;
Player temp;
void evaluate(){
seat = 0;
for(int i = 0; i < numSeats; i++){
if(table.size() > 1){
if(table[seat].hand.getValue() < table[i].hand.getValue()) seat = i;
else if(table[seat].hand.getValue() == table[i].hand.getValue()){
if(table[seat].hand.getSuitNum() < table[i].hand.getSuitNum()) seat = i;
}
}
}
}
public:
Table(int numSeats, int ante){
this->numSeats = numSeats;
this->ante = ante;
}
bool emptySeat(){
return (table.size() < numSeats);
}
void addPlayer(Player p){
table.push_back(p);
}
std::vector<Player> playRound(){
Deck deck;
deck.shuffle();
for(unsigned int i = 0; i < numSeats; i++){
// std::cout<<"loop i "<<i<<std::endl;
table[i].bet(ante);
table[i].hand = deck.draw();
deck.discard();
//std::cout<<"card value "<<table[i].hand.getValue()<<std::endl;
}
evaluate();
table[seat].collectWinnings(numSeats * ante);
for(int i = numSeats - 1; i = 0; i--){
if(i != seat){
losers.push_back(table.back());
table.pop_back();
}
else{
temp.copy(table.back());
table.pop_back();
}
}
table.push_back(temp);
return losers;
}
void printWinner(){
std::cout<<"The winner is"<<table[seat].getName()<<std::endl;
}
};
#endif | [
"noreply@github.com"
] | Jiang5.noreply@github.com |
20972e3802000e44affb110488590b04a444927f | 72af5cc9c361bc86c68c9ef158a6b7c52b968fec | /Solutions/URI Online Judge/Iniciante/2763.cpp | 405cff4c8a78996e4eb64fe5f8bf0621b8d18696 | [] | no_license | jaimelay/competitive-programming | 40f4d747d4c63a8e58f3a47fa2ff90c3de4ea229 | 16c061800f840f24ffabf4b47b0b22696c622031 | refs/heads/master | 2022-05-05T03:28:03.646782 | 2022-03-30T12:28:12 | 2022-03-30T12:28:12 | 172,822,185 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 236 | cpp | #include <bits/stdc++.h>
using namespace std;
int main(void){
string cpf;
getline(cin, cpf);
for(auto i : cpf){
if(i >= '0' && i <= '9') cout << i;
else cout << endl;
}
cout << endl;
return 0;
} | [
"jaimelay1997@gmail.com"
] | jaimelay1997@gmail.com |
58a59858d603abef19b331b9cde113f7aabfd757 | be47ada85aecc8cdf2d4e8857f8e160e1daa396c | /4th Year/2nd Semester/DC Project/codegen/lib/PSO_Library/abs.cpp | 13e5531c050c9519e7d988f7b3eb787d3c4a9137 | [] | no_license | ljw3351639/college-work | 0ea99af3f4889ecb3d21df948b4cab246c847b5d | ca3f7d4167671d227f10760a9c2002362e6dfa08 | refs/heads/master | 2020-05-18T00:17:43.886306 | 2013-10-17T18:43:46 | 2013-10-17T18:43:46 | 35,103,851 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 703 | cpp | /*
* abs.cpp
*
* Code generation for function 'abs'
*
* C source code generated on: Tue May 22 03:41:52 2012
*
*/
/* Include files */
#include "Calculate_Fitness_AF_fay.h"
#include "Calculate_Fitness_AFmin.h"
#include "calculate_pbest_obj_AF.h"
#include "abs.h"
#include "PSO_Library_rtwutil.h"
/* Type Definitions */
/* Named Constants */
/* Variable Declarations */
/* Variable Definitions */
/* Function Declarations */
/* Function Definitions */
/*
*
*/
void b_abs(const creal_T x[90], real_T y[90])
{
int32_T k;
for (k = 0; k < 90; k++) {
y[k] = rt_hypotd(fabs(x[k].re), fabs(x[k].im));
}
}
/* End of code generation (abs.cpp) */
| [
"hmdmgd3@gmail.com@582ae471-1916-86ea-2319-aa95173a7865"
] | hmdmgd3@gmail.com@582ae471-1916-86ea-2319-aa95173a7865 |
154784f947f09dd4d83ee1d46506addf00abd0e7 | 10e990bbbae2aea1ecde10eb36a2988cb0ebe5d8 | /build-raytrace-Desktop_Qt_5_7_0_MinGW_32bit-Debug/tmp/moc_RenderPanel.cpp | 2d634a074dc102eb8cd3fa10f6cb3a779bb75cbd | [] | no_license | tchonny/trabalho2cgversao2 | 6a9d3ae4baa25ffcc78fe995237895293f01c34b | 8824652d5870c227f188246fa307bbfeb32e0aad | refs/heads/master | 2020-04-06T03:37:45.950391 | 2016-06-20T04:52:30 | 2016-06-20T04:52:30 | 61,517,659 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,147 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'RenderPanel.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.7.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../projeto/src/RenderPanel.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'RenderPanel.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.7.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_RenderPanel_t {
QByteArrayData data[8];
char stringdata0[89];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_RenderPanel_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_RenderPanel_t qt_meta_stringdata_RenderPanel = {
{
QT_MOC_LITERAL(0, 0, 11), // "RenderPanel"
QT_MOC_LITERAL(1, 12, 12), // "atualizaMain"
QT_MOC_LITERAL(2, 25, 0), // ""
QT_MOC_LITERAL(3, 26, 15), // "atualizaTamanho"
QT_MOC_LITERAL(4, 42, 12), // "enviaArquivo"
QT_MOC_LITERAL(5, 55, 6), // "update"
QT_MOC_LITERAL(6, 62, 13), // "recebeArquivo"
QT_MOC_LITERAL(7, 76, 12) // "salvaArquivo"
},
"RenderPanel\0atualizaMain\0\0atualizaTamanho\0"
"enviaArquivo\0update\0recebeArquivo\0"
"salvaArquivo"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_RenderPanel[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
6, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
3, // signalCount
// signals: name, argc, parameters, tag, flags
1, 0, 44, 2, 0x06 /* Public */,
3, 2, 45, 2, 0x06 /* Public */,
4, 1, 50, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
5, 1, 53, 2, 0x08 /* Private */,
6, 1, 56, 2, 0x08 /* Private */,
7, 1, 59, 2, 0x08 /* Private */,
// signals: parameters
QMetaType::Void,
QMetaType::Void, QMetaType::Int, QMetaType::Int, 2, 2,
QMetaType::Void, QMetaType::QString, 2,
// slots: parameters
QMetaType::Void, QMetaType::QImage, 2,
QMetaType::Void, QMetaType::QString, 2,
QMetaType::Void, QMetaType::QString, 2,
0 // eod
};
void RenderPanel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
RenderPanel *_t = static_cast<RenderPanel *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->atualizaMain(); break;
case 1: _t->atualizaTamanho((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
case 2: _t->enviaArquivo((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 3: _t->update((*reinterpret_cast< const QImage(*)>(_a[1]))); break;
case 4: _t->recebeArquivo((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 5: _t->salvaArquivo((*reinterpret_cast< const QString(*)>(_a[1]))); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
void **func = reinterpret_cast<void **>(_a[1]);
{
typedef void (RenderPanel::*_t)();
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&RenderPanel::atualizaMain)) {
*result = 0;
return;
}
}
{
typedef void (RenderPanel::*_t)(int , int );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&RenderPanel::atualizaTamanho)) {
*result = 1;
return;
}
}
{
typedef void (RenderPanel::*_t)(const QString & );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&RenderPanel::enviaArquivo)) {
*result = 2;
return;
}
}
}
}
const QMetaObject RenderPanel::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_RenderPanel.data,
qt_meta_data_RenderPanel, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *RenderPanel::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *RenderPanel::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_RenderPanel.stringdata0))
return static_cast<void*>(const_cast< RenderPanel*>(this));
return QWidget::qt_metacast(_clname);
}
int RenderPanel::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 6)
qt_static_metacall(this, _c, _id, _a);
_id -= 6;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 6)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 6;
}
return _id;
}
// SIGNAL 0
void RenderPanel::atualizaMain()
{
QMetaObject::activate(this, &staticMetaObject, 0, Q_NULLPTR);
}
// SIGNAL 1
void RenderPanel::atualizaTamanho(int _t1, int _t2)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 1, _a);
}
// SIGNAL 2
void RenderPanel::enviaArquivo(const QString & _t1)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 2, _a);
}
QT_END_MOC_NAMESPACE
| [
"jon.handam@gmail.com"
] | jon.handam@gmail.com |
da26fed07280f473eceeafa7ded64a8dd2ebe1b8 | 13740c1f486a513b1a45ca060add0455737a03f9 | /cpp/sourcep10/wx1_lru.cpp | 836d3bc78457ccd6998b368a4530c3a8894681f5 | [] | no_license | zxwtry/OJ | 66b2bfd465f7875bc391ef6cd13fb615509d16ce | b6028e1afcce89e2214242033707d10dc814d14d | refs/heads/master | 2021-04-22T11:54:36.455136 | 2020-09-30T15:02:24 | 2020-09-30T15:02:24 | 57,225,986 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,246 | cpp | #include <algorithm>
using namespace std;
const int MOD = 10000000;
const int LIMIT = 100000000;
struct Node
{
uint32_t iKey;
uint32_t iElem;
};
const int MOD = 10000000; // 桶取模
const int LIMIT = 100000000; // 限制
// 存储hash冲突
struct HashLinkedList
{
Node *val;
HashLinkedList *next;
HashLinkedList *prev;
};
// 每个hash下面的桶
struct HashBucket
{
HashLinkedList *head;
HashLinkedList *tail;
};
// 存储lru的链表
struct LRULinkedList
{
HashLinkedList *val;
LRULinkedList *next;
LRULinkedList *prev;
};
// LRU 结构
HashBucket *hashBkts[MOD] = {NULL};
LRULinkedList *lruhead = NULL;
LRULinkedList *lrutail = NULL;
int lrusize = 0;
Node *Get(uint32_t key)
{
int m = key % MOD;
if (hashBkts[m] == NULL)
{
return NULL;
}
HashLinkedList *h = hashBkts[m]->head;
while (h != NULL)
{
if (h->val->iKey == key)
{
return h->val;
}
h = h->next;
}
// 新用节点,放置到头
if (hashBkts[m]->prev != NULL)
{
hashBkts[m]->val->next = hashBkts[m]->val->next;
}
else
{
lruhead = hashBkts[m]->val;
hashBkts[m]->val->prev = NULL;
}
return NULL;
}
void Insert(uint32_t key, uint32_t val)
{
// 写入hash
int m = key % MOD;
if (hashBkts[m] == NULL)
{
hashBkts[m] = new (HashBucket);
hashBkts[m]->head = NULL;
hashBkts[m]->tail = NULL;
}
Node *node = new (Node);
node->iKey = key;
node->iElem = val;
HashLinkedList *l = new (HashLinkedList);
l->val = node;
l->next = NULL;
if (hashBkts[m]->tail == NULL)
{
hashBkts[m]->head = hashBkts[m]->tail = l;
}
else
{
hashBkts[m]->tail->next = l;
hashBkts[m]->tail = l;
}
// 写入lru
LRULinkedList *lruNode = new (LRULinkedList);
lruNode->next = lruhead; // 新使用节点,放在头
lruNode->val = node; // 复用
if (lruhead != NULL)
{
lruhead->prev = lruNode;
}
lruhead = lruNode;
if (lrusize > LIMIT)
{
if (lrutail != NULL)
{
// 删除hash
int tailm = lrutail->val->iKey % MOD;
HashLinkedList *tailN = hashBkts[tailm]->head;
HashLinkedList *tailPre = hashBkts[tailm]->head;
while (tailN != NULL)
{
// 删除当前节点
if (tailN->val->iKey == lrutail->val->iKey)
{
if (tailN == hashBkts[tailm]->head)
{
hashBkts[tailm]->head = tailN->next;
}
else
{
tailPre->next = tailN->next;
}
}
tailPre = tailN;
tailN = tailN->next;
}
// 删除lru
LRULinkedList *prev = lrutail->prev;
if (prev != NULL)
{
prev->next = NULL;
lrutail = prev;
}
else
{
lruhead = lrutail = NULL;
}
delete (lrutail);
}
}
}
| [
"xinweizhu@tencent.com"
] | xinweizhu@tencent.com |
e9ca469ee51f39dbc096e0d4c3ee3bc62b15b3d8 | 46aebbcb1a7bcfe584506244602e8ba1f33f8634 | /src/ign-rendering/include/ignition/rendering/Visual.hh | 9c18af664e4bf820b4ad0676f52c3bd36c0e2a7a | [
"Apache-2.0"
] | permissive | mingfeisun/gsoc-mingfei | eecc4f784241a938d5675978fc8e4083b4f3cb39 | 265073fc643a54042f69afbad536aa38f49de801 | refs/heads/master | 2020-07-10T05:03:58.365892 | 2019-08-27T02:26:47 | 2019-08-27T02:26:47 | 204,171,268 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,089 | hh | /*
* Copyright (C) 2015 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef IGNITION_RENDERING_VISUAL_HH_
#define IGNITION_RENDERING_VISUAL_HH_
#include <string>
#include "ignition/rendering/config.hh"
#include "ignition/rendering/Node.hh"
namespace ignition
{
namespace rendering
{
inline namespace IGNITION_RENDERING_VERSION_NAMESPACE {
//
/// \class Visual Visual.hh ignition/rendering/Visual.hh
/// \brief Represents a visual node in a scene graph. A Visual is the only
/// node that can have Geometry and other Visual children.
class IGNITION_RENDERING_VISIBLE Visual :
public virtual Node
{
/// \brief Deconstructor
public: virtual ~Visual() { }
/// \brief Get the number of geometries attached to this visual
/// \return The number of geometries attached to this visual
public: virtual unsigned int GeometryCount() const = 0;
/// \brief Determine if given geometry is attached to this visual
/// \param[in] _geometry Geometry in question
/// \return True if given node is attached to this visual
public: virtual bool HasGeometry(ConstGeometryPtr _geometry) const = 0;
/// \brief Get geometry at given index. If no geometry exists at given
/// index, NULL will be returned.
/// \param[in] _index Index of the desired geometry
/// \return The specified geometry
public: virtual GeometryPtr GeometryByIndex(
unsigned int _index) const = 0;
/// \brief Add the given geometry to this visual. If the given node is
/// already attached, no work will be done.
/// \param[in] _geometry Geometry to be added
public: virtual void AddGeometry(GeometryPtr _geometry) = 0;
/// \brief Remove the given geometry from this visual. If the given node
/// is not a child of this visual, no work will be done.
/// \param[in] _geometry Geometry to be removed
/// \return The removed geometry
public: virtual GeometryPtr RemoveGeometry(GeometryPtr _geometry) = 0;
/// \brief Remove the geometry at the given index from this visual. If the
/// specified node is not attached this visual, no work will be done.
/// \param[in] _index Index of the geometry to be removed
/// \return The removed geometry
public: virtual GeometryPtr RemoveGeometryByIndex(
unsigned int _index) = 0;
/// \brief Remove all attached geometries from this visual
public: virtual void RemoveGeometries() = 0;
/// \brief Set the material for all attached visuals and geometries. The
/// specified material will be retrieved from Scene::Material using
/// the given material name. If no material is registered with the given
/// name, no work will be done.
/// \param[in] _name Name of the material to be assigned
/// \param[in] _unique True if the specified material should be cloned
public: virtual void SetMaterial(const std::string &_name,
bool unique = true) = 0;
/// \brief Set the material for all attached visuals and geometries
/// \param[in] _name Name of the material to be assigned
/// \param[in] _unique True if the specified material should be cloned
public: virtual void SetMaterial(MaterialPtr _material,
bool unique = true) = 0;
/// \brief Set the material for all attached visuals only
/// \param[in] _name Name of the material to be assigned
/// \param[in] _unique True if the specified material should be cloned
public: virtual void SetChildMaterial(MaterialPtr _material,
bool unique = true) = 0;
/// \brief Set the material for all attached geometries only
/// \param[in] _name Name of the material to be assigned
/// \param[in] _unique True if the specified material should be cloned
public: virtual void SetGeometryMaterial(MaterialPtr _material,
bool unique = true) = 0;
/// \brief Get the material assigned to attached visuals and geometries.
/// \return the Pointer to the material assigned to this visual. If the
/// material is cloned at the time it is set to this visual, the cloned
/// material will be returned.
public: virtual MaterialPtr Material() = 0;
/// \brief Specify if this visual is visible
/// \param[in] _visible True if this visual should be made visible
public: virtual void SetVisible(bool _visible) = 0;
};
}
}
}
#endif
| [
"mingfei.sun@ust.hk"
] | mingfei.sun@ust.hk |
42462734f4aed59977d9829e0eb14c99cdb0d460 | 1dbed0f84a670c787d2217d97ae3984401c7edb3 | /cf/894v/D.cpp | 3deabf19631c6ef65491e1eee9aab857b9b33d46 | [] | no_license | prprprpony/oj | 311d12a25f06e6c54b88bc2bcd38003f7b6696a9 | 84988be500c06cb62130585333fddd1a278f0aaa | refs/heads/master | 2021-07-13T16:03:54.398841 | 2021-03-27T14:19:52 | 2021-03-27T14:19:52 | 46,796,050 | 9 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,291 | cpp | #include <bits/stdc++.h>
using namespace std;
// nichijou
#define REP(i,a,b) for (int i(a); i < (b); ++i)
#define RP(i,n) REP(i,0,n)
#define PER(i,a,b) for(int i((a)-1); i >= (b); --i)
#define PR(i,n) PER(i,n,0)
#define REP1(i,a,b) REP(i,a,(b)+1)
#define RP1(i,n) REP1(i,1,n)
#define PER1(i,a,b) PER(i,(a)+1,b)
#define PR1(i,n) PER1(i,n,1)
#define DO(n) RP(__i,n)
template<class T,class U>
bool cmax(T & a, const U & b) {return a < b ? a = b, 1 : 0;}
template<class T,class U>
bool cmin(T & a, const U & b) {return b < a ? a = b, 1 : 0;}
// data type
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
#define F first
#define S second
// STL container
typedef vector<int> vi;
typedef vector<ll> vll;
#define SZ(a) ((int)(a).size())
#define ALL(a) begin(a), end(a)
#define CLR(a) (a).clear()
#define BK(a) ((a).back())
#define FT(a) ((a).front())
#define DB(a) (a).pop_back()
#define DF(a) (a).pop_front()
#define PB push_back
#define EB emplace_back
/* I gave you my heart and then you turned around. */
void _BG(const char * s) {cerr<<s<<endl;};
template<class T, class ... TT>
void _BG(const char * s,T a, TT...b)
{
for (int c = 0; *s && (c || *s != ','); ++s) {
cerr<<*s;
for (char x : "([{") c += *s == x;
for (char x : ")]}") c -= *s == x;
}
cerr<<" = "<<a;
if (sizeof...(b)) {
cerr<<", ";
++s;
}
_BG(s,b...);
}
#define BG(...) do { \
cerr << __PRETTY_FUNCTION__ << ':' << __LINE__ << ": "; \
_BG(#__VA_ARGS__,__VA_ARGS__); \
} while(0)
/* Reading input is now 20% cooler! */
bool RD() {return 1;}
bool RD(char & a) {return scanf(" %c", &a) == 1;}
bool RD(char * a) {return scanf("%s", a) == 1;}
bool RD(double & a) {return scanf("%lf", &a) == 1;}
bool RD(int & a) {return scanf("%d", &a) == 1;}
bool RD(ll & a) {return scanf("%lld", &a) == 1;}
template<class T, class ... TT>
bool RD(T & a, TT & ... b) {return RD(a) && RD(b...);}
/* Do princesses dream of magic sheep? */
#define DR(T,...) T __VA_ARGS__; RD(__VA_ARGS__)
#define RI(...) DR(int,__VA_ARGS__)
/* For it's time for you to fulfill your output. */
void PT(const char & a) {putchar(a);}
void PT(char const * const & a) {fputs(a, stdout);}
void PT(const double & a) {printf("%.16f", a);}
void PT(const int & a) {printf("%d", a);}
void PT(const ll & a) {printf("%lld", a);}
/* The line will last forever! */
template<char s = ' ', char e = '\n'>
void PL() {if (e) PT(e);}
template<char s = ' ', char e = '\n', class T, class ... TT>
void PL(const T & a, const TT & ... b)
{PT(a); if (sizeof...(b) && s) PT(s); PL<s,e>(b...);}
/* Good Luck && Have Fun ! */
const int N = 1e6 + 87;
int w[N];
vector<ll> d[N], s[N];
ll qs(int u,ll v)
{
int k = lower_bound(ALL(d[u]), v) - begin(d[u]);
if (k == 0)
return 0;
return k * v - s[u][k-1];
}
ll qry(int u,ll h)
{
ll ans = qs(u,h);
for (int v = u/2; v; u = v, v /= 2) {
ans += qs(v,h-w[u]) - qs(u,h-w[u]*2);
h -= w[u];
}
return ans;
}
int main()
{
RI(n,m);
REP1(i,2,n)
RD(w[i]);
PER1(i,n,1) {
d[i].PB(0);
sort(ALL(d[i]));
s[i].resize(SZ(d[i]));
partial_sum(ALL(d[i]),begin(s[i]));
for (const auto & x : d[i])
d[i/2].PB(x + w[i]);
}
while (m--) {
RI(a,h);
PL(qry(a,h));
}
}
| [
"3254tg89@gmail.com"
] | 3254tg89@gmail.com |
a2a16816f788486591328ff82a20854d7a4cbee0 | 5a49b5da44fa9c3a585febcf3d975197d872efc9 | /Tools/SGP_WorldEditor/TerrainEditorDlg.cpp | a4ac07d9e6c9ec25b7c71a8c8e4dd8db0b717706 | [
"MIT"
] | permissive | phoenixzz/SGPEngine | 1ab3de99fdf6dd791baaf57e029a09e8db3580f7 | 593b4313abdb881d60e82750b36ddda2d7c73c49 | refs/heads/master | 2021-01-24T03:42:44.683083 | 2017-01-24T04:39:43 | 2017-01-24T04:39:43 | 53,315,434 | 4 | 2 | null | null | null | null | GB18030 | C++ | false | false | 7,801 | cpp | // TerrainEditorDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "WorldEditor.h"
#include "TerrainEditorDlg.h"
#include "afxdialogex.h"
#define DLG_MINWIDTH 260
// CTerrainEditorDlg 对话框
IMPLEMENT_DYNAMIC(CTerrainEditorDlg, CDialogEx)
CTerrainEditorDlg::CTerrainEditorDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(CTerrainEditorDlg::IDD, pParent)
{
m_nButtonState=-1;
}
CTerrainEditorDlg::~CTerrainEditorDlg()
{
}
void CTerrainEditorDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CTerrainEditorDlg, CDialogEx)
ON_WM_SIZE()
ON_WM_HSCROLL()
ON_WM_VSCROLL()
ON_WM_NCHITTEST()
END_MESSAGE_MAP()
// CTerrainEditorDlg 消息处理程序
BOOL CTerrainEditorDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
m_HeightDlg.Create(IDD_TERRAIN_HEIGHT,this);
m_HeightDlg.ShowWindow(SW_SHOW);
m_TerrainTexDlg.Create(IDD_TERRAIN_TEXTURE,this);
m_TerrainTexDlg.ShowWindow(SW_SHOW);
m_TerrainGrassDlg.Create(IDD_TERRAIN_GRASS,this);
m_TerrainGrassDlg.ShowWindow(SW_SHOW);
m_TerrainWaterDlg.Create(IDD_TERRAIN_WATER,this);
m_TerrainWaterDlg.ShowWindow(SW_SHOW);
// Init Scroll Info
ModifyStyle(0,WS_VSCROLL|WS_HSCROLL);
SCROLLINFO si;
si.cbSize=sizeof(SCROLLINFO);
si.fMask=SIF_POS;
si.nPos=0;
SetScrollInfo(SB_VERT,&si);
SetScrollInfo(SB_HORZ,&si);
EnableAllCtrls(FALSE);
return TRUE;
}
BOOL CTerrainEditorDlg::PreTranslateMessage(MSG* pMsg)
{
//avoid ESC/OK to exit dialog
if(pMsg->message==WM_KEYDOWN)
{
if(pMsg->wParam==VK_ESCAPE||pMsg->wParam==VK_RETURN) return TRUE;
}
if(pMsg->message == WM_MOUSEWHEEL&&pMsg->hwnd!=m_TerrainTexDlg.m_TextureList.m_hWnd)
{
short zDelta = GET_WHEEL_DELTA_WPARAM(pMsg->wParam);
if(zDelta > 0)
{
SendMessage(WM_VSCROLL,MAKEWPARAM(SB_LINEUP,0));
SendMessage(WM_VSCROLL,MAKEWPARAM(SB_LINEUP,0));
}
else
{
SendMessage(WM_VSCROLL,MAKEWPARAM(SB_LINEDOWN,0));
SendMessage(WM_VSCROLL,MAKEWPARAM(SB_LINEDOWN,0));
}
return TRUE;
}
return CDialogEx::PreTranslateMessage(pMsg);
}
void CTerrainEditorDlg::OnSize(UINT nType, int cx, int cy)
{
CDialogEx::OnSize(nType, cx, cy);
if(m_HeightDlg.m_hWnd!=NULL&&m_TerrainTexDlg.m_hWnd!=NULL&&m_TerrainGrassDlg.m_hWnd!=NULL)
SetCtrlPos();
}
void CTerrainEditorDlg::SetCtrlPos()
{
CRect rcClient;
GetClientRect(rcClient);
int cx=rcClient.Width(),cy=rcClient.Height();
SCROLLINFO si;
si.cbSize=sizeof(si);
// Set Horizontal Scrollbar Info
GetScrollInfo(SB_HORZ,&si);
si.nMin=0;
if(cx<=DLG_MINWIDTH)
{
si.nPage=cx;
si.nMax=DLG_MINWIDTH;
}
else
{
si.nPage=cx+1;
si.nMax=cx;
}
if(si.nMax<=(int)si.nPage) si.nPos=0;
else if(si.nPos>si.nMax-(int)si.nPage) si.nPos=si.nMax-si.nPage;
int xPos=si.nPos;
si.fMask=SIF_PAGE|SIF_RANGE|SIF_POS;
SetScrollInfo(SB_HORZ,&si);
// Get Sub Dialog Info
int height=0;
CRect rc;
m_HeightDlg.GetClientRect(rc);
height+=rc.Height()+1;
m_TerrainTexDlg.GetClientRect(rc);
height+=rc.Height()+1;
m_TerrainGrassDlg.GetClientRect(rc);
height+=rc.Height()+1;
m_TerrainWaterDlg.GetClientRect(rc);
height+=rc.Height()+1;
// Set Vertical Scrollbar Info
GetScrollInfo(SB_VERT,&si);
si.nPage=cy;
si.nMax=height;
if((int)si.nPage>=si.nMax) si.nPos=0;
else if(si.nPos>si.nMax-(int)si.nPage) si.nPos=si.nMax-si.nPage;
int yPos=si.nPos;
si.fMask=SIF_PAGE|SIF_RANGE|SIF_POS;
SetScrollInfo(SB_VERT,&si);
int width=cx>DLG_MINWIDTH?cx:DLG_MINWIDTH;
GetClientRect(rc);
if(rc.Width()!=cx||rc.Height()!=cy) SetCtrlPos();
else
{
// Set Ctrl Pos
int top=0;
CRect rcCtrl;
m_HeightDlg.GetClientRect(rc);
rcCtrl.SetRect(0,top,width,rc.Height());
rcCtrl.OffsetRect(-xPos,-yPos);
m_HeightDlg.MoveWindow(rcCtrl);
top+=rc.Height()+1;
m_TerrainTexDlg.GetClientRect(rc);
rcCtrl.SetRect(0,top,width,top+rc.Height());
rcCtrl.OffsetRect(-xPos,-yPos);
m_TerrainTexDlg.MoveWindow(rcCtrl);
top+=rc.Height()+1;
m_TerrainGrassDlg.GetClientRect(rc);
rcCtrl.SetRect(0,top,width,top+rc.Height());
rcCtrl.OffsetRect(-xPos,-yPos);
m_TerrainGrassDlg.MoveWindow(rcCtrl);
top+=rc.Height()+1;
m_TerrainWaterDlg.GetClientRect(rc);
rcCtrl.SetRect(0,top,width,top+rc.Height());
rcCtrl.OffsetRect(-xPos,-yPos);
m_TerrainWaterDlg.MoveWindow(rcCtrl);
top+=rc.Height()+1;
}
}
void CTerrainEditorDlg::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
SCROLLINFO si;
si.cbSize=sizeof(si);
GetScrollInfo(SB_HORZ,&si);
int pos;
switch(nSBCode)
{
case SB_LEFT:
ScrollWindow(si.nPos-si.nMin,0);
si.nPos=si.nMin;
SetScrollInfo(SB_HORZ,&si);
break;
case SB_RIGHT:
ScrollWindow(si.nPos-si.nMax+si.nPage,0);
si.nPos=si.nMax-si.nPage;
SetScrollInfo(SB_HORZ,&si);
break;
case SB_LINELEFT:
pos=si.nPos;
si.nPos-=10;
if(si.nPos<si.nMin) si.nPos=si.nMin;
ScrollWindow(pos-si.nPos,0);
SetScrollInfo(SB_HORZ,&si);
break;
case SB_LINERIGHT:
pos=si.nPos;
si.nPos+=si.nPage;
if(si.nPos>si.nMax-(int)si.nPage) si.nPos=si.nMax-si.nPage;
ScrollWindow(pos-si.nPos,0);
SetScrollInfo(SB_HORZ,&si);
break;
case SB_PAGELEFT:
pos=si.nPos;
si.nPos-=si.nPage;
if(si.nPos<si.nMin) si.nPos=si.nMin;
ScrollWindow(pos-si.nPos,0);
SetScrollInfo(SB_HORZ,&si);
break;
case SB_PAGERIGHT:
pos=si.nPos;
si.nPos+=10;
if(si.nPos>si.nMax-(int)si.nPage) si.nPos=si.nMax-si.nPage;
ScrollWindow(pos-si.nPos,0);
SetScrollInfo(SB_HORZ,&si);
break;
case SB_THUMBPOSITION:
case SB_THUMBTRACK:
ScrollWindow(si.nPos-nPos,0);
si.nPos=nPos;
SetScrollInfo(SB_HORZ,&si);
break;
default:
break;
}
CDialogEx::OnHScroll(nSBCode, nPos, pScrollBar);
}
void CTerrainEditorDlg::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
SCROLLINFO si;
si.cbSize=sizeof(si);
GetScrollInfo(SB_VERT,&si);
int pos;
// ScrollWindow(0,prev pos-current pos);
switch(nSBCode)
{
case SB_TOP:
ScrollWindow(0,si.nPos-si.nMin);
si.nPos=si.nMin;
SetScrollInfo(SB_VERT,&si);
break;
case SB_BOTTOM:
ScrollWindow(0,si.nPos-si.nMax+si.nPage);
si.nPos=si.nMax-si.nPage;
SetScrollInfo(SB_VERT,&si);
break;
case SB_LINEUP:
if((int)si.nPage<si.nMax)
{
pos=si.nPos;
si.nPos-=15;
if(si.nPos<si.nMin) si.nPos=si.nMin;
ScrollWindow(0,pos-si.nPos);
SetScrollInfo(SB_VERT,&si);
}
break;
case SB_LINEDOWN:
if((int)si.nPage<si.nMax)
{
pos=si.nPos;
si.nPos+=15;
if(si.nPos>si.nMax-(int)si.nPage) si.nPos=si.nMax-(int)si.nPage;
ScrollWindow(0,pos-si.nPos);
SetScrollInfo(SB_VERT,&si);
}
break;
case SB_PAGEUP:
pos=si.nPos;
si.nPos-=si.nPage;
if(si.nPos<si.nMin) si.nPos=si.nMin;
ScrollWindow(0,pos-si.nPos);
SetScrollInfo(SB_VERT,&si);
break;
case SB_PAGEDOWN:
pos=si.nPos;
si.nPos+=si.nPage;
if(si.nPos>si.nMax-(int)si.nPage) si.nPos=si.nMax-si.nPage;
ScrollWindow(0,pos-si.nPos);
SetScrollInfo(SB_VERT,&si);
break;
case SB_THUMBPOSITION:
case SB_THUMBTRACK:
pos=(int)nPos;
ScrollWindow(0,si.nPos-pos);
si.nPos=pos;
SetScrollInfo(SB_VERT,&si);
break;
default:
break;
}
CDialogEx::OnVScroll(nSBCode, nPos, pScrollBar);
}
LRESULT CTerrainEditorDlg::OnNcHitTest(CPoint point)
{
CRect rc;
GetClientRect(rc);
ScreenToClient(&point);
if(point.x>rc.right&&point.y<rc.bottom) return HTVSCROLL;
if(point.y>rc.bottom&&point.x<rc.right) return HTHSCROLL;
return CDialogEx::OnNcHitTest(point);
}
void CTerrainEditorDlg::EnableAllCtrls(BOOL bEnable)
{
m_HeightDlg.EnableAllCtrls(bEnable);
m_TerrainTexDlg.EnableAllCtrls(bEnable);
m_TerrainGrassDlg.EnableAllCtrls(bEnable);
m_TerrainWaterDlg.EnableAllCtrls(bEnable);
}
void CTerrainEditorDlg::SetButtonState(int nSelID)
{
if(m_nButtonState!=nSelID)
{
m_HeightDlg.SetButtonState(nSelID);
m_TerrainTexDlg.SetButtonState(nSelID);
m_TerrainGrassDlg.SetButtonState(nSelID);
m_TerrainWaterDlg.SetButtonState(nSelID);
m_nButtonState=nSelID;
}
} | [
"phoenixzz@sina.com"
] | phoenixzz@sina.com |
dd871135ed4a836f58ad38ab87ef1db3350b235b | ef85c7bb57412c86d9ab28a95fd299e8411c316e | /inference-engine/tests/functional/plugin/shared/src/low_precision_transformations/subtract_transformation.cpp | 58898d9be441ac4fc0f6c81229bbd684e0c3213e | [
"Apache-2.0"
] | permissive | SDxKeeper/dldt | 63bf19f01d8021c4d9d7b04bec334310b536a06a | a7dff0d0ec930c4c83690d41af6f6302b389f361 | refs/heads/master | 2023-01-08T19:47:29.937614 | 2021-10-22T15:56:53 | 2021-10-22T15:56:53 | 202,734,386 | 0 | 1 | Apache-2.0 | 2022-12-26T13:03:27 | 2019-08-16T13:41:06 | C++ | UTF-8 | C++ | false | false | 1,326 | cpp | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "low_precision_transformations/subtract_transformation.hpp"
#include <memory>
#include <tuple>
#include <vector>
#include <string>
#include <ie_core.hpp>
#include <transformations/init_node_info.hpp>
#include "lpt_ngraph_functions/subtract_function.hpp"
namespace LayerTestsDefinitions {
std::string SubtractTransformation::getTestCaseName(const testing::TestParamInfo<SubtractTransformationParams>& obj) {
ngraph::element::Type netPrecision;
ngraph::PartialShape inputShapes;
std::string targetDevice;
ngraph::pass::low_precision::LayerTransformation::Params params;
std::tie(netPrecision, inputShapes, targetDevice, params) = obj.param;
return getTestCaseNameByParams(netPrecision, inputShapes, targetDevice, params);
}
void SubtractTransformation::SetUp() {
ngraph::element::Type netPrecision;
ngraph::PartialShape inputShape;
ngraph::pass::low_precision::LayerTransformation::Params params;
std::tie(netPrecision, inputShape, targetDevice, params) = this->GetParam();
function = ngraph::builder::subgraph::SubtractFunction::getOriginal(netPrecision, inputShape);
}
TEST_P(SubtractTransformation, CompareWithRefImpl) {
Run();
};
} // namespace LayerTestsDefinitions
| [
"noreply@github.com"
] | SDxKeeper.noreply@github.com |
04c4463ff3537484b6a0b79cbd71cae73c1b7c83 | 5286798f369775a6607636a7c97c87d2a4380967 | /thirdparty/cgal/CGAL-5.1/include/CGAL/Segment_Delaunay_graph_Linf_filtered_traits_2.h | 4ea78cc324fdd488c0c9ecc9d6289b9d6502845a | [
"GPL-3.0-only",
"LGPL-2.1-or-later",
"LicenseRef-scancode-proprietary-license",
"GPL-1.0-or-later",
"LGPL-2.0-or-later",
"MIT",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference",
"MIT-0",
"LGPL-3.0-only",
"LGPL-3.0-or-later"
] | permissive | MelvinG24/dust3d | d03e9091c1368985302bd69e00f59fa031297037 | c4936fd900a9a48220ebb811dfeaea0effbae3ee | refs/heads/master | 2023-08-24T20:33:06.967388 | 2021-08-10T10:44:24 | 2021-08-10T10:44:24 | 293,045,595 | 0 | 0 | MIT | 2020-09-05T09:38:30 | 2020-09-05T09:38:29 | null | UTF-8 | C++ | false | false | 11,162 | h | // Copyright (c) 2015 Università della Svizzera italiana.
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org).
//
// $URL: https://github.com/CGAL/cgal/blob/v5.1/Segment_Delaunay_graph_Linf_2/include/CGAL/Segment_Delaunay_graph_Linf_filtered_traits_2.h $
// $Id: Segment_Delaunay_graph_Linf_filtered_traits_2.h 9a17c8d 2020-04-16T16:28:01+02:00 Sébastien Loriot
// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial
//
//
// Author(s) : Panagiotis Cheilaris, Sandeep Kumar Dey, Evanthia Papadopoulou
//philaris@gmail.com, sandeep.kr.dey@gmail.com, evanthia.papadopoulou@usi.ch
#ifndef CGAL_SEGMENT_DELAUNAY_GRAPH_LINF_FILTERED_TRAITS_2_H
#define CGAL_SEGMENT_DELAUNAY_GRAPH_LINF_FILTERED_TRAITS_2_H
#include <CGAL/license/Segment_Delaunay_graph_Linf_2.h>
#include <CGAL/disable_warnings.h>
#include <CGAL/Segment_Delaunay_graph_Linf_2/basic.h>
#include <CGAL/Segment_Delaunay_graph_Linf_2/Filtered_traits_base_2.h>
#include <CGAL/Segment_Delaunay_graph_2/Filtered_traits_concept_check_tags.h>
// includes for the default parameters of the filtered traits
#include <CGAL/internal/Exact_type_selector.h>
#include <CGAL/Simple_cartesian.h>
#include <CGAL/Interval_arithmetic.h>
#include <CGAL/Cartesian_converter.h>
#include <CGAL/number_utils_classes.h>
namespace CGAL {
#define SDG2_INS CGAL_SEGMENT_DELAUNAY_GRAPH_2_NS::Internal
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// the filtered Traits classes
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// this traits class does support intersecting segments
template<class CK,
class CK_MTag = Field_with_sqrt_tag,
class EK = Simple_cartesian< internal::Exact_field_selector<double>::Type >,
class EK_MTag = Field_tag,
class FK = Simple_cartesian< Interval_nt<false> >,
class FK_MTag = Field_with_sqrt_tag,
class C2E = Cartesian_converter<CK, EK>,
class C2F =
Cartesian_converter<CK, FK, To_interval<typename CK::RT> > >
struct Segment_Delaunay_graph_Linf_filtered_traits_2
: public Segment_Delaunay_graph_Linf_filtered_traits_base_2<CK, CK_MTag,
EK, EK_MTag,
FK, FK_MTag,
C2E, C2F,
Tag_true>
{
public:
Segment_Delaunay_graph_Linf_filtered_traits_2() {
SDG2_INS::Concept_check_tags<Integral_domain_without_division_tag,CK_MTag,2>();
SDG2_INS::Concept_check_tags<Integral_domain_without_division_tag,EK_MTag,4>();
SDG2_INS::Concept_check_tags<Integral_domain_without_division_tag,FK_MTag,6>();
}
};
template<class CK, class EK, class EK_MTag, class FK, class FK_MTag,
class C2E, class C2F>
struct Segment_Delaunay_graph_Linf_filtered_traits_2<CK, Field_tag,
EK, EK_MTag,
FK, FK_MTag,
C2E, C2F>
: public Segment_Delaunay_graph_Linf_filtered_traits_base_2<CK, Integral_domain_without_division_tag,
EK, EK_MTag,
FK, FK_MTag,
C2E, C2F,
Tag_true>
{
public:
Segment_Delaunay_graph_Linf_filtered_traits_2() {
SDG2_INS::Concept_check_tags<Integral_domain_without_division_tag,EK_MTag,4>();
SDG2_INS::Concept_check_tags<Integral_domain_without_division_tag,FK_MTag,6>();
}
};
template<class CK, class CK_MTag, class EK, class FK, class FK_MTag,
class C2E, class C2F>
struct Segment_Delaunay_graph_Linf_filtered_traits_2<CK, CK_MTag,
EK, Field_tag,
FK, FK_MTag,
C2E, C2F>
: public Segment_Delaunay_graph_Linf_filtered_traits_base_2<CK, CK_MTag,
EK, Integral_domain_without_division_tag,
FK, FK_MTag,
C2E, C2F,
Tag_true>
{
public:
Segment_Delaunay_graph_Linf_filtered_traits_2() {
SDG2_INS::Concept_check_tags<Integral_domain_without_division_tag,CK_MTag,2>();
SDG2_INS::Concept_check_tags<Integral_domain_without_division_tag,FK_MTag,6>();
}
};
template<class CK, class CK_MTag, class EK, class EK_MTag, class FK,
class C2E, class C2F>
struct Segment_Delaunay_graph_Linf_filtered_traits_2<CK, CK_MTag,
EK, EK_MTag,
FK, Field_tag,
C2E, C2F>
: public Segment_Delaunay_graph_Linf_filtered_traits_base_2<CK, CK_MTag,
EK, EK_MTag,
FK, Integral_domain_without_division_tag,
C2E, C2F,
Tag_true>
{
public:
Segment_Delaunay_graph_Linf_filtered_traits_2() {
SDG2_INS::Concept_check_tags<Integral_domain_without_division_tag,CK_MTag,2>();
SDG2_INS::Concept_check_tags<Integral_domain_without_division_tag,EK_MTag,4>();
}
};
template<class CK, class CK_MTag, class EK, class FK,
class C2E, class C2F>
struct Segment_Delaunay_graph_Linf_filtered_traits_2<CK, CK_MTag,
EK, Field_tag,
FK, Field_tag,
C2E, C2F>
: public Segment_Delaunay_graph_Linf_filtered_traits_base_2<CK, CK_MTag,
EK, Integral_domain_without_division_tag,
FK, Integral_domain_without_division_tag,
C2E, C2F,
Tag_true>
{
public:
Segment_Delaunay_graph_Linf_filtered_traits_2() {
SDG2_INS::Concept_check_tags<Integral_domain_without_division_tag,CK_MTag,2>();
}
};
template<class CK, class EK, class EK_MTag, class FK,
class C2E, class C2F>
struct Segment_Delaunay_graph_Linf_filtered_traits_2<CK, Field_tag,
EK, EK_MTag,
FK, Field_tag,
C2E, C2F>
: public Segment_Delaunay_graph_Linf_filtered_traits_base_2<CK, Integral_domain_without_division_tag,
EK, EK_MTag,
FK, Integral_domain_without_division_tag,
C2E, C2F,
Tag_true>
{
public:
Segment_Delaunay_graph_Linf_filtered_traits_2() {
SDG2_INS::Concept_check_tags<Integral_domain_without_division_tag,EK_MTag,4>();
}
};
template<class CK, class EK, class FK, class FK_MTag,
class C2E, class C2F>
struct Segment_Delaunay_graph_Linf_filtered_traits_2<CK, Field_tag,
EK, Field_tag,
FK, FK_MTag,
C2E, C2F>
: public Segment_Delaunay_graph_Linf_filtered_traits_base_2<CK, Integral_domain_without_division_tag,
EK, Integral_domain_without_division_tag,
FK, FK_MTag,
C2E, C2F,
Tag_true>
{
public:
Segment_Delaunay_graph_Linf_filtered_traits_2() {
SDG2_INS::Concept_check_tags<Integral_domain_without_division_tag,FK_MTag,6>();
}
};
template<class CK, class EK, class FK, class C2E, class C2F>
struct Segment_Delaunay_graph_Linf_filtered_traits_2<CK, Field_tag,
EK, Field_tag,
FK, Field_tag,
C2E, C2F>
: public Segment_Delaunay_graph_Linf_filtered_traits_base_2<CK, Integral_domain_without_division_tag,
EK, Integral_domain_without_division_tag,
FK, Integral_domain_without_division_tag,
C2E, C2F,
Tag_true>
{};
//=========================================================================
// this traits class does NOT support intersecting segments
template<class CK,
class CK_MTag = Field_with_sqrt_tag,
#ifdef CGAL_USE_GMP
class EK = Simple_cartesian< Gmpq >,
#else
class EK = Simple_cartesian< CGAL::Quotient<MP_Float> >,
#endif
class EK_MTag = Integral_domain_without_division_tag,
class FK = Simple_cartesian< Interval_nt<false> >,
class FK_MTag = Field_with_sqrt_tag,
class C2E = Cartesian_converter<CK, EK>,
class C2F =
Cartesian_converter<CK, FK, To_interval<typename CK::RT> > >
struct Segment_Delaunay_graph_Linf_filtered_traits_without_intersections_2
: public Segment_Delaunay_graph_Linf_filtered_traits_base_2<CK, CK_MTag,
EK, EK_MTag,
FK, FK_MTag,
C2E, C2F,
Tag_false>
{
Segment_Delaunay_graph_Linf_filtered_traits_without_intersections_2() {
SDG2_INS::Concept_check_tags_wi<Integral_domain_without_division_tag,CK_MTag,2>();
SDG2_INS::Concept_check_tags_wi<Integral_domain_without_division_tag,EK_MTag,4>();
SDG2_INS::Concept_check_tags_wi<Integral_domain_without_division_tag,FK_MTag,6>();
}
};
#undef SDG2_INS
} //namespace CGAL
#include <CGAL/enable_warnings.h>
#endif // CGAL_SEGMENT_DELAUNAY_GRAPH_LINF_FILTERED_TRAITS_2_H
| [
"huxingyi@msn.com"
] | huxingyi@msn.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.