hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a67a7f95be5bf83bba0dbdb6aae35befd1e0d7c6 | 2,073 | hh | C++ | gazebo/physics/bullet/BulletPlaneShape.hh | hyunoklee/Gazebo | 619218c0bb3dc8878b6c4dc2fddf3f7ec1d85497 | [
"ECL-2.0",
"Apache-2.0"
] | 45 | 2015-07-17T10:14:22.000Z | 2022-03-30T19:25:36.000Z | gazebo/physics/bullet/BulletPlaneShape.hh | hyunoklee/Gazebo | 619218c0bb3dc8878b6c4dc2fddf3f7ec1d85497 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2021-04-15T07:14:26.000Z | 2021-04-15T07:14:26.000Z | gazebo/physics/bullet/BulletPlaneShape.hh | hyunoklee/Gazebo | 619218c0bb3dc8878b6c4dc2fddf3f7ec1d85497 | [
"ECL-2.0",
"Apache-2.0"
] | 64 | 2015-04-18T07:10:14.000Z | 2022-02-21T13:15:41.000Z | /*
* Copyright (C) 2012-2014 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.
*
*/
/* Desc: Plane shape
* Author: Nate Koenig
* Date: 14 Oct 2009
*/
#ifndef _BULLETPLANESHAPE_HH_
#define _BULLETPLANESHAPE_HH_
#include <iostream>
#include "gazebo/physics/bullet/BulletPhysics.hh"
#include "gazebo/physics/PlaneShape.hh"
#include "gazebo/util/system.hh"
namespace gazebo
{
namespace physics
{
/// \ingroup gazebo_physics
/// \addtogroup gazebo_physics_bullet Bullet Physics
/// \{
/// \brief Bullet collision for an infinite plane.
class GAZEBO_VISIBLE BulletPlaneShape : public PlaneShape
{
/// \brief Constructor
public: BulletPlaneShape(CollisionPtr _parent) : PlaneShape(_parent) {}
/// \brief Destructor
public: virtual ~BulletPlaneShape() {}
/// \brief Set the altitude of the plane
public: void SetAltitude(const math::Vector3 &pos)
{
PlaneShape::SetAltitude(pos);
}
/// \brief Create the plane
public: void CreatePlane()
{
PlaneShape::CreatePlane();
BulletCollisionPtr bParent;
bParent = boost::dynamic_pointer_cast<BulletCollision>(
this->collisionParent);
math::Vector3 n = this->GetNormal();
btVector3 vec(n.x, n.y, n.z);
bParent->SetCollisionShape(new btStaticPlaneShape(vec, 0.0),
false);
}
};
/// \}
}
}
#endif
| 28.39726 | 77 | 0.638205 | [
"shape"
] |
a67f1de67ed73ec15e238c07e746a91a5eddd52f | 31,155 | cpp | C++ | llvm/utils/TableGen/GlobalISel/GIMatchTree.cpp | atulkulk/intel-llvm | b8afff4213ccbbd936da59ad235a276b868b6b86 | [
"Apache-2.0"
] | null | null | null | llvm/utils/TableGen/GlobalISel/GIMatchTree.cpp | atulkulk/intel-llvm | b8afff4213ccbbd936da59ad235a276b868b6b86 | [
"Apache-2.0"
] | 6 | 2021-02-04T21:32:09.000Z | 2021-02-08T09:31:15.000Z | llvm/utils/TableGen/GlobalISel/GIMatchTree.cpp | AlexeySachkov/llvm | 4a5f2a7830a9195cf13c8063c1c9f8c2b03730c2 | [
"Apache-2.0"
] | null | null | null | //===- GIMatchTree.cpp - A decision tree to match GIMatchDag's ------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "GIMatchTree.h"
#include "../CodeGenInstruction.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/ScopedPrinter.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/TableGen/Error.h"
#include "llvm/TableGen/Record.h"
#define DEBUG_TYPE "gimatchtree"
using namespace llvm;
void GIMatchTree::writeDOTGraph(raw_ostream &OS) const {
OS << "digraph \"matchtree\" {\n";
writeDOTGraphNode(OS);
OS << "}\n";
}
void GIMatchTree::writeDOTGraphNode(raw_ostream &OS) const {
OS << format(" Node%p", this) << " [shape=record,label=\"{";
if (Partitioner) {
Partitioner->emitDescription(OS);
OS << "|" << Partitioner->getNumPartitions() << " partitions|";
} else
OS << "No partitioner|";
bool IsFullyTraversed = true;
bool IsFullyTested = true;
StringRef Separator = "";
for (const auto &Leaf : PossibleLeaves) {
OS << Separator << Leaf.getName();
Separator = ",";
if (!Leaf.isFullyTraversed())
IsFullyTraversed = false;
if (!Leaf.isFullyTested())
IsFullyTested = false;
}
if (!Partitioner && !IsFullyTraversed)
OS << "|Not fully traversed";
if (!Partitioner && !IsFullyTested) {
OS << "|Not fully tested";
if (IsFullyTraversed) {
for (const GIMatchTreeLeafInfo &Leaf : PossibleLeaves) {
if (Leaf.isFullyTested())
continue;
OS << "\\n" << Leaf.getName() << ": " << &Leaf;
for (const GIMatchDagPredicate *P : Leaf.untested_predicates())
OS << *P;
}
}
}
OS << "}\"";
if (!Partitioner &&
(!IsFullyTraversed || !IsFullyTested || PossibleLeaves.size() > 1))
OS << ",color=red";
OS << "]\n";
for (const auto &C : Children)
C.writeDOTGraphNode(OS);
writeDOTGraphEdges(OS);
}
void GIMatchTree::writeDOTGraphEdges(raw_ostream &OS) const {
for (const auto &Child : enumerate(Children)) {
OS << format(" Node%p", this) << " -> " << format("Node%p", &Child.value())
<< " [label=\"#" << Child.index() << " ";
Partitioner->emitPartitionName(OS, Child.index());
OS << "\"]\n";
}
}
GIMatchTreeBuilderLeafInfo::GIMatchTreeBuilderLeafInfo(
GIMatchTreeBuilder &Builder, StringRef Name, unsigned RootIdx,
const GIMatchDag &MatchDag, void *Data)
: Builder(Builder), Info(Name, RootIdx, Data), MatchDag(MatchDag),
InstrNodeToInfo(),
RemainingInstrNodes(BitVector(MatchDag.getNumInstrNodes(), true)),
RemainingEdges(BitVector(MatchDag.getNumEdges(), true)),
RemainingPredicates(BitVector(MatchDag.getNumPredicates(), true)),
TraversableEdges(MatchDag.getNumEdges()),
TestablePredicates(MatchDag.getNumPredicates()) {
// Number all the predicates in this DAG
for (auto &P : enumerate(MatchDag.predicates())) {
PredicateIDs.insert(std::make_pair(P.value(), P.index()));
}
// Number all the predicate dependencies in this DAG and set up a bitvector
// for each predicate indicating the unsatisfied dependencies.
for (auto &Dep : enumerate(MatchDag.predicate_edges())) {
PredicateDepIDs.insert(std::make_pair(Dep.value(), Dep.index()));
}
UnsatisfiedPredDepsForPred.resize(MatchDag.getNumPredicates(),
BitVector(PredicateDepIDs.size()));
for (auto &Dep : enumerate(MatchDag.predicate_edges())) {
unsigned ID = PredicateIDs.lookup(Dep.value()->getPredicate());
UnsatisfiedPredDepsForPred[ID].set(Dep.index());
}
}
void GIMatchTreeBuilderLeafInfo::declareInstr(const GIMatchDagInstr *Instr, unsigned ID) {
// Record the assignment of this instr to the given ID.
auto InfoI = InstrNodeToInfo.insert(std::make_pair(
Instr, GIMatchTreeInstrInfo(ID, Instr)));
InstrIDToInfo.insert(std::make_pair(ID, &InfoI.first->second));
if (Instr == nullptr)
return;
if (!Instr->getUserAssignedName().empty())
Info.bindInstrVariable(Instr->getUserAssignedName(), ID);
for (const auto &VarBinding : Instr->user_assigned_operand_names())
Info.bindOperandVariable(VarBinding.second, ID, VarBinding.first);
// Clear the bit indicating we haven't visited this instr.
const auto &NodeI = find(MatchDag.instr_nodes(), Instr);
assert(NodeI != MatchDag.instr_nodes_end() && "Instr isn't in this DAG");
unsigned InstrIdx = MatchDag.getInstrNodeIdx(NodeI);
RemainingInstrNodes.reset(InstrIdx);
// When we declare an instruction, we don't expose any traversable edges just
// yet. A partitioner has to check they exist and are registers before they
// are traversable.
// When we declare an instruction, we potentially activate some predicates.
// Mark the dependencies that are now satisfied as a result of this
// instruction and mark any predicates whose dependencies are fully
// satisfied.
for (auto &Dep : enumerate(MatchDag.predicate_edges())) {
if (Dep.value()->getRequiredMI() == Instr &&
Dep.value()->getRequiredMO() == nullptr) {
for (auto &DepsFor : enumerate(UnsatisfiedPredDepsForPred)) {
DepsFor.value().reset(Dep.index());
if (DepsFor.value().none())
TestablePredicates.set(DepsFor.index());
}
}
}
}
void GIMatchTreeBuilderLeafInfo::declareOperand(unsigned InstrID,
unsigned OpIdx) {
const GIMatchDagInstr *Instr = InstrIDToInfo.lookup(InstrID)->getInstrNode();
OperandIDToInfo.insert(std::make_pair(
std::make_pair(InstrID, OpIdx),
GIMatchTreeOperandInfo(Instr, OpIdx)));
// When an operand becomes reachable, we potentially activate some traversals.
// Record the edges that can now be followed as a result of this
// instruction.
for (auto &E : enumerate(MatchDag.edges())) {
if (E.value()->getFromMI() == Instr &&
E.value()->getFromMO()->getIdx() == OpIdx) {
TraversableEdges.set(E.index());
}
}
// When an operand becomes reachable, we potentially activate some predicates.
// Clear the dependencies that are now satisfied as a result of this
// operand and activate any predicates whose dependencies are fully
// satisfied.
for (auto &Dep : enumerate(MatchDag.predicate_edges())) {
if (Dep.value()->getRequiredMI() == Instr && Dep.value()->getRequiredMO() &&
Dep.value()->getRequiredMO()->getIdx() == OpIdx) {
for (auto &DepsFor : enumerate(UnsatisfiedPredDepsForPred)) {
DepsFor.value().reset(Dep.index());
if (DepsFor.value().none())
TestablePredicates.set(DepsFor.index());
}
}
}
}
void GIMatchTreeBuilder::addPartitionersForInstr(unsigned InstrIdx) {
// Find the partitioners that can be used now that this node is
// uncovered. Our choices are:
// - Test the opcode
addPartitioner(std::make_unique<GIMatchTreeOpcodePartitioner>(InstrIdx));
}
void GIMatchTreeBuilder::addPartitionersForOperand(unsigned InstrID,
unsigned OpIdx) {
LLVM_DEBUG(dbgs() << "Add partitioners for Instrs[" << InstrID
<< "].getOperand(" << OpIdx << ")\n");
addPartitioner(
std::make_unique<GIMatchTreeVRegDefPartitioner>(InstrID, OpIdx));
}
void GIMatchTreeBuilder::filterRedundantPartitioners() {
// TODO: Filter partitioners for facts that are already known
// - If we know the opcode, we can elide the num operand check so long as
// the instruction has a fixed number of operands.
// - If we know an exact number of operands then we can elide further number
// of operand checks.
// - If the current min number of operands exceeds the one we want to check
// then we can elide it.
}
void GIMatchTreeBuilder::evaluatePartitioners() {
// Determine the partitioning the partitioner would produce
for (auto &Partitioner : Partitioners) {
LLVM_DEBUG(dbgs() << " Weighing up ";
Partitioner->emitDescription(dbgs()); dbgs() << "\n");
Partitioner->repartition(Leaves);
LLVM_DEBUG(Partitioner->emitPartitionResults(dbgs()));
}
}
void GIMatchTreeBuilder::runStep() {
LLVM_DEBUG(dbgs() << "Building match tree node for " << TreeNode << "\n");
LLVM_DEBUG(dbgs() << " Rules reachable at this node:\n");
for (const auto &Leaf : Leaves) {
LLVM_DEBUG(dbgs() << " " << Leaf.getName() << " (" << &Leaf.getInfo() << "\n");
TreeNode->addPossibleLeaf(Leaf.getInfo(), Leaf.isFullyTraversed(),
Leaf.isFullyTested());
}
LLVM_DEBUG(dbgs() << " Partitioners available at this node:\n");
#ifndef NDEBUG
for (const auto &Partitioner : Partitioners)
LLVM_DEBUG(dbgs() << " "; Partitioner->emitDescription(dbgs());
dbgs() << "\n");
#endif // ifndef NDEBUG
// Check for unreachable rules. Rules are unreachable if they are preceeded by
// a fully tested rule.
// Note: This is only true for the current algorithm, if we allow the
// algorithm to compare equally valid rules then they will become
// reachable.
{
auto FullyTestedLeafI = Leaves.end();
for (auto LeafI = Leaves.begin(), LeafE = Leaves.end();
LeafI != LeafE; ++LeafI) {
if (LeafI->isFullyTraversed() && LeafI->isFullyTested())
FullyTestedLeafI = LeafI;
else if (FullyTestedLeafI != Leaves.end()) {
PrintError("Leaf " + LeafI->getName() + " is unreachable");
PrintNote("Leaf " + FullyTestedLeafI->getName() +
" will have already matched");
}
}
}
LLVM_DEBUG(dbgs() << " Eliminating redundant partitioners:\n");
filterRedundantPartitioners();
LLVM_DEBUG(dbgs() << " Partitioners remaining:\n");
#ifndef NDEBUG
for (const auto &Partitioner : Partitioners)
LLVM_DEBUG(dbgs() << " "; Partitioner->emitDescription(dbgs());
dbgs() << "\n");
#endif // ifndef NDEBUG
if (Partitioners.empty()) {
// Nothing left to do but check we really did identify a single rule.
if (Leaves.size() > 1) {
LLVM_DEBUG(dbgs() << "Leaf contains multiple rules, drop after the first "
"fully tested rule\n");
auto FirstFullyTested =
llvm::find_if(Leaves, [](const GIMatchTreeBuilderLeafInfo &X) {
return X.isFullyTraversed() && X.isFullyTested() &&
!X.getMatchDag().hasPostMatchPredicate();
});
if (FirstFullyTested != Leaves.end())
FirstFullyTested++;
#ifndef NDEBUG
for (auto &Leaf : make_range(Leaves.begin(), FirstFullyTested))
LLVM_DEBUG(dbgs() << " Kept " << Leaf.getName() << "\n");
for (const auto &Leaf : make_range(FirstFullyTested, Leaves.end()))
LLVM_DEBUG(dbgs() << " Dropped " << Leaf.getName() << "\n");
#endif // ifndef NDEBUG
TreeNode->dropLeavesAfter(
std::distance(Leaves.begin(), FirstFullyTested));
}
for (const auto &Leaf : Leaves) {
if (!Leaf.isFullyTraversed()) {
PrintError("Leaf " + Leaf.getName() + " is not fully traversed");
PrintNote("This indicates a missing partitioner within tblgen");
Leaf.dump(errs());
for (unsigned InstrIdx : Leaf.untested_instrs())
PrintNote("Instr " + llvm::to_string(*Leaf.getInstr(InstrIdx)));
for (unsigned EdgeIdx : Leaf.untested_edges())
PrintNote("Edge " + llvm::to_string(*Leaf.getEdge(EdgeIdx)));
}
}
// Copy out information about untested predicates so the user of the tree
// can deal with them.
for (auto LeafPair : zip(Leaves, TreeNode->possible_leaves())) {
const GIMatchTreeBuilderLeafInfo &BuilderLeaf = std::get<0>(LeafPair);
GIMatchTreeLeafInfo &TreeLeaf = std::get<1>(LeafPair);
if (!BuilderLeaf.isFullyTested())
for (unsigned PredicateIdx : BuilderLeaf.untested_predicates())
TreeLeaf.addUntestedPredicate(BuilderLeaf.getPredicate(PredicateIdx));
}
return;
}
LLVM_DEBUG(dbgs() << " Weighing up partitioners:\n");
evaluatePartitioners();
// Select the best partitioner by its ability to partition
// - Prefer partitioners that don't distinguish between partitions. This
// is to fail early on decisions that must go a single way.
auto PartitionerI = std::max_element(
Partitioners.begin(), Partitioners.end(),
[](const std::unique_ptr<GIMatchTreePartitioner> &A,
const std::unique_ptr<GIMatchTreePartitioner> &B) {
// We generally want partitioners that subdivide the
// ruleset as much as possible since these take fewer
// checks to converge on a particular rule. However,
// it's important to note that one leaf can end up in
// multiple partitions if the check isn't mutually
// exclusive (e.g. getVRegDef() vs isReg()).
// We therefore minimize average leaves per partition.
return (double)A->getNumLeavesWithDupes() / A->getNumPartitions() >
(double)B->getNumLeavesWithDupes() / B->getNumPartitions();
});
// Select a partitioner and partition the ruleset
// Note that it's possible for a single rule to end up in multiple
// partitions. For example, an opcode test on a rule without an opcode
// predicate will result in it being passed to all partitions.
std::unique_ptr<GIMatchTreePartitioner> Partitioner = std::move(*PartitionerI);
Partitioners.erase(PartitionerI);
LLVM_DEBUG(dbgs() << " Selected partitioner: ";
Partitioner->emitDescription(dbgs()); dbgs() << "\n");
assert(Partitioner->getNumPartitions() > 0 &&
"Must always partition into at least one partition");
TreeNode->setNumChildren(Partitioner->getNumPartitions());
for (auto &C : enumerate(TreeNode->children())) {
SubtreeBuilders.emplace_back(&C.value(), NextInstrID);
Partitioner->applyForPartition(C.index(), *this, SubtreeBuilders.back());
}
TreeNode->setPartitioner(std::move(Partitioner));
// Recurse into the subtree builders. Each one must get a copy of the
// remaining partitioners as each path has to check everything.
for (auto &SubtreeBuilder : SubtreeBuilders) {
for (const auto &Partitioner : Partitioners)
SubtreeBuilder.addPartitioner(Partitioner->clone());
SubtreeBuilder.runStep();
}
}
std::unique_ptr<GIMatchTree> GIMatchTreeBuilder::run() {
unsigned NewInstrID = allocInstrID();
// Start by recording the root instruction as instr #0 and set up the initial
// partitioners.
for (auto &Leaf : Leaves) {
LLVM_DEBUG(Leaf.getMatchDag().writeDOTGraph(dbgs(), Leaf.getName()));
GIMatchDagInstr *Root =
*(Leaf.getMatchDag().roots().begin() + Leaf.getRootIdx());
Leaf.declareInstr(Root, NewInstrID);
}
addPartitionersForInstr(NewInstrID);
std::unique_ptr<GIMatchTree> TreeRoot = std::make_unique<GIMatchTree>();
TreeNode = TreeRoot.get();
runStep();
return TreeRoot;
}
void GIMatchTreeOpcodePartitioner::emitPartitionName(raw_ostream &OS, unsigned Idx) const {
if (PartitionToInstr[Idx] == nullptr) {
OS << "* or nullptr";
return;
}
OS << PartitionToInstr[Idx]->Namespace
<< "::" << PartitionToInstr[Idx]->TheDef->getName();
}
void GIMatchTreeOpcodePartitioner::repartition(
GIMatchTreeBuilder::LeafVec &Leaves) {
Partitions.clear();
InstrToPartition.clear();
PartitionToInstr.clear();
TestedPredicates.clear();
for (const auto &Leaf : enumerate(Leaves)) {
bool AllOpcodes = true;
GIMatchTreeInstrInfo *InstrInfo = Leaf.value().getInstrInfo(InstrID);
BitVector TestedPredicatesForLeaf(
Leaf.value().getMatchDag().getNumPredicates());
// If the instruction isn't declared then we don't care about it. Ignore
// it for now and add it to all partitions later once we know what
// partitions we have.
if (!InstrInfo) {
LLVM_DEBUG(dbgs() << " " << Leaf.value().getName()
<< " doesn't care about Instr[" << InstrID << "]\n");
assert(TestedPredicatesForLeaf.size() == Leaf.value().getMatchDag().getNumPredicates());
TestedPredicates.push_back(TestedPredicatesForLeaf);
continue;
}
// If the opcode is available to test then any opcode predicates will have
// been enabled too.
for (unsigned PIdx : Leaf.value().TestablePredicates.set_bits()) {
const auto &P = Leaf.value().getPredicate(PIdx);
SmallVector<const CodeGenInstruction *, 1> OpcodesForThisPredicate;
if (const auto *OpcodeP = dyn_cast<const GIMatchDagOpcodePredicate>(P)) {
// We've found _an_ opcode predicate, but we don't know if it's
// checking this instruction yet.
bool IsThisPredicate = false;
for (const auto &PDep : Leaf.value().getMatchDag().predicate_edges()) {
if (PDep->getRequiredMI() == InstrInfo->getInstrNode() &&
PDep->getRequiredMO() == nullptr && PDep->getPredicate() == P) {
IsThisPredicate = true;
break;
}
}
if (!IsThisPredicate)
continue;
// If we get here twice then we've somehow ended up with two opcode
// predicates for one instruction in the same DAG. That should be
// impossible.
assert(AllOpcodes && "Conflicting opcode predicates");
const CodeGenInstruction *Expected = OpcodeP->getInstr();
OpcodesForThisPredicate.push_back(Expected);
}
if (const auto *OpcodeP =
dyn_cast<const GIMatchDagOneOfOpcodesPredicate>(P)) {
// We've found _an_ oneof(opcodes) predicate, but we don't know if it's
// checking this instruction yet.
bool IsThisPredicate = false;
for (const auto &PDep : Leaf.value().getMatchDag().predicate_edges()) {
if (PDep->getRequiredMI() == InstrInfo->getInstrNode() &&
PDep->getRequiredMO() == nullptr && PDep->getPredicate() == P) {
IsThisPredicate = true;
break;
}
}
if (!IsThisPredicate)
continue;
// If we get here twice then we've somehow ended up with two opcode
// predicates for one instruction in the same DAG. That should be
// impossible.
assert(AllOpcodes && "Conflicting opcode predicates");
for (const CodeGenInstruction *Expected : OpcodeP->getInstrs())
OpcodesForThisPredicate.push_back(Expected);
}
for (const CodeGenInstruction *Expected : OpcodesForThisPredicate) {
// Mark this predicate as one we're testing.
TestedPredicatesForLeaf.set(PIdx);
// Partitions must be numbered 0, 1, .., N but instructions don't meet
// that requirement. Assign a partition number to each opcode if we
// lack one ...
auto Partition = InstrToPartition.find(Expected);
if (Partition == InstrToPartition.end()) {
BitVector Contents(Leaves.size());
Partition = InstrToPartition
.insert(std::make_pair(Expected, Partitions.size()))
.first;
PartitionToInstr.push_back(Expected);
Partitions.insert(std::make_pair(Partitions.size(), Contents));
}
// ... and mark this leaf as being in that partition.
Partitions.find(Partition->second)->second.set(Leaf.index());
AllOpcodes = false;
LLVM_DEBUG(dbgs() << " " << Leaf.value().getName()
<< " is in partition " << Partition->second << "\n");
}
// TODO: This is where we would handle multiple choices of opcode
// the end result will be that this leaf ends up in multiple
// partitions similarly to AllOpcodes.
}
// If we never check the opcode, add it to every partition.
if (AllOpcodes) {
// Add a partition for the default case if we don't already have one.
if (InstrToPartition.insert(std::make_pair(nullptr, 0)).second) {
PartitionToInstr.push_back(nullptr);
BitVector Contents(Leaves.size());
Partitions.insert(std::make_pair(Partitions.size(), Contents));
}
LLVM_DEBUG(dbgs() << " " << Leaf.value().getName()
<< " is in all partitions (opcode not checked)\n");
for (auto &Partition : Partitions)
Partition.second.set(Leaf.index());
}
assert(TestedPredicatesForLeaf.size() == Leaf.value().getMatchDag().getNumPredicates());
TestedPredicates.push_back(TestedPredicatesForLeaf);
}
if (Partitions.size() == 0) {
// Add a partition for the default case if we don't already have one.
if (InstrToPartition.insert(std::make_pair(nullptr, 0)).second) {
PartitionToInstr.push_back(nullptr);
BitVector Contents(Leaves.size());
Partitions.insert(std::make_pair(Partitions.size(), Contents));
}
}
// Add any leaves that don't care about this instruction to all partitions.
for (const auto &Leaf : enumerate(Leaves)) {
GIMatchTreeInstrInfo *InstrInfo = Leaf.value().getInstrInfo(InstrID);
if (!InstrInfo) {
// Add a partition for the default case if we don't already have one.
if (InstrToPartition.insert(std::make_pair(nullptr, 0)).second) {
PartitionToInstr.push_back(nullptr);
BitVector Contents(Leaves.size());
Partitions.insert(std::make_pair(Partitions.size(), Contents));
}
for (auto &Partition : Partitions)
Partition.second.set(Leaf.index());
}
}
}
void GIMatchTreeOpcodePartitioner::applyForPartition(
unsigned PartitionIdx, GIMatchTreeBuilder &Builder, GIMatchTreeBuilder &SubBuilder) {
LLVM_DEBUG(dbgs() << " Making partition " << PartitionIdx << "\n");
const CodeGenInstruction *CGI = PartitionToInstr[PartitionIdx];
BitVector PossibleLeaves = getPossibleLeavesForPartition(PartitionIdx);
// Consume any predicates we handled.
for (auto &EnumeratedLeaf : enumerate(Builder.getPossibleLeaves())) {
if (!PossibleLeaves[EnumeratedLeaf.index()])
continue;
auto &Leaf = EnumeratedLeaf.value();
const auto &TestedPredicatesForLeaf =
TestedPredicates[EnumeratedLeaf.index()];
for (unsigned PredIdx : TestedPredicatesForLeaf.set_bits()) {
LLVM_DEBUG(dbgs() << " " << Leaf.getName() << " tested predicate #"
<< PredIdx << " of " << TestedPredicatesForLeaf.size()
<< " " << *Leaf.getPredicate(PredIdx) << "\n");
Leaf.RemainingPredicates.reset(PredIdx);
Leaf.TestablePredicates.reset(PredIdx);
}
SubBuilder.addLeaf(Leaf);
}
// Nothing to do, we don't know anything about this instruction as a result
// of this partitioner.
if (CGI == nullptr)
return;
GIMatchTreeBuilder::LeafVec &NewLeaves = SubBuilder.getPossibleLeaves();
// Find all the operands we know to exist and are referenced. This will
// usually be all the referenced operands but there are some cases where
// instructions are variadic. Such operands must be handled by partitioners
// that check the number of operands.
BitVector ReferencedOperands(1);
for (auto &Leaf : NewLeaves) {
GIMatchTreeInstrInfo *InstrInfo = Leaf.getInstrInfo(InstrID);
// Skip any leaves that don't care about this instruction.
if (!InstrInfo)
continue;
const GIMatchDagInstr *Instr = InstrInfo->getInstrNode();
for (auto &E : enumerate(Leaf.getMatchDag().edges())) {
if (E.value()->getFromMI() == Instr &&
E.value()->getFromMO()->getIdx() < CGI->Operands.size()) {
ReferencedOperands.resize(E.value()->getFromMO()->getIdx() + 1);
ReferencedOperands.set(E.value()->getFromMO()->getIdx());
}
}
}
for (auto &Leaf : NewLeaves) {
for (unsigned OpIdx : ReferencedOperands.set_bits()) {
Leaf.declareOperand(InstrID, OpIdx);
}
}
for (unsigned OpIdx : ReferencedOperands.set_bits()) {
SubBuilder.addPartitionersForOperand(InstrID, OpIdx);
}
}
void GIMatchTreeOpcodePartitioner::emitPartitionResults(
raw_ostream &OS) const {
OS << "Partitioning by opcode would produce " << Partitions.size()
<< " partitions\n";
for (const auto &Partition : InstrToPartition) {
if (Partition.first == nullptr)
OS << "Default: ";
else
OS << Partition.first->TheDef->getName() << ": ";
StringRef Separator = "";
for (unsigned I : Partitions.find(Partition.second)->second.set_bits()) {
OS << Separator << I;
Separator = ", ";
}
OS << "\n";
}
}
void GIMatchTreeOpcodePartitioner::generatePartitionSelectorCode(
raw_ostream &OS, StringRef Indent) const {
// Make sure not to emit empty switch or switch with just default
if (PartitionToInstr.size() == 1 && PartitionToInstr[0] == nullptr) {
OS << Indent << "Partition = 0;\n";
} else if (PartitionToInstr.size()) {
OS << Indent << "Partition = -1;\n"
<< Indent << "switch (MIs[" << InstrID << "]->getOpcode()) {\n";
for (const auto &EnumInstr : enumerate(PartitionToInstr)) {
if (EnumInstr.value() == nullptr)
OS << Indent << "default:";
else
OS << Indent << "case " << EnumInstr.value()->Namespace
<< "::" << EnumInstr.value()->TheDef->getName() << ":";
OS << " Partition = " << EnumInstr.index() << "; break;\n";
}
OS << Indent << "}\n";
}
OS << Indent
<< "// Default case but without conflicting with potential default case "
"in selection.\n"
<< Indent << "if (Partition == -1) return false;\n";
}
void GIMatchTreeVRegDefPartitioner::addToPartition(bool Result,
unsigned LeafIdx) {
auto I = ResultToPartition.find(Result);
if (I == ResultToPartition.end()) {
ResultToPartition.insert(std::make_pair(Result, PartitionToResult.size()));
PartitionToResult.push_back(Result);
}
I = ResultToPartition.find(Result);
auto P = Partitions.find(I->second);
if (P == Partitions.end())
P = Partitions.insert(std::make_pair(I->second, BitVector())).first;
P->second.resize(LeafIdx + 1);
P->second.set(LeafIdx);
}
void GIMatchTreeVRegDefPartitioner::repartition(
GIMatchTreeBuilder::LeafVec &Leaves) {
Partitions.clear();
for (const auto &Leaf : enumerate(Leaves)) {
GIMatchTreeInstrInfo *InstrInfo = Leaf.value().getInstrInfo(InstrID);
BitVector TraversedEdgesForLeaf(Leaf.value().getMatchDag().getNumEdges());
// If the instruction isn't declared then we don't care about it. Ignore
// it for now and add it to all partitions later once we know what
// partitions we have.
if (!InstrInfo) {
TraversedEdges.push_back(TraversedEdgesForLeaf);
continue;
}
// If this node has an use -> def edge from this operand then this
// instruction must be in partition 1 (isVRegDef()).
bool WantsEdge = false;
for (unsigned EIdx : Leaf.value().TraversableEdges.set_bits()) {
const auto &E = Leaf.value().getEdge(EIdx);
if (E->getFromMI() != InstrInfo->getInstrNode() ||
E->getFromMO()->getIdx() != OpIdx || E->isDefToUse())
continue;
// We're looking at the right edge. This leaf wants a vreg def so we'll
// put it in partition 1.
addToPartition(true, Leaf.index());
TraversedEdgesForLeaf.set(EIdx);
WantsEdge = true;
}
bool isNotReg = false;
if (!WantsEdge && isNotReg) {
// If this leaf doesn't have an edge and we _don't_ want a register,
// then add it to partition 0.
addToPartition(false, Leaf.index());
} else if (!WantsEdge) {
// If this leaf doesn't have an edge and we don't know what we want,
// then add it to partition 0 and 1.
addToPartition(false, Leaf.index());
addToPartition(true, Leaf.index());
}
TraversedEdges.push_back(TraversedEdgesForLeaf);
}
// Add any leaves that don't care about this instruction to all partitions.
for (const auto &Leaf : enumerate(Leaves)) {
GIMatchTreeInstrInfo *InstrInfo = Leaf.value().getInstrInfo(InstrID);
if (!InstrInfo)
for (auto &Partition : Partitions)
Partition.second.set(Leaf.index());
}
}
void GIMatchTreeVRegDefPartitioner::applyForPartition(
unsigned PartitionIdx, GIMatchTreeBuilder &Builder,
GIMatchTreeBuilder &SubBuilder) {
BitVector PossibleLeaves = getPossibleLeavesForPartition(PartitionIdx);
std::vector<BitVector> TraversedEdgesByNewLeaves;
// Consume any edges we handled.
for (auto &EnumeratedLeaf : enumerate(Builder.getPossibleLeaves())) {
if (!PossibleLeaves[EnumeratedLeaf.index()])
continue;
auto &Leaf = EnumeratedLeaf.value();
const auto &TraversedEdgesForLeaf = TraversedEdges[EnumeratedLeaf.index()];
TraversedEdgesByNewLeaves.push_back(TraversedEdgesForLeaf);
Leaf.RemainingEdges.reset(TraversedEdgesForLeaf);
Leaf.TraversableEdges.reset(TraversedEdgesForLeaf);
SubBuilder.addLeaf(Leaf);
}
// Nothing to do. The only thing we know is that it isn't a vreg-def.
if (PartitionToResult[PartitionIdx] == false)
return;
NewInstrID = SubBuilder.allocInstrID();
GIMatchTreeBuilder::LeafVec &NewLeaves = SubBuilder.getPossibleLeaves();
for (const auto I : zip(NewLeaves, TraversedEdgesByNewLeaves)) {
auto &Leaf = std::get<0>(I);
auto &TraversedEdgesForLeaf = std::get<1>(I);
GIMatchTreeInstrInfo *InstrInfo = Leaf.getInstrInfo(InstrID);
// Skip any leaves that don't care about this instruction.
if (!InstrInfo)
continue;
for (unsigned EIdx : TraversedEdgesForLeaf.set_bits()) {
const GIMatchDagEdge *E = Leaf.getEdge(EIdx);
Leaf.declareInstr(E->getToMI(), NewInstrID);
}
}
SubBuilder.addPartitionersForInstr(NewInstrID);
}
void GIMatchTreeVRegDefPartitioner::emitPartitionResults(
raw_ostream &OS) const {
OS << "Partitioning by vreg-def would produce " << Partitions.size()
<< " partitions\n";
for (const auto &Partition : Partitions) {
OS << Partition.first << " (";
emitPartitionName(OS, Partition.first);
OS << "): ";
StringRef Separator = "";
for (unsigned I : Partition.second.set_bits()) {
OS << Separator << I;
Separator = ", ";
}
OS << "\n";
}
}
void GIMatchTreeVRegDefPartitioner::generatePartitionSelectorCode(
raw_ostream &OS, StringRef Indent) const {
OS << Indent << "Partition = -1\n"
<< Indent << "if (MIs.size() <= NewInstrID) MIs.resize(NewInstrID + 1);\n"
<< Indent << "MIs[" << NewInstrID << "] = nullptr;\n"
<< Indent << "if (MIs[" << InstrID << "].getOperand(" << OpIdx
<< ").isReg()))\n"
<< Indent << " MIs[" << NewInstrID << "] = MRI.getVRegDef(MIs[" << InstrID
<< "].getOperand(" << OpIdx << ").getReg()));\n";
for (const auto &Pair : ResultToPartition)
OS << Indent << "if (MIs[" << NewInstrID << "] "
<< (Pair.first ? "==" : "!=")
<< " nullptr) Partition = " << Pair.second << ";\n";
OS << Indent << "if (Partition == -1) return false;\n";
}
| 39.891165 | 94 | 0.650393 | [
"shape",
"vector"
] |
a691a39dc5b9cdc5ed1475a6803a96fbcf4f5881 | 810 | cpp | C++ | main.cpp | ids-imaging/ids-nxt-vision-app-multi-cnn-classifier | 894488306a883e981cfc44ca30ad19a27c2109fa | [
"Apache-2.0"
] | null | null | null | main.cpp | ids-imaging/ids-nxt-vision-app-multi-cnn-classifier | 894488306a883e981cfc44ca30ad19a27c2109fa | [
"Apache-2.0"
] | null | null | null | main.cpp | ids-imaging/ids-nxt-vision-app-multi-cnn-classifier | 894488306a883e981cfc44ca30ad19a27c2109fa | [
"Apache-2.0"
] | null | null | null | #include <QLoggingCategory>
// Include framework headers
#include "signaler.h"
#include "systemsignals.h"
// Include local header files
#include "myapp.h"
// Instantiate a QLoggingCategory Object
static QLoggingCategory lc{"multicnnclassifier"};
/**
* @brief Serves as the main entry point for our program
* @param argc count of command line arguments
* @param argv list of command line arguments
* @return Exit success
*/
int main(int argc, char* argv[]) {
IDS::Utils::catchSignalsAndQuit({SIGQUIT, SIGINT, SIGTERM, SIGHUP});
// Create the app object
MyApp app{argc, argv};
// Log that the app runs now
qCInfo(lc) << lc.categoryName() << "is up and running.";
// Actually start the app. This line will not return until the app object terminates
return MyApp::exec();
}
| 26.129032 | 88 | 0.707407 | [
"object"
] |
a698c5db370c2aaa90fee05f83adfdaa890b83eb | 5,789 | cpp | C++ | src/app/finder/abstractfinder.cpp | mB-PiBox/communi-desktop | 0dc18431f1058effe8db1ae1b22d6869fd114e62 | [
"BSD-3-Clause"
] | 55 | 2015-01-22T22:30:28.000Z | 2021-12-27T00:11:54.000Z | src/app/finder/abstractfinder.cpp | mB-PiBox/communi-desktop | 0dc18431f1058effe8db1ae1b22d6869fd114e62 | [
"BSD-3-Clause"
] | 52 | 2015-01-03T19:06:51.000Z | 2021-12-04T21:35:13.000Z | src/app/finder/abstractfinder.cpp | mB-PiBox/communi-desktop | 0dc18431f1058effe8db1ae1b22d6869fd114e62 | [
"BSD-3-Clause"
] | 18 | 2015-04-24T12:15:33.000Z | 2021-10-31T14:01:02.000Z | /*
Copyright (C) 2008-2016 The Communi Project
You may use this file under the terms of BSD license as follows:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright 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 HOLDERS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "abstractfinder.h"
#include <QPropertyAnimation>
#include <QGraphicsOpacityEffect>
#include <QStylePainter>
#include <QStyleOption>
#include <QApplication>
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QEvent>
AbstractFinder::AbstractFinder(QWidget* parent) : QWidget(parent)
{
d.offset = -1;
d.error = false;
d.filter = false;
parent->installEventFilter(this);
setGraphicsEffect(new QGraphicsOpacityEffect(this));
d.lineEdit = new QLineEdit(this);
d.lineEdit->setAttribute(Qt::WA_MacShowFocusRect, false);
d.lineEdit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
d.prevButton = new QToolButton(this);
d.prevButton->setObjectName("prev");
d.prevButton->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Preferred);
connect(d.prevButton, SIGNAL(clicked()), this, SLOT(findPrevious()));
d.nextButton = new QToolButton(this);
d.nextButton->setObjectName("next");
d.nextButton->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Preferred);
connect(d.nextButton, SIGNAL(clicked()), this, SLOT(findNext()));
QHBoxLayout* layout = new QHBoxLayout(this);
layout->addWidget(d.lineEdit);
layout->addWidget(d.prevButton);
layout->addWidget(d.nextButton);
layout->setSpacing(0);
layout->setMargin(0);
connect(d.lineEdit, SIGNAL(returnPressed()), this, SIGNAL(returnPressed()));
connect(d.lineEdit, SIGNAL(textEdited(QString)), this, SLOT(textEdited()));
}
AbstractFinder::~AbstractFinder()
{
emit destroyed(this);
}
QString AbstractFinder::text() const
{
return d.lineEdit->text();
}
void AbstractFinder::setText(const QString& text)
{
d.lineEdit->setText(text);
}
int AbstractFinder::offset() const
{
return d.offset;
}
void AbstractFinder::setOffset(int offset)
{
d.offset = offset;
relocate();
}
bool AbstractFinder::hasError() const
{
return d.error;
}
void AbstractFinder::setError(bool error)
{
if (d.error != error) {
d.error = error;
// force restyle
setStyleSheet(QString());
d.lineEdit->setStyleSheet(QString());
d.nextButton->setEnabled(!error);
d.prevButton->setEnabled(!error);
}
}
QLineEdit *AbstractFinder::lineEdit() const
{
return d.lineEdit;
}
bool AbstractFinder::isFilter() const
{
return d.filter;
}
void AbstractFinder::setFilter(bool enabled)
{
if (d.filter != enabled) {
d.filter = enabled;
d.prevButton->setVisible(!enabled);
d.nextButton->setVisible(!enabled);
if (enabled) {
filter(d.lineEdit->text());
} else {
filter(QString());
find(d.lineEdit->text());
}
emit filterChanged(enabled);
}
}
bool AbstractFinder::eventFilter(QObject* object, QEvent* event)
{
Q_UNUSED(object);
if (event->type() == QEvent::Resize)
relocate();
return false;
}
void AbstractFinder::findNext()
{
find(d.lineEdit->text(), true, false, false);
}
void AbstractFinder::findPrevious()
{
find(d.lineEdit->text(), false, true, false);
}
void AbstractFinder::doFind()
{
setFixedHeight(d.lineEdit->sizeHint().height() + 1);
setOffset(-sizeHint().height());
relocate();
animateShow();
reFind();
}
void AbstractFinder::reFind()
{
d.lineEdit->setFocus(Qt::ShortcutFocusReason);
d.lineEdit->selectAll();
}
void AbstractFinder::animateShow()
{
QPropertyAnimation *animation = new QPropertyAnimation(this, "offset");
animation->setDuration(50);
animation->setEndValue(-1);
animation->start(QAbstractAnimation::DeleteWhenStopped);
setVisible(true);
}
void AbstractFinder::animateHide()
{
QPropertyAnimation *animation = new QPropertyAnimation(this, "offset");
animation->setDuration(50);
animation->setEndValue(-sizeHint().height());
animation->start(QAbstractAnimation::DeleteWhenStopped);
connect(animation, SIGNAL(destroyed()), this, SLOT(hide()));
connect(animation, SIGNAL(destroyed()), this, SLOT(deleteLater()));
}
void AbstractFinder::textEdited()
{
if (d.filter)
filter(d.lineEdit->text());
else
find(d.lineEdit->text());
}
| 28.800995 | 83 | 0.702021 | [
"object"
] |
a6a02573db00928f72cf0f1646970c34ce1450be | 1,107 | cpp | C++ | Offer/Offer-10-II-qing-wa-tiao-tai-jie-wen-ti-lcof.cpp | wandsX/LeetCodeExperience | 8502e6e8ce911045f45f0075bcf3ee751a4558c7 | [
"MIT"
] | null | null | null | Offer/Offer-10-II-qing-wa-tiao-tai-jie-wen-ti-lcof.cpp | wandsX/LeetCodeExperience | 8502e6e8ce911045f45f0075bcf3ee751a4558c7 | [
"MIT"
] | null | null | null | Offer/Offer-10-II-qing-wa-tiao-tai-jie-wen-ti-lcof.cpp | wandsX/LeetCodeExperience | 8502e6e8ce911045f45f0075bcf3ee751a4558c7 | [
"MIT"
] | null | null | null | //一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。
//
// 答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。
//
// 示例 1:
//
// 输入:n = 2
//输出:2
//
//
// 示例 2:
//
// 输入:n = 7
//输出:21
//
//
// 示例 3:
//
// 输入:n = 0
//输出:1
//
// 提示:
//
//
// 0 <= n <= 100
//
//
// 注意:本题与主站 70 题相同:https://leetcode-cn.com/problems/climbing-stairs/
//
//
// Related Topics 递归
// 👍 137 👎 0
#include <iostream>
#include <vector>
using namespace std;
//leetcode submit region begin(Prohibit modification and deletion)
class Solution
{
public:
int numWays(int n)
{
if (n == 0 || n == 1 )
{
return 1;
}
int a = 1;
int b = 1;
int sum;
for (int i = 2; i <= n; i++)
{
sum = (a + b) % 1000000007;
a = b;
b = sum;
}
return sum;
}
};
//leetcode submit region end(Prohibit modification and deletion)
int main()
{
Solution s;
vector<int> data{7, 1, 5, 3, 6, 4};
cout << "Hello LeetCode" << endl;
} | 15.814286 | 69 | 0.459801 | [
"vector"
] |
a6a297d717a880b611dc42d52b4cc929c8ddff00 | 1,463 | cpp | C++ | charges-on-sphere/mc/nemo.cpp | mlund/faunus-notebooks | 81ebaaf876f7cb91761364dd804cd3df7ce06306 | [
"MIT"
] | 2 | 2016-04-06T14:05:23.000Z | 2017-10-17T00:45:20.000Z | charges-on-sphere/mc/nemo.cpp | mlund/faunus-notebooks | 81ebaaf876f7cb91761364dd804cd3df7ce06306 | [
"MIT"
] | null | null | null | charges-on-sphere/mc/nemo.cpp | mlund/faunus-notebooks | 81ebaaf876f7cb91761364dd804cd3df7ce06306 | [
"MIT"
] | 5 | 2016-02-25T13:59:39.000Z | 2020-05-17T19:26:38.000Z | #include <faunus/faunus.h>
using namespace Faunus;
using namespace Faunus::Potential;
typedef Coulomb Tpairpot;
typedef Geometry::SphereSurface Tgeometry;
typedef Space<Tgeometry> Tspace;
int main() {
InputMap mcp("nemo.json");
MCLoop loop(mcp);
EnergyDrift sys;
Tspace spc(mcp);
auto pot = Energy::Nonbonded<Tspace,Tpairpot>(mcp);
Move::Propagator<Tspace> mv(mcp,pot,spc);
Analysis::RadialDistribution<> rdf(0.1);
//FormatXTC xtc(1000);
vector<double> energy;;
//spc.load("state");
sys.init( Energy::systemEnergy(spc,pot,spc.p) );
cout << atom.info() + spc.info() + pot.info();
while ( loop[0] ) { // Markov chain
while ( loop[1] ) {
sys += mv.move();
rdf.sample( spc, atom["Na"].id, atom["Na"].id );
//xtc.setbox( 10.0 );
//xtc.save( "traj.xtc", spc.p );
//energy.push_back(Energy::systemEnergy(spc,pot,spc.p));
}
sys.checkDrift(Energy::systemEnergy(spc,pot,spc.p));
cout << loop.timing();
}
FormatPQR::save("confout.pqr", spc.p);
rdf.save("rdf.dat");
spc.save("state");
// print information
cout << loop.info() + sys.info() + mv.info();
//string file = "energy.dat";
//std::ofstream f(file.c_str());
//if (f)
// for (unsigned int i = 0; i < energy.size(); i++)
// f << std::left << std::setw(10) << energy.at(i) << endl;
return 0;
}
| 25.224138 | 64 | 0.56391 | [
"geometry",
"vector"
] |
a6a4064032ba13949d49b758098b90bd34837a86 | 534 | cc | C++ | mersenne/mersenne_main.cc | ULL-ESIT-IB-2020-2021/ib-practica09-funciones-seguisergio1 | 4afcad21bdde4f17a90e400a016af75dbead49ab | [
"MIT"
] | null | null | null | mersenne/mersenne_main.cc | ULL-ESIT-IB-2020-2021/ib-practica09-funciones-seguisergio1 | 4afcad21bdde4f17a90e400a016af75dbead49ab | [
"MIT"
] | null | null | null | mersenne/mersenne_main.cc | ULL-ESIT-IB-2020-2021/ib-practica09-funciones-seguisergio1 | 4afcad21bdde4f17a90e400a016af75dbead49ab | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstring>
#include <vector>
#include <math.h>
#include "mersenne.h"
int main (int argc,char *argv[]){
usage (argc, argv);
int parameter = atoi(argv[1]);
int prime_number;
int current_number = 0;
std::vector<int>vector_with_prime_numbers;
NumbersOfVector (vector_with_prime_numbers, parameter, current_number, prime_number);
std::cout << "la suma de los " << parameter << " primeros numeros de Mersenne es: " << Mersenne(vector_with_prime_numbers, parameter) << std::endl;
return 0;
} | 29.666667 | 149 | 0.713483 | [
"vector"
] |
a6a4b381c861e369811f1b2d40499075ab752d81 | 65,587 | cpp | C++ | Src/FuncApprox/MarsBagg.cpp | lbianchi-lbl/psuade-lite | 09d7ca75aba8a9e31e1fb5c3e134af046fca3460 | [
"Apache-2.0"
] | 1 | 2021-03-10T23:25:30.000Z | 2021-03-10T23:25:30.000Z | Src/FuncApprox/MarsBagg.cpp | lbianchi-lbl/psuade-lite | 09d7ca75aba8a9e31e1fb5c3e134af046fca3460 | [
"Apache-2.0"
] | 3 | 2021-03-10T22:10:32.000Z | 2022-01-14T04:31:05.000Z | Src/FuncApprox/MarsBagg.cpp | lbianchi-lbl/psuade-lite | 09d7ca75aba8a9e31e1fb5c3e134af046fca3460 | [
"Apache-2.0"
] | 1 | 2021-02-24T22:59:02.000Z | 2021-02-24T22:59:02.000Z | // ************************************************************************
// Copyright (c) 2007 Lawrence Livermore National Security, LLC.
// Produced at the Lawrence Livermore National Laboratory.
// Written by the PSUADE team.
// All rights reserved.
//
// Please see the COPYRIGHT_and_LICENSE file for the copyright notice,
// disclaimer, contact information and the GNU Lesser General Public License.
//
// PSUADE is free software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License (as published by the Free Software
// Foundation) version 2.1 dated February 1999.
//
// PSUADE 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 terms and conditions of the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// ************************************************************************
// Functions for the class MarsBagg
// AUTHOR : CHARLES TONG
// DATE : 2008
// ************************************************************************
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "MarsBagg.h"
#include "sysdef.h"
#include "PsuadeUtil.h"
#include "Psuade.h"
#define PABS(x) ((x) > 0 ? (x) : (-(x)))
// ************************************************************************
// Constructor for object class MarsBagg
// ------------------------------------------------------------------------
MarsBagg::MarsBagg(int nInputs,int nSamples) : FuncApprox(nInputs,nSamples)
{
#ifdef HAVE_MARS
int ii, itmp;
char pString[500], *cString, *targv[3], winput1[100], winput2[100];
faID_ = PSUADE_RS_MARSB;
numMars_ = 100;
mode_ = 0;
usageIndex_ = 1;
maxBasis_ = 100;
if (maxBasis_ > nSamples) maxBasis_ = nSamples - 1;
if (nInputs >= 8) varPerBasis_ = 8;
else varPerBasis_ = nInputs;
if (psRSExpertMode_ != 1 && psConfig_ != NULL)
{
cString = psConfig_->getParameter("MARS_num");
if (cString != NULL)
{
sscanf(cString, "%s %s %d", winput1, winput2, &itmp);
if (itmp < 2)
{
printf("MarsBag INFO: numMars from config file not valid.\n");
printf(" numMars kept at %d.\n", numMars_);
}
else
{
numMars_ = itmp;
printf("MarsBag INFO: number of instantiations set to %d.\n",
numMars_);
}
}
cString = psConfig_->getParameter("MARS_num_bases");
if (cString != NULL)
{
sscanf(cString, "%s %s %d", winput1, winput2, &itmp);
if (itmp < 10 || itmp > nSamples)
{
printf("MarsBag INFO: nbasis from config file not valid.\n");
printf(" nbasis kept at %d.\n", maxBasis_);
}
else
{
maxBasis_ = itmp;
printf("MarsBag INFO: number of basis set to %d (config).\n",
maxBasis_);
}
}
cString = psConfig_->getParameter("MARS_interaction");
if (cString != NULL)
{
sscanf(cString, "%s %s %d", winput1, winput2, &itmp);
if (itmp > nInputs || itmp < 1)
{
printf("MarsBag INFO: interaction from config file not valid.\n");
printf(" interaction kept at %d.\n", varPerBasis_);
}
else
{
varPerBasis_ = itmp;
printf("MarsBag INFO: interaction set to %d (config).\n",varPerBasis_);
}
}
}
if (outputLevel_ > 1)
{
printAsterisks(PL_INFO, 0);
printf("* MarsBag Analysis\n");
printDashes(PL_INFO, 0);
printf("Default mode = mean (options: mean, median).\n");
printf("Number of instantiations = %d\n",numMars_);
printf("No. of basis functions = %d\n",maxBasis_);
printf("No. of variables per basis = %d\n",varPerBasis_);
printf("* Turn on rs_expert mode to select internal parameters.\n");
printf("* Set print level to 5 to print out ranking information.\n");
printEquals(PL_INFO, 0);
}
if (psRSExpertMode_ == 1 && psInteractive_ == 1)
{
sprintf(pString,"MARS with bagging: mean (0) or median (1) mode ? ");
mode_ = getInt(0, 1, pString);
sprintf(pString,
"How many instantiation of MARS (10-5000, default=100) ? ");
numMars_ = getInt(10, 5000, pString);
sprintf(pString,
"How many basis functions in MARS (< %d, default = %d) ? ",
nSamples, maxBasis_);
maxBasis_ = getInt(1, nSamples, pString);
sprintf(pString, "How many variables per basis (<= %d, default = %d) ? ",
nInputs, varPerBasis_);
varPerBasis_ = getInt(1, nInputs, pString);
if (psMasterMode_ == 1)
{
printf("You can control the probability of using more sample\n");
printf("points in any instantiation by setting a 'frequency' knob.\n");
printf("The default is 4, which gives 80-90 percent usage.\n");
printf("Set this number to a larger value to increase usage.\n");
printf("If you do not know what this knob does, enter 3.\n");
printf("To see the actual usage percentage, turn on printlevel 2.\n");
sprintf(pString,
"What value should be assigned to this knob? (2 - 8) ");
usageIndex_ = getInt(2, 8, pString);
}
}
strcpy(pString, "mars_params");
targv[0] = (char *) pString;
targv[1] = (char *) &maxBasis_;
targv[2] = (char *) &varPerBasis_;
itmp = psRSExpertMode_;
psRSExpertMode_ = 0;
marsObjs_ = new Mars*[numMars_];
PsuadeConfig *tmpConfig = psConfig_;
psConfig_ = NULL;
for (ii = 0; ii < numMars_; ii++)
{
marsObjs_[ii] = new Mars(nInputs_, nSamples_);
marsObjs_[ii]->setParams(3, targv);
}
psConfig_ = tmpConfig;
psRSExpertMode_ = itmp;
marsFms_ = NULL;
marsIms_ = NULL;
#else
printf("PSUADE ERROR : MARSBAGG not installed.\n");
exit(1);
#endif
}
// ************************************************************************
// destructor
// ------------------------------------------------------------------------
MarsBagg::~MarsBagg()
{
int ii;
if (marsObjs_ != NULL)
{
for (ii = 0; ii < numMars_; ii++) delete marsObjs_[ii];
delete [] marsObjs_;
}
if (marsFms_ != NULL)
{
for (ii = 0; ii < numMars_; ii++) delete marsFms_[ii];
delete [] marsFms_;
}
if (marsIms_ != NULL)
{
for (ii = 0; ii < numMars_; ii++) delete marsIms_[ii];
delete [] marsIms_;
}
}
// ************************************************************************
// Set bounds for object class FuncApprox
// ------------------------------------------------------------------------
int MarsBagg::setBounds( double *lower, double *upper )
{
for (int ii=0 ; ii<numMars_; ii++) marsObjs_[ii]->setBounds(lower,upper);
return 0;
}
// ************************************************************************
// load output weights
// ------------------------------------------------------------------------
int MarsBagg::loadWeights(int n, double *wgts)
{
for (int ii=0 ; ii<numMars_; ii++) marsObjs_[ii]->loadWeights(n, wgts);
return 0;
}
// ************************************************************************
// set number of points to generate in each dimension
// ------------------------------------------------------------------------
void MarsBagg::setNPtsPerDim(int npoints)
{
nPtsPerDim_ = npoints;
for (int ii=0 ; ii<numMars_; ii++) marsObjs_[ii]->setNPtsPerDim(npoints);
}
// ************************************************************************
// initialize
// ------------------------------------------------------------------------
int MarsBagg::initialize(double *XX, double *Y)
{
#ifdef HAVE_MARS
int ii, ss, jj, index, SAFlag, expertFlag;
FILE *fp;
psVector vecXB, vecYB;
psIVector ivecT, ivecCnts;
psMatrix matSAIndices;
vecXB.setLength(nInputs_ * nSamples_);
vecYB.setLength(nSamples_);
if (outputLevel_ >= 4)
{
matSAIndices.setFormat(2);
matSAIndices.setDim(numMars_, nInputs_);
ivecT.setLength(nInputs_);
}
SAFlag = 0;
ivecCnts.setLength(nSamples_);
expertFlag = psRSExpertMode_;
psRSExpertMode_ = 0;
for (ii = 0; ii < numMars_; ii++)
{
if (outputLevel_ >= 2)
printf("MarsBagg::initialize : creating Mars #%d (of %d)\n",
ii+1, numMars_);
if (dataSetX_.nrows() <= 0)
{
for (ss = 0; ss < nSamples_; ss++) ivecCnts[ss] = usageIndex_ * 2;
for (ss = 0; ss < nSamples_; ss++)
{
index = -1;
while (index == -1)
{
index = PSUADE_rand() % nSamples_;
if (ivecCnts[index] > 0 && (ivecCnts[index] % usageIndex_) == 0)
{
ivecCnts[index] = ivecCnts[index] - 1;
}
else if ((ivecCnts[index] > 0) &&
(ivecCnts[index] % usageIndex_) != 0)
{
ivecCnts[index] = ivecCnts[index] - 1;
index = -1;
}
else if (ivecCnts[index] <= 0) index = -1;
}
for (jj = 0; jj < nInputs_; jj++)
vecXB[ss*nInputs_+jj] = XX[index*nInputs_+jj];
vecYB[ss] = Y[index];
}
index = 0;
for (ss = 0; ss < nSamples_; ss++)
if (ivecCnts[ss] < usageIndex_*2) index++;
if (outputLevel_ >= 2)
printf(" Number of sample points used = %d (out of %d)\n",
index,nSamples_);
}
else
{
double **matX2D = dataSetX_.getMatrix2D();
double **matY2D = dataSetY_.getMatrix2D();
for (ss = 0; ss < nSamples_; ss++)
{
for (jj = 0; jj < nInputs_; jj++)
vecXB[ss*nInputs_+jj] = matX2D[ii][ss*nInputs_+jj];
vecYB[ss] = matY2D[ii][ss];
}
}
marsObjs_[ii]->setOutputLevel(0);
jj = 0;
for (ss = 0; ss < nSamples_; ss++)
if (vecYB[ss] >= PSUADE_UNDEFINED) jj++;
if (jj > 0)
{
printf("MarsBag ERROR: some of the sample outputs are undefined.\n");
exit(1);
}
marsObjs_[ii]->initialize(vecXB.getDVector(), vecYB.getDVector());
if (outputLevel_ >= 4)
{
double **matI2D = matSAIndices.getMatrix2D();
SAFlag += getImportance(nInputs_, matI2D[ii]);
}
fp = fopen("ps_print", "r");
if (fp != NULL)
{
printf("MarsBagg: set print level to 2\n");
outputLevel_ = 2;
fclose(fp);
}
if (psRSCodeGen_ == 1) readRSInterpolator(ii);
}
if (psRSCodeGen_ == 1) genRSInterpolator();
if (SAFlag == 0 && matSAIndices.nrows() > 0)
{
psVector vecMeans, vecStds;
vecMeans.setLength(nInputs_);
vecStds.setLength(nInputs_);
double **matI2D = matSAIndices.getMatrix2D();
for (jj = 0; jj < nInputs_; jj++)
{
vecMeans[jj] = 0.0;
vecStds[jj] = 0.0;
for (ii = 0; ii < numMars_; ii++) vecMeans[jj] += matI2D[ii][jj];
vecMeans[jj] /= (double) numMars_;
for (ii = 0; ii < numMars_; ii++)
vecStds[jj] += pow(matI2D[ii][jj] - vecMeans[jj], 2.0e0);
vecStds[jj] /= (double) numMars_;
vecStds[jj] = sqrt(vecStds[jj]);
}
if (psPlotTool_ == 1)
{
fp = fopen("scilabmarsbsa.sci", "w");
if (fp == NULL)
{
printf("MarsBag ERROR: cannot open scilab file.\n");
return 0;
}
fprintf(fp,"// This file contains MarsBag ranking measures\n");
fprintf(fp,"// and also their spreads based on bootstraping.\n");
fprintf(fp,"// To select the most important ones to display,\n");
fprintf(fp,"// set sortFlag = 1 and set nn to be the number\n");
fprintf(fp,"// of inputs to display.\n");
}
else
{
fp = fopen("matlabmarsbsa.m", "w");
if (fp == NULL)
{
printf("MarsBag ERROR: cannot open matlab file.\n");
return 0;
}
fprintf(fp,"%% This file contains MarsBag ranking measures\n");
fprintf(fp,"%% and also their spreads based on bootstraping.\n");
fprintf(fp,"%% To select the most important ones to display,\n");
fprintf(fp,"%% set sortFlag = 1 and set nn to be the number\n");
fprintf(fp,"%% of inputs to display.\n");
}
fwritePlotCLF(fp);
fprintf(fp, "nn = %d;\n", nInputs_);
fprintf(fp, "Means = [\n");
for (ii = 0; ii < nInputs_; ii++)
{
index = (int) (100 * vecMeans[ii]);
fprintf(fp, "%d\n", index);
}
fprintf(fp, "];\n");
fprintf(fp, "Stds = [\n");
for (ii = 0; ii < nInputs_; ii++)
{
index = (int) (100 * vecStds[ii]);
fprintf(fp, "%d\n", index);
}
fprintf(fp, "];\n");
fprintf(fp, "ymax = max(Means);\n");
fprintf(fp, "ymin = min(Means);\n");
fprintf(fp, "if (ymax == ymin)\n");
fprintf(fp, " ymax = ymax * 1.01;\n");
fprintf(fp, " ymin = ymin * 0.99;\n");
fprintf(fp, "end;\n");
fprintf(fp, "if (ymax == ymin)\n");
fprintf(fp, " ymax = ymax + 0.01;\n");
fprintf(fp, " ymin = ymin - 0.01;\n");
fprintf(fp,"end;\n");
fprintf(fp, "bar(Means,0.8);\n");
fprintf(fp, "for ii = 1:nn\n");
fprintf(fp, " if (ii == 1)\n");
if (psPlotTool_ == 1)
fprintf(fp, " set(gca(),\"auto_clear\",\"off\")\n");
else fprintf(fp, " hold on\n");
fprintf(fp, " end;\n");
fprintf(fp, " XX = [ii ii];\n");
fprintf(fp, " YY = [Means(ii)-Stds(ii) Means(ii)+Stds(ii)];\n");
fprintf(fp, " plot(XX,YY,'-ko','LineWidth',3.0,'MarkerEdgeColor',");
fprintf(fp, "'k','MarkerFaceColor','g','MarkerSize',12)\n");
fprintf(fp, "end;\n");
fwritePlotAxes(fp);
fwritePlotTitle(fp, "MARSB Rankings");
fwritePlotXLabel(fp, "Input parameters");
fwritePlotYLabel(fp, "MARSB ranks");
if (psPlotTool_ == 1)
{
fprintf(fp, "a=gca();\n");
fprintf(fp, "a.data_bounds=[0, ymin-0.01*(ymax-ymin); ");
fprintf(fp, "nn+1, ymax+0.01*(ymax-ymin)];\n");
}
else
{
fprintf(fp,"axis([0 nn+1 ymin-0.01*(ymax-ymin) ");
fprintf(fp,"ymax+0.01*(ymax-ymin)])\n");
}
fclose(fp);
for (ii = 0; ii < nInputs_; ii++) ivecT[ii] = ii;
sortDbleList2a(nInputs_, vecMeans.getDVector(), ivecT.getIVector());
printf("* ========== MARS screening rankings =========== *\n");
for (ii = nInputs_-1; ii >= 0; ii--)
{
index = (int) (100 * vecMeans[ii]);
printf("* Rank %3d : Input = %3d (measure = %3d, stdev = %9.3e)\n",
nInputs_-ii, ivecT[ii]+1, index, 100.0*vecStds[ii]);
}
printf("* ============================================== *\n");
if (psPlotTool_ == 1)
printf("MarsBag ranking is now in scilabmarsbsa.sci.\n");
else printf("MarsBag ranking is now in matlabmarsbsa.m.\n");
}
psRSExpertMode_ = expertFlag;
return 0;
#else
printf("PSUADE ERROR : MARS not installed.\n");
return -1;
#endif
}
// ************************************************************************
// Generate results for display
// ------------------------------------------------------------------------
int MarsBagg::genNDGridData(double *XIn,double *YIn,int *NOut,double **XOut,
double **YOut)
{
#ifdef HAVE_MARS
int totPts, ii, ss, jj, index, SAFlag, expertFlag;
double *XXt, *Yt, **YM, **SAIndices, *means, *stdevs;
FILE *fp;
psIVector ivecT, ivecCnts;
psVector vecXB, vecYB;
psMatrix matSAIndices;
vecXB.setLength(nInputs_ * nSamples_);
vecYB.setLength(nSamples_);
if (outputLevel_ >= 4)
{
matSAIndices.setFormat(2);
matSAIndices.setDim(numMars_, nInputs_);
ivecT.setLength(nInputs_);
}
SAFlag = 0;
if ((*NOut) == -999)
{
ivecCnts.setLength(nSamples_);
expertFlag = psRSExpertMode_;
psRSExpertMode_ = 0;
for (ii = 0; ii < numMars_; ii++)
{
if (outputLevel_ >= 2)
printf("MarsBagg::genNDGridData : creating Mars #%d (of %d)\n",
ii+1, numMars_);
if (dataSetX_.nrows() <= 0)
{
for (ss = 0; ss < nSamples_; ss++) ivecCnts[ss] = usageIndex_ * 2;
for (ss = 0; ss < nSamples_; ss++)
{
index = -1;
while (index == -1)
{
index = PSUADE_rand() % nSamples_;
if (ivecCnts[index] > 0 && (ivecCnts[index] % usageIndex_) == 0)
{
ivecCnts[index]--;
}
else if (ivecCnts[index] > 0 &&
(ivecCnts[index] % usageIndex_) != 0)
{
ivecCnts[index]--;
index = -1;
}
else if (ivecCnts[index] <= 0) index = -1;
}
for (jj = 0; jj < nInputs_; jj++)
vecXB[ss*nInputs_+jj] = XIn[index*nInputs_+jj];
vecYB[ss] = YIn[index];
}
index = 0;
for (ss = 0; ss < nSamples_; ss++)
if (ivecCnts[ss] < usageIndex_*2) index++;
if (outputLevel_ >= 2)
printf(" Number of sample points used = %d (out of %d)\n",
index,nSamples_);
}
else
{
double **matX2D = dataSetX_.getMatrix2D();
double **matY2D = dataSetY_.getMatrix2D();
for (ss = 0; ss < nSamples_; ss++)
{
for (jj = 0; jj < nInputs_; jj++)
vecXB[ss*nInputs_+jj] = matX2D[ii][ss*nInputs_+jj];
vecYB[ss] = matY2D[ii][ss];
}
}
marsObjs_[ii]->setOutputLevel(0);
marsObjs_[ii]->genNDGridData(vecXB.getDVector(),vecYB.getDVector(),
NOut, NULL, NULL);
if (outputLevel_ >= 4)
{
double **matS2D = matSAIndices.getMatrix2D();
SAFlag += getImportance(nInputs_, matS2D[ii]);
}
fp = fopen("ps_print", "r");
if (fp != NULL)
{
printf("MarsBagg: set print level to 2\n");
outputLevel_ = 2;
fclose(fp);
}
}
if (SAFlag == 0 && matSAIndices.nrows() > 0)
{
double **matS2D = matSAIndices.getMatrix2D();
psVector vecMeans, vecStds;
vecMeans.setLength(nInputs_);
vecStds.setLength(nInputs_);
for (jj = 0; jj < nInputs_; jj++)
{
vecMeans[jj] = stdevs[jj] = 0.0;
for (ii = 0; ii < numMars_; ii++) vecMeans[jj] += matS2D[ii][jj];
vecMeans[jj] /= (double) numMars_;
for (ii = 0; ii < numMars_; ii++)
vecStds[jj] += pow(matS2D[ii][jj] - vecMeans[jj], 2.0e0);
vecStds[jj] /= (double) numMars_;
vecStds[jj] = sqrt(stdevs[jj]);
}
if (psPlotTool_ == 1)
{
fp = fopen("scilabmarsbsa.sci", "w");
if (fp == NULL)
{
printf("MarsBag ERROR: cannot open scilab file.\n");
return 0;
}
fprintf(fp,"// This file contains MarsBag ranking measures\n");
fprintf(fp,"// and also their spreads based on bootstraping.\n");
fprintf(fp,"// To select the most important ones to display,\n");
fprintf(fp,"// set sortFlag = 1 and set nn to be the number\n");
fprintf(fp,"// of inputs to display.\n");
}
else
{
fp = fopen("matlabmarsbsa.m", "w");
if (fp == NULL)
{
printf("MarsBag ERROR: cannot open matlab file.\n");
return 0;
}
fprintf(fp,"%% This file contains MarsBag ranking measures\n");
fprintf(fp,"%% and also their spreads based on bootstraping.\n");
fprintf(fp,"%% To select the most important ones to display,\n");
fprintf(fp,"%% set sortFlag = 1 and set nn to be the number\n");
fprintf(fp,"%% of inputs to display.\n");
}
fwritePlotCLF(fp);
fprintf(fp, "nn = %d;\n", nInputs_);
fprintf(fp, "Means = [\n");
for (ii = 0; ii < nInputs_; ii++)
{
index = (int) (100 * vecMeans[ii]);
fprintf(fp, "%d\n", index);
}
fprintf(fp, "];\n");
fprintf(fp, "Stds = [\n");
for (ii = 0; ii < nInputs_; ii++)
{
index = (int) (100 * vecStds[ii]);
fprintf(fp, "%d\n", index);
}
fprintf(fp, "];\n");
fprintf(fp, "ymax = max(Means);\n");
fprintf(fp, "ymin = min(Means);\n");
fprintf(fp, "if (ymax == ymin)\n");
fprintf(fp, " ymax = ymax * 1.01;\n");
fprintf(fp, " ymin = ymin * 0.99;\n");
fprintf(fp, "end;\n");
fprintf(fp, "if (ymax == ymin)\n");
fprintf(fp, " ymax = ymax + 0.01;\n");
fprintf(fp, " ymin = ymin - 0.01;\n");
fprintf(fp,"end;\n");
fprintf(fp, "bar(Means,0.8);\n");
fprintf(fp, "for ii = 1:nn\n");
fprintf(fp, " if (ii == 1)\n");
if (psPlotTool_ == 1)
fprintf(fp, " set(gca(),\"auto_clear\",\"off\")\n");
else fprintf(fp, " hold on\n");
fprintf(fp, " end;\n");
fprintf(fp, " XX = [ii ii];\n");
fprintf(fp, " YY = [Means(ii)-Stds(ii) Means(ii)+Stds(ii)];\n");
fprintf(fp, " plot(XX,YY,'-ko','LineWidth',3.0,'MarkerEdgeColor',");
fprintf(fp, "'k','MarkerFaceColor','g','MarkerSize',12)\n");
fprintf(fp, "end;\n");
fwritePlotAxes(fp);
fwritePlotTitle(fp, "MARSB Rankings");
fwritePlotXLabel(fp, "Input parameters");
fwritePlotYLabel(fp, "MARSB ranks");
if (psPlotTool_ == 1)
{
fprintf(fp, "a=gca();\n");
fprintf(fp, "a.data_bounds=[0, ymin-0.01*(ymax-ymin); ");
fprintf(fp, "nn+1, ymax+0.01*(ymax-ymin)];\n");
}
else
{
fprintf(fp,"axis([0 nn+1 ymin-0.01*(ymax-ymin) ");
fprintf(fp,"ymax+0.01*(ymax-ymin)])\n");
}
fclose(fp);
for (ii = 0; ii < nInputs_; ii++) ivecT[ii] = ii;
sortDbleList2a(nInputs_,vecMeans.getDVector(),ivecT.getIVector());
printf("* ========== MARS screening rankings =========== *\n");
for (ii = nInputs_-1; ii >= 0; ii--)
{
index = (int) (100 * means[ii]);
printf("* Rank %3d : Input = %3d (measure = %3d, stdev = %9.3e)\n",
nInputs_-ii, ivecT[ii]+1, index, 100.0*vecStds[ii]);
}
printf("* ============================================== *\n");
if (psPlotTool_ == 1)
printf("MarsBag ranking is now in scilabmarsbsa.sci.\n");
else printf("MarsBag ranking is now in matlabmarsbsa.m.\n");
}
psRSExpertMode_ = expertFlag;
}
else
{
expertFlag = psRSExpertMode_;
psRSExpertMode_ = 0;
totPts = nPtsPerDim_;
for (ii = 1; ii < nInputs_; ii++) totPts = totPts * nPtsPerDim_;
(*XOut) = new double[nInputs_ * totPts];
(*YOut) = new double[totPts];
checkAllocate(*YOut,"YOut in MarsBagg::genNDGridData");
for (ii = 0; ii < totPts; ii++) (*YOut)[ii] = 0.0;
if (mode_ != 0)
{
YM = new double*[totPts];
checkAllocate(YM,"YM in MarsBagg::genNDGridData");
for (ss = 0; ss < totPts; ss++) YM[ss] = new double[numMars_];
checkAllocate(YM[totPts-1],"YM[nn] in MarsBagg::genNDGridData");
}
for (ii = 0; ii < numMars_; ii++)
{
for (ss = 0; ss < nSamples_; ss++)
{
index = PSUADE_rand() % nSamples_;
for (jj = 0; jj < nInputs_; jj++)
vecXB[ss*nInputs_+jj] = XIn[index*nInputs_+jj];
vecYB[ss] = YIn[index];
}
marsObjs_[ii]->genNDGridData(vecXB.getDVector(),vecYB.getDVector(),
NOut, &XXt, &Yt);
if (outputLevel_ >= 4)
{
double **matS2D = matSAIndices.getMatrix2D();
SAFlag += getImportance(nInputs_, matS2D[ii]);
}
if (mode_ != 0)
{
for (ss = 0; ss < totPts; ss++) YM[ss][ii] = Yt[ss];
}
else
{
for (ss = 0; ss < totPts; ss++) (*YOut)[ss] += Yt[ss];
}
if (ii == numMars_-1)
for (ss = 0; ss < totPts*nInputs_; ss++) (*XOut)[ss] = XXt[ss];
delete [] XXt;
delete [] Yt;
}
if (SAFlag == 0 && matSAIndices.nrows() > 0)
{
double **matS2D = matSAIndices.getMatrix2D();
psVector vecMeans, vecStds;
vecMeans.setLength(nInputs_);
vecStds.setLength(nInputs_);
for (jj = 0; jj < nInputs_; jj++)
{
vecMeans[jj] = vecStds[jj] = 0.0;
for (ii = 0; ii < numMars_; ii++) vecMeans[jj] += matS2D[ii][jj];
vecMeans[jj]/= (double) numMars_;
for (ii = 0; ii < numMars_; ii++)
vecStds[jj] += pow(matS2D[ii][jj] - vecMeans[jj], 2.0e0);
vecStds[jj] /= (double) numMars_;
vecStds[jj] = sqrt(vecStds[jj]);
}
for (ii = 0; ii < nInputs_; ii++) ivecT[ii] = ii;
sortDbleList2a(nInputs_, vecMeans.getDVector(), ivecT.getIVector());
printf("* ========= MARSBAG screening rankings ========= *\n");
for (ii = nInputs_-1; ii >= 0; ii--)
{
index = (int) (100 * vecMeans[ii]);
printf("* Rank %3d : Input = %3d (measure = %3d, stdev = %9.3e)\n",
nInputs_-ii, ivecT[ii]+1, index, 100.0*vecStds[ii]);
}
printf("* ============================================== *\n");
}
(*NOut) = totPts;
if (mode_ != 0)
{
for (ss = 0; ss < totPts; ss++)
{
sortDbleList(numMars_, YM[ss]);
(*YOut)[ss] = YM[ss][numMars_/2];
delete [] YM[ss];
}
delete [] YM;
}
else
{
for (ss = 0; ss < totPts; ss++) (*YOut)[ss] /= (double) numMars_;
}
psRSExpertMode_ = expertFlag;
}
#else
printf("PSUADE ERROR : MARS not installed.\n");
return -1;
#endif
return 0;
}
// ************************************************************************
// Generate results for display
// ------------------------------------------------------------------------
int MarsBagg::gen1DGridData(double *XIn, double *YIn, int ind1,
double *settings, int *NOut, double **XOut,
double **YOut)
{
#ifdef HAVE_MARS
int totPts, ii, ss, jj, index, expertFlag;
double *XXt, *YYt, **YM;
psVector vecXB, vecYB;
expertFlag = psRSExpertMode_;
psRSExpertMode_ = 0;
vecXB.setLength(nInputs_ * nSamples_);
vecYB.setLength(nSamples_);
totPts = nPtsPerDim_;
(*NOut) = totPts;
(*XOut) = new double[totPts];
(*YOut) = new double[totPts];
checkAllocate(*YOut, "YOut in MarsBagg::gen1DGridData");
for (ii = 0; ii < totPts; ii++) (*YOut)[ii] = 0.0;
if (mode_ != 0)
{
YM = new double*[totPts];
checkAllocate(YM, "YM in MarsBagg::gen1DGridData");
for (ss = 0; ss < totPts; ss++) YM[ss] = new double[numMars_];
checkAllocate(YM[totPts-1], "YM[nn] in MarsBagg::gen1DGridData");
}
for (ii = 0; ii < numMars_; ii++)
{
if (dataSetX_.nrows() <= 0)
{
for (ss = 0; ss < nSamples_; ss++)
{
index = PSUADE_rand() % nSamples_;
for (jj = 0; jj < nInputs_; jj++)
vecXB[ss*nInputs_+jj] = XIn[index*nInputs_+jj];
vecYB[ss] = YIn[index];
}
}
else
{
double **matX2D = dataSetX_.getMatrix2D();
double **matY2D = dataSetY_.getMatrix2D();
for (ss = 0; ss < nSamples_; ss++)
{
for (jj = 0; jj < nInputs_; jj++)
vecXB[ss*nInputs_+jj] = matX2D[ii][ss*nInputs_+jj];
vecYB[ss] = matY2D[ii][ss];
}
}
marsObjs_[ii]->gen1DGridData(vecXB.getDVector(),vecYB.getDVector(),
ind1,settings,NOut,&XXt,&YYt);
if (mode_ != 0)
{
for (ss = 0; ss < totPts; ss++) YM[ss][ii] = YYt[ss];
}
else
{
for (ss = 0; ss < totPts; ss++) (*YOut)[ss] += YYt[ss];
}
if (ii == numMars_-1)
for (ss = 0; ss < totPts; ss++) (*XOut)[ss] = XXt[ss];
delete [] XXt;
delete [] YYt;
}
if (mode_ != 0)
{
for (ss = 0; ss < totPts; ss++)
{
sortDbleList(numMars_, YM[ss]);
(*YOut)[ss] = YM[ss][numMars_/2];
delete [] YM[ss];
}
delete [] YM;
}
else
{
for (ss = 0; ss < totPts; ss++) (*YOut)[ss] /= (double) numMars_;
}
psRSExpertMode_ = expertFlag;
#else
printf("PSUADE ERROR : MARS not installed.\n");
return -1;
#endif
return 0;
}
// ************************************************************************
// Generate results for display
// ------------------------------------------------------------------------
int MarsBagg::gen2DGridData(double *XIn, double *YIn, int ind1, int ind2,
double *settings, int *NOut, double **XOut,
double **YOut)
{
#ifdef HAVE_MARS
int totPts, ii, ss, jj, index, expertFlag;
double *XXt, *YYt, **YM;
psVector vecXB, vecYB;
expertFlag = psRSExpertMode_;
psRSExpertMode_ = 0;
vecXB.setLength(nInputs_ * nSamples_);
vecYB.setLength(nSamples_);
totPts = nPtsPerDim_ * nPtsPerDim_;
(*NOut) = totPts;
(*XOut) = new double[2 * totPts];
(*YOut) = new double[totPts];
checkAllocate(*YOut, "YOut in MarsBagg::gen2DGridData");
for (ii = 0; ii < totPts; ii++) (*YOut)[ii] = 0.0;
if (mode_ != 0)
{
YM = new double*[totPts];
checkAllocate(YM, "YM in MarsBagg::gen2DGridData");
for (ss = 0; ss < totPts; ss++) YM[ss] = new double[numMars_];
checkAllocate(YM[totPts-1], "YM[nn] in MarsBagg::gen2DGridData");
}
for (ii = 0; ii < numMars_; ii++)
{
if (outputLevel_ >= 1)
printf("MarsBagg::gen2DGridData : creating Mars #%d (of %d)\n",
ii+1, numMars_);
if (dataSetX_.nrows() <= 0)
{
for (ss = 0; ss < nSamples_; ss++)
{
index = PSUADE_rand() % nSamples_;
for (jj = 0; jj < nInputs_; jj++)
vecXB[ss*nInputs_+jj] = XIn[index*nInputs_+jj];
vecYB[ss] = YIn[index];
}
}
else
{
double **matX2D = dataSetX_.getMatrix2D();
double **matY2D = dataSetY_.getMatrix2D();
for (ss = 0; ss < nSamples_; ss++)
{
for (jj = 0; jj < nInputs_; jj++)
vecXB[ss*nInputs_+jj] = matX2D[ii][ss*nInputs_+jj];
vecYB[ss] = matY2D[ii][ss];
}
}
marsObjs_[ii]->gen2DGridData(vecXB.getDVector(),vecYB.getDVector(),
ind1,ind2,settings,NOut,&XXt,&YYt);
if (mode_ != 0)
{
for (ss = 0; ss < totPts; ss++) YM[ss][ii] = YYt[ss];
}
else
{
for (ss = 0; ss < totPts; ss++) (*YOut)[ss] += YYt[ss];
}
if (ii == numMars_-1)
for (ss = 0; ss < 2*totPts; ss++) (*XOut)[ss] = XXt[ss];
delete [] XXt;
delete [] YYt;
}
if (mode_ != 0)
{
for (ss = 0; ss < totPts; ss++)
{
sortDbleList(numMars_, YM[ss]);
(*YOut)[ss] = YM[ss][numMars_/2];
delete [] YM[ss];
}
delete [] YM;
}
else
{
for (ss = 0; ss < totPts; ss++) (*YOut)[ss] /= (double) numMars_;
}
psRSExpertMode_ = expertFlag;
#else
printf("PSUADE ERROR : MARS not installed.\n");
return -1;
#endif
return 0;
}
// ************************************************************************
// Generate 3D results for display
// ------------------------------------------------------------------------
int MarsBagg::gen3DGridData(double *XIn, double *YIn, int ind1, int ind2,
int ind3, double *settings, int *NOut,
double **XOut, double **YOut)
{
#ifdef HAVE_MARS
int totPts, ii, ss, jj, index, expertFlag;
double *XXt, *YYt, **YM;
psVector vecXB, vecYB;
expertFlag = psRSExpertMode_;
psRSExpertMode_ = 0;
vecXB.setLength(nInputs_ * nSamples_);
vecYB.setLength(nSamples_);
totPts = nPtsPerDim_ * nPtsPerDim_ * nPtsPerDim_;
(*NOut) = totPts;
(*XOut) = new double[3 * totPts];
(*YOut) = new double[totPts];
checkAllocate(*YOut, "YOut in MarsBagg::gen3DGridData");
for (ii = 0; ii < totPts; ii++) (*YOut)[ii] = 0.0;
if (mode_ != 0)
{
YM = new double*[totPts];
checkAllocate(YM, "YM in MarsBagg::gen3DGridData");
for (ss = 0; ss < totPts; ss++) YM[ss] = new double[numMars_];
checkAllocate(YM[totPts-1], "YM[nn] in MarsBagg::gen3DGridData");
}
for (ii = 0; ii < numMars_; ii++)
{
if (dataSetX_.nrows() <= 0)
{
for (ss = 0; ss < nSamples_; ss++)
{
index = PSUADE_rand() % nSamples_;
for (jj = 0; jj < nInputs_; jj++)
vecXB[ss*nInputs_+jj] = XIn[index*nInputs_+jj];
vecYB[ss] = YIn[index];
}
}
else
{
double **matX2D = dataSetX_.getMatrix2D();
double **matY2D = dataSetY_.getMatrix2D();
for (ss = 0; ss < nSamples_; ss++)
{
for (jj = 0; jj < nInputs_; jj++)
vecXB[ss*nInputs_+jj] = matX2D[ii][ss*nInputs_+jj];
vecYB[ss] = matY2D[ii][ss];
}
}
marsObjs_[ii]->gen3DGridData(vecXB.getDVector(),vecYB.getDVector(),
ind1,ind2,ind3,settings,NOut,&XXt,&YYt);
if (mode_ != 0)
{
for (ss = 0; ss < totPts; ss++) YM[ss][ii] = YYt[ss];
}
else
{
for (ss = 0; ss < totPts; ss++) (*YOut)[ss] += YYt[ss];
}
if (ii == numMars_-1)
for (ss = 0; ss < 3*totPts; ss++) (*XOut)[ss] = XXt[ss];
delete [] XXt;
delete [] YYt;
}
if (mode_ != 0)
{
for (ss = 0; ss < totPts; ss++)
{
sortDbleList(numMars_, YM[ss]);
(*YOut)[ss] = YM[ss][numMars_/2];
delete [] YM[ss];
}
delete [] YM;
}
else
{
for (ss = 0; ss < totPts; ss++) (*YOut)[ss] /= (double) numMars_;
}
psRSExpertMode_ = expertFlag;
#else
printf("PSUADE ERROR : MARS not installed.\n");
return -1;
#endif
return 0;
}
// ************************************************************************
// Generate 4D results for display
// ------------------------------------------------------------------------
int MarsBagg::gen4DGridData(double *XIn, double *YIn, int ind1, int ind2,
int ind3, int ind4, double *settings,
int *NOut, double **XOut, double **YOut)
{
#ifdef HAVE_MARS
int totPts, ii, ss, jj, index, expertFlag;
double *XXt, *YYt, **YM;
psVector vecXB, vecYB;
expertFlag = psRSExpertMode_;
psRSExpertMode_ = 0;
vecXB.setLength(nInputs_ * nSamples_);
vecYB.setLength(nSamples_);
totPts = nPtsPerDim_ * nPtsPerDim_ * nPtsPerDim_ * nPtsPerDim_;
(*NOut) = totPts;
(*XOut) = new double[4 * totPts];
(*YOut) = new double[totPts];
checkAllocate(*YOut, "YOut in MarsBagg::gen4DGridData");
for (ii = 0; ii < totPts; ii++) (*YOut)[ii] = 0.0;
if (mode_ != 0)
{
YM = new double*[totPts];
checkAllocate(YM, "YM in MarsBagg::gen4DGridData");
for (ss = 0; ss < totPts; ss++) YM[ss] = new double[numMars_];
checkAllocate(YM[totPts-1], "YM[nn] in MarsBagg::gen4DGridData");
}
for (ii = 0; ii < numMars_; ii++)
{
if (dataSetX_.nrows() <= 0)
{
for (ss = 0; ss < nSamples_; ss++)
{
index = PSUADE_rand() % nSamples_;
for (jj = 0; jj < nInputs_; jj++)
vecXB[ss*nInputs_+jj] = XIn[index*nInputs_+jj];
vecYB[ss] = YIn[index];
}
}
else
{
double **matX2D = dataSetX_.getMatrix2D();
double **matY2D = dataSetY_.getMatrix2D();
for (ss = 0; ss < nSamples_; ss++)
{
for (jj = 0; jj < nInputs_; jj++)
vecXB[ss*nInputs_+jj] = matX2D[ii][ss*nInputs_+jj];
vecYB[ss] = matY2D[ii][ss];
}
}
marsObjs_[ii]->gen4DGridData(vecXB.getDVector(), vecYB.getDVector(),
ind1, ind2, ind3, ind4, settings, NOut, &XXt, &YYt);
if (mode_ != 0)
{
for (ss = 0; ss < totPts; ss++) YM[ss][ii] = YYt[ss];
}
else
{
for (ss = 0; ss < totPts; ss++) (*YOut)[ss] += YYt[ss];
}
if (ii == numMars_-1)
for (ss = 0; ss < 4*totPts; ss++) (*XOut)[ss] = XXt[ss];
delete [] XXt;
delete [] YYt;
}
if (mode_ != 0)
{
for (ss = 0; ss < totPts; ss++)
{
sortDbleList(numMars_, YM[ss]);
(*YOut)[ss] = YM[ss][numMars_/2];
delete [] YM[ss];
}
delete [] YM;
}
else
{
for (ss = 0; ss < totPts; ss++) (*YOut)[ss] /= (double) numMars_;
}
psRSExpertMode_ = expertFlag;
#else
printf("PSUADE ERROR : MARS not installed.\n");
return -1;
#endif
return 0;
}
// ************************************************************************
// Evaluate a given point
// ------------------------------------------------------------------------
double MarsBagg::evaluatePoint(double *X)
{
double Y=0.0;
#ifdef HAVE_MARS
int ii;
double Yt;
psVector vecYM;
if (mode_ != 0) vecYM.setLength(numMars_);
for (ii = 0; ii < numMars_; ii++)
{
Yt = marsObjs_[ii]->evaluatePoint(X);
if (mode_ != 0) vecYM[ii] = Yt;
else Y += Yt;
}
if (mode_ != 0)
{
sortDbleList(numMars_, vecYM.getDVector());
Y = vecYM[numMars_/2];
}
else Y /= (double) numMars_;
#else
printf("PSUADE ERROR : MARS not installed.\n");
#endif
return Y;
}
// ************************************************************************
// Evaluate a number of points
// ------------------------------------------------------------------------
double MarsBagg::evaluatePoint(int npts, double *X, double *Y)
{
#ifdef HAVE_MARS
int in, ii;
double YY, Yt;
psVector vecYM;
if (mode_ != 0) vecYM.setLength(numMars_);
for (in = 0; in < npts; in++)
{
YY = 0.0;
for (ii = 0; ii < numMars_; ii++)
{
Yt = marsObjs_[ii]->evaluatePoint(&(X[in*nInputs_]));
if (mode_ != 0) vecYM[ii] = Yt;
else YY += Yt;
}
if (mode_ != 0)
{
sortDbleList(numMars_, vecYM.getDVector());
Y[in] = vecYM[numMars_/2];
}
else Y[in] = YY / (double) numMars_;
}
#else
printf("PSUADE ERROR : MARS not installed.\n");
#endif
return 0.0;
}
// ************************************************************************
// Evaluate a given point with standard deviation
// ------------------------------------------------------------------------
double MarsBagg::evaluatePointFuzzy(double *X, double &std)
{
double Ymean=0.0;
#ifdef HAVE_MARS
int ii;
psVector vecYY;
vecYY.setLength(numMars_);
for (ii = 0; ii < numMars_; ii++)
{
vecYY[ii] = marsObjs_[ii]->evaluatePoint(X);
Ymean += vecYY[ii];
}
Ymean /= (double) numMars_;
std = 0.0;
for (ii = 0; ii < numMars_; ii++)
std += (vecYY[ii] - Ymean) * (vecYY[ii] - Ymean);
std = sqrt(std / (double) numMars_);
#else
printf("PSUADE ERROR : MARS not installed.\n");
#endif
return Ymean;
}
// ************************************************************************
// Evaluate a number of points with standard deviations
// ------------------------------------------------------------------------
double MarsBagg::evaluatePointFuzzy(int npts, double *X, double *Y,
double *Ystd)
{
#ifdef HAVE_MARS
int in, ii;
psVector vecYY;
vecYY.setLength(numMars_);
for (in = 0; in < npts; in++)
{
for (ii = 0; ii < numMars_; ii++)
vecYY[ii] = marsObjs_[ii]->evaluatePoint(&(X[in*nInputs_]));
Y[in] = 0.0;
for (ii = 0; ii < numMars_; ii++) Y[in] += vecYY[ii];
Y[in] /= (double) numMars_;
Ystd[in] = 0.0;
for (ii = 0; ii < numMars_; ii++)
Ystd[in] += (vecYY[ii] - Y[in]) * (vecYY[ii] - Y[in]);
Ystd[in] = sqrt(Ystd[in] / (double) numMars_);
}
#else
printf("PSUADE ERROR : MARS not installed.\n");
#endif
return 0.0;
}
// ************************************************************************
// get the importance indicators
// ------------------------------------------------------------------------
int MarsBagg::getImportance(int nInputs, double *indicators)
{
int lineLeng=500, ii, jj, nCount;
double dmax;
char line[500], word1[500], word2[500], word3[500];
FILE *fp;
fp = fopen(".psuade_mars", "r");
if (fp == NULL) return -1;
else
{
nCount = 0;
strcpy(word1, "none");
while ((fgets(line, lineLeng, fp) != NULL) && (feof(fp) == 0))
{
sscanf(line,"%s %s %s", word1, word2, word3);
if (!strcmp(word1,"relative") && !strcmp(word2,"variable") &&
!strcmp(word3,"importance:"))
{
fgets(line, lineLeng, fp);
fgets(line, lineLeng, fp);
if (feof(fp) == 0)
{
for (ii = 0; ii < nInputs_; ii+=6)
{
for (jj = 0; jj < 6; jj++)
{
if (ii+jj < nInputs_)
{
fscanf(fp,"%lg", &(indicators[ii+jj]));
nCount++;
}
}
fgets(line, lineLeng, fp);
fgets(line, lineLeng, fp);
fgets(line, lineLeng, fp);
}
}
}
}
if (nCount != nInputs_)
{
fclose(fp);
return -1;
}
dmax = indicators[0];
for (ii = 1; ii < nInputs_; ii++)
if (indicators[ii] > dmax) dmax = indicators[ii];
for (ii = 0; ii < nInputs_; ii++) indicators[ii] /= dmax;
fclose(fp);
}
return 0;
}
// ************************************************************************
// set parameters
// ------------------------------------------------------------------------
double MarsBagg::setParams(int targc, char **targv)
{
int ii, itmp, leng;
double *Xdata, *Ydata;
char cString[500], *argv[3];
if (targc == 1 && !strcmp(targv[0], "median"))
{
mode_ = 1;
}
else if (targc == 2 && !strcmp(targv[0], "num_mars"))
{
if (marsObjs_ != NULL)
{
for (ii = 0; ii < numMars_; ii++) delete marsObjs_[ii];
delete [] marsObjs_;
}
numMars_ = *(int *) targv[1];
if (numMars_ < 2) numMars_ = 2;
printf("MARS with bagging: no. of MARS set to = %d.\n", numMars_);
strcpy(cString, "mars_params");
argv[0] = (char *) cString;
argv[1] = (char *) &maxBasis_;
argv[2] = (char *) &varPerBasis_;
itmp = psRSExpertMode_;
psRSExpertMode_ = 0;
marsObjs_ = new Mars*[numMars_];
for (ii = 0; ii < numMars_; ii++)
{
marsObjs_[ii] = new Mars(nInputs_, nSamples_);
marsObjs_[ii]->setParams(3, argv);
}
psRSExpertMode_ = itmp;
}
else if (targc == 5 && !strcmp(targv[0], "mars_sample"))
{
itmp = *(int *) targv[1];
if (itmp < 0 || itmp >= numMars_)
{
printf("MarsBag ERROR: in loading sample - invalid index.\n");
exit(1);
}
leng = *(int *) targv[2];
if (leng != nSamples_)
{
printf("MarsBag ERROR: in loading sample - nSamples mismatch.\n");
exit(1);
}
Xdata = (double *) targv[3];
Ydata = (double *) targv[4];
dataSetX_.setFormat(2);
dataSetX_.setDim(numMars_, leng*nInputs_);
for (ii = 0; ii < leng*nInputs_; ii++)
dataSetX_.setEntry(itmp, ii, Xdata[ii]);
dataSetY_.setFormat(2);
dataSetY_.setDim(numMars_, leng);
for (ii = 0; ii < leng; ii++)
dataSetY_.setEntry(itmp, ii, Ydata[ii]);
}
else if (targc == 3 && !strcmp(targv[0], "mars_params"))
{
maxBasis_ = *(int *) targv[1];
varPerBasis_ = *(int *) targv[2];
printf("MARS with bagging: numBasis set to = %d.\n", maxBasis_);
printf("MARS with bagging: varPerBasis set to = %d.\n", varPerBasis_);
}
else
{
printf("MarsBagg setParams ERROR: invalid command %s.\n", targv[0]);
}
return 0.0;
}
// ************************************************************************
// read mars information
// ------------------------------------------------------------------------
int MarsBagg::readRSInterpolator(int index)
{
int ii, jj, idata, count;
double ddata;
char line[1001], word[1001];
FILE *fp;
fp = fopen("psuade_rs.info", "r");
if (fp == NULL || index >= numMars_ || index < 0) return 0;
if (index == 0)
{
if (marsFms_ != NULL)
{
for (ii = 0; ii < numMars_; ii++)
{
if (marsFms_[ii] != NULL) delete marsFms_[ii];
if (marsIms_[ii] != NULL) delete marsIms_[ii];
}
delete [] marsFms_;
delete [] marsIms_;
}
marsFms_ = new psVector*[numMars_];
marsIms_ = new psIVector*[numMars_];
marsNfms_.setLength(numMars_);
marsNims_.setLength(numMars_);
marsXMeans_.setFormat(2);
marsXMeans_.setDim(numMars_, nInputs_);
marsXStds_.setFormat(2);
marsXStds_.setDim(numMars_, nInputs_);
for (ii = 0; ii < numMars_; ii++)
{
marsNfms_[ii] = marsNims_[ii] = 0;
marsFms_[ii] = NULL;
marsIms_[ii] = NULL;
}
}
while (1)
{
fgets(line, 500, fp);
sscanf(line, "%s",word);
if (!strcmp(word, "FM")) break;
}
sscanf(line, "%s %d",word,&count);
fgets(line, 500, fp);
fgets(line, 500, fp);
fgets(line, 500, fp);
fgets(line, 500, fp);
if (count > 0)
{
marsNfms_[index] = count;
marsFms_[index] = new psVector();
marsFms_[index]->setLength(count);
for (ii = 0; ii < count; ii++)
{
fgets(line, 500, fp);
sscanf(line, "%lg", &ddata);
marsFms_[index]->setEntry(ii, ddata);
}
}
while (1)
{
fgets(line, 500, fp);
sscanf(line, "%s",word);
if (!strcmp(word, "IM")) break;
}
sscanf(line, "%s %d",word,&count);
fgets(line, 500, fp);
fgets(line, 500, fp);
fgets(line, 500, fp);
fgets(line, 500, fp);
if (count > 0)
{
marsNims_[index] = count;
marsIms_[index] = new psIVector();
marsIms_[index]->setLength(count);
for (ii = 0; ii < count; ii++)
{
fgets(line, 500, fp);
sscanf(line, "%d", &idata);
marsIms_[index]->setEntry(ii,idata);
}
}
while (1)
{
fgets(line, 500, fp);
sscanf(line, "%s",word);
if (!strcmp(word, "XM")) break;
}
fgets(line, 500, fp);
fgets(line, 500, fp);
fgets(line, 500, fp);
fgets(line, 500, fp);
for (ii = 0; ii < nInputs_; ii++)
{
fgets(line, 500, fp);
sscanf(line, "%lg", &ddata);
marsXMeans_.setEntry(index, ii, ddata);
}
while (1)
{
fgets(line, 500, fp);
sscanf(line, "%s",word);
if (!strcmp(word, "XS")) break;
}
fgets(line, 500, fp);
fgets(line, 500, fp);
fgets(line, 500, fp);
fgets(line, 500, fp);
for (ii = 0; ii < nInputs_; ii++)
{
fgets(line, 500, fp);
sscanf(line, "%lg", &ddata);
marsXStds_.setEntry(index, ii, ddata);
}
fclose(fp);
return 0;
}
// ************************************************************************
// generate marsbag information
// ------------------------------------------------------------------------
int MarsBagg::genRSInterpolator()
{
int mm, ii, countFm, countIm, idata;
double ddata;
FILE *fp;
fp = fopen("psuade_rs.info", "w");
if (fp == NULL)
{
printf("ERROR: Cannot open file psuade_rs.info.\n");
return 0;
}
fprintf(fp,"/* This file contains information to re-construct MARSBag\n");
fprintf(fp," response surface offline. Follow the steps below:\n");
fprintf(fp," 1. Rename this file to, say, main.c\n");
fprintf(fp," 2. Compile main.c (cc -o main main.c -lm) and run \n");
fprintf(fp," (optionally, to output also the std. dev., uncomment\n");
fprintf(fp," the corresponding lines below and compile with lapack.)\n");
fprintf(fp," 3. Run: main input output (input file has number of \n");
fprintf(fp," inputs followed by the input values. Upon termination,\n");
fprintf(fp," the result will be stored in 'output' */\n");
fprintf(fp,"/* *************************************/\n");
fprintf(fp,"/* MARSBag interpolator from PSUADE. */\n");
fprintf(fp,"/* ====================================*/\n");
fprintf(fp,"#include <math.h>\n");
fprintf(fp,"#include <stdlib.h>\n");
fprintf(fp,"#include <stdio.h>\n");
fprintf(fp,"int interpolate(int,double*,double*,double*);\n");
fprintf(fp,"main(int argc, char **argv) {\n");
fprintf(fp," int i, iOne=1, nInps;\n");
fprintf(fp," double X[%d], Y, S;\n",nInputs_);
fprintf(fp," FILE *fIn=NULL, *fOut=NULL;\n");
fprintf(fp," if (argc != 3) {\n");
fprintf(fp," printf(\"ERROR: not enough argument.\\n\");\n");
fprintf(fp," exit(1);\n");
fprintf(fp," }\n");
fprintf(fp," fIn = fopen(argv[1], \"r\");\n");
fprintf(fp," if (fIn == NULL) {\n");
fprintf(fp," printf(\"ERROR: cannot open input file.\\n\");\n");
fprintf(fp," exit(1);\n");
fprintf(fp," }\n");
fprintf(fp," fscanf(fIn, \"%%d\", &nInps);\n");
fprintf(fp," if (nInps != %d) {\n", nInputs_);
fprintf(fp," printf(\"ERROR - wrong nInputs.\\n\");\n");
fprintf(fp," exit(1);\n");
fprintf(fp," }\n");
fprintf(fp," for (i=0; i<%d; i++) fscanf(fIn, \"%%lg\", &X[i]);\n",
nInputs_);
fprintf(fp," fclose(fIn);\n");
fprintf(fp," interpolate(iOne,X,&Y,&S);\n");
fprintf(fp," printf(\"Y = %%e\\n\", Y);\n");
fprintf(fp," fOut = fopen(argv[2], \"w\");\n");
fprintf(fp," if (fOut == NULL) {\n");
fprintf(fp," printf(\"ERROR: cannot open output file.\\n\");\n");
fprintf(fp," exit(1);\n");
fprintf(fp," }\n");
fprintf(fp," fprintf(fOut,\" %%e\\n\", Y);\n");
fprintf(fp," fclose(fOut);\n");
fprintf(fp,"}\n\n");
fprintf(fp,"/* *************************************/\n");
fprintf(fp,"/* **** MARS interpolation function ****/\n");
fprintf(fp,"/* X[0], X[1], .. X[m-1] - first point\n");
fprintf(fp," * X[m], X[m+1], .. X[2*m-1] - second point\n");
fprintf(fp," * ... */\n");
fprintf(fp,"/* ====================================*/\n");
countFm = 0;
for (mm = 0; mm < numMars_; mm++)
countFm = (marsNfms_[mm] > countFm) ? marsNfms_[mm] : countFm;
countIm = 0;
for (mm = 0; mm < numMars_; mm++)
countIm = (marsNims_[mm] > countIm) ? marsNims_[mm] : countIm;
fprintf(fp,"int getCoefs(int, double *, int *,double *, double *);\n");
fprintf(fp,"int icat(double, int, double *);\n");
fprintf(fp,"int interpolate(int npts,double *X,double *Y,double *S){\n");
fprintf(fp," int k, nk, ss, nn, ip, ind, nmars=%d, tt, *im;\n",
numMars_);
fprintf(fp," int nInps=%d;\n", nInputs_);
fprintf(fp," double *YY, Yt, az, *tb, *cm, phi, t, u, v, *XX, *fm;\n");
fprintf(fp," double mean, std, *xm, *xs;\n");
fprintf(fp," XX = (double *) malloc(nInps*sizeof(double));\n");
fprintf(fp," YY = (double *) malloc(nmars*sizeof(double));\n");
fprintf(fp," fm = (double *) malloc(sizeof(double)* %d);\n",countFm);
fprintf(fp," im = (int *) malloc(sizeof(int)* %d);\n",countIm);
fprintf(fp," xm = (double *) malloc(sizeof(double)* %d);\n",nInputs_);
fprintf(fp," xs = (double *) malloc(sizeof(double)* %d);\n",nInputs_);
fprintf(fp," for (ss = 0; ss < npts; ss++) {\n");
fprintf(fp," Y[ss] = 0.0;\n");
fprintf(fp," for (tt = 0; tt < nmars; tt++) {\n");
fprintf(fp," getCoefs(tt, fm, im, xm, xs);\n");
fprintf(fp," for (nn = 0; nn < nInps; nn++)\n");
fprintf(fp," XX[nn]=(X[nn+nInps*ss]-xm[nn])/xs[nn];\n");
fprintf(fp," nk = im[4];\n");
fprintf(fp," ind = im[10] - 1; az = fm[ind];\n");
fprintf(fp," ind = im[11] - 1; tb = &fm[ind];\n");
fprintf(fp," ind = im[14] - 1; cm = &fm[ind];\n");
fprintf(fp," Yt = az;\n");
fprintf(fp," for (nn = 0; nn < nk; nn++) {\n");
fprintf(fp," if (tb[nn*5] != 0.0) {\n");
fprintf(fp," phi = 1.0;\n");
fprintf(fp," ip = nn;\n");
fprintf(fp," while (ip > -1) {\n");
fprintf(fp," t = tb[ip*5+1];\n");
fprintf(fp," v = t;\n");
fprintf(fp," if (v < 0) v = - v;\n");
fprintf(fp," ind = floor(v+0.1) - 1;\n");
fprintf(fp," if (cm[2*ind] <= 0.0) {\n");
fprintf(fp," v = 1.0;\n");
fprintf(fp," if (t < 0.0) v = -1.0;\n");
fprintf(fp," u = v * (XX[ind]-tb[ip*5+2]); \n");
fprintf(fp," if (u < 0.0) u = 0.0;\n");
fprintf(fp," }\n");
fprintf(fp," else {\n");
fprintf(fp," k = icat(XX[ind], ind, cm);\n");
fprintf(fp," if (k != 0) {\n");
fprintf(fp," ind = floor(tb[ip*5+2]+0.1) - 1;\n");
fprintf(fp," u = cm[k+ind];\n");
fprintf(fp," }\n");
fprintf(fp," else u = 0.0;\n");
fprintf(fp," if (t < 0.0) {\n");
fprintf(fp," if (u == 0.0) u = 1.0;\n");
fprintf(fp," else u = 0.0;\n");
fprintf(fp," }\n");
fprintf(fp," } \n");
fprintf(fp," if (u == 0.0) {\n");
fprintf(fp," phi = 0.0;\n");
fprintf(fp," break;\n");
fprintf(fp," }\n");
fprintf(fp," else {\n");
fprintf(fp," phi *= u;\n");
fprintf(fp," ip = floor(tb[ip*5+3] + 0.1) - 1;\n");
fprintf(fp," }\n");
fprintf(fp," }\n");
fprintf(fp," Yt += tb[nn*5] * phi;\n");
fprintf(fp," }\n");
fprintf(fp," }\n");
fprintf(fp," YY[tt] = Yt;\n");
fprintf(fp," }\n");
fprintf(fp," mean = 0.0;\n");
fprintf(fp," for (tt = 0; tt < nmars; tt++) mean += YY[tt];\n");
fprintf(fp," mean /= nmars;\n");
fprintf(fp," std = 0.0;\n");
fprintf(fp," for (tt=0; tt<nmars; tt++) std += pow(YY[tt]-mean,2.0);\n");
fprintf(fp," std = sqrt(std/(nmars-1));\n");
fprintf(fp," Y[ss] = mean;\n");
fprintf(fp," S[ss] = std;\n");
fprintf(fp," }\n");
fprintf(fp," free(XX);\n");
fprintf(fp," free(YY);\n");
fprintf(fp," free(fm);\n");
fprintf(fp," free(im);\n");
fprintf(fp," free(xm);\n");
fprintf(fp," free(xs);\n");
fprintf(fp," return 0;\n");
fprintf(fp,"}\n");
fprintf(fp,"/* ====================================*/\n");
fprintf(fp,"int icat(double X, int input, double *cm) {\n");
fprintf(fp," int j0, j1, j2, k, rdata;\n");
fprintf(fp," j0 = floor(cm[2*input] + 0.1);\n");
fprintf(fp," j1 = j0; j2 = floor(cm[2*input+1] + 0.1);\n");
fprintf(fp," while (j2 != (j1+1)) {\n");
fprintf(fp," k = floor(0.5*(j1+j2)) - 1;\n");
fprintf(fp," if (cm[k] == X) {\n");
fprintf(fp," rdata = k - j0; break;\n");
fprintf(fp," }\n");
fprintf(fp," else if (cm[k] < X) j1 = k;\n");
fprintf(fp," else j2 = k;\n");
fprintf(fp," if (X == cm[j1-1]) rdata = j2 - j0;\n");
fprintf(fp," else {\n");
fprintf(fp," if (X == cm[j2-1]) rdata = j2 - j0;\n");
fprintf(fp," else rdata = 0;\n");
fprintf(fp," }\n");
fprintf(fp," }\n");
fprintf(fp," return rdata;\n");
fprintf(fp,"}\n");
fprintf(fp,"/* ====================================*/\n");
for (mm = countFm-1; mm >= 0; mm--)
{
for (ii = 0; ii < numMars_; ii++)
{
if (marsNfms_[ii] > mm)
{
ddata = marsFms_[ii]->getEntry(mm);
if (ddata < PSUADE_UNDEFINED) break;
}
}
if (ii != numMars_) break;
countFm--;
}
if (countFm > 0)
{
fprintf(fp,"static double\n");
fprintf(fp,"FMS[%d][%d] = \n", countFm, numMars_);
fprintf(fp,"{\n");
for (mm = 0; mm < countFm; mm++)
{
fprintf(fp," {");
for (ii = 0; ii < numMars_-1; ii++)
{
if (marsNfms_[ii] > mm)
{
ddata = marsFms_[ii]->getEntry(mm);
fprintf(fp," %24.16e,", ddata);
}
else fprintf(fp," 0,");
}
if (marsNfms_[numMars_-1] > mm)
{
ddata = marsFms_[numMars_-1]->getEntry(mm);
fprintf(fp," %24.16e },\n", ddata);
}
else fprintf(fp," 0 },\n");
}
fprintf(fp,"};\n");
}
for (mm = countIm-1; mm >= 0; mm--)
{
for (ii = 0; ii < numMars_; ii++)
{
if (marsNims_[ii] > mm)
{
idata = marsIms_[ii]->getEntry(mm);
if (idata != -9999) break;
}
}
if (ii != numMars_) break;
countIm--;
}
if (countIm > 0)
{
fprintf(fp,"static int\n");
fprintf(fp,"IMS[%d][%d] = \n", countIm, numMars_);
fprintf(fp,"{\n");
for (mm = 0; mm < countIm; mm++)
{
fprintf(fp," {");
for (ii = 0; ii < numMars_-1; ii++)
{
if (marsNims_[ii] > mm)
{
idata = marsIms_[ii]->getEntry(mm);
fprintf(fp," %d,", idata);
}
else fprintf(fp," 0,");
}
if (marsNims_[numMars_-1] > mm)
{
idata = marsIms_[numMars_-1]->getEntry(mm);
fprintf(fp," %d },\n", idata);
}
else fprintf(fp," 0 },\n");
}
}
fprintf(fp,"};\n");
fprintf(fp,"static double\n");
fprintf(fp,"XMeans[%d][%d] = \n", numMars_, nInputs_);
fprintf(fp,"{\n");
double **mat2DM = marsXMeans_.getMatrix2D();
double **mat2DS = marsXStds_.getMatrix2D();
for (mm = 0; mm < numMars_; mm++)
{
fprintf(fp," {");
for (ii = 0; ii < nInputs_-1; ii++)
fprintf(fp," %24.16e,", mat2DM[mm][ii]);
fprintf(fp," %24.16e },\n", mat2DM[mm][nInputs_-1]);
}
fprintf(fp,"};\n");
fprintf(fp,"static double\n");
fprintf(fp,"XStds[%d][%d] = \n", numMars_, nInputs_);
fprintf(fp,"{\n");
for (mm = 0; mm < numMars_; mm++)
{
fprintf(fp," {");
for (ii = 0; ii < nInputs_-1; ii++)
fprintf(fp," %24.16e,", mat2DS[mm][ii]);
fprintf(fp," %24.16e },\n", mat2DS[mm][nInputs_-1]);
}
fprintf(fp,"};\n");
fprintf(fp,"/* ====================================*/\n");
fprintf(fp,
"int getCoefs(int ind,double *fm,int *im,double *XM,double *XS)\n");
fprintf(fp,"{\n");
fprintf(fp," int mm;\n");
fprintf(fp," for (mm = 0; mm < %d; mm++)\n",countFm);
fprintf(fp," fm[mm] = FMS[mm][ind];\n");
fprintf(fp," for (mm = 0; mm < %d; mm++)\n",countIm);
fprintf(fp," im[mm] = IMS[mm][ind];\n");
fprintf(fp," for (mm = 0; mm < %d; mm++)\n",nInputs_);
fprintf(fp," XM[mm] = XMeans[ind][mm];\n");
fprintf(fp," for (mm = 0; mm < %d; mm++)\n",nInputs_);
fprintf(fp," XS[mm] = XStds[ind][mm];\n");
fprintf(fp," return 0;\n");
fprintf(fp,"}\n");
fprintf(fp,"/* ====================================*/\n");
fclose(fp);
printf("MarsBagg parameters are now stored in psuade_rs.info\n");
fp = fopen("psuade_rs.py", "w");
if (fp == NULL)
{
printf("ERROR: Cannot open file psuade_rs.py.\n");
return 0;
}
fwriteRSPythonHeader(fp);
fprintf(fp,"#==================================================\n");
fprintf(fp,"# MARS with bagging interpolation\n");
fprintf(fp,"#==================================================\n");
fwriteRSPythonCommon(fp);
fprintf(fp,"numMars=%d\n",numMars_);
fprintf(fp,"nInputs=%d\n",nInputs_);
for (mm = countFm-1; mm >= 0; mm--)
{
for (ii = 0; ii < numMars_; ii++)
{
if (marsNfms_[ii] > mm)
{
ddata = marsFms_[ii]->getEntry(mm);
if (ddata < PSUADE_UNDEFINED) break;
}
}
if (ii != numMars_) break;
countFm--;
}
if (countFm > 0)
{
fprintf(fp,"FMS = [\n");
for (mm = 0; mm < countFm; mm++)
{
fprintf(fp," [");
for (ii = 0; ii < numMars_-1; ii++)
{
if (marsNfms_[ii] > mm)
{
ddata = marsFms_[ii]->getEntry(mm);
fprintf(fp," %24.16e,", ddata);
}
else fprintf(fp," 0,");
}
if (marsNfms_[numMars_-1] > mm)
{
ddata = marsFms_[numMars_-1]->getEntry(mm);
fprintf(fp," %24.16e ],\n", ddata);
}
else fprintf(fp," 0 ],\n");
}
fprintf(fp,"]\n");
}
for (mm = countIm-1; mm >= 0; mm--)
{
for (ii = 0; ii < numMars_; ii++)
{
if (marsNims_[ii] > mm)
{
idata = marsIms_[ii]->getEntry(mm);
if (idata != -9999) break;
}
}
if (ii != numMars_) break;
countIm--;
}
if (countIm > 0)
{
fprintf(fp,"IMS = [\n");
for (mm = 0; mm < countIm; mm++)
{
fprintf(fp," [");
for (ii = 0; ii < numMars_-1; ii++)
{
if (marsNims_[ii] > mm)
{
idata = marsIms_[ii]->getEntry(mm);
fprintf(fp," %d,", idata);
}
else fprintf(fp," 0,");
}
if (marsNims_[numMars_-1] > mm)
{
idata = marsIms_[numMars_-1]->getEntry(mm);
fprintf(fp," %d ],\n", idata);
}
else fprintf(fp," 0 ],\n");
}
}
fprintf(fp,"]\n");
fprintf(fp,"XMeans = [\n");
for (ii = 0; ii < nInputs_; ii++)
{
fprintf(fp," [");
for (mm = 0; mm < numMars_-1; mm++)
fprintf(fp," %24.16e,", mat2DM[mm][ii]);
fprintf(fp," %24.16e ],\n", mat2DM[numMars_-1][ii]);
}
fprintf(fp,"]\n");
fprintf(fp,"XStds = [\n");
for (ii = 0; ii < nInputs_; ii++)
{
fprintf(fp," [");
for (mm = 0; mm < numMars_-1; mm++)
fprintf(fp," %24.16e,", mat2DS[mm][ii]);
fprintf(fp," %24.16e ],\n", mat2DS[numMars_-1][ii]);
}
fprintf(fp,"]\n");
fprintf(fp,"###################################################\n");
fprintf(fp,"def icat(X, input, fm, indcm,tt) :\n");
fprintf(fp," j0 = int(fm[indcm+2*input][tt] + 0.1)\n");
fprintf(fp," j1 = j0 \n");
fprintf(fp," j2 = int(fm[indcm+2*input+1][tt] + 0.1)\n");
fprintf(fp," while (j2 != (j1+1)) :\n");
fprintf(fp," k = int(0.5*(j1+j2)+1.0e-8) - 1\n");
fprintf(fp," if (fm[indcm+k][tt] == X) :\n");
fprintf(fp," rdata = k - j0\n");
fprintf(fp," break\n");
fprintf(fp," elif (fm[indcm+k][tt] < X) :\n");
fprintf(fp," j1 = k\n");
fprintf(fp," else :\n");
fprintf(fp," j2 = k;\n");
fprintf(fp," if (X == fm[indcm+j1-1][tt]) : \n");
fprintf(fp," rdata = j2 - j0\n");
fprintf(fp," else :\n");
fprintf(fp," if (X == fm[indcm+j2-1][tt]) : \n");
fprintf(fp," rdata = j2 - j0\n");
fprintf(fp," else :\n");
fprintf(fp," rdata = 0\n");
fprintf(fp," return rdata\n");
fprintf(fp,"###################################################\n");
fprintf(fp,"# Interpolation function \n");
fprintf(fp,"# X[0], X[1], .. X[m-1] - first point\n");
fprintf(fp,"# X[m], X[m+1], .. X[2*m-1] - second point\n");
fprintf(fp,"# ... \n");
fprintf(fp,"#==================================================\n");
fprintf(fp,"def interpolate(XX): \n");
fprintf(fp," nSamp = int(len(XX) / nInputs + 1.0e-8)\n");
fprintf(fp," X = nInputs * [0.0]\n");
fprintf(fp," Ys = 2 * nSamp * [0.0]\n");
fprintf(fp," Yt = numMars * [0.0]\n");
fprintf(fp," for ss in range(nSamp) : \n");
fprintf(fp," for ii in range(nInputs) : \n");
fprintf(fp," X[ii] = XX[ss*nInputs+ii]\n");
fprintf(fp," for tt in range(numMars) : \n");
fprintf(fp," nk = IMS[4][tt]\n");
fprintf(fp," ind = IMS[10][tt] - 1; az = FMS[ind][tt]\n");
fprintf(fp," indtb = IMS[11][tt] - 1\n");
fprintf(fp," indcm = IMS[14][tt] - 1\n");
fprintf(fp," yt = az\n");
fprintf(fp," for nn in range(nk) : \n");
fprintf(fp," if (FMS[indtb+nn*5][tt] != 0.0) :\n");
fprintf(fp," phi = 1.0\n");
fprintf(fp," ip = nn\n");
fprintf(fp," while (ip > -1) :\n");
fprintf(fp," ind = int(indtb+ip*5)+1\n");
fprintf(fp," t = FMS[ind][tt]\n");
fprintf(fp," v = t\n");
fprintf(fp," if (v < 0): \n");
fprintf(fp," v = - v\n");
fprintf(fp," ind = int(v+0.1) - 1\n");
fprintf(fp," ind1 = indcm+2*ind\n");
fprintf(fp," if (FMS[ind1][tt] <= 0.0) :\n");
fprintf(fp," v = 1.0\n");
fprintf(fp," if (t < 0.0) : \n");
fprintf(fp," v = -1.0\n");
fprintf(fp," dt = (X[ind]-XMeans[ind][tt])/XStds[ind][tt]\n");
fprintf(fp," ind2 = int(indtb+ip*5+2)\n");
fprintf(fp," u = v * (dt-FMS[ind2][tt]) \n");
fprintf(fp," if (u < 0.0) : \n");
fprintf(fp," u = 0.0\n");
fprintf(fp," else :\n");
fprintf(fp," dt = (X[ind]-XMeans[ind][tt])/XStds[ind][tt]\n");
fprintf(fp," k = icat(dt, ind, FMS, indcm, tt)\n");
fprintf(fp," if (k != 0) :\n");
fprintf(fp," ind = int(FMS[indtb+ip*5+2][tt]+0.1) - 1\n");
fprintf(fp," u = FMS[indcm+k+ind][tt]\n");
fprintf(fp," else : \n");
fprintf(fp," u = 0.0\n");
fprintf(fp," if (t < 0.0) :\n");
fprintf(fp," if (u == 0.0) : \n");
fprintf(fp," u = 1.0\n");
fprintf(fp," else : \n");
fprintf(fp," u = 0.0\n");
fprintf(fp," if (u == 0.0) :\n");
fprintf(fp," phi = 0.0\n");
fprintf(fp," break\n");
fprintf(fp," else :\n");
fprintf(fp," phi *= u\n");
fprintf(fp," ind3 = int(indtb+ip*5+3)\n");
fprintf(fp," ip = int(FMS[ind3][tt] + 0.1) - 1\n");
fprintf(fp," yt += FMS[indtb+nn*5][tt] * phi\n");
fprintf(fp," Yt[tt] = yt\n");
fprintf(fp," Ymean = 0.0\n");
fprintf(fp," for tt in range(numMars) : \n");
fprintf(fp," Ymean = Ymean + Yt[tt]\n");
fprintf(fp," Ymean = Ymean / numMars\n");
fprintf(fp," Ystd = 0.0\n");
fprintf(fp," for tt in range(numMars) : \n");
fprintf(fp," Ystd = Ystd + (Yt[tt] - Ymean) * (Yt[tt] - Ymean)\n");
fprintf(fp," Ystd = math.sqrt(Ystd / (numMars - 1.0))\n");
fprintf(fp," Ys[ss*2] = Ymean\n");
fprintf(fp," Ys[ss*2+1] = Ystd\n");
fprintf(fp," return Ys\n");
fprintf(fp,"###################################################\n");
fprintf(fp,"# main program\n");
fprintf(fp,"#==================================================\n");
fprintf(fp,"infileName = sys.argv[1]\n");
fprintf(fp,"outfileName = sys.argv[2]\n");
fprintf(fp,"inputs = getInputData(infileName)\n");
fprintf(fp,"outputs = interpolate(inputs)\n");
fprintf(fp,"genOutputFile(outfileName, outputs)\n");
fclose(fp);
printf("FILE psuade_rs.py contains the final MarsBag interpolator.\n");
return 0;
}
| 32.277067 | 80 | 0.493878 | [
"object",
"3d"
] |
16f99455e333de8b214ecb618a81cf7128a0d392 | 5,962 | cpp | C++ | inference_backend/image_inference/async_with_va_api/image_inference_async/image_inference_async.cpp | MisterArslan/dlstreamer_gst | ff6d0bc138f372bb988baf368af4a3693b808e16 | [
"MIT"
] | 125 | 2020-09-18T10:50:27.000Z | 2022-02-10T06:20:59.000Z | inference_backend/image_inference/async_with_va_api/image_inference_async/image_inference_async.cpp | MisterArslan/dlstreamer_gst | ff6d0bc138f372bb988baf368af4a3693b808e16 | [
"MIT"
] | 155 | 2020-09-10T23:32:29.000Z | 2022-02-05T07:10:26.000Z | inference_backend/image_inference/async_with_va_api/image_inference_async/image_inference_async.cpp | MisterArslan/dlstreamer_gst | ff6d0bc138f372bb988baf368af4a3693b808e16 | [
"MIT"
] | 41 | 2020-09-15T08:49:17.000Z | 2022-01-24T10:39:36.000Z | /*******************************************************************************
* Copyright (C) 2018-2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
******************************************************************************/
#include "environment_variable_options_reader.h"
#include "feature_toggling/ifeature_toggle.h"
#include "runtime_feature_toggler.h"
#include "image_inference_async.h"
#include "vaapi_context.h"
#include "vaapi_converter.h"
#include "vaapi_images.h"
#include <future>
#include <tuple>
#include <utility>
using namespace InferenceBackend;
namespace {
CREATE_FEATURE_TOGGLE(VaapiPreprocYUVToggle, "vaapi-preproc-yuv",
"Vaapi pre-proc with RGBP output may be not high-performant on some systems. Please set "
"environment variable ENABLE_GVA_FEATURES=vaapi-preproc-yuv to enable I420 output for vaapi "
"pre-proc and see if it enables better performance. ")
std::unique_ptr<VaApiImagePool> create_va_api_image_pool(VaApiImagePool::ImageInfo info, size_t pool_size,
VaApiContext *context) {
// If ENABLE_GVA_FEATURES=vaapi-preproc-yuv set, then VA pipeline ends with scaled I420 image and I420->RGBP CSC
// happens with OpenCV later.
auto feature_toggler = std::unique_ptr<FeatureToggling::Runtime::RuntimeFeatureToggler>(
new FeatureToggling::Runtime::RuntimeFeatureToggler());
FeatureToggling::Runtime::EnvironmentVariableOptionsReader env_var_options_reader;
feature_toggler->configure(env_var_options_reader.read("ENABLE_GVA_FEATURES"));
if (feature_toggler->enabled(VaapiPreprocYUVToggle::id))
info.format = FourCC::FOURCC_I420;
else
GVA_WARNING(VaapiPreprocYUVToggle::deprecation_message.c_str());
std::unique_ptr<VaApiImagePool> pool =
std::unique_ptr<VaApiImagePool>(new VaApiImagePool(context, pool_size, info));
return pool;
}
VaApiImagePool::ImageInfo get_pool_image_info(const ImageInference::Ptr &inference) {
size_t width = 0;
size_t height = 0;
size_t batch_size = 0;
int format = 0;
int memory_type = 0;
inference->GetModelImageInputInfo(width, height, batch_size, format, memory_type);
VaApiImagePool::ImageInfo info = {.width = (uint32_t)width,
.height = (uint32_t)height,
.batch = (uint32_t)batch_size,
.format = (FourCC)format,
.memory_type = (MemoryType)memory_type};
return info;
}
} // namespace
ImageInferenceAsync::ImageInferenceAsync(uint32_t thread_pool_size, VaApiDisplayPtr va_display,
ImageInference::Ptr inference)
: _inference(inference), _thread_pool(thread_pool_size) {
if (!_inference)
throw std::invalid_argument("Ivalid inference object!");
_va_context = std::unique_ptr<VaApiContext>(new VaApiContext(va_display));
_va_converter = std::unique_ptr<VaApiConverter>(new VaApiConverter(_va_context.get()));
auto inference_image_info = get_pool_image_info(_inference);
size_t image_pool_size = inference_image_info.batch * _inference->GetNireq();
if (image_pool_size < thread_pool_size)
image_pool_size = thread_pool_size;
_va_image_pool = create_va_api_image_pool(inference_image_info, image_pool_size, _va_context.get());
std::string msg = "Vpp image pool size: " + std::to_string(image_pool_size);
GVA_INFO(msg.c_str());
}
void ImageInferenceAsync::SubmitInference(VaApiImage *va_api_image, IFrameBase::Ptr user_data,
const std::map<std::string, InputLayerDesc::Ptr> &input_preprocessors) {
auto deleter = [this, va_api_image](Image *img) {
va_api_image->Unmap();
this->_va_image_pool->ReleaseBuffer(va_api_image);
delete img;
};
std::shared_ptr<Image> image = std::shared_ptr<Image>(new Image(va_api_image->Map()), deleter);
user_data->SetImage(image);
_inference->SubmitImage(*image, std::move(user_data), input_preprocessors);
}
void ImageInferenceAsync::SubmitImage(const Image &src_image, IFrameBase::Ptr user_data,
const std::map<std::string, InputLayerDesc::Ptr> &input_preprocessors) {
VaApiImage *dst_image = _va_image_pool->AcquireBuffer();
_va_converter->Convert(src_image, *dst_image);
dst_image->sync = _thread_pool.schedule([this, dst_image, user_data, input_preprocessors]() {
SubmitInference(dst_image, user_data, input_preprocessors);
});
}
const std::string &ImageInferenceAsync::GetModelName() const {
return _inference->GetModelName();
}
size_t ImageInferenceAsync::GetNireq() const {
return _inference->GetNireq();
}
void ImageInferenceAsync::GetModelImageInputInfo(size_t &width, size_t &height, size_t &batch_size, int &format,
int &memory_type) const {
_inference->GetModelImageInputInfo(width, height, batch_size, format, memory_type);
}
std::map<std::string, std::vector<size_t>> ImageInferenceAsync::GetModelInputsInfo() const {
if (not _inference) {
throw std::runtime_error("Inference not set");
}
return _inference->GetModelInputsInfo();
}
std::map<std::string, std::vector<size_t>> ImageInferenceAsync::GetModelOutputsInfo() const {
if (not _inference) {
throw std::runtime_error("Inference not set");
}
return _inference->GetModelOutputsInfo();
}
bool ImageInferenceAsync::IsQueueFull() {
return _inference->IsQueueFull();
}
void ImageInferenceAsync::Flush() {
if (_va_image_pool) {
_va_image_pool->Flush();
}
if (_inference) {
_inference->Flush();
}
}
void ImageInferenceAsync::Close() {
_inference->Close();
}
ImageInferenceAsync::~ImageInferenceAsync() = default;
| 38.96732 | 116 | 0.668568 | [
"object",
"vector"
] |
16fff3b682d9f7aada2816f73bad50a4bcb92ffb | 12,512 | cpp | C++ | src/limits.cpp | stefan-lindstrom/circpp | d0ac5d75126883b8273823753db1fb7bcb877433 | [
"Info-ZIP",
"Unlicense"
] | 4 | 2016-06-23T02:37:11.000Z | 2018-12-23T10:00:12.000Z | src/limits.cpp | stefan-lindstrom/circpp | d0ac5d75126883b8273823753db1fb7bcb877433 | [
"Info-ZIP",
"Unlicense"
] | null | null | null | src/limits.cpp | stefan-lindstrom/circpp | d0ac5d75126883b8273823753db1fb7bcb877433 | [
"Info-ZIP",
"Unlicense"
] | null | null | null | /* ************************************************************************
* File: limits.c Part of CircleMUD *
* Usage: limits & gain funcs for HMV, exp, hunger/thirst, idle time *
* *
* All rights reserved. See license.doc for complete information. *
* *
* Copyright (C) 1993, 94 by the Trustees of the Johns Hopkins University *
* CircleMUD is based on DikuMUD, Copyright (C) 1990, 1991. *
************************************************************************ */
#include "conf.h"
#include "sysdep.h"
#include "structs.h"
#include "utils.h"
#include "spells.h"
#include "comm.h"
#include "db.h"
#include "handler.h"
#include "interpreter.h"
/* external variables */
extern int max_exp_gain;
extern int max_exp_loss;
extern int idle_rent_time;
extern int idle_max_level;
extern int idle_void;
extern int immort_level_ok;
extern int use_autowiz;
extern int min_wizlist_lev;
extern int free_rent;
/* local functions */
int graf(int grafage, int p0, int p1, int p2, int p3, int p4, int p5, int p6);
void run_autowiz(void);
void Crash_rentsave(struct char_data *ch, int cost);
int level_exp(int chclass, int level);
char *title_male(int chclass, int level);
char *title_female(int chclass, int level);
void update_char_objects(struct char_data *ch); /* handler.c */
void reboot_wizlists(void);
/* When age < 15 return the value p0 */
/* When age in 15..29 calculate the line between p1 & p2 */
/* When age in 30..44 calculate the line between p2 & p3 */
/* When age in 45..59 calculate the line between p3 & p4 */
/* When age in 60..79 calculate the line between p4 & p5 */
/* When age >= 80 return the value p6 */
int graf(int grafage, int p0, int p1, int p2, int p3, int p4, int p5, int p6)
{
if (grafage < 15)
return (p0); /* < 15 */
else if (grafage <= 29)
return (p1 + (((grafage - 15) * (p2 - p1)) / 15)); /* 15..29 */
else if (grafage <= 44)
return (p2 + (((grafage - 30) * (p3 - p2)) / 15)); /* 30..44 */
else if (grafage <= 59)
return (p3 + (((grafage - 45) * (p4 - p3)) / 15)); /* 45..59 */
else if (grafage <= 79)
return (p4 + (((grafage - 60) * (p5 - p4)) / 20)); /* 60..79 */
else
return (p6); /* >= 80 */
}
/*
* The hit_limit, mana_limit, and move_limit functions are gone. They
* added an unnecessary level of complexity to the internal structure,
* weren't particularly useful, and led to some annoying bugs. From the
* players' point of view, the only difference the removal of these
* functions will make is that a character's age will now only affect
* the HMV gain per tick, and _not_ the HMV maximums.
*/
/* manapoint gain pr. game hour */
int mana_gain(struct char_data *ch)
{
int gain;
if (IS_NPC(ch)) {
/* Neat and fast */
gain = GET_LEVEL(ch);
} else {
gain = graf(age(ch)->year, 4, 8, 12, 16, 12, 10, 8);
/* Class calculations */
/* Skill/Spell calculations */
/* Position calculations */
switch (GET_POS(ch)) {
case POS_SLEEPING:
gain *= 2;
break;
case POS_RESTING:
gain += (gain / 2); /* Divide by 2 */
break;
case POS_SITTING:
gain += (gain / 4); /* Divide by 4 */
break;
}
if (IS_MAGIC_USER(ch) || IS_CLERIC(ch))
gain *= 2;
if ((GET_COND(ch, FULL) == 0) || (GET_COND(ch, THIRST) == 0))
gain /= 4;
}
if (AFF_FLAGGED(ch, AFF_POISON))
gain /= 4;
return (gain);
}
/* Hitpoint gain pr. game hour */
int hit_gain(struct char_data *ch)
{
int gain;
if (IS_NPC(ch)) {
/* Neat and fast */
gain = GET_LEVEL(ch);
} else {
gain = graf(age(ch)->year, 8, 12, 20, 32, 16, 10, 4);
/* Class/Level calculations */
/* Skill/Spell calculations */
/* Position calculations */
switch (GET_POS(ch)) {
case POS_SLEEPING:
gain += (gain / 2); /* Divide by 2 */
break;
case POS_RESTING:
gain += (gain / 4); /* Divide by 4 */
break;
case POS_SITTING:
gain += (gain / 8); /* Divide by 8 */
break;
}
if (IS_MAGIC_USER(ch) || IS_CLERIC(ch))
gain /= 2; /* Ouch. */
if ((GET_COND(ch, FULL) == 0) || (GET_COND(ch, THIRST) == 0))
gain /= 4;
}
if (AFF_FLAGGED(ch, AFF_POISON))
gain /= 4;
return (gain);
}
/* move gain pr. game hour */
int move_gain(struct char_data *ch)
{
int gain;
if (IS_NPC(ch)) {
/* Neat and fast */
gain = GET_LEVEL(ch);
} else {
gain = graf(age(ch)->year, 16, 20, 24, 20, 16, 12, 10);
/* Class/Level calculations */
/* Skill/Spell calculations */
/* Position calculations */
switch (GET_POS(ch)) {
case POS_SLEEPING:
gain += (gain / 2); /* Divide by 2 */
break;
case POS_RESTING:
gain += (gain / 4); /* Divide by 4 */
break;
case POS_SITTING:
gain += (gain / 8); /* Divide by 8 */
break;
}
if ((GET_COND(ch, FULL) == 0) || (GET_COND(ch, THIRST) == 0))
gain /= 4;
}
if (AFF_FLAGGED(ch, AFF_POISON))
gain /= 4;
return (gain);
}
void set_title(struct char_data *ch, char *title)
{
if (title == NULL) {
if (GET_SEX(ch) == SEX_FEMALE)
title = title_female(GET_CLASS(ch), GET_LEVEL(ch));
else
title = title_male(GET_CLASS(ch), GET_LEVEL(ch));
}
if (strlen(title) > MAX_TITLE_LENGTH)
title[MAX_TITLE_LENGTH] = '\0';
if (GET_TITLE(ch) != NULL)
free(GET_TITLE(ch));
GET_TITLE(ch) = strdup(title);
}
void run_autowiz(void)
{
#if defined(CIRCLE_UNIX) || defined(CIRCLE_WINDOWS)
if (use_autowiz) {
size_t res;
char buf[256];
#if defined(CIRCLE_UNIX)
res = snprintf(buf, sizeof(buf), "nice ../bin/autowiz %d %s %d %s %d &",
min_wizlist_lev, WIZLIST_FILE, LVL_IMMORT, IMMLIST_FILE, (int) getpid());
#elif defined(CIRCLE_WINDOWS)
res = snprintf(buf, sizeof(buf), "autowiz %d %s %d %s",
min_wizlist_lev, WIZLIST_FILE, LVL_IMMORT, IMMLIST_FILE);
#endif /* CIRCLE_WINDOWS */
/* Abusing signed -> unsigned conversion to avoid '-1' check. */
if (res < sizeof(buf)) {
mudlog(CMP, LVL_IMMORT, FALSE, "Initiating autowiz.");
system(buf);
reboot_wizlists();
} else
log("Cannot run autowiz: command-line doesn't fit in buffer.");
}
#endif /* CIRCLE_UNIX || CIRCLE_WINDOWS */
}
void gain_exp(struct char_data *ch, int gain)
{
int is_altered = FALSE;
int num_levels = 0;
if (!IS_NPC(ch) && ((GET_LEVEL(ch) < 1 || GET_LEVEL(ch) >= LVL_IMMORT)))
return;
if (IS_NPC(ch)) {
GET_EXP(ch) += gain;
return;
}
if (gain > 0) {
gain = MIN(max_exp_gain, gain); /* put a cap on the max gain per kill */
GET_EXP(ch) += gain;
while (GET_LEVEL(ch) < LVL_IMMORT - immort_level_ok &&
GET_EXP(ch) >= level_exp(GET_CLASS(ch), GET_LEVEL(ch) + 1)) {
GET_LEVEL(ch) += 1;
num_levels++;
advance_level(ch);
is_altered = TRUE;
}
if (is_altered) {
mudlog(BRF, MAX(LVL_IMMORT, GET_INVIS_LEV(ch)), TRUE, "%s advanced %d level%s to level %d.",
GET_NAME(ch), num_levels, num_levels == 1 ? "" : "s", GET_LEVEL(ch));
if (num_levels == 1)
send_to_char(ch, "You rise a level!\r\n");
else
send_to_char(ch, "You rise %d levels!\r\n", num_levels);
set_title(ch, NULL);
if (GET_LEVEL(ch) >= LVL_IMMORT)
run_autowiz();
}
} else if (gain < 0) {
gain = MAX(-max_exp_loss, gain); /* Cap max exp lost per death */
GET_EXP(ch) += gain;
if (GET_EXP(ch) < 0)
GET_EXP(ch) = 0;
}
}
void gain_exp_regardless(struct char_data *ch, int gain)
{
int is_altered = FALSE;
int num_levels = 0;
GET_EXP(ch) += gain;
if (GET_EXP(ch) < 0)
GET_EXP(ch) = 0;
if (!IS_NPC(ch)) {
while (GET_LEVEL(ch) < LVL_IMPL &&
GET_EXP(ch) >= level_exp(GET_CLASS(ch), GET_LEVEL(ch) + 1)) {
GET_LEVEL(ch) += 1;
num_levels++;
advance_level(ch);
is_altered = TRUE;
}
if (is_altered) {
mudlog(BRF, MAX(LVL_IMMORT, GET_INVIS_LEV(ch)), TRUE, "%s advanced %d level%s to level %d.",
GET_NAME(ch), num_levels, num_levels == 1 ? "" : "s", GET_LEVEL(ch));
if (num_levels == 1)
send_to_char(ch, "You rise a level!\r\n");
else
send_to_char(ch, "You rise %d levels!\r\n", num_levels);
set_title(ch, NULL);
if (GET_LEVEL(ch) >= LVL_IMMORT)
run_autowiz();
}
}
}
void gain_condition(struct char_data *ch, int condition, int value)
{
bool intoxicated;
if (IS_NPC(ch) || GET_COND(ch, condition) == -1) /* No change */
return;
intoxicated = (GET_COND(ch, DRUNK) > 0);
GET_COND(ch, condition) += value;
GET_COND(ch, condition) = MAX(0, GET_COND(ch, condition));
GET_COND(ch, condition) = MIN(24, GET_COND(ch, condition));
if (GET_COND(ch, condition) || PLR_FLAGGED(ch, PLR_WRITING))
return;
switch (condition) {
case FULL:
send_to_char(ch, "You are hungry.\r\n");
break;
case THIRST:
send_to_char(ch, "You are thirsty.\r\n");
break;
case DRUNK:
if (intoxicated)
send_to_char(ch, "You are now sober.\r\n");
break;
default:
break;
}
}
void check_idling(struct char_data *ch)
{
if (++(ch->char_specials.timer) > idle_void) {
if (GET_WAS_IN(ch) == NOWHERE && IN_ROOM(ch) != NOWHERE) {
GET_WAS_IN(ch) = IN_ROOM(ch);
if (FIGHTING(ch)) {
stop_fighting(FIGHTING(ch));
stop_fighting(ch);
}
act("$n disappears into the void.", TRUE, ch, 0, 0, CommTarget::TO_ROOM);
send_to_char(ch, "You have been idle, and are pulled into a void.\r\n");
save_char(ch);
Crash_crashsave(ch);
char_from_room(ch);
char_to_room(ch, 1);
} else if (ch->char_specials.timer > idle_rent_time) {
if (IN_ROOM(ch) != NOWHERE)
char_from_room(ch);
char_to_room(ch, 3);
if (ch->desc) {
STATE(ch->desc) = CON_DISCONNECT;
/*
* For the 'if (d->character)' test in close_socket().
* -gg 3/1/98 (Happy anniversary.)
*/
ch->desc->character = NULL;
ch->desc = NULL;
}
if (free_rent)
Crash_rentsave(ch, 0);
else
Crash_idlesave(ch);
mudlog(CMP, LVL_GOD, TRUE, "%s force-rented and extracted (idle).", GET_NAME(ch));
extract_char(ch);
}
}
}
/* Update PCs, NPCs, and objects */
void point_update(void)
{
struct char_data *i, *next_char;
struct obj_data *j, *next_thing, *jj, *next_thing2;
/* characters */
for (i = character_list; i; i = next_char) {
next_char = i->next;
gain_condition(i, FULL, -1);
gain_condition(i, DRUNK, -1);
gain_condition(i, THIRST, -1);
if (GET_POS(i) >= POS_STUNNED) {
GET_HIT(i) = MIN(GET_HIT(i) + hit_gain(i), GET_MAX_HIT(i));
GET_MANA(i) = MIN(GET_MANA(i) + mana_gain(i), GET_MAX_MANA(i));
GET_MOVE(i) = MIN(GET_MOVE(i) + move_gain(i), GET_MAX_MOVE(i));
if (AFF_FLAGGED(i, AFF_POISON))
if (damage(i, i, 2, SPELL_POISON) == -1)
continue; /* Oops, they died. -gg 6/24/98 */
if (GET_POS(i) <= POS_STUNNED)
update_pos(i);
} else if (GET_POS(i) == POS_INCAP) {
if (damage(i, i, 1, TYPE_SUFFERING) == -1)
continue;
} else if (GET_POS(i) == POS_MORTALLYW) {
if (damage(i, i, 2, TYPE_SUFFERING) == -1)
continue;
}
if (!IS_NPC(i)) {
update_char_objects(i);
if (GET_LEVEL(i) < idle_max_level)
check_idling(i);
}
}
/* objects */
for (j = object_list; j; j = next_thing) {
next_thing = j->next; /* Next in object list */
/* If this is a corpse */
if (IS_CORPSE(j)) {
/* timer count down */
if (GET_OBJ_TIMER(j) > 0)
GET_OBJ_TIMER(j)--;
if (!GET_OBJ_TIMER(j)) {
if (j->carried_by)
act("$p decays in your hands.", FALSE, j->carried_by, j, 0, CommTarget::TO_CHAR);
else if ((IN_ROOM(j) != NOWHERE) && (world[IN_ROOM(j)].people)) {
act("A quivering horde of maggots consumes $p.",
TRUE, world[IN_ROOM(j)].people, j, 0, CommTarget::TO_ROOM);
act("A quivering horde of maggots consumes $p.",
TRUE, world[IN_ROOM(j)].people, j, 0, CommTarget::TO_CHAR);
}
for (jj = j->contains; jj; jj = next_thing2) {
next_thing2 = jj->next_content; /* Next in inventory */
obj_from_obj(jj);
if (j->in_obj)
obj_to_obj(jj, j->in_obj);
else if (j->carried_by)
obj_to_room(jj, IN_ROOM(j->carried_by));
else if (IN_ROOM(j) != NOWHERE)
obj_to_room(jj, IN_ROOM(j));
else
core_dump();
}
extract_obj(j);
}
}
}
}
| 26.121086 | 98 | 0.583919 | [
"object"
] |
e5062e4b25579e79d7962c63f269ba6ecce94e85 | 595 | cpp | C++ | C++/Data_Structures/DFS.cpp | IUC4801/HactoberFest21 | ad52dee669deba54630584435b77a6ab07dc67b2 | [
"Unlicense"
] | 1 | 2021-10-04T14:39:02.000Z | 2021-10-04T14:39:02.000Z | C++/Data_Structures/DFS.cpp | IUC4801/HactoberFest21 | ad52dee669deba54630584435b77a6ab07dc67b2 | [
"Unlicense"
] | null | null | null | C++/Data_Structures/DFS.cpp | IUC4801/HactoberFest21 | ad52dee669deba54630584435b77a6ab07dc67b2 | [
"Unlicense"
] | null | null | null | class Solution
{
public:
//Function to return a list containing the DFS traversal of the graph.
void dfs(vector<bool> & isVisited,vector<int>& ans,int i,vector<int> adj[]){
if(!isVisited[i]) {
isVisited[i]=true;
ans.push_back(i);
for(int j = 0;j<adj[i].size();j++){
dfs(isVisited,ans,adj[i][j],adj);
}
}
}
vector<int>dfsOfGraph(int V, vector<int> adj[])
{
vector<bool> isVisited(V,false);
vector<int> ans;
for(int i = 0;i<V;i++){
if(!isVisited[i]) dfs(isVisited,ans,i,adj);
}
return ans;
}
};
| 24.791667 | 77 | 0.557983 | [
"vector"
] |
e508a6a32135c208f9a326525587d3a9c42ee05c | 4,092 | cpp | C++ | src/Tarcog/tst/units/DoubleClearSingleSystemWithSun.unit.cpp | LBNL-ETA/Windows-CalcEngine | c81528f25ffb79989fcb15b03f00b7c18da138c4 | [
"BSD-3-Clause-LBNL"
] | 15 | 2018-04-20T19:16:50.000Z | 2022-02-11T04:11:41.000Z | src/Tarcog/tst/units/DoubleClearSingleSystemWithSun.unit.cpp | LBNL-ETA/Windows-CalcEngine | c81528f25ffb79989fcb15b03f00b7c18da138c4 | [
"BSD-3-Clause-LBNL"
] | 31 | 2016-04-05T20:56:28.000Z | 2022-03-31T22:02:46.000Z | src/Tarcog/tst/units/DoubleClearSingleSystemWithSun.unit.cpp | LBNL-ETA/Windows-CalcEngine | c81528f25ffb79989fcb15b03f00b7c18da138c4 | [
"BSD-3-Clause-LBNL"
] | 6 | 2018-04-20T19:38:58.000Z | 2020-04-06T00:30:47.000Z | #include <memory>
#include <stdexcept>
#include <gtest/gtest.h>
#include "WCETarcog.hpp"
#include "WCECommon.hpp"
class TestDoubleClearSingleSystemWithSun : public testing::Test
{
private:
std::shared_ptr<Tarcog::ISO15099::CSingleSystem> m_TarcogSystem;
protected:
void SetUp() override
{
/////////////////////////////////////////////////////////
/// Outdoor
/////////////////////////////////////////////////////////
auto airTemperature = 305.15; // Kelvins
auto airSpeed = 2.75; // meters per second
auto tSky = 305.15; // Kelvins
auto solarRadiation = 783.0;
auto Outdoor = Tarcog::ISO15099::Environments::outdoor(
airTemperature, airSpeed, solarRadiation, tSky, Tarcog::ISO15099::SkyModel::AllSpecified);
ASSERT_TRUE(Outdoor != nullptr);
Outdoor->setHCoeffModel(Tarcog::ISO15099::BoundaryConditionsCoeffModel::CalculateH);
/////////////////////////////////////////////////////////
/// Indoor
/////////////////////////////////////////////////////////
auto roomTemperature = 297.15;
auto Indoor = Tarcog::ISO15099::Environments::indoor(roomTemperature);
ASSERT_TRUE(Indoor != nullptr);
/////////////////////////////////////////////////////////
/// IGU
/////////////////////////////////////////////////////////
auto solidLayerThickness = 0.005715; // [m]
auto solidLayerConductance = 1.0;
auto solarAbsorptance = 0.187443971634;
auto layer1 = Tarcog::ISO15099::Layers::solid(solidLayerThickness, solidLayerConductance);
layer1->setSolarAbsorptance(solarAbsorptance, solarRadiation);
solarAbsorptance = 0.054178960621;
auto layer2 = Tarcog::ISO15099::Layers::solid(solidLayerThickness, solidLayerConductance);
layer2->setSolarAbsorptance(solarAbsorptance, solarRadiation);
auto gapThickness = 0.012;
auto m_GapLayer = Tarcog::ISO15099::Layers::gap(gapThickness);
ASSERT_TRUE(m_GapLayer != nullptr);
double windowWidth = 1;
double windowHeight = 1;
Tarcog::ISO15099::CIGU aIGU(windowWidth, windowHeight);
aIGU.addLayers({layer1, m_GapLayer, layer2});
// Alternative way to add layers.
// aIGU.addLayer(layer1);
// aIGU.addLayer(m_GapLayer);
// aIGU.addLayer(layer2);
/////////////////////////////////////////////////////////
// System
/////////////////////////////////////////////////////////
m_TarcogSystem = std::make_shared<Tarcog::ISO15099::CSingleSystem>(aIGU, Indoor, Outdoor);
ASSERT_TRUE(m_TarcogSystem != nullptr);
m_TarcogSystem->solve();
}
public:
std::shared_ptr<Tarcog::ISO15099::CSingleSystem> GetSystem() const
{
return m_TarcogSystem;
};
};
TEST_F(TestDoubleClearSingleSystemWithSun, Test1)
{
SCOPED_TRACE("Begin Test: Double Clear Single System - Surface temperatures");
auto aSystem = GetSystem();
ASSERT_TRUE(aSystem != nullptr);
auto Temperature = aSystem->getTemperatures();
std::vector<double> correctTemperature = {310.818074, 311.064868, 306.799522, 306.505704};
ASSERT_EQ(correctTemperature.size(), Temperature.size());
for(auto i = 0u; i < correctTemperature.size(); ++i)
{
EXPECT_NEAR(correctTemperature[i], Temperature[i], 1e-5);
}
auto Radiosity = aSystem->getRadiosities();
std::vector<double> correctRadiosity = {523.148794, 526.906252, 506.252171, 491.059753};
ASSERT_EQ(correctRadiosity.size(), Radiosity.size());
for(auto i = 0u; i < correctRadiosity.size(); ++i)
{
EXPECT_NEAR(correctRadiosity[i], Radiosity[i], 1e-5);
}
const auto heatFlow = aSystem->getHeatFlow(Tarcog::ISO15099::Environment::Indoor);
EXPECT_NEAR(-72.622787, heatFlow, 1e-5);
const auto Uvalue = aSystem->getUValue();
EXPECT_NEAR(9.077848, Uvalue, 1e-5);
const auto numOfIter = aSystem->getNumberOfIterations();
EXPECT_EQ(20u, numOfIter);
}
| 35.275862 | 100 | 0.580156 | [
"vector",
"solid"
] |
e50d2598e87f9b5a6a59b314fc173c7b3b854b78 | 1,849 | cpp | C++ | src/telemetryv1.cpp | leroythelegend/pcars_nn | bf6cd55b41741ebec59cd72a82aef9906e816bc8 | [
"MIT"
] | null | null | null | src/telemetryv1.cpp | leroythelegend/pcars_nn | bf6cd55b41741ebec59cd72a82aef9906e816bc8 | [
"MIT"
] | null | null | null | src/telemetryv1.cpp | leroythelegend/pcars_nn | bf6cd55b41741ebec59cd72a82aef9906e816bc8 | [
"MIT"
] | null | null | null | #include "telemetryv1.h"
#include <memory>
#include <vector>
#include <iostream>
#include "transportudp.h"
#include "capture.h"
#include "packettelemetrydatav1.h"
#include "packetparticipantinfostrings.h"
#include "packetparticipantinfostringsadditional.h"
#include "gamestate.h"
#include "packetgeneric.h"
using namespace pcars;
using namespace std;
namespace pcars
{
void TelemetryV1::start(const std::shared_ptr<Process> & process)
{
TransportUDP transport(5606);
Capture capture;
capture.nextGameState(make_shared<GamePlayingStateV1>(process));
while (true) {
const PCars_Data data = transport.read(30000);
PacketGeneric packetBase;
Position pos = 0;
packetBase.decode(data, pos);
if (packetBase.packet_type() == Packet_Type::PACKET_TYPE_TELEMETRY && data.size() == 1367) {
shared_ptr<Packet> packet = make_shared<PacketTelemetryDataV1>();
pos = 0;
packet->decode(data, pos);
capture.capturePacket(packet);
}
if (packetBase.packet_type() == Packet_Type::PACKET_TYPE_PARTICIPANT_INFO_STRINGS &&
data.size() == 1347) {
shared_ptr<Packet> packet = make_shared<PacketParticipantInfoStrings>();
pos = 0;
packet->decode(data, pos);
capture.capturePacket(packet);
}
if (packetBase.packet_type() == Packet_Type::PACKET_TYPE_PARTICIPANT_INFO_STRINGS_ADDITIONAL &&
data.size() == 1028) {
shared_ptr<Packet> packet = make_shared<PacketParticipantInfoStringsAdditional>();
pos = 0;
packet->decode(data, pos);
capture.capturePacket(packet);
}
}
}
} | 31.87931 | 107 | 0.605733 | [
"vector"
] |
e50d8cb12e4d7909d187c40ae72ad3bdd77066ee | 6,976 | hpp | C++ | Engine/Core/Headers/Molten/Renderer/Renderer.hpp | jimmiebergmann/MoltenEngine | d39e1dc8f2e92bcac7936a5e283faa66f65118ab | [
"MIT"
] | 1 | 2020-10-05T05:24:47.000Z | 2020-10-05T05:24:47.000Z | Engine/Core/Headers/Molten/Renderer/Renderer.hpp | jimmiebergmann/MoltenEngine | d39e1dc8f2e92bcac7936a5e283faa66f65118ab | [
"MIT"
] | null | null | null | Engine/Core/Headers/Molten/Renderer/Renderer.hpp | jimmiebergmann/MoltenEngine | d39e1dc8f2e92bcac7936a5e283faa66f65118ab | [
"MIT"
] | null | null | null | /*
* MIT License
*
* Copyright (c) 2020 Jimmie Bergmann
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files(the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions :
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#ifndef MOLTEN_CORE_RENDERER_RENDERER_HPP
#define MOLTEN_CORE_RENDERER_RENDERER_HPP
#include "Molten/Memory/Reference.hpp"
#include "Molten/Renderer/Framebuffer.hpp"
#include "Molten/Renderer/IndexBuffer.hpp"
#include "Molten/Renderer/Pipeline.hpp"
#include "Molten/Renderer/Texture.hpp"
#include "Molten/Renderer/UniformBlock.hpp"
#include "Molten/Renderer/UniformBuffer.hpp"
#include "Molten/Renderer/VertexBuffer.hpp"
#include "Molten/System/Version.hpp"
#include <functional>
namespace Molten::Shader::Visual
{
class VertexScript;
class FragmentScript;
}
namespace Molten
{
class Window;
class Logger;
/** Base class of renderer. */
class MOLTEN_API Renderer
{
public:
/** Types of renderers. */
enum class BackendApi
{
OpenGL,
Vulkan
};
/**
* Static function for creating any renderer by Type.
* Make sure to open the renderer before using it.
*
* @return Pointer to renderer, nullptr if the type of renderer is unavailable.
*/
static Renderer * Create(const BackendApi renderApi);
/** Virtual destructor. */
virtual ~Renderer();
/**
* Opens renderer by loading and attaching renderer to provided window.
*
* @param window Render target window.
*/
virtual bool Open(const Window& window, const Version& version = Version::None, Logger * logger = nullptr) = 0;
/** Closing renderer. */
virtual void Close() = 0;
/**
* Resize the framebuffers.
* Execute this function as soon as the render target's work area is resized.
*/
virtual void Resize(const Vector2ui32& size) = 0;
/** Get backend API type. */
virtual BackendApi GetBackendApi() const = 0;
/** Get renderer API version. */
virtual Version GetVersion() const = 0;
/** Get location of pipeline push constant by id. Id is set in shader script. */
virtual uint32_t GetPushConstantLocation(Pipeline* pipeline, const uint32_t id) = 0;
/** Create framebuffer object. */
virtual Framebuffer* CreateFramebuffer(const FramebufferDescriptor& descriptor) = 0;
/** Create index buffer object. */
virtual IndexBuffer* CreateIndexBuffer(const IndexBufferDescriptor& descriptor) = 0;
/** Create pipeline object. */
virtual Pipeline* CreatePipeline(const PipelineDescriptor& descriptor) = 0;
/** Create texture object. */
virtual Texture* CreateTexture() = 0;
/** Create uniform buffer object. */
virtual UniformBlock* CreateUniformBlock(const UniformBlockDescriptor& descriptor) = 0;
/** Create uniform buffer object. */
virtual UniformBuffer* CreateUniformBuffer(const UniformBufferDescriptor& descriptor) = 0;
/** Create vertex buffer object. */
virtual VertexBuffer* CreateVertexBuffer(const VertexBufferDescriptor& descriptor) = 0;
/** Destroy framebuffer object. */
virtual void DestroyFramebuffer(Framebuffer* framebuffer) = 0;
/** Destroy index buffer object. */
virtual void DestroyIndexBuffer(IndexBuffer* indexBuffer) = 0;
/** Destroy pipeline object. */
virtual void DestroyPipeline(Pipeline* pipeline) = 0;
/** Destroy texture object. */
virtual void DestroyTexture(Texture* texture) = 0;
/** Destroy uniform block object. */
virtual void DestroyUniformBlock(UniformBlock* uniformBlock) = 0;
/** Destroy uniform buffer object. */
virtual void DestroyUniformBuffer(UniformBuffer* uniformBuffer) = 0;
/** Destroy vertex buffer object. */
virtual void DestroyVertexBuffer(VertexBuffer* vertexBuffer) = 0;
/** Bind pipeline to draw queue. */
virtual void BindPipeline(Pipeline* pipeline) = 0;
/** Bind pipeline to draw queue. */
virtual void BindUniformBlock(UniformBlock* uniformBlock, const uint32_t offset = 0) = 0;
/** Begin and initialize rendering to framebuffers. */
virtual void BeginDraw() = 0;
/** Draw vertex buffer, using the current bound pipeline. */
virtual void DrawVertexBuffer(VertexBuffer* vertexBuffer) = 0;
/** Draw indexed vertex buffer, using the current bound pipeline. */
virtual void DrawVertexBuffer(IndexBuffer* indexBuffer, VertexBuffer* vertexBuffer) = 0;
/**
* Push constant values to shader stage.
* This function call has no effect if provided id argument is greater than the number of push constants in pipeline.
*
* @param id Id of push constant to update. This id can be shared between multiple shader stages.
*/
/**@{*/
virtual void PushConstant(const uint32_t location, const bool& value) = 0;
virtual void PushConstant(const uint32_t location, const int32_t& value) = 0;
virtual void PushConstant(const uint32_t location, const float& value) = 0;
virtual void PushConstant(const uint32_t location, const Vector2f32& value) = 0;
virtual void PushConstant(const uint32_t location, const Vector3f32& value) = 0;
virtual void PushConstant(const uint32_t location, const Vector4f32& value) = 0;
virtual void PushConstant(const uint32_t location, const Matrix4x4f32& value) = 0;
/**@}*/
/** Finalize and present rendering. */
virtual void EndDraw() = 0;
/** Sleep until the graphical device is ready. */
virtual void WaitForDevice() = 0;
/** Update uniform buffer data. */
virtual void UpdateUniformBuffer(UniformBuffer* uniformBuffer, const size_t offset, const size_t size, const void* data) = 0;
};
}
#endif
| 35.774359 | 133 | 0.672018 | [
"render",
"object"
] |
e514d1a6fbbb58569ada6f9f77b0feaf2919b595 | 2,595 | cc | C++ | src/json/src/json/stream/parse_stream/parser.cc | Oaticus/Deltatron | 88ac3b56d7e46fd66c3dcaeab5861c7f8016a736 | [
"BSD-2-Clause"
] | null | null | null | src/json/src/json/stream/parse_stream/parser.cc | Oaticus/Deltatron | 88ac3b56d7e46fd66c3dcaeab5861c7f8016a736 | [
"BSD-2-Clause"
] | null | null | null | src/json/src/json/stream/parse_stream/parser.cc | Oaticus/Deltatron | 88ac3b56d7e46fd66c3dcaeab5861c7f8016a736 | [
"BSD-2-Clause"
] | null | null | null | #include <dt/json/stream/parse_stream/parser.hh>
#include <dt/json/stream/parse_stream/parser/state.hh>
dt::json_object dt::parse_object(parser_state& state) {
auto new_obj = json_object{};
state.try_increment();
while (true) {
if (!state.current_token().has_type(token_type::String))
state.throw_error("Expected object entry or end of object");
auto new_key = *state.current_token().value_as<std::string>();
state.try_increment();
if (!state.current_token().has_type(token_type::Colon))
state.throw_error("Expected colon after object key");
state.try_increment();
switch(state.current_token().type()) {
case token_type::Bool: [[fallthrough]];
case token_type::Null: [[fallthrough]];
case token_type::Float: [[fallthrough]];
case token_type::String: [[fallthrough]];
case token_type::Integer: new_obj.emplace(new_key, json_container_imp(state.current_token())); break;
case token_type::LBrace: new_obj.emplace(new_key, json_container_imp(parse_object(state))); break;
case token_type::LBrack: new_obj.emplace(new_key, json_container_imp(parse_array(state))); break;
default: state.throw_error("Expected object entry value after colon");
}
state.try_increment();
if (!state.current_token().has_type(token_type::Comma)) {
if (!state.current_token().has_type(token_type::RBrace))
state.throw_error("Expected end of object or comma");
break;
}
state.try_increment();
}
return new_obj;
}
dt::json_array dt::parse_array(parser_state& state) {
auto new_arr = json_array{};
state.try_increment();
while (true) {
switch (state.current_token().type()) {
case token_type::Bool: [[fallthrough]];
case token_type::Null: [[fallthrough]];
case token_type::Float: [[fallthrough]];
case token_type::String: [[fallthrough]];
case token_type::Integer: new_arr.push_back(json_container_imp(state.current_token())); break;
case token_type::LBrace: new_arr.push_back(json_container_imp(parse_object(state))); break;
case token_type::LBrack: new_arr.push_back(json_container_imp(parse_array(state))); break;
default: state.throw_error("Expected array entry value or end of array");
}
if (!state.current_token().has_type(token_type::Comma)) {
if (!state.current_token().has_type(token_type::RBrack))
state.throw_error("Expected end of array or comma");
break;
}
state.try_increment();
}
return new_arr;
}
| 31.26506 | 107 | 0.676301 | [
"object"
] |
e515f139b8f7dd028390a403092882096ec67d29 | 2,953 | cpp | C++ | ZooidEngine/Scene/SceneComponent.cpp | azon04/Z0-Engine | 1a44781fb5308c11c3b63b954ad683a51e9ba271 | [
"MIT"
] | 4 | 2019-05-31T22:55:49.000Z | 2020-11-26T11:55:34.000Z | ZooidEngine/Scene/SceneComponent.cpp | azon04/Z0-Engine | 1a44781fb5308c11c3b63b954ad683a51e9ba271 | [
"MIT"
] | null | null | null | ZooidEngine/Scene/SceneComponent.cpp | azon04/Z0-Engine | 1a44781fb5308c11c3b63b954ad683a51e9ba271 | [
"MIT"
] | 1 | 2018-04-11T02:50:47.000Z | 2018-04-11T02:50:47.000Z | #include "SceneComponent.h"
#include "Events/Events.h"
namespace ZE {
IMPLEMENT_CLASS_1(SceneComponent, Component);
void SceneComponent::calculateTransform(const Matrix4x4& parentMat)
{
Matrix4x4::FastMul(parentMat, m_localTransform, m_cacheWorldMatrix);
}
void SceneComponent::setupComponent()
{
Component::setupComponent();
addEventDelegate(Event_UPDATE, &SceneComponent::handleUpdateEvent);
addEventDelegate(Event_CALC_TRANSFORM, &SceneComponent::handleCalculateTransform);
}
void SceneComponent::setLocalTransform(Matrix4x4& _localTransform)
{
m_localTransform = _localTransform;
// #TODO Calculate new world transform to its children
}
void SceneComponent::setWorldTransform(Matrix4x4& _worldTransform)
{
m_cacheWorldMatrix = _worldTransform;
// #TODO Calculate new world transform to its children
}
void SceneComponent::setWorldPosition(const Vector3& _worldPosition)
{
m_worldTransform.setPosition(_worldPosition);
m_bTransformDirty = true;
// #TODO Calculate new world transform to its children
}
void SceneComponent::handleUpdateEvent(Event* event)
{
}
void SceneComponent::handleCalculateTransform(Event* event)
{
updateCacheMatrix();
}
void SceneComponent::updateCacheMatrix()
{
if (m_bTransformDirty)
{
m_cacheWorldMatrix = m_worldTransform.toMatrix();
m_bTransformDirty = false;
}
}
void SceneComponent::setRelativePosition(const Vector3& _relativePosition)
{
m_localTransform.setPos(_relativePosition);
// #TODO Calculate new world transform to its children
}
void SceneComponent::setScale(const Vector3& _scale)
{
m_worldTransform.setScale(_scale);
m_bTransformDirty = true;
// #TODO Calculate new world transform to its children
}
void SceneComponent::rotateInDeg(const Vector3& _eulerAngle)
{
m_worldTransform.setRotation(_eulerAngle);
m_bTransformDirty = true;
// #TODO Calculate new world transform to its children
}
Vector3 SceneComponent::getRelativePosition() const
{
return m_localTransform.getPos();
}
Vector3 SceneComponent::getWorldPosition() const
{
if (m_bTransformDirty)
{
return m_worldTransform.getPosition();
}
return m_cacheWorldMatrix.getPos();
}
Vector3 SceneComponent::getForwardVector() const
{
if (m_bTransformDirty)
{
return m_worldTransform.m_quat.rotate(Vector3(0.0f, 0.0f, 1.0f));
}
return m_cacheWorldMatrix.getN();
}
Vector3 SceneComponent::getRightVector() const
{
if (m_bTransformDirty)
{
return m_worldTransform.m_quat.rotate(Vector3(1.0f, 0.0f, 0.0f));
}
return m_cacheWorldMatrix.getU();
}
Vector3 SceneComponent::getUpVector() const
{
if (m_bTransformDirty)
{
return m_worldTransform.m_quat.rotate(Vector3(0.0f, 1.0f, 0.0f));
}
return m_cacheWorldMatrix.getV();
}
Matrix4x4 SceneComponent::getLocalTransform()
{
return m_localTransform;
}
Matrix4x4 SceneComponent::getWorldTransform()
{
return m_cacheWorldMatrix;
}
} | 21.713235 | 84 | 0.757535 | [
"transform"
] |
e5172f024d021c9b232779588447a73fa75505b1 | 4,739 | cpp | C++ | tests/src/examples/observer_examples.cpp | YarikTH/ureact | a870c274ce9f84b9cc4fc9be41cb0a8922f2cf67 | [
"BSL-1.0"
] | 115 | 2021-01-07T15:36:13.000Z | 2022-03-07T15:34:52.000Z | tests/src/examples/observer_examples.cpp | YarikTH/ureact | a870c274ce9f84b9cc4fc9be41cb0a8922f2cf67 | [
"BSL-1.0"
] | 70 | 2021-01-09T18:08:11.000Z | 2022-03-27T18:35:55.000Z | tests/src/examples/observer_examples.cpp | YarikTH/ureact | a870c274ce9f84b9cc4fc9be41cb0a8922f2cf67 | [
"BSL-1.0"
] | 8 | 2021-06-16T13:08:58.000Z | 2021-09-07T11:14:19.000Z | //
// Copyright (C) 2020-2021 Krylov Yaroslav.
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#include "tests_stdafx.hpp"
#include "ureact/ureact.hpp"
TEST_SUITE( "Examples" )
{
TEST_CASE( "Observers" )
{
ureact::context ctx;
auto x = make_value( ctx, 0 );
auto identity = []( const int value ) { return value; };
std::vector<int> x_values;
auto on_x_value_change = [&]( const int new_value ) { x_values.push_back( new_value ); };
CHECK( x_values == std::vector<int>{} );
SUBCASE( "Subject-bound observers v1" )
{
// Inner scope
{
// Create a signal in the function scope
auto my_signal = make_function( x, identity );
// The lifetime of the observer is bound to my_signal.
// After scope my_signal is destroyed, and so is the observer
observe( my_signal, on_x_value_change );
x <<= 1; // output: 2
CHECK( x_values == std::vector<int>{ 1 } );
}
// ~Inner scope
x <<= 2; // no output
CHECK( x_values == std::vector<int>{ 1 } );
}
SUBCASE( "Subject-bound observers v2" )
{
// Outer scope
{
// Unbound observer
ureact::observer obs;
// Inner scope
{
auto my_signal = make_function( x, identity );
// Move-assign to obs
obs = observe( my_signal, on_x_value_change );
// The node linked to my_signal is now also owned by obs
x <<= 1; // output: 2
CHECK( x_values == std::vector<int>{ 1 } );
}
// ~Inner scope
// my_signal was destroyed, but as long as obs exists and is still
// attached to the signal node, this signal node won't be destroyed
x <<= 2; // output: 3
CHECK( x_values == std::vector<int>{ 1, 2 } );
}
// ~Outer scope
// obs was destroyed
// -> the signal node is no longer owned by anything and is destroyed
// -> the observer node is destroyed as it was bound to the subject
x <<= 3; // no output
CHECK( x_values == std::vector<int>{ 1, 2 } );
}
SUBCASE( "Detaching observers manually" )
{
ureact::observer obs = observe( x, on_x_value_change );
x <<= 1; // output: 2
CHECK( x_values == std::vector<int>{ 1 } );
obs.detach(); // detach the observer
x <<= 2; // no output
CHECK( x_values == std::vector<int>{ 1 } );
}
SUBCASE( "Using scoped observer" )
{
// Note the semantic difference between scoped_observer and observer.
//
// During its lifetime, the observer handle of an observer guarantees that the
// observed subject will not be destroyed and allows explicit detach.
// But even after the observer handle is destroyed, the subject may continue to exist
// and so will the observer.
//
// scoped_observer has similar semantics to a scoped lock.
// When it's destroyed, it detaches and destroys the observer.
// Inner scope
{
ureact::scoped_observer scoped_obs = observe( x, on_x_value_change );
x <<= 1; // output: 1
CHECK( x_values == std::vector<int>{ 1 } );
}
// ~Inner scope
x <<= 2; // no output
CHECK( x_values == std::vector<int>{ 1 } );
}
SUBCASE( "Detaching observers using return value" )
{
// Functor used for observer can optionally return value
// Using this value observer can be optionally self detached
ureact::observer obs = observe( x, [&]( const int v ) {
if( v < 0 )
{
return ureact::observer_action::stop_and_detach;
}
else
{
x_values.push_back( v );
return ureact::observer_action::next;
}
} );
x <<= 1;
x <<= 2;
x <<= 3;
x <<= -1;
x <<= 4;
CHECK( x_values == std::vector<int>{ 1, 2, 3 } );
}
}
}
| 30.184713 | 97 | 0.483435 | [
"vector"
] |
e522636a80d46e8f6f1b43c6942d2d54e1115677 | 1,540 | cpp | C++ | tools/libgtextutils-0.7/tests/test_natural_sort.cpp | benranco/test | 7cf9740108844da30dcc506e733015fd5dd76a05 | [
"MIT"
] | null | null | null | tools/libgtextutils-0.7/tests/test_natural_sort.cpp | benranco/test | 7cf9740108844da30dcc506e733015fd5dd76a05 | [
"MIT"
] | null | null | null | tools/libgtextutils-0.7/tests/test_natural_sort.cpp | benranco/test | 7cf9740108844da30dcc506e733015fd5dd76a05 | [
"MIT"
] | null | null | null | /*
Gordon's Text-Utilities Library
Copyright (C) 2009-2013 Assaf Gordon (assafgordon@gmail.com)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#include <vector>
#include <string>
#include <iostream>
#include <gtextutils/container_join.h>
#include <gtextutils/natsort.h>
/*
* Tiny test suite for natural sort
*/
using namespace std;
int main()
{
vector<string> v;
v.push_back("chr4");
v.push_back("chr2");
v.push_back("chr10");
v.push_back("chr11");
v.push_back("chr1");
v.push_back("chrX");
v.push_back("chr20");
v.push_back("ChR13");
sort(v.begin(), v.end());
cout << "Regular sort: " << join(v) << endl;
sort(v.begin(), v.end(), natural_sort_predicate() );
cout << "Natural sort (case sensitive): " << join(v) << endl;
sort(v.begin(), v.end(), natural_sort_ignore_case_predicate() );
cout << "Natural sort (case-insensitive): " << join(v) << endl;
return 0;
}
| 25.666667 | 78 | 0.68961 | [
"vector"
] |
e5255e847e86bc08f078df1fad24860b9c2a39a7 | 206 | cpp | C++ | llvm/test/tools/llvm-symbolizer/Inputs/split-dwarf-addr-object-relocation.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 4,812 | 2015-01-02T19:38:10.000Z | 2022-03-27T12:42:24.000Z | llvm/test/tools/llvm-symbolizer/Inputs/split-dwarf-addr-object-relocation.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 3,740 | 2019-01-23T15:36:48.000Z | 2022-03-31T22:01:13.000Z | llvm/test/tools/llvm-symbolizer/Inputs/split-dwarf-addr-object-relocation.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 2,543 | 2015-01-01T11:18:36.000Z | 2022-03-22T21:32:36.000Z | void f1();
__attribute__((always_inline)) void f2() {
f1();
}
void f3() {
f2();
}
// $ clang++ split-dwarf-addr-object-relocation.cpp -gsplit-dwarf -c Xclang \
// -fdebug-compilation-dir -Xclang .
| 18.727273 | 77 | 0.631068 | [
"object"
] |
e5255efb7acee2b9d77c414cc596df56b42848f3 | 1,047 | cpp | C++ | ejercicios/semana4/ex3.cpp | lschinchilla/FISI2028-202120 | 5c4a80494f5867a91786771f388e9e3c9ef20eb2 | [
"MIT"
] | 3 | 2021-08-17T19:19:11.000Z | 2021-11-08T12:26:41.000Z | ejercicios/semana4/ex3.cpp | lschinchilla/FISI2028-202120 | 5c4a80494f5867a91786771f388e9e3c9ef20eb2 | [
"MIT"
] | 12 | 2021-09-18T01:33:58.000Z | 2021-10-16T00:11:45.000Z | ejercicios/semana4/ex3.cpp | lschinchilla/FISI2028-202120 | 5c4a80494f5867a91786771f388e9e3c9ef20eb2 | [
"MIT"
] | 28 | 2021-09-17T22:38:23.000Z | 2021-10-02T19:59:49.000Z | #include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
struct Vector {
double *v;
uint n;
};
string print_vector(int* v, int);
int main(void){
// Review the averages problem
cout<< "Vamos a crear nuestra primera estructura!"<<endl;
Vector A;
cout<<"Tamaño de A: "<<sizeof(A)<<" bits."<<endl;
return 0;
}
#ifndef V_PRINT_WRAP_NUM // OJO: esto es de procesador
#define V_PRINT_WRAP_NUM 8
#endif
#ifndef V_PRINT_MAX_ROWS
#define V_PRINT_MAX_ROWS 16
#endif
string print_vector(int* v, int n){
ostringstream ss;
ss << "[" << ( n > V_PRINT_WRAP_NUM ? "\n ":" ");
for(int it = 0; it < n; it++){
ss << v[it] << (it != n-1 ? ", ":"\0");
if( (it+1) % V_PRINT_WRAP_NUM == 0 && it < n-1 )
ss << "\n ";
if( V_PRINT_MAX_ROWS > 0 && \
it == V_PRINT_MAX_ROWS*V_PRINT_WRAP_NUM ){
ss << "...";
break;
}
}
ss << ( n > V_PRINT_WRAP_NUM ? "\n":" ") << "]";
return ss.str();
}
| 22.76087 | 61 | 0.543457 | [
"vector"
] |
e52bd6e4b215741deb406f6942e04a5726604fd0 | 2,488 | cpp | C++ | AMDGraph.cpp | BorisNikulin/Path-Finding | 3c2a881d5d6f37152448d35508a3f00848301347 | [
"MIT"
] | null | null | null | AMDGraph.cpp | BorisNikulin/Path-Finding | 3c2a881d5d6f37152448d35508a3f00848301347 | [
"MIT"
] | null | null | null | AMDGraph.cpp | BorisNikulin/Path-Finding | 3c2a881d5d6f37152448d35508a3f00848301347 | [
"MIT"
] | null | null | null | #include "AMDGraph.h"
namespace pf
{
namespace graph
{
template<typename K, typename V>
AMDGraph<K, V>::AMDGraph()
{
}
template<typename K, typename V>
AMDGraph<K, V>& AMDGraph<K, V>::addVertex(const K& v)
{
vl.push_back(v);
am.reserve(vl.size());
std::for_each(am.begin(), am.end(), [&](std::vector<V>& v){v.reserve(vl.size());});
for(int i = 0; i < am.size() - 1; ++i)
{
am[vl.size() - 1][i] = nullptr;
am[i][vl.size() - 1] = nullptr;
}
am[vl.size() - 1][vl.size() - 1] = nullptr;
return this;
}
template<typename K, typename V>
bool AMDGraph<K, V>::addEdge(const K& v1, const K& v2, const V* weight)
{
typename std::vector<K>::iterator v1It = std::find(vl.begin(), vl.end(), v1);
typename std::vector<K>::iterator v2It = std::find(vl.begin(), vl.end(), v2);
if(v1It != vl.end() && v2It != vl.end())
{
*((am.begin() + v1It)->begin() + v2It) = weight;
return true;
}
return false;
}
template<typename K, typename V>
bool AMDGraph<K, V>::removeVertex(const K& v)
{
typename std::vector<K>::iterator it = std::find(vl.begin(), vl.end(), v);
if(it != vl.end())
{
vl.erase(it);
am.erase(am.begin() + it);
for(int i = 0; i < am.size(); ++i)
{
am[i].erase(am[i].begin() + it);
}
return true;
}
return false;
}
template<typename K, typename V>
bool AMDGraph<K, V>::removeEdge(const K& v1, const K& v2)
{
typename std::vector<K>::iterator v1It = std::find(vl.begin(), vl.end(), v1);
typename std::vector<K>::iterator v2It = std::find(vl.begin(), vl.end(), v2);
if(v1It != vl.end() && v2It != vl.end())
{
*((am.begin() + v1It)->begin() + v2It) = nullptr;
return true;
}
return false;
}
template<typename K, typename V>
std::list<Neighbor<K, V>>& AMDGraph<K, V>::getNeigbors(const K& v) const
{
typename std::list<Neighbor<K, V>> nbrs;
typename std::vector<K>::iterator it = std::find(vl.begin(), vl.end(), v);
for(int i = 0; i < vl.size(); ++i)
{
V*& edge = (am + it)[i];
if(edge != nullptr)
{
Neighbor<K, V> n{vl[i], edge};
nbrs.push_back(n);
}
}
return nbrs;
}
template<typename K, typename V>
AMDGraph<K, V>::~AMDGraph()
{
~vl();
for_each(am.begin(), am.end(), [&](std::vector<V>& v){~v();});
~am();
}
template<typename K, typename V>
std::ostream& operator<<(std::ostream& out, AMDGraph<K, V> graph)
{
//todo do the needfull
//todo make friend of AMDGraph?
return out;
}
}
}
| 21.084746 | 85 | 0.569936 | [
"vector"
] |
e5311ee7539feedb6a5c697ee75dfe0e1d6df084 | 11,894 | hpp | C++ | sources/Licensing/FsLocalStorage.hpp | palchukovsky/TunnelEx | ec645271ab8b79225e378345ff108795110c57de | [
"Apache-2.0"
] | null | null | null | sources/Licensing/FsLocalStorage.hpp | palchukovsky/TunnelEx | ec645271ab8b79225e378345ff108795110c57de | [
"Apache-2.0"
] | null | null | null | sources/Licensing/FsLocalStorage.hpp | palchukovsky/TunnelEx | ec645271ab8b79225e378345ff108795110c57de | [
"Apache-2.0"
] | null | null | null | /**************************************************************************
* Created: 2009/12/02 1:09
* Author: Eugene V. Palchukovsky
* E-mail: eugene@palchukovsky.com
* -------------------------------------------------------------------
* Project: TunnelEx
* URL: http://tunnelex.net
**************************************************************************/
#ifndef INCLUDED_FILE__TUNNELEX__FsLocalStorage_hpp__0912020109
#define INCLUDED_FILE__TUNNELEX__FsLocalStorage_hpp__0912020109
#include "License.hpp"
#include "KeyRetrievePolicies.hpp"
#include "CheckPolicies.hpp"
#include "Core/String.hpp"
namespace TunnelEx { namespace Licensing {
struct FsLocalStorageState {
FsLocalStorageState()
: licenseKeyModificationTime(0) {
//...//
}
time_t licenseKeyModificationTime;
};
template<class ClientTrait, bool isTestMode>
struct LocalStoragePolicy {
typedef typename ClientTrait::License License;
typedef typename ClientTrait::KeyRetrieve KeyRetrieve;
# pragma pack(push, 1)
struct LicenseDbHead {
LicenseDbHead()
: version(1),
modifTime(0),
privateKeyLen(0),
licenseKeyLen(0) {
//...//
}
unsigned short version;
time_t modifTime;
size_t privateKeyLen;
size_t licenseKeyLen;
char licenseUuid[36];
};
# pragma pack(pop)
static std::string GetDbDir() {
std::vector<char> buffer(MAX_PATH + 1, 0);
if (!SHGetSpecialFolderPathA(NULL, &buffer[0], CSIDL_COMMON_APPDATA, TRUE)) {
assert(false);
return std::string();
}
std::string result = &buffer[0];
result += "\\" TUNNELEX_NAME "\\";
return result;
}
inline static std::string GetDbFilePath() {
return std::string(GetDbDir() + "Service.license");
}
inline static time_t GetDbFileModificationTime() {
try {
return boost::filesystem::last_write_time(GetDbFilePath());
} catch (const std::exception &) {
return 0;
}
}
inline static void GetFileEncryptingKey(std::vector<unsigned char> &result) {
std::vector<unsigned char> key;
/*
GdsH1\[6r>Ua{Zt3cF7O?<N*OX1@6u57o20}mEOzn_'Trz`jOUY#w4}xt^MGv58np*nxB,VN_?*O7?oz'b0$(b?TwJ{H+!L2`5Se+IL''.uhck8s=m,]-F)h*8e@s!eeYw+S[m#y=`3c;;<7?sc?TNg&L$RL`EiuHc`v'<5z"x-;>ElQs"IQG:"k27G4`n^Q]62&6}3<gg#!/#>U4snizCfGhBLi46rOl-wJb+h}$D_U-G#,\^g9>"e6RQ:7,:>0
length: 256
*/
key.resize(174); key[173] = 'E'; key[172] = '>'; key.resize(246);
key[245] = '"'; key[25] = 'X'; key[55] = 'x'; key[107] = 'h';
key[37] = 'E'; key[8] = 'r'; key[94] = 'L'; key[244] = '>';
key[20] = '?'; key[220] = '4'; key[211] = 'i'; key[44] = 'r';
key[114] = ','; key[90] = '{'; key[39] = 'z'; key[84] = '(';
key[202] = '#'; key[174] = 'l'; key[100] = '+'; key[0] = 'G';
key[148] = 'T'; key[230] = 'h'; key[129] = 'w'; key[87] = 'T';
key[146] = 'c'; key[33] = '2'; key[108] = 'c'; key[47] = 'j';
key[179] = 'Q'; key[222] = 'r'; key[80] = '\''; key[135] = 'y';
key[233] = 'D'; key[185] = '7'; key[56] = 't'; key[164] = '\'';
key[168] = '"'; key[204] = '/'; key[183] = 'k'; key[24] = 'O';
key[92] = '+'; key[134] = '#'; key[214] = 'f'; key[187] = '4';
key.resize(253); key[252] = ','; key[18] = '7'; key[223] = 'O';
key[34] = '0'; key[112] = '='; key[58] = 'M'; key[159] = 'u';
key[119] = 'h'; key[149] = 'N'; key[184] = '2'; key[137] = '`';
key[166] = '5'; key[109] = 'k'; key[1] = 'd'; key[31] = '7';
key[188] = '`'; key[51] = '#'; key[26] = '1'; key[106] = 'u';
key[124] = 's'; key[59] = 'G'; key[38] = 'O'; key[104] = '\'';
key[13] = 'Z'; key[196] = '6'; key[4] = '1'; key[102] = 'L';
key[118] = ')'; key[139] = 'c'; key[16] = 'c'; key[241] = '^';
key[15] = '3'; key[157] = 'E'; key[243] = '9'; key[181] = ':';
key[203] = '!'; key[218] = 'L'; key[23] = '*'; key[36] = 'm';
key[42] = '\''; key[32] = 'o'; key[93] = '!'; key[228] = 'b';
key[65] = '*'; key[212] = 'z'; key[151] = '&'; key[175] = 'Q';
key[197] = '}'; key[49] = 'U'; key[48] = 'O'; key[61] = '5';
key[67] = 'x'; key[95] = '2'; key[205] = '#'; key[121] = '8';
key.resize(255); key[254] = '>'; key[250] = ':'; key[155] = 'L';
key[160] = 'H'; key[120] = '*'; key[224] = 'l'; key[150] = 'g';
key[170] = '-'; key[231] = '}'; key[123] = '@'; key[145] = 's';
key[103] = '\''; key[248] = 'R'; key[200] = 'g'; key[45] = 'z';
key[177] = '"'; key[216] = 'h'; key[97] = '5'; key[207] = 'U';
key[192] = ']'; key[21] = '<'; key[127] = 'e'; key[249] = 'Q';
key[130] = '+'; key[105] = '.'; key[69] = ','; key[161] = 'c';
key[198] = '3'; key[35] = '}'; key[50] = 'Y'; key[162] = '`';
key[246] = 'e'; key[71] = 'N'; key[11] = 'a'; key[215] = 'G';
key[82] = '0'; key[144] = '?'; key[133] = 'm'; key[180] = 'G';
key[41] = '_'; key[210] = 'n'; key[63] = 'n'; key.resize(256);
key[255] = '0'; key[253] = ':'; key[40] = 'n'; key[83] = '$';
key[229] = '+'; key[73] = '?'; key[237] = 'G'; key[5] = '\\';
key[10] = 'U'; key[117] = 'F'; key[115] = ']'; key[199] = '<';
key[242] = 'g'; key[57] = '^'; key[206] = '>'; key[191] = 'Q';
key[2] = 's'; key[110] = '8'; key[176] = 's'; key[189] = 'n';
key[226] = 'w'; key[152] = 'L'; key[221] = '6'; key[14] = 't';
key[68] = 'B'; key[30] = '5'; key[12] = '{'; key[128] = 'Y';
key[132] = '['; key[236] = '-'; key[29] = 'u'; key[167] = 'z';
key[54] = '}'; key[138] = '3'; key[163] = 'v'; key[17] = 'F';
key[76] = '7'; key[158] = 'i'; key[251] = '7'; key[99] = 'e';
key[209] = 's'; key[70] = 'V'; key[46] = '`'; key[126] = 'e';
key[66] = 'n'; key[111] = 's'; key[60] = 'v'; key[122] = 'e';
key[27] = '@'; key[178] = 'I'; key[147] = '?'; key[88] = 'w';
key[101] = 'I'; key[85] = 'b'; key[3] = 'H'; key[131] = 'S';
key[81] = 'b'; key[125] = '!'; key[116] = '-'; key[165] = '<';
key[28] = '6'; key[79] = 'z'; key[235] = 'U'; key[232] = '$';
key[74] = '*'; key[9] = '>'; key[169] = 'x'; key[186] = 'G';
key[201] = 'g'; key[193] = '6'; key[62] = '8'; key[53] = '4';
key[227] = 'J'; key[143] = '7'; key[77] = '?'; key[156] = '`';
key[225] = '-'; key[86] = '?'; key[195] = '&'; key[153] = '$';
key[91] = 'H'; key[72] = '_'; key[98] = 'S'; key[194] = '2';
key[6] = '['; key[89] = 'J'; key[19] = 'O'; key[136] = '=';
key[238] = '#'; key[43] = 'T'; key[182] = '"'; key[240] = '\\';
key[7] = '6'; key[234] = '_'; key[96] = '`'; key[113] = 'm';
key[22] = 'N'; key[217] = 'B'; key[142] = '<'; key[171] = ';';
key[213] = 'C'; key[154] = 'R'; key[219] = 'i'; key[78] = 'o';
key[52] = 'w'; key[239] = ','; key[208] = '4'; key[190] = '^';
key[247] = '6'; key[140] = ';'; key[64] = 'p'; key[141] = ';';
key[75] = 'O';
result.swap(key);
}
inline static void SetFileContent(
const LicenseDbHead &head,
const std::vector<unsigned char> &varData) {
assert(varData.size() == head.licenseKeyLen + head.privateKeyLen);
std::vector<unsigned char> fileKey;
GetFileEncryptingKey(fileKey);
std::ofstream f(GetDbFilePath().c_str(), std::ios::binary | std::ios::trunc);
size_t token = 0;
foreach (char ch, varData) {
ch ^= fileKey[token++ % fileKey.size()];
f << ch;
}
for (size_t i = 0; i < sizeof(LicenseDbHead); ++i) {
char ch = *(reinterpret_cast<const char *>(&head) + i);
ch ^= fileKey[token++ % fileKey.size()];
f << ch;
}
}
inline static bool GetFileContent(LicenseDbHead &head) {
std::vector<unsigned char> tmpVarData;
return GetFileContent(head, tmpVarData);
}
inline static bool GetFileContent(
LicenseDbHead &head,
std::vector<unsigned char> &varData) {
assert(varData.size() == head.licenseKeyLen + head.privateKeyLen);
std::vector<unsigned char> fileKey;
GetFileEncryptingKey(fileKey);
std::ifstream f(GetDbFilePath().c_str(), std::ios::binary);
f.unsetf(std::ios_base::skipws);
typedef std::istreambuf_iterator<char> Iter;
const Iter end;
size_t token = 0;
std::vector<unsigned char> decrypted;
for (Iter i = Iter(f); i != end; ++i) {
unsigned char ch = *i;
ch ^= fileKey[token++ % fileKey.size()];
decrypted.push_back(ch);
}
if (decrypted.size() < sizeof LicenseDbHead) {
return false;
}
LicenseDbHead headTmp;
memcpy(
&headTmp,
&*(decrypted.rbegin() + sizeof(LicenseDbHead) - 1),
sizeof(LicenseDbHead));
decrypted.resize(decrypted.size() - sizeof(LicenseDbHead));
head = headTmp;
decrypted.swap(varData);
return true;
}
inline static std::string GetTrialLicense() {
std::string result;
LicenseDbHead head;
std::vector<unsigned char> varData;
if (!GetFileContent(head, varData)) {
result = ConvertString<String>(Helpers::Uuid().GetAsString().c_str()).GetCStr();
memcpy(head.licenseUuid, result.c_str(), sizeof(head.licenseUuid));
SetFileContent(head, varData);
} else {
std::string(head.licenseUuid, head.licenseUuid + sizeof(head.licenseUuid))
.swap(result);
}
assert(result.size() == 36);
return result;
}
inline static std::string GetLicenseKey(const boost::any &clientParam) {
LicenseDbHead head;
std::vector<unsigned char> varData;
for (size_t i = 1; i <= 2; ++i) {
GetFileContent(head, varData);
break;
/* if (all.size()) {
break;
}
using namespace Crypto;
const Rsa rsa;
std::vector<unsigned char> key;
Seale seale(key, rsa.GetPublicKey());
std::string keyEncrypted(seale.GetSealed().begin(), seale.GetSealed().end());
copy(seale.GetEnvKey().begin(), seale.GetEnvKey().end(), back_inserter(keyEncrypted));
format keyFormated("%1%%2% %3% %4% %5%%1%\r\n%6%\r\n%1%%7% %3% %4% %5%%1%\r\n");
keyFormated
% "-----"
% "BEGIN"
% "TUNNELEX"
% "LICENSE"
% "KEY"
% keyEncrypted
% "END";
StoreLicenseKey(keyFormated.str(), rsa.GetPrivateKey().Export()); */
}
if (varData.size() < head.licenseKeyLen) {
License::RegisterError(
"1CE91D56-F2D9-4A5D-8C1B-3863C7206E66",
varData.size(),
clientParam);
return std::string();
}
return std::string(
varData.begin(),
varData.begin() + head.licenseKeyLen);
}
inline static std::string GetLocalAsymmetricPrivateKey(
const boost::any &clientParam) {
LicenseDbHead head;
std::vector<unsigned char> varData;
GetFileContent(head, varData);
if (varData.size() < head.licenseKeyLen + head.privateKeyLen) {
License::RegisterError(
"723181DF-962C-42B5-8E0B-0637AC722CDC",
varData.size(),
clientParam);
return std::string();
}
return std::string(
varData.begin() + head.licenseKeyLen,
varData.begin() + head.licenseKeyLen + head.privateKeyLen);
}
inline static void StoreLicenseKey(
const std::string &licenseKey,
const std::string &privateKey) {
LicenseDbHead head;
GetFileContent(head);
std::vector<unsigned char> varData(licenseKey.begin(), licenseKey.end());
copy(privateKey.begin(), privateKey.end(), back_inserter(varData));
head.licenseKeyLen = licenseKey.size();
head.privateKeyLen = privateKey.size();
const std::string license
= License::GetLicense(KeyRetrieve::Import(licenseKey, privateKey));
memcpy(head.licenseUuid, license.c_str(), sizeof(head.licenseUuid));
SetFileContent(head, varData);
}
inline static bool IsLicenseKeyChanged(const boost::any &clientParam) {
if (clientParam.empty()) {
return false;
}
FsLocalStorageState &state = *boost::any_cast<FsLocalStorageState *>(clientParam);
return state.licenseKeyModificationTime != GetDbFileModificationTime();
}
inline static void ResetLicenseKeyUpdateState(const boost::any &clientParam) {
if (clientParam.empty()) {
return;
}
FsLocalStorageState &state = *boost::any_cast<FsLocalStorageState *>(clientParam);
state.licenseKeyModificationTime = GetDbFileModificationTime();
}
};
} }
#endif // INCLUDED_FILE__TUNNELEX__FsLocalStorage_hpp__0912020109
| 37.639241 | 260 | 0.554902 | [
"vector"
] |
e53f3df463864ed5370eecdd8b71fa81d18da456 | 3,701 | cpp | C++ | Siv3D/src/Siv3D/Polygon/SivPolygon.cpp | azaika/OpenSiv3D | 2e8258ea15741b7dafa6637b50b43637f7b9923a | [
"MIT"
] | null | null | null | Siv3D/src/Siv3D/Polygon/SivPolygon.cpp | azaika/OpenSiv3D | 2e8258ea15741b7dafa6637b50b43637f7b9923a | [
"MIT"
] | null | null | null | Siv3D/src/Siv3D/Polygon/SivPolygon.cpp | azaika/OpenSiv3D | 2e8258ea15741b7dafa6637b50b43637f7b9923a | [
"MIT"
] | 1 | 2019-10-06T17:09:26.000Z | 2019-10-06T17:09:26.000Z | //-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2018 Ryo Suzuki
// Copyright (c) 2016-2018 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# include "CPolygon.hpp"
# include <Siv3D/Shape2D.hpp>
# include <Siv3D/Mouse.hpp>
# include <Siv3D/Cursor.hpp>
namespace s3d
{
Polygon::Polygon()
: pImpl(std::make_unique<CPolygon>())
{
}
Polygon::Polygon(const Polygon& polygon)
: Polygon()
{
pImpl->copyFrom(*polygon.pImpl);
}
Polygon::Polygon(Polygon&& polygon)
: Polygon()
{
pImpl->moveFrom(*polygon.pImpl);
}
Polygon::Polygon(const Vec2* outer, const size_t size, const Array<Array<Vec2>>& holes)
: pImpl(std::make_unique<CPolygon>(outer, size, holes))
{
}
Polygon::Polygon(const Shape2D& shape)
: pImpl(std::make_unique<CPolygon>(shape.vertices().data(), shape.vertices().size(), shape.indices()))
{
}
Polygon::~Polygon()
{
}
Polygon& Polygon::operator =(const Polygon& polygon)
{
pImpl->copyFrom(*polygon.pImpl);
return *this;
}
Polygon& Polygon::operator =(Polygon&& polygon)
{
pImpl->moveFrom(*polygon.pImpl);
return *this;
}
bool Polygon::isEmpty() const
{
return pImpl->outer().isEmpty();
}
bool Polygon::hasHoles() const
{
return !pImpl->inners().isEmpty();
}
void Polygon::swap(Polygon& polygon) noexcept
{
std::swap(pImpl, polygon.pImpl);
}
const Array<Vec2>& Polygon::outer() const
{
return pImpl->outer();
}
const Array<Array<Vec2>>& Polygon::inners() const
{
return pImpl->inners();
}
const Array<Float2>& Polygon::vertices() const
{
return pImpl->vertices();
}
const Array<uint32>& Polygon::indices() const
{
return pImpl->indices();
}
const RectF& Polygon::boundingRect() const
{
return pImpl->boundingRect();
}
size_t Polygon::num_triangles() const
{
return pImpl->indices().size() / 3;
}
Triangle Polygon::triangle(const size_t index) const
{
const auto& vertices = pImpl->vertices();
const auto& indices = pImpl->indices();
return{ vertices[indices[index * 3]], vertices[indices[index * 3 + 1]], vertices[indices[index * 3 + 2]] };
}
Polygon Polygon::movedBy(const double x, const double y) const
{
Polygon result(*this);
result.moveBy(x, y);
return result;
}
Polygon& Polygon::moveBy(const double x, const double y)
{
pImpl->moveBy(x, y);
return *this;
}
//double Polygon::area() const
//{
// return pImpl->area();
//}
//double Polygon::perimeter() const
//{
// return pImpl->perimeter();
//}
Vec2 Polygon::centroid() const
{
return pImpl->centroid();
}
Polygon Polygon::computeConvexHull() const
{
return pImpl->computeConvexHull();
}
bool Polygon::intersects(const Polygon& polygon) const
{
return pImpl->intersects(*polygon.pImpl);
}
bool Polygon::leftClicked() const
{
return MouseL.down() && mouseOver();
}
bool Polygon::leftPressed() const
{
return MouseL.pressed() && mouseOver();
}
bool Polygon::leftReleased() const
{
return MouseL.up() && mouseOver();
}
bool Polygon::rightClicked() const
{
return MouseR.down() && mouseOver();
}
bool Polygon::rightPressed() const
{
return MouseR.pressed() && mouseOver();
}
bool Polygon::rightReleased() const
{
return MouseR.up() && mouseOver();
}
bool Polygon::mouseOver() const
{
return Geometry2D::Intersect(Cursor::PosF(), *this);
}
const Polygon& Polygon::draw(const ColorF& color) const
{
pImpl->draw(color);
return *this;
}
const Polygon& Polygon::drawFrame(const double thickness, const ColorF& color) const
{
pImpl->drawFrame(thickness, color);
return *this;
}
}
| 17.62381 | 109 | 0.64415 | [
"shape"
] |
e54c776fa73496d6ed67cafb41036493ade28d00 | 2,352 | hpp | C++ | include/Utils.hpp | OnurKader/cgol | 47a277bcbef37530beac08929f7d382b8000f0c0 | [
"BSD-3-Clause",
"MIT"
] | null | null | null | include/Utils.hpp | OnurKader/cgol | 47a277bcbef37530beac08929f7d382b8000f0c0 | [
"BSD-3-Clause",
"MIT"
] | null | null | null | include/Utils.hpp | OnurKader/cgol | 47a277bcbef37530beac08929f7d382b8000f0c0 | [
"BSD-3-Clause",
"MIT"
] | null | null | null | #pragma once
#include <fstream>
#include <string>
#include <string_view>
#include <vector>
namespace cgol
{
static inline std::string read_file(std::string_view filename)
{
std::ifstream stream {filename.data()};
if(!stream)
{
throw std::runtime_error("Error: Could not open file to read");
}
return std::string {std::istreambuf_iterator<char>(stream), std::istreambuf_iterator<char>()};
}
static inline std::vector<std::string> split_string(const std::string& str,
std::string_view delimiter)
{
std::vector<std::string> strings;
std::string::size_type pos = 0;
std::string::size_type prev = 0;
while((pos = str.find(delimiter, prev)) != std::string::npos)
{
strings.push_back(str.substr(prev, pos - prev));
prev = pos + delimiter.size();
}
// To get the last substring (or only, if delimiter is not found)
strings.push_back(str.substr(prev));
return strings;
}
static inline void ltrim(std::string& s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](char ch) { return !std::isspace(ch); }));
}
static inline void rtrim(std::string& s)
{
s.erase(std::find_if(s.rbegin(), s.rend(), [](char ch) { return !std::isspace(ch); }).base(),
s.end());
}
static inline void trim(std::string& s)
{
ltrim(s);
rtrim(s);
}
static inline std::string ltrim_copy(std::string s)
{
ltrim(s);
return s;
}
static inline std::string rtrim_copy(std::string s)
{
rtrim(s);
return s;
}
static inline std::string trim_copy(std::string s)
{
trim(s);
return s;
}
static inline std::string strip_left(const std::string& input_string, std::string_view chars)
{
std::string result = input_string;
result.erase(result.begin(), std::find_if(result.begin(), result.end(), [&chars](char ch) {
return (!std::isspace(ch) && (chars.find(ch) == std::string::npos));
}));
return result;
}
static inline std::string strip_right(const std::string& input_string, std::string_view chars)
{
std::string result = input_string;
result.erase(std::find_if(result.rbegin(),
result.rend(),
[&chars](char ch) {
return (!std::isspace(ch) &&
(chars.find(ch) == std::string::npos));
})
.base(),
result.end());
return result;
}
static inline std::size_t parse_digit_from_char(char c) noexcept
{
return static_cast<std::size_t>(c - '0');
}
} // namespace cgol
| 22.834951 | 97 | 0.659439 | [
"vector"
] |
e54e32e9bf419c0dddb54a0015297041ebc51707 | 7,316 | cpp | C++ | test/testFeatureExtraction.cpp | liyi2017/StructSLAM | 7eb205489d7bde30ee74b08e72d01deaa42741fa | [
"MIT"
] | 43 | 2017-08-01T22:56:44.000Z | 2022-02-21T13:03:08.000Z | test/testFeatureExtraction.cpp | jyakaranda/StructSLAM | 7eb205489d7bde30ee74b08e72d01deaa42741fa | [
"MIT"
] | 1 | 2019-03-11T09:20:53.000Z | 2019-07-04T11:00:24.000Z | test/testFeatureExtraction.cpp | jyakaranda/StructSLAM | 7eb205489d7bde30ee74b08e72d01deaa42741fa | [
"MIT"
] | 30 | 2017-07-23T11:33:26.000Z | 2022-02-21T05:35:53.000Z | /***
* 本程序测试在EUROC数据集上双目特征提取部分算法
*/
#include<iostream>
#include<algorithm>
#include<fstream>
#include<chrono>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <common/include/ygz/Feature.h>
#include "ygz/Frame.h"
#include "ygz/Settings.h"
#include "ygz/ORBExtractor.h"
#include "ygz/EurocReader.h"
using namespace std;
using namespace ygz;
// 路径
string leftFolder = "/home/xiang/dataset/euroc/MH_01_easy/cam0/data";
string rightFolder = "/home/xiang/dataset/euroc/MH_01_easy/cam1/data";
string timeFolder = "./examples/EuRoC_TimeStamps/MH01.txt";
string configFile = "./examples/EuRoC.yaml";
string imuFolder = "/home/xiang/dataset/euroc/MH_01_easy/imu0/data.csv";
// string leftFolder = "/Users/gaoxiang/dataset/euroc/MH_01_easy/cam0/data";
// string rightFolder = "/Users/gaoxiang/dataset/euroc/MH_01_easy/cam1/data";
// string imuFolder = "/Users/gaoxiang/dataset/euroc/MH_01_easy/imu0/data.csv";
// string timeFolder = "./examples/EuRoC_TimeStamps/MH01.txt";
// string configFile = "./examples/EuRoC.yaml";
int main(int argc, char **argv) {
LOG(INFO) << "test feature extraction step in EuRoC" << endl;
// Retrieve paths to images
vector<string> vstrImageLeft;
vector<string> vstrImageRight;
vector<double> vTimeStamp;
VecIMU vimus;
LoadImages(leftFolder, rightFolder, timeFolder, vstrImageLeft, vstrImageRight, vTimeStamp);
LoadImus(imuFolder, vimus);
if (vstrImageLeft.empty() || vstrImageRight.empty()) {
cerr << "ERROR: No images in provided path." << endl;
return 1;
}
if (vstrImageLeft.size() != vstrImageRight.size()) {
cerr << "ERROR: Different number of left and right images." << endl;
return 1;
}
// Read rectification parameters
cv::FileStorage fsSettings(configFile, cv::FileStorage::READ);
if (!fsSettings.isOpened()) {
cerr << "ERROR: Wrong path to settings" << endl;
return -1;
}
cv::Mat K_l, K_r, P_l, P_r, R_l, R_r, D_l, D_r;
fsSettings["LEFT.K"] >> K_l;
fsSettings["RIGHT.K"] >> K_r;
fsSettings["LEFT.P"] >> P_l;
fsSettings["RIGHT.P"] >> P_r;
fsSettings["LEFT.R"] >> R_l;
fsSettings["RIGHT.R"] >> R_r;
fsSettings["LEFT.D"] >> D_l;
fsSettings["RIGHT.D"] >> D_r;
int rows_l = fsSettings["LEFT.height"];
int cols_l = fsSettings["LEFT.width"];
int rows_r = fsSettings["RIGHT.height"];
int cols_r = fsSettings["RIGHT.width"];
if (K_l.empty() || K_r.empty() || P_l.empty() || P_r.empty() || R_l.empty() || R_r.empty() || D_l.empty() ||
D_r.empty() ||
rows_l == 0 || rows_r == 0 || cols_l == 0 || cols_r == 0) {
cerr << "ERROR: Calibration parameters to rectify stereo are missing!" << endl;
return -1;
}
cv::Mat M1l, M2l, M1r, M2r;
cv::initUndistortRectifyMap(K_l, D_l, R_l, P_l.rowRange(0, 3).colRange(0, 3), cv::Size(cols_l, rows_l), CV_32F, M1l,
M2l);
cv::initUndistortRectifyMap(K_r, D_r, R_r, P_r.rowRange(0, 3).colRange(0, 3), cv::Size(cols_r, rows_r), CV_32F, M1r,
M2r);
const int nImages = vstrImageLeft.size();
// Create camera object
setting::initSettings();
float fx = fsSettings["Camera.fx"];
float fy = fsSettings["Camera.fy"];
float cx = fsSettings["Camera.cx"];
float cy = fsSettings["Camera.cy"];
shared_ptr<CameraParam> camera = make_shared<CameraParam>(fx, fy, cx, cy);
cout << endl << "-------" << endl;
cout << "Start processing sequence ..." << endl;
cout << "Images in the sequence: " << nImages << endl << endl;
// Main loop
cv::Mat imLeft, imRight, imLeftRect, imRightRect;
size_t imuIndex = 0;
// ORBExtractor extractor(ORBExtractor::ORB_SLAM2);
// ORBExtractor extractor(ORBExtractor::FAST_MULTI_LEVEL);
ORBExtractor extractor( ORBExtractor::FAST_SINGLE_LEVEL );
for (int ni = 0; ni < nImages; ni++) {
// Read left and right images from file
imLeft = cv::imread(vstrImageLeft[ni], CV_LOAD_IMAGE_UNCHANGED);
imRight = cv::imread(vstrImageRight[ni], CV_LOAD_IMAGE_UNCHANGED);
if (imLeft.empty()) {
cerr << endl << "Failed to load image at: "
<< string(vstrImageLeft[ni]) << endl;
return 1;
}
if (imRight.empty()) {
cerr << endl << "Failed to load image at: "
<< string(vstrImageRight[ni]) << endl;
return 1;
}
cv::remap(imLeft, imLeftRect, M1l, M2l, cv::INTER_LINEAR);
cv::remap(imRight, imRightRect, M1r, M2r, cv::INTER_LINEAR);
VecIMU vimu;
double tframe = vTimeStamp[ni];
while (1) {
const ygz::IMUData &imudata = vimus[imuIndex];
if (imudata.mfTimeStamp >= tframe)
break;
vimu.push_back(imudata);
imuIndex++;
}
shared_ptr<Frame> frame = make_shared<Frame>(imLeftRect, imRightRect, tframe, camera, vimu);
std::chrono::steady_clock::time_point t1 = std::chrono::steady_clock::now();
// do some operation
LOG(INFO) << "detecting features" << endl;
extractor.Detect(frame, true);
extractor.Detect(frame, false);
std::chrono::steady_clock::time_point t2 = std::chrono::steady_clock::now();
double timeCost = std::chrono::duration_cast<std::chrono::duration<double> >(t2 - t1).count();
LOG(INFO) << "time of feature extraction: " << timeCost << endl;
// show the result
LOG(INFO) << "showing features, size = " << frame->mFeaturesLeft.size() << endl;
Mat img_left;
cv::cvtColor(imLeftRect, img_left, cv::COLOR_GRAY2BGR);
for (shared_ptr<Feature> feature: frame->mFeaturesLeft) {
Vector3f color;
feature->mScore /= 100.;
if (feature->mScore < 0.5) {
color = Vector3f(0, 2 * feature->mScore, 1) * 255;
} else if (feature->mScore < 1) {
color = Vector3f(0, 1, 1 - 2 * (feature->mScore - 0.5)) * 255;
} else {
color = Vector3f(0, 1, 0) * 255;
}
cv::circle(img_left, cv::Point2f(feature->mPixel[0], feature->mPixel[1]), 1,
cv::Scalar(color[0], color[1], color[2]), 2);
}
cv::imshow("Feature Left", img_left);
Mat img_right;
cv::cvtColor(imRightRect, img_right, cv::COLOR_GRAY2BGR);
for (shared_ptr<Feature> feature: frame->mFeaturesRight) {
feature->mScore /= 100.;
Vector3f color;
if (feature->mScore < 0.5) {
color = Vector3f(0, 2 * feature->mScore, 1) * 255;
} else if (feature->mScore < 1) {
color = Vector3f(0, 1, 1 - 2 * (feature->mScore - 0.5)) * 255;
} else {
color = Vector3f(0, 1, 0) * 255;
}
cv::circle(img_right, cv::Point2f(feature->mPixel[0], feature->mPixel[1]), 1,
cv::Scalar(color[0], color[1], color[2]), 2);
}
cv::imshow("Feature Right", img_right);
cv::waitKey(1);
}
setting::destroySettings();
return 0;
}
| 34.838095 | 120 | 0.593357 | [
"object",
"vector"
] |
e54f536b84f9f99ad84eb02e132f9af9107f4b3d | 8,406 | hpp | C++ | phosphor-power-supply/psu_manager.hpp | openbmc/phosphor-power | b85b9dded072889faf937e29af32b2600dcc8d64 | [
"Apache-2.0"
] | 7 | 2019-10-04T01:19:49.000Z | 2021-06-02T23:11:19.000Z | phosphor-power-supply/psu_manager.hpp | openbmc/phosphor-power | b85b9dded072889faf937e29af32b2600dcc8d64 | [
"Apache-2.0"
] | 9 | 2019-10-23T14:22:03.000Z | 2022-03-22T20:39:05.000Z | phosphor-power-supply/psu_manager.hpp | openbmc/phosphor-power | b85b9dded072889faf937e29af32b2600dcc8d64 | [
"Apache-2.0"
] | 11 | 2019-10-04T01:20:01.000Z | 2022-03-03T06:08:16.000Z | #pragma once
#include "power_supply.hpp"
#include "types.hpp"
#include "utility.hpp"
#include <phosphor-logging/log.hpp>
#include <sdbusplus/bus/match.hpp>
#include <sdeventplus/event.hpp>
#include <sdeventplus/utility/timer.hpp>
struct sys_properties
{
int powerSupplyCount;
std::vector<uint64_t> inputVoltage;
};
using namespace phosphor::power::psu;
using namespace phosphor::logging;
namespace phosphor::power::manager
{
// Validation timeout. Allow 10s to detect if new EM interfaces show up in D-Bus
// before performing the validation.
constexpr auto validationTimeout = std::chrono::seconds(10);
/**
* @class PSUManager
*
* This class will create an object used to manage and monitor a list of power
* supply devices.
*/
class PSUManager
{
public:
PSUManager() = delete;
~PSUManager() = default;
PSUManager(const PSUManager&) = delete;
PSUManager& operator=(const PSUManager&) = delete;
PSUManager(PSUManager&&) = delete;
PSUManager& operator=(PSUManager&&) = delete;
/**
* Constructor to read configuration from D-Bus.
*
* @param[in] bus - D-Bus bus object
* @param[in] e - event object
*/
PSUManager(sdbusplus::bus::bus& bus, const sdeventplus::Event& e);
/**
* Get PSU properties from D-Bus, use that to build a power supply
* object.
*
* @param[in] properties - A map of property names and values
*
*/
void getPSUProperties(util::DbusPropertyMap& properties);
/**
* Get PSU configuration from D-Bus
*/
void getPSUConfiguration();
/**
* @brief Initialize the system properties from the Supported Configuration
* D-Bus object provided by Entity Manager.
*/
void getSystemProperties();
/**
* Initializes the manager.
*
* Get current BMC state, ...
*/
void initialize()
{
// When state = 1, system is powered on
int32_t state = 0;
try
{
// Use getProperty utility function to get power state.
util::getProperty<int32_t>(POWER_IFACE, "state", POWER_OBJ_PATH,
powerService, bus, state);
if (state)
{
powerOn = true;
validationTimer->restartOnce(validationTimeout);
}
else
{
powerOn = false;
runValidateConfig = true;
}
}
catch (const std::exception& e)
{
log<level::INFO>("Failed to get power state. Assuming it is off.");
powerOn = false;
runValidateConfig = true;
}
onOffConfig(phosphor::pmbus::ON_OFF_CONFIG_CONTROL_PIN_ONLY);
clearFaults();
updateInventory();
}
/**
* Starts the timer to start monitoring the list of devices.
*/
int run()
{
return timer->get_event().loop();
}
/**
* Write PMBus ON_OFF_CONFIG
*
* This function will be called to cause the PMBus device driver to send the
* ON_OFF_CONFIG command. Takes one byte of data.
*/
void onOffConfig(const uint8_t data)
{
for (auto& psu : psus)
{
psu->onOffConfig(data);
}
}
/**
* This function will be called in various situations in order to clear
* any fault status bits that may have been set, in order to start over
* with a clean state. Presence changes and power state changes will want
* to clear any faults logged.
*/
void clearFaults()
{
for (auto& psu : psus)
{
psu->clearFaults();
}
}
private:
/**
* The D-Bus object
*/
sdbusplus::bus::bus& bus;
/**
* The timer that runs to periodically check the power supplies.
*/
std::unique_ptr<
sdeventplus::utility::Timer<sdeventplus::ClockId::Monotonic>>
timer;
/**
* The timer that performs power supply validation as the entity manager
* interfaces show up in d-bus.
*/
std::unique_ptr<
sdeventplus::utility::Timer<sdeventplus::ClockId::Monotonic>>
validationTimer;
/**
* Create an error
*
* @param[in] faultName - 'name' message for the BMC error log entry
* @param[in,out] additionalData - The AdditionalData property for the error
*/
void createError(const std::string& faultName,
std::map<std::string, std::string>& additionalData);
/**
* Analyze the status of each of the power supplies.
*
* Log errors for faults, when and where appropriate.
*/
void analyze();
/** @brief True if the power is on. */
bool powerOn = false;
/** @brief Used as part of subscribing to power on state changes*/
std::string powerService;
/** @brief Used to subscribe to D-Bus power on state changes */
std::unique_ptr<sdbusplus::bus::match_t> powerOnMatch;
/** @brief Used to subscribe to Entity Manager interfaces added */
std::unique_ptr<sdbusplus::bus::match_t> entityManagerIfacesAddedMatch;
/**
* @brief Callback for power state property changes
*
* Process changes to the powered on state property for the system.
*
* @param[in] msg - Data associated with the power state signal
*/
void powerStateChanged(sdbusplus::message::message& msg);
/**
* @brief Callback for entity-manager interface added
*
* Process the information from the supported configuration and or IBM CFFPS
* Connector interface being added.
*
* @param[in] msg - Data associated with the interfaces added signal
*/
void entityManagerIfaceAdded(sdbusplus::message::message& msg);
/**
* @brief Adds properties to the inventory.
*
* Reads the values from the devices and writes them to the associated
* power supply D-Bus inventory objects.
*
* This needs to be done on startup, and each time the presence state
* changes.
*/
void updateInventory()
{
for (auto& psu : psus)
{
psu->updateInventory();
}
}
/**
* @brief Helper function to populate the system properties
*
* @param[in] properties - A map of property names and values
*/
void populateSysProperties(const util::DbusPropertyMap& properties);
/**
* @brief Perform power supply configuration validation.
* @details Validates if the existing power supply properties are a
* supported configuration, and acts on its findings such as logging errors.
*/
void validateConfig();
/**
* @brief Flag to indicate if the validateConfig() function should be run.
* Set to false once the configuration has been validated to avoid running
* multiple times due to interfaces added signal. Set to true during power
* off to trigger the validation on power on.
*/
bool runValidateConfig = true;
/**
* @brief Check that all PSUs have the same model name and that the system
* has the required number of PSUs present as specified in the Supported
* Configuration interface.
*
* @param[out] additionalData - Contains debug information on why the check
* might have failed. Can be used to fill in error logs.
* @return true if all the required PSUs are present, false otherwise.
*/
bool hasRequiredPSUs(std::map<std::string, std::string>& additionalData);
/**
* @brief Helper function to validate that all PSUs have the same model name
*
* @param[out] model - The model name. Empty if there is a mismatch.
* @param[out] additionalData - If there is a mismatch, it contains debug
* information such as the mismatched model name.
* @return true if all the PSUs have the same model name, false otherwise.
*/
bool validateModelName(std::string& model,
std::map<std::string, std::string>& additionalData);
/**
* @brief Map of supported PSU configurations that include the model name
* and their properties.
*/
std::map<std::string, sys_properties> supportedConfigs;
/**
* @brief The vector for power supplies.
*/
std::vector<std::unique_ptr<PowerSupply>> psus;
};
} // namespace phosphor::power::manager
| 29.086505 | 80 | 0.620985 | [
"object",
"vector",
"model"
] |
e551927c6319817f3bcbaec3b3619e608730a1fc | 3,618 | cpp | C++ | 051. N-Queens AC 1+ [Counting, DFS, Math, Stack].cpp | Lywx/CppLeetcode | ad80eb8305f2317ca7d3712976c82cffdf2046fc | [
"MIT"
] | null | null | null | 051. N-Queens AC 1+ [Counting, DFS, Math, Stack].cpp | Lywx/CppLeetcode | ad80eb8305f2317ca7d3712976c82cffdf2046fc | [
"MIT"
] | null | null | null | 051. N-Queens AC 1+ [Counting, DFS, Math, Stack].cpp | Lywx/CppLeetcode | ad80eb8305f2317ca7d3712976c82cffdf2046fc | [
"MIT"
] | null | null | null | #include <vector>
#include <algorithm>
#include <list>
using namespace std;
// NOTE(Wuxiang): You would like to avoid store a board structure in this problem.
// Because the queen collision detection can be done in constant time even you don't
// have a structure for a board. You don't want to waste time in maintain the
// validity of the board structure.
class Solution
{
public:
list<vector<pair<int, int>>> queenArrangementList;
vector<pair<int, int>> queenArrangementCurrent;
vector<vector<string>> queenResultList;
vector<string> queenResultTemplate;
bool canQueenAttack(int rowIndexQueen, int columnIndexQueen, int rowIndexTarget, int columnIndexTarget)
{
int rowDiff = rowIndexQueen - rowIndexTarget;
int columnDiff = columnIndexQueen - columnIndexTarget;
return rowDiff == 0
|| columnDiff == 0
|| rowDiff == columnDiff
|| rowDiff == -columnDiff;
}
// NOTE(Wuxiang): The improvement of this routine over "051. N-Queens AC 1 [Counting, DFS, Stack]" is
// that this routine use the notion of one queen per row. As a result, we avoid
// looping though rows altogether.
void chooseQueen(int rowOffset, int columnOffset, int rowNum, int columnNum)
{
// Termination condition
if (queenArrangementCurrent.size() == rowNum)
{
queenArrangementList.push_back(queenArrangementCurrent);
return;
}
for (int columnIndex = columnOffset; columnIndex < columnNum; ++columnIndex)
{
if (queenArrangementCurrent.empty())
{
queenArrangementCurrent.push_back(make_pair(rowOffset, columnIndex));
chooseQueen(rowOffset + 1, 0, rowNum, columnNum);
queenArrangementCurrent.pop_back();
}
else
{
bool queenCanAttackIsNone = true;
for (int queenIndex = 0; queenIndex < int(queenArrangementCurrent.size()); ++queenIndex)
{
pair<int, int> q = queenArrangementCurrent[queenIndex];
if (canQueenAttack(q.first, q.second, rowOffset, columnIndex))
{
queenCanAttackIsNone = false;
break;
}
}
if (queenCanAttackIsNone)
{
queenArrangementCurrent.push_back(make_pair(rowOffset, columnIndex));
chooseQueen(rowOffset + 1, 0, rowNum, columnNum);
queenArrangementCurrent.pop_back();
}
}
}
}
void prepareResult(int rowNum, int columnNum)
{
typedef list<vector<pair<int, int>>>::iterator Iter;
queenResultTemplate.assign(rowNum, string(columnNum, '.'));
for (Iter iter = queenArrangementList.begin(); iter != queenArrangementList.end(); ++iter)
{
vector<string> queenArrangementResult = queenResultTemplate;
for (int queenIndex = 0; queenIndex < int(iter->size()); ++queenIndex)
{
pair<int, int> q = (*iter)[queenIndex];
queenArrangementResult[q.first][q.second] = 'Q';
}
queenResultList.push_back(queenArrangementResult);
}
}
vector<vector<string>> solveNQueens(int n)
{
int rowNum = n;
int columnNum = n;
chooseQueen(0, 0, rowNum, columnNum);
prepareResult(rowNum, columnNum);
return queenResultList;
}
}; | 32.594595 | 107 | 0.587341 | [
"vector"
] |
e554c84fb70321458d3591a0ec0c575bc42c6416 | 20,351 | cpp | C++ | mysql-dst/mysql-cluster/storage/ndb/tools/ndb_index_stat.cpp | SJTU-IPADS/dst | 897b929a692642cbf295c105d9d6e64090abb673 | [
"Apache-2.0"
] | 9 | 2020-12-17T01:59:13.000Z | 2022-03-30T16:25:08.000Z | mysql-dst/mysql-cluster/storage/ndb/tools/ndb_index_stat.cpp | SJTU-IPADS/dst | 897b929a692642cbf295c105d9d6e64090abb673 | [
"Apache-2.0"
] | 1 | 2021-07-30T12:06:33.000Z | 2021-07-31T10:16:09.000Z | mysql-dst/mysql-cluster/storage/ndb/tools/ndb_index_stat.cpp | SJTU-IPADS/dst | 897b929a692642cbf295c105d9d6e64090abb673 | [
"Apache-2.0"
] | 1 | 2021-08-01T13:47:07.000Z | 2021-08-01T13:47:07.000Z | /* Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */
#include <ndb_global.h>
#include <ndb_opts.h>
#include <NdbOut.hpp>
#include <NdbApi.hpp>
#include <NDBT.hpp>
#include <NdbIndexStatImpl.hpp>
#include <ndb_rand.h>
// stats options
static const char* _dbname = 0;
static my_bool _delete = false;
static my_bool _update = false;
static my_bool _dump = false;
static int _query = 0;
static int _stats_any = 0;
// sys options
static my_bool _sys_drop = false;
static my_bool _sys_create = false;
static my_bool _sys_create_if_not_exist = false;
static my_bool _sys_create_if_not_valid = false;
static my_bool _sys_check = false;
static my_bool _sys_skip_tables = false;
static my_bool _sys_skip_events = false;
static int _sys_any = 0;
// other
static my_bool _verbose = false;
static int _loops = 1;
static Ndb_cluster_connection* g_ncc = 0;
static Ndb* g_ndb = 0;
static Ndb* g_ndb_sys = 0;
static NdbDictionary::Dictionary* g_dic = 0;
static NdbIndexStat* g_is = 0;
static const char* g_tabname = 0;
static const NdbDictionary::Table* g_tab = 0;
static int g_indcount = 0;
static const char** g_indnames = 0;
static const NdbDictionary::Index** g_indlist = 0;
// current index in loop
static const char* g_indname = 0;
static const NdbDictionary::Index* g_ind = 0;
#define CHK1(b) \
if (!(b)) { \
ret = -1; \
break; \
}
#define CHK2(b, e) \
if (!(b)) { \
g_err << "ERR: " << #b << " failed at line " << __LINE__ \
<< ": " << e << endl; \
ret = -1; \
break; \
}
inline void ndb_end_and_exit(int exitcode)
{
ndb_end(0);
exit(exitcode);
}
static NdbError
getNdbError(Ndb_cluster_connection* ncc)
{
NdbError err;
err.code = g_ncc->get_latest_error();
err.message = g_ncc->get_latest_error_msg();
return err;
}
static int
doconnect()
{
int ret = 0;
do
{
g_ncc = new Ndb_cluster_connection(opt_ndb_connectstring);
CHK2(g_ncc->connect(opt_connect_retries - 1, opt_connect_retry_delay) == 0, getNdbError(g_ncc));
CHK2(g_ncc->wait_until_ready(30, 10) == 0, getNdbError(g_ncc));
if (!_sys_any)
{
g_ndb = new Ndb(g_ncc, _dbname);
CHK2(g_ndb->init() == 0, g_ndb->getNdbError());
CHK2(g_ndb->waitUntilReady(30) == 0, g_ndb->getNdbError());
g_dic = g_ndb->getDictionary();
}
g_ndb_sys = new Ndb(g_ncc, NDB_INDEX_STAT_DB);
CHK2(g_ndb_sys->init() == 0, g_ndb_sys->getNdbError());
CHK2(g_ndb_sys->waitUntilReady(30) == 0, g_ndb_sys->getNdbError());
g_is = new NdbIndexStat;
g_info << "connected" << endl;
}
while (0);
return ret;
}
static void
dodisconnect()
{
delete g_is;
delete g_ndb_sys;
delete g_ndb;
delete g_ncc;
g_info << "disconnected" << endl;
}
static const char*
format(Uint64 us64, char* buf)
{
Uint32 ms = (Uint32)(us64 / (Uint64)1000);
Uint32 us = (Uint32)(us64 % (Uint64)1000);
sprintf(buf, "%u.%03u", ms, us);
return buf;
}
static const char*
format(double x, char* buf)
{
sprintf(buf, "%.02f", x);
return buf;
}
static void
show_head(const NdbIndexStat::Head& head)
{
setOutputLevel(2);
g_info << "table:" << g_tabname;
g_info << " index:" << g_indname;
g_info << " fragCount:" << head.m_fragCount;
g_info << endl;
g_info << "sampleVersion:" << head.m_sampleVersion;
g_info << " loadTime:" << head.m_loadTime;
g_info << " sampleCount:" << head.m_sampleCount;
g_info << " keyBytes:" << head.m_keyBytes;
g_info << endl;
setOutputLevel(_verbose ? 2 : 0);
}
static void
show_cache_info(const char* name, const NdbIndexStat::CacheInfo& info)
{
Uint64 us64;
char buf[100];
setOutputLevel(2);
g_info << name << ":";
g_info << " valid:" << info.m_valid;
g_info << " sampleCount:" << info.m_sampleCount;
g_info << " totalBytes:" << info.m_totalBytes;
g_info << endl;
g_info << "times in ms:";
g_info << " save: " << format(info.m_save_time, buf);
g_info << " sort: " << format(info.m_sort_time, buf);
if (info.m_sampleCount != 0)
{
us64 = info.m_sort_time / (Uint64)info.m_sampleCount;
g_info << " sort per sample: " << format(us64, buf);
}
g_info << endl;
setOutputLevel(_verbose ? 2 : 0);
}
static void
show_cache_entry(const NdbIndexStatImpl::CacheIter& iter)
{
setOutputLevel(2);
const NdbPack::DataC& key = iter.m_keyData;
const NdbPack::DataC& value = iter.m_valueData;
char buf[8000];
key.print(buf, sizeof(buf));
g_info << "key:" << buf << endl;
value.print(buf, sizeof(buf));
g_info << "value:" << buf << endl;
setOutputLevel(_verbose ? 2 : 0);
}
static int
doquery()
{
int ret = 0;
char buf[100];
Uint8 b_lo_buffer[NdbIndexStat::BoundBufferBytes];
Uint8 b_hi_buffer[NdbIndexStat::BoundBufferBytes];
NdbIndexStat::Bound b_lo(g_is, b_lo_buffer);
NdbIndexStat::Bound b_hi(g_is, b_hi_buffer);
do
{
NdbIndexStat::Range r(b_lo, b_hi);
Uint8 s_buffer[NdbIndexStat::StatBufferBytes];
NdbIndexStat::Stat s(s_buffer);
for (int n = 0; n < _query; n++)
{
g_is->reset_range(r);
for (int i = 0; i <= 1; i++)
{
NdbIndexStat::Bound& b = (i == 0 ? b_lo : b_hi);
if (ndb_rand() % 3 != 0)
{
if (ndb_rand() % 3 != 0)
{
Uint32 x = ndb_rand();
CHK2(g_is->add_bound(b, &x) == 0, g_is->getNdbError());
}
else
{
CHK2(g_is->add_bound_null(b) == 0, g_is->getNdbError());
}
bool strict = (ndb_rand() % 2 == 0);
g_is->set_bound_strict(b, strict);
}
}
CHK2(ret == 0, "failed");
CHK2(g_is->finalize_range(r) == 0, g_is->getNdbError());
CHK2(g_is->query_stat(r, s) == 0, g_is->getNdbError());
double rir = -1.0;
NdbIndexStat::get_rir(s, &rir);
g_info << "rir: " << format(rir, buf) << endl;
}
CHK2(ret == 0, "failed");
}
while (0);
return ret;
}
static int
dostats(int i)
{
int ret = 0;
do
{
g_indname = g_indnames[i];
g_ind = g_indlist[i];
g_is->reset_index();
CHK2(g_is->set_index(*g_ind, *g_tab) == 0, g_is->getNdbError());
if (_delete)
{
g_info << g_indname << ": delete stats" << endl;
if (ndb_rand() % 2 == 0)
{
CHK2(g_dic->deleteIndexStat(*g_ind, *g_tab) == 0, g_dic->getNdbError());
}
else
{
CHK2(g_is->delete_stat(g_ndb_sys) == 0, g_is->getNdbError());
}
}
if (_update)
{
g_info << g_indname << ": update stats" << endl;
if (ndb_rand() % 2 == 0)
{
CHK2(g_dic->updateIndexStat(*g_ind, *g_tab) == 0, g_dic->getNdbError());
}
else
{
CHK2(g_is->update_stat(g_ndb_sys) == 0, g_is->getNdbError());
}
}
NdbIndexStat::Head head;
g_is->read_head(g_ndb_sys);
g_is->get_head(head);
CHK2(head.m_found != -1, g_is->getNdbError());
if (head.m_found == false)
{
g_info << "no stats" << endl;
break;
}
show_head(head);
g_info << "read stats" << endl;
CHK2(g_is->read_stat(g_ndb_sys) == 0, g_is->getNdbError());
g_is->move_cache();
g_is->clean_cache();
g_info << "query cache created" << endl;
NdbIndexStat::CacheInfo infoQuery;
g_is->get_cache_info(infoQuery, NdbIndexStat::CacheQuery);
show_cache_info("query cache", infoQuery);
if (_dump)
{
NdbIndexStatImpl& impl = g_is->getImpl();
NdbIndexStatImpl::CacheIter iter(impl);
CHK2(impl.dump_cache_start(iter) == 0, g_is->getNdbError());
while (impl.dump_cache_next(iter) == true)
{
show_cache_entry(iter);
}
}
if (_query > 0)
{
CHK2(doquery() == 0, "failed");
}
}
while (0);
return ret;
}
static int
dostats()
{
int ret = 0;
do
{
for (int i = 0; i < g_indcount; i++)
{
CHK1(dostats(i) == 0);
}
CHK1(ret == 0);
}
while (0);
return ret;
}
static int
checkobjs()
{
int ret = 0;
do
{
CHK2((g_tab = g_dic->getTable(g_tabname)) != 0,
g_tabname << ": " << g_dic->getNdbError());
if (g_indcount == 0)
{
NdbDictionary::Dictionary::List list;
CHK2(g_dic->listIndexes(list, g_tabname) == 0, g_dic->getNdbError());
const int count = list.count;
g_indnames = (const char**)malloc(sizeof(char*) * count);
CHK2(g_indnames != 0, "out of memory");
for (int i = 0; i < count; i++)
{
const NdbDictionary::Dictionary::List::Element& e = list.elements[i];
if (e.type == NdbDictionary::Object::OrderedIndex)
{
g_indnames[g_indcount] = strdup(e.name);
CHK2(g_indnames[g_indcount] != 0, "out of memory");
g_indcount++;
}
}
CHK1(ret == 0);
}
g_indlist = (const NdbDictionary::Index**)malloc(sizeof(NdbDictionary::Index*) * g_indcount);
CHK2(g_indlist != 0, "out of memory");
for (int i = 0; i < g_indcount; i++)
{
CHK2((g_indlist[i] = g_dic->getIndex(g_indnames[i], g_tabname)) != 0,
g_tabname << "." << g_indnames[i] << ": " << g_dic->getNdbError());
}
}
while (0);
return ret;
}
static int
dosys()
{
int ret = 0;
do
{
if (_sys_drop)
{
if (!_sys_skip_events)
{
g_info << "dropping sys events" << endl;
CHK2(g_is->drop_sysevents(g_ndb_sys) == 0, g_is->getNdbError());
CHK2(g_is->check_sysevents(g_ndb_sys) == -1, "unexpected success");
CHK2(g_is->getNdbError().code == NdbIndexStat::NoSysEvents,
"unexpected error: " << g_is->getNdbError());
}
if (!_sys_skip_tables)
{
g_info << "dropping all sys tables" << endl;
CHK2(g_is->drop_systables(g_ndb_sys) == 0, g_is->getNdbError());
CHK2(g_is->check_systables(g_ndb_sys) == -1, "unexpected success");
CHK2(g_is->getNdbError().code == NdbIndexStat::NoSysTables,
"unexpected error: " << g_is->getNdbError());
}
g_info << "drop done" << endl;
}
if (_sys_create)
{
if (!_sys_skip_tables)
{
g_info << "creating all sys tables" << endl;
CHK2(g_is->create_systables(g_ndb_sys) == 0, g_is->getNdbError());
CHK2(g_is->check_systables(g_ndb_sys) == 0, g_is->getNdbError());
}
if (!_sys_skip_events)
{
g_info << "creating sys events" << endl;
CHK2(g_is->create_sysevents(g_ndb_sys) == 0, g_is->getNdbError());
CHK2(g_is->check_sysevents(g_ndb_sys) == 0, g_is->getNdbError());
g_info << "create done" << endl;
}
}
if (_sys_create_if_not_exist)
{
if (!_sys_skip_tables)
{
if (g_is->check_systables(g_ndb_sys) == -1)
{
CHK2(g_is->getNdbError().code == NdbIndexStat::NoSysTables,
g_is->getNdbError());
g_info << "creating all sys tables" << endl;
CHK2(g_is->create_systables(g_ndb_sys) == 0, g_is->getNdbError());
CHK2(g_is->check_systables(g_ndb_sys) == 0, g_is->getNdbError());
g_info << "create done" << endl;
}
else
{
g_info << "using existing sys tables" << endl;
}
}
if (!_sys_skip_events)
{
if (g_is->check_sysevents(g_ndb_sys) == -1)
{
CHK2(g_is->getNdbError().code == NdbIndexStat::NoSysEvents,
g_is->getNdbError());
g_info << "creating sys events" << endl;
CHK2(g_is->create_sysevents(g_ndb_sys) == 0, g_is->getNdbError());
g_info << "create done" << endl;
}
else
{
g_info << "using existing sys events" << endl;
}
}
}
if (_sys_create_if_not_valid)
{
if (!_sys_skip_tables)
{
if (g_is->check_systables(g_ndb_sys) == -1)
{
if (g_is->getNdbError().code != NdbIndexStat::NoSysTables)
{
CHK2(g_is->getNdbError().code == NdbIndexStat::BadSysTables,
g_is->getNdbError());
g_info << "dropping invalid sys tables" << endl;
CHK2(g_is->drop_systables(g_ndb_sys) == 0, g_is->getNdbError());
CHK2(g_is->check_systables(g_ndb_sys) == -1, "unexpected success");
CHK2(g_is->getNdbError().code == NdbIndexStat::NoSysTables,
"unexpected error: " << g_is->getNdbError());
g_info << "drop done" << endl;
}
g_info << "creating all sys tables" << endl;
CHK2(g_is->create_systables(g_ndb_sys) == 0, g_is->getNdbError());
CHK2(g_is->check_systables(g_ndb_sys) == 0, g_is->getNdbError());
g_info << "create done" << endl;
}
else
{
g_info << "using existing sys tables" << endl;
}
}
if (!_sys_skip_events)
{
if (g_is->check_sysevents(g_ndb_sys) == -1)
{
if (g_is->getNdbError().code != NdbIndexStat::NoSysEvents)
{
CHK2(g_is->getNdbError().code == NdbIndexStat::BadSysEvents,
g_is->getNdbError());
g_info << "dropping invalid sys events" << endl;
CHK2(g_is->drop_sysevents(g_ndb_sys) == 0, g_is->getNdbError());
CHK2(g_is->check_sysevents(g_ndb_sys) == -1, "unexpected success");
CHK2(g_is->getNdbError().code == NdbIndexStat::NoSysEvents,
"unexpected error: " << g_is->getNdbError());
g_info << "drop done" << endl;
}
g_info << "creating sys events" << endl;
CHK2(g_is->create_sysevents(g_ndb_sys) == 0, g_is->getNdbError());
CHK2(g_is->check_sysevents(g_ndb_sys) == 0, g_is->getNdbError());
g_info << "create done" << endl;
}
else
{
g_info << "using existing sys events" << endl;
}
}
}
if (_sys_check)
{
if (!_sys_skip_tables)
{
CHK2(g_is->check_systables(g_ndb_sys) == 0, g_is->getNdbError());
g_info << "sys tables ok" << endl;
}
if (!_sys_skip_events)
{
CHK2(g_is->check_sysevents(g_ndb_sys) == 0, g_is->getNdbError());
g_info << "sys events ok" << endl;
}
}
}
while (0);
return ret;
}
static int
doall()
{
int ret = 0;
do
{
CHK2(doconnect() == 0, "connect to NDB");
int loop = 0;
while (++loop <= _loops)
{
g_info << "loop " << loop << " of " << _loops << endl;
if (!_sys_any)
{
if (loop == 1)
{
CHK1(checkobjs() == 0);
}
CHK2(dostats() == 0, "at loop " << loop);
}
else
{
CHK2(dosys() == 0, "at loop " << loop);
}
}
CHK1(ret == 0);
}
while (0);
dodisconnect();
return ret;
}
static struct my_option
my_long_options[] =
{
NDB_STD_OPTS("ndb_index_stat"),
// stats options
{ "database", 'd',
"Name of database table is in",
(uchar**) &_dbname, (uchar**) &_dbname, 0,
GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0 },
{ "delete", NDB_OPT_NOSHORT,
"Delete index stats of given table"
" and stop any configured auto update",
(uchar **)&_delete, (uchar **)&_delete, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0 },
{ "update", NDB_OPT_NOSHORT,
"Update index stats of given table"
" and restart any configured auto update",
(uchar **)&_update, (uchar **)&_update, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0 },
{ "dump", NDB_OPT_NOSHORT,
"Dump query cache",
(uchar **)&_dump, (uchar **)&_dump, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0 },
{ "query", NDB_OPT_NOSHORT,
"Perform random range queries on first key attr (must be int unsigned)",
(uchar **)&_query, (uchar **)&_query, 0,
GET_INT, REQUIRED_ARG, 0, 0, 0, 0, 0, 0 },
// sys options
{ "sys-drop", NDB_OPT_NOSHORT,
"Drop any stats tables and events in NDB kernel (all stats is lost)",
(uchar **)&_sys_drop, (uchar **)&_sys_drop, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0 },
{ "sys-create", NDB_OPT_NOSHORT,
"Create stats tables and events in NDB kernel (must not exist)",
(uchar **)&_sys_create, (uchar **)&_sys_create, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0 },
{ "sys-create-if-not-exist", NDB_OPT_NOSHORT,
"Like --sys-create but do nothing if correct objects exist",
(uchar **)&_sys_create_if_not_exist, (uchar **)&_sys_create_if_not_exist, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0 },
{ "sys-create-if-not-valid", NDB_OPT_NOSHORT,
"Like --sys-create-if-not-exist but first drop any invalid objects",
(uchar **)&_sys_create_if_not_valid, (uchar **)&_sys_create_if_not_valid, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0 },
{ "sys-check", NDB_OPT_NOSHORT,
"Check that correct stats tables and events exist in NDB kernel",
(uchar **)&_sys_check, (uchar **)&_sys_check, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0 },
{ "sys-skip-tables", NDB_OPT_NOSHORT,
"Do not apply sys options to tables",
(uchar **)&_sys_skip_tables, (uchar **)&_sys_skip_tables, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0 },
{ "sys-skip-events", NDB_OPT_NOSHORT,
"Do not apply sys options to events",
(uchar **)&_sys_skip_events, (uchar **)&_sys_skip_events, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0 },
// other
{ "verbose", 'v',
"Verbose messages",
(uchar **)&_verbose, (uchar **)&_verbose, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0 },
{ "loops", NDB_OPT_NOSHORT,
"Repeat same commands a number of times (for testing)",
(uchar **)&_loops, (uchar **)&_loops, 0,
GET_INT, REQUIRED_ARG, 1, 0, 0, 0, 0, 0 },
{ 0, 0,
0,
0, 0, 0,
GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0 }
};
const char*
load_default_groups[]= { "mysql_cluster", 0 };
static void
short_usage_sub(void)
{
ndb_short_usage_sub("[table [index...]]");
}
static void
usage()
{
printf("%s: ordered index stats tool and test\n", my_progname);
ndb_usage(short_usage_sub, load_default_groups, my_long_options);
}
static int
checkopts(int argc, char** argv)
{
int ret = 0;
do
{
_stats_any =
(_dbname != 0) +
(_delete != 0) +
(_update != 0) +
(_dump != 0) +
(_query != 0);
_sys_any =
(_sys_create != 0) +
(_sys_create_if_not_exist != 0) +
(_sys_create_if_not_valid != 0) +
(_sys_drop != 0) +
( _sys_check != 0) +
(_sys_skip_tables != 0) +
(_sys_skip_events != 0);
if (!_sys_any)
{
if (_dbname == 0)
_dbname = "TEST_DB";
CHK2(argc >= 1, "stats options require table");
g_tabname = strdup(argv[0]);
CHK2(g_tabname != 0, "out of memory");
g_indcount = argc - 1;
if (g_indcount != 0)
{
g_indnames = (const char**)malloc(sizeof(char*) * g_indcount);
CHK2(g_indnames != 0, "out of memory");
for (int i = 0; i < g_indcount; i++)
{
g_indnames[i] = strdup(argv[1 + i]);
CHK2(g_indnames[i] != 0, "out of memory");
}
CHK1(ret == 0);
}
}
else
{
CHK2(_stats_any == 0, "cannot mix --sys options with stats options");
CHK2(argc == 0, "--sys options take no args");
}
}
while (0);
return ret;
}
int
main(int argc, char** argv)
{
my_progname = "ndb_index_stat";
int ret;
ndb_init();
ndb_opt_set_usage_funcs(short_usage_sub, usage);
ret = handle_options(&argc, &argv, my_long_options, ndb_std_get_one_option);
if (ret != 0 || checkopts(argc, argv) != 0)
{
ndb_end_and_exit(NDBT_ProgramExit(NDBT_WRONGARGS));
}
setOutputLevel(_verbose ? 2 : 0);
unsigned seed = (unsigned)time(0);
g_info << "random seed " << seed << endl;
ndb_srand(seed);
ret = doall();
if (ret == -1)
{
ndb_end_and_exit(NDBT_ProgramExit(NDBT_FAILED));
}
ndb_end_and_exit(NDBT_ProgramExit(NDBT_OK));
}
| 27.726158 | 100 | 0.585229 | [
"object"
] |
e5556e8db35049b4436aab3d3650cb6e398e5710 | 1,697 | cpp | C++ | demo/wait_example.cpp | yo123abxd/cpp_rate_limit | dede58e328949c22ee0cb46a3082ca970924a856 | [
"MIT"
] | 28 | 2019-12-31T03:07:34.000Z | 2022-03-27T12:50:22.000Z | demo/wait_example.cpp | yo123abxd/cpp_rate_limit | dede58e328949c22ee0cb46a3082ca970924a856 | [
"MIT"
] | null | null | null | demo/wait_example.cpp | yo123abxd/cpp_rate_limit | dede58e328949c22ee0cb46a3082ca970924a856 | [
"MIT"
] | 2 | 2021-02-18T09:46:40.000Z | 2021-07-26T08:31:29.000Z | /*
* These codes below explain how to generate 3.0 tokens per second
* and cosume 2.0 tokens every time execute your codes.
*/
#include <iostream>
#include <string>
#include <vector>
#include <thread>
#include <chrono>
#include "../include/Limiter.h"
using std::chrono::duration_cast;
using std::chrono::microseconds;
using std::chrono::seconds;
using std::chrono::system_clock;
token_bucket::Limiter* lim_p;
void foo (int th_num) {
for(int loop_time = 0; loop_time < 5; ) {
//wait(cosume tokens num, max wait time/s )
bool ok = lim_p->wait(2.0, seconds(20));
if (ok) {
/*
* write your codes here
*/
std::cout << "thread_num = " << th_num
<< ", loop_time = " << loop_time
<< " time : "
<< duration_cast<seconds>(system_clock::now().time_since_epoch()).count()
<< std::endl;
++loop_time;
} else {
//if exceed max wait time
std::this_thread::sleep_for(microseconds(1000));
}
}
}
int main() {
//first parameter->generate n tokens per s, second parameter->burst tokens
//means generate 3.0 tokens per s
//when rate <= 0, it will not generator tokens anymore
lim_p = new token_bucket::Limiter(3.0, 5.0);
std::vector<std::thread*> vec(5, nullptr);
for (int th_num = 0; th_num < static_cast<int>(vec.size()); th_num++) {
vec[th_num] = new std::thread(foo, th_num);
}
for (int th_num = 0; th_num < static_cast<int>(vec.size()); th_num++) {
vec[th_num]->join();
delete vec[th_num];
}
delete lim_p;
return 0;
}
| 29.258621 | 94 | 0.56924 | [
"vector"
] |
e555d5917f15ec08b7a485ff3b3dc785b9915618 | 616 | cpp | C++ | Hackerrank/Practice/C++/STL/6. Maps-STL.cpp | mohitkhedkar/Competitive-programming | 85d08791002363c6a1104b6b51bf049489fd5257 | [
"MIT"
] | 2 | 2020-10-22T15:37:14.000Z | 2020-12-11T06:45:02.000Z | Hackerrank/Practice/C++/STL/6. Maps-STL.cpp | mohitkhedkar/Competitive-programming | 85d08791002363c6a1104b6b51bf049489fd5257 | [
"MIT"
] | null | null | null | Hackerrank/Practice/C++/STL/6. Maps-STL.cpp | mohitkhedkar/Competitive-programming | 85d08791002363c6a1104b6b51bf049489fd5257 | [
"MIT"
] | null | null | null | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <set>
#include <map>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int q;
cin >> q;
map<string,int> m;
for (int i = 0; i<q; i++)
{
int t, marks;
string name;
cin >> t >> name;
if (t == 1){
cin >> marks;
m[name] += marks;
}
else if (t == 2)
m.erase(name);
else
cout << m[name] << "\n";
}
return 0;
}
| 16.210526 | 77 | 0.465909 | [
"vector"
] |
e55739b84a7dfff22f04798bbaf80b2fa9b0a84f | 5,649 | cpp | C++ | src/qt/pivx/settings/moc_settingswalletrepairwidget.cpp | PlutusCapital/core | 9a02ab820245afdb2b3ab4bea621a78bfef37590 | [
"MIT"
] | null | null | null | src/qt/pivx/settings/moc_settingswalletrepairwidget.cpp | PlutusCapital/core | 9a02ab820245afdb2b3ab4bea621a78bfef37590 | [
"MIT"
] | null | null | null | src/qt/pivx/settings/moc_settingswalletrepairwidget.cpp | PlutusCapital/core | 9a02ab820245afdb2b3ab4bea621a78bfef37590 | [
"MIT"
] | null | null | null | /****************************************************************************
** Meta object code from reading C++ file 'settingswalletrepairwidget.h'
**
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "qt/pivx/settings/settingswalletrepairwidget.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'settingswalletrepairwidget.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.5.1. 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_SettingsWalletRepairWidget_t {
QByteArrayData data[11];
char stringdata0[145];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_SettingsWalletRepairWidget_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_SettingsWalletRepairWidget_t qt_meta_stringdata_SettingsWalletRepairWidget = {
{
QT_MOC_LITERAL(0, 0, 26), // "SettingsWalletRepairWidget"
QT_MOC_LITERAL(1, 27, 13), // "handleRestart"
QT_MOC_LITERAL(2, 41, 0), // ""
QT_MOC_LITERAL(3, 42, 4), // "args"
QT_MOC_LITERAL(4, 47, 13), // "walletSalvage"
QT_MOC_LITERAL(5, 61, 12), // "walletRescan"
QT_MOC_LITERAL(6, 74, 14), // "walletZaptxes1"
QT_MOC_LITERAL(7, 89, 14), // "walletZaptxes2"
QT_MOC_LITERAL(8, 104, 13), // "walletUpgrade"
QT_MOC_LITERAL(9, 118, 13), // "walletReindex"
QT_MOC_LITERAL(10, 132, 12) // "walletResync"
},
"SettingsWalletRepairWidget\0handleRestart\0"
"\0args\0walletSalvage\0walletRescan\0"
"walletZaptxes1\0walletZaptxes2\0"
"walletUpgrade\0walletReindex\0walletResync"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_SettingsWalletRepairWidget[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
8, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: name, argc, parameters, tag, flags
1, 1, 54, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
4, 0, 57, 2, 0x0a /* Public */,
5, 0, 58, 2, 0x0a /* Public */,
6, 0, 59, 2, 0x0a /* Public */,
7, 0, 60, 2, 0x0a /* Public */,
8, 0, 61, 2, 0x0a /* Public */,
9, 0, 62, 2, 0x0a /* Public */,
10, 0, 63, 2, 0x0a /* Public */,
// signals: parameters
QMetaType::Void, QMetaType::QStringList, 3,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void SettingsWalletRepairWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
SettingsWalletRepairWidget *_t = static_cast<SettingsWalletRepairWidget *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->handleRestart((*reinterpret_cast< QStringList(*)>(_a[1]))); break;
case 1: _t->walletSalvage(); break;
case 2: _t->walletRescan(); break;
case 3: _t->walletZaptxes1(); break;
case 4: _t->walletZaptxes2(); break;
case 5: _t->walletUpgrade(); break;
case 6: _t->walletReindex(); break;
case 7: _t->walletResync(); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
void **func = reinterpret_cast<void **>(_a[1]);
{
typedef void (SettingsWalletRepairWidget::*_t)(QStringList );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&SettingsWalletRepairWidget::handleRestart)) {
*result = 0;
}
}
}
}
const QMetaObject SettingsWalletRepairWidget::staticMetaObject = {
{ &PWidget::staticMetaObject, qt_meta_stringdata_SettingsWalletRepairWidget.data,
qt_meta_data_SettingsWalletRepairWidget, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *SettingsWalletRepairWidget::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *SettingsWalletRepairWidget::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_SettingsWalletRepairWidget.stringdata0))
return static_cast<void*>(const_cast< SettingsWalletRepairWidget*>(this));
return PWidget::qt_metacast(_clname);
}
int SettingsWalletRepairWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = PWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 8)
qt_static_metacall(this, _c, _id, _a);
_id -= 8;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 8)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 8;
}
return _id;
}
// SIGNAL 0
void SettingsWalletRepairWidget::handleRestart(QStringList _t1)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
QT_END_MOC_NAMESPACE
| 34.87037 | 111 | 0.630554 | [
"object"
] |
e56000efc4caf2a06ab717923f203454b9923156 | 18,184 | cc | C++ | Geometry/FbcmGeometryBuilder/src/FbcmGeometryBuilderFromDDD.cc | m-sedghi/cmssw | 859df8affee372c53be79cdd2d8a5ff001eae841 | [
"Apache-2.0"
] | null | null | null | Geometry/FbcmGeometryBuilder/src/FbcmGeometryBuilderFromDDD.cc | m-sedghi/cmssw | 859df8affee372c53be79cdd2d8a5ff001eae841 | [
"Apache-2.0"
] | null | null | null | Geometry/FbcmGeometryBuilder/src/FbcmGeometryBuilderFromDDD.cc | m-sedghi/cmssw | 859df8affee372c53be79cdd2d8a5ff001eae841 | [
"Apache-2.0"
] | null | null | null | ///-------------------------------------------
// Author: Mohammad Sedghi, msedghi@cern.ch
// Isfahan University of Technology
// Date created: September 2020
///-------------------------------------------
#include "Geometry/FbcmGeometryBuilder/src/FbcmGeometryBuilderFromDDD.h"
#include "Geometry/FbcmGeometry/interface/FbcmGeometry.h"
#include "Geometry/FbcmGeometry/interface/FbcmSiPadSpecs.h"
#include "DetectorDescription/Core/interface/DDFilter.h"
#include "DetectorDescription/Core/interface/DDFilteredView.h"
#include "DetectorDescription/Core/interface/DDSolid.h"
#include "DataFormats/GeometrySurface/interface/RectangularPlaneBounds.h"
#include "DataFormats/GeometrySurface/interface/SimpleTubBounds.h"
#include "DataFormats/GeometryVector/interface/Basic3DVector.h"
#include "CLHEP/Units/GlobalSystemOfUnits.h"
#include <algorithm>
#include <iostream>
#include <string>
#define DONTCARE 0
FbcmGeometryBuilderFromDDD::FbcmGeometryBuilderFromDDD() {}
FbcmGeometryBuilderFromDDD::~FbcmGeometryBuilderFromDDD() {}
void FbcmGeometryBuilderFromDDD::build(FbcmGeometry& theGeometry, const DDCompactView* cview) {
std::string attribute = "FbcmDDDGeom" ;
std::string value = "FbcmTopLevelGeometry";
//std::string attribute = "MuStructure" ;
//std::string value = "MuonEndCapME0";
// std::cout << "attribute: " << attribute << ", Tag: " << value << "\n";
DDSpecificsMatchesValueFilter filter{DDValue(attribute, value, 0.0)};
// I should make sure that this filter leads to a valid fview
// Otherwise and error shoould be rised
//std::cout << "Hello from FbcmGeometryBuilderFromDDD_build\n";
DDFilteredView fview(*cview, filter);
// before utilization of fview, it refers to the Main RootNode, i.e. OCMS,
// after one move down (child), it refers to the Filter
fview.firstChild(); // this is essential to apply the filter to the Node
buildGeometry(theGeometry, fview);
}
void FbcmGeometryBuilderFromDDD::buildGeometry(FbcmGeometry& theFbcmGeometry, DDFilteredView& fv) {
//FbcmGeometry* geometry = new FbcmGeometry();
DDValue NumOfStations("nStations");
const std::vector<const DDsvalues_type*>& specs = fv.specifics();
//std::cout << "SpecSizeSattion: " << specs.size() << "\n" ;
//std::cout << specs << "\n" ;
int nStations=0;
for (auto const& is : specs) {
if (DDfetch(is, NumOfStations))
nStations = (int) (NumOfStations.doubles()[0]);
}
theFbcmGeometry.SetNumOfStations(nStations); // this is per end
//std::cout << "SetNumOfStations read as: " << theFbcmGeometry.NumOfStations() << "\n";
//std::cout << "Hello from FbcmGeometryBuilderFromDDD_buildGeometry\n";
//std::cout << "fviewTopName logical Name: " << fv.logicalPart().name().name() << "\n" ;
/*
std::cout << "fviewTopName: " << fv.name() << "\n" ;
std::cout << "fviewTopName logical Name: " << fv.logicalPart().name().name() << "\n" ;
fv.firstChild();
std::cout << "fviewfirstChild: " << fv.logicalPart().name().name() << "\n" ;
fv.firstChild();
std::cout << "fviewfirstChild: " << fv.logicalPart().name().name() << "\n" ;
fv.firstChild();
std::cout << "fviewfirstChild: " << fv.logicalPart().name().name() << "\n" ;
fv.firstChild();
std::cout << "fviewfirstChild: " << fv.logicalPart().name().name() << "\n" ;
fv.firstChild();
std::cout << "fviewfirstChild: " << fv.logicalPart().name().name() << "\n" ;
fv.nextSibling();
std::cout << "fviewa after next: " << fv.logicalPart().name().name() << "\n" ;
fv.firstChild();
std::cout << "fviewfirstChild: " << fv.logicalPart().name().name() << "\n" ;
*/
LogTrace("FbcmGeometryBuilderFromDDD") << "Building the FBCM geometry:";
LogTrace("FbcmGeometryBuilderFromDDD") << "Top level logical part: " << fv.logicalPart().name().name();
/// --------- FBCM Geometry Builder --------------
/// Caution: there is a aditinal level in fbcm.xml which is ignored in the the FBCMGeometry Class.
/// (i.e. SiliconCols).
// For the moment, in the fbxm.xml we have the following Parent-Child relationship:
/// FBCM --> Station --> SiliconDie --> SensorRow ---> SiPad
// but the FbcmGeometry class is something like this:
/// FBCM --> Station --> SiliconDie -----------------> SiPad
bool doFbcmSides = true;
//int SideID =1; // This is a temporary solving the code!!. It should be read out from the FBCM Side CopyNo.
int FbcmCopyNo;
while (doFbcmSides) {
FbcmCopyNo = fv.copyno(); // FbcmCopyNo is always 1, we should get the CopyNo of its parent.
//std::cout << "FbcmCopyNo" << FbcmCopyNo << "\n";
//fv.parent(); // its parent is the volum at endcap
//= fv.copyno(); // the CopyNo of the Sides, i.e. the parent of FBCM
//fv.firstChild(); // returing to FBCM
//std::cout << "SideID: " << SideID << "\n";
bool doStations = fv.firstChild(); // move to Stations level
while (doStations) {
int StationCopyNo = fv.copyno(); // Stations
//std::cout << "Station: " << fv.logicalPart().name().name() << ", ";
//std::cout << StationCopyNo << "\n";
FbcmDetId StationDetId_ = FbcmDetId(FbcmCopyNo,StationCopyNo,DONTCARE,DONTCARE);
FbcmStationGeom* NewStation = buildStation(fv, StationDetId_.StationDetId());
theFbcmGeometry.add(NewStation);
//std::cout << "nRings: " << NewStation->NumOfRings() << ",nDiePerRing: " << NewStation->NumOfDiesPerRing() << " \n";
// in FbcmGeometry: loop over SiliconDies of the Station
bool doSiDies = fv.firstChild(); // SiliconDie
while (doSiDies) {
int SilconDieCopyNo = fv.copyno(); // SiliconDie
//std::cout << "SiliconDie: " << fv.logicalPart().name().name() << ", ";
//std::cout << SilconDieCopyNo << "\n";
FbcmDetId SiDieDetId = FbcmDetId(FbcmCopyNo,StationCopyNo,SilconDieCopyNo,DONTCARE);
FbcmSiliconDieGeom* NewSiDie = buildSiliconDie(fv, SiDieDetId.SiliconDieDetId());
NewStation->add(NewSiDie);
theFbcmGeometry.add(NewSiDie);
//unsigned int nCols=NewSiDie->NumOfCols();
unsigned int nRows=NewSiDie->NumOfRows();
//std::cout << SiDieDetId;
//std::cout << "nCols: " << NewSiDie->NumOfCols() << ",nRows: " << NewSiDie->NumOfRows() << " \n";
// loop over SiliconCols of each SiliconDie
// SiliconCol has not a geometry in the FBCMGeometry !
bool doSiCols = fv.firstChild(); // SiliconCols
while (doSiCols) {
int SilconColCopyNo = fv.copyno(); // SiliconCol
// loop over SiPads of the SiliconCol
bool doSiPads = fv.firstChild(); // SiPads
while (doSiPads) {
int SiPadCopyNo = fv.copyno(); // SiPad
int SensorPadID=SilconColCopyNo*nRows+SiPadCopyNo;
//std::cout << "SiPad: " << fv.logicalPart().name().name() << ", ";
//std::cout << SensorPadID << "\n";
FbcmDetId SiPadDetId = FbcmDetId(FbcmCopyNo,StationCopyNo,SilconDieCopyNo,SensorPadID);
//std::cout << SiPadDetId << "\n";
FbcmSiPadGeom* NewSiPad = buildSiPad(fv, SiPadDetId);
NewSiDie->add(NewSiPad);
theFbcmGeometry.add(NewSiPad);
doSiPads = fv.nextSibling();
}
fv.parent(); // get back to SiliconCol
doSiCols = fv.nextSibling(); // Next SiliconCol
}
fv.parent(); // get back to SiliconDie
doSiDies = fv.nextSibling();
}
fv.parent(); // get back to Station
doStations = fv.nextSibling(); // Next Station
}
fv.parent(); // get back to FbcmSides
doFbcmSides = fv.nextSibling(); // Other Side
//SideID++; // Notice: this line is just for temporary fix!, it should be read out from FilterView
}
//return theFbcmGeometry;
}
FbcmStationGeom* FbcmGeometryBuilderFromDDD::buildStation(DDFilteredView& fv, FbcmDetId StationDetId_) const {
LogTrace("FbcmGeometryBuilderFromDDD") << "buildStation " << fv.logicalPart().name().name() << ", StationDetId_: " << StationDetId_ << std::endl;
//std:: cout << "buildStation " << fv.logicalPart().name().name() << ", StationDetId_: " << StationDetId_ << std::endl;
//std::cout << " Hi buildStation: "<< StationDetId_;
DDTubs solid = (DDTubs)(fv.logicalPart().solid());
std::vector<double> dpar = solid.parameters();
double halfZ = solid.zhalf() / cm; // halfThickness
double rMin = solid.rIn() / cm;
double rMax = solid.rOut() / cm ;
double StartPhi = solid.startPhi();
double DeltaPhi = solid.deltaPhi();
// std::cout << " name of logical part = " << fv.logicalPart().name().name() << std::endl;
// std::cout << " dpar is vector with size = " << dpar.size() << std::endl;
// for (unsigned int i = 0; i < dpar.size(); ++i) {
// std::cout << " dpar [" << i << "] = " << dpar[i] << " mm or rad" << std::endl;
// }
// std::cout << "halfZ: " << halfZ << "cm, rMin: " << rMin << "cm, rMax: " << rMax << "cm, StartPhi: " << StartPhi << ", DeltaPhi: " << DeltaPhi << std::endl;
// std::cout << "\n";
// #ifdef EDM_ML_DEBUG
// LogTrace("FbcmGeometryBuilderFromDDD") << " name of logical part = " << fv.logicalPart().name().name() << std::endl;
// LogTrace("FbcmGeometryBuilderFromDDD") << " dpar is vector with size = " << dpar.size() << std::endl;
// for (unsigned int i = 0; i < dpar.size(); ++i) {
// LogTrace("FbcmGeometryBuilderFromDDD") << " dpar [" << i << "] = " << dpar[i] / cm << " cm " << std::endl;
// }
// LogTrace("FbcmGeometryBuilderFromDDD") << "size halfWidth: " << w << "cm, halfLength: " << h << "cm, halfThickness: " << t << "cm" << std::endl;
// #endif
DDValue NumOfDiesPerRing("nSiDiesPerStationPerRing");
DDValue NumOfRings("nRingsPerStation");
const std::vector<const DDsvalues_type*>& specs = fv.specifics();
//std::cout << specs << "\n" ;
int nDiesPerRing = 0, nRings = 0;
for (auto const& is : specs) {
if (DDfetch(is, NumOfDiesPerRing))
nDiesPerRing = (int) (NumOfDiesPerRing.doubles()[0]);
if (DDfetch(is, NumOfRings))
nRings = (int)(NumOfRings.doubles()[0]);
}
// SimpleTubBounds(float rmin, float rmax, float dz, float startPhi, float deltaPhi);
FbcmBoundPlane surf(boundPlane(fv, new SimpleTubBounds(rMin, rMax , halfZ, StartPhi, DeltaPhi)));
FbcmStationGeom* Station = new FbcmStationGeom(StationDetId_, surf, nDiesPerRing, nRings);
return Station;
}
FbcmSiliconDieGeom* FbcmGeometryBuilderFromDDD::buildSiliconDie(DDFilteredView& fv, FbcmDetId SiDieDetId) const {
LogTrace("FbcmGeometryBuilderFromDDD") << "buildSiliconDie " << fv.logicalPart().name().name() << ", SiliconDieId: " << SiDieDetId << std::endl;
//std::cout << "buildSiliconDie: "<< SiDieDetId;
DDBox solid = (DDBox)(fv.logicalPart().solid());
std::vector<double> dpar = solid.parameters();
// double w = dpar[0] / cm; // halfWidth
// double h = dpar[1] / cm; // halfLength
// double t = dpar[2] / cm; // halfThickness
double w = solid.halfX() / cm; // halfWidth
double h = solid.halfY() / cm; // halfLength
double t = solid.halfZ() / cm; // halfThickness
DDValue NumOfCols("nCols");
DDValue NumOfRows("nRows");
const std::vector<const DDsvalues_type*>& specs = fv.specifics();
//std::cout << specs << "\n" ;
unsigned int nCols = 0, nRows = 0;
for (auto const& is : specs) {
if (DDfetch(is, NumOfCols))
nCols = (unsigned int)(NumOfCols.doubles()[0]);
if (DDfetch(is, NumOfRows))
nRows = (unsigned int)(NumOfRows.doubles()[0]);
}
// std::cout << " name of logical part = " << fv.logicalPart().name().name() << std::endl;
// std::cout << " dpar is vector with size = " << dpar.size() << std::endl;
// for (unsigned int i = 0; i < dpar.size(); ++i) {
// std::cout << " dpar [" << i << "] = " << dpar[i] / cm << " cm " << std::endl;
// }
// std::cout << "size halfWidth: " << w << "cm, halfLength: " << h << "cm, halfThickness: " << t << "cm" << std::endl;
// std::cout << "\n";
#ifdef EDM_ML_DEBUG
LogTrace("FbcmGeometryBuilderFromDDD") << " name of logical part = " << fv.logicalPart().name().name() << std::endl;
LogTrace("FbcmGeometryBuilderFromDDD") << " dpar is vector with size = " << dpar.size() << std::endl;
for (unsigned int i = 0; i < dpar.size(); ++i) {
LogTrace("FbcmGeometryBuilderFromDDD") << " dpar [" << i << "] = " << dpar[i] / cm << " cm " << std::endl;
}
LogTrace("FbcmGeometryBuilderFromDDD") << "size halfWidth: " << w << "cm, halfLength: " << h << "cm, halfThickness: " << t << "cm" << std::endl;
#endif
FbcmBoundPlane surf(boundPlane(fv, new RectangularPlaneBounds(w, h, t)));
FbcmSiliconDieGeom* SiliconDie = new FbcmSiliconDieGeom(SiDieDetId, surf, nCols, nRows);
return SiliconDie;
}
FbcmSiPadGeom* FbcmGeometryBuilderFromDDD::buildSiPad(DDFilteredView& fv, FbcmDetId detId) const {
LogTrace("FbcmGeometryBuilderFromDDD") << "buildSiPad " << fv.logicalPart().name().name() << ", FbcmDetId: " << detId << std::endl;
//std::cout << "buildSiPad: "<< detId;
DDBox solid = (DDBox)(fv.logicalPart().solid());
std::vector<double> dpar = solid.parameters();
// double w = dpar[0] / cm; // halfWidth
// double h = dpar[1] / cm; // halfLength
// double t = dpar[2] / cm; // halfThickness
double w = solid.halfX() / cm; // halfWidth
double h = solid.halfY() / cm; // halfLength
double t = solid.halfZ() / cm; // halfThickness
// std::cout << " name of logical part = " << fv.logicalPart().name().name() << std::endl;
// std::cout << " dpar is vector with size = " << dpar.size() << std::endl;
// for (unsigned int i = 0; i < dpar.size(); ++i) {
// std::cout << " dpar [" << i << "] = " << dpar[i] / cm << " cm " << std::endl;
// }
// std::cout << "size halfWidth: " << w << "cm, halfLength: " << h << "cm, halfThickness: " << t << "cm" << std::endl;
// std::cout << "\n";
#ifdef EDM_ML_DEBUG
LogTrace("FbcmGeometryBuilderFromDDD") << " name of logical part = " << fv.logicalPart().name().name() << std::endl;
LogTrace("FbcmGeometryBuilderFromDDD") << " dpar is vector with size = " << dpar.size() << std::endl;
for (unsigned int i = 0; i < dpar.size(); ++i) {
LogTrace("FbcmGeometryBuilderFromDDD") << " dpar [" << i << "] = " << dpar[i] / cm << " cm " << std::endl;
}
LogTrace("FbcmGeometryBuilderFromDDD") << "size halfWidth: " << w << "cm, halfLength: " << h << "cm, halfThickness: " << t << "cm" << std::endl;
#endif
std::vector<float> pars;
pars.emplace_back(2*w); // pitchX = pars[0];
pars.emplace_back(2*h); // pitchY = pars[1];
//RectangularPlaneBounds::RectangularPlaneBounds(float w, float h, float t), halfWidth(w), halfLength(h), halfThickness(t)
FbcmBoundPlane surf(boundPlane(fv, new RectangularPlaneBounds(w, h, t)));
std::string name = fv.logicalPart().name().name();
FbcmSiPadSpecs* SiPad_Specs = new FbcmSiPadSpecs(GeomDetEnumerators::FBCM, name, pars);
FbcmSiPadGeom* SiPad = new FbcmSiPadGeom(detId, surf, SiPad_Specs);
return SiPad;
}
FbcmGeometryBuilderFromDDD::FbcmBoundPlane FbcmGeometryBuilderFromDDD::boundPlane(const DDFilteredView& fv, Bounds* bounds) const {
// extract the position
const DDTranslation& trans(fv.translation());
const Surface::PositionType posResult(float(trans.x() / cm), float(trans.y() / cm), float(trans.z() / cm));
//std::cout << " name of logical part = " << fv.logicalPart().name().name() << std::endl;
// std::cout << "x: " << posResult.x() << ", y: " << posResult.y() << ", z: " << posResult.z() << "\n";
// now the rotation
// DDRotationMatrix tmp = fv.rotation();
// === DDD uses 'active' rotations - see CLHEP user guide ===
// ORCA uses 'passive' rotation.
// 'active' and 'passive' rotations are inverse to each other
// DDRotationMatrix tmp = fv.rotation();
const DDRotationMatrix& rotation = fv.rotation();
DD3Vector x, y, z;
rotation.GetComponents(x, y, z);
// std::cout << "translation: "<< fv.translation() << std::endl;
// std::cout << "rotation : "<< fv.rotation() << std::endl;
// std::cout << "INVERSE rotation manually: \n"
// << x.X() << ", " << x.Y() << ", " << x.Z() << std::endl
// << y.X() << ", " << y.Y() << ", " << y.Z() << std::endl
// << z.X() << ", " << z.Y() << ", " << z.Z() << std::endl;
// LogTrace("GEMGeometryBuilderFromDDD") << "translation: "<< fv.translation() << std::endl;
// LogTrace("GEMGeometryBuilderFromDDD") << "rotation : "<< fv.rotation() << std::endl;
// LogTrace("GEMGeometryBuilderFromDDD") << "INVERSE rotation manually: \n"
// << x.X() << ", " << x.Y() << ", " << x.Z() << std::endl
// << y.X() << ", " << y.Y() << ", " << y.Z() << std::endl
// << z.X() << ", " << z.Y() << ", " << z.Z() << std::endl;
Surface::RotationType rotResult(float(x.X()),
float(x.Y()),
float(x.Z()),
float(y.X()),
float(y.Y()),
float(y.Z()),
float(z.X()),
float(z.Y()),
float(z.Z()));
//for shape other than BOXs, the conversion of local GEANT position
// to global needs some modifications to change axis.
// Im not sure about the rotation Axis conversion. I should double check it later. !!
//--------------------------
// it seems there was also a need to chagnge XZ to XY rotation axis
// for release earlier than 11 for Dbox as well. something like this:
// if (!theCompatiblity11Flag) {
// if (tran[2] > -1500.) {
// Basic3DVector<float> newX(-1., 0., 0.);
// Basic3DVector<float> newY(0., -1., 0.);
// Basic3DVector<float> newZ(0., 0., 1.);
// rot.rotateAxes(newX, newY, newZ);
// }
// }
//--------------------------
// // Change of axes for the forward for other shapse other than DBox
// Basic3DVector<float> newX(1., 0., 0.);
// Basic3DVector<float> newY(0., 0., 1.);
// Basic3DVector<float> newZ(0., 1., 0.);
// newY *= -1;
// rotResult.rotateAxes(newX, newY, newZ);
//--------------------------
//std::cout << "rotation final :\n"<< rotResult << std::endl;
return FbcmBoundPlane(new BoundPlane(posResult, rotResult, bounds));
}
| 41.610984 | 160 | 0.607237 | [
"geometry",
"shape",
"vector",
"solid"
] |
e56564482f14dece060e9dfcccce01c2367de030 | 13,843 | hpp | C++ | include/TMPro/TMP_FontAssetUtilities.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/TMPro/TMP_FontAssetUtilities.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/TMPro/TMP_FontAssetUtilities.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
}
// Forward declaring namespace: TMPro
namespace TMPro {
// Forward declaring type: TMP_Character
class TMP_Character;
// Forward declaring type: TMP_FontAsset
class TMP_FontAsset;
// Forward declaring type: FontStyles
struct FontStyles;
// Forward declaring type: FontWeight
struct FontWeight;
}
// Forward declaring namespace: UnityEngine::TextCore
namespace UnityEngine::TextCore {
// Forward declaring type: Glyph
class Glyph;
}
// Completed forward declares
// Type namespace: TMPro
namespace TMPro {
// Forward declaring type: TMP_FontAssetUtilities
class TMP_FontAssetUtilities;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::TMPro::TMP_FontAssetUtilities);
DEFINE_IL2CPP_ARG_TYPE(::TMPro::TMP_FontAssetUtilities*, "TMPro", "TMP_FontAssetUtilities");
// Type namespace: TMPro
namespace TMPro {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: TMPro.TMP_FontAssetUtilities
// [TokenAttribute] Offset: FFFFFFFF
class TMP_FontAssetUtilities : public ::Il2CppObject {
public:
// Get static field: static private readonly TMPro.TMP_FontAssetUtilities s_Instance
static ::TMPro::TMP_FontAssetUtilities* _get_s_Instance();
// Set static field: static private readonly TMPro.TMP_FontAssetUtilities s_Instance
static void _set_s_Instance(::TMPro::TMP_FontAssetUtilities* value);
// Get static field: static private System.Collections.Generic.List`1<System.Int32> k_SearchedFontAssets
static ::System::Collections::Generic::List_1<int>* _get_k_SearchedFontAssets();
// Set static field: static private System.Collections.Generic.List`1<System.Int32> k_SearchedFontAssets
static void _set_k_SearchedFontAssets(::System::Collections::Generic::List_1<int>* value);
// Get static field: static private System.Boolean k_IsFontEngineInitialized
static bool _get_k_IsFontEngineInitialized();
// Set static field: static private System.Boolean k_IsFontEngineInitialized
static void _set_k_IsFontEngineInitialized(bool value);
// static public TMPro.TMP_FontAssetUtilities get_instance()
// Offset: 0x143DB54
static ::TMPro::TMP_FontAssetUtilities* get_instance();
// static private System.Void .cctor()
// Offset: 0x143DAE8
static void _cctor();
// static public TMPro.TMP_Character GetCharacterFromFontAsset(System.UInt32 unicode, TMPro.TMP_FontAsset sourceFontAsset, System.Boolean includeFallbacks, TMPro.FontStyles fontStyle, TMPro.FontWeight fontWeight, out System.Boolean isAlternativeTypeface, out TMPro.TMP_FontAsset fontAsset)
// Offset: 0x143DBBC
static ::TMPro::TMP_Character* GetCharacterFromFontAsset(uint unicode, ::TMPro::TMP_FontAsset* sourceFontAsset, bool includeFallbacks, ::TMPro::FontStyles fontStyle, ::TMPro::FontWeight fontWeight, ByRef<bool> isAlternativeTypeface, ByRef<::TMPro::TMP_FontAsset*> fontAsset);
// static private TMPro.TMP_Character GetCharacterFromFontAsset_Internal(System.UInt32 unicode, TMPro.TMP_FontAsset sourceFontAsset, System.Boolean includeFallbacks, TMPro.FontStyles fontStyle, TMPro.FontWeight fontWeight, out System.Boolean isAlternativeTypeface, out TMPro.TMP_FontAsset fontAsset)
// Offset: 0x143DD2C
static ::TMPro::TMP_Character* GetCharacterFromFontAsset_Internal(uint unicode, ::TMPro::TMP_FontAsset* sourceFontAsset, bool includeFallbacks, ::TMPro::FontStyles fontStyle, ::TMPro::FontWeight fontWeight, ByRef<bool> isAlternativeTypeface, ByRef<::TMPro::TMP_FontAsset*> fontAsset);
// static public TMPro.TMP_Character GetCharacterFromFontAssets(System.UInt32 unicode, System.Collections.Generic.List`1<TMPro.TMP_FontAsset> fontAssets, System.Boolean includeFallbacks, TMPro.FontStyles fontStyle, TMPro.FontWeight fontWeight, out System.Boolean isAlternativeTypeface, out TMPro.TMP_FontAsset fontAsset)
// Offset: 0x143E138
static ::TMPro::TMP_Character* GetCharacterFromFontAssets(uint unicode, ::System::Collections::Generic::List_1<::TMPro::TMP_FontAsset*>* fontAssets, bool includeFallbacks, ::TMPro::FontStyles fontStyle, ::TMPro::FontWeight fontWeight, ByRef<bool> isAlternativeTypeface, ByRef<::TMPro::TMP_FontAsset*> fontAsset);
// static private System.Boolean TryGetCharacterFromFontFile(System.UInt32 unicode, TMPro.TMP_FontAsset fontAsset, out TMPro.TMP_Character character)
// Offset: 0x143E360
static bool TryGetCharacterFromFontFile(uint unicode, ::TMPro::TMP_FontAsset* fontAsset, ByRef<::TMPro::TMP_Character*> character);
// static public System.Boolean TryGetGlyphFromFontFile(System.UInt32 glyphIndex, TMPro.TMP_FontAsset fontAsset, out UnityEngine.TextCore.Glyph glyph)
// Offset: 0x143E56C
static bool TryGetGlyphFromFontFile(uint glyphIndex, ::TMPro::TMP_FontAsset* fontAsset, ByRef<::UnityEngine::TextCore::Glyph*> glyph);
// public System.Void .ctor()
// Offset: 0x143DB4C
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static TMP_FontAssetUtilities* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::TMPro::TMP_FontAssetUtilities::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<TMP_FontAssetUtilities*, creationType>()));
}
}; // TMPro.TMP_FontAssetUtilities
#pragma pack(pop)
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: TMPro::TMP_FontAssetUtilities::get_instance
// Il2CppName: get_instance
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::TMPro::TMP_FontAssetUtilities* (*)()>(&TMPro::TMP_FontAssetUtilities::get_instance)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(TMPro::TMP_FontAssetUtilities*), "get_instance", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: TMPro::TMP_FontAssetUtilities::_cctor
// Il2CppName: .cctor
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&TMPro::TMP_FontAssetUtilities::_cctor)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(TMPro::TMP_FontAssetUtilities*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: TMPro::TMP_FontAssetUtilities::GetCharacterFromFontAsset
// Il2CppName: GetCharacterFromFontAsset
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::TMPro::TMP_Character* (*)(uint, ::TMPro::TMP_FontAsset*, bool, ::TMPro::FontStyles, ::TMPro::FontWeight, ByRef<bool>, ByRef<::TMPro::TMP_FontAsset*>)>(&TMPro::TMP_FontAssetUtilities::GetCharacterFromFontAsset)> {
static const MethodInfo* get() {
static auto* unicode = &::il2cpp_utils::GetClassFromName("System", "UInt32")->byval_arg;
static auto* sourceFontAsset = &::il2cpp_utils::GetClassFromName("TMPro", "TMP_FontAsset")->byval_arg;
static auto* includeFallbacks = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* fontStyle = &::il2cpp_utils::GetClassFromName("TMPro", "FontStyles")->byval_arg;
static auto* fontWeight = &::il2cpp_utils::GetClassFromName("TMPro", "FontWeight")->byval_arg;
static auto* isAlternativeTypeface = &::il2cpp_utils::GetClassFromName("System", "Boolean")->this_arg;
static auto* fontAsset = &::il2cpp_utils::GetClassFromName("TMPro", "TMP_FontAsset")->this_arg;
return ::il2cpp_utils::FindMethod(classof(TMPro::TMP_FontAssetUtilities*), "GetCharacterFromFontAsset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{unicode, sourceFontAsset, includeFallbacks, fontStyle, fontWeight, isAlternativeTypeface, fontAsset});
}
};
// Writing MetadataGetter for method: TMPro::TMP_FontAssetUtilities::GetCharacterFromFontAsset_Internal
// Il2CppName: GetCharacterFromFontAsset_Internal
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::TMPro::TMP_Character* (*)(uint, ::TMPro::TMP_FontAsset*, bool, ::TMPro::FontStyles, ::TMPro::FontWeight, ByRef<bool>, ByRef<::TMPro::TMP_FontAsset*>)>(&TMPro::TMP_FontAssetUtilities::GetCharacterFromFontAsset_Internal)> {
static const MethodInfo* get() {
static auto* unicode = &::il2cpp_utils::GetClassFromName("System", "UInt32")->byval_arg;
static auto* sourceFontAsset = &::il2cpp_utils::GetClassFromName("TMPro", "TMP_FontAsset")->byval_arg;
static auto* includeFallbacks = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* fontStyle = &::il2cpp_utils::GetClassFromName("TMPro", "FontStyles")->byval_arg;
static auto* fontWeight = &::il2cpp_utils::GetClassFromName("TMPro", "FontWeight")->byval_arg;
static auto* isAlternativeTypeface = &::il2cpp_utils::GetClassFromName("System", "Boolean")->this_arg;
static auto* fontAsset = &::il2cpp_utils::GetClassFromName("TMPro", "TMP_FontAsset")->this_arg;
return ::il2cpp_utils::FindMethod(classof(TMPro::TMP_FontAssetUtilities*), "GetCharacterFromFontAsset_Internal", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{unicode, sourceFontAsset, includeFallbacks, fontStyle, fontWeight, isAlternativeTypeface, fontAsset});
}
};
// Writing MetadataGetter for method: TMPro::TMP_FontAssetUtilities::GetCharacterFromFontAssets
// Il2CppName: GetCharacterFromFontAssets
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::TMPro::TMP_Character* (*)(uint, ::System::Collections::Generic::List_1<::TMPro::TMP_FontAsset*>*, bool, ::TMPro::FontStyles, ::TMPro::FontWeight, ByRef<bool>, ByRef<::TMPro::TMP_FontAsset*>)>(&TMPro::TMP_FontAssetUtilities::GetCharacterFromFontAssets)> {
static const MethodInfo* get() {
static auto* unicode = &::il2cpp_utils::GetClassFromName("System", "UInt32")->byval_arg;
static auto* fontAssets = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System.Collections.Generic", "List`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("TMPro", "TMP_FontAsset")})->byval_arg;
static auto* includeFallbacks = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* fontStyle = &::il2cpp_utils::GetClassFromName("TMPro", "FontStyles")->byval_arg;
static auto* fontWeight = &::il2cpp_utils::GetClassFromName("TMPro", "FontWeight")->byval_arg;
static auto* isAlternativeTypeface = &::il2cpp_utils::GetClassFromName("System", "Boolean")->this_arg;
static auto* fontAsset = &::il2cpp_utils::GetClassFromName("TMPro", "TMP_FontAsset")->this_arg;
return ::il2cpp_utils::FindMethod(classof(TMPro::TMP_FontAssetUtilities*), "GetCharacterFromFontAssets", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{unicode, fontAssets, includeFallbacks, fontStyle, fontWeight, isAlternativeTypeface, fontAsset});
}
};
// Writing MetadataGetter for method: TMPro::TMP_FontAssetUtilities::TryGetCharacterFromFontFile
// Il2CppName: TryGetCharacterFromFontFile
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(uint, ::TMPro::TMP_FontAsset*, ByRef<::TMPro::TMP_Character*>)>(&TMPro::TMP_FontAssetUtilities::TryGetCharacterFromFontFile)> {
static const MethodInfo* get() {
static auto* unicode = &::il2cpp_utils::GetClassFromName("System", "UInt32")->byval_arg;
static auto* fontAsset = &::il2cpp_utils::GetClassFromName("TMPro", "TMP_FontAsset")->byval_arg;
static auto* character = &::il2cpp_utils::GetClassFromName("TMPro", "TMP_Character")->this_arg;
return ::il2cpp_utils::FindMethod(classof(TMPro::TMP_FontAssetUtilities*), "TryGetCharacterFromFontFile", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{unicode, fontAsset, character});
}
};
// Writing MetadataGetter for method: TMPro::TMP_FontAssetUtilities::TryGetGlyphFromFontFile
// Il2CppName: TryGetGlyphFromFontFile
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(uint, ::TMPro::TMP_FontAsset*, ByRef<::UnityEngine::TextCore::Glyph*>)>(&TMPro::TMP_FontAssetUtilities::TryGetGlyphFromFontFile)> {
static const MethodInfo* get() {
static auto* glyphIndex = &::il2cpp_utils::GetClassFromName("System", "UInt32")->byval_arg;
static auto* fontAsset = &::il2cpp_utils::GetClassFromName("TMPro", "TMP_FontAsset")->byval_arg;
static auto* glyph = &::il2cpp_utils::GetClassFromName("UnityEngine.TextCore", "Glyph")->this_arg;
return ::il2cpp_utils::FindMethod(classof(TMPro::TMP_FontAssetUtilities*), "TryGetGlyphFromFontFile", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{glyphIndex, fontAsset, glyph});
}
};
// Writing MetadataGetter for method: TMPro::TMP_FontAssetUtilities::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 74.424731 | 326 | 0.756483 | [
"object",
"vector"
] |
e565834f839fcc6a95bcd2139a804d572bdeed65 | 7,155 | cc | C++ | Algorithms/SegmentStats/SegmentStats.cc | jwillemsen/sidecar | 941d9f3b84d05ca405df1444d4d9fd0bde03887f | [
"MIT"
] | null | null | null | Algorithms/SegmentStats/SegmentStats.cc | jwillemsen/sidecar | 941d9f3b84d05ca405df1444d4d9fd0bde03887f | [
"MIT"
] | null | null | null | Algorithms/SegmentStats/SegmentStats.cc | jwillemsen/sidecar | 941d9f3b84d05ca405df1444d4d9fd0bde03887f | [
"MIT"
] | null | null | null | #include "SegmentStats.h"
#include "Messages/MetaTypeInfo.h"
#include "Messages/RadarConfig.h"
#include "boost/bind.hpp"
using namespace SideCar::Algorithms;
using namespace SideCar::Messages;
SegmentStats::SegmentStats(Controller& controller, Logger::Log& log) :
Algorithm(controller, log), deltaRange(Parameter::IntValue::Make("range/2", "Range / 2", 3)),
deltaAz(Parameter::IntValue::Make("azimuth/2", "Azimuth / 2", 6)),
maxRangeDrop(Parameter::NormalizedValue::Make("maxRangeDrop", "Max Range Drop", 0.5)),
maxAzDrop(Parameter::NormalizedValue::Make("maxAzimuthDrop", "Max Azimuth Drop", 0.5)),
minPower(Parameter::NormalizedValue::Make("minPower", "Min Power", 0.5)),
azimuthEncodings(RadarConfig::GetShaftEncodingMax() + 1), rangeGates(RadarConfig::GetGateCountMax()),
buffer(azimuthEncodings, rangeGates, deltaAz->getValue(), deltaRange->getValue()), row(buffer)
{
// use a circular buffer to source the video data
}
bool
SegmentStats::startup()
{
registerProcessor<SegmentStats, SegmentMessage>(&SegmentStats::processSegmentMessage);
registerProcessor<SegmentStats, Video>(&SegmentStats::processVideo);
return registerParameter(deltaRange) && registerParameter(deltaAz) && registerParameter(maxRangeDrop) &&
registerParameter(maxAzDrop) && registerParameter(minPower) && Algorithm::startup();
}
bool
SegmentStats::processSegmentMessage(SegmentMessage::Ref pri)
{
// Read in the message
SegmentList& in = *pri->data();
// Create a new message to send
SegmentMessage::Ref output(new SegmentMessage("SegmentStats", pri, pri->getRangeMin(), pri->getRangeFactor()));
SegmentList& out = *output->data();
// calculate the statistics in one pass
//
/*
Note on handling wraparound:
Normally one calculates the first moment by finding sum(bin*position)/sum(bin).
This doesn't work when there is a discontinuity (such as at 0==2pi).
Instead, calculate two independent first moments, one for [0,pi) and another for [pi,2pi).
Then look at the angle between these two moments to determine how things should resolve.
Only fails if the angle exceeds pi, which won't happen for a well-formed target.
*/
// Calculate the total power
const size_t pi = (RadarConfig::GetShaftEncodingMax() + 1) / 2;
double powerA = 0; // for [0,pi)
double powerB = 0; // for [pi,2pi)
// Calculate the power centroid
double powerAx = 0;
double powerBx = 0;
double powery = 0; // range doesn't wrap
// Find the peak power
VideoT peak = std::numeric_limits<VideoT>::min();
size_t peakRange = 0, peakAz = 0;
if (in.peakPower > peak) {
peak = in.peakPower;
peakRange = in.peakRange;
peakAz = in.peakAzimuth;
}
// The master loop
std::list<Segment>::const_iterator seg;
std::list<Segment>::const_iterator stop = in.data().end();
for (seg = in.data().begin(); seg != stop; seg++) {
out.merge(*seg); // Add this segment to the output
size_t azimuth = seg->azimuth;
for (size_t i = seg->start; i < seg->stop; i++) {
VideoT p = buffer.get(azimuth, i);
if (azimuth < pi) {
powerA += p;
powerAx += p * azimuth;
} else {
powerB += p;
powerBx += p * azimuth;
}
powery += p * i;
if (p > peak) {
peak = p;
peakRange = i;
peakAz = azimuth;
}
}
}
// Resolve the power centroid
const double dpi = (RadarConfig::GetShaftEncodingMax() + 1) / 2;
double power = powerA + powerB;
double powerx = (powerAx + powerBx) / power;
if (powerA && powerB) {
powerAx /= powerA;
powerBx /= powerB;
if (powerBx - powerAx >= dpi) {
if (powerA >= powerB) {
powerx -= dpi;
} else {
powerx += dpi;
}
}
}
powery /= power;
out.totalPower = power;
out.centroidRange = powery;
out.centroidAzimuth = powerx;
out.peakPower = peak;
out.peakRange = peakRange;
out.peakAzimuth = peakAz;
// Check for sharp fall-off at the edges ?? Average over a few PRI's to avoid modulation noise ??
//
size_t meanx = size_t(powerx + 0.5);
size_t meany = size_t(powery + 0.5);
const VideoT thresh = VideoT(power * minPower->getValue() / out.getCellCount());
out.distMinRange = findRangeEnd(meanx, meany, -deltaRange->getValue(), -1, thresh);
out.distMaxRange = findRangeEnd(meanx, meany, deltaRange->getValue(), rangeGates, thresh);
out.distMinAzimuth = findAzEnd(meany, meanx, -deltaAz->getValue(), -1, azimuthEncodings - 1, thresh);
out.distMaxAzimuth = findAzEnd(meany, meanx, deltaAz->getValue(), azimuthEncodings, 0, thresh);
return send(output);
}
// Go up to maxDistance from start. Stop at bound.
int
SegmentStats::findRangeEnd(size_t az, size_t start, int maxDistance, int bound, VideoT threshold)
{
int dir = 1;
if (maxDistance < 0) dir = -1;
int stop = start + maxDistance;
int shortStop = stop;
if (dir * stop > dir * bound) shortStop = bound;
double maxDrop = maxRangeDrop->getValue();
VideoT p0 = buffer.get(az, start);
int range;
for (range = start; range != shortStop; range += dir) {
// check
VideoT p = buffer.get(az, range);
if (p < threshold || p < maxDrop * p0) return range - start;
p0 = p;
}
return range - start;
}
// Go up to maxDistance from start. If bound is reached, continue from restart.
int
SegmentStats::findAzEnd(size_t range, size_t start, int maxDistance, int bound, size_t restart, VideoT threshold)
{
int dir = 1;
if (maxDistance < 0) dir = -1;
int stop = start + maxDistance;
int shortStop = stop;
if (dir * stop > dir * bound) shortStop = bound;
double maxDrop = maxAzDrop->getValue();
VideoT p0 = buffer.get(start, range);
for (int az = start; az != shortStop; az += dir) {
// check
VideoT p = buffer.get(az, range);
if (p < threshold || p < maxDrop * p0) return az - start;
p0 = p;
}
if (shortStop != stop) {
int newStop = stop - shortStop;
for (int az = restart; az != newStop; az += dir) {
// check
VideoT p = buffer.get(az, range);
if (p < threshold || p < maxDrop * p0) return (az - restart) + (shortStop - start);
p0 = p;
}
}
return maxDistance;
}
bool
SegmentStats::processVideo(Messages::Video::Ref msg)
{
msg->resize(buffer.getDataCols(), 0);
vsip::Dense<1, VideoT> mMsg(vsip::Domain<1>(buffer.getDataCols()), &msg[0]);
vsip::Vector<VideoT> vMsg(mMsg);
mMsg.admit(true);
currentRow = msg->getShaftEncoding();
row.setRow(currentRow);
row.v = vMsg;
mMsg.release(false);
return send(msg);
}
// DLL support
//
extern "C" ACE_Svc_Export Algorithm*
SegmentStatsMake(Controller& controller, Logger::Log& log)
{
return new SegmentStats(controller, log);
}
| 32.375566 | 115 | 0.620545 | [
"vector"
] |
e573ee28c2bee07d91b5dd9a249c20a63312f41c | 12,419 | cc | C++ | src/developer/debug/zxdb/client/stack.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 210 | 2019-02-05T12:45:09.000Z | 2022-03-28T07:59:06.000Z | src/developer/debug/zxdb/client/stack.cc | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | 5 | 2019-12-04T15:13:37.000Z | 2020-02-19T08:11:38.000Z | src/developer/debug/zxdb/client/stack.cc | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | 73 | 2019-03-06T18:55:23.000Z | 2022-03-26T12:04:51.000Z | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/developer/debug/zxdb/client/stack.h"
#include <lib/syslog/cpp/macros.h>
#include <map>
#include "src/developer/debug/ipc/records.h"
#include "src/developer/debug/shared/message_loop.h"
#include "src/developer/debug/zxdb/client/arch_info.h"
#include "src/developer/debug/zxdb/client/frame.h"
#include "src/developer/debug/zxdb/client/frame_fingerprint.h"
#include "src/developer/debug/zxdb/client/process.h"
#include "src/developer/debug/zxdb/client/session.h"
#include "src/developer/debug/zxdb/client/thread.h"
#include "src/developer/debug/zxdb/common/err.h"
#include "src/developer/debug/zxdb/expr/abi.h"
#include "src/developer/debug/zxdb/expr/eval_context_impl.h"
#include "src/developer/debug/zxdb/symbols/function.h"
#include "src/developer/debug/zxdb/symbols/process_symbols.h"
#include "src/lib/fxl/macros.h"
namespace zxdb {
namespace {
// Implementation of Frame for inlined frames. Inlined frames have a different location in the
// source code, but refer to the underlying physical frame for most data.
class InlineFrame final : public Frame {
public:
// The physical_frame must outlive this class. Normally both are owned by the Stack and have the
// same lifetime.
InlineFrame(Frame* physical_frame, Location loc)
: Frame(physical_frame->session()), physical_frame_(physical_frame), location_(loc) {}
~InlineFrame() override = default;
// Frame implementation.
Thread* GetThread() const override { return physical_frame_->GetThread(); }
bool IsInline() const override { return true; }
const Frame* GetPhysicalFrame() const override { return physical_frame_; }
const Location& GetLocation() const override { return location_; }
uint64_t GetAddress() const override { return location_.address(); }
const std::vector<debug::RegisterValue>* GetRegisterCategorySync(
debug::RegisterCategory category) const override {
return physical_frame_->GetRegisterCategorySync(category);
}
void GetRegisterCategoryAsync(
debug::RegisterCategory category, bool always_request,
fit::function<void(const Err&, const std::vector<debug::RegisterValue>&)> cb) override {
return physical_frame_->GetRegisterCategoryAsync(category, always_request, std::move(cb));
}
void WriteRegister(debug::RegisterID id, std::vector<uint8_t> data,
fit::callback<void(const Err&)> cb) override {
return physical_frame_->WriteRegister(id, std::move(data), std::move(cb));
}
std::optional<uint64_t> GetBasePointer() const override {
return physical_frame_->GetBasePointer();
}
void GetBasePointerAsync(fit::callback<void(uint64_t bp)> cb) override {
return physical_frame_->GetBasePointerAsync(std::move(cb));
}
uint64_t GetCanonicalFrameAddress() const override {
return physical_frame_->GetCanonicalFrameAddress();
}
uint64_t GetStackPointer() const override { return physical_frame_->GetStackPointer(); }
fxl::RefPtr<SymbolDataProvider> GetSymbolDataProvider() const override {
return physical_frame_->GetSymbolDataProvider();
}
fxl::RefPtr<EvalContext> GetEvalContext() const override {
if (!symbol_eval_context_) {
// Tolerate a null thread here because it makes testing much simpler. The EvalContext supports
// a null ProcessSymbols for this case.
fxl::WeakPtr<const ProcessSymbols> process_syms;
if (Thread* thread = GetThread())
process_syms = thread->GetProcess()->GetSymbols()->GetWeakPtr();
symbol_eval_context_ = fxl::MakeRefCounted<EvalContextImpl>(
session()->arch_info().abi(), process_syms, GetSymbolDataProvider(), location_);
}
return symbol_eval_context_;
}
bool IsAmbiguousInlineLocation() const override {
const Location& loc = GetLocation();
// Extract the inline function.
if (!loc.symbol())
return false;
const Function* function = loc.symbol().Get()->As<Function>();
if (!function)
return false;
if (!function->is_inline())
return false;
// There could be multiple code ranges for the inlined function, consider any of them as being a
// candidate.
for (const auto& cur : function->GetAbsoluteCodeRanges(loc.symbol_context())) {
if (loc.address() == cur.begin())
return true;
}
return false;
}
private:
Frame* physical_frame_; // Non-owning.
Location location_;
mutable fxl::RefPtr<EvalContextImpl> symbol_eval_context_; // Lazy.
FXL_DISALLOW_COPY_AND_ASSIGN(InlineFrame);
};
// Returns a fixed-up location referring to an indexed element in an inlined function call chain.
// This also handles the case where there are no inline calls and the function is the only one (this
// returns the same location).
//
// The main_location is the location returned by symbol lookup for the current address.
Location LocationForInlineFrameChain(const std::vector<fxl::RefPtr<Function>>& inline_chain,
size_t chain_index, const Location& main_location) {
// The file/line is the call location of the next (into the future) inlined function. Fall back on
// the file/line from the main lookup.
const FileLine* new_line = &main_location.file_line();
int new_column = main_location.column();
if (chain_index > 0) {
const Function* next_call = inline_chain[chain_index - 1].get();
if (next_call->call_line().is_valid()) {
new_line = &next_call->call_line();
new_column = 0; // DWARF doesn't contain inline call column.
}
}
return Location(main_location.address(), *new_line, new_column, main_location.symbol_context(),
inline_chain[chain_index]);
}
} // namespace
Stack::Stack(Delegate* delegate) : delegate_(delegate), weak_factory_(this) {}
Stack::~Stack() = default;
fxl::WeakPtr<Stack> Stack::GetWeakPtr() { return weak_factory_.GetWeakPtr(); }
std::optional<size_t> Stack::IndexForFrame(const Frame* frame) const {
for (size_t i = hide_ambiguous_inline_frame_count_; i < frames_.size(); i++) {
if (frames_[i].get() == frame)
return i - hide_ambiguous_inline_frame_count_;
}
return std::nullopt;
}
size_t Stack::InlineDepthForIndex(size_t index) const {
FX_DCHECK(index < frames_.size());
for (size_t depth = 0; index + depth < frames_.size(); depth++) {
if (!frames_[index + depth]->IsInline())
return depth;
}
FX_NOTREACHED(); // Should have found a physical frame that generated it.
return 0;
}
FrameFingerprint Stack::GetFrameFingerprint(size_t virtual_frame_index) const {
size_t frame_index = virtual_frame_index + hide_ambiguous_inline_frame_count_;
// Should reference a valid index in the array.
if (frame_index >= frames_.size()) {
FX_NOTREACHED();
return FrameFingerprint();
}
// The inline frame count is the number of steps from the requested frame index to the current
// physical frame.
size_t inline_count = InlineDepthForIndex(frame_index);
return FrameFingerprint(frames_[frame_index]->GetCanonicalFrameAddress(), inline_count);
}
size_t Stack::GetAmbiguousInlineFrameCount() const {
// This can't be InlineDepthForIndex() because that takes an index relative to the
// hide_ambiguous_inline_frame_count_ and this function always wants to return the same thing
// regardless of the hide count.
for (size_t i = 0; i < frames_.size(); i++) {
if (!frames_[i]->IsAmbiguousInlineLocation())
return i;
}
// Should always have a non-inline frame if there are any.
FX_DCHECK(frames_.empty());
return 0;
}
void Stack::SetHideAmbiguousInlineFrameCount(size_t hide_count) {
FX_DCHECK(hide_count <= GetAmbiguousInlineFrameCount());
hide_ambiguous_inline_frame_count_ = hide_count;
}
void Stack::SyncFrames(fit::callback<void(const Err&)> callback) {
delegate_->SyncFramesForStack(std::move(callback));
}
void Stack::SetFrames(debug_ipc::ThreadRecord::StackAmount amount,
const std::vector<debug_ipc::StackFrame>& new_frames) {
// See if the new frames are an extension of the existing frames or are a replacement.
size_t appending_from = 0; // First index in new_frames to append.
for (size_t i = 0; i < frames_.size(); i++) {
// The input will not contain any inline frames so skip over those when doing the checking.
if (frames_[i]->IsInline())
continue;
if (appending_from >= new_frames.size() ||
frames_[i]->GetAddress() != new_frames[appending_from].ip ||
frames_[i]->GetStackPointer() != new_frames[appending_from].sp) {
// New frames are not a superset of our existing stack, replace everything.
hide_ambiguous_inline_frame_count_ = 0;
frames_.clear();
appending_from = 0;
break;
}
appending_from++;
}
for (size_t i = appending_from; i < new_frames.size(); i++)
AppendFrame(new_frames[i]);
has_all_frames_ = amount == debug_ipc::ThreadRecord::StackAmount::kFull;
}
void Stack::SetFramesForTest(std::vector<std::unique_ptr<Frame>> frames, bool has_all) {
frames_ = std::move(frames);
has_all_frames_ = has_all;
hide_ambiguous_inline_frame_count_ = 0;
}
bool Stack::ClearFrames() {
has_all_frames_ = false;
hide_ambiguous_inline_frame_count_ = 0;
if (frames_.empty())
return false; // Nothing to do.
frames_.clear();
return true;
}
void Stack::AppendFrame(const debug_ipc::StackFrame& record) {
// This symbolizes all stack frames since the expansion of inline frames depends on the symbols.
// Its possible some stack objects will never have their frames queried which makes this duplicate
// work. A possible addition is to just save the debug_ipc::StackFrames and only expand the inline
// frames when the frame list is accessed.
// Indicates we're adding the newest physical frame and its inlines to the frame list.
bool is_top_physical_frame = frames_.empty();
// The symbols will provide the location for the innermost inlined function.
Location inner_loc = delegate_->GetSymbolizedLocationForStackFrame(record);
const Function* cur_func = inner_loc.symbol().Get()->As<Function>();
if (!cur_func) {
// No function associated with this location.
frames_.push_back(delegate_->MakeFrameForStack(record, inner_loc));
return;
}
// The Location object will reference the most-specific inline function but
// we need the whole chain.
std::vector<fxl::RefPtr<Function>> inline_chain = cur_func->GetInlineChain();
if (inline_chain.back()->is_inline()) {
// A non-inline frame was not found. The symbols are corrupt so give up on inline processing and
// add the physical frame only.
frames_.push_back(delegate_->MakeFrameForStack(record, inner_loc));
return;
}
// Need to make the base "physical" frame first because all of the inline frames refer to it.
auto physical_frame = delegate_->MakeFrameForStack(
record, LocationForInlineFrameChain(inline_chain, inline_chain.size() - 1, inner_loc));
// Add inline functions (skipping the last which is the physical frame made above).
for (size_t i = 0; i < inline_chain.size() - 1; i++) {
auto inline_frame = std::make_unique<InlineFrame>(
physical_frame.get(), LocationForInlineFrameChain(inline_chain, i, inner_loc));
// Only add ambiguous inline frames when they correspond to the top physical frame of the stack.
// The reason is that the instruction pointer of non-topmost stack frames represents the return
// address. An ambiguous inline frame means the return address is the beginning of an inlined
// function. This implies that the function call itself isn't actually in that inlined function.
//
// TODO(brettw) we may want to consider checking the address immediately before the IP for these
// frames and using that for inline frame computation. This may make the stack make more sense
// when a function call is the last part of an inline frame, but it also may make the line
// numbers for these frames inconsistent with how they're displayed for non-inlined frames.
if (is_top_physical_frame || !inline_frame->IsAmbiguousInlineLocation())
frames_.push_back(std::move(inline_frame));
}
// Physical frame goes last (back in time).
frames_.push_back(std::move(physical_frame));
}
} // namespace zxdb
| 40.851974 | 100 | 0.72526 | [
"object",
"vector"
] |
e575f08ed6080734682b5a6570dfc7de1a3efa9a | 7,775 | cpp | C++ | Gems/Atom/RHI/Vulkan/Code/Source/RHI/AliasingBarrierTracker.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-09-13T00:01:12.000Z | 2021-09-13T00:01:12.000Z | Gems/Atom/RHI/Vulkan/Code/Source/RHI/AliasingBarrierTracker.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | null | null | null | Gems/Atom/RHI/Vulkan/Code/Source/RHI/AliasingBarrierTracker.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-20T11:07:25.000Z | 2021-07-20T11:07:25.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include "Atom_RHI_Vulkan_precompiled.h"
#include <RHI/AliasingBarrierTracker.h>
#include <RHI/Buffer.h>
#include <RHI/Image.h>
#include <RHI/Scope.h>
#include <RHI/Conversion.h>
#include <RHI/Device.h>
namespace AZ
{
namespace Vulkan
{
AliasingBarrierTracker::AliasingBarrierTracker(Device& device)
:m_device(device)
{
}
void AliasingBarrierTracker::AppendBarrierInternal(const RHI::AliasedResource& beforeResource, const RHI::AliasedResource& afterResource)
{
// We only need a barrier if the old or new resource writes to memory.
bool needsBarrier = false;
VkPipelineStageFlags srcPipelineFlags = {};
VkPipelineStageFlags dstPipelineFlags = {};
VkAccessFlags srcAccessFlags = {};
VkAccessFlags dstAccessFlags = {};
const RHI::ImageBindFlags writeImageFlags = RHI::ImageBindFlags::ShaderWrite | RHI::ImageBindFlags::Color | RHI::ImageBindFlags::DepthStencil | RHI::ImageBindFlags::CopyWrite;
const RHI::BufferBindFlags writeBufferFlags = RHI::BufferBindFlags::ShaderWrite | RHI::BufferBindFlags::CopyWrite;
// Get the srcPipeline and srcAccessFlags from the resource (image or buffer)
if (beforeResource.m_type == RHI::AliasedResourceType::Image)
{
const Image* image = static_cast<const Image*>(beforeResource.m_resource);
const auto& bindFlags = image->GetDescriptor().m_bindFlags;
needsBarrier |= RHI::CheckBitsAny(bindFlags, writeImageFlags);
srcPipelineFlags = GetResourcePipelineStateFlags(bindFlags);
srcAccessFlags = GetResourceAccessFlags(bindFlags);
}
else // Buffer
{
const Buffer* buffer = static_cast<const Buffer*>(beforeResource.m_resource);
const auto& bindFlags = buffer->GetDescriptor().m_bindFlags;
needsBarrier |= RHI::CheckBitsAny(bindFlags, writeBufferFlags);
srcPipelineFlags = GetResourcePipelineStateFlags(bindFlags);
srcAccessFlags = GetResourceAccessFlags(bindFlags);
}
const auto& queueContext = m_device.GetCommandQueueContext();
const QueueId& oldQueueId = queueContext.GetCommandQueue(beforeResource.m_endScope->GetHardwareQueueClass()).GetId();
const QueueId& newQueueId = queueContext.GetCommandQueue(afterResource.m_beginScope->GetHardwareQueueClass()).GetId();
if (afterResource.m_type == RHI::AliasedResourceType::Image)
{
Image* image = static_cast<Image*>(afterResource.m_resource);
const auto& bindFlags = image->GetDescriptor().m_bindFlags;
needsBarrier |= RHI::CheckBitsAny(bindFlags, writeImageFlags);
dstPipelineFlags = GetResourcePipelineStateFlags(bindFlags);
dstAccessFlags = GetResourceAccessFlags(bindFlags);
if (!needsBarrier)
{
return;
}
// If the old and new queues are different, we will add a semaphore that
// serves as the memory dependency.
if (oldQueueId == newQueueId)
{
VkImageMemoryBarrier barrier = {};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.pNext = nullptr;
barrier.srcAccessMask = srcAccessFlags;
barrier.dstAccessMask = dstAccessFlags;
barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image->GetNativeImage();
barrier.subresourceRange.aspectMask = image->GetImageAspectFlags();
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.levelCount = image->GetDescriptor().m_mipLevels;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = image->GetDescriptor().m_arraySize;
static_cast<Scope*>(afterResource.m_beginScope)->QueueBarrier(Scope::BarrierSlot::Aliasing, srcPipelineFlags, dstPipelineFlags, barrier);
image->SetLayout(barrier.newLayout);
image->SetOwnerQueue(newQueueId);
}
}
else // Buffer
{
Buffer* buffer = static_cast<Buffer*>(afterResource.m_resource);
const auto& bindFlags = buffer->GetDescriptor().m_bindFlags;
needsBarrier |= RHI::CheckBitsAny(bindFlags, writeBufferFlags);
dstPipelineFlags = GetResourcePipelineStateFlags(bindFlags);
dstAccessFlags = GetResourceAccessFlags(bindFlags);
if (!needsBarrier)
{
return;
}
// If the old and new queues are different, we will add a semaphore that
// serves as the memory dependency.
if (oldQueueId == newQueueId)
{
const auto* bufferMemory = buffer->GetBufferMemoryView();
VkBufferMemoryBarrier barrier{};
barrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
barrier.pNext = nullptr;
barrier.srcAccessMask = srcAccessFlags;
barrier.dstAccessMask = dstAccessFlags;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.buffer = bufferMemory->GetNativeBuffer();
barrier.offset = bufferMemory->GetOffset() + afterResource.m_byteOffsetMin;
barrier.size = afterResource.m_byteOffsetMax - afterResource.m_byteOffsetMin + 1;
static_cast<Scope*>(afterResource.m_beginScope)->QueueBarrier(Scope::BarrierSlot::Aliasing, srcPipelineFlags, dstPipelineFlags, barrier);
buffer->SetOwnerQueue(newQueueId);
}
}
// If resources are in different queues then we need to add an execution dependency so
// we don't start using the aliased resource in the new scope before the old scope finishes.
// The framegraph does not handle this case because we have to remember that from its perspective
// these are two different resources that don't need a barrier/semaphore.
if (oldQueueId != newQueueId)
{
auto semaphore = m_device.GetSemaphoreAllocator().Allocate();
static_cast<Scope*>(beforeResource.m_endScope)->AddSignalSemaphore(semaphore);
static_cast<Scope*>(afterResource.m_beginScope)->AddWaitSemaphore(AZStd::make_pair(dstPipelineFlags, semaphore));
// This will not deallocate immediately.
m_barrierSemaphores.push_back(semaphore);
}
}
void AliasingBarrierTracker::EndInternal()
{
m_device.GetSemaphoreAllocator().DeAllocate(m_barrierSemaphores.data(), m_barrierSemaphores.size());
m_barrierSemaphores.clear();
}
}
}
| 51.833333 | 187 | 0.61955 | [
"3d"
] |
ec820f71a4fdff6749aaafda2fc1659aaf2938e1 | 954 | cc | C++ | angrygl/enemy_spawner.cc | lubomirjurukov/AngryGL | 795f07c6550e428e7c27fcdcd98430129428280a | [
"Apache-2.0"
] | 334 | 2020-01-04T01:52:40.000Z | 2022-03-16T11:36:15.000Z | angrygl/enemy_spawner.cc | lubomirjurukov/AngryGL | 795f07c6550e428e7c27fcdcd98430129428280a | [
"Apache-2.0"
] | 5 | 2021-02-11T23:41:10.000Z | 2021-05-18T11:12:11.000Z | angrygl/enemy_spawner.cc | lubomirjurukov/AngryGL | 795f07c6550e428e7c27fcdcd98430129428280a | [
"Apache-2.0"
] | 60 | 2020-02-20T23:50:59.000Z | 2022-03-02T13:23:13.000Z | #include "angrygl/enemy_spawner.h"
#include <cstdlib>
namespace {
const float enemySpawnInterval = 1.0f; // seconds
const int spawnsPerInterval = 1;
const float spawnRadius = 10.0f; // from player
} // namespace
EnemySpawner::EnemySpawner(float _monsterY, std::vector<Enemy>* _enemies) : enemies(_enemies), countdown(spawnsPerInterval), monsterY(_monsterY) {}
void EnemySpawner::update(const glm::vec3& playerPos, float deltaTimeSeconds) {
countdown -= deltaTimeSeconds;
if (countdown <= 0.0f) {
for (int i = 0; i < spawnsPerInterval; ++i) {
spawnEnemy(playerPos);
}
countdown += enemySpawnInterval;
}
}
void EnemySpawner::spawnEnemy(const glm::vec3& playerPos) {
const float theta = glm::radians((float)(rand() % 360));
const float x = playerPos.x + sin(theta) * spawnRadius;
const float z = playerPos.z + cos(theta) * spawnRadius;
enemies->emplace_back(glm::vec3(x, monsterY, z), glm::vec3(0.0f, 0.0f, 1.0f));
}
| 30.774194 | 147 | 0.701258 | [
"vector"
] |
ec83c1cb58fee8e95a06d73eb474d139d6b8375c | 2,093 | hh | C++ | include/NCPhysicsModel.hh | ramic-k/ncplugin-NJOY_NCrystal | e38fc58a78c2775470ed51ed7fae461a29318d43 | [
"Apache-2.0"
] | null | null | null | include/NCPhysicsModel.hh | ramic-k/ncplugin-NJOY_NCrystal | e38fc58a78c2775470ed51ed7fae461a29318d43 | [
"Apache-2.0"
] | null | null | null | include/NCPhysicsModel.hh | ramic-k/ncplugin-NJOY_NCrystal | e38fc58a78c2775470ed51ed7fae461a29318d43 | [
"Apache-2.0"
] | null | null | null | #ifndef NCPlugin_PhysicsModel_hh
#define NCPlugin_PhysicsModel_hh
#include "NCrystal/NCPluginBoilerplate.hh"//Common stuff (includes NCrystal
//public API headers, sets up
//namespaces and aliases)
namespace NCPluginNamespace {
//We implement the actual physics model in this completely custom C++ helper
//class. That decouples it from NCrystal interfaces (which is nice in case the
//NCrystal API changes at some point), and it makes it easy to directly
//instantiate and test the modelling implementation from standalone C++ code.
//
//We mark the class as MoveOnly, to make sure it doesn't get copied around by
//accident (since it could easily end up having large data members).
class PhysicsModel final : public NC::MoveOnly {
public:
//A few static helper functions which can extract relevant data from NCInfo
//objects (the createFromInfo function will raise BadInput exceptions in
//case of syntax errors in the @CUSTOM_ section data):
static bool isApplicable( const NC::Info& );
static PhysicsModel createFromInfo( const NC::Info& );//will raise BadInput in case of syntax errors
//The dummy model we are implementing is completely nonsense from a physics
//point of view, and provides a constant sigma for wavelengths below a
//certain cutoff value. Scatterings are isotropic and elastic.
//Constructor gets constant cross section value, and the neutron wavelength
//cutoff:
PhysicsModel( double sigma, double lambda_cutoff );
//Provide cross sections for a given neutron:
double calcCrossSection( double neutron_ekin ) const;
//Sample scattering event (rng is random number stream). Results are given
//as the final ekin of the neutron and scat_mu which is cos(scattering_angle).
struct ScatEvent { double ekin_final, mu; };
ScatEvent sampleScatteringEvent( NC::RandomBase& rng, double neutron_ekin ) const;
private:
//Data members:
double m_sigma;
double m_cutoffekin;
};
}
#endif
| 40.25 | 104 | 0.71763 | [
"model"
] |
ec8991dcbf9861e21f2567d8ded94a0a8daa0b70 | 2,179 | cpp | C++ | algorithms/kruskal_mst.cpp | oishikm12/cpp-collection | 4a454a6ed5b24570c7df0d4f0b692ae98c1ffa97 | [
"MIT"
] | 5 | 2021-05-17T12:32:42.000Z | 2021-12-12T21:09:55.000Z | algorithms/kruskal_mst.cpp | oishikm12/cpp-collection | 4a454a6ed5b24570c7df0d4f0b692ae98c1ffa97 | [
"MIT"
] | null | null | null | algorithms/kruskal_mst.cpp | oishikm12/cpp-collection | 4a454a6ed5b24570c7df0d4f0b692ae98c1ffa97 | [
"MIT"
] | 1 | 2021-05-13T20:29:57.000Z | 2021-05-13T20:29:57.000Z | #include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
vector<vector<int>> kruskalMST(vector<vector<int>> &graph);
int main() {
/**
* Kruskal's algorithm is implemented with the idea of sorting all
* the edges in a graph based on their weights, and then simply
* connecting those nodes in ascending, which do not form a circle
*/
cout << "\nThis program uses Kruskal's Algorithm to find out minimum spanning tree.\n" << endl;
int edges;
cout << "Enter the number of edges to consider: ";
cin >> edges;
vector<vector<int>> graph(edges, vector<int>(3));
cout << "Enter space seperated nodes in a edge and their weights, delimited by newline," << endl;
for (int i = 0; i < edges; i += 1) cin >> graph[i][0] >> graph[i][1] >> graph[i][2];
vector<vector<int>> mst = kruskalMST(graph);
int sum = 0;
cout << "\nThe resulting MST is," << endl;
for (auto &edge : mst) {
cout << edge[0] << " -> " << edge[1] << " => " << edge[2] << endl;
sum += edge[2];
}
cout << "\nThe cost incurred is: " << sum << "." << endl;
cout << endl;
return 0;
}
vector<vector<int>> kruskalMST(vector<vector<int>> &graph) {
// In order to find out minimal cost nodes we need to sort
// the edges on the basis of ascending travelling cost
sort(graph.begin(), graph.end(), [](vector<int> &a, vector<int> &b) {
return a[2] < b[2];
});
// Next we need to maintain visitation status of each node
// in order to prevent formation of a cycle
unordered_map<int, bool> visited;
for (auto &edge : graph) {
visited[edge[0]] = false;
visited[edge[1]] = false;
}
// We need a vector of vector to store valid connections
vector<vector<int>> result;
for (auto &edge : graph) {
// Since both the nodes have already been traversed, connecting
// them will create a loop, hence we ignore
if (visited[edge[0]] && visited[edge[1]]) continue;
result.push_back(edge);
visited[edge[0]] = true;
visited[edge[1]] = true;
}
return result;
} | 31.57971 | 101 | 0.601193 | [
"vector"
] |
ec8b88ffba3682ffd01e5d50718de568534c8e17 | 2,810 | cpp | C++ | src/PageBody.cpp | atzom/htmlCplusplus | ac4627c2515526b41f9fa692ff463e0be75a3041 | [
"BSD-3-Clause"
] | 3 | 2020-07-04T18:26:55.000Z | 2020-07-07T09:17:26.000Z | src/PageBody.cpp | atzom/htmlCplusplus | ac4627c2515526b41f9fa692ff463e0be75a3041 | [
"BSD-3-Clause"
] | null | null | null | src/PageBody.cpp | atzom/htmlCplusplus | ac4627c2515526b41f9fa692ff463e0be75a3041 | [
"BSD-3-Clause"
] | null | null | null | // BSD 3-Clause License
// Copyright (c) 2020, Andreas Tzomakas
// 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.
#include "Page.h"
#include "Tag.h"
#include <iostream>
#include "IParent.h"
using namespace std;
namespace htmlCplusplus
{
void Page::AddToBody(ITag *tag)
{
if (m_htmlBody != NULL)
{
m_htmlBody->Add(tag);
}
else
{
tag->Dispose();
}
}
void Page::SetBody(IHtmlBody *body)
{
m_htmlBody = body;
}
void Page::BodyAdd(string name, string content, bool escapeChars)
{
Tag *tag = new Tag(*m_ostream);
tag->SetName(name);
tag->SetContent(content, escapeChars);
if (m_autoRender)
{
tag->Render((Identation){m_Identation.Ident, m_Identation.IdentNumber, m_Identation.Level});
tag->Dispose();
}
else
AddToBody(tag);
}
void Page::BodyAdd(ITag *tag)
{
if (tag != NULL)
{
tag->SetStream(*m_ostream);
tag->SetBeautifier(m_Beautify);
if (m_autoRender)
tag->Render((Identation){m_Identation.Ident, m_Identation.IdentNumber, m_Identation.Level});
else
AddToBody(tag);
}
}
} // namespace htmlCplusplus
| 31.573034 | 108 | 0.668327 | [
"render"
] |
ec8bed7d0b8bc6878fc449f297a110c2ff2724ff | 1,783 | cpp | C++ | libfairygui/Classes/gears/GearAnimation.cpp | zeas2/FairyGUI-cocos2dx | c6ddaafc1b1bf51b0ef6929d6937c0cf111cd06a | [
"MIT"
] | null | null | null | libfairygui/Classes/gears/GearAnimation.cpp | zeas2/FairyGUI-cocos2dx | c6ddaafc1b1bf51b0ef6929d6937c0cf111cd06a | [
"MIT"
] | null | null | null | libfairygui/Classes/gears/GearAnimation.cpp | zeas2/FairyGUI-cocos2dx | c6ddaafc1b1bf51b0ef6929d6937c0cf111cd06a | [
"MIT"
] | null | null | null | #include "GearAnimation.h"
#include "GObject.h"
#include "utils/ToolSet.h"
#include "UIPackage.h"
NS_FGUI_BEGIN
USING_NS_CC;
GearAnimation::GearAnimationValue::GearAnimationValue() :frame(0), playing(false)
{
}
GearAnimation::GearAnimationValue::GearAnimationValue(bool playing, int frame)
{
this->playing = playing;
this->frame = frame;
}
GearAnimation::GearAnimation(GObject * owner) :GearBase(owner)
{
}
GearAnimation::~GearAnimation()
{
}
void GearAnimation::init()
{
IAnimationGear *ag = dynamic_cast<IAnimationGear*>(_owner);
_default = GearAnimationValue(ag->isPlaying(), ag->getCurrentFrame());
_storage.clear();
}
void GearAnimation::addStatus(const std::string& pageId, const std::string& value)
{
if (value == "-" || value.length() == 0)
return;
std::vector<std::string> arr;
ToolSet::splitString(value, ',', arr);
GearAnimationValue gv;
gv.frame = Value(arr[0]).asInt();
gv.playing = arr[1] == "p";
if (pageId.size() == 0)
_default = gv;
else
_storage[pageId] = gv;
}
void GearAnimation::apply()
{
_owner->_gearLocked = true;
GearAnimationValue gv;
auto it = _storage.find(_controller->getSelectedPageId());
if (it != _storage.end())
gv = it->second;
else
gv = _default;
IAnimationGear *ag = dynamic_cast<IAnimationGear*>(_owner);
ag->setPlaying(gv.playing);
ag->setCurrentFrame(gv.frame);
_owner->_gearLocked = false;
}
void GearAnimation::updateState()
{
IAnimationGear *ag = dynamic_cast<IAnimationGear*>(_owner);
_storage[_controller->getSelectedPageId()] = GearAnimationValue(ag->isPlaying(), ag->getCurrentFrame());
}
NS_FGUI_END | 22.2875 | 109 | 0.641615 | [
"vector"
] |
ec8bef69e2442b052a569d1869c773e3bcda1c8e | 1,471 | cpp | C++ | ecs/src/v2/model/ChangeSeversOsMetadata.cpp | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | 5 | 2021-03-03T08:23:43.000Z | 2022-02-16T02:16:39.000Z | ecs/src/v2/model/ChangeSeversOsMetadata.cpp | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | null | null | null | ecs/src/v2/model/ChangeSeversOsMetadata.cpp | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | 7 | 2021-02-26T13:53:35.000Z | 2022-03-18T02:36:43.000Z |
#include "huaweicloud/ecs/v2/model/ChangeSeversOsMetadata.h"
namespace HuaweiCloud {
namespace Sdk {
namespace Ecs {
namespace V2 {
namespace Model {
ChangeSeversOsMetadata::ChangeSeversOsMetadata()
{
userData_ = "";
userDataIsSet_ = false;
}
ChangeSeversOsMetadata::~ChangeSeversOsMetadata() = default;
void ChangeSeversOsMetadata::validate()
{
}
web::json::value ChangeSeversOsMetadata::toJson() const
{
web::json::value val = web::json::value::object();
if(userDataIsSet_) {
val[utility::conversions::to_string_t("user_data")] = ModelBase::toJson(userData_);
}
return val;
}
bool ChangeSeversOsMetadata::fromJson(const web::json::value& val)
{
bool ok = true;
if(val.has_field(utility::conversions::to_string_t("user_data"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("user_data"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setUserData(refVal);
}
}
return ok;
}
std::string ChangeSeversOsMetadata::getUserData() const
{
return userData_;
}
void ChangeSeversOsMetadata::setUserData(const std::string& value)
{
userData_ = value;
userDataIsSet_ = true;
}
bool ChangeSeversOsMetadata::userDataIsSet() const
{
return userDataIsSet_;
}
void ChangeSeversOsMetadata::unsetuserData()
{
userDataIsSet_ = false;
}
}
}
}
}
}
| 17.939024 | 100 | 0.67777 | [
"object",
"model"
] |
ec93580e171ddcf90bcb158eccf2d16a1f093388 | 2,655 | hpp | C++ | src/vigenere_square.hpp | tuokri/breakcipher | 4d326dc2ba1be18a9c0269a16864dbf75716b3ab | [
"MIT"
] | null | null | null | src/vigenere_square.hpp | tuokri/breakcipher | 4d326dc2ba1be18a9c0269a16864dbf75716b3ab | [
"MIT"
] | null | null | null | src/vigenere_square.hpp | tuokri/breakcipher | 4d326dc2ba1be18a9c0269a16864dbf75716b3ab | [
"MIT"
] | null | null | null | /**
* \file vigenere_square.hpp
* \brief vigenere_square header file.
*/
#ifndef VIGENERE_SQUARE_H
#define VIGENERE_SQUARE_H
#include <string>
#include <vector>
/**
* \class vigenere_square
* \brief Represents a Vigenère square initialized with a certain alphabet,
* to which strings can be passed for encryption or decryption.
*/
class vigenere_square
{
public:
/**
* \brief Default constructor.
*/
vigenere_square();
/**
* \brief Parametrized constructor.
* If i_alphabet contains duplicates, an exception is thrown.
* \param i_alphabet String to represent available characters.
* \throw std::invalid_argument.
*/
vigenere_square(const std::string& i_alphabet);
/**
* \brief Default destructor.
*/
virtual ~vigenere_square() = default;
/**
* \brief operator= overload. Copy assignment.
* \param rhs Reference to vigenere_square.
* \return Reference to vigenere_square.
*/
vigenere_square& operator=(const vigenere_square& rhs);
/**
* \brief String representation of the Vigenère table.
* \return std::string.
*/
std::string to_string() const;
/**
* \brief Print string representation to std::ostream.
* \param os Reference to std::ostream.
*/
void print(std::ostream& os) const;
/**
* \brief Encrypt a string using the vigenere_square instance's
* data member table.
* \param plaintext Reference to the string to be encrypted.
* \param key Reference to the key used in encryption.
* \return Encrypted string.
*/
std::string encrypt(const std::string& plaintext,
const std::string& key);
/**
* \brief Decrypt a string using the vigenere_square instance's
* data member table.
* \param cipher Reference to the string to be decrypted.
* \param key Reference to the key used in decryption.
* \return Decrypted string.
*/
std::string decrypt(const std::string& chipher,
const std::string& key);
private:
std::string alphabet;
std::vector<std::string> table;
};
/**
* \brief operator<< overload.
* \param os Reference to std::ostream.
* \param vsq Reference to vigenere_square.
* \return Reference to std::ostream.
*/
std::ostream& operator<<(std::ostream& os, const vigenere_square& vsq);
#endif // VIGENERE_SQUARE_H
| 28.858696 | 76 | 0.592844 | [
"vector"
] |
ec969b6e9bc82737efb8fa6200a98fb605c20a44 | 7,804 | cpp | C++ | TiCore/runtime/ObjectPrototype.cpp | vishalduggal/tijscore | 0b20b5731766628109bdd2c657558de9d5a976ec | [
"MS-PL",
"Naumen",
"Condor-1.1",
"Apache-1.1"
] | null | null | null | TiCore/runtime/ObjectPrototype.cpp | vishalduggal/tijscore | 0b20b5731766628109bdd2c657558de9d5a976ec | [
"MS-PL",
"Naumen",
"Condor-1.1",
"Apache-1.1"
] | null | null | null | TiCore/runtime/ObjectPrototype.cpp | vishalduggal/tijscore | 0b20b5731766628109bdd2c657558de9d5a976ec | [
"MS-PL",
"Naumen",
"Condor-1.1",
"Apache-1.1"
] | null | null | null | /**
* Appcelerator Titanium License
* This source code and all modifications done by Appcelerator
* are licensed under the Apache Public License (version 2) and
* are Copyright (c) 2009-2012 by Appcelerator, Inc.
*/
/*
* Copyright (C) 1999-2000 Harri Porten (porten@kde.org)
* Copyright (C) 2008, 2011 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "config.h"
#include "ObjectPrototype.h"
#include "Error.h"
#include "TiFunction.h"
#include "TiString.h"
#include "TiStringBuilder.h"
namespace TI {
static EncodedTiValue JSC_HOST_CALL objectProtoFuncValueOf(TiExcState*);
static EncodedTiValue JSC_HOST_CALL objectProtoFuncHasOwnProperty(TiExcState*);
static EncodedTiValue JSC_HOST_CALL objectProtoFuncIsPrototypeOf(TiExcState*);
static EncodedTiValue JSC_HOST_CALL objectProtoFuncDefineGetter(TiExcState*);
static EncodedTiValue JSC_HOST_CALL objectProtoFuncDefineSetter(TiExcState*);
static EncodedTiValue JSC_HOST_CALL objectProtoFuncLookupGetter(TiExcState*);
static EncodedTiValue JSC_HOST_CALL objectProtoFuncLookupSetter(TiExcState*);
static EncodedTiValue JSC_HOST_CALL objectProtoFuncPropertyIsEnumerable(TiExcState*);
static EncodedTiValue JSC_HOST_CALL objectProtoFuncToLocaleString(TiExcState*);
}
#include "ObjectPrototype.lut.h"
namespace TI {
const ClassInfo ObjectPrototype::s_info = { "Object", &JSNonFinalObject::s_info, 0, TiExcState::objectPrototypeTable };
/* Source for ObjectPrototype.lut.h
@begin objectPrototypeTable
toString objectProtoFuncToString DontEnum|Function 0
toLocaleString objectProtoFuncToLocaleString DontEnum|Function 0
valueOf objectProtoFuncValueOf DontEnum|Function 0
hasOwnProperty objectProtoFuncHasOwnProperty DontEnum|Function 1
propertyIsEnumerable objectProtoFuncPropertyIsEnumerable DontEnum|Function 1
isPrototypeOf objectProtoFuncIsPrototypeOf DontEnum|Function 1
__defineGetter__ objectProtoFuncDefineGetter DontEnum|Function 2
__defineSetter__ objectProtoFuncDefineSetter DontEnum|Function 2
__lookupGetter__ objectProtoFuncLookupGetter DontEnum|Function 1
__lookupSetter__ objectProtoFuncLookupSetter DontEnum|Function 1
@end
*/
ASSERT_CLASS_FITS_IN_CELL(ObjectPrototype);
ObjectPrototype::ObjectPrototype(TiExcState* exec, TiGlobalObject* globalObject, Structure* stucture)
: JSNonFinalObject(exec->globalData(), stucture)
, m_hasNoPropertiesWithUInt32Names(true)
{
ASSERT(inherits(&s_info));
putAnonymousValue(globalObject->globalData(), 0, globalObject);
}
void ObjectPrototype::put(TiExcState* exec, const Identifier& propertyName, TiValue value, PutPropertySlot& slot)
{
JSNonFinalObject::put(exec, propertyName, value, slot);
if (m_hasNoPropertiesWithUInt32Names) {
bool isUInt32;
propertyName.toUInt32(isUInt32);
m_hasNoPropertiesWithUInt32Names = !isUInt32;
}
}
bool ObjectPrototype::getOwnPropertySlot(TiExcState* exec, unsigned propertyName, PropertySlot& slot)
{
if (m_hasNoPropertiesWithUInt32Names)
return false;
return JSNonFinalObject::getOwnPropertySlot(exec, propertyName, slot);
}
bool ObjectPrototype::getOwnPropertySlot(TiExcState* exec, const Identifier& propertyName, PropertySlot &slot)
{
return getStaticFunctionSlot<JSNonFinalObject>(exec, TiExcState::objectPrototypeTable(exec), this, propertyName, slot);
}
bool ObjectPrototype::getOwnPropertyDescriptor(TiExcState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)
{
return getStaticFunctionDescriptor<JSNonFinalObject>(exec, TiExcState::objectPrototypeTable(exec), this, propertyName, descriptor);
}
// ------------------------------ Functions --------------------------------
EncodedTiValue JSC_HOST_CALL objectProtoFuncValueOf(TiExcState* exec)
{
TiValue thisValue = exec->hostThisValue();
return TiValue::encode(thisValue.toThisObject(exec));
}
EncodedTiValue JSC_HOST_CALL objectProtoFuncHasOwnProperty(TiExcState* exec)
{
TiValue thisValue = exec->hostThisValue();
return TiValue::encode(jsBoolean(thisValue.toThisObject(exec)->hasOwnProperty(exec, Identifier(exec, exec->argument(0).toString(exec)))));
}
EncodedTiValue JSC_HOST_CALL objectProtoFuncIsPrototypeOf(TiExcState* exec)
{
TiValue thisValue = exec->hostThisValue();
TiObject* thisObj = thisValue.toThisObject(exec);
if (!exec->argument(0).isObject())
return TiValue::encode(jsBoolean(false));
TiValue v = asObject(exec->argument(0))->prototype();
while (true) {
if (!v.isObject())
return TiValue::encode(jsBoolean(false));
if (v == thisObj)
return TiValue::encode(jsBoolean(true));
v = asObject(v)->prototype();
}
}
EncodedTiValue JSC_HOST_CALL objectProtoFuncDefineGetter(TiExcState* exec)
{
TiValue thisValue = exec->hostThisValue();
CallData callData;
if (getCallData(exec->argument(1), callData) == CallTypeNone)
return throwVMError(exec, createSyntaxError(exec, "invalid getter usage"));
thisValue.toThisObject(exec)->defineGetter(exec, Identifier(exec, exec->argument(0).toString(exec)), asObject(exec->argument(1)));
return TiValue::encode(jsUndefined());
}
EncodedTiValue JSC_HOST_CALL objectProtoFuncDefineSetter(TiExcState* exec)
{
TiValue thisValue = exec->hostThisValue();
CallData callData;
if (getCallData(exec->argument(1), callData) == CallTypeNone)
return throwVMError(exec, createSyntaxError(exec, "invalid setter usage"));
thisValue.toThisObject(exec)->defineSetter(exec, Identifier(exec, exec->argument(0).toString(exec)), asObject(exec->argument(1)));
return TiValue::encode(jsUndefined());
}
EncodedTiValue JSC_HOST_CALL objectProtoFuncLookupGetter(TiExcState* exec)
{
TiValue thisValue = exec->hostThisValue();
return TiValue::encode(thisValue.toThisObject(exec)->lookupGetter(exec, Identifier(exec, exec->argument(0).toString(exec))));
}
EncodedTiValue JSC_HOST_CALL objectProtoFuncLookupSetter(TiExcState* exec)
{
TiValue thisValue = exec->hostThisValue();
return TiValue::encode(thisValue.toThisObject(exec)->lookupSetter(exec, Identifier(exec, exec->argument(0).toString(exec))));
}
EncodedTiValue JSC_HOST_CALL objectProtoFuncPropertyIsEnumerable(TiExcState* exec)
{
TiValue thisValue = exec->hostThisValue();
return TiValue::encode(jsBoolean(thisValue.toThisObject(exec)->propertyIsEnumerable(exec, Identifier(exec, exec->argument(0).toString(exec)))));
}
EncodedTiValue JSC_HOST_CALL objectProtoFuncToLocaleString(TiExcState* exec)
{
TiValue thisValue = exec->hostThisValue();
return TiValue::encode(thisValue.toThisTiString(exec));
}
EncodedTiValue JSC_HOST_CALL objectProtoFuncToString(TiExcState* exec)
{
TiValue thisValue = exec->hostThisValue();
return TiValue::encode(jsMakeNontrivialString(exec, "[object ", thisValue.toThisObject(exec)->className(), "]"));
}
} // namespace TI
| 40.435233 | 148 | 0.751281 | [
"object"
] |
ec9c097d2dc1dfcd3c0884a55790fe88e4ab6a9e | 4,062 | cpp | C++ | src/qfhydrate.cpp | tomicooler/quickflux | 0b0a144afa54a397382605ccea52286107678cb9 | [
"Apache-2.0"
] | 306 | 2015-06-12T11:18:53.000Z | 2022-02-25T09:53:07.000Z | src/qfhydrate.cpp | tomicooler/quickflux | 0b0a144afa54a397382605ccea52286107678cb9 | [
"Apache-2.0"
] | 32 | 2015-06-23T18:11:21.000Z | 2021-10-08T21:27:10.000Z | src/qfhydrate.cpp | tomicooler/quickflux | 0b0a144afa54a397382605ccea52286107678cb9 | [
"Apache-2.0"
] | 74 | 2015-12-14T13:12:06.000Z | 2022-02-02T09:22:55.000Z | #include <QtCore>
#include <QVariantMap>
#include "qfhydrate.h"
#include "qfobject.h"
#include "qfstore.h"
#include <functional>
static QVariantMap dehydrator(QObject* source);
static auto dehydratorFunction = [](const QStringList& ignoreList) -> std::function<QVariantMap (QObject *)> {
return [=](QObject* source) {
QVariantMap dest;
const QMetaObject* meta = source->metaObject();
for (int i = 0 ; i < meta->propertyCount(); i++) {
const QMetaProperty property = meta->property(i);
const char* name = property.name();
QString stringName = name;
if (ignoreList.indexOf(stringName) >= 0) {
continue;
}
QVariant value = source->property(name);
if (value.canConvert<QObject*>()) {
QObject* object = value.value<QObject*>();
if (!object) {
continue;
}
value = dehydrator(object);
}
dest[stringName] = value;
}
return dest;
};
};
static auto dehydrateQObject = dehydratorFunction(QStringList() << "parent" << "objectName");
static auto dehydrateQFObject = dehydratorFunction(QStringList() << "parent" << "objectName" << "children");
static auto dehydrateQFStore = dehydratorFunction(QStringList() << "parent" << "objectName" << "children" << "bindSource" << "redispatchTargets" << "filterFunctionEnabled");
/// Default dehydrator function
static QVariantMap dehydrator(QObject* source) {
QVariantMap ret;
if (qobject_cast<QFStore*>(source)) {
ret = dehydrateQFStore(source);
} else if (qobject_cast<QFObject*>(source)) {
ret = dehydrateQFObject(source);
} else {
ret = dehydrateQObject(source);
}
return ret;
}
/*!
\qmltype Hydrate
\inqmlmodule QuickFlux
\code
import QuickFlux 1.1
\endcode
Hydrate provides an interface to rehydrate / hydrate a Store component. Rehydration and dehydration are just another words for deserialize and serialize. It could be used to convert Store into JSON object, and vice versa.
Remarks: Hydrate supports any QObject based type as the target of deserialize and serialize.
\code
Hydrate.rehydrate(store, {
value1: 1,
value2: 2.0,
value3: "",
value4: {
subValue1: 1
}
});
var data = Hydrate.dehydrate(MainStore);
console.log(JSON.stringify(data));
\endcode
It is added since Quick Flux 1.1
*/
QFHydrate::QFHydrate(QObject *parent) : QObject(parent)
{
}
/*!
\qmlmethod Hydrate::rehydrate(target, source)
Deserialize data from source and write to target object.
\code
Hydrate.rehydrate(store, {
value1: 1,
value2: 2.0,
value3: "",
value4: {
subValue1: 1
}
\endcode
*/
void QFHydrate::rehydrate(QObject *dest, const QVariantMap &source)
{
const QMetaObject* meta = dest->metaObject();
QMap<QString,QVariant>::const_iterator iter = source.begin();
while (iter != source.end()) {
QByteArray key = iter.key().toLocal8Bit();
int index = meta->indexOfProperty(key.constData());
if (index < 0) {
qWarning() << QString("Hydrate.rehydrate: %1 property is not existed").arg(iter.key());
iter++;
continue;
}
QVariant orig = dest->property(key.constData());
QVariant value = source[iter.key()];
if (orig.canConvert<QObject*>()) {
if (value.type() != QVariant::Map) {
qWarning() << QString("Hydrate.rehydrate: expect a QVariantMap property but it is not: %1");
} else {
rehydrate(orig.value<QObject*>(), value.toMap());
}
} else if (orig != value) {
dest->setProperty(key.constData(), value);
}
iter++;
}
}
/*!
\qmlmethod Hydrate::dehydrate(object)
Serialize data from a object
\code
var data = Hydrate.dehydrate(MainStore);
console.log(JSON.stringify(data));
\endcode
*/
QVariantMap QFHydrate::dehydrate(QObject *source)
{
return dehydrator(source);
}
| 25.708861 | 221 | 0.622107 | [
"object"
] |
ecaa16253fbab88424ed1c0e46c4d24b5d284ccf | 5,508 | hpp | C++ | al5d_low_level_driver/test/AL5DLowLevelDriverTests.hpp | User-TGK/franka_robot_control | 48d62b2056aca2226cbe5ac3914f01bef3659f49 | [
"MIT"
] | 3 | 2019-12-12T13:09:49.000Z | 2021-09-07T09:08:56.000Z | al5d_low_level_driver/test/AL5DLowLevelDriverTests.hpp | User-TGK/franka_robot_control | 48d62b2056aca2226cbe5ac3914f01bef3659f49 | [
"MIT"
] | null | null | null | al5d_low_level_driver/test/AL5DLowLevelDriverTests.hpp | User-TGK/franka_robot_control | 48d62b2056aca2226cbe5ac3914f01bef3659f49 | [
"MIT"
] | null | null | null | #ifndef AL5D_LOW_LEVEL_DRIVER_TESTS_
#define AL5D_LOW_LEVEL_DRIVER_TESTS_
#include <gtest/gtest.h>
#include <Driver.hpp>
namespace RobotControl
{
namespace Al5dLowLevelDriver
{
/**
* @brief function to set an example set of DoF's (used in the following unittests)
* @author Ties Klappe
*
* @return std::vector<RobotControl::Al5dLowLevelDriver::DegreeOfFreedom> the example DoF set
*/
std::vector<RobotControl::Al5dLowLevelDriver::DegreeOfFreedom> setDoFs()
{
std::vector<RobotControl::Al5dLowLevelDriver::DegreeOfFreedom> degreeOfFreedoms;
degreeOfFreedoms.push_back(RobotControl::Al5dLowLevelDriver::DegreeOfFreedom(0, 500, 2500, -90, 90, 272.73, 0, 0)); // AL5D's - Base servo
degreeOfFreedoms.push_back(RobotControl::Al5dLowLevelDriver::DegreeOfFreedom(1, 500, 2500, -90, 90, 315.79, 0, 0)); // AL5D's - Turret servo
degreeOfFreedoms.push_back(RobotControl::Al5dLowLevelDriver::DegreeOfFreedom(2, 500, 2500, -90, 90, 214.29, 0, 0)); // AL5D's - Upperarm servo
degreeOfFreedoms.push_back(RobotControl::Al5dLowLevelDriver::DegreeOfFreedom(3, 500, 2500, -90, 90, 250.00, 0, 0)); // AL5D's - Forearm servo
degreeOfFreedoms.push_back(RobotControl::Al5dLowLevelDriver::DegreeOfFreedom(4, 500, 2500, -90, 90, 285.71, 0, 0)); // AL5D's - Gripper
degreeOfFreedoms.push_back(RobotControl::Al5dLowLevelDriver::DegreeOfFreedom(5, 500, 2500, -90, 90, 285.71, 0, 0)); // AL5D's - Wrist servo
return degreeOfFreedoms;
}
/**
* @brief Unittests for the DegreeOfFreedom class that tests if a pulse width is correctly converted
* from an angle (in degrees) and its alternative flows: if an angle is above the maximum angle
* it will return the maximum pulse width (Alternative flowA) and if an angle is under the minimum angle it will
* return the minimum pulse width (Alternative flow B)
* @author Ties Klappe
*/
TEST (DegreeOfFreedomSuite, PulseWidthFromAngleTest)
{
DegreeOfFreedom doF(0, 500, 2500, -90, 90, 272.73, 0, 0);
ASSERT_EQ(doF.pulseWidthFromAngle(0), 1500);
ActionParser actionParser(setDoFs(), 6);
ASSERT_EQ(actionParser.toAngle(0, 1396), -9.36);
ASSERT_EQ(actionParser.toAngle(0, 300), -90); // Alternative flow A
ASSERT_EQ(actionParser.toAngle(0, 3000), 90); // Alternative flow B
}
/**
* @brief Unittests for the DegreeOfFreedom class that tests if an angle is correctly converted from
* a pulse width and its alternative flows: if a pulse width is above the maximum pulse width
* it will return the maximum angle (in degrees) (Alternative flow A) and if a pulse width is under the minimum
* pulse width it will return the minimum angle (Alternative flow B)
* @author Ties Klappe
*/
TEST (DegreeOfFreedomSuite, AngleFromPulseWidthTest)
{
DegreeOfFreedom doF(0, 500, 2500, -90, 90, 272.73, 0, 0);
ASSERT_EQ(doF.angleFromPulseWidth(1500), 0);
ASSERT_EQ(doF.angleFromPulseWidth(100), -90); // Alternative flow A
ASSERT_EQ(doF.angleFromPulseWidth(2600), 90); // Alternative flow B
}
/**
* @brief Unittests for the convertion of a speed in rad/second to its mapped pulse with
* @author Ties Klappe
*
*/
TEST (DegreeOfFreedomSuite, PulseWidthSpeedFromDegreesPerSecondTest)
{
DegreeOfFreedom doF(0, 500, 2500, -90, 90, 272.73, 0, 0);
ASSERT_EQ(doF.getConvertedSpeedFromDegreesPerSecond(100), 916);
ASSERT_EQ(doF.getConvertedSpeedFromDegreesPerSecond(10), 500);
ASSERT_EQ(doF.getConvertedSpeedFromDegreesPerSecond(400), 2500);
}
/**
* @brief Unittests for the SSC32U action parser class: it will check if an Al5dConfigurationGoal
* is correctly parsed into a SSC32U Command string and if the last possible finished time is correctly calculated
* @author Ties Klappe
*
*/
TEST (SSC32UActionParserSuite, SSC32UCommandTest)
{
ActionParser actionParser(setDoFs(), 6);
al5d_low_level_driver::Al5dConfigurationGoal initGoal;
al5d_low_level_driver::DoFConfiguration configurationMessage;
initGoal.time = 0;
configurationMessage.channel = 0;
configurationMessage.angle = 50;
configurationMessage.speed = 55;
initGoal.configuration.push_back(configurationMessage);
auto goal = boost::make_shared<al5d_low_level_driver::Al5dConfigurationGoal>(initGoal);
ASSERT_EQ(actionParser.configurationToSSC32UCommandString(goal), "#0P2055S504\r");
ASSERT_EQ(actionParser.getLastFinishedTime(goal), 653);
}
/**
* @brief Unittest for the actionparser class: it will check if local stored configuration is correctly
* updated and used.
* @author Ties Klappe
*
*/
TEST (SSC32UActionParserSuite, LocalConfigurationTest)
{
ActionParser actionParser(setDoFs(), 6);
al5d_low_level_driver::Al5dConfigurationGoal targetGoal;
al5d_low_level_driver::DoFConfiguration configurationMessage;
targetGoal.time = 0;
configurationMessage.channel = 0;
configurationMessage.angle = 50;
configurationMessage.speed = 55;
targetGoal.configuration.push_back(configurationMessage);
auto goal = boost::make_shared<al5d_low_level_driver::Al5dConfigurationGoal>(targetGoal);
actionParser.setTargetPositions(goal);
std::map<unsigned short, unsigned long> currentPositions;
for (const auto& doF: actionParser.getDegreeOfFreedoms())
{
currentPositions.insert(std::pair<unsigned short, unsigned long>(doF.getChannel(), doF.getTargetPos()));
}
actionParser.updateCurrentPositions(currentPositions);
ASSERT_EQ(actionParser.toAngle(0, 500), -90);
}
}
}
#endif //AL5D_LOW_LEVEL_DRIVER_TESTS_ | 39.06383 | 148 | 0.748184 | [
"vector"
] |
ecafe06a5ae4c50d58cae6dd4a680d65cee3be26 | 2,565 | hpp | C++ | include/atomistic/fundamental.hpp | ltalirz/util-programs | 93c76cb8f52543b55afdd968f6d8374997031a27 | [
"MIT"
] | null | null | null | include/atomistic/fundamental.hpp | ltalirz/util-programs | 93c76cb8f52543b55afdd968f6d8374997031a27 | [
"MIT"
] | null | null | null | include/atomistic/fundamental.hpp | ltalirz/util-programs | 93c76cb8f52543b55afdd968f6d8374997031a27 | [
"MIT"
] | null | null | null | /**
* @file fundamental.hpp
* Some classes describing fundamental atomistic concepts.
*/
#ifndef ATOMISTIC_FUNDAMENTAL_HPP
#define ATOMISTIC_FUNDAMENTAL_HPP
#include "types.hpp"
#include "la.hpp"
namespace atomistic {
//class EigenState {
// types::Real energy;
// WfnCube cube;
//
// types::Real getEnergy() const { return energy;}
// const WfnCube & getCube() const { return waveFunction;}
//};
/**
* An array of energy levels.
*/
class EnergyLevels {
std::vector<types::Real> levels;
types::Real fermi;
public:
EnergyLevels(std::vector<types::Real> levels, types::Real fermi);
EnergyLevels(const EnergyLevels& e);
EnergyLevels() {};
void join(EnergyLevels e2);
EnergyLevels & operator*=(types::Real factor);
void sort();
types::Uint count() const;
types::Uint countOccupied() const;
void print() const;
void shift(types::Real deltaE);
void setFermiZero();
const std::vector<types::Real> & getLevels() const { return levels; };
void setLevels(const std::vector<types::Real> l) { levels = l; };
types::Real getFermi() const { return fermi; }
void setFermi(types::Real f) { fermi = f; }
bool rangeCheck(types::Uint i) const;
types::Real getLevel(types::Uint i) const {
if(rangeCheck(i)) return levels[i-1];
else return false;
}
void setLevel(types::Uint i, types::Real value) {
if(rangeCheck(i)) levels[i-1] = value;
}
};
/**
* Representation of an atomic core in an atomistic simulation.
*/
struct Atom {
std::vector<types::Real> coordinates;
types::Uint number;
types::Real charge;
types::String symbol;
Atom(std::vector<types::Real> coordinates,
types::Uint number,
types::Real charge) :
coordinates(coordinates), number(number), charge(charge) {};
Atom(std::vector<types::Real> coordinates): coordinates(coordinates) {};
Atom() { }
const std::vector<types::Real> &getCoordinates () const {
return coordinates;
}
types::Uint getNumber() const {
return number;
}
types::Real getCharge() const {
return charge;
}
types::String getSymbol() const {
return symbol;
}
types::Real distance(const Atom& a) const;
friend class Cube;
};
//class LDOS {
// private:
// std::vector< types::Real > energies;
// std::vector< types::Real > densities;
// public:
// LDOS(const std::vector< std::vector<types::Real> > & levels, types::Real broadening);
//};
}
#endif
| 24.663462 | 95 | 0.62729 | [
"vector"
] |
ecb2cd409aa164c7ccc24a8a91f50a243b2eaeed | 1,917 | cpp | C++ | Geometria/Application/Application.cpp | TheNachoBIT/TheRetroFunkProject | f2ae65e8a6659987e9735ac3b668b132e460c615 | [
"MIT",
"BSD-3-Clause"
] | 7 | 2021-12-01T07:16:49.000Z | 2022-01-20T03:34:13.000Z | Geometria/Application/Application.cpp | TheNachoBIT/TheRetroFunkProject | f2ae65e8a6659987e9735ac3b668b132e460c615 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | Geometria/Application/Application.cpp | TheNachoBIT/TheRetroFunkProject | f2ae65e8a6659987e9735ac3b668b132e460c615 | [
"MIT",
"BSD-3-Clause"
] | 2 | 2021-12-14T19:19:37.000Z | 2021-12-16T21:09:46.000Z | #include "Application.h"
#include "../Behaviours/Behaviour.h"
#include "../Graphics/Cores/MainAPI/Graphics.h"
#include "../Graphics/Cores/Renderer/RendererCore.h"
#include "../Graphics/Externals/SceneAndDrawCall.h"
//SCENES
//#include "../Game/SampleScene.tits.h"
#include "../Game/GameMain.h"
#include "../Editor/Editor.h"
#include "../Graphics/Cores/Texture/Texture.h"
#include "Multithreading/Multithreading.h"
Application::State Application::_engineState;
bool Application::IsPlatform(Platform p)
{
Platform currentPlatform;
#ifdef _WIN32
currentPlatform = Platform::Windows;
#endif
#ifdef __linux__
currentPlatform = Platform::Linux;
#endif
return p == currentPlatform;
}
void Application::SetEditor()
{
Application::_engineState = State::Editor;
Hierarchy::StartScripts();
Editor::SwitchEditorView();
}
void Application::SetGame()
{
Application::_engineState = State::Game;
Hierarchy::StartScripts();
Editor::SwitchGameView();
}
void Application::Start()
{
TextureManager::ClearRAM();
RendererCore::EndThreads();
Multithreading::Start();
for (int i = 0; i < Hierarchy::allScripts.size(); i++)
{
if (Hierarchy::allScripts[i] != nullptr)
Hierarchy::allScripts[i]->DestroyScript();
Hierarchy::allScripts[i] = nullptr;
}
Hierarchy::allStaticScripts.clear();
std::vector<ScriptBehaviour*>().swap(Hierarchy::allStaticScripts);
Hierarchy::listOfStaticScripts.clear();
std::vector<std::string>().swap(Hierarchy::listOfStaticScripts);
Hierarchy::allScripts.clear();
std::vector<ScriptBehaviour*>().swap(Hierarchy::allScripts);
Graphics::MainCamera() = new Camera(Vector3(0, 0, 2), 70.0f, (float)Graphics::GetMainWindow().width / (float)Graphics::GetMainWindow().height, 0.1f, 1000.0f);
Graphics::MainCamera()->objectClassName = "Main Camera";
RendererCore::SetUp();
Application::SetEditor();
RendererCore::Start();
//Application::SetGame();
GameMain::Init();
}
| 23.096386 | 159 | 0.728743 | [
"vector"
] |
ecb42fbd3daa4d9d35406fb22fde16f2bd09c2b8 | 9,829 | cpp | C++ | Coda/src/nlp-stack/Dictionary/DictionaryTrieBuild.cpp | Samsung/veles.nlp | 972fde27203cb04d301e34274b57435ed58372c4 | [
"Apache-2.0"
] | 8 | 2016-02-16T10:15:39.000Z | 2020-03-12T21:14:36.000Z | src/nlp-stack/Dictionary/Core/DictionaryTrie/DictionaryTrieBuild.cpp | bdbabiak/Coda | 5e84624ae2b759fb1743778316f64c801591c48a | [
"Apache-2.0"
] | null | null | null | src/nlp-stack/Dictionary/Core/DictionaryTrie/DictionaryTrieBuild.cpp | bdbabiak/Coda | 5e84624ae2b759fb1743778316f64c801591c48a | [
"Apache-2.0"
] | 6 | 2016-02-16T10:15:47.000Z | 2020-01-20T20:33:25.000Z | /**
* DictionaryTrieBuild.cpp
*/
#include "DictionaryTrieBuild.h"
#include "Dictionary.h"
#define DIC_FILE_PATH "C:\\Python33\\_Ha\\2013_03_11_DictionaryVer5\\2013_03_12_dicRootModel_Ver5.txt"
#define LINK_FILE_PATH "C:\\Python33\\_Ha\\2013_02_07_ImproveDictionary\\2013_02_08_links.txt"
/**
* Constructor of DictionaryTrieBuild
*/
DictionaryTrieBuild::DictionaryTrieBuild(Dictionary* _dic) : DictionaryTrie(_dic)
{
//this->readFromTextFiles(DIC_FILE_PATH, LINK_FILE_PATH);
}
/**
* Destructor of DictionaryTrieBuild
*/
DictionaryTrieBuild::~DictionaryTrieBuild(void)
{
dic = NULL;
}
/**
* Read models, LPMs and links from text files
*/
void DictionaryTrieBuild::readFromTextFiles(string _modelLpmFilePath, string _linkFilePath)
{
root = new DictionaryNode();
numberOfNodes = 1;
readModelsAndLPMsFromFile(_modelLpmFilePath);
readLinksFromFile(_linkFilePath);
}
/**
* Read models and LPMs from file
*/
void DictionaryTrieBuild::readModelsAndLPMsFromFile(string _filePath)
{
//wcout << "Read models ... " << endl;
// open file
wifstream fin(_filePath.c_str());
// set encoding to UTF-8
#ifdef MSVC
fin.imbue(locale(fin.getloc(), new codecvt_utf8<wchar_t>));
#else
//fin.imbue(std::locale("ru_RU.UTF-8"));
fin.imbue(std::locale("en_US.UTF-8"));
#endif
wstring line;
// read number of features
getline(fin, line);
// read features
while(getline(fin, line))
{
// stop if reach end of index
if (line.length() >= 2 && line.at(0) == L'#' && line.at(1) == L'-')
{
break;
}
// process line to model
//wcout << line << endl;
addFeature(line);
}
// read number of featureLists
getline(fin, line);
// read features
while(getline(fin, line))
{
// stop if reach end of index
if (line.length() >= 2 && line.at(0) == L'#' && line.at(1) == L'-')
{
break;
}
// process line to featureList
//wcout << line << endl;
addFeatureList(line);
}
// read number of models
getline(fin, line);
// get numerical value of number of models
//numberOfModels = _wtoi(line.c_str());
//wcout << "Read model model ... " << endl;
// read models
while(getline(fin, line))
{
// stop if reach end of index
if (line.length() >= 2 && line.at(0) == L'#' && line.at(1) == L'-')
{
break;
}
// process line to model
//wcout << line << endl;
addModel(line);
}
// read max lemma index
getline(fin, line);
// @todo
//maxLemmaId = _wtoi(line.c_str());
// read LPMs and model index
//wcout << "Read models LPM... " << endl;
while(getline(fin, line))
{
// process line to LPM
addLPM(line);
}
// close file
fin.close();
//wcout << "Read models & LPMs done! " << endl;
}
/**
* Read links from file
*/
void DictionaryTrieBuild::readLinksFromFile(string _filePath)
{
//wcout << "Read links ... ";
// open file
wifstream fin(_filePath.c_str());
// set endoding to UTF-8
#ifdef MSVC
fin.imbue(locale(fin.getloc(), new codecvt_utf8<wchar_t>));
#else
//fin.imbue(std::locale("ru_RU.UTF-8"));
fin.imbue(std::locale("en_US.UTF-8"));
#endif
wstring line;
// read links
while(getline(fin, line))
{
// must have length >= 3, minimum 1#2
if (line.length() >= 3)
{
addLink(line);
}
}
fin.close();
//wcout << "done!" << endl;
}
/*
* add a line (rule)
* eg : @PRTS@perf@past@pssv&@masc@sing&\u0430@femn@sing&\u043e@neut@sing&\u044b@plur#20//here was cyrrilic symbols: а,о,ы
* \u0430@NOUN@anim@femn@Sgtm@Surn&\u0430@sing@nomn&\u043e\u0439@sing@ablt&\u043e\u0439@sing@datv&\u043e\u0439@sing@gent&\u043e\u0439@sing@loct&\u0443@sing@accs#21//here was cyrrilic symbols: а,а,ой,ой,ой,ой,у
*/
void DictionaryTrieBuild::addModel(wstring _line)
{
// find position of # in _str, which separates suffixes-attributes and modelIndex
int sharpPos = _line.find(L'#');
// suffixes + attributes is before #
wstring sufixesAttrs = _line.substr(0, sharpPos);
// modelIndex part is after #
wstring modelIndexStr = _line.substr(sharpPos + 1);
// get numeric value of modelIndex
//int modelIndex = _wtoi(modelIndexStr.c_str());
int modelIndex = atoi(this->getDictionary()->getDictionaryTools()->wstring2string(modelIndexStr).c_str());
// continue if modelIndex is invalid
if (modelIndex <= 0)
{
return;
}
// create a TrieModel from string sufixesAttrs
DictionaryTrieModel* trieModel = getTrieModelFromString(sufixesAttrs);
// map modelIndex to trieModel
mapModelIndexToTrieModel(modelIndex, trieModel);
}
/*
* add a LPM + modelIndex
* eg : #11195&1
* #500&2
* \u0451\u0436\u0438\u043a#38&3//here was cyrrilic symbols: ёжик
*/
void DictionaryTrieBuild::addLPM(wstring _line)
{
int andPos = _line.find(L'&');
int sharpPos = _line.find(L'#');
// get LPM
wstring lpm = _line.substr(0, sharpPos);
// get model index
wstring strModelIndex = _line.substr(sharpPos + 1, andPos - sharpPos - 1);
// get lemma index
wstring strLemmaIndex = _line.substr(andPos + 1);
// get numerical value of modelIndex
//int modelIndex = _wtoi(strModelIndex.c_str());
int modelIndex = atoi(this->getDictionary()->getDictionaryTools()->wstring2string(strModelIndex).c_str());
// get numerical value of lemmaIndex
//int lemmaIndex = _wtoi(strLemmaIndex.c_str());
int lemmaIndex = atoi(this->getDictionary()->getDictionaryTools()->wstring2string(strLemmaIndex).c_str());
// stop if modelIndex or lemmaIndex is invalid
//@todo : modelIndex > maxModelIndex
if (modelIndex < 0 || lemmaIndex < 0)
{
return;
}
addLPMModel(lpm, modelIndex, lemmaIndex);
}
/*
* add a link between 2 lemmas
* eg : 1#2
*/
void DictionaryTrieBuild::addLink(wstring _line)
{
numberOfLinks++;
// find first occurrence of '#'
int sharpPos = _line.find(L"#");
if (sharpPos >= 0)
{
// convert 2 strings to int
wstring fromLemmaIndexStr = _line.substr(0, sharpPos);
//int _fromLemmaId = _wtoi(fromLemmaIndexStr.c_str());
int _fromLemmaId = atoi(this->getDictionary()->getDictionaryTools()->wstring2string(fromLemmaIndexStr).c_str());
wstring toLemmaIndexStr = _line.substr(sharpPos + 1);
//int _toLemmaId = _wtoi(toLemmaIndexStr.c_str());
int _toLemmaId = atoi(this->getDictionary()->getDictionaryTools()->wstring2string(toLemmaIndexStr).c_str());
addLinkByLemmaIds(_fromLemmaId, _toLemmaId);
}
}
/*
* add a feature
* eg :
*/
void DictionaryTrieBuild::addFeature(wstring _line)
{
// find first occurrence of '@'
int _pos = _line.find(L"@");
if (_pos >= 0)
{
// convert 2 strings to int
wstring _str1 = _line.substr(0, _pos);
//int _featureId = _wtoi(_str1.c_str());
int _featureId = atoi(this->getDictionary()->getDictionaryTools()->wstring2string(_str1).c_str());
wstring _str2 = _line.substr(_pos + 1);
if (featureMap.count(_featureId) == 0)
{
featureMap.insert(pair<int, wstring>(_featureId, _str2));
}
}
}
/*
* add a featureList
* eg :
*/
void DictionaryTrieBuild::addFeatureList(wstring _line)
{
// find first occurrence of '#'
int _pos = _line.find(L"%");
if (_pos >= 0)
{
// convert 2 strings to int
wstring _str1 = _line.substr(0, _pos);
wstring _str2 = _line.substr(_pos + 1);
//int _featureListId = _wtoi(_str2.c_str());
int _featureListId = atoi(this->getDictionary()->getDictionaryTools()->wstring2string(_str2).c_str());
if (featureListMap.count(_featureListId) == 0)
{
vector<wstring> toks = dic->getDictionaryTools()->dictionarySplit(_str1, L"@");
vector<int> tmp = vector<int>();
for (int i = 0; i < (int) toks.size(); ++i)
{
tmp.push_back(atoi(this->getDictionary()->getDictionaryTools()->wstring2string(toks.at(i)).c_str()));
}
featureListMap.insert(pair<int, vector<int> >(_featureListId, tmp));
}
}
}
/**
* get TrieModel from string
* return NULL if string can not be converted to TrieModel
*/
DictionaryTrieModel* DictionaryTrieBuild::getTrieModelFromString(wstring _str)
{
// return NULL if _str is empty
if (_str.length() == 0)
{
return NULL;
}
// create a TrieModel
DictionaryTrieModel *trieModel = new DictionaryTrieModel();
// tokenize suffix_attrs and add to model list
// [suffix_attr]s are separated by '&'
vector<wstring> toks = dic->getDictionaryTools()->dictionarySplit(_str, L"&");
for (int i_tok = 0; i_tok < (int) toks.size(); ++ i_tok)
{
wstring tok = toks.at(i_tok);
DictionaryTrieModelElement* trieModelElement = getTrieModelElementFromString(tok);
// if trieModelElement is valid than add it to trieModel
if (trieModelElement != NULL && trieModelElement->isValid()) {
trieModel->addDictionaryTrieModelElement(trieModelElement);
}
}
return trieModel;
}
/**
* get TrieModelElement from string
* return NULL if string can not be converted to TrieModelElement
*/
DictionaryTrieModelElement* DictionaryTrieBuild::getTrieModelElementFromString(wstring _str)
{
// return NULL if _str is empty
if (_str.length() == 0)
{
return NULL;
}
// find position of '@' - \u0430@29//here was cyrrilic symbols: а
int atPos = _str.find(L'@');
// return NULL if not found '@'
if (atPos < 0)
{
return NULL;
}
// suffix is the part of string before first '@'
wstring suffix = _str.substr(0, atPos);
// attributes are the remaining
wstring attrs = _str.substr(atPos + 1);
DictionaryTrieModelElement* trieModelElement = new DictionaryTrieModelElement();
// if suffix begins with '*' - word begins with PO
if (suffix.length() > 0 && suffix.at(0) == L'*')
{
trieModelElement->setBeginWithPo(true);
suffix = suffix.substr(1);
}
// set suffix to trieModelElement
trieModelElement->setSuffix(suffix);
// convert attrs to int
//int _featureListId = _wtoi(attrs.c_str());
int _featureListId = atoi(this->getDictionary()->getDictionaryTools()->wstring2string(attrs).c_str());
// set featureListId for trieModelElement
trieModelElement->setFeatureListId(_featureListId);
return trieModelElement;
}
| 28.082857 | 214 | 0.685828 | [
"vector",
"model"
] |
ecb6078980825c1ce8c7e14d9c2d77c7703dbe3d | 10,877 | cpp | C++ | src/lib/crypto/test/EDDSATests.cpp | ansasaki/SoftHSMv2 | 80b96a9f79b9898a2c799aa6ce899ae6f88211cd | [
"BSD-2-Clause"
] | 2 | 2019-03-16T08:06:15.000Z | 2021-05-29T17:03:11.000Z | src/lib/crypto/test/EDDSATests.cpp | martinpaljak/SoftHSMv2 | a431e61b890b91fb208711816014c25fb83367a9 | [
"BSD-2-Clause"
] | null | null | null | src/lib/crypto/test/EDDSATests.cpp | martinpaljak/SoftHSMv2 | a431e61b890b91fb208711816014c25fb83367a9 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2010 SURFnet bv
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
/*****************************************************************************
EDDSATests.cpp
Contains test cases to test the EDDSA class
*****************************************************************************/
#include <stdlib.h>
#include <utility>
#include <vector>
#include <cppunit/extensions/HelperMacros.h>
#include "EDDSATests.h"
#include "CryptoFactory.h"
#include "RNG.h"
#include "AsymmetricKeyPair.h"
#include "AsymmetricAlgorithm.h"
#ifdef WITH_EDDSA
#include "ECParameters.h"
#include "EDPublicKey.h"
#include "EDPrivateKey.h"
CPPUNIT_TEST_SUITE_REGISTRATION(EDDSATests);
void EDDSATests::setUp()
{
eddsa = NULL;
eddsa = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::EDDSA);
// Check the EDDSA object
CPPUNIT_ASSERT(eddsa != NULL);
}
void EDDSATests::tearDown()
{
if (eddsa != NULL)
{
CryptoFactory::i()->recycleAsymmetricAlgorithm(eddsa);
}
fflush(stdout);
}
void EDDSATests::testKeyGeneration()
{
AsymmetricKeyPair* kp;
// Curves to test
std::vector<ByteString> curves;
// Add x25519
curves.push_back(ByteString("06032b656e"));
// Add ed25519
curves.push_back(ByteString("06032b6570"));
for (std::vector<ByteString>::iterator c = curves.begin(); c != curves.end(); c++)
{
// Set domain parameters
ECParameters* p = new ECParameters;
p->setEC(*c);
// Generate key-pair
CPPUNIT_ASSERT(eddsa->generateKeyPair(&kp, p));
EDPublicKey* pub = (EDPublicKey*) kp->getPublicKey();
EDPrivateKey* priv = (EDPrivateKey*) kp->getPrivateKey();
CPPUNIT_ASSERT(pub->getEC() == *c);
CPPUNIT_ASSERT(priv->getEC() == *c);
eddsa->recycleParameters(p);
eddsa->recycleKeyPair(kp);
}
}
void EDDSATests::testSerialisation()
{
// Get ed25519 domain parameters
ECParameters* p = new ECParameters;
p->setEC(ByteString("06032b6570"));
// Serialise the parameters
ByteString serialisedParams = p->serialise();
// Deserialise the parameters
AsymmetricParameters* dEC;
CPPUNIT_ASSERT(eddsa->reconstructParameters(&dEC, serialisedParams));
CPPUNIT_ASSERT(dEC->areOfType(ECParameters::type));
ECParameters* ddEC = (ECParameters*) dEC;
CPPUNIT_ASSERT(p->getEC() == ddEC->getEC());
// Generate a key-pair
AsymmetricKeyPair* kp;
CPPUNIT_ASSERT(eddsa->generateKeyPair(&kp, dEC));
// Serialise the key-pair
ByteString serialisedKP = kp->serialise();
// Deserialise the key-pair
AsymmetricKeyPair* dKP;
CPPUNIT_ASSERT(eddsa->reconstructKeyPair(&dKP, serialisedKP));
// Check the deserialised key-pair
EDPrivateKey* privKey = (EDPrivateKey*) kp->getPrivateKey();
EDPublicKey* pubKey = (EDPublicKey*) kp->getPublicKey();
EDPrivateKey* dPrivKey = (EDPrivateKey*) dKP->getPrivateKey();
EDPublicKey* dPubKey = (EDPublicKey*) dKP->getPublicKey();
CPPUNIT_ASSERT(privKey->getEC() == dPrivKey->getEC());
CPPUNIT_ASSERT(privKey->getK() == dPrivKey->getK());
CPPUNIT_ASSERT(pubKey->getEC() == dPubKey->getEC());
CPPUNIT_ASSERT(pubKey->getA() == dPubKey->getA());
eddsa->recycleParameters(p);
eddsa->recycleParameters(dEC);
eddsa->recycleKeyPair(kp);
eddsa->recycleKeyPair(dKP);
}
void EDDSATests::testPKCS8()
{
// Get ed25519 domain parameters
ECParameters* p = new ECParameters;
p->setEC(ByteString("06032b6570"));
// Generate a key-pair
AsymmetricKeyPair* kp;
CPPUNIT_ASSERT(eddsa->generateKeyPair(&kp, p));
CPPUNIT_ASSERT(kp != NULL);
EDPrivateKey* priv = (EDPrivateKey*) kp->getPrivateKey();
CPPUNIT_ASSERT(priv != NULL);
// Encode and decode the private key
ByteString pkcs8 = priv->PKCS8Encode();
CPPUNIT_ASSERT(pkcs8.size() != 0);
EDPrivateKey* dPriv = (EDPrivateKey*) eddsa->newPrivateKey();
CPPUNIT_ASSERT(dPriv != NULL);
CPPUNIT_ASSERT(dPriv->PKCS8Decode(pkcs8));
CPPUNIT_ASSERT(priv->getEC() == dPriv->getEC());
CPPUNIT_ASSERT(priv->getK() == dPriv->getK());
eddsa->recycleParameters(p);
eddsa->recycleKeyPair(kp);
eddsa->recyclePrivateKey(dPriv);
}
void EDDSATests::testSigningVerifying()
{
AsymmetricKeyPair* kp;
ECParameters *p;
// Curves to test
std::vector<ByteString> curves;
// Add ed25519
curves.push_back(ByteString("06032b6570"));
for (std::vector<ByteString>::iterator c = curves.begin(); c != curves.end(); c++)
{
// Get parameters
p = new ECParameters;
CPPUNIT_ASSERT(p != NULL);
p->setEC(*c);
// Generate key-pair
CPPUNIT_ASSERT(eddsa->generateKeyPair(&kp, p));
// Generate some data to sign
ByteString dataToSign;
RNG* rng = CryptoFactory::i()->getRNG();
CPPUNIT_ASSERT(rng != NULL);
CPPUNIT_ASSERT(rng->generateRandom(dataToSign, 567));
// Sign the data
ByteString sig;
CPPUNIT_ASSERT(eddsa->sign(kp->getPrivateKey(), dataToSign, sig, AsymMech::EDDSA));
// And verify it
CPPUNIT_ASSERT(eddsa->verify(kp->getPublicKey(), dataToSign, sig, AsymMech::EDDSA));
eddsa->recycleKeyPair(kp);
eddsa->recycleParameters(p);
}
}
void EDDSATests::testSignVerifyKnownVector()
{
EDPublicKey* pubKey1 = (EDPublicKey*) eddsa->newPublicKey();
EDPublicKey* pubKey2 = (EDPublicKey*) eddsa->newPublicKey();
EDPrivateKey* privKey1 = (EDPrivateKey*) eddsa->newPrivateKey();
EDPrivateKey* privKey2 = (EDPrivateKey*) eddsa->newPrivateKey();
// Reconstruct public and private key #1
ByteString ec1 = "06032b6570"; // ed25519
ByteString k1 = "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60";
ByteString a1 = "0420d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a";
pubKey1->setEC(ec1);
pubKey1->setA(a1);
privKey1->setEC(ec1);
privKey1->setK(k1);
// Test with key #1
ByteString data1; // ""
ByteString goodSignature1 = "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b";
ByteString badSignature1 = "e5564300c360ac728086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b";
// Reconstruct public and private key #2
ByteString ec2 = "06032b6570"; // ed25519
ByteString k2 = "c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7";
ByteString a2 = "0420fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025";
pubKey2->setEC(ec2);
pubKey2->setA(a2);
privKey2->setEC(ec2);
privKey2->setK(k2);
// Test with key #2
ByteString data2 = "af82";
ByteString goodSignature2 = "6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a";
ByteString badSignature2 = "6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027bedeea1ec40a";
CPPUNIT_ASSERT(eddsa->verify(pubKey1, data1, goodSignature1, AsymMech::EDDSA));
CPPUNIT_ASSERT(!eddsa->verify(pubKey1, data1, badSignature1, AsymMech::EDDSA));
CPPUNIT_ASSERT(eddsa->verify(pubKey2, data2, goodSignature2, AsymMech::EDDSA));
CPPUNIT_ASSERT(!eddsa->verify(pubKey2, data2, badSignature2, AsymMech::EDDSA));
eddsa->recyclePublicKey(pubKey1);
eddsa->recyclePublicKey(pubKey2);
eddsa->recyclePrivateKey(privKey1);
eddsa->recyclePrivateKey(privKey2);
}
void EDDSATests::testDerivation()
{
AsymmetricKeyPair* kpa;
AsymmetricKeyPair* kpb;
ECParameters* p;
// Curves to test
std::vector<ByteString> curves;
// Add x25519
curves.push_back(ByteString("06032b656e"));
for (std::vector<ByteString>::iterator c = curves.begin(); c != curves.end(); c++)
{
// Get parameters
p = new ECParameters;
CPPUNIT_ASSERT(p != NULL);
p->setEC(*c);
// Generate key-pairs
CPPUNIT_ASSERT(eddsa->generateKeyPair(&kpa, p));
CPPUNIT_ASSERT(eddsa->generateKeyPair(&kpb, p));
// Derive secrets
SymmetricKey* sa;
CPPUNIT_ASSERT(eddsa->deriveKey(&sa, kpb->getPublicKey(), kpa->getPrivateKey()));
SymmetricKey* sb;
CPPUNIT_ASSERT(eddsa->deriveKey(&sb, kpa->getPublicKey(), kpb->getPrivateKey()));
// Must be the same
CPPUNIT_ASSERT(sa->getKeyBits() == sb->getKeyBits());
// Clean up
eddsa->recycleSymmetricKey(sa);
eddsa->recycleSymmetricKey(sb);
eddsa->recycleKeyPair(kpa);
eddsa->recycleKeyPair(kpb);
eddsa->recycleParameters(p);
}
}
void EDDSATests::testDeriveKnownVector()
{
EDPublicKey* pubKeya = (EDPublicKey*) eddsa->newPublicKey();
EDPublicKey* pubKeyb = (EDPublicKey*) eddsa->newPublicKey();
EDPrivateKey* privKeya = (EDPrivateKey*) eddsa->newPrivateKey();
EDPrivateKey* privKeyb = (EDPrivateKey*) eddsa->newPrivateKey();
// Reconstruct public and private key for Alice
ByteString ec = "06032b656e"; // x25519
ByteString ka = "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a";
ByteString aa = "04208520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a";
pubKeya->setEC(ec);
pubKeya->setA(aa);
privKeya->setEC(ec);
privKeya->setK(ka);
// Reconstruct public and private key for Bob
ByteString kb = "5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb";
ByteString ab = "0420de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f";
pubKeyb->setEC(ec);
pubKeyb->setA(ab);
privKeyb->setEC(ec);
privKeyb->setK(kb);
// Test
ByteString expected = "4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742";
SymmetricKey* sa;
CPPUNIT_ASSERT(eddsa->deriveKey(&sa, pubKeya, privKeyb));
CPPUNIT_ASSERT(sa->getKeyBits() == expected);
SymmetricKey* sb;
CPPUNIT_ASSERT(eddsa->deriveKey(&sb, pubKeyb, privKeya));
CPPUNIT_ASSERT(sb->getKeyBits() == expected);
eddsa->recyclePublicKey(pubKeya);
eddsa->recyclePublicKey(pubKeyb);
eddsa->recyclePrivateKey(privKeya);
eddsa->recyclePrivateKey(privKeyb);
eddsa->recycleSymmetricKey(sa);
eddsa->recycleSymmetricKey(sb);
}
#endif
| 30.639437 | 160 | 0.740829 | [
"object",
"vector"
] |
ecbae11ba996a5cffd5e99b47bb6d8fda816b5ea | 16,638 | cpp | C++ | Libraries/RobsJuceModules/rosic/modulators/rosic_Modulator.cpp | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | 34 | 2017-04-19T18:26:02.000Z | 2022-02-15T17:47:26.000Z | Libraries/RobsJuceModules/rosic/modulators/rosic_Modulator.cpp | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | 307 | 2017-05-04T21:45:01.000Z | 2022-02-03T00:59:01.000Z | Libraries/RobsJuceModules/rosic/modulators/rosic_Modulator.cpp | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | 4 | 2017-09-05T17:04:31.000Z | 2021-12-15T21:24:28.000Z | #include "rosic_Modulator.h"
using namespace rosic;
//-----------------------------------------------------------------------------
// construction/destruction:
Modulator::Modulator()
{
//TEST:
//fadeInOutSlewRateLimiter.setReleaseTime(5.0);
scaleFactor = 1.0;
offset = 0.0;
currentKey = -1;
currentVel = -1;
applyMode = ADDITIVE;
timeScaleNominal = 1.0;
//timeScale = 1.0;
timeScaleByKey = 0.0;
timeScaleByVel = 0.0;
depthNominal = 1.0;
depth = 1.0;
depthByKey = 0.0;
depthByVel = 0.0;
slewUp = 0.0;
slewUpByKey = 0.0;
slewUpByVel = 0.0;
slewDown = 0.0;
slewDownByKey = 0.0;
slewDownByVel = 0.0;
fadeInTime = 0.0;
fadeInTimeByKey = 0.0;
fadeInTimeByVel = 0.0;
fadeInIsOn = false;
fadeOutTime = 0.0;
fadeOutTimeByKey = 0.0;
fadeOutTimeByVel = 0.0;
fadeOutIsOn = false;
noRelease = false;
}
Modulator::~Modulator()
{
}
void Modulator::copyDataFrom(const rosic::Modulator &source)
{
breakpointModulator.copyDataFrom(source.breakpointModulator);
sampleModulator.copyDataFrom(source.sampleModulator);
upDownSlewRateLimiter = source.upDownSlewRateLimiter;
fadeInOutSlewRateLimiter = source.fadeInOutSlewRateLimiter;
applyMode = source.applyMode;
currentKey = source.currentKey;
currentVel = source.currentVel;
offset = source.offset;
depth = source.depth;
depthByKey = source.depthByKey;
depthByVel = source.depthByVel;
depthNominal = source.depthNominal;
fadeInIsOn = source.fadeInIsOn;
fadeInTime = source.fadeInTime;
fadeInTimeByKey = source.fadeInTimeByKey;
fadeInTimeByVel = source.fadeInTimeByVel;
fadeOutIsOn = source.fadeOutIsOn;
fadeOutTime = source.fadeOutTime;
fadeOutTimeByKey = source.fadeOutTimeByKey;
fadeOutTimeByVel = source.fadeOutTimeByVel;
modulationSource = source.modulationSource;
noRelease = source.noRelease;
scaleFactor = source.scaleFactor;
slewDown = source.slewDown;
slewDownByKey = source.slewDownByKey;
slewDownByVel = source.slewDownByVel;
slewUp = source.slewUp;
slewUpByKey = source.slewUpByKey;
slewUpByVel = source.slewUpByVel;
timeScaleByKey = source.timeScaleByKey;
timeScaleByVel = source.timeScaleByVel;
timeScaleNominal = source.timeScaleNominal;
}
//-----------------------------------------------------------------------------
// parameter settings:
void Modulator::setSampleRate(double newSampleRate)
{
breakpointModulator.setSampleRate(newSampleRate);
upDownSlewRateLimiter.setSampleRate(newSampleRate);
fadeInOutSlewRateLimiter.setSampleRate(newSampleRate);
sampleModulator.setSampleRate(newSampleRate);
//riseRamp.setSampleRate(newSampleRate);
}
void Modulator::setModulationSource(int newModulationSource)
{
if( newModulationSource >= BREAKPOINT_MODULATOR &&
newModulationSource <= SAMPLE_MODULATOR )
{
modulationSource = newModulationSource;
}
}
void Modulator::setScaleFactor(double newScaleFactor)
{
scaleFactor = newScaleFactor;
}
void Modulator::setOffset(double newOffset)
{
offset = newOffset;
}
void Modulator::setBeatsPerMinute(double newBpm)
{
breakpointModulator.setBeatsPerMinute(newBpm);
sampleModulator.setBeatsPerMinute(newBpm);
}
void Modulator::setTimeScale(double newTimeScale)
{
if( newTimeScale >= 0.0001 )
timeScaleNominal = newTimeScale;
double timeScale = timeScaleNominal * pow(2.0, 0.01*timeScaleByKey*(currentKey-60.0)/12.0)
* pow(2.0, 0.01*timeScaleByVel*(currentVel-64.0)/63.0);
breakpointModulator.setTimeScale(timeScale);
sampleModulator.setNumCyclesPerTimeUnit(1.0/timeScale);
}
void Modulator::setTimeScaleByKey(double newTimeScaleByKey)
{
timeScaleByKey = newTimeScaleByKey;
double timeScale = timeScaleNominal * pow(2.0, 0.01*timeScaleByKey*(currentKey-60.0)/12.0)
* pow(2.0, 0.01*timeScaleByVel*(currentVel-64.0)/63.0);
breakpointModulator.setTimeScale(timeScale);
sampleModulator.setNumCyclesPerTimeUnit(1.0/timeScale);
}
void Modulator::setTimeScaleByVel(double newTimeScaleByVel)
{
timeScaleByVel = newTimeScaleByVel;
double timeScale = timeScaleNominal * pow(2.0, 0.01*timeScaleByKey*(currentKey-60.0)/12.0)
* pow(2.0, 0.01*timeScaleByVel*(currentVel-64.0)/63.0);
breakpointModulator.setTimeScale(timeScale);
sampleModulator.setNumCyclesPerTimeUnit(1.0/timeScale);
}
void Modulator::setDepth(double newDepth)
{
depthNominal = newDepth;
depth = depthNominal
* pow(2.0, 0.01*depth*(currentKey-60.0)/12.0)
* pow(2.0, 0.01*depth*(currentVel-64.0)/63.0);
}
void Modulator::setDepthByKey(double newDepthByKey)
{
depthByKey = newDepthByKey;
depth = depthNominal
* pow(2.0, 0.01*depth*(currentKey-60.0)/12.0)
* pow(2.0, 0.01*depth*(currentVel-64.0)/63.0);
}
void Modulator::setDepthByVel(double newDepthByVel)
{
depthByVel = newDepthByVel;
depth = depthNominal
* pow(2.0, 0.01*depth*(currentKey-60.0)/12.0)
* pow(2.0, 0.01*depth*(currentVel-64.0)/63.0);
}
void Modulator::setUpwardSlewRateLimit(double newLimit)
{
if( newLimit >= 0.0 )
slewUp = newLimit;
double tmp = slewUp
* pow(2.0, 0.01*slewUpByKey*(currentKey-60.0)/12.0)
* pow(2.0, 0.01*slewUpByVel*(currentVel-64.0)/63.0);
upDownSlewRateLimiter.setAttackTime(tmp);
}
void Modulator::setUpwardSlewRateLimitByKey(double newLimitByKey)
{
slewUpByKey = newLimitByKey;
double tmp = slewUp
* pow(2.0, 0.01*slewUpByKey*(currentKey-60.0)/12.0)
* pow(2.0, 0.01*slewUpByVel*(currentVel-64.0)/63.0);
upDownSlewRateLimiter.setAttackTime(tmp);
}
void Modulator::setUpwardSlewRateLimitByVel(double newLimitByVel)
{
slewUpByVel = newLimitByVel;
double tmp = slewUp
* pow(2.0, 0.01*slewUpByKey*(currentKey-60.0)/12.0)
* pow(2.0, 0.01*slewUpByVel*(currentVel-64.0)/63.0);
upDownSlewRateLimiter.setAttackTime(tmp);
}
void Modulator::setDownwardSlewRateLimit(double newLimit)
{
if( newLimit >= 0.0 )
slewDown = newLimit;
double tmp = slewDown
* pow(2.0, 0.01*slewDownByKey*(currentKey-60.0)/12.0)
* pow(2.0, 0.01*slewDownByVel*(currentVel-64.0)/63.0);
upDownSlewRateLimiter.setReleaseTime(tmp);
}
void Modulator::setDownwardSlewRateLimitByKey(double newLimitByKey)
{
slewDownByKey = newLimitByKey;
double tmp = slewDown
* pow(2.0, 0.01*slewDownByKey*(currentKey-60.0)/12.0)
* pow(2.0, 0.01*slewDownByVel*(currentVel-64.0)/63.0);
upDownSlewRateLimiter.setReleaseTime(tmp);
}
void Modulator::setDownwardSlewRateLimitByVel(double newLimitByVel)
{
slewDownByVel = newLimitByVel;
double tmp = slewDown
* pow(2.0, 0.01*slewDownByKey*(currentKey-60.0)/12.0)
* pow(2.0, 0.01*slewDownByVel*(currentVel-64.0)/63.0);
upDownSlewRateLimiter.setReleaseTime(tmp);
}
void Modulator::setFadeInTime(double newFadeInTime)
{
if( newFadeInTime >= 0.0 )
fadeInTime = newFadeInTime;
double tmp = fadeInTime
* pow(2.0, 0.01*fadeInTimeByKey*(currentKey-60.0)/12.0)
* pow(2.0, 0.01*fadeInTimeByVel*(currentVel-64.0)/63.0);
fadeInOutSlewRateLimiter.setAttackTime(tmp);
}
void Modulator::setFadeInTimeByKey(double newFadeInTimeByKey)
{
fadeInTimeByKey = newFadeInTimeByKey;
double tmp = fadeInTime
* pow(2.0, 0.01*fadeInTimeByKey*(currentKey-60.0)/12.0)
* pow(2.0, 0.01*fadeInTimeByVel*(currentVel-64.0)/63.0);
fadeInOutSlewRateLimiter.setAttackTime(tmp);
}
void Modulator::setFadeInTimeByVel(double newFadeInTimeByVel)
{
fadeInTimeByVel = newFadeInTimeByVel;
double tmp = fadeInTime
* pow(2.0, 0.01*fadeInTimeByVel*(currentKey-60.0)/12.0)
* pow(2.0, 0.01*fadeInTimeByVel*(currentVel-64.0)/63.0);
fadeInOutSlewRateLimiter.setAttackTime(tmp);
}
void Modulator::switchFadeInOnOff(bool fadeInShouldBeOn)
{
fadeInIsOn = fadeInShouldBeOn;
}
void Modulator::setFadeOutTime(double newFadeOutTime)
{
if( newFadeOutTime >= 0.0 )
fadeOutTime = newFadeOutTime;
double tmp = fadeOutTime
* pow(2.0, 0.01*fadeOutTimeByKey*(currentKey-60.0)/12.0)
* pow(2.0, 0.01*fadeOutTimeByVel*(currentVel-64.0)/63.0);
fadeInOutSlewRateLimiter.setReleaseTime(tmp);
}
void Modulator::setFadeOutTimeByKey(double newFadeOutTimeByKey)
{
fadeOutTimeByKey = newFadeOutTimeByKey;
double tmp = fadeOutTime
* pow(2.0, 0.01*fadeOutTimeByKey*(currentKey-60.0)/12.0)
* pow(2.0, 0.01*fadeOutTimeByVel*(currentVel-64.0)/63.0);
fadeInOutSlewRateLimiter.setReleaseTime(tmp);
}
void Modulator::setFadeOutTimeByVel(double newFadeOutTimeByVel)
{
fadeOutTimeByVel = newFadeOutTimeByVel;
double tmp = fadeOutTime
* pow(2.0, 0.01*fadeOutTimeByVel*(currentKey-60.0)/12.0)
* pow(2.0, 0.01*fadeOutTimeByVel*(currentVel-64.0)/63.0);
fadeInOutSlewRateLimiter.setReleaseTime(tmp);
}
void Modulator::switchFadeOutOnOff(bool fadeOutShouldBeOn)
{
fadeOutIsOn = fadeOutShouldBeOn;
}
void Modulator::setApplyMode(int newApplyMode)
{
applyMode = newApplyMode;
}
void Modulator::setLoopMode(int newLoopMode)
{
breakpointModulator.setLoopMode(newLoopMode != BreakpointModulator::NO_LOOP);
sampleModulator.setLoopMode(newLoopMode);
}
void Modulator::setLoopStart(int newLoopStart)
{
if( modulationSource == BREAKPOINT_MODULATOR )
breakpointModulator.setLoopStartIndex(newLoopStart);
else if( modulationSource == SAMPLE_MODULATOR )
sampleModulator.setLoopStartSample(newLoopStart);
}
void Modulator::setLoopEnd(int newLoopEnd)
{
if( modulationSource == BREAKPOINT_MODULATOR )
breakpointModulator.setLoopEndIndex(newLoopEnd);
else if( modulationSource == SAMPLE_MODULATOR )
sampleModulator.setLoopEndSample(newLoopEnd);
}
void Modulator::setNumCyclesInLoop(int newNumCycles)
{
if( modulationSource == BREAKPOINT_MODULATOR )
breakpointModulator.setNumCyclesInLoop(newNumCycles);
else if( modulationSource == SAMPLE_MODULATOR )
sampleModulator.setNumCyclesInLoop(newNumCycles);
}
void Modulator::setSyncMode(bool shouldBeSynced)
{
if( modulationSource == BREAKPOINT_MODULATOR )
breakpointModulator.setSyncMode(shouldBeSynced);
else if( modulationSource == SAMPLE_MODULATOR )
sampleModulator.setSyncMode(shouldBeSynced);
}
void Modulator::switchReleaseOnOff(bool shouldBeOn)
{
noRelease = !shouldBeOn;
}
//-----------------------------------------------------------------------------
// inquiry:
double Modulator::getSampleRate()
{
return sampleModulator.getSampleRate();
// it doesn't matter from which of the embedded objects we return the sample-rate as they are
// all in sync.
}
int Modulator::getModulationSource() const
{
return modulationSource;
}
double Modulator::getScaleFactor() const
{
return scaleFactor;
}
double Modulator::getOffset() const
{
return offset;
}
double Modulator::getTimeScale() const
{
return timeScaleNominal;
}
double Modulator::getTimeScaleByKey() const
{
return timeScaleByKey;
}
double Modulator::getTimeScaleByVel() const
{
return timeScaleByVel;
}
double Modulator::getDepth() const
{
return depthNominal;
}
double Modulator::getDepthByKey() const
{
return depthByKey;
}
double Modulator::getDepthByVel() const
{
return depthByVel;
}
double Modulator::getUpwardSlewRateLimit() const
{
return slewUp;
}
double Modulator::getUpwardSlewRateLimitByKey() const
{
return slewUpByKey;
}
double Modulator::getUpwardSlewRateLimitByVel() const
{
return slewUpByVel;
}
double Modulator::getDownwardSlewRateLimit() const
{
return slewDown;
}
double Modulator::getDownwardSlewRateLimitByKey() const
{
return slewDownByKey;
}
double Modulator::getDownwardSlewRateLimitByVel() const
{
return slewDownByVel;
}
double Modulator::getFadeInTime() const
{
return fadeInTime;
}
double Modulator::getFadeInTimeByKey() const
{
return fadeInTimeByKey;
}
double Modulator::getFadeInTimeByVel() const
{
return fadeInTimeByVel;
}
bool Modulator::isFadeInOn()
{
return fadeInIsOn;
}
double Modulator::getFadeOutTime() const
{
return fadeOutTime;
}
double Modulator::getFadeOutTimeByKey() const
{
return fadeOutTimeByKey;
}
double Modulator::getFadeOutTimeByVel() const
{
return fadeOutTimeByVel;
}
bool Modulator::isFadeOutOn()
{
return fadeOutIsOn;
}
int Modulator::getApplyMode()
{
return applyMode;
}
int Modulator::getLoopMode()
{
if( modulationSource == BREAKPOINT_MODULATOR )
return breakpointModulator.getLoopMode();
else if( modulationSource == SAMPLE_MODULATOR )
return sampleModulator.getLoopMode();
else
return 0;
}
int Modulator::getLoopStart()
{
if( modulationSource == BREAKPOINT_MODULATOR )
return breakpointModulator.getLoopStartIndex();
else if( modulationSource == SAMPLE_MODULATOR )
return sampleModulator.getLoopStartSample();
else
return 0;
}
int Modulator::getLoopEnd()
{
if( modulationSource == BREAKPOINT_MODULATOR )
return breakpointModulator.getLoopEndIndex();
else if( modulationSource == SAMPLE_MODULATOR )
return sampleModulator.getLoopEndSample();
else
return 0;
}
int Modulator::getNumCyclesInLoop()
{
if( modulationSource == BREAKPOINT_MODULATOR )
return breakpointModulator.getNumCyclesInLoop();
else if( modulationSource == SAMPLE_MODULATOR )
return sampleModulator.getNumCyclesInLoop();
else
return 0;
}
bool Modulator::isInSyncMode()
{
if( modulationSource == BREAKPOINT_MODULATOR )
return breakpointModulator.isInSyncMode();
else if( modulationSource == SAMPLE_MODULATOR )
return sampleModulator.isInSyncMode();
else
return false;
}
bool Modulator::isReleaseOn()
{
return !noRelease;
}
bool Modulator::endIsReached()
{
if( modulationSource == BREAKPOINT_MODULATOR )
return breakpointModulator.endIsReached;
else if( modulationSource == SAMPLE_MODULATOR )
return sampleModulator.endIsReached;
else
return false;
}
//-----------------------------------------------------------------------------
// event handling :
void Modulator::noteOn(bool startFromCurrentLevel, int newKey, int newVelocity)
{
// keep track of the note-key and velocity:
currentKey = newKey;
currentVel = newVelocity;
// set the time scale-variable for the inherited BreakpointModulator object
// according to key and velocity:
double timeScale = timeScaleNominal * pow(2.0, 0.01*timeScaleByKey*(currentKey-60.0)/12.0)
* pow(2.0, 0.01*timeScaleByVel*(currentVel-64.0)/63.0);
if( modulationSource == BREAKPOINT_MODULATOR )
breakpointModulator.setTimeScale(timeScale);
else
sampleModulator.setNumCyclesPerTimeUnit(1.0/timeScale);
depth = depthNominal * pow(2.0, 0.01*depth*(currentKey-60.0)/12.0)
* pow(2.0, 0.01*depth*(currentVel-64.0)/63.0);
// set up the embedded SlewRateLimiters according to the key and velocity:
double tmp;
tmp = slewUp
* pow(2.0, 0.01*slewUpByKey*(currentKey-60.0)/12.0)
* pow(2.0, 0.01*slewUpByVel*(currentVel-64.0)/63.0);
upDownSlewRateLimiter.setAttackTime(tmp);
tmp = slewDown
* pow(2.0, 0.01*slewDownByKey*(currentKey-60.0)/12.0)
* pow(2.0, 0.01*slewDownByVel*(currentVel-64.0)/63.0);
upDownSlewRateLimiter.setReleaseTime(tmp);
tmp = fadeInTime
* pow(2.0, 0.01*fadeInTimeByKey*(currentKey-60.0)/12.0)
* pow(2.0, 0.01*fadeInTimeByVel*(currentVel-64.0)/63.0);
fadeInOutSlewRateLimiter.setAttackTime(tmp);
tmp = fadeOutTime
* pow(2.0, 0.01*fadeOutTimeByKey*(currentKey-60.0)/12.0)
* pow(2.0, 0.01*fadeOutTimeByVel*(currentVel-64.0)/63.0);
fadeInOutSlewRateLimiter.setReleaseTime(tmp);
// let the inherited BreakpointModulator object do its stuff which happens on
// note-on:
breakpointModulator.noteOn(startFromCurrentLevel);
// retrigger the embedded SlewRateLimiter and ExponentialRamp, if we do not
// start from the current level:
if( startFromCurrentLevel == false )
{
upDownSlewRateLimiter.reset();
fadeInOutSlewRateLimiter.reset();
}
}
void Modulator::noteOff(bool startFromCurrentLevel)
{
if( noRelease == false )
breakpointModulator.noteOff(startFromCurrentLevel);
currentKey = -1;
currentVel = -1;
}
| 25.795349 | 95 | 0.694374 | [
"object"
] |
ecbbbc55caa3165c295ba148955738d37cee0273 | 605 | cpp | C++ | LeetCode/763 - Partition Labels.cpp | GokulVSD/ScratchPad | 53dee2293a2039186b00c7a465c7ef28e2b8e291 | [
"Unlicense"
] | null | null | null | LeetCode/763 - Partition Labels.cpp | GokulVSD/ScratchPad | 53dee2293a2039186b00c7a465c7ef28e2b8e291 | [
"Unlicense"
] | null | null | null | LeetCode/763 - Partition Labels.cpp | GokulVSD/ScratchPad | 53dee2293a2039186b00c7a465c7ef28e2b8e291 | [
"Unlicense"
] | null | null | null | // https://leetcode.com/problems/partition-labels/
// Greedy solution, keeping track of last occurence of a character.
class Solution {
public:
vector<int> partitionLabels(string s) {
vector<int> ans;
unordered_map<char, int> m;
for(int i = 0; i < s.size(); ++i){
m[s[i]] = i;
}
int p;
for(int i = 0; i < s.size(); ++i){
p = m[s[i]];
for(int j = i + 1; j < p; ++j){
p = max(p, m[s[j]]);
}
ans.emplace_back(p - i + 1);
i = p;
}
return ans;
}
}; | 25.208333 | 67 | 0.439669 | [
"vector"
] |
ecbeb6f3463f2ea34d0033d07512228f9ed4b13b | 15,276 | cxx | C++ | cgv/gui/provider.cxx | henne90gen/cgv | 31995e9f09d093f9997980093452a5424d0c1319 | [
"BSD-3-Clause"
] | 11 | 2017-09-30T12:21:55.000Z | 2021-04-29T21:31:57.000Z | cgv/gui/provider.cxx | henne90gen/cgv | 31995e9f09d093f9997980093452a5424d0c1319 | [
"BSD-3-Clause"
] | 2 | 2017-07-11T11:20:08.000Z | 2018-03-27T12:09:02.000Z | cgv/gui/provider.cxx | henne90gen/cgv | 31995e9f09d093f9997980093452a5424d0c1319 | [
"BSD-3-Clause"
] | 24 | 2018-03-27T11:46:16.000Z | 2021-05-01T20:28:34.000Z | #include <cgv/gui/provider.h>
#include <cgv/gui/gui_driver.h>
#include <cgv/gui/trigger.h>
#include <cgv/base/base_generator.h>
//#include <cgv/os/mutex.h>
#include <iostream>
#include <set>
namespace cgv {
namespace gui {
// update the parent group
void provider::update_parent()
{
parent_group->set("label",get_gui_name());
}
/// add a newly created view to the group
view_ptr provider::add_view_void(const std::string& label, const void* value_ptr, const std::string& value_type, const std::string& gui_type, const std::string& options, const std::string& align)
{
if (parent_group.empty())
return view_ptr();
return parent_group->add_view_void(label,value_ptr,value_type,gui_type,options,align);
}
/// add a newly created control to the group
control_ptr provider::add_control_void(const std::string& label, void* value_ptr, abst_control_provider* acp, const std::string& value_type, const std::string& gui_type, const std::string& options, const std::string& align, void* user_data)
{
if (parent_group.empty())
return control_ptr();
return parent_group->add_control_void(label,value_ptr,acp,value_type,gui_type,options,align,user_data);
}
// send pure alignment information
void provider::align(const std::string& _align)
{
if (!parent_group.empty())
parent_group->align(_align);
}
/// concatenate names in string to enum declaration and optionally prepend or append given additional names
std::string provider::concat_enum_def(const std::vector<std::string>& names, const std::string& additional_first_name, const std::string& additional_last_name)
{
std::string result = "enums='";
if (!additional_first_name.empty())
result += additional_first_name + "=-1,";
for (unsigned i = 0; i < names.size(); ++i) {
if (i > 0)
result += ',';
result += names[i];
}
if (!additional_last_name.empty()) {
result += ',';
result += additional_last_name;
}
result += "'";
return result;
}
/*
// add a new group to the given parent group, not supported yet
gui_group_ptr provider::add_group(const std::string& label, const std::string& group_type, const std::string& options, const std::string& align)
{
if (parent_group.empty())
return gui_group_ptr();
return parent_group->add_group(label, group_type, options, align);
}
*/
// call this to update all views and controls of a member
void provider::update_member(void* member_ptr)
{
update_views(member_ptr);
/*
int i=0;
do {
cgv::gui::control_ptr cp = find_control_void(member_ptr, &i);
if (cp) {
cp->update();
cp->update_views();
}
else
break;
++i;
} while (true);
i = 0;
do {
cgv::gui::view_ptr vp = find_view_void(member_ptr, &i);
if (vp) {
vp->update();
vp->update_views();
}
else
break;
++i;
} while (true);
*/
}
void update_group_members(cgv::base::group_ptr gp)
{
if (!gp)
return;
for (unsigned i=0; i<gp->get_nr_children(); ++i) {
base_ptr bp = gp->get_child(i);
abst_view* v = bp->get_interface<abst_view>();
if (v)
v->update();
cgv::base::group_ptr cgp = bp->cast<cgv::base::group>();
if (cgp)
update_group_members(cgp);
}
}
/// call this to update all views and controls of all member
void provider::update_all_members()
{
update_group_members(parent_group);
}
gui_group_ptr provider::add_object_gui(base_ptr object, const std::string& label, const std::string& group_type, const std::string& options, const std::string& align)
{
provider* p = object->get_interface<provider>();
if (!p)
return gui_group_ptr();
gui_group_ptr g = parent_group->add_group(label, group_type, options, align);
// gui_group_ptr g = add_group(label,group_type,options,align);
p->set_parent(parent_group);
// p->create_gui();
return g;
}
// inline the gui of another object that must be derived from provider.
void provider::inline_object_gui(base_ptr object)
{
provider* p = object->get_interface<provider>();
if (!p)
return;
//gui_group_ptr pg = p->get_parent_group();
p->set_parent(parent_group);
p->parent_provider = this;
p->create_gui();
//p->set_parent(pg);
}
/// add a newly created subgroup to the group
gui_group_ptr provider::add_group(const std::string& label, const std::string& group_type, const std::string& options, const std::string& align)
{
if (parent_group.empty())
return gui_group_ptr();
return parent_group->add_group(label, group_type, options, align);
}
// add a newly created decorator to the group, not implemented yet
base_ptr provider::add_decorator(const std::string& label, const std::string& decorator_type, const std::string& options, const std::string& align)
{
if (parent_group.empty())
return base_ptr();
return parent_group->add_decorator(label, decorator_type, options, align);
}
// use the current gui driver to append a new button with the given label
button_ptr provider::add_button(const std::string& label, const std::string& options, const std::string& align)
{
if (parent_group.empty())
return button_ptr();
return parent_group->add_button(label, options, align);
}
bool provider::add_tree_node(const std::string& label, bool& toggle, int level, const std::string& a, gui_group_ptr ggp)
{
if (!ggp)
ggp = parent_group;
int ii = 0;
if (a.size() != 1 || a[0] != '\n') {
ii += 1;
}
int size = 24-4*level;
int off = size+12;
ggp->align(std::string("%x-=")+cgv::utils::to_string(off));
connect_copy(ggp->add_control(std::string(toggle?"-":"+"), toggle, "toggle", std::string("w=")+cgv::utils::to_string(size), " ")->value_change,
rebind(static_cast<provider*>(this), &provider::post_recreate_gui));
ggp->add_decorator(label, "heading", std::string("level=")+cgv::utils::to_string(level), a);
return toggle;
}
std::map<std::pair<const void*,int>, bool>& get_tree_node_toggle_map()
{
static std::map<std::pair<const void*,int>, bool> tree_node_toggle_map;
return tree_node_toggle_map;
}
///
bool provider::begin_tree_node_void(const std::string& label, const void* value_ptr, int index, bool initial_visibility, const std::string& options, gui_group_ptr ggp)
{
if (!ggp)
ggp = parent_group;
bool decorated = true; cgv::base::has_property(options, "decorated", decorated, true);
int level = 2; cgv::base::has_property(options, "level", level, true);
std::string align("\n"); cgv::base::has_property(options, "align", align, true);
std::string child_opt; cgv::base::has_property(options, "options", child_opt, true);
std::string button_opt; cgv::base::has_property(options, "button_options", button_opt, true);
int size = 24 - 4 * level; cgv::base::has_property(options, "size", size, true);
int relative_offset = 12; cgv::base::has_property(options, "relative_offset", relative_offset, true);
int off = size+relative_offset;
if (!button_opt.empty())
button_opt = std::string(";")+button_opt;
button_opt = std::string("w=")+cgv::utils::to_string(size) + button_opt;
std::map<std::pair<const void*,int>, bool>::iterator it = get_tree_node_toggle_map().find(std::pair<const void*,int>(value_ptr,index));
if (it == get_tree_node_toggle_map().end())
get_tree_node_toggle_map()[std::pair<const void*,int>(value_ptr,index)] = initial_visibility;
bool& toggle = get_tree_node_toggle_map()[std::pair<const void*,int>(value_ptr,index)];
data::ref_ptr<control<bool> > control_ptr;
if (decorated) {
ggp->align(std::string("%x-=")+cgv::utils::to_string(off));
control_ptr = ggp->add_control(std::string(toggle ? "-" : "+"), toggle, "toggle", button_opt, " ");
if (!child_opt.empty())
child_opt = std::string(";")+child_opt;
child_opt = std::string("level=")+cgv::utils::to_string(level) + child_opt;
ggp->add_decorator(label, "heading", child_opt, align);
}
else {
control_ptr = ggp->add_control(std::string(toggle ? "-" : "+"), toggle, "toggle", button_opt, align);
}
if (control_ptr) {
connect_copy(control_ptr->value_change, rebind(static_cast<provider*>(this), &provider::post_recreate_gui));
// if this class is derived from cgv::base::base
cgv::base::base* bp = dynamic_cast<cgv::base::base*>(this);
// connect to on_set callback
if (bp) {
connect_copy(control_ptr->value_change, rebind(bp, &cgv::base::base::on_set, cgv::signal::_c((void*)(&toggle))));
}
}
return toggle;
}
///
bool& provider::ref_tree_node_visible_flag_void(const void* value_ptr, int index)
{
auto& map = get_tree_node_toggle_map();
std::pair<const void*, int> key(value_ptr, index);
auto iter = map.find(key);
if (iter == map.end())
return map[key] = false;
else
return iter->second;
}
///
void provider::end_tree_node_void(const void* value_ptr, int)
{
}
///
bool provider::is_tree_node_visible_void(const void* value_ptr, int index) const
{
return get_tree_node_toggle_map()[std::pair<const void*,int>(value_ptr,index)];
}
///
void provider::set_tree_node_visibility_void(const void* value_ptr, int index, bool is_visible)
{
bool& toggle = get_tree_node_toggle_map()[std::pair<const void*,int>(value_ptr,index)];
if (toggle != is_visible) {
toggle = is_visible;
post_recreate_gui();
}
}
// remove a single element from the gui
void provider::remove_element(base_ptr e)
{
if (!parent_group.empty())
parent_group->remove_child(e);
}
// this method removes all elements in the gui and can be used in a method that rebuilds the complete gui
void provider::remove_all_elements()
{
if (!parent_group.empty()) {
parent_group->remove_all_children();
parent_group->release_all_managed_objects();
}
}
//! find a gui element by name in the current group, return empty pointer if not found
base_ptr provider::find_element(const std::string& name)
{
if (parent_group.empty())
return base_ptr();
return parent_group->find_element(name);
}
// access to control of untyped member pointer
control_ptr provider::find_control_void(void* value_ptr, int* idx_ptr)
{
if (parent_group.empty())
return control_ptr();
return parent_group->find_control_void(value_ptr,idx_ptr);
}
// access to view of untyped member pointer
view_ptr provider::find_view_void(void* value_ptr, int* idx_ptr)
{
if (parent_group.empty())
return view_ptr();
return parent_group->find_view_void(value_ptr,idx_ptr);
}
// default construction
provider::provider()
{
parent_provider = 0;
}
// called by selection_change_cb whenever the gui of this provider is selected
void provider::on_select()
{
}
// called by selection_change_cb whenever the gui of this provider is deselected
void provider::on_deselect()
{
}
// this is called by the gui group when the selection changes
void provider::selection_change_cb(cgv::base::base_ptr new_child, bool selected)
{
if (new_child == parent_group) {
if (selected)
on_select();
else
on_deselect();
}
}
// the gui window sets the parent group through this method
void provider::set_parent(gui_group_ptr _parent_group)
{
if (parent_group) {
gui_group_ptr ctrl_grp = parent_group->get_parent()->get_interface<gui_group>();
if (ctrl_grp)
disconnect(ctrl_grp->on_selection_change, this, &provider::selection_change_cb);
}
parent_group = _parent_group;
gui_group_ptr ctrl_grp = parent_group->get_parent()->get_interface<gui_group>();
if (ctrl_grp)
connect(ctrl_grp->on_selection_change, this, &provider::selection_change_cb);
}
/** this method uses the following strategy to automatically determine
the name shown in guis for a provider instance:
- try to cast the object into cgv::base::named, if successful,
use get_name() method
- check whether get_menu_path() results in a path or name. In
case of a path, use the last entry of the path as name.
- try to cast to cgv::base::base and use get_type_name().
- return "unnamed" otherwise
*/
std::string provider::get_gui_name() const
{
const cgv::base::base* bp = dynamic_cast<const cgv::base::base*>(this);
if (bp) {
if (const_cast<cgv::base::base*>(bp)->get_named())
return const_cast<cgv::base::base*>(bp)->get_named()->get_name();
}
std::string mp = get_menu_path();
if (!mp.empty()) {
unsigned int pos = (unsigned int) mp.find_last_of('/');
if (pos == std::string::npos || pos == mp.size()-1)
return mp;
return mp.substr(pos+1);
}
if (bp)
return bp->get_type_name();
return "unnamed";
}
std::string provider::get_parent_type() const
{
return "align_group";
}
/// ensure that my UI is selected in the closest parent that is a tab group
bool provider::ensure_selected_in_tab_group_parent()
{
cgv::gui::gui_group_ptr my_group = get_parent_group();
if (my_group) {
cgv::gui::gui_group_ptr tab_group = my_group->get_parent()->cast<cgv::gui::gui_group>();
if (tab_group) {
cgv::base::base_ptr c = my_group;
if (c) {
tab_group->select_child(c, true);
return true;
}
}
}
return false;
}
// return a path in the main menu to select the gui
std::string provider::get_menu_path() const
{
return "";
}
// return a shortcut to activate the gui without menu navigation
shortcut provider::get_shortcut() const
{
return shortcut();
}
// use this method to recreate the gui, dont call create gui directly
void provider::recreate_gui()
{
if (!parent_group)
return;
// ensure that layout is available
parent_group->set("dolayout", true);
int xscroll = parent_group->get<int>("xscroll");
int yscroll = parent_group->get<int>("yscroll");
remove_all_elements();
create_gui();
parent_group->set("dolayout", true);
parent_group->set("xscroll", xscroll);
parent_group->set("yscroll", yscroll);
}
std::set<provider*>& ref_providers()
{
static std::set<provider*> providers;
return providers;
}
/*
cgv::os::mutex& ref_mutex()
{
static cgv::os::mutex m;
return m;
}
*/
void trigger_callback(double,double)
{
// ref_mutex().lock();
std::set<provider*>& ps = ref_providers();
while (ps.size() > 0) {
provider* p = *ps.begin();
p->recreate_gui();
ps.erase(p);
}
// ref_mutex().unlock();
}
trigger& ref_one_shot_trigger()
{
static trigger t;
static bool initialized = false;
if (!initialized) {
initialized = true;
connect(t.shoot, &trigger_callback);
}
return t;
}
// ensure to remove posted recreation callbacks
provider::~provider()
{
std::set<provider*>& ps = ref_providers();
if (ps.empty())
return;
// ref_mutex().lock();
if (ps.find(this) != ps.end())
ps.erase(this);
// ref_mutex().unlock();
}
// schedule the recreation of the gui for the next time the program is idle
void provider::post_recreate_gui()
{
if (parent_provider)
parent_provider->post_recreate_gui();
else {
// ref_mutex().lock();
std::set<provider*>& ps = ref_providers();
if (ps.find(this) == ps.end()) {
bool dont_insert = false;
if (!ref_one_shot_trigger().is_scheduled())
if (!ref_one_shot_trigger().schedule_one_shot(0))
dont_insert = true;
if (!dont_insert)
ps.insert(this);
}
// ref_mutex().unlock();
}
}
}
}
| 29.097143 | 241 | 0.682836 | [
"object",
"vector"
] |
ecbf7638f31434a77a930f34b471eb95fc657b00 | 4,777 | cpp | C++ | private/bt/core/render/RenderManager.cpp | c0de4un/btSDK | fbdd6873cc33b5d7af09920f62edf6c1c26cf5f7 | [
"MIT"
] | 1 | 2020-05-20T17:45:47.000Z | 2020-05-20T17:45:47.000Z | private/bt/core/render/RenderManager.cpp | c0de4un/btSDK | fbdd6873cc33b5d7af09920f62edf6c1c26cf5f7 | [
"MIT"
] | null | null | null | private/bt/core/render/RenderManager.cpp | c0de4un/btSDK | fbdd6873cc33b5d7af09920f62edf6c1c26cf5f7 | [
"MIT"
] | null | null | null | /**
* Copyright © 2020 Denis Z. (code4un@yandex.ru) All rights reserved.
* Authors: Denis Z. (code4un@yandex.ru)
* All rights reserved.
* License: see LICENSE.txt
*
* 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 display the names 'Denis Zyamaev' and
* in the credits of the application, if such credits exist.
* The authors of this work must be notified via email (code4un@yandex.ru) in
* this case of redistribution.
* 3. Neither the name of copyright holders nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS
* IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
// -----------------------------------------------------------
// ===========================================================
// INCLUDES
// ===========================================================
// HEADER
#ifndef BT_CORE_RENDER_MANAGER_HPP
#include "../../../../public/bt/core/render/RenderManager.hpp"
#endif // !BT_CORE_RENDER_MANAGER_HPP
// Include bt::SystemTypes
#ifndef BT_CFG_SYSTEMS_HPP
#include "../../../../public/bt/cfg/bt_systems.hpp"
#endif // !BT_CFG_SYSTEMS_HPP
// ===========================================================
// bt::core::RenderManager
// ===========================================================
namespace bt
{
namespace core
{
// -----------------------------------------------------------
// ===========================================================
// FIELDS
// ===========================================================
bt_AsyncStorage<bt_sptr<RenderManager>> RenderManager::mInstanceHolder;
// ===========================================================
// CONSTRUCTOR & DESTRUCTOR
// ===========================================================
RenderManager::RenderManager()
: System( static_cast<const ecs_TypeID>(bt_SystemTypes::RENDER) ),
mClearColor( 0.39F, 0.6F, 1.0F, 1.0F )
{
}
RenderManager::~RenderManager()
{
this->Stop();
}
// ===========================================================
// GETTERS & SETTERS
// ===========================================================
bt_sptr<RenderManager> RenderManager::getInstance() BT_NOEXCEPT
{ return mInstanceHolder.getItem(); }
void RenderManager::setSurfaceColor( const Color4f& pColor ) BT_NOEXCEPT
{ mClearColor = pColor; }
Color4f RenderManager::getSurfaceColor() const BT_NOEXCEPT
{ return mClearColor; }
// ===========================================================
// METHODS
// ===========================================================
bool RenderManager::onStart()
{
return System::onStart();
}
bool RenderManager::onResume()
{
return System::onResume();
}
void RenderManager::onPause()
{
System::onPause();
}
void RenderManager::onStop()
{
System::onPause();
}
void RenderManager::Initialize( bt_sptr<RenderManager> pInstance )
{
bt_sptr<bt_RenderManager> instance = getInstance();
if ( instance == nullptr )
mInstanceHolder.setItem( bt_Memory::MoveShared(pInstance) ); //std::move(pInstance)
}
void RenderManager::Terminate()
{ mInstanceHolder.setItem( bt_sptr<bt_RenderManager>(nullptr) ); }
// -----------------------------------------------------------
} /// bt::core
} /// bt
// -----------------------------------------------------------
| 35.125 | 99 | 0.515596 | [
"render"
] |
ecc13ff44ba3c37eff5bf03a01764aabe413ccd1 | 1,264 | cpp | C++ | test/002-must-exist.cpp | once-ler/Store-cpp | 27d65057b2984c61a4b8be9d96d8fa6d70de1fb7 | [
"BSD-3-Clause"
] | 3 | 2019-08-18T19:14:02.000Z | 2019-09-20T05:38:58.000Z | test/002-must-exist.cpp | once-ler/Store-cpp | 27d65057b2984c61a4b8be9d96d8fa6d70de1fb7 | [
"BSD-3-Clause"
] | null | null | null | test/002-must-exist.cpp | once-ler/Store-cpp | 27d65057b2984c61a4b8be9d96d8fa6d70de1fb7 | [
"BSD-3-Clause"
] | 1 | 2019-09-20T05:39:01.000Z | 2019-09-20T05:39:01.000Z | /*
g++ -std=c++14 -I ../../ -I /usr/local/include -I ../../../Store-cpp -I ../../../json/single_include/nlohmann ../002-must-exist.cpp -o bin/testing -L /usr/lib/x86_64-linux-gnu -L /usr/local/lib -luuid
*/
#include <cassert>
#include <iostream>
#include "store.models/src/extensions.hpp"
using namespace std;
using namespace store::extensions;
string testMustExist(vector<string> mustExistKeys = {}) {
vector<string> mustExistKeysQuoted;
std::transform(mustExistKeys.begin(), mustExistKeys.end(), std::back_inserter(mustExistKeysQuoted), [](const string& s) { return wrapString(s); });
string mustExistKeysQuotedString = join(mustExistKeysQuoted.begin(), mustExistKeysQuoted.end(), string(","));
string matchMustExistKeys = mustExistKeysQuotedString.size() > 0 ? string_format(" and data ?& array[%s]", mustExistKeysQuotedString.c_str()) : "";
return move(matchMustExistKeys);
}
int main(int argc, char *argv[]) {
auto res = testMustExist();
cout << "Should be empty: " << std::boolalpha << (res.size() == 0) << endl;
assert(res == "");
auto res1 = testMustExist({"a", "b", "c"});
cout << "Should not be empty: " << std::boolalpha << (res1.size() > 0) << endl << res1 << endl;
assert(" and data ?& array['a','b','c']" == res1);
}
| 38.30303 | 200 | 0.662184 | [
"vector",
"transform"
] |
ecc20aa2f34dc929f99405a1e82be4a00c2e49fa | 3,396 | cc | C++ | tutorial/append_computation_example.cc | kalyanbhetwal/IEGenLib | 6828a4940f75c734da5f67116c1a5271610901ac | [
"BSD-2-Clause"
] | 1 | 2021-03-04T07:29:34.000Z | 2021-03-04T07:29:34.000Z | tutorial/append_computation_example.cc | kalyanbhetwal/IEGenLib | 6828a4940f75c734da5f67116c1a5271610901ac | [
"BSD-2-Clause"
] | 160 | 2021-01-05T18:34:10.000Z | 2022-03-03T01:27:49.000Z | tutorial/append_computation_example.cc | kalyanbhetwal/IEGenLib | 6828a4940f75c734da5f67116c1a5271610901ac | [
"BSD-2-Clause"
] | 3 | 2020-07-01T19:38:46.000Z | 2022-03-03T02:16:08.000Z | #include "iegenlib.h"
#include <utility>
#include <fstream>
#include <iostream>
#include <sstream>
Computation* func1();
Computation* func2();
Computation* func1() {
Computation* comp = new Computation();
comp->addParameter("var", "int&");
comp->addParameter("baz", "int*");
comp->addStmt(new Stmt (
"*baz = (*baz) + 1;",
"{[0]}",
"{[0]->[0]}",
{{"baz", "{[0]->[0]}"}},
{{"baz", "{[0]->[0]}"}}
));
comp->addStmt(new Stmt (
"var = (*baz) * 3;",
"{[0]}",
"{[0]->[1]}",
{{"baz", "{[0]->[0]}"}},
{{"var", "{[0]->[0]}"}}
));
std::vector<std::string> args = {"var"};
Computation* func2Comp = func2();
AppendComputationResult func2Res = comp->appendComputation(func2Comp, "{[0]}", "{[0]->[2]}", args);
delete func2Comp;
unsigned int i = func2Res.tuplePosition + 1;
std::string ret = func2Res.returnValues.back();
comp->addStmt(new Stmt (
"*baz = "+ret+";",
"{[0]}",
"{[0]->["+std::to_string(i)+"]}",
{{ret, "{[0]->[0]}"}},
{{"baz", "{[0]->[0]}"}}
));
return comp;
}
Computation* func2() {
Computation* comp = new Computation();
comp->addParameter("val", "int&");
comp->addStmt(new Stmt (
"val = val - 5;",
"{[0]}",
"{[0]->[0]}",
{{"val", "{[0]->[0]}"}},
{{"val", "{[0]->[0]}"}}
));
comp->addDataSpace("valReturn", "int");
comp->addReturnValue("valReturn", true);
comp->addStmt(new Stmt (
"valReturn = val + 8;",
"{[0]}",
"{[0]->[1]}",
{{"val", "{[0]->[0]}"}},
{{"valReturn", "{[0]->[0]}"}}
));
return comp;
}
/*
* Instructions to view the codegen file.
* From root make tutorial.
* Run the executable from root to generate codegen.
*/
using iegenlib::Computation;
using namespace std;
int main(int argc, char** argv) {
/* int foo = 6;
* int bar = foo * 2;
* func1(foo, &bar);
* bar = foo * 2;
* func1(foo, bar);
*
*
* func1(int& var, int* baz) {
* (*baz)++;
* var = (*baz) * 3;
* *baz = func2(var);
* }
*
* func2(int& val) {
* val -= 5;
* return val + 8;
* }
* */
Computation* comp = new Computation();
comp->addDataSpace("foo", "int");
comp->addDataSpace("bar", "int");
comp->addStmt(new Stmt (
"foo = 6;",
"{[0]}",
"{[0]->[0]}",
{},
{{"foo", "{[0]->[0]}"}}
));
comp->addStmt(new Stmt (
"bar = foo * 2;",
"{[0]}",
"{[0]->[1]}",
{{"foo", "{[0]->[0]}"}},
{{"bar", "{[0]->[0]}"}}
));
std::vector<std::string> args = {"foo", "bar"};
Computation* func1Comp = func1();
AppendComputationResult func1Res = comp->appendComputation(func1Comp, "{[0]}", "{[0]->[2]}", args);
unsigned int i = func1Res.tuplePosition + 1;
comp->addStmt(new Stmt (
"bar = foo * 2;",
"{[0]}",
"{[0]->["+std::to_string(i++)+"]}",
{{"foo", "{[0]->[0]}"}},
{{"bar", "{[0]->[0]}"}}
));
func1Res = comp->appendComputation(func1Comp, "{[0]}", "{[0]->["+std::to_string(i++)+"]}", args);
delete func1Comp;
comp->finalize();
ofstream outStream;
outStream.open("append_test.c");
outStream << comp->codeGen();
outStream.close();
delete comp;
return 0;
}
| 21.358491 | 103 | 0.454653 | [
"vector"
] |
ecc87344d1245df63ddddaee8ca7ae0754afc6de | 1,283 | cpp | C++ | opt_algs.1.0/oa_frosen.cpp | ghornby/opt_algs | b68aefceda7c6ab50976e87551cc6986b5616321 | [
"BSD-3-Clause"
] | 1 | 2020-02-23T03:32:22.000Z | 2020-02-23T03:32:22.000Z | opt_algs.1.0/oa_frosen.cpp | ghornby/opt_algs | b68aefceda7c6ab50976e87551cc6986b5616321 | [
"BSD-3-Clause"
] | null | null | null | opt_algs.1.0/oa_frosen.cpp | ghornby/opt_algs | b68aefceda7c6ab50976e87551cc6986b5616321 | [
"BSD-3-Clause"
] | null | null | null | /***
This file is part of the OptAlgs C++ library originally developed
by Gregory Hornby.
This code is released under the BSD-3 license:
http://opensource.org/licenses/BSD-3-Clause
See the file "license.txt" in the root directory for full details.
***/
/*******************************************************
File: oaf_rosen.cpp
********************************************************/
#include "oa_frosen.h"
#include "individ_real.h"
const std::string OAFRosen :: class_name_("OAF_Rosen");
OAFRosen :: OAFRosen()
{
num_evaluations_ = 0;
}
OAFRosen :: ~OAFRosen()
{
}
FitnessFunc* OAFRosen :: new_instance() const
{
FitnessFunc* func = new OAFRosen();
return func;
}
double OAFRosen :: evaluate(Individual* ind)
{
Individ_Real* ind_real = (Individ_Real*)ind;
std::vector<double> x(ind_real->get_genes());
std::vector<double> y = ind_real->get_genes();
double fitness = 0;
for (std::vector<double>::size_type i=0; i<x.size(); i++) {
double val = 1.0 - x[i];
fitness += val * val;
}
for (std::vector<double>::size_type i=1; i<x.size(); i++) {
double val = x[i] - x[i-1]*x[i-1];
fitness += 100.0 * val * val;
}
ind_real->set_fitness(fitness);
update_best(fitness);
increment_num_evals();
return fitness;
}
| 17.575342 | 66 | 0.597038 | [
"vector"
] |
ecd0929bcd456c86970a16e42e3c4e9fa1331b65 | 27,573 | cpp | C++ | Engine/Source/Runtime/Slate/Private/Framework/Application/MenuStack.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Runtime/Slate/Private/Framework/Application/MenuStack.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Runtime/Slate/Private/Framework/Application/MenuStack.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "Framework/Application/MenuStack.h"
#include "Layout/LayoutUtils.h"
#include "Layout/WidgetPath.h"
#include "Framework/Application/SlateApplication.h"
#include "Widgets/Text/STextBlock.h"
#include "Widgets/Layout/SBox.h"
#include "Widgets/Layout/SPopup.h"
#include "Framework/Application/Menu.h"
#define LOCTEXT_NAMESPACE "MenuStack"
namespace FMenuStackDefs
{
/** Maximum size of menus as a fraction of the work area height */
const float MaxMenuScreenHeightFraction = 0.8f;
const float AnimationDuration = 0.15f;
}
/** Overlay widget class used to hold menu contents and display them on top of the current window */
class SMenuPanel : public SOverlay
{
public:
SLATE_BEGIN_ARGS(SMenuPanel)
{
_Visibility = EVisibility::SelfHitTestInvisible;
}
SLATE_END_ARGS()
void Construct(const FArguments& InArgs)
{
SOverlay::Construct(SOverlay::FArguments());
}
void PushMenu(TSharedRef<FMenuBase> InMenu, const FVector2D& InLocation)
{
check(InMenu->GetContent().IsValid());
TSharedPtr<SWindow> ParentWindow = InMenu->GetParentWindow();
check(ParentWindow.IsValid());
// Transform InLocation into a position local to this panel (assumes the panel is in an overlay that covers the whole of the panel window)
FVector2D PanelInScreen = ParentWindow->GetRectInScreen().GetTopLeft();
FVector2D PanelInWindow = ParentWindow->GetLocalToScreenTransform().Inverse().TransformPoint(PanelInScreen);
FVector2D LocationInWindow = ParentWindow->GetLocalToScreenTransform().Inverse().TransformPoint(InLocation);
FVector2D LocationInPanel = LocationInWindow - PanelInWindow;
// Add the new menu into a slot on this panel and set the padding so that its position is correct
AddSlot()
.HAlign(HAlign_Left)
.VAlign(VAlign_Top)
.Padding(LocationInPanel.X, LocationInPanel.Y, 0, 0)
[
InMenu->GetContent().ToSharedRef()
];
// Make sure that the menu will remove itself from the panel when dismissed
InMenu->GetOnMenuDismissed().AddSP(this, &SMenuPanel::OnMenuClosed);
}
void OnMenuClosed(TSharedRef<IMenu> InMenu)
{
RemoveSlot(InMenu->GetContent().ToSharedRef());
}
};
namespace
{
/** Widget that wraps any menu created in FMenuStack to provide default key handling, focus tracking and helps us spot menus in widget paths */
DECLARE_DELEGATE_RetVal_OneParam(FReply, FOnKeyDown, FKey)
DECLARE_DELEGATE_OneParam(FOnMenuLostFocus, const FWidgetPath&)
class SMenuContentWrapper : public SCompoundWidget
{
public:
SLATE_BEGIN_ARGS(SMenuContentWrapper)
: _MenuContent()
, _OnKeyDown()
, _OptionalMinMenuWidth()
, _OptionalMinMenuHeight()
{}
SLATE_DEFAULT_SLOT(FArguments, MenuContent)
SLATE_EVENT(FOnKeyDown, OnKeyDown)
SLATE_EVENT(FOnMenuLostFocus, OnMenuLostFocus)
SLATE_ARGUMENT(FOptionalSize, OptionalMinMenuWidth)
SLATE_ARGUMENT(FOptionalSize, OptionalMinMenuHeight)
SLATE_END_ARGS()
/** Construct this widget */
void Construct(const FArguments& InArgs)
{
// The visibility of the content wrapper should match that of the provided content
Visibility = AccessWidgetVisibilityAttribute(InArgs._MenuContent.Widget);
OnKeyDownDelegate = InArgs._OnKeyDown;
OnMenuLostFocus = InArgs._OnMenuLostFocus;
ChildSlot
[
SNew(SBox)
.MinDesiredWidth(InArgs._OptionalMinMenuWidth)
.MaxDesiredHeight(InArgs._OptionalMinMenuHeight)
[
InArgs._MenuContent.Widget
]
];
}
virtual void OnFocusChanging(const FWeakWidgetPath& PreviousFocusPath, const FWidgetPath& NewWidgetPath, const FFocusEvent& InFocusEvent) override
{
// if focus changed and this menu content had focus (or one of its children did) then inform the stack via the OnMenuLostFocus event
if (OnMenuLostFocus.IsBound() && PreviousFocusPath.ContainsWidget(AsShared()))
{
return OnMenuLostFocus.Execute(NewWidgetPath);
}
}
private:
/** This widget must support keyboard focus */
virtual bool SupportsKeyboardFocus() const override
{
return true;
}
virtual FReply OnKeyDown( const FGeometry& MyGeometry, const FKeyEvent& InKeyEvent ) override
{
if (OnKeyDownDelegate.IsBound())
{
return OnKeyDownDelegate.Execute(InKeyEvent.GetKey());
}
return FReply::Unhandled();
}
/** Delegate to forward keys down events on the menu */
FOnKeyDown OnKeyDownDelegate;
/** Delegate to inform the stack that a menu has lost focus and might need to be closed */
FOnMenuLostFocus OnMenuLostFocus;
};
/** Global handler used to handle key presses on popup menus */
FReply OnMenuKeyDown(const FKey Key)
{
if (Key == EKeys::Escape)
{
FSlateApplication::Get().DismissAllMenus();
return FReply::Handled();
}
return FReply::Unhandled();
}
} // anon namespace
TSharedRef<IMenu> FMenuStack::Push(const FWidgetPath& InOwnerPath, const TSharedRef<SWidget>& InContent, const FVector2D& SummonLocation, const FPopupTransitionEffect& TransitionEffect, const bool bFocusImmediately, const FVector2D& SummonLocationSize, TOptional<EPopupMethod> InMethod, const bool bIsCollapsedByParent, const bool bEnablePerPixelTransparency)
{
// We want to ensure that when the window is restored to restore the current keyboard focus
InOwnerPath.GetWindow()->SetWidgetToFocusOnActivate(FSlateApplication::Get().GetKeyboardFocusedWidget());
FSlateRect Anchor(SummonLocation, SummonLocation + SummonLocationSize);
TSharedPtr<IMenu> ParentMenu;
if (HasMenus())
{
// Find a menu in the stack in InOwnerPath to determine the level to insert this
ParentMenu = FindMenuInWidgetPath(InOwnerPath);
check(HostWindow.IsValid());
}
if (!ParentMenu.IsValid())
{
// pushing a new root menu (leave ParentMenu invalid)
// The active method is determined when a new root menu is pushed
ActiveMethod = InMethod.IsSet() ? FPopupMethodReply::UseMethod(InMethod.GetValue()) : QueryPopupMethod(InOwnerPath);
// The host window is determined when a new root menu is pushed
// This must be set prior to PushInternal below, as it will be referenced if the menu being created is a new root menu.
SetHostPath(InOwnerPath);
}
TGuardValue<bool> Guard(bHostWindowGuard, true);
return PushInternal(ParentMenu, InContent, Anchor, TransitionEffect, bFocusImmediately, ActiveMethod.GetShouldThrottle(), bIsCollapsedByParent, bEnablePerPixelTransparency);
}
TSharedRef<IMenu> FMenuStack::Push(const TSharedPtr<IMenu>& InParentMenu, const TSharedRef<SWidget>& InContent, const FVector2D& SummonLocation, const FPopupTransitionEffect& TransitionEffect, const bool bFocusImmediately, const FVector2D& SummonLocationSize, const bool bIsCollapsedByParent, const bool bEnablePerPixelTransparency)
{
check(Stack.Contains(InParentMenu));
check(HostWindow.IsValid());
FSlateRect Anchor(SummonLocation, SummonLocation + SummonLocationSize);
return PushInternal(InParentMenu, InContent, Anchor, TransitionEffect, bFocusImmediately, EShouldThrottle::Yes, bIsCollapsedByParent, bEnablePerPixelTransparency);
}
TSharedRef<IMenu> FMenuStack::PushHosted(const FWidgetPath& InOwnerPath, const TSharedRef<IMenuHost>& InMenuHost, const TSharedRef<SWidget>& InContent, TSharedPtr<SWidget>& OutWrappedContent, const FPopupTransitionEffect& TransitionEffect, EShouldThrottle ShouldThrottle, const bool bIsCollapsedByParent)
{
TSharedPtr<IMenu> ParentMenu;
if (HasMenus())
{
// Find a menu in the stack in InOwnerPath to determine the level to insert this
ParentMenu = FindMenuInWidgetPath(InOwnerPath);
check(HostWindow.IsValid());
}
if (!ParentMenu.IsValid())
{
// pushing a new root menu (leave ParentMenu invalid)
// The active method is determined when a new root menu is pushed and hosted menus are always UseCurrentWindow
ActiveMethod = FPopupMethodReply::UseMethod(EPopupMethod::UseCurrentWindow);
// The host window is determined when a new root menu is pushed
SetHostPath(InOwnerPath);
}
return PushHosted(ParentMenu, InMenuHost, InContent, OutWrappedContent, TransitionEffect, ShouldThrottle);
}
TSharedRef<IMenu> FMenuStack::PushHosted(const TSharedPtr<IMenu>& InParentMenu, const TSharedRef<IMenuHost>& InMenuHost, const TSharedRef<SWidget>& InContent, TSharedPtr<SWidget>& OutWrappedContent, const FPopupTransitionEffect& TransitionEffect, EShouldThrottle ShouldThrottle, const bool bIsCollapsedByParent)
{
check(HostWindow.IsValid());
// Create a FMenuInHostWidget
TSharedRef<SWidget> WrappedContent = WrapContent(InContent);
TSharedRef<FMenuInHostWidget> OutMenu = MakeShareable(new FMenuInHostWidget(InMenuHost, WrappedContent, bIsCollapsedByParent));
PendingNewMenu = OutMenu;
// Set the returned content - this must be drawn by the hosting widget until the menu gets dismissed and calls IMenuHost::OnMenuDismissed on its host
OutWrappedContent = WrappedContent;
// Register to get a callback when it's dismissed - to fixup stack
OutMenu->GetOnMenuDismissed().AddRaw(this, &FMenuStack::OnMenuDestroyed);
PostPush(InParentMenu, OutMenu, ShouldThrottle);
PendingNewMenu.Reset();
return OutMenu;
}
TSharedRef<IMenu> FMenuStack::PushInternal(const TSharedPtr<IMenu>& InParentMenu, const TSharedRef<SWidget>& InContent, FSlateRect Anchor, const FPopupTransitionEffect& TransitionEffect, const bool bFocusImmediately, EShouldThrottle ShouldThrottle, const bool bIsCollapsedByParent, const bool bEnablePerPixelTransparency)
{
FPrePushArgs PrePushArgs;
PrePushArgs.Content = InContent;
PrePushArgs.Anchor = Anchor;
PrePushArgs.TransitionEffect = TransitionEffect;
PrePushArgs.bFocusImmediately = bFocusImmediately;
PrePushArgs.bIsCollapsedByParent = bIsCollapsedByParent;
// Pre-push stage
// Determines correct layout
// Wraps content
// Other common setup steps needed by all (non-hosted) menus
const FPrePushResults PrePushResults = PrePush(PrePushArgs);
// Menu object creation stage
TSharedRef<FMenuBase> OutMenu = ActiveMethod.GetPopupMethod() == EPopupMethod::CreateNewWindow
? PushNewWindow(InParentMenu, PrePushResults, bEnablePerPixelTransparency)
: PushPopup(InParentMenu, PrePushResults);
// Post-push stage
// Updates the stack and content map member variables
PostPush(InParentMenu, OutMenu, ShouldThrottle);
PendingNewMenu.Reset();
return OutMenu;
}
FMenuStack::FPrePushResults FMenuStack::PrePush(const FPrePushArgs& InArgs)
{
FPrePushResults OutResults;
OutResults.bIsCollapsedByParent = InArgs.bIsCollapsedByParent;
OutResults.bFocusImmediately = InArgs.bFocusImmediately;
if (InArgs.bFocusImmediately)
{
OutResults.WidgetToFocus = InArgs.Content;
}
// Only enable window position/size transitions if we're running at a decent frame rate
OutResults.bAllowAnimations = FSlateApplication::Get().AreMenuAnimationsEnabled() && FSlateApplication::Get().IsRunningAtTargetFrameRate();
// Calc the max height available on screen for the menu
float MaxHeight;
if (ActiveMethod.GetPopupMethod() == EPopupMethod::CreateNewWindow)
{
FSlateRect WorkArea = FSlateApplication::Get().GetWorkArea(InArgs.Anchor);
MaxHeight = FMenuStackDefs::MaxMenuScreenHeightFraction * WorkArea.GetSize().Y;
}
else
{
MaxHeight = FMenuStackDefs::MaxMenuScreenHeightFraction * HostWindow->GetClientSizeInScreen().Y;
}
bool bAnchorSetsMinWidth = InArgs.TransitionEffect.SlideDirection == FPopupTransitionEffect::ComboButton;
// Wrap menu content in a box needed for various sizing and tracking purposes
FOptionalSize OptionalMinWidth = bAnchorSetsMinWidth ? InArgs.Anchor.GetSize().X : FOptionalSize();
FOptionalSize OptionalMinHeight = MaxHeight;
// Wrap content in an SPopup before the rest of the wrapping process - should make menus appear on top using deferred presentation
TSharedRef<SWidget> TempContent = SNew(SPopup)[InArgs.Content.ToSharedRef()];
OutResults.WrappedContent = WrapContent(TempContent, OptionalMinWidth, OptionalMinHeight);
const float ApplicationScale = FSlateApplication::Get().GetApplicationScale() * HostWindow->GetNativeWindow()->GetDPIScaleFactor();
OutResults.WrappedContent->SlatePrepass(ApplicationScale);
// @todo slate: Doesn't take into account potential window border size
OutResults.ExpectedSize = OutResults.WrappedContent->GetDesiredSize() * ApplicationScale;
EOrientation Orientation = (InArgs.TransitionEffect.SlideDirection == FPopupTransitionEffect::SubMenu) ? Orient_Horizontal : Orient_Vertical;
// Calculate the correct position for the menu based on the popup method
if (ActiveMethod.GetPopupMethod() == EPopupMethod::CreateNewWindow)
{
// already handled
const bool bAutoAdjustForDPIScale = false;
// Places the menu's window in the work area
OutResults.AnimStartLocation = OutResults.AnimFinalLocation = FSlateApplication::Get().CalculatePopupWindowPosition(InArgs.Anchor, OutResults.ExpectedSize, bAutoAdjustForDPIScale, FVector2D::ZeroVector, Orientation);
}
else
{
// Places the menu's content in the host window
const FVector2D ProposedPlacement(
Orientation == Orient_Horizontal ? InArgs.Anchor.Right : InArgs.Anchor.Left,
Orientation == Orient_Horizontal ? InArgs.Anchor.Top : InArgs.Anchor.Bottom);
OutResults.AnimStartLocation = OutResults.AnimFinalLocation =
ComputePopupFitInRect(InArgs.Anchor, FSlateRect(ProposedPlacement, ProposedPlacement + OutResults.ExpectedSize), Orientation, HostWindow->GetClientRectInScreen());
}
// Start the pop-up menu at an offset location, then animate it to its target location over time
// @todo: Anims aren't supported or attempted - this is legacy code left in in case we reinstate menu anims
if (OutResults.bAllowAnimations)
{
const bool bSummonRight = OutResults.AnimFinalLocation.X >= OutResults.AnimStartLocation.X;
const bool bSummonBelow = OutResults.AnimFinalLocation.Y >= OutResults.AnimStartLocation.Y;
const int32 SummonDirectionX = bSummonRight ? 1 : -1;
const int32 SummonDirectionY = bSummonBelow ? 1 : -1;
switch (InArgs.TransitionEffect.SlideDirection)
{
case FPopupTransitionEffect::None:
// No sliding
break;
case FPopupTransitionEffect::ComboButton:
OutResults.AnimStartLocation.Y = FMath::Max(OutResults.AnimStartLocation.Y + 30.0f * SummonDirectionY, 0.0f);
break;
case FPopupTransitionEffect::TopMenu:
OutResults.AnimStartLocation.Y = FMath::Max(OutResults.AnimStartLocation.Y + 60.0f * SummonDirectionY, 0.0f);
break;
case FPopupTransitionEffect::SubMenu:
OutResults.AnimStartLocation.X += 60.0f * SummonDirectionX;
break;
case FPopupTransitionEffect::TypeInPopup:
OutResults.AnimStartLocation.Y = FMath::Max(OutResults.AnimStartLocation.Y + 30.0f * SummonDirectionY, 0.0f);
break;
case FPopupTransitionEffect::ContextMenu:
OutResults.AnimStartLocation.X += 30.0f * SummonDirectionX;
OutResults.AnimStartLocation.Y += 50.0f * SummonDirectionY;
break;
}
}
// Release the mouse so that context can be properly restored upon closing menus. See CL 1411833 before changing this.
if (InArgs.bFocusImmediately)
{
FSlateApplication::Get().ReleaseMouseCapture();
}
return OutResults;
}
TSharedRef<FMenuBase> FMenuStack::PushNewWindow(TSharedPtr<IMenu> InParentMenu, const FPrePushResults& InPrePushResults, const bool bEnablePerPixelTransparency)
{
check(ActiveMethod.GetPopupMethod() == EPopupMethod::CreateNewWindow);
// Start pop-up windows out transparent, then fade them in over time
#if ALPHA_BLENDED_WINDOWS
const EWindowTransparency Transparency(bEnablePerPixelTransparency ? EWindowTransparency::PerPixel : InPrePushResults.bAllowAnimations ? EWindowTransparency::PerWindow : EWindowTransparency::None);
#else
const EWindowTransparency Transparency(InPrePushResults.bAllowAnimations ? EWindowTransparency::PerWindow : EWindowTransparency::None);
#endif
const float InitialWindowOpacity = InPrePushResults.bAllowAnimations ? 0.0f : 1.0f;
const float TargetWindowOpacity = 1.0f;
// Create a new window for the menu
TSharedRef<SWindow> NewMenuWindow = SNew(SWindow)
.Type(EWindowType::Menu)
.IsPopupWindow(true)
.SizingRule(ESizingRule::Autosized)
.ScreenPosition(InPrePushResults.AnimStartLocation)
.AutoCenter(EAutoCenter::None)
.ClientSize(InPrePushResults.ExpectedSize)
.AdjustInitialSizeAndPositionForDPIScale(false)
.InitialOpacity(InitialWindowOpacity)
.SupportsTransparency(Transparency)
.FocusWhenFirstShown(InPrePushResults.bFocusImmediately)
.ActivationPolicy(InPrePushResults.bFocusImmediately ? EWindowActivationPolicy::Always : EWindowActivationPolicy::Never)
[
InPrePushResults.WrappedContent.ToSharedRef()
];
PendingNewWindow = NewMenuWindow;
if (InPrePushResults.bFocusImmediately && InPrePushResults.WidgetToFocus.IsValid())
{
// Focus the unwrapped content rather than just the window
NewMenuWindow->SetWidgetToFocusOnActivate(InPrePushResults.WidgetToFocus);
}
TSharedRef<FMenuInWindow> Menu = MakeShareable(new FMenuInWindow(NewMenuWindow, InPrePushResults.WrappedContent.ToSharedRef(), InPrePushResults.bIsCollapsedByParent));
PendingNewMenu = Menu;
TSharedPtr<SWindow> ParentWindow;
if (InParentMenu.IsValid())
{
ParentWindow = InParentMenu->GetParentWindow();
}
else
{
ParentWindow = HostWindow;
}
FSlateApplication::Get().AddWindowAsNativeChild(NewMenuWindow, ParentWindow.ToSharedRef(), true);
// Kick off the intro animation!
// @todo: Anims aren't supported or attempted - this is legacy code left in in case we reinstate menu anims
if (InPrePushResults.bAllowAnimations)
{
FCurveSequence Sequence;
Sequence.AddCurve(0, FMenuStackDefs::AnimationDuration, ECurveEaseFunction::CubicOut);
NewMenuWindow->MorphToPosition(Sequence, TargetWindowOpacity, InPrePushResults.AnimFinalLocation);
}
PendingNewWindow.Reset();
return Menu;
}
TSharedRef<FMenuBase> FMenuStack::PushPopup(TSharedPtr<IMenu> InParentMenu, const FPrePushResults& InPrePushResults)
{
check(ActiveMethod.GetPopupMethod() == EPopupMethod::UseCurrentWindow);
// Create a FMenuInPopup
check(InPrePushResults.WrappedContent.IsValid());
TSharedRef<FMenuInPopup> Menu = MakeShareable(new FMenuInPopup(InPrePushResults.WrappedContent.ToSharedRef(), InPrePushResults.bIsCollapsedByParent));
PendingNewMenu = Menu;
// Register to get callback when it's dismissed - to fixup stack
Menu->GetOnMenuDismissed().AddRaw(this, &FMenuStack::OnMenuDestroyed);
// Add it to a slot on the menus panel widget
HostWindowPopupPanel->PushMenu(Menu, InPrePushResults.AnimFinalLocation);
if (InPrePushResults.bFocusImmediately && InPrePushResults.WidgetToFocus.IsValid())
{
FSlateApplication::Get().SetKeyboardFocus(InPrePushResults.WidgetToFocus, EFocusCause::SetDirectly);
}
return Menu;
}
void FMenuStack::PostPush(TSharedPtr<IMenu> InParentMenu, TSharedRef<FMenuBase> InMenu, EShouldThrottle ShouldThrottle )
{
// Determine at which index we insert this new menu in the stack
int32 InsertIndex = 0;
if (InParentMenu.IsValid())
{
int32 ParentIndex = Stack.IndexOfByKey(InParentMenu);
check(ParentIndex != INDEX_NONE);
InsertIndex = ParentIndex + 1;
}
// Insert before dismissing others to stop the stack accidentally emptying briefly mid-push and reseting some state
Stack.Insert(InMenu, InsertIndex);
CachedContentMap.Add(InMenu->GetContent(), InMenu);
// Dismiss menus after the insert point
if (Stack.Num() > InsertIndex + 1)
{
DismissFrom(Stack[InsertIndex + 1]);
// tidy the stack data now (it will happen via callbacks from the dismissed menus but that might be delayed)
for (int32 StackIndex = Stack.Num() - 1; StackIndex > InsertIndex; --StackIndex)
{
CachedContentMap.Remove(Stack[StackIndex]->GetContent());
Stack.RemoveAt(StackIndex);
}
}
// When a new menu is pushed, if we are not already in responsive mode for Slate UI, enter it now
// to ensure the menu is responsive in low FPS situations
if (!ThrottleHandle.IsValid() && ShouldThrottle == EShouldThrottle::Yes)
{
ThrottleHandle = FSlateThrottleManager::Get().EnterResponsiveMode();
}
}
FPopupMethodReply FMenuStack::QueryPopupMethod(const FWidgetPath& PathToQuery)
{
for (int32 WidgetIndex = PathToQuery.Widgets.Num() - 1; WidgetIndex >= 0; --WidgetIndex)
{
FPopupMethodReply PopupMethod = PathToQuery.Widgets[WidgetIndex].Widget->OnQueryPopupMethod();
if (PopupMethod.IsEventHandled())
{
return PopupMethod;
}
}
return FPopupMethodReply::UseMethod(EPopupMethod::CreateNewWindow);
}
void FMenuStack::DismissFrom(const TSharedPtr<IMenu>& InFromMenu)
{
int32 Index = Stack.IndexOfByKey(InFromMenu);
if (Index != INDEX_NONE)
{
DismissInternal(Index);
}
}
void FMenuStack::DismissAll()
{
const int32 TopLevel = 0;
DismissInternal(TopLevel);
}
void FMenuStack::DismissInternal(int32 FirstStackIndexToRemove)
{
// Dismiss the stack in reverse order so we destroy children before parents (causes focusing issues if done the other way around)
for ( int32 StackIndex = Stack.Num() - 1; StackIndex >= FirstStackIndexToRemove; --StackIndex )
{
if ( Stack.IsValidIndex(StackIndex) )
{
Stack[StackIndex]->Dismiss();
}
}
}
void FMenuStack::SetHostPath(const FWidgetPath& InOwnerPath)
{
if (bHostWindowGuard)
{
return;
}
if ( HostPopupLayer.IsValid() )
{
if ( !InOwnerPath.ContainsWidget(HostPopupLayer->GetHost()) )
{
HostPopupLayer->Remove();
HostPopupLayer.Reset();
HostWindowPopupPanel.Reset();
}
}
HostWindow = InOwnerPath.IsValid() ? InOwnerPath.GetWindow() : TSharedPtr<SWindow>();
if ( HostWindow.IsValid() && !HostWindowPopupPanel.IsValid() )
{
TSharedRef<SMenuPanel> NewHostWindowPopupPanel = SNew(SMenuPanel);
for ( int i = InOwnerPath.Widgets.Num() - 1; i >= 0; i-- )
{
const TSharedRef<SWidget>& HostWidget = InOwnerPath.Widgets[i].Widget;
HostPopupLayer = HostWidget->OnVisualizePopup(NewHostWindowPopupPanel);
if ( HostPopupLayer.IsValid() )
{
HostWindowPopupPanel = NewHostWindowPopupPanel;
break;
}
}
}
}
void FMenuStack::OnMenuDestroyed(TSharedRef<IMenu> InMenu)
{
int32 Index = Stack.IndexOfByKey(InMenu);
if (Index != INDEX_NONE)
{
// Dismiss menus below this one
for (int32 StackIndex = Stack.Num() - 1; StackIndex > Index; --StackIndex)
{
Stack[StackIndex]->Dismiss(); // this will cause OnMenuDestroyed() to re-enter
}
// Clean up the stack and content map arrays
for (int32 StackIndex = Stack.Num() - 1; StackIndex >= Index; --StackIndex)
{
CachedContentMap.Remove(Stack[StackIndex]->GetContent());
Stack.RemoveAt(StackIndex);
}
// Leave responsive mode once the last menu closes
if (Stack.Num() == 0)
{
if (ThrottleHandle.IsValid())
{
FSlateThrottleManager::Get().LeaveResponsiveMode(ThrottleHandle);
}
SetHostPath(FWidgetPath());
}
}
}
void FMenuStack::OnMenuContentLostFocus(const FWidgetPath& InFocussedPath)
{
// In UseCurrentWindow mode we must look for focus moving from menus
// Window activation messages will make menus collapse when in CreateNewWindow mode
// However, we cannot rely on window activation messages because they might not be generated on Mac.
// So, always do this focus/collapse code, even in CreateNewWindow mode.
if (HasMenus() && !PendingNewMenu.IsValid())
{
// If focus is switching determine which of our menus it is in, if any
TSharedPtr<IMenu> FocussedMenu = FindMenuInWidgetPath(InFocussedPath);
if (FocussedMenu.IsValid())
{
// dismiss menus below FocussedMenu
int32 FocussedIndex = Stack.IndexOfByKey(FocussedMenu);
check(FocussedIndex != INDEX_NONE);
for (int32 DismissIndex = FocussedIndex + 1; DismissIndex < Stack.Num(); DismissIndex++)
{
if (Stack[DismissIndex]->IsCollapsedByParent())
{
DismissFrom(Stack[DismissIndex]);
break;
}
}
}
else
{
// Focus has moved outside all menus - collapse the stack
DismissAll();
}
}
}
TSharedRef<SWidget> FMenuStack::WrapContent(TSharedRef<SWidget> InContent, FOptionalSize OptionalMinWidth, FOptionalSize OptionalMinHeight)
{
// Wrap menu content in a box that limits its maximum height
// and in a SMenuContentWrapper that handles key presses and focus changes.
return SNew(SMenuContentWrapper)
.OnKeyDown_Static(&OnMenuKeyDown)
.OnMenuLostFocus_Raw(this, &FMenuStack::OnMenuContentLostFocus)
.OptionalMinMenuWidth(OptionalMinWidth)
.OptionalMinMenuHeight(OptionalMinHeight)
.MenuContent()
[
InContent
];
}
TSharedPtr<IMenu> FMenuStack::FindMenuInWidgetPath(const FWidgetPath& PathToQuery) const
{
for (int32 PathIndex = PathToQuery.Widgets.Num() - 1; PathIndex >= 0; --PathIndex)
{
TSharedPtr<const SWidget> Widget = PathToQuery.Widgets[PathIndex].Widget;
const TSharedPtr<FMenuBase>* FoundMenu = CachedContentMap.Find(Widget);
if (FoundMenu != nullptr)
{
return *FoundMenu;
}
}
return TSharedPtr<IMenu>();
}
void FMenuStack::OnWindowDestroyed(TSharedRef<SWindow> InWindow)
{
if (HostWindow == InWindow)
{
// If the host window is destroyed, collapse the whole stack and reset all state
Stack.Empty();
CachedContentMap.Empty();
SetHostPath(FWidgetPath());
}
else
{
// A window was requested to be destroyed, so make sure it's not in the menu stack to avoid it
// becoming a parent to a freshly-created window!
TSharedPtr<IMenu> Menu = FindMenuFromWindow(InWindow);
if (Menu.IsValid())
{
OnMenuDestroyed(Menu.ToSharedRef());
}
}
}
void FMenuStack::OnWindowActivated( TSharedRef<SWindow> ActivatedWindow )
{
if (ActivatedWindow != PendingNewWindow && HasMenus())
{
TWeakPtr<IMenu> ActivatedMenu = FindMenuFromWindow(ActivatedWindow);
if (ActivatedMenu.IsValid())
{
// Dismiss menus below ActivatedMenu
int32 ActivatedIndex = Stack.IndexOfByKey(ActivatedMenu);
check(ActivatedIndex != INDEX_NONE);
for (int32 DismissIndex = ActivatedIndex + 1; DismissIndex < Stack.Num(); DismissIndex++)
{
if (Stack[DismissIndex]->IsCollapsedByParent())
{
DismissFrom(Stack[DismissIndex]);
break;
}
}
}
else
{
// Activated a window that isn't a menu - collapse the stack
DismissAll();
}
}
}
TSharedPtr<IMenu> FMenuStack::FindMenuFromWindow(TSharedRef<SWindow> InWindow) const
{
const TSharedPtr<FMenuBase>* FoundMenu = Stack.FindByPredicate([InWindow](TSharedPtr<FMenuBase> Menu) { return Menu->GetOwnedWindow() == InWindow; });
if (FoundMenu != nullptr)
{
return *FoundMenu;
}
return TSharedPtr<IMenu>();
}
FSlateRect FMenuStack::GetToolTipForceFieldRect(TSharedRef<IMenu> InMenu, const FWidgetPath& PathContainingMenu) const
{
FSlateRect ForceFieldRect(0, 0, 0, 0);
int32 StackLevel = Stack.IndexOfByKey(InMenu);
if (StackLevel != INDEX_NONE)
{
for (int32 StackLevelIndex = StackLevel + 1; StackLevelIndex < Stack.Num(); ++StackLevelIndex)
{
TSharedPtr<SWidget> MenuContent = Stack[StackLevelIndex]->GetContent();
if (MenuContent.IsValid())
{
FWidgetPath WidgetPath = PathContainingMenu.GetPathDownTo(MenuContent.ToSharedRef());
if (!WidgetPath.IsValid())
{
FSlateApplication::Get().GeneratePathToWidgetChecked(MenuContent.ToSharedRef(), WidgetPath);
}
if (WidgetPath.IsValid())
{
const FGeometry& ContentGeometry = WidgetPath.Widgets.Last().Geometry;
ForceFieldRect = ForceFieldRect.Expand(ContentGeometry.GetLayoutBoundingRect());
}
}
}
}
return ForceFieldRect;
}
bool FMenuStack::HasMenus() const
{
return Stack.Num() > 0;
}
bool FMenuStack::HasOpenSubMenus(TSharedPtr<IMenu> InMenu) const
{
int32 StackIndex = Stack.IndexOfByKey(InMenu);
return StackIndex != INDEX_NONE && StackIndex < Stack.Num() - 1;
}
TSharedPtr<SWindow> FMenuStack::GetHostWindow() const
{
return HostWindow;
}
#undef LOCTEXT_NAMESPACE
| 34.770492 | 359 | 0.768324 | [
"geometry",
"object",
"transform"
] |
ecd3286bcb9a35650ec621cee3183ae9796acb3f | 1,117 | cc | C++ | sensors/beam_pattern_HLA.cc | fraclipe/UnderSeaModelingLibrary | 52ef9dd03c7cbe548749e4527190afe7668ff4e7 | [
"BSD-2-Clause"
] | 1 | 2021-02-07T14:48:22.000Z | 2021-02-07T14:48:22.000Z | sensors/beam_pattern_HLA.cc | Wolframy-NUDT/UnderSeaModelingLibrary | 43365639b435841e1bf2297cf1ac575b8cf91932 | [
"BSD-2-Clause"
] | null | null | null | sensors/beam_pattern_HLA.cc | Wolframy-NUDT/UnderSeaModelingLibrary | 43365639b435841e1bf2297cf1ac575b8cf91932 | [
"BSD-2-Clause"
] | null | null | null | /**
* @file beam_pattern_HLA.cc
*/
#include <usml/sensors/beam_pattern_HLA.h>
using namespace usml::sensors ;
/**
* Constructor
*/
beam_pattern_HLA::beam_pattern_HLA(
double sound_speed,
double spacing,
size_t elements,
double steering_angle )
: beam_pattern_line( sound_speed, spacing,
elements, steering_angle,
beam_pattern_line::HORIZONTAL )
{
_beamID = beam_pattern_model::HLA ;
}
/**
* Destructor
*/
beam_pattern_HLA::~beam_pattern_HLA()
{
}
/**
* Calculates the beam level in de, az, and frequency
*/
void beam_pattern_HLA::beam_level(
double de, double az,
orientation& orient,
const vector<double>& frequencies,
vector<double>* level )
{
if( orient.heading() != _orient_HLA.heading() ||
orient.pitch() != _orient_HLA.pitch() ||
orient.roll() != _orient_HLA.roll() )
{
_orient_HLA.update_orientation(
orient.heading(), -orient.pitch(), orient.roll() ) ;
}
beam_pattern_line::beam_level( de, az, _orient_HLA, frequencies, level ) ;
}
| 21.901961 | 78 | 0.623993 | [
"vector"
] |
ecd9c211270f1dc976d8d85c44bfea10178e8d92 | 14,495 | cpp | C++ | csv2stats/csv2stats.cpp | rsuchecki/biokanga | ef0fa1cf58fb2903ae18d14e5b0f84de7b7e744e | [
"MIT"
] | null | null | null | csv2stats/csv2stats.cpp | rsuchecki/biokanga | ef0fa1cf58fb2903ae18d14e5b0f84de7b7e744e | [
"MIT"
] | null | null | null | csv2stats/csv2stats.cpp | rsuchecki/biokanga | ef0fa1cf58fb2903ae18d14e5b0f84de7b7e744e | [
"MIT"
] | null | null | null | // csv2stats.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "../libbiokanga/commhdrs.h"
const char *cpszProgVer = "1.0.0"; // increment with each release
const int cDfltMinLengthRange = 4; // accept sequence lengths from this min length up
const int cMaxLengthRange = 500000000; // max sequence length accepted
int
Process(bool bSkipFirst, // true if first line contains header and should be skipped
int MinLength, // core elements must be of at least this length
int MaxLength, // and no longer than this length
char *pszInLociFile, // CSV file containing elements
char *pszInSeqFile, // file containing genome assembly sequences
char *pszRsltsFile); // file to write results into
CStopWatch gStopWatch;
CDiagnostics gDiagnostics; // for writing diagnostics messages to log file
char gszProcName[_MAX_FNAME]; // process name
#ifdef _WIN32
int _tmain(int argc, char* argv[])
{
// determine my process name
_splitpath(argv[0],NULL,NULL,gszProcName,NULL);
#else
int
main(int argc, const char** argv)
{
// determine my process name
CUtility::splitpath((char *)argv[0],NULL,gszProcName);
#endif
int iScreenLogLevel; // level of screen diagnostics
int iFileLogLevel; // level of file diagnostics
char szLogFile[_MAX_PATH]; // write diagnostics to this file
int Rslt;
bool bSkipFirst; // true if first line contains header and should be skipped
int iMinLength; // core elements must be of at least this length
int iMaxLength; // and no longer than this length
char szInLociFile[_MAX_PATH]; // input element loci from this file
char szInSeqFile[_MAX_PATH]; // input bioseq file containing assembly
char szRsltsFile[_MAX_PATH]; // output stats to this file
// command line args
struct arg_lit *help = arg_lit0("hH","help", "print this help and exit");
struct arg_lit *version = arg_lit0("v","version,ver", "print version information and exit");
struct arg_int *FileLogLevel=arg_int0("f", "FileLogLevel", "<int>","Level of diagnostics written to logfile 0=fatal,1=errors,2=info,3=diagnostics,4=debug");
struct arg_int *ScreenLogLevel=arg_int0("S", "ScreenLogLevel", "<int>","Level of diagnostics written to logfile 0=fatal,1=errors,2=info,3=diagnostics,4=debug");
struct arg_file *LogFile = arg_file0("F","log","<file>", "diagnostics log file");
struct arg_file *InLociFile = arg_file1("i","inloci","<file>", "element loci CSV file");
struct arg_file *InSeqFile = arg_file1("I","assembly","<file>", "genome assembly bioseq file");
struct arg_file *RsltsFile = arg_file1("o","output","<file>", "output file");
struct arg_lit *SkipFirst = arg_lit0("x","skipfirst", "skip first line of CSV - header line");
struct arg_int *MinLength = arg_int0("l","minlength","<int>", "minimum element length (default 10)");
struct arg_int *MaxLength = arg_int0("L","maxlength","<int>", "maximum element length (default 1000000000)");
struct arg_end *end = arg_end(20);
void *argtable[] = {help,version,FileLogLevel,ScreenLogLevel,LogFile,
InLociFile,InSeqFile,RsltsFile,SkipFirst,MinLength,MaxLength,
end};
char **pAllArgs;
int argerrors;
argerrors = CUtility::arg_parsefromfile(argc,(char **)argv,&pAllArgs);
if(argerrors >= 0)
argerrors = arg_parse(argerrors,pAllArgs,argtable);
/* special case: '--help' takes precedence over error reporting */
if (help->count > 0)
{
printf("\n%s csv2stats, Version %s\nOptions ---\n", gszProcName,cpszProgVer);
arg_print_syntax(stdout,argtable,"\n");
arg_print_glossary(stdout,argtable," %-25s %s\n");
printf("\nNote: Parameters can be entered into a parameter file, one parameter per line.");
printf("\n To invoke this parameter file then precede its name with '@'");
printf("\n e.g. %s @myparams.txt\n\n",gszProcName);
exit(1);
}
/* special case: '--version' takes precedence error reporting */
if (version->count > 0)
{
printf("\n%s Version %s\n",gszProcName,cpszProgVer);
exit(1);
}
if (!argerrors)
{
if(FileLogLevel->count && !LogFile->count)
{
printf("\nError: FileLogLevel '-f%d' specified but no logfile '-F<logfile>'",FileLogLevel->ival[0]);
exit(1);
}
iScreenLogLevel = iFileLogLevel = FileLogLevel->count ? FileLogLevel->ival[0] : eDLInfo;
if(iFileLogLevel < eDLNone || iFileLogLevel > eDLDebug)
{
printf("\nError: FileLogLevel '-l%d' specified outside of range %d..%d",iFileLogLevel,eDLNone,eDLDebug);
exit(1);
}
if(LogFile->count)
{
strncpy(szLogFile,LogFile->filename[0],_MAX_PATH);
szLogFile[_MAX_PATH-1] = '\0';
}
else
{
iFileLogLevel = eDLNone;
szLogFile[0] = '\0';
}
bSkipFirst = SkipFirst->count ? true : false;
iMinLength = MinLength->count ? MinLength->ival[0] : cDfltMinLengthRange;
if(iMinLength < 1 || iMinLength > cMaxLengthRange)
{
printf("Error: Mininum element length '-l%d' is not in range 1..%d",iMinLength,cMaxLengthRange);
exit(1);
}
iMaxLength = MaxLength->count ? MaxLength->ival[0] : cMaxLengthRange;
if(iMaxLength < iMinLength || iMaxLength > cMaxLengthRange)
{
printf("Error: Maximum element length '-L%d' is not in range %d..%d",iMaxLength,iMinLength,cMaxLengthRange);
exit(1);
}
strncpy(szInLociFile,InLociFile->filename[0],_MAX_PATH);
szInLociFile[_MAX_PATH-1] = '\0';
strncpy(szInSeqFile,InSeqFile->filename[0],_MAX_PATH);
szInSeqFile[_MAX_PATH-1] = '\0';
strncpy(szRsltsFile,RsltsFile->filename[0],_MAX_PATH);
szRsltsFile[_MAX_PATH-1] = '\0';
// now that command parameters have been parsed then initialise diagnostics log system
if(!gDiagnostics.Open(szLogFile,(etDiagLevel)iScreenLogLevel,(etDiagLevel)iFileLogLevel,true))
{
printf("\nError: Unable to start diagnostics subsystem.");
if(szLogFile[0] != '\0')
printf(" Most likely cause is that logfile '%s' can't be opened/created",szLogFile);
exit(1);
}
gDiagnostics.DiagOut(eDLInfo,gszProcName,"Version: %s Processing parameters:",cpszProgVer);
gDiagnostics.DiagOutMsgOnly(eDLInfo,"Input CSV element loci file: '%s'",szInLociFile);
gDiagnostics.DiagOutMsgOnly(eDLInfo,"Input bioseq genome assembly file: '%s'",szInSeqFile);
gDiagnostics.DiagOutMsgOnly(eDLInfo,"Output to file: '%s'",szRsltsFile);
gDiagnostics.DiagOutMsgOnly(eDLInfo,"First line contains header: %s",bSkipFirst ? "yes" : "no");
gDiagnostics.DiagOutMsgOnly(eDLInfo,"Minimum element length: %d",iMinLength);
gDiagnostics.DiagOutMsgOnly(eDLInfo,"Maximum element length: %d",iMaxLength);
#ifdef _WIN32
SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS);
#endif
// processing here...
Rslt = Process(bSkipFirst,iMinLength,iMaxLength,szInLociFile,szInSeqFile,szRsltsFile);
gStopWatch.Stop();
Rslt = Rslt >=0 ? 0 : 1;
gDiagnostics.DiagOut(eDLInfo,gszProcName,"Exit code: %d Total processing time: %s",Rslt,gStopWatch.Read());
exit(Rslt);
}
else
{
printf("\n%s csv2stats, Version %s\n",gszProcName,cpszProgVer);
arg_print_errors(stdout,end,gszProcName);
arg_print_syntax(stdout,argtable,"\nUse '-h' to view option and parameter usage\n");
exit(1);
}
}
typedef struct TAG_sBaseCompStats {
int TotBases; // total number of bases (canonical and non-canonical)
int CBases; // total number of all canonical bases
int NBases; // total of all non-canonical bases
int MonoCnts[4]; // raw counts for a,c,g,t
int DiCnts[4*4]; // dinucleotide counts indexed by aa,ac,ag,at,ca,...,ta,tc,tg,tt
int TriCnts[4*4*4]; // trinucleotide counts indexed by aaa,aac,aag,aat,tta,ttc,ttg,ttt
} tsBaseCompStats;
char *
Idx2Seq(int NMer, // number of bases encoded by EncodedBases (1..3)
int EncodedBases) // bases encoded as index into BaseCnts[]...TrinucCnts[]
{
static char szBases[80];
char *pBase;
int Base;
int Idx;
pBase = &szBases[NMer-1];
for(Idx = 0; Idx < NMer; Idx++,pBase--)
{
Base = EncodedBases & 0x03;
EncodedBases >>= 2;
switch(Base) {
case eBaseA:
*pBase = 'A';
break;
case eBaseC:
*pBase = 'C';
break;
case eBaseG:
*pBase = 'G';
break;
case eBaseT:
*pBase = 'T';
break;
}
}
szBases[NMer] = '\0';
return(szBases);
}
int
ReportStats(int hFile,tsBaseCompStats *pStats)
{
char szBuff[10000];
int Len;
int Idx;
Len = sprintf(szBuff,"0,\"TotalBases\",%d\n",pStats->TotBases);
Len += sprintf(&szBuff[Len],"1,\"TotalCanonical\",%d\n",pStats->CBases);
Len += sprintf(&szBuff[Len],"2,\"TotalNoncanonical\",%d\n",pStats->NBases);
for(Idx = 0; Idx < 4; Idx++)
Len += sprintf(&szBuff[Len],"%d,\"%s\",%d\n",3+Idx,Idx2Seq(1,Idx),pStats->MonoCnts[Idx]);
for(Idx = 0; Idx < (4*4); Idx++)
Len += sprintf(&szBuff[Len],"%d,\"%s\",%d\n",7+Idx,Idx2Seq(2,Idx),pStats->DiCnts[Idx]);
for(Idx = 0; Idx < (4*4*4); Idx++)
Len += sprintf(&szBuff[Len],"%d,\"%s\",%d\n",23+Idx,Idx2Seq(3,Idx),pStats->TriCnts[Idx]);
return(write(hFile,szBuff,Len));
}
int
GenStats(int SeqLen,etSeqBase *pSeq,tsBaseCompStats *pStats)
{
etSeqBase Base;
int DiIdx;
int TriIdx;
int DiCnts;
int TriCnts;
int Cnt;
DiIdx = TriIdx = 0;
DiCnts = TriCnts = 0;
for(Cnt = 0; Cnt < SeqLen; Cnt++)
{
pStats->TotBases += 1;
Base = *pSeq++ & ~cRptMskFlg;
switch(Base) {
case eBaseA:
case eBaseC:
case eBaseG:
case eBaseT:
pStats->MonoCnts[(int)Base] += 1;
pStats->CBases += 1;
break;
default:
pStats->NBases += 1;
DiCnts = TriCnts = 0;
continue;
}
DiIdx <<= 2;
DiIdx &= 0x0f;
DiIdx |= (int)Base;
if(DiCnts++ >= 1)
pStats->DiCnts[DiIdx] += 1;
TriIdx <<= 2;
TriIdx &= 0x03f;
TriIdx |= (int)Base;
if(TriCnts++ >= 2)
pStats->TriCnts[TriIdx] += 1;
}
return(SeqLen);
}
int
Process(bool bSkipFirst, // true if first line contains header and should be skipped
int MinLength, // core elements must be of at least this length
int MaxLength, // and no longer than this length
char *pszInLociFile, // CSV file containing elements
char *pszInSeqFile, // file containing genome assembly sequences
char *pszRsltsFile) // file to write fasta into
{
int NumFields;
int Rslt;
int SrcID;
char *pszChrom;
int ChromID;
char *pszElType;
char *pszRefSpecies;
int StartLoci;
int EndLoci;
int Len;
int ReqAllocLen;
int AllocSeqBuffLen = 0;
int AllocLineBuffLen = 0;
int NumAccepted;
int NumProcessed;
int NumUnderLen;
int NumOverLen;
tsBaseCompStats CompStats;
etSeqBase *pElSeqBuff = NULL;
int hRsltFile = -1;
CBioSeqFile *pBioseq = NULL;
CCSVFile *pCSV = new CCSVFile;
if(pCSV == NULL)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to instantiate CCSVfile");
return(eBSFerrObj);
}
if((Rslt=pCSV->Open(pszInLociFile))!=eBSFSuccess)
{
while(pCSV->NumErrMsgs())
gDiagnostics.DiagOut(eDLFatal,gszProcName,pCSV->GetErrMsg());
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to open file: %s",pszInLociFile);
delete pCSV;
return(Rslt);
}
if((pBioseq = new CBioSeqFile) == NULL)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to instantiate CBioSeqFile object");
delete pCSV;
return(eBSFerrObj);
}
if((Rslt = pBioseq->Open(pszInSeqFile))!=eBSFSuccess)
{
while(pBioseq->NumErrMsgs())
gDiagnostics.DiagOut(eDLFatal,gszProcName,pBioseq->GetErrMsg());
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to open assembly sequence file '%s'",pszInSeqFile);
delete pCSV;
delete pBioseq;
return(Rslt);
}
#ifdef _WIN32
if((hRsltFile = open(pszRsltsFile, _O_RDWR | _O_BINARY | _O_SEQUENTIAL | _O_CREAT | _O_TRUNC, _S_IREAD | _S_IWRITE ))==-1)
#else
if((hRsltFile = open(pszRsltsFile, O_RDWR | O_CREAT,S_IREAD | S_IWRITE))==-1)
#endif
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to create %s - %s",pszRsltsFile,strerror(errno));
delete pCSV;
delete pBioseq;
return(eBSFerrCreateFile);
}
gDiagnostics.DiagOut(eDLInfo,gszProcName,"Output file created/truncated: '%s'",pszRsltsFile);
memset(&CompStats,0,sizeof(CompStats));
NumUnderLen = 0;
NumOverLen = 0;
NumAccepted = 0;
NumProcessed = 0;
while((Rslt=pCSV->NextLine()) > 0) // onto next line containing fields
{
NumFields = pCSV->GetCurFields();
if(NumFields < 7)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Expected 7+ fields in '%s', GetCurFields() returned '%d'",pszInLociFile,NumFields);
Rslt = eBSFerrFieldCnt;
break;
}
if(bSkipFirst || (!NumProcessed && pCSV->IsLikelyHeaderLine()))
{
bSkipFirst = false;
continue;
}
NumProcessed += 1;
pCSV->GetInt(7,&Len);
if(Len < MinLength)
{
NumUnderLen += 1;
continue;
}
if(Len > MaxLength)
{
NumOverLen += 1;
continue;
}
pCSV->GetInt(1,&SrcID);
pCSV->GetText(2,&pszElType);
pCSV->GetText(3,&pszRefSpecies);
pCSV->GetText(4,&pszChrom);
pCSV->GetInt(5,&StartLoci);
pCSV->GetInt(6,&EndLoci);
ReqAllocLen = Len;
if(pElSeqBuff == NULL || ReqAllocLen > AllocSeqBuffLen)
{
if(pElSeqBuff != NULL)
delete pElSeqBuff;
ReqAllocLen += 10000; // a little extra to reduce number of potential subsequent reallocations
if((pElSeqBuff = (etSeqBase *)new unsigned char[ReqAllocLen])==NULL)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to allocate %s bytes as a sequence buffer",ReqAllocLen);
Rslt = eBSFerrMem;
break;
}
AllocSeqBuffLen = ReqAllocLen;
}
// now get the sequence
if((Rslt= ChromID = pBioseq->LocateEntryIDbyName(pszChrom))<=0)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to locate chrom '%s' in assembly file '%s'",pszChrom,pszInSeqFile);
break;
}
if((Rslt=pBioseq->GetData(ChromID,eSeqBaseType,StartLoci,pElSeqBuff,Len)) != Len)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Loading sequence failed from chrom: %s loci %d len: %d file: '%s'",pszChrom,StartLoci,Len,pszInSeqFile);
break;
}
GenStats(Len,pElSeqBuff,&CompStats);
NumAccepted += 1;
}
if(Rslt >= eBSFSuccess)
{
gDiagnostics.DiagOut(eDLInfo,gszProcName,"Elements accepted: %d, Processed: %d, UnderLen: %d, OverLen: %d",
NumAccepted,NumProcessed,NumUnderLen,NumOverLen);
ReportStats(hRsltFile,&CompStats);
}
close(hRsltFile);
delete pCSV;
delete pBioseq;
if(pElSeqBuff != NULL)
delete pElSeqBuff;
return(Rslt < 0 ? NumAccepted : Rslt);
}
| 30.709746 | 161 | 0.681476 | [
"object"
] |
ece4d6ccae0732031b84f224e939ddad5e58845a | 14,132 | cc | C++ | mindspore/lite/tools/optimizer/graph/transpose_strategy.cc | ZLkanyo009/mindspore | 0a6ed86bb443ed233504fa7eee931a24637d50bb | [
"Apache-2.0"
] | null | null | null | mindspore/lite/tools/optimizer/graph/transpose_strategy.cc | ZLkanyo009/mindspore | 0a6ed86bb443ed233504fa7eee931a24637d50bb | [
"Apache-2.0"
] | null | null | null | mindspore/lite/tools/optimizer/graph/transpose_strategy.cc | ZLkanyo009/mindspore | 0a6ed86bb443ed233504fa7eee931a24637d50bb | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2021 Huawei Technologies Co., Ltd
*
* 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 "tools/optimizer/graph/transpose_strategy.h"
#include <algorithm>
#include <memory>
#include <vector>
#include <string>
#include <utility>
#include "ops/crop.h"
#include "ops/fusion/activation.h"
#include "ops/fusion/slice_fusion.h"
#include "ops/op_utils.h"
#include "ops/strided_slice.h"
#include "tools/converter/quant_param_holder.h"
namespace mindspore {
namespace opt {
namespace {
constexpr size_t kFirstInput = 1;
constexpr size_t kTransposePerm = 2;
constexpr size_t kOnnxStridedSlice = 6;
const std::vector<int> NH2NC = {0, 3, 1, 2};
const std::vector<int> NC2NH = {0, 2, 3, 1};
STATUS GetPostNodes(const FuncGraphPtr &func_graph, const CNodePtr &cnode, std::vector<AnfNodePtr> *out_nodes) {
auto manager = func_graph->manager();
if (manager == nullptr) {
manager = Manage(func_graph, true);
}
if (manager == nullptr) {
MS_LOG(ERROR) << "manager is nullptr.";
return lite::RET_ERROR;
}
auto node_users = manager->node_users()[cnode];
if (node_users.empty()) {
MS_LOG(ERROR) << "cnode is isolated.";
return lite::RET_ERROR;
}
std::transform(node_users.begin(), node_users.end(), std::back_inserter(*out_nodes),
[](const std::pair<AnfNodePtr, int> &node_user) { return node_user.first; });
return lite::RET_OK;
}
} // namespace
AnfNodePtr TransposeStrategy::TransposePairFuseWhenInsert(const FuncGraphPtr &func_graph, const CNodePtr &cnode,
const std::vector<int> &perm, bool before, size_t index) {
MS_ASSERT(func_graph != nullptr && cnode != nullptr);
AnfNodePtr trans_input_node = before ? cnode->input(index) : cnode;
// judge pair transpose after insert.
if (CheckPrimitiveType(trans_input_node, prim::kPrimTranspose)) {
std::vector<int> trans_perm;
auto input_cnode = trans_input_node->cast<CNodePtr>();
if (input_cnode == nullptr) {
MS_LOG(ERROR) << "input node is invalid.";
return nullptr;
}
if (GetTransposePerm(input_cnode->input(kTransposePerm), &trans_perm) != lite::RET_OK) {
MS_LOG(ERROR) << "transpose perm get failed.";
return nullptr;
}
if ((perm == NH2NC && trans_perm == NC2NH) || (perm == NC2NH && trans_perm == NH2NC)) {
return input_cnode->input(kFirstInput);
}
}
// insert depend on shape
return TransposeDependOnShape(func_graph, cnode, perm, before, index);
}
AnfNodePtr TransposeStrategy::TransposeDependOnShape(const FuncGraphPtr &func_graph, const CNodePtr &cnode,
const std::vector<int> &perm, bool before, size_t index) {
MS_ASSERT(func_graph != nullptr && cnode != nullptr);
AnfNodePtr trans_input_node = before ? cnode->input(index) : cnode;
auto status = TransposeInsertDependOnShape(func_graph, cnode, before, index);
if (status == lite::RET_ERROR) {
return nullptr;
} else if (status == lite::RET_NO_CHANGE) {
return before ? cnode->input(index) : cnode;
}
// insert tranpsoe
std::string trans_name =
before ? cnode->fullname_with_scope() + "_pre" + std::to_string(index - 1) : cnode->fullname_with_scope() + "_post";
auto trans_insert_node = GenTransposeNode(func_graph, trans_input_node, perm, trans_name);
auto quant_params_holder = std::make_shared<lite::QuantParamHolder>();
quant_params_holder->AddInputQuantParam(std::vector<schema::QuantParamT>(1));
quant_params_holder->AddOutputQuantParam(std::vector<schema::QuantParamT>(1));
auto trans_insert_prim = GetValueNode<PrimitivePtr>(trans_insert_node->input(0));
trans_insert_prim->AddAttr("quant_params", quant_params_holder);
return trans_insert_node;
}
bool TransposeStrategy::CanFusionIfInsert(const FuncGraphPtr &func_graph, const CNodePtr &cnode,
TransTypePair *trans_info, TransTypePair *trans_insert_info) {
MS_ASSERT(func_graph != nullptr && cnode != nullptr);
MS_ASSERT(pre_type != nullptr && post_type != nullptr);
size_t trans_count = 0;
std::vector<AnfNodePtr> in_nodes;
for (size_t i = 1; i < cnode->size(); ++i) {
if (utils::isa<CNodePtr>(cnode->input(i))) {
in_nodes.push_back(cnode->input(i));
}
}
if (!IsInOutCanFuison(func_graph, in_nodes, &trans_count, &trans_info->pre_)) {
return false;
}
std::vector<AnfNodePtr> out_nodes;
if (GetPostNodes(func_graph, cnode, &out_nodes) != lite::RET_OK) {
return false;
}
if (!IsInOutCanFuison(func_graph, out_nodes, &trans_count, &trans_info->post_)) {
return false;
}
if (trans_info->pre_ == trans_info->post_) {
return false;
}
auto total_node_count = in_nodes.size() + out_nodes.size();
bool can_insert = trans_count > total_node_count / 2;
if (CheckPrimitiveType(cnode, prim::kPrimActivation)) {
auto prim_act = GetValueNode<std::shared_ptr<ops::Activation>>(cnode->input(0));
MS_ASSERT(prim_act != nullptr);
if (prim_act->get_activation_type() == mindspore::ActivationType::LEAKY_RELU) {
can_insert = trans_count >= total_node_count / 2;
}
}
if (CheckPrimitiveType(cnode, prim::kPrimSplit) || CheckPrimitiveType(cnode, prim::kPrimQuantDTypeCast)) {
can_insert = trans_count >= total_node_count / 2;
}
if (!can_insert) {
return can_insert;
}
DecidePreAndPostTransType(trans_info, trans_insert_info);
return can_insert;
}
STATUS TransposeStrategy::ChangeOpAxis(const FuncGraphPtr &func_graph, const CNodePtr &cnode) {
MS_ASSERT(cnode != nullptr);
auto shape = node_infer_shape_.GetInputShape(cnode, 1);
if (shape.size() != 4) {
if (cnode->size() > 2) {
shape = node_infer_shape_.GetInputShape(cnode, 2);
if (shape.size() != 4 && !shape.empty()) {
return lite::RET_NOT_SUPPORT;
}
} else {
return lite::RET_NOT_SUPPORT;
}
}
auto axis_map = GetNC2NHAxisMap();
if (CheckPrimitiveType(cnode, prim::kPrimConcat) || CheckPrimitiveType(cnode, prim::kPrimSplit)) {
auto prim = GetValueNode<PrimitivePtr>(cnode->input(0));
if (prim->GetAttr(ops::kAxis) == nullptr) {
return lite::RET_NOT_SUPPORT;
}
auto axis = GetValue<int64_t>(prim->GetAttr(ops::kAxis));
auto new_axis = axis_map[axis < 0 ? axis + 4 : axis];
prim->AddAttr(ops::kAxis, MakeValue<int64_t>(new_axis));
}
if (CheckPrimitiveType(cnode, prim::kPrimCrop)) {
auto crop_prim = GetValueNode<std::shared_ptr<ops::Crop>>(cnode->input(0));
if (crop_prim == nullptr) {
return lite::RET_NULL_PTR;
}
auto axis = crop_prim->get_axis();
auto offsets = crop_prim->get_offsets();
auto new_axis = axis_map[axis < 0 ? axis + 4 : axis];
if (new_axis == 0) {
offsets = {offsets[0], offsets[2], offsets[3], offsets[1]};
} else if (new_axis == 3) {
offsets = {offsets[1], offsets[2], offsets[0]};
} else {
offsets.push_back(0);
}
crop_prim->set_offsets(offsets);
}
if (CheckPrimitiveType(cnode, prim::kPrimSliceFusion)) {
return ChangeOpSlice(func_graph, cnode);
}
if (CheckPrimitiveType(cnode, prim::kPrimStridedSlice)) {
return ChangeOpStrideSlice(func_graph, cnode);
}
return lite::RET_OK;
}
STATUS TransposeStrategy::TransposeInsertDependOnShape(const FuncGraphPtr &func_graph, const CNodePtr &cnode,
bool before, size_t index) {
MS_ASSERT(func_graph != nullptr && cnode != nullptr);
auto manager = func_graph->manager();
if (manager == nullptr) {
manager = Manage(func_graph, true);
}
if (manager == nullptr) {
MS_LOG(ERROR) << "manager is nullptr.";
return lite::RET_ERROR;
}
auto node_users = manager->node_users()[cnode];
if (node_users.empty()) {
MS_LOG(ERROR) << "cnode is isolated.";
return lite::RET_ERROR;
}
if (!utils::isa<CNodePtr>(node_users.front().first)) {
return lite::RET_ERROR;
}
CNodePtr base_node = before ? cnode : node_users.front().first->cast<CNodePtr>();
size_t input_index = before ? index : node_users.front().second;
auto shape = node_infer_shape_.GetInputShape(base_node, input_index);
if (!shape.empty() && shape.size() != NH2NC.size()) {
return lite::RET_NO_CHANGE;
}
return lite::RET_OK;
}
bool TransposeStrategy::IsInOutCanFuison(const FuncGraphPtr &func_graph, const std::vector<AnfNodePtr> &nodes,
size_t *trans_count, FormatTransNodeType *trans_type) {
MS_ASSERT(func_graph != nullptr);
MS_ASSERT(trans_count != nullptr && trans_type != nullptr);
for (auto &node : nodes) {
if (CheckPrimitiveType(node, prim::kPrimTranspose)) {
FormatTransNodeType cur_type;
std::vector<int> perm;
auto cnode = node->cast<CNodePtr>();
if (cnode == nullptr) {
return false;
}
if (GetTransposePerm(cnode->input(kTransposePerm), &perm) != lite::RET_OK) {
return false;
}
if (perm == NH2NC) {
cur_type = kNHWC2NCHW;
} else if (perm == NC2NH) {
cur_type = kNCHW2NHWC;
} else {
return false;
}
if (*trans_type == kNONE) {
*trans_type = cur_type;
} else if (*trans_type != cur_type) {
return false;
}
*trans_count += 1;
}
}
return true;
}
void TransposeStrategy::DecidePreAndPostTransType(TransTypePair *trans_info, TransTypePair *trans_insert_info) {
if (trans_info->pre_ == trans_info->post_) {
return;
}
if (trans_info->pre_ != kNONE && trans_info->post_ != kNONE) {
trans_insert_info->pre_ = trans_info->pre_ == kNHWC2NCHW ? kNCHW2NHWC : kNHWC2NCHW;
trans_insert_info->post_ = trans_info->post_ == kNHWC2NCHW ? kNCHW2NHWC : kNHWC2NCHW;
} else if (trans_info->pre_ == kNONE) {
trans_insert_info->pre_ = trans_info->post_ == kNHWC2NCHW ? kNHWC2NCHW : kNCHW2NHWC;
trans_insert_info->post_ = trans_info->post_ == kNHWC2NCHW ? kNCHW2NHWC : kNHWC2NCHW;
} else {
trans_insert_info->pre_ = trans_info->pre_ == kNHWC2NCHW ? kNCHW2NHWC : kNHWC2NCHW;
trans_insert_info->post_ = trans_info->pre_ == kNHWC2NCHW ? kNHWC2NCHW : kNCHW2NHWC;
}
}
STATUS TransposeStrategy::ChangeOpSlice(const FuncGraphPtr &func_graph, const CNodePtr &cnode) {
MS_ASSERT(cnode != nullptr);
for (size_t i = 2; i < cnode->size(); ++i) {
if (utils::isa<CNodePtr>(cnode->input(i))) {
return lite::RET_NOT_SUPPORT;
}
}
auto shape = node_infer_shape_.GetInputShape(cnode, 2);
if (shape.empty()) {
return lite::RET_NOT_SUPPORT;
}
int element_num = shape.front();
auto prim = GetValueNode<std::shared_ptr<ops::SliceFusion>>(cnode->input(0));
std::vector<int> axes;
if (prim->GetAttr(ops::kAxes) == nullptr || prim->get_axes().empty()) {
for (int index = 0; index < element_num; ++index) {
axes.push_back(index);
}
} else {
auto origin_axes = prim->get_axes();
std::transform(origin_axes.begin(), origin_axes.end(), std::back_inserter(axes),
[](int64_t v) { return static_cast<int>(v); });
}
for (size_t i = 2; i < cnode->size(); ++i) {
TransformAttrByAxes(func_graph, cnode, i, axes);
}
auto tmp_axes = TransformOpAxesAttr(axes);
std::vector<int64_t> new_axes(tmp_axes.begin(), tmp_axes.end());
prim->set_axes(new_axes);
return lite::RET_OK;
}
STATUS TransposeStrategy::ChangeOpStrideSlice(const FuncGraphPtr &func_graph, const CNodePtr &cnode) {
if (cnode->size() != kOnnxStridedSlice) {
return lite::RET_NOT_SUPPORT;
}
for (size_t i = 2; i < cnode->size(); ++i) {
if (utils::isa<CNodePtr>(cnode->input(i))) {
return lite::RET_NOT_SUPPORT;
}
}
std::vector<int> axes = node_infer_shape_.GetIntVecInput(cnode, kOnnxStridedSlice - 2);
if (axes.empty()) {
MS_LOG(ERROR) << "strided slice input invalid.";
return lite::RET_ERROR;
}
for (size_t index = 2; index < cnode->size(); ++index) {
if (index == 4) {
continue;
}
TransformAttrByAxes(func_graph, cnode, index, axes);
}
auto cur_axes = TransformOpAxesAttr(axes);
auto param_node = BuildIntVecParameterNode(func_graph, cur_axes, cnode->input(4)->fullname_with_scope());
func_graph->manager()->Replace(cnode->input(4), param_node);
return lite::RET_OK;
}
void TransposeStrategy::TransformAttrByAxes(const FuncGraphPtr &func_graph, const CNodePtr &cnode, size_t input_index,
const std::vector<int> &axes) {
if (cnode == nullptr || input_index >= cnode->size() || axes.empty()) {
return;
}
auto axis_map = GetNC2NHAxisMap();
auto origin_input = node_infer_shape_.GetIntVecInput(cnode, input_index);
if (origin_input.size() != axes.size()) {
return;
}
std::vector<int> cur_input;
for (int dim = 0; dim < 4; ++dim) {
for (size_t index = 0; index < axes.size(); ++index) {
int nhwc_dim = axis_map[axes[index] < 0 ? axes[index] + 4 : axes[index]];
if (nhwc_dim == dim) {
cur_input.push_back(origin_input[index]);
}
}
}
auto param_node = BuildIntVecParameterNode(func_graph, cur_input, cnode->input(input_index)->fullname_with_scope());
func_graph->manager()->Replace(cnode->input(input_index), param_node);
}
std::vector<int> TransposeStrategy::TransformOpAxesAttr(const std::vector<int> &origin_axes) {
auto axis_map = GetNC2NHAxisMap();
std::vector<int> cur_axis;
for (size_t i = 0; i < origin_axes.size(); ++i) {
cur_axis.push_back(axis_map[origin_axes[i] < 0 ? origin_axes[i] + 4 : origin_axes[i]]);
}
std::sort(cur_axis.begin(), cur_axis.end());
return cur_axis;
}
} // namespace opt
} // namespace mindspore
| 38.717808 | 120 | 0.669049 | [
"shape",
"vector",
"transform"
] |
ece6012b5bec712737c1a5c92923f9b0ff95033e | 4,324 | hxx | C++ | main/drawinglayer/inc/drawinglayer/primitive3d/sdrextrudelathetools3d.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/drawinglayer/inc/drawinglayer/primitive3d/sdrextrudelathetools3d.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/drawinglayer/inc/drawinglayer/primitive3d/sdrextrudelathetools3d.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef INCLUDED_DRAWINGLAYER_PRIMITIVE3D_SDREXTRUDELATHETOOLS3D_HXX
#define INCLUDED_DRAWINGLAYER_PRIMITIVE3D_SDREXTRUDELATHETOOLS3D_HXX
#include <drawinglayer/drawinglayerdllapi.h>
#include <basegfx/polygon/b3dpolypolygon.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <vector>
//////////////////////////////////////////////////////////////////////////////
// predefines
namespace drawinglayer { namespace geometry {
class ViewInformation3D;
}}
//////////////////////////////////////////////////////////////////////////////
namespace drawinglayer
{
namespace primitive3d
{
/** SliceType3D definition */
enum SliceType3D
{
SLICETYPE3D_REGULAR, // normal geoemtry Slice3D
SLICETYPE3D_FRONTCAP, // front cap
SLICETYPE3D_BACKCAP // back cap
};
/// class to hold one Slice3D
class DRAWINGLAYER_DLLPUBLIC Slice3D
{
protected:
basegfx::B3DPolyPolygon maPolyPolygon;
SliceType3D maSliceType;
public:
Slice3D(
const basegfx::B2DPolyPolygon& rPolyPolygon,
const basegfx::B3DHomMatrix& aTransform,
SliceType3D aSliceType = SLICETYPE3D_REGULAR)
: maPolyPolygon(basegfx::tools::createB3DPolyPolygonFromB2DPolyPolygon(rPolyPolygon)),
maSliceType(aSliceType)
{
maPolyPolygon.transform(aTransform);
}
Slice3D(
const basegfx::B3DPolyPolygon& rPolyPolygon,
SliceType3D aSliceType = SLICETYPE3D_REGULAR)
: maPolyPolygon(rPolyPolygon),
maSliceType(aSliceType)
{
}
// data access
const basegfx::B3DPolyPolygon& getB3DPolyPolygon() const { return maPolyPolygon; }
SliceType3D getSliceType() const { return maSliceType; }
};
/// typedef for a group of Slice3Ds
typedef ::std::vector< Slice3D > Slice3DVector;
/// helpers for creation
void createLatheSlices(
Slice3DVector& rSliceVector,
const basegfx::B2DPolyPolygon& rSource,
double fBackScale,
double fDiagonal,
double fRotation,
sal_uInt32 nSteps,
bool bCharacterMode,
bool bCloseFront,
bool bCloseBack);
void createExtrudeSlices(
Slice3DVector& rSliceVector,
const basegfx::B2DPolyPolygon& rSource,
double fBackScale,
double fDiagonal,
double fDepth,
bool bCharacterMode,
bool bCloseFront,
bool bCloseBack);
/// helpers for geometry extraction
basegfx::B3DPolyPolygon extractHorizontalLinesFromSlice(const Slice3DVector& rSliceVector, bool bCloseHorLines);
basegfx::B3DPolyPolygon extractVerticalLinesFromSlice(const Slice3DVector& rSliceVector);
void extractPlanesFromSlice(
::std::vector< basegfx::B3DPolyPolygon >& rFill,
const Slice3DVector& rSliceVector,
bool bCreateNormals,
bool bSmoothHorizontalNormals,
bool bSmoothNormals,
bool bSmoothLids,
bool bClosed,
double fSmoothNormalsMix,
double fSmoothLidsMix,
bool bCreateTextureCoordinates,
const basegfx::B2DHomMatrix& rTexTransform);
void createReducedOutlines(
const geometry::ViewInformation3D& rViewInformation,
const basegfx::B3DHomMatrix& rObjectTransform,
const basegfx::B3DPolygon& rLoopA,
const basegfx::B3DPolygon& rLoopB,
basegfx::B3DPolyPolygon& rTarget);
} // end of namespace overlay
} // end of namespace drawinglayer
//////////////////////////////////////////////////////////////////////////////
#endif //_DRAWINGLAYER_PRIMITIVE3D_SDREXTRUDELATHETOOLS3D_HXX
// eof
| 30.666667 | 114 | 0.688483 | [
"geometry",
"vector",
"transform"
] |
ece7e7e78f21194540d66c988021144ecec7c17c | 2,111 | cpp | C++ | src/Common/Utilities/src/ThreadManager.cpp | hausdorff/BitFunnel | d15591de31853d60a1552c0631b37fb63a501421 | [
"MIT"
] | null | null | null | src/Common/Utilities/src/ThreadManager.cpp | hausdorff/BitFunnel | d15591de31853d60a1552c0631b37fb63a501421 | [
"MIT"
] | null | null | null | src/Common/Utilities/src/ThreadManager.cpp | hausdorff/BitFunnel | d15591de31853d60a1552c0631b37fb63a501421 | [
"MIT"
] | null | null | null | // The MIT License (MIT)
// Copyright (c) 2016, Microsoft
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The 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 <stddef.h>
#include "BitFunnel/Utilities/Factories.h"
#include "ThreadManager.h"
namespace BitFunnel
{
std::unique_ptr<IThreadManager> Factories::CreateThreadManager(
const std::vector<IThreadBase*>& threads)
{
return std::unique_ptr<IThreadManager>(new ThreadManager(threads));
}
ThreadManager::ThreadManager(const std::vector<IThreadBase*>& threads)
{
for (size_t i = 0 ; i < threads.size(); ++i)
{
m_threads.push_back(std::thread(ThreadEntryPoint, threads[i]));
}
}
ThreadManager::~ThreadManager()
{
// REVIEW: what should this do if threads are still running?
}
void ThreadManager::WaitForThreads()
{
for (auto& thread : m_threads)
{
thread.join();
}
}
void ThreadManager::ThreadEntryPoint(void* data)
{
IThreadBase* thread = static_cast<IThreadBase*>(data);
thread->EntryPoint();
}
}
| 30.594203 | 80 | 0.69351 | [
"vector"
] |
ecea696f0db19add18a7f7710654af237c366790 | 7,709 | cpp | C++ | SubtitleIO.cpp | matijalukic/subtitly | c7001fd6c70019c6ed745b8726035486bd645dd4 | [
"MIT"
] | null | null | null | SubtitleIO.cpp | matijalukic/subtitly | c7001fd6c70019c6ed745b8726035486bd645dd4 | [
"MIT"
] | null | null | null | SubtitleIO.cpp | matijalukic/subtitly | c7001fd6c70019c6ed745b8726035486bd645dd4 | [
"MIT"
] | null | null | null | #include "SubtitleIO.h"
double SubtitleIO::framesPerSecond = 25.;
SubtitleIO::SubtitleIO(string fileName) {
loadedSubtitle.open(fileName, ios_base::in | ios_base::out | ios_base::app);
if (!loadedSubtitle.is_open())
throw IOError();
}
SubtitleIO::~SubtitleIO() {
loadedSubtitle.close();
}
// pre nego sto otvorimo
void SubtitleIO::premakeSubtitles(Subtitles& tempSubtitles) {
tempSubtitles.clearTitles();
if (!loadedSubtitle.is_open())
throw IOError();
}
// Pravimo
// pravljenje i parsiranje tilova
void SubtitleIO::makeSubtitle(Subtitles& tempSubtitles) {
premakeSubtitles(tempSubtitles);
// sve dok nije kraj fajla
while (!loadedSubtitle.eof()) {
// Procitamo novi title
Subtitle * newSubtitle = readOneSubtitle();
if (newSubtitle)
tempSubtitles.addBack(*newSubtitle);
else
failedReads++;
}
}
// Funkcija MicroDVD sa streamom
ostream& makeMPlayerFile(ostream& outputStream, Subtitle& titleToConvert, double& prevLastTime){
// Dohvatanje i update
double timeAppearance = titleToConvert.getTimeOfAppearance().getSeconds() - prevLastTime;
double timeLasts = titleToConvert.getTimeOfRemoval().getSeconds() - titleToConvert.getTimeOfAppearance().getSeconds() ;
prevLastTime = titleToConvert.getTimeOfRemoval().getSeconds();
// dodajemo
outputStream << timeAppearance << " " << timeLasts << endl;
outputStream << titleToConvert.getString() << endl;
return outputStream;
}
// MPlayer sa streamom
ostream& makeMicroDVDFile(ostream& outputStream, Subtitle& titleToConvert){
int fps = SubtitleIO::framesPerSecond;
int frameAppearance = (int)(fps * titleToConvert.getTimeOfAppearance().getSeconds() + 0.5);
int frameRemoval = (int)(fps * titleToConvert.getTimeOfRemoval().getSeconds() + 0.5);
outputStream << "{" << frameAppearance << "}";
outputStream << "{" << frameRemoval<< "}";
// dohvatamo i preuredjujemo u format za fajl
string titleText = titleToConvert.getString();
replace(titleText.begin(), titleText.end(), '\n', '|');
outputStream << titleText << endl;
return outputStream;
}
// Dohvatamo broj neprocitanih
int inline SubtitleIO::getFailedReads() const {
return failedReads;
}
// Za cuvanje titlova
void SubtitleIO::saveTitle(string fileName, const Subtitles& subtitlesToSave, SubtitleType type) throw (IOError) {
// uzimamo format
string format = fileName.substr(fileName.find_last_of(".") + 1);
transform(format.begin(), format.end(), format.begin(), ::tolower);
bool formatError = false;
// test
loadedSubtitle.close();
loadedSubtitle.open(fileName, ios_base::in | ios_base::out | ios_base::trunc);
switch (type) {
case SubtitleIO::SubRip:
// Ako se ne slaze format sa tipom
if (format != "srt"){
formatError = true;
break;
}
// Ubacujemo u fajl
loadedSubtitle << const_cast<Subtitles&>(subtitlesToSave);
break;
case SubtitleIO::MicroDVD:
if (format != "sub" && format != "txt")
{
formatError = true;
break;
}
// upisujemo u ovom formatu u fajl
for (const Subtitle& tempTitle : subtitlesToSave.getSubtitles()) {
//loadedSubtitle << SubtitleIO::makeMicroDVD(const_cast<Subtitle&>(tempTitle));
makeMicroDVDFile(loadedSubtitle, const_cast<Subtitle&>(tempTitle));
}
break;
case SubtitleIO::MPlayer:
if (format != "sub")
{
formatError = true;
break;
}
// upisujemo u MPlayer formatu
// upisujemo u ovom formatu u fajl
double startTime = 0;
for (const Subtitle& tempTitle : subtitlesToSave.getSubtitles()) {
//loadedSubtitle << SubtitleIO::makeMPlayer(const_cast<Subtitle&>(tempTitle), startTime);
makeMPlayerFile(loadedSubtitle, const_cast<Subtitle&>(tempTitle), startTime);
}
break;
}
// Pogresan format
if (formatError){
throw IOError();
}
loadedSubtitle.close();
loadedSubtitle.open(fileName, ios_base::in | ios_base::out | ios_base::app);
}
// Cuvamo kao novi
void SubtitleIO::saveTitleAs(string fileName, const Subtitles& subtitlesToSave, SubtitleType type) throw (IOError) {
// uzimamo format
string format = fileName.substr(fileName.find_last_of(".") + 1);
transform(format.begin(), format.end(), format.begin(), ::tolower);
bool formatError = false;
ofstream tempFile;
// test
tempFile.open(fileName, ios_base::in | ios_base::out | ios_base::trunc);
if(tempFile.is_open()){
switch (type) {
case SubtitleIO::SubRip:
// Ako se ne slaze format sa tipom
if (format != "srt"){
formatError = true;
break;
}
// Ubacujemo u fajl
tempFile << const_cast<Subtitles&>(subtitlesToSave);
break;
case SubtitleIO::MicroDVD:
if (format != "sub" && format != "txt")
{
formatError = true;
break;
}
// upisujemo u ovom formatu u fajl
for (const Subtitle& tempTitle : subtitlesToSave.getSubtitles()) {
//tempFile << SubtitleIO::makeMicroDVD(const_cast<Subtitle&>(tempTitle));
makeMicroDVDFile(tempFile, const_cast<Subtitle&>(tempTitle));
}
break;
case SubtitleIO::MPlayer:
if (format != "sub")
{
formatError = true;
break;
}
// upisujemo u MPlayer formatu
// upisujemo u ovom formatu u fajl
double startTime = 0;
for (const Subtitle& tempTitle : subtitlesToSave.getSubtitles()) {
//tempFile << SubtitleIO::makeMPlayer(const_cast<Subtitle&>(tempTitle), startTime);
makeMPlayerFile(tempFile, const_cast<Subtitle&>(tempTitle), startTime);
}
break;
}
// Pogresan format
if (formatError){
throw IOError();
}
tempFile.close();
}
else
throw IOError();
}
// Kovertujemo MicroDVD
string SubtitleIO::makeMicroDVD(Subtitle& titleToConvert) {
string toReturn = "";
int fps = SubtitleIO::framesPerSecond;
int frameAppearance = (int)(fps * titleToConvert.getTimeOfAppearance().getSeconds() + 0.5);
int frameRemoval = (int)(fps * titleToConvert.getTimeOfRemoval().getSeconds() + 0.5);
toReturn.append("{" + to_string(frameAppearance) + "}");
toReturn.append("{" + to_string(frameRemoval) + "}");
// dohvatamo i preuredjujemo u format za fajl
string titleText = titleToConvert.getString();
replace(titleText.begin(), titleText.end(), '\n', '|');
toReturn.append(titleText + "\n");
return toReturn;
}
// Konvertujemo u MPlayer
string SubtitleIO::makeMPlayer(Subtitle& subtitleToConvert, double& prevLastTime) {
string toReturn = "";
// Dohvatanje i update
double timeAppearance = subtitleToConvert.getTimeOfAppearance().getSeconds() - prevLastTime;
double timeLasts = subtitleToConvert.getTimeOfRemoval().getSeconds() - subtitleToConvert.getTimeOfAppearance().getSeconds() ;
prevLastTime = subtitleToConvert.getTimeOfRemoval().getSeconds();
// dodajemo
toReturn.append(to_string(timeAppearance)).append(" ").append(to_string(timeLasts)).append("\n");
toReturn.append(subtitleToConvert.getString()).append("\n");
return toReturn;
}
| 28.764925 | 130 | 0.624335 | [
"transform"
] |
ecec1a02a91f1adda406ebe3913d9bf78045ad44 | 710 | cc | C++ | chipyard.TestHarness.TinyRocketConfig/testchip_tsi.cc | vargandhi/ime-congs | 963be79b7b319d8e74edae09df7bdf3330371401 | [
"BSD-3-Clause"
] | null | null | null | chipyard.TestHarness.TinyRocketConfig/testchip_tsi.cc | vargandhi/ime-congs | 963be79b7b319d8e74edae09df7bdf3330371401 | [
"BSD-3-Clause"
] | null | null | null | chipyard.TestHarness.TinyRocketConfig/testchip_tsi.cc | vargandhi/ime-congs | 963be79b7b319d8e74edae09df7bdf3330371401 | [
"BSD-3-Clause"
] | null | null | null | #include "testchip_tsi.h"
testchip_tsi_t::testchip_tsi_t(int argc, char** argv, bool can_have_loadmem) : tsi_t(argc, argv)
{
has_loadmem = false;
std::vector<std::string> args(argv + 1, argv + argc);
for (auto& arg : args) {
if (arg.find("+loadmem=") == 0)
has_loadmem = can_have_loadmem;
}
}
void testchip_tsi_t::write_chunk(addr_t taddr, size_t nbytes, const void* src)
{
if (is_loadmem) {
load_mem_write(taddr, nbytes, src);
} else {
tsi_t::write_chunk(taddr, nbytes, src);
}
}
void testchip_tsi_t::read_chunk(addr_t taddr, size_t nbytes, void* dst)
{
if (is_loadmem) {
load_mem_read(taddr, nbytes, dst);
} else {
tsi_t::read_chunk(taddr, nbytes, dst);
}
}
| 22.903226 | 96 | 0.666197 | [
"vector"
] |
eced6649f1ba7af0cd72d186828c89f23136d653 | 4,628 | cpp | C++ | main.cpp | FrankMakesStuff/franks-drawing-library | 5e0e2f2248d886f5a77550fa9103ae49b01f1534 | [
"libtiff",
"libpng-2.0",
"BSD-3-Clause"
] | null | null | null | main.cpp | FrankMakesStuff/franks-drawing-library | 5e0e2f2248d886f5a77550fa9103ae49b01f1534 | [
"libtiff",
"libpng-2.0",
"BSD-3-Clause"
] | null | null | null | main.cpp | FrankMakesStuff/franks-drawing-library | 5e0e2f2248d886f5a77550fa9103ae49b01f1534 | [
"libtiff",
"libpng-2.0",
"BSD-3-Clause"
] | null | null | null | #define SDL_MAIN_HANDLED
#include <iostream>
#include <string>
#include "SDL2\SDL.h"
#include "SDL2\SDL_image.h"
const int SCREEN_WIDTH = 800;
const int SCREEN_HEIGHT = 600;
const int WINDOW_LEFT = 250;
const int WINDOW_TOP = 100;
const char *WINDOW_TITLE = "Frank's SDL2 Demo";
/**
-=-=-=-=-=-=-=- LogError -=-=-=-=-=-
*/
void logError( std::ostream &os, const std::string &msg){
os << msg << " error: " << SDL_GetError() << std::endl;
}
void logVerbose( std::ostream &os, const std::string &msg ){
os << msg << std::endl;
}
/**
-=-=-=-=-=-=- LoadTexture -=-=-=-=-=-
*/
SDL_Texture* loadTexture(const std::string &file, SDL_Renderer *ren){
SDL_Texture *texture = IMG_LoadTexture(ren, file.c_str());
if (texture == nullptr){
std::cout << "IMG_LoadTexture failed: " << file.c_str() << std::endl;
}
return texture;
}
/**
-=-=-=-= renderTexture -=-=-=-=-
*/
void renderTexture( SDL_Texture *tex, SDL_Renderer *ren, int x, int y, int w, int h ){
SDL_Rect dst;
dst.w = w; dst.h = h; dst.x = x; dst.y = y;
SDL_RenderCopy( ren, tex, NULL, &dst );
}
void renderTexture( SDL_Texture *tex, SDL_Renderer *ren, int x, int y ){
int w, h;
SDL_QueryTexture( tex, NULL, NULL, &w, &h );
renderTexture( tex, ren, x, y, w, h );
}
/**
-=-=-=-=-=- MAIN -=-=-=-=-=-=-=-
**/
int main(int argc, char** argv) {
SDL_Event e;
bool quit = false;
int blitX=15, blitY= 15, xdir=1, ydir=1;
// initialize SDL
if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) != 0) {
logError( std::cout, "SDL_Init failed." );
return 1;
} logVerbose( std::cout, "SDL initialized..." );
// initialize SDL image helper library
if( (IMG_Init( IMG_INIT_PNG ) & IMG_INIT_PNG) != IMG_INIT_PNG ){
logError( std::cout, "IMG_Init failed.");
SDL_Quit();
return 1;
} logVerbose( std::cout, "SDL_image initialized..." );
// create a window
SDL_Window *win = SDL_CreateWindow( WINDOW_TITLE, WINDOW_LEFT, WINDOW_TOP, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
if (win == nullptr){
std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
SDL_Quit();
return 1;
} logVerbose( std::cout, "Window created." );
// create a renderer
SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); // second param sets preferred device, here we use -1 to let SDL choose the best one for us
if (ren == nullptr){
SDL_DestroyWindow(win);
std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl;
SDL_Quit();
return 1;
} logVerbose( std::cout, "SDL renderer created." );
// load a bitmap file
// std::string imagePath = SDL_GetBasePath() + (std::string)"hello.bmp";
// SDL_Surface *bmp = SDL_LoadBMP(imagePath.c_str());
// if (bmp == nullptr){
// SDL_DestroyRenderer(ren);
// SDL_DestroyWindow(win);
// std::cout << "SDL_LoadBMP Error: " << SDL_GetError() << std::endl;
// SDL_Quit();
// return 1;
// }
// put bitmap into texture
// SDL_Texture *tex = SDL_CreateTextureFromSurface(ren, bmp);
// SDL_FreeSurface(bmp);
// if (tex == nullptr){
// SDL_DestroyRenderer(ren);
// SDL_DestroyWindow(win);
// std::cout << "SDL_CreateTextureFromSurface Error: " << SDL_GetError() << std::endl;
// SDL_Quit();
// return 1;
// }
// Use SDL_Image to directly load an image into a texture
std::string pngPath = SDL_GetBasePath() + (std::string)"hello.png";
SDL_Texture *tex = loadTexture( pngPath, ren );
// //A sleepy rendering loop, wait for 3 seconds and render and present the screen each time
// for (int i = 0; i < 3; ++i){
// //First clear the renderer
// SDL_RenderClear(ren);
// //Draw the texture
//// SDL_RenderCopy(ren, tex, NULL, NULL);
// renderTexture( tex, ren, 100, 100 );
// //Update the screen
// SDL_RenderPresent(ren);
// //Take a quick break after all that hard work
// SDL_Delay(1000);
// }
// render/event loop
logVerbose( std::cout, "Entering main loop..." );
while( !quit ){
while( SDL_PollEvent( &e )){
if( e.type == SDL_QUIT ) quit = true;
if( e.type == SDL_KEYDOWN ) quit = true;
if( e.type == SDL_MOUSEBUTTONDOWN ) quit = true;
}
// update bouncing image
blitX += xdir;
blitY += ydir;
if( blitX < 0 || (blitX + 400 > SCREEN_WIDTH) ) xdir *= -1;
if( blitY < 0 || (blitY + 400 > SCREEN_HEIGHT) ) ydir *= -1;
// render
SDL_RenderClear( ren );
renderTexture( tex, ren, blitX, blitY );
SDL_RenderPresent( ren );
} logVerbose( std::cout, "Loop ended... beginning clean-up..." );
// clean up and end
SDL_DestroyTexture(tex);
SDL_DestroyRenderer(ren);
SDL_DestroyWindow(win);
IMG_Quit();
SDL_Quit();
return 0;
}
| 28.745342 | 195 | 0.63764 | [
"render"
] |
eced990f86e4b96fe2cd5939a895544595e0b3f6 | 5,524 | cpp | C++ | src/xercesc/util/NetAccessors/MacOSURLAccess/URLAccessBinInputStream.cpp | rherardi/xerces-c-src_2_7_0 | a23711292bba70519940d7e6aeb07100319b607c | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/xercesc/util/NetAccessors/MacOSURLAccess/URLAccessBinInputStream.cpp | rherardi/xerces-c-src_2_7_0 | a23711292bba70519940d7e6aeb07100319b607c | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/xercesc/util/NetAccessors/MacOSURLAccess/URLAccessBinInputStream.cpp | rherardi/xerces-c-src_2_7_0 | a23711292bba70519940d7e6aeb07100319b607c | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
* Copyright 1999-2000,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: URLAccessBinInputStream.cpp 176026 2004-09-08 13:57:07Z peiyongz $
*/
#include <xercesc/util/XMLNetAccessor.hpp>
#include <xercesc/util/NetAccessors/MacOSURLAccess/URLAccessBinInputStream.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XMLExceptMsgs.hpp>
#include <xercesc/util/Janitor.hpp>
#include <cstdlib>
#include <cstring>
XERCES_CPP_NAMESPACE_BEGIN
URLAccessBinInputStream::URLAccessBinInputStream(const XMLURL& urlSource)
: mBytesProcessed(0),
mURLReference(NULL),
mBuffer(NULL),
mBufPos(NULL),
mBufAvailable(0)
{
OSStatus status = noErr;
// Get the full URL from the source
char* url = XMLString::transcode(urlSource.getURLText(), urlSource.getMemoryManager());
ArrayJanitor<char> janBuf(url, urlSource.getMemoryManager());
// Create a URL reference from the URL
status = URLNewReference(url, &mURLReference);
// Begin the transfer
if (status == noErr)
status = URLOpen(
mURLReference,
NULL, // FSSpec* (not reading to file)
0, // URLOpenFlags
NULL, // URLNotifyUPP
0, // URLEventMask
0); // userContext
// If we failed, we throw
switch (status)
{
case noErr:
break;
case kURLInvalidURLError:
ThrowXML(MalformedURLException, XMLExcepts::URL_MalformedURL);
break;
case kURLUnsupportedSchemeError:
ThrowXML(MalformedURLException, XMLExcepts::URL_UnsupportedProto);
break;
default:
ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_ConnSocket, urlSource.getURLText());
break;
}
}
URLAccessBinInputStream::~URLAccessBinInputStream()
{
OSStatus status = noErr;
// Release any buffer we've still got a hold of
if (status == noErr && mBuffer)
{
status = URLReleaseBuffer(mURLReference, mBuffer);
mBuffer = NULL;
}
// Get the current state
URLState state = 0;
if (status == noErr)
status = URLGetCurrentState(mURLReference, &state);
// Abort if we're not completed
if (status == noErr && state != kURLNullState && state != kURLCompletedState)
status = URLAbort(mURLReference);
// Loop til we reach a terminal state.
// This may be unneeded by URLAccess, but the docs are
// not very good.
while (
status == noErr
&& state != kURLNullState
&& state != kURLErrorOccurredState
&& state != kURLCompletedState
)
{
status = URLIdle();
if (status == noErr)
status = URLGetCurrentState(mURLReference, &state);
}
// Dispose the reference
status = URLDisposeReference(mURLReference);
}
//
// Call URLAccess to fullfill the read request. Since it
// passes us back buffers full of data, our object maintains
// a partial buffer across calls.
//
unsigned int
URLAccessBinInputStream::readBytes(XMLByte* const toFill
, const unsigned int maxToRead)
{
OSStatus status = noErr;
XMLByte* writePos = toFill;
std::size_t bytesDesired = maxToRead;
URLState state = kURLNullState;
while ( // while...
status == noErr // there's been no error
&& bytesDesired > 0 // more data is wanted
&& (status = URLGetCurrentState(mURLReference, &state)) == noErr // we can get the state
&& (state != kURLErrorOccurredState) // no error has occurred in the transaction
&& (mBuffer || state != kURLCompletedState) // we have data still buffered or the request isn't complete
&& (mBuffer || bytesDesired == maxToRead) // we have data still buffered or we've supplied absolutely none
)
{
// Give time to URLAccess
status = URLIdle();
// If we've got buffered data, use it
if (status == noErr && mBuffer)
{
// Supply as much as we can from the buffer
std::size_t n = mBufAvailable;
if (n > bytesDesired)
n = bytesDesired;
// If we've got data, copy it over and update our pointers
if (n > 0)
{
std::memcpy(writePos, mBufPos, n);
writePos += n;
bytesDesired -= n;
mBufPos += n;
mBufAvailable -= n;
mBytesProcessed += n;
}
// If we exhausted the buffer, release it
if (mBufAvailable == 0)
{
status = URLReleaseBuffer(mURLReference, mBuffer);
mBuffer = NULL;
}
}
// If the buffer is exhausted, get a new one
if (status == noErr && !mBuffer)
{
status = URLGetBuffer(mURLReference, &mBuffer, &mBufAvailable);
if (status == noErr)
mBufPos = reinterpret_cast<char*>(mBuffer);
}
}
// Throw on any error
if (status != noErr || state == kURLErrorOccurredState)
ThrowXML(NetAccessorException, XMLExcepts::NetAcc_ReadSocket);
// Return number of bytes delivered
return maxToRead - bytesDesired;
}
XERCES_CPP_NAMESPACE_END
| 28.328205 | 111 | 0.653331 | [
"object"
] |
eceedc91f1048d32c2df74aab5cb83259eddee2d | 1,938 | cpp | C++ | EngineTest/EngineTest/Source/Core/M5Phy.cpp | mattCasanova/Mach5 | 0d98a092bee4c38816911c118fd6552a40850201 | [
"MIT"
] | 16 | 2017-06-30T12:49:24.000Z | 2021-01-23T17:39:35.000Z | EngineTest/EngineTest/Source/Core/M5Phy.cpp | mattCasanova/Mach5 | 0d98a092bee4c38816911c118fd6552a40850201 | [
"MIT"
] | 2 | 2017-03-09T20:35:26.000Z | 2020-03-20T01:09:40.000Z | EngineTest/EngineTest/Source/Core/M5Phy.cpp | mattCasanova/Mach5 | 0d98a092bee4c38816911c118fd6552a40850201 | [
"MIT"
] | 2 | 2018-10-21T01:33:17.000Z | 2020-03-19T09:30:19.000Z | /******************************************************************************/
/*!
file M5Phy.cpp
\author Matt Casanova
\\par email: lazersquad\@gmail.com
\par Mach5 Game Engine
\date 2016/09/26
Basis Physics engine for Mach 5. This is a work in progress.
*/
/******************************************************************************/
#include "M5Phy.h"
#include "M5Object.h"
#include "ColliderComponent.h"
#include <stack>
namespace
{
//Class Private variables
static std::vector<ColliderComponent*> s_colliders; //!< Vector of regiestered colliders
static CollisionPairs s_collisionPairs; //!< This frames collision pairs.
static int s_colliderStart = 0; //!< The index to start updating on
static std::stack<int> s_pauseStack;
}
void M5Phy::RegisterCollider(ColliderComponent* pCollider)
{
s_colliders.push_back(pCollider);
}
void M5Phy::UnregisterCollider(ColliderComponent* pCollider)
{
for (size_t i = s_colliderStart; i < s_colliders.size(); ++i)
{
if (s_colliders[i] == pCollider)
{
s_colliders[i] = s_colliders[s_colliders.size() - 1];
s_colliders.pop_back();
}
}
}
void M5Phy::GetCollisionPairs(CollisionPairs& pairs)
{
pairs = s_collisionPairs;
}
void M5Phy::AddCollisionPair(int firstID, int secondID)
{
s_collisionPairs.push_back(std::make_pair(firstID, secondID));
}
void M5Phy::Update(void)
{
s_collisionPairs.clear();
size_t size = s_colliders.size();
for (size_t i = s_colliderStart; i < size; ++i)
{
ColliderComponent* pFirst = s_colliders[i];
for (size_t j = i + 1; j < size; ++j)
{
pFirst->TestCollision(s_colliders[j]);
}
}
}
void M5Phy::Pause(void)
{
s_pauseStack.push(s_colliderStart);
s_colliderStart = s_colliders.size();
}
void M5Phy::Resume(void)
{
s_colliderStart = s_pauseStack.top();
s_pauseStack.pop();
} | 26.189189 | 97 | 0.609907 | [
"vector"
] |
eceefc86a50abfe21d9f0997ceec4b5be0af2eef | 868 | cpp | C++ | test/algorithms/data_structures/array/test_max_consecutive_equal_elements.cpp | iamantony/CppNotes | 2707db6560ad80b0e5e286a04b2d46e5c0280b3f | [
"MIT"
] | 2 | 2020-07-31T14:13:56.000Z | 2021-02-03T09:51:43.000Z | test/algorithms/data_structures/array/test_max_consecutive_equal_elements.cpp | iamantony/CppNotes | 2707db6560ad80b0e5e286a04b2d46e5c0280b3f | [
"MIT"
] | 28 | 2015-09-22T07:38:21.000Z | 2018-10-02T11:00:58.000Z | test/algorithms/data_structures/array/test_max_consecutive_equal_elements.cpp | iamantony/CppNotes | 2707db6560ad80b0e5e286a04b2d46e5c0280b3f | [
"MIT"
] | 2 | 2018-10-11T14:10:50.000Z | 2021-02-27T08:53:50.000Z | #include <boost/test/unit_test.hpp>
#include "algorithms/data_structures/array/max_consecutive_equal_elements.hpp"
BOOST_AUTO_TEST_SUITE(TestMaxConsecutiveEqualElements)
BOOST_AUTO_TEST_CASE(empty_arr)
{
std::vector<int> array = {};
BOOST_CHECK(0 == Algo::DS::Array::MaxConsecutiveElems::MaxOnes(array));
}
BOOST_AUTO_TEST_CASE(no_ones)
{
std::vector<int> array = {0, 0, 0};
BOOST_CHECK(0 == Algo::DS::Array::MaxConsecutiveElems::MaxOnes(array));
}
BOOST_AUTO_TEST_CASE(have_ones)
{
std::vector<int> array = {0, 0, 0, 1};
BOOST_CHECK(1 == Algo::DS::Array::MaxConsecutiveElems::MaxOnes(array));
array = {1, 0, 0, 0, 1};
BOOST_CHECK(1 == Algo::DS::Array::MaxConsecutiveElems::MaxOnes(array));
array = {1, 0, 1, 1, 1, 0};
BOOST_CHECK(3 == Algo::DS::Array::MaxConsecutiveElems::MaxOnes(array));
}
BOOST_AUTO_TEST_SUITE_END()
| 28 | 78 | 0.701613 | [
"vector"
] |
ecff0a4ead79ab4cafde655f3119d7a830a94365 | 7,987 | cpp | C++ | platforms/umc/src/dtmfsession.cpp | bjqiwei/unimrcp | c081282cc5b9572d7ee6c9d01aa42bd5ce0628ba | [
"Apache-2.0"
] | null | null | null | platforms/umc/src/dtmfsession.cpp | bjqiwei/unimrcp | c081282cc5b9572d7ee6c9d01aa42bd5ce0628ba | [
"Apache-2.0"
] | null | null | null | platforms/umc/src/dtmfsession.cpp | bjqiwei/unimrcp | c081282cc5b9572d7ee6c9d01aa42bd5ce0628ba | [
"Apache-2.0"
] | 1 | 2020-08-02T12:23:25.000Z | 2020-08-02T12:23:25.000Z | /*
* Copyright 2008-2015 Arsen Chaloyan
*
* 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 "dtmfsession.h"
#include "dtmfscenario.h"
#include "mrcp_message.h"
#include "mrcp_generic_header.h"
#include "mrcp_recog_header.h"
#include "mrcp_recog_resource.h"
#include "mpf_dtmf_generator.h"
#include "apt_nlsml_doc.h"
#include "apt_log.h"
struct RecogChannel
{
/** MRCP control channel */
mrcp_channel_t* m_pMrcpChannel;
/** DTMF generator */
mpf_dtmf_generator_t* m_pDtmfGenerator;
/** Streaming is in-progress */
bool m_Streaming;
};
DtmfSession::DtmfSession(const DtmfScenario* pScenario) :
UmcSession(pScenario),
m_pRecogChannel(NULL)
{
}
DtmfSession::~DtmfSession()
{
}
bool DtmfSession::Start()
{
/* create channel and associate all the required data */
m_pRecogChannel = CreateRecogChannel();
if(!m_pRecogChannel)
return false;
/* add channel to session (send asynchronous request) */
if(!AddMrcpChannel(m_pRecogChannel->m_pMrcpChannel))
{
delete m_pRecogChannel;
m_pRecogChannel = NULL;
return false;
}
return true;
}
bool DtmfSession::OnSessionTerminate(mrcp_sig_status_code_e status)
{
if(m_pRecogChannel)
{
if(m_pRecogChannel->m_pDtmfGenerator)
{
mpf_dtmf_generator_destroy(m_pRecogChannel->m_pDtmfGenerator);
m_pRecogChannel->m_pDtmfGenerator = NULL;
}
delete m_pRecogChannel;
m_pRecogChannel = NULL;
}
return UmcSession::OnSessionTerminate(status);
}
static apt_bool_t ReadStream(mpf_audio_stream_t* pStream, mpf_frame_t* pFrame)
{
RecogChannel* pRecogChannel = (RecogChannel*) pStream->obj;
if(pRecogChannel && pRecogChannel->m_Streaming)
{
if(pRecogChannel->m_pDtmfGenerator)
{
mpf_dtmf_generator_put_frame(pRecogChannel->m_pDtmfGenerator,pFrame);
}
}
return TRUE;
}
RecogChannel* DtmfSession::CreateRecogChannel()
{
mrcp_channel_t* pChannel;
mpf_termination_t* pTermination;
mpf_stream_capabilities_t* pCapabilities;
apr_pool_t* pool = GetSessionPool();
/* create channel */
RecogChannel *pRecogChannel = new RecogChannel;
pRecogChannel->m_pMrcpChannel = NULL;
pRecogChannel->m_pDtmfGenerator = NULL;
pRecogChannel->m_Streaming = false;
/* create source stream capabilities */
pCapabilities = mpf_source_stream_capabilities_create(pool);
GetScenario()->InitCapabilities(pCapabilities);
static const mpf_audio_stream_vtable_t audio_stream_vtable =
{
NULL,
NULL,
NULL,
ReadStream,
NULL,
NULL,
NULL,
NULL
};
pTermination = CreateAudioTermination(
&audio_stream_vtable, /* virtual methods table of audio stream */
pCapabilities, /* capabilities of audio stream */
pRecogChannel); /* object to associate */
pChannel = CreateMrcpChannel(
MRCP_RECOGNIZER_RESOURCE, /* MRCP resource identifier */
pTermination, /* media termination, used to terminate audio stream */
NULL, /* RTP descriptor, used to create RTP termination (NULL by default) */
pRecogChannel); /* object to associate */
if(!pChannel)
{
delete pRecogChannel;
return NULL;
}
pRecogChannel->m_pMrcpChannel = pChannel;
return pRecogChannel;
}
bool DtmfSession::OnChannelAdd(mrcp_channel_t* pMrcpChannel, mrcp_sig_status_code_e status)
{
if(!UmcSession::OnChannelAdd(pMrcpChannel,status))
return false;
if(status != MRCP_SIG_STATUS_CODE_SUCCESS)
{
/* error case, just terminate the demo */
return Terminate();
}
RecogChannel* pRecogChannel = (RecogChannel*) mrcp_application_channel_object_get(pMrcpChannel);
if(pRecogChannel)
{
const mpf_audio_stream_t* pStream = mrcp_application_audio_stream_get(pMrcpChannel);
if(pStream)
{
pRecogChannel->m_pDtmfGenerator = mpf_dtmf_generator_create(pStream,GetSessionPool());
}
}
return StartRecognition(pMrcpChannel);
}
bool DtmfSession::OnMessageReceive(mrcp_channel_t* pMrcpChannel, mrcp_message_t* pMrcpMessage)
{
if(!UmcSession::OnMessageReceive(pMrcpChannel,pMrcpMessage))
return false;
const DtmfScenario* pScenario = GetScenario();
RecogChannel* pRecogChannel = (RecogChannel*) mrcp_application_channel_object_get(pMrcpChannel);
if(pMrcpMessage->start_line.message_type == MRCP_MESSAGE_TYPE_RESPONSE)
{
if(pMrcpMessage->start_line.method_id == RECOGNIZER_RECOGNIZE)
{
/* received the response to RECOGNIZE request */
if(pMrcpMessage->start_line.request_state == MRCP_REQUEST_STATE_INPROGRESS)
{
/* start to stream the DTMFs to recognize */
if(pRecogChannel && pRecogChannel->m_pDtmfGenerator)
{
const char* digits = pScenario->GetDigits();
if(digits)
{
mpf_dtmf_generator_enqueue(pRecogChannel->m_pDtmfGenerator,digits);
pRecogChannel->m_Streaming = true;
}
}
}
else
{
/* received unexpected response, terminate the session */
Terminate();
}
}
else
{
/* received unexpected response */
}
}
else if(pMrcpMessage->start_line.message_type == MRCP_MESSAGE_TYPE_EVENT)
{
if(pMrcpMessage->start_line.method_id == RECOGNIZER_RECOGNITION_COMPLETE)
{
ParseNLSMLResult(pMrcpMessage);
if(pRecogChannel)
{
pRecogChannel->m_Streaming = false;
}
Terminate();
}
else if(pMrcpMessage->start_line.method_id == RECOGNIZER_START_OF_INPUT)
{
/* received start-of-input, do whatever you need here */
}
}
return true;
}
bool DtmfSession::StartRecognition(mrcp_channel_t* pMrcpChannel)
{
RecogChannel* pRecogChannel = (RecogChannel*) mrcp_application_channel_object_get(pMrcpChannel);
/* create and send RECOGNIZE request */
mrcp_message_t* pMrcpMessage = CreateRecognizeRequest(pMrcpChannel);
if(pMrcpMessage)
{
SendMrcpRequest(pRecogChannel->m_pMrcpChannel,pMrcpMessage);
}
return true;
}
mrcp_message_t* DtmfSession::CreateRecognizeRequest(mrcp_channel_t* pMrcpChannel)
{
mrcp_message_t* pMrcpMessage = CreateMrcpMessage(pMrcpChannel,RECOGNIZER_RECOGNIZE);
if(!pMrcpMessage)
return NULL;
const DtmfScenario* pScenario = GetScenario();
mrcp_generic_header_t* pGenericHeader;
mrcp_recog_header_t* pRecogHeader;
/* get/allocate generic header */
pGenericHeader = (mrcp_generic_header_t*) mrcp_generic_header_prepare(pMrcpMessage);
if(pGenericHeader)
{
apt_string_assign(&pGenericHeader->content_type,pScenario->GetContentType(),pMrcpMessage->pool);
mrcp_generic_header_property_add(pMrcpMessage,GENERIC_HEADER_CONTENT_TYPE);
/* set message body */
if(pScenario->GetGrammar())
apt_string_assign(&pMrcpMessage->body,pScenario->GetGrammar(),pMrcpMessage->pool);
}
/* get/allocate recognizer header */
pRecogHeader = (mrcp_recog_header_t*) mrcp_resource_header_prepare(pMrcpMessage);
if(pRecogHeader)
{
/* set recognizer header fields */
if(pMrcpMessage->start_line.version == MRCP_VERSION_2)
{
pRecogHeader->cancel_if_queue = FALSE;
mrcp_resource_header_property_add(pMrcpMessage,RECOGNIZER_HEADER_CANCEL_IF_QUEUE);
}
}
return pMrcpMessage;
}
bool DtmfSession::ParseNLSMLResult(mrcp_message_t* pMrcpMessage)
{
nlsml_result_t *pResult = nlsml_result_parse(pMrcpMessage->body.buf, pMrcpMessage->body.length, pMrcpMessage->pool);
if(!pResult)
return false;
nlsml_result_trace(pResult, pMrcpMessage->pool);
return true;
}
| 28.730216 | 118 | 0.724552 | [
"object"
] |
a6010007bb4fc6b379248a1e64b1730ad3b6b509 | 16,828 | cxx | C++ | Qt/ApplicationComponents/pqLoadDataReaction.cxx | xj361685640/ParaView | 0a27eef5abc5a0c0472ab0bc806c4db881156e64 | [
"Apache-2.0",
"BSD-3-Clause"
] | 815 | 2015-01-03T02:14:04.000Z | 2022-03-26T07:48:07.000Z | Qt/ApplicationComponents/pqLoadDataReaction.cxx | xj361685640/ParaView | 0a27eef5abc5a0c0472ab0bc806c4db881156e64 | [
"Apache-2.0",
"BSD-3-Clause"
] | 9 | 2015-04-28T20:10:37.000Z | 2021-08-20T18:19:01.000Z | Qt/ApplicationComponents/pqLoadDataReaction.cxx | xj361685640/ParaView | 0a27eef5abc5a0c0472ab0bc806c4db881156e64 | [
"Apache-2.0",
"BSD-3-Clause"
] | 328 | 2015-01-22T23:11:46.000Z | 2022-03-14T06:07:52.000Z | /*=========================================================================
Program: ParaView
Module: pqLoadDataReaction.cxx
Copyright (c) 2005,2006 Sandia Corporation, Kitware Inc.
All rights reserved.
ParaView is a free software; you can redistribute it and/or modify it
under the terms of the ParaView license version 1.2.
See License_v1.2.txt for the full ParaView license.
A copy of this license can be obtained by contacting
Kitware Inc.
28 Corporate Drive
Clifton Park, NY 12065
USA
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 AUTHORS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
========================================================================*/
#include "pqLoadDataReaction.h"
#include "pqActiveObjects.h"
#include "pqApplicationCore.h"
#include "pqCoreUtilities.h"
#include "pqFileDialog.h"
#include "pqObjectBuilder.h"
#include "pqPipelineSource.h"
#include "pqSelectReaderDialog.h"
#include "pqServer.h"
#include "pqStandardRecentlyUsedResourceLoaderImplementation.h"
#include "pqUndoStack.h"
#include "vtkSMPropertyHelper.h"
#include "vtkSMProxy.h"
#include "vtkSMProxyManager.h"
#include "vtkSMReaderFactory.h"
#include "vtkSMSessionProxyManager.h"
#include "vtkSMSettings.h"
#include "vtkSMSettingsProxy.h"
#include "vtkStringList.h"
#include <vtksys/SystemTools.hxx>
#include <QDebug>
#include <QInputDialog>
#include <cassert>
//-----------------------------------------------------------------------------
pqLoadDataReaction::pqLoadDataReaction(QAction* parentObject)
: Superclass(parentObject)
{
pqActiveObjects* activeObjects = &pqActiveObjects::instance();
QObject::connect(
activeObjects, SIGNAL(serverChanged(pqServer*)), this, SLOT(updateEnableState()));
this->updateEnableState();
}
//-----------------------------------------------------------------------------
void pqLoadDataReaction::updateEnableState()
{
pqActiveObjects& activeObjects = pqActiveObjects::instance();
// TODO: also is there's a pending accept.
bool enable_state = (activeObjects.activeServer() != nullptr);
this->parentAction()->setEnabled(enable_state);
}
//-----------------------------------------------------------------------------
QList<pqPipelineSource*> pqLoadDataReaction::loadData()
{
pqServer* server = pqActiveObjects::instance().activeServer();
vtkSMReaderFactory* readerFactory = vtkSMProxyManager::GetProxyManager()->GetReaderFactory();
std::vector<FileTypeDetailed> filtersDetailed =
readerFactory->GetSupportedFileTypesDetailed(server->session());
QString filtersString;
bool first = true;
// Generates the filter string used by the fileDialog
// For example, this could be "Supported Files (*.jpg *.jpeg *.png);;All Files (*);;JPEG Image
// Files(*.jpg *.jpeg);;PNG Image Files (*.png)"
for (auto const& filterDetailed : filtersDetailed)
{
if (!first)
{
filtersString += ";;";
}
filtersString += QString::fromStdString(filterDetailed.Description) + " (" +
QString::fromStdString(vtksys::SystemTools::Join(filterDetailed.FilenamePatterns, " ")) + ")";
first = false;
}
int constexpr SupportedFilesFilterIndex = 0;
int constexpr AllFilesFilterIndex = 1;
pqFileDialog fileDialog(
server, pqCoreUtilities::mainWidget(), tr("Open File:"), QString(), filtersString);
fileDialog.setObjectName("FileOpenDialog");
fileDialog.setFileMode(pqFileDialog::ExistingFilesAndDirectories);
QList<pqPipelineSource*> sources;
if (fileDialog.exec() == QDialog::Accepted)
{
QList<QStringList> files = fileDialog.getAllSelectedFiles();
int filterIndex = fileDialog.getSelectedFilterIndex();
switch (filterIndex)
{
case SupportedFilesFilterIndex:
{
auto newSources = pqLoadDataReaction::loadFilesForSupportedTypes(files);
for (auto const& source : newSources)
{
sources << source;
}
}
break;
case AllFilesFilterIndex:
{
auto newSources = pqLoadDataReaction::loadFilesForAllTypes(files, server, readerFactory);
for (auto const& source : newSources)
{
sources << source;
}
}
break;
default:
// Specific reader
pqPipelineSource* source = pqLoadDataReaction::loadData(files,
QString::fromStdString(filtersDetailed[filterIndex].Group),
QString::fromStdString(filtersDetailed[filterIndex].Name));
if (source)
{
sources << source;
}
}
}
return sources;
}
//-----------------------------------------------------------------------------
QVector<pqPipelineSource*> pqLoadDataReaction::loadFilesForSupportedTypes(QList<QStringList> files)
{
QVector<pqPipelineSource*> newSources;
auto* settings = vtkSMSettings::GetInstance();
char const* settingName = ".settings.RepresentedArrayListSettings.ReaderDetails";
for (auto const& file : files)
{
QFileInfo fileInfo(file[0]);
bool loaded = false;
unsigned int const numberOfEntries = settings->GetSettingNumberOfElements(settingName) / 3;
for (unsigned int loopIndex = 0; loopIndex < numberOfEntries; ++loopIndex)
{
// Read entries from the end to the start
unsigned int const reversedIndex = numberOfEntries - loopIndex - 1;
auto const patternsString = settings->GetSettingAsString(settingName, reversedIndex * 3, "");
std::vector<std::string> patterns;
vtksys::SystemTools::Split(patternsString, patterns, ' ');
for (std::string const& pattern : patterns)
{
if (QRegExp(QString::fromStdString(pattern), Qt::CaseInsensitive, QRegExp::Wildcard)
.exactMatch(fileInfo.fileName()))
{
pqLoadDataReaction::loadData(file, "sources",
QString::fromStdString(
settings->GetSettingAsString(settingName, reversedIndex * 3 + 2, "")));
loaded = true;
break;
}
}
if (loaded)
{
break;
}
}
if (!loaded)
{
pqPipelineSource* source = pqLoadDataReaction::loadData({ file });
if (source)
{
newSources << source;
}
}
}
return newSources;
}
//-----------------------------------------------------------------------------
QVector<pqPipelineSource*> pqLoadDataReaction::loadFilesForAllTypes(
QList<QStringList> files, pqServer* server, vtkSMReaderFactory* readerFactory)
{
QVector<pqPipelineSource*> newSources;
vtkStringList* list = readerFactory->GetReaders(server->session());
for (QStringList const& fileGroups : files)
{
pqSelectReaderDialog prompt(fileGroups[0], server, list, pqCoreUtilities::mainWidget());
if (prompt.exec() == QDialog::Accepted)
{
if (prompt.isSetAsDefault())
{
QString customPattern;
QString const completeSuffix = QFileInfo(fileGroups[0]).completeSuffix();
if (completeSuffix.isEmpty())
{
customPattern = "*";
}
else
{
customPattern = "*." + completeSuffix;
}
bool cancel = false;
bool patternValid = false;
QString errorString = "";
// Ask the user the pattern they want to associate with the reader as long as the pattern is
// not valid, or the user cancels the operation
while (!patternValid)
{
bool ok;
customPattern = QInputDialog::getText(&prompt, "Define custom pattern",
QString(
"Define the pattern you want to use to default to this reader.\nFor example: '*.png "
"*.jpg'") +
(errorString.isEmpty() ? "" : ("\nError: '" + errorString + "'")),
QLineEdit::Normal, customPattern, &ok);
if (!ok)
{
cancel = true;
break;
}
#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
auto splitCustomPattern = customPattern.split(".", Qt::SkipEmptyParts);
#else
auto splitCustomPattern = customPattern.split(" ", QString::SkipEmptyParts);
#endif
patternValid = !splitCustomPattern.empty() &&
std::all_of(
splitCustomPattern.begin(), splitCustomPattern.end(), [&](QString const& pattern) {
QRegExp regexp(pattern, Qt::CaseInsensitive, QRegExp::Wildcard);
if (!regexp.isValid())
{
errorString = regexp.errorString();
return false;
}
return true;
});
if (splitCustomPattern.empty())
{
errorString = "pattern cannot be empty";
}
}
if (cancel)
{
continue;
}
pqLoadDataReaction::addReaderToDefaults(
prompt.getReader(), server, readerFactory, customPattern);
}
pqPipelineSource* source =
pqLoadDataReaction::loadData(files, prompt.getGroup(), prompt.getReader());
if (source)
{
newSources << source;
}
}
}
return newSources;
}
//-----------------------------------------------------------------------------
pqPipelineSource* pqLoadDataReaction::loadData(
const QStringList& files, const QString& smgroup, const QString& smname, pqServer* server)
{
QList<QStringList> f;
f.append(files);
return pqLoadDataReaction::loadData(f, smgroup, smname, server);
}
//-----------------------------------------------------------------------------
pqPipelineSource* pqLoadDataReaction::loadData(
const QList<QStringList>& files, const QString& smgroup, const QString& smname, pqServer* server)
{
if (files.empty())
{
return nullptr;
}
server = server != nullptr ? server : pqActiveObjects::instance().activeServer();
if (!server)
{
qCritical() << "Cannot create reader without an active server.";
return nullptr;
}
vtkSMReaderFactory* readerFactory = vtkSMProxyManager::GetProxyManager()->GetReaderFactory();
pqPipelineSource* reader = nullptr;
// Extension to ReaderType,ReaderGroup Hash table
QHash<QString, QPair<QString, QString>> extensionToReaderSelection;
Q_FOREACH (const QStringList& filegroup, files)
{
QPair<QString, QString> readerInfo; // type,group
QString filename(filegroup[0]);
QFileInfo fi(filename);
if (!pqLoadDataReaction::TestFileReadability(filename, server, readerFactory))
{
qWarning() << "File '" << filename << "' cannot be read.";
continue;
}
if (!smgroup.isEmpty() && !smname.isEmpty())
{
readerInfo = QPair<QString, QString>(smname, smgroup);
}
else
{
// Determine reader type based on if we have asked the user for this extension before
QHash<QString, QPair<QString, QString>>::const_iterator it =
extensionToReaderSelection.find(fi.suffix());
if (it != extensionToReaderSelection.end())
{
readerInfo = it.value();
}
else
{
// Determine reader type based on the first filegroup
bool valid =
pqLoadDataReaction::DetermineFileReader(filename, server, readerFactory, readerInfo);
if (valid == 0)
{
// no reader selected
continue;
}
}
}
// read the filegroup
BEGIN_UNDO_SET("Create 'Reader'");
reader = pqLoadDataReaction::LoadFile(filegroup, server, readerInfo);
END_UNDO_SET();
// add this extension to the hash set
extensionToReaderSelection.insert(fi.suffix(), readerInfo);
}
return reader;
}
//-----------------------------------------------------------------------------
bool pqLoadDataReaction::TestFileReadability(
const QString& file, pqServer* server, vtkSMReaderFactory* vtkNotUsed(factory))
{
return vtkSMReaderFactory::TestFileReadability(file.toUtf8().data(), server->session());
}
//-----------------------------------------------------------------------------
bool pqLoadDataReaction::DetermineFileReader(const QString& filename, pqServer* server,
vtkSMReaderFactory* factory, QPair<QString, QString>& readerInfo)
{
QString readerType, readerGroup;
vtkStringList* list = factory->GetReaders(filename.toUtf8().data(), server->session());
if (list->GetLength() > 3)
{
// If more than one readers found.
pqSelectReaderDialog prompt(filename, server, list, pqCoreUtilities::mainWidget());
if (prompt.exec() == QDialog::Accepted)
{
if (prompt.isSetAsDefault())
{
pqLoadDataReaction::addReaderToDefaults(prompt.getReader(), server, factory);
}
readerType = prompt.getReader();
readerGroup = prompt.getGroup();
}
else
{
// User didn't choose any reader.
return false;
}
}
else if (list->GetLength() == 3)
{
// reader knows the type
readerGroup = list->GetString(0);
readerType = list->GetString(1);
}
else
{
// The reader factory could not determine the type of reader to create for the
// file. Ask the user.
pqSelectReaderDialog prompt(filename, server, factory, pqCoreUtilities::mainWidget());
if (prompt.exec() == QDialog::Accepted)
{
if (prompt.isSetAsDefault())
{
pqLoadDataReaction::addReaderToDefaults(prompt.getReader(), server, factory);
}
readerType = prompt.getReader();
readerGroup = prompt.getGroup();
}
else
{
// User didn't choose any reader.
return false;
}
}
readerInfo.first = readerType;
readerInfo.second = readerGroup;
return true;
}
//-----------------------------------------------------------------------------
pqPipelineSource* pqLoadDataReaction::LoadFile(
const QStringList& files, pqServer* server, const QPair<QString, QString>& readerInfo)
{
pqObjectBuilder* builder = pqApplicationCore::instance()->getObjectBuilder();
pqPipelineSource* reader =
builder->createReader(readerInfo.second, readerInfo.first, files, server);
if (reader)
{
pqStandardRecentlyUsedResourceLoaderImplementation::addDataFilesToRecentResources(
server, files, reader->getProxy()->GetXMLGroup(), reader->getProxy()->GetXMLName());
}
return reader;
}
//-----------------------------------------------------------------------------
void pqLoadDataReaction::addReaderToDefaults(QString const& readerName, pqServer* server,
vtkSMReaderFactory* readerFactory, QString const& customPattern)
{
auto pxm = server ? server->proxyManager() : nullptr;
auto settingsProxy = pxm
? vtkSMSettingsProxy::SafeDownCast(pxm->GetProxy("settings", "RepresentedArrayListSettings"))
: nullptr;
auto* settings = vtkSMSettings::GetInstance();
char const* settingName = ".settings.RepresentedArrayListSettings.ReaderDetails";
unsigned int numberOfEntries = settings->GetSettingNumberOfElements(settingName) / 3;
std::string const readerNameString = readerName.toStdString();
auto filtersDetailed = readerFactory->GetSupportedFileTypesDetailed(server->session());
auto readerIt = std::find_if(filtersDetailed.begin(), filtersDetailed.end(),
[&](FileTypeDetailed const& fileType) { return fileType.Name == readerNameString; });
if (readerIt == filtersDetailed.end())
{
vtkGenericWarningMacro(<< "Could not add reader as default, name '" << readerName.toStdString()
<< "' is incorrect.");
return;
}
std::string customPatternString = customPattern.toStdString();
if (customPatternString.empty())
{
customPatternString = vtksys::SystemTools::Join(readerIt->FilenamePatterns, " ");
}
settings->SetSetting(settingName, numberOfEntries * 3, customPatternString);
vtkSMPropertyHelper(settingsProxy, "ReaderDetails")
.Set(numberOfEntries * 3, customPatternString.c_str());
settings->SetSetting(settingName, numberOfEntries * 3 + 1, readerIt->Description);
vtkSMPropertyHelper(settingsProxy, "ReaderDetails")
.Set(numberOfEntries * 3 + 1, readerIt->Description.c_str());
settings->SetSetting(settingName, numberOfEntries * 3 + 2, readerNameString);
vtkSMPropertyHelper(settingsProxy, "ReaderDetails")
.Set(numberOfEntries * 3 + 2, readerNameString.c_str());
settingsProxy->UpdateVTKObjects();
numberOfEntries++;
}
| 34.483607 | 100 | 0.63537 | [
"vector"
] |
a6045d3eb74b708ab979df492bb5f2c3c1aeb1bb | 5,746 | cpp | C++ | cplusplus/RCF/src/RCF/HttpConnectFilter.cpp | ASMlover/study | 5878f862573061f94c5776a351e30270dfd9966a | [
"BSD-2-Clause"
] | 22 | 2015-05-18T07:04:36.000Z | 2021-08-02T03:01:43.000Z | cplusplus/RCF/src/RCF/HttpConnectFilter.cpp | ASMlover/study | 5878f862573061f94c5776a351e30270dfd9966a | [
"BSD-2-Clause"
] | 1 | 2017-08-31T22:13:57.000Z | 2017-09-05T15:00:25.000Z | cplusplus/RCF/src/RCF/HttpConnectFilter.cpp | ASMlover/study | 5878f862573061f94c5776a351e30270dfd9966a | [
"BSD-2-Clause"
] | 6 | 2015-06-06T07:16:12.000Z | 2021-07-06T13:45:56.000Z |
//******************************************************************************
// RCF - Remote Call Framework
//
// Copyright (c) 2005 - 2013, Delta V Software. All rights reserved.
// http://www.deltavsoft.com
//
// RCF is distributed under dual licenses - closed source or GPL.
// Consult your particular license for conditions of use.
//
// If you have not purchased a commercial license, you are using RCF
// under GPL terms.
//
// Version: 2.0
// Contact: support <at> deltavsoft.com
//
//******************************************************************************
#include <RCF/HttpConnectFilter.hpp>
#include <RCF/ClientStub.hpp>
#include <RCF/Exception.hpp>
#include <RCF/ThreadLocalData.hpp>
#include <RCF/Tools.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string/predicate.hpp>
namespace RCF {
HttpConnectFilter::HttpConnectFilter() :
mServerAddr(),
mServerPort(0)
{
resetState();
}
HttpConnectFilter::HttpConnectFilter(const std::string serverAddr, int serverPort) :
mServerAddr(serverAddr),
mServerPort(serverPort)
{
resetState();
}
void HttpConnectFilter::resetState()
{
mPassThrough = false;
mOrigWriteBuffers.clear();
mHttpConnectRequest.clear();
mHttpConnectResponse.clear();
mWritePos = 0;
mReadPos = 0;
mReadVector.clear();
}
void HttpConnectFilter::read(
const ByteBuffer &byteBuffer,
std::size_t bytesRequested)
{
RCF_ASSERT(mPassThrough);
mpPostFilter->read(byteBuffer, bytesRequested);
}
void HttpConnectFilter::write(const std::vector<ByteBuffer> &byteBuffers)
{
if (mPassThrough)
{
mpPostFilter->write(byteBuffers);
}
else
{
ClientStub * pClientStub = getTlsClientStubPtr();
RCF_ASSERT(pClientStub);
bool usingProxy = pClientStub->getHttpProxy().size() > 0;
if (!usingProxy)
{
mPassThrough = true;
write(byteBuffers);
}
else
{
mOrigWriteBuffers = byteBuffers;
MemOstream os;
os
<< "CONNECT " << mServerAddr << ":" << mServerPort << " HTTP/1.1\r\n"
<< "Host: " << mServerAddr << ":" << mServerPort << "\r\n"
<< "Proxy-Connection: Keep-Alive\r\n"
<< "\r\n";
mHttpConnectRequest = os.string();
mWritePos = 0;
std::vector<ByteBuffer> writeBuffers;
writeBuffers.push_back( ByteBuffer(
(char * ) mHttpConnectRequest.c_str(),
mHttpConnectRequest.size()));
mpPostFilter->write(writeBuffers);
}
}
}
void HttpConnectFilter::onReadCompleted(const ByteBuffer &byteBuffer)
{
if (mPassThrough)
{
mpPreFilter->onReadCompleted(byteBuffer);
}
else
{
RCF_ASSERT(byteBuffer.getLength() <= mReadVector.size());
mReadPos += byteBuffer.getLength();
mHttpConnectResponse.assign(&mReadVector[0], mReadPos);
std::size_t endPos = mHttpConnectResponse.find("\r\n\r\n");
if (endPos != std::string::npos)
{
std::string http;
std::string httpStatus;
std::string firstLine = mHttpConnectResponse.substr(0, mHttpConnectResponse.find("\r\n"));
MemIstream is(firstLine.c_str(), firstLine.size());
is >> http >> httpStatus;
boost::trim_left(httpStatus);
if (boost::istarts_with(firstLine, "HTTP/") && boost::istarts_with(httpStatus, "200"))
{
// CONNECT is OK.
mPassThrough = true;
mpPostFilter->write(mOrigWriteBuffers);
}
else
{
// Something went wrong.
RCF_THROW( Exception(_RcfError_HttpConnectFailed(firstLine, mHttpConnectResponse)) );
}
}
else
{
// Read some more.
if (mReadPos == mReadVector.size())
{
RCF_THROW( Exception("Invalid HTTP CONNECT response.") );
}
ByteBuffer buffer(&mReadVector[mReadPos], mReadVector.size() - mReadPos);
mpPostFilter->read(buffer, buffer.getLength());
}
}
}
void HttpConnectFilter::onWriteCompleted(std::size_t bytesTransferred)
{
if (mPassThrough)
{
mpPreFilter->onWriteCompleted(bytesTransferred);
}
else
{
mWritePos += bytesTransferred;
if (mWritePos < mHttpConnectRequest.size())
{
std::vector<ByteBuffer> writeBuffers;
writeBuffers.push_back( ByteBuffer(
(char *) (mHttpConnectRequest.c_str() + mWritePos),
mHttpConnectRequest.size() - mWritePos));
mpPostFilter->write(writeBuffers);
}
else
{
// CONNECT request has been sent, now wait for reply.
mReadVector.resize(1024);
ByteBuffer buffer(&mReadVector[0], mReadVector.size());
mpPostFilter->read(buffer, buffer.getLength());
}
}
}
int HttpConnectFilter::getFilterId() const
{
return RcfFilter_Unknown;
}
} // namespace RCF
| 30.402116 | 106 | 0.519144 | [
"vector"
] |
a606242359c5a09af956b6ae2de646825776bde5 | 5,971 | cpp | C++ | CAnEn/src/Config.cpp | codacy-badger/AnalogsEnsemble | f2627096662b32eac8009e6778b8ee6d6ef326c1 | [
"MIT"
] | null | null | null | CAnEn/src/Config.cpp | codacy-badger/AnalogsEnsemble | f2627096662b32eac8009e6778b8ee6d6ef326c1 | [
"MIT"
] | null | null | null | CAnEn/src/Config.cpp | codacy-badger/AnalogsEnsemble | f2627096662b32eac8009e6778b8ee6d6ef326c1 | [
"MIT"
] | null | null | null | /*
* File: Config.cpp
* Author: Guido Cervone <cervone@psu.edu>
* Weiming Hu <cervone@psu.edu>
*
* Created on January 31, 2020, 2:05 PM
*/
#include "Config.h"
#include "Functions.h"
#include <limits>
#include <cmath>
using namespace std;
const bool Config::_CIRCULAR = false;
const double Config::_X = 0.0;
const double Config::_Y = 0.0;
const size_t Config::_TIME = 0;
const string Config::_NAME = "UNDEFINED";
const string Config::_NUM_ANALOGS = "num_analogs";
const string Config::_NUM_SIMS = "num_similarity";
const string Config::_OBS_ID = "observation_id";
const string Config::_NUM_PAR_NA = "max_par_nan";
const string Config::_NUM_FLT_NA = "max_flt_nan";
const string Config::_FLT_RADIUS = "flt_radius";
const string Config::_NUM_NEAREST = "num_nearest";
const string Config::_EXTEND_OBS = "extend_observation";
const string Config::_DISTANCE = "distance";
const string Config::_OPERATION = "operation";
const string Config::_WEIGHTS = "weights";
const string Config::_PREVENT_SEARCH_FUTURE = "prevent_search_future";
const string Config::_SAVE_ANALOGS = "save_analogs";
const string Config::_SAVE_ANALOGS_TIME_IND = "save_analogs_time_index";
const string Config::_SAVE_SIMS = "save_similarity";
const string Config::_SAVE_SIMS_TIME_IND = "save_similarity_time_index";
const string Config::_SAVE_SIMS_STATION_IND = "save_similarity_station_index";
const string Config::_SAVE_SDS = "save_sds";
const string Config::_SAVE_OBS_TIME_IND_TABLE = "save_obs_time_index_table";
const string Config::_SAVE_SEARCH_STATIONS_IND = "save_search_stations_index";
const string Config::_QUICK = "quick";
const string Config::_VERBOSE = "verbose";
const string Config::_DATA = "Data";
const string Config::_PAR_NAMES = "ParameterNames";
const string Config::_CIRCULARS = "ParameterCirculars";
const string Config::_XS = "Xs";
const string Config::_YS = "Ys";
const string Config::_STATION_NAMES = "StationNames";
const string Config::_TIMES = "Times";
const string Config::_FLTS = "FLTs";
const string Config::_DIM_STATIONS = "num_stations";
const string Config::_DIM_TIMES = "num_times";
const string Config::_DIM_TEST_TIMES = "num_test_times";
const string Config::_DIM_SEARCH_TIMES = "num_search_times";
const string Config::_DIM_FLTS = "num_flts";
const string Config::_DIM_PARS = "num_parameters";
const string Config::_DIM_CHARS = "num_chars";
const string Config::_DIM_ANALOGS = "num_analogs";
const string Config::_DIM_SIMS = "num_similarity";
const string Config::_ANALOGS = "analogs";
const string Config::_ANALOGS_TIME_IND = "analogs_time_index";
const string Config::_SIMS = "similarity";
const string Config::_SIMS_TIME_IND = "similarity_time_index";
const string Config::_SIMS_STATION_IND = "similarity_station_index";
const string Config::_SDS = "sds";
const string Config::_TIME_MAPPING = "mapping";
const string Config::_SEARCH_STATIONS_IND = "search_stations";
const string Config::_TEST_TIMES = "test_times";
const string Config::_SEARCH_TIMES = "search_times";
Config::Config() {
reset();
}
Config::Config(const Config & orig) {
*this = orig;
}
Config::~Config() {
}
void
Config::print(ostream & os) {
os << "Configuration details:" << endl
<< "num_analogs: " << num_analogs << endl
<< "num_sims: " << num_sims << endl
<< "obs_var_index: " << obs_var_index << endl
<< "quick_sort: " << (quick_sort ? "true" : "false") << endl
<< "max_par_nan: " << max_par_nan << endl
<< "max_flt_nan: " << max_flt_nan << endl
<< "flt_radius: " << flt_radius << endl
<< "num_nearest: " << num_nearest << endl
<< "distance: " << distance << endl
<< "extend_obs: " << (extend_obs ? "true" : "false") << endl
<< "operation: " << (operation ? "true" : "false") << endl
<< "prevent_search_future: " << (prevent_search_future ? "true" : "false") << endl
<< "save_analogs: " << (save_analogs ? "true" : "false") << endl
<< "save_analogs_time_index: " << (save_analogs_time_index ? "true" : "false") << endl
<< "save_sims: " << (save_sims ? "true" : "false") << endl
<< "save_sims_time_index: " << (save_sims_time_index ? "true" : "false") << endl
<< "save_sims_station_index: " << (save_sims_station_index ? "true" : "false") << endl
<< "save_sds: " << (save_sds ? "true" : "false") << endl
<< "save_obs_time_index_table: " << (save_obs_time_index_table ? "true" : "false") << endl
<< "save_search_stations_index: " << (save_search_stations_index ? "true" : "false") << endl
<< "weights: " << (weights.size() > 0 ? Functions::format(weights) : "[equally weighted with 1s]") << endl
<< "verbose: " << Functions::vtoi(verbose) << " (" << Functions::vtos(verbose) << ")" << endl;
return;
}
int
Config::getVerbose() {
return Functions::vtoi(verbose);
}
void
Config::setVerbose(int i) {
verbose = Functions::itov(i);
return;
}
int
Config::getWorkerVerbose() {
return Functions::vtoi(worker_verbose);
}
void
Config::setWorkerVerbose(int i) {
worker_verbose = Functions::itov(i);
return;
}
void
Config::reset() {
// This is the default configuration setting.
//
// weights are automatically initialized to empty vector
//
num_analogs = 1;
num_sims = 1;
obs_var_index = 0;
quick_sort = false;
max_par_nan = 0;
max_flt_nan = 0;
flt_radius = 1;
num_nearest = 1;
distance = NAN;
extend_obs = true;
operation = false;
prevent_search_future = true;
save_analogs = true;
save_analogs_time_index = false;
save_sims = false;
save_sims_time_index = false;
save_sims_station_index = false;
save_sds = false;
save_obs_time_index_table = false;
save_search_stations_index = false;
verbose = Verbose::Warning;
worker_verbose = Verbose::Warning;
return;
}
| 35.331361 | 118 | 0.672082 | [
"vector"
] |
a6185dec6d61d88c8bdb43d0c81c1283e7a9fef2 | 272 | cpp | C++ | 852-peak-index-in-a-mountain-array/852-peak-index-in-a-mountain-array.cpp | Edith-panda/leetcode | 175b4cbcd25b95b4863d793c876719eabb94dafc | [
"Apache-2.0"
] | null | null | null | 852-peak-index-in-a-mountain-array/852-peak-index-in-a-mountain-array.cpp | Edith-panda/leetcode | 175b4cbcd25b95b4863d793c876719eabb94dafc | [
"Apache-2.0"
] | null | null | null | 852-peak-index-in-a-mountain-array/852-peak-index-in-a-mountain-array.cpp | Edith-panda/leetcode | 175b4cbcd25b95b4863d793c876719eabb94dafc | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
int peakIndexInMountainArray(vector<int>& arr) {
int n = arr.size();
int ans =0;
for(int i=1;i<n-1;i++){
if(arr[i-1] < arr[i] && arr[i] > arr[i+1]) ans =i;
}
return ans;
}
}; | 22.666667 | 62 | 0.444853 | [
"vector"
] |
a618ae1915c156a1b528ebaeef41019218481985 | 5,072 | cpp | C++ | src/Search/DancingLink.cpp | S1xe/Way-to-Algorithm | e666edfb000b3eaef8cc1413f71b035ec4141718 | [
"MIT"
] | 101 | 2015-11-19T02:40:01.000Z | 2017-12-01T13:43:06.000Z | src/Search/DancingLink.cpp | S1xe/Way-to-Algorithm | e666edfb000b3eaef8cc1413f71b035ec4141718 | [
"MIT"
] | 3 | 2019-05-31T14:27:56.000Z | 2021-07-28T04:24:55.000Z | src/Search/DancingLink.cpp | S1xe/Way-to-Algorithm | e666edfb000b3eaef8cc1413f71b035ec4141718 | [
"MIT"
] | 72 | 2016-01-28T15:20:01.000Z | 2017-12-01T13:43:07.000Z | #include "DancingLink.h"
#include "Util.h"
#include <cassert>
#include <cstring>
#include <iostream>
#include <vector>
#define index(i, j, m) ((j) + (i) * (m))
// uplink[i],downlink[i],leftlink[i],rightlink[i]
//分别为节点i的上下左右邻节点下标
static int uplink[MAX], downlink[MAX], leftlink[MAX], rightlink[MAX];
// rowlink[i],collink[i]为节点i的行号和列号
static int rowlink[MAX], collink[MAX];
// 精确覆盖
static int chose[MAX];
// 覆盖元素
static int cover[MAX];
static void DumpGraph(int s[MAX][MAX], int n, int m) {
std::cout << std::endl << "dump -- n: " << n << ", m: " << m << std::endl;
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= m; j++) {
if (s[i][j]) {
int p = index(i, j, m);
std::cout << "s[" << i << "," << j << "]:" << p
<< ", u/d/l/r:" << uplink[p] << "/" << downlink[p] << "/"
<< leftlink[p] << "/" << rightlink[p] << std::endl;
}
}
}
}
static void BuildLink(int s[MAX][MAX], int n, int m) {
std::memset(uplink, 0, MAX * sizeof(int));
std::memset(downlink, 0, MAX * sizeof(int));
std::memset(leftlink, 0, MAX * sizeof(int));
std::memset(rightlink, 0, MAX * sizeof(int));
std::memset(rowlink, 0, MAX * sizeof(int));
std::memset(collink, 0, MAX * sizeof(int));
std::memset(cover, 0, MAX * sizeof(int));
std::memset(chose, 0, MAX * sizeof(int));
// 初始化头节点[0,n]
for (int i = 0; i <= m; i++) {
assert(i >= 0);
assert(i < MAX);
s[0][i] = 1;
rowlink[i] = 0;
collink[i] = i;
uplink[i] = i;
downlink[i] = i;
leftlink[i] = (i > 0) ? (i - 1) : m;
rightlink[i] = (i < m) ? (i + 1) : 0;
}
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
if (!s[i][j])
continue;
int p = index(i, j, m);
assert(p >= 0);
assert(p < MAX);
rowlink[p] = i;
collink[p] = j;
// 找到p下方节点
// k:[0, n]
for (int k = (i + 1 > n) ? 0 : i + 1;; k = (k + 1 > n) ? 0 : k + 1)
if (s[k][j]) {
assert(index(k, j, m) >= 0);
assert(index(k, j, m) < MAX);
downlink[p] = index(k, j, m);
uplink[index(k, j, m)] = p;
break;
}
// 找到p上方节点
// k:[0, n]
for (int k = (i - 1 < 0) ? n : i - 1;; k = (k - 1 < 0) ? n : k - 1)
if (s[k][j]) {
assert(index(k, j, m) >= 0);
assert(index(k, j, m) < MAX);
uplink[p] = index(k, j, m);
downlink[index(k, j, m)] = p;
break;
}
// 找到p右方节点
// k:[1, m]
for (int k = (j + 1 > m) ? 1 : j + 1;; k = (k + 1 > m) ? 1 : k + 1)
if (s[i][k]) {
assert(index(i, k, m) >= 0);
assert(index(i, k, m) < MAX);
rightlink[p] = index(i, k, m);
leftlink[index(i, k, m)] = p;
break;
}
// 找到p左方节点
// k:[1, m]
for (int k = (j - 1 < 1) ? m : j - 1;; k = (k - 1 < 1) ? m : k - 1)
if (s[i][k]) {
assert(index(i, k, m) >= 0);
assert(index(i, k, m) < MAX);
leftlink[p] = index(i, k, m);
rightlink[index(i, k, m)] = p;
break;
}
} // for
}
static void Remove(int i) {
//在头节点的一行删除节点i
leftlink[rightlink[i]] = leftlink[i];
rightlink[leftlink[i]] = rightlink[i];
cover[collink[i]] = 1;
//所有包含i的子集
for (int p = downlink[i]; p != i; p = downlink[p]) {
//在列上删除子集上除了i的其他节点
for (int q = rightlink[p]; q != p; q = rightlink[q]) {
uplink[downlink[q]] = uplink[q];
downlink[uplink[q]] = downlink[q];
}
}
}
static void Resume(int i) {
//在头节点的一行恢复节点i
leftlink[rightlink[i]] = i;
rightlink[leftlink[i]] = i;
cover[collink[i]] = 0;
//所有包含i的子集
for (int p = uplink[i]; p != i; p = uplink[p]) {
//在列上恢复子集上除了i的其他节点
for (int q = rightlink[p]; q != p; q = rightlink[q]) {
uplink[downlink[q]] = q;
downlink[uplink[q]] = q;
}
}
}
static bool Dance(int x, int s[MAX][MAX], int n, int m) {
//头节点一行的所有元素都被删除
//只剩0节点
if (leftlink[0] == 0) {
return true;
}
//已经被子集覆盖
//不再重复操作
if (cover[collink[x]]) {
return Dance(x + 1, s, n, m);
}
Remove(index(0, x, m));
DumpGraph(s, n, m);
//遍历所有包含x的子集
for (int p = downlink[index(0, x, m)]; p != index(0, x, m); p = downlink[p]) {
//选择子集rowlink[p]
chose[rowlink[p]] = 1;
//删除包含子集rowlink[p]所有元素的子集
for (int q = rightlink[p]; q != p; q = rightlink[q])
Remove(index(0, collink[q], m));
DumpGraph(s, n, m);
//下一个元素x+1
if (Dance(x + 1, s, n, m))
return true;
//排除子集rowlink[p]
chose[rowlink[p]] = 0;
//恢复链表
for (int q = leftlink[p]; q != p; q = leftlink[q])
Resume(index(0, collink[q], m));
DumpGraph(s, n, m);
}
Resume(index(0, x, m));
DumpGraph(s, n, m);
return false;
}
std::pair<bool, std::vector<int>> DancingLink(int n, int m, int s[MAX][MAX]) {
BuildLink(s, n, m);
DumpGraph(s, n, m);
bool dance = Dance(1, s, n, m);
std::vector<int> vec;
std::transform(chose, chose + n + 1, std::back_inserter(vec), [](const int &v) { return v; });
return std::make_pair(dance, vec);
}
| 26.14433 | 96 | 0.479495 | [
"vector",
"transform"
] |
a618d20b80b99b73f9e93338721c68c71ab461d1 | 15,339 | cpp | C++ | FEBioSource2.9/FEBioMech/FERigidWallInterface.cpp | wzaylor/FEBio_MCLS | f1052733c31196544fb0921aa55ffa5167a25f98 | [
"Intel"
] | 1 | 2021-08-24T08:37:21.000Z | 2021-08-24T08:37:21.000Z | FEBioSource2.9/FEBioMech/FERigidWallInterface.cpp | wzaylor/FEBio_MCLS | f1052733c31196544fb0921aa55ffa5167a25f98 | [
"Intel"
] | null | null | null | FEBioSource2.9/FEBioMech/FERigidWallInterface.cpp | wzaylor/FEBio_MCLS | f1052733c31196544fb0921aa55ffa5167a25f98 | [
"Intel"
] | 1 | 2021-03-15T08:22:06.000Z | 2021-03-15T08:22:06.000Z | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2019 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FERigidWallInterface.h"
#include "FECore/FENNQuery.h"
#include <FECore/FEModel.h>
#include "FECore/FEGlobalMatrix.h"
#include "FECore/log.h"
#include <FEBioMech/FEElasticShellDomainOld.h>
//-----------------------------------------------------------------------------
// Define sliding interface parameters
BEGIN_PARAMETER_LIST(FERigidWallInterface, FEContactInterface)
ADD_PARAMETER(m_blaugon , FE_PARAM_BOOL , "laugon" );
ADD_PARAMETER(m_atol , FE_PARAM_DOUBLE, "tolerance" );
ADD_PARAMETER(m_eps , FE_PARAM_DOUBLE, "penalty" );
ADD_PARAMETER(m_d , FE_PARAM_DOUBLE, "offset" );
ADD_PARAMETERV(m_plane.a, FE_PARAM_DOUBLE, 4, "plane" );
END_PARAMETER_LIST();
///////////////////////////////////////////////////////////////////////////////
// FERigidWallSurface
///////////////////////////////////////////////////////////////////////////////
FERigidWallSurface::FERigidWallSurface(FEModel* pfem) : FESurface(&pfem->GetMesh())
{
m_NQ.Attach(this);
// I want to use the FEModel class for this, but don't know how
DOFS& dofs = pfem->GetDOFS();
m_dofX = dofs.GetDOF("x");
m_dofY = dofs.GetDOF("y");
m_dofZ = dofs.GetDOF("z");
}
//-----------------------------------------------------------------------------
//! Creates a surface for use with a sliding interface. All surface data
//! structures are allocated.
//! Note that it is assumed that the element array is already created
//! and initialized.
bool FERigidWallSurface::Init()
{
// always intialize base class first!
if (FESurface::Init() == false) return false;
// get the number of nodes
int nn = Nodes();
// allocate other surface data
m_gap.assign(nn, 0); // gap funtion
m_nu.resize(nn); // node normal
m_pme.assign(nn, static_cast<FESurfaceElement*>(0)); // penetrated master element
m_rs.resize(nn); // natural coords of projected slave node on master element
m_rsp.resize(nn);
m_Lm.assign(nn, 0);
m_M.resize(nn);
m_Lt.resize(nn);
m_off.assign(nn, 0.0);
m_eps.assign(nn, 1.0);
// we calculate the gap offset values
// This value is used to take the shell thickness into account
// note that we force rigid shells to have zero thickness
FEMesh& m = *m_pMesh;
vector<double> tag(m.Nodes());
zero(tag);
for (int nd=0; nd<m.Domains(); ++nd)
{
FEElasticShellDomainOld* psd = dynamic_cast<FEElasticShellDomainOld*>(&m.Domain(nd));
if (psd)
{
for (int i=0; i<psd->Elements(); ++i)
{
FEShellElement& el = psd->Element(i);
int n = el.Nodes();
for (int j=0; j<n; ++j) tag[el.m_node[j]] = 0.5*el.m_h0[j];
}
}
}
for (int i=0; i<nn; ++i) m_off[i] = tag[NodeIndex(i)];
return true;
}
//-----------------------------------------------------------------------------
//!
vec3d FERigidWallSurface::traction(int inode)
{
vec3d t(0,0,0);
FESurfaceElement* pe = m_pme[inode];
if (pe)
{
FESurfaceElement& el = *pe;
double Tn = m_Lm[inode];
double T1 = m_Lt[inode][0];
double T2 = m_Lt[inode][1];
double r = m_rs[inode][0];
double s = m_rs[inode][1];
vec3d tn = m_nu[inode]*Tn, tt;
vec3d e[2];
ContraBaseVectors0(el, r, s, e);
tt = e[0]*T1 + e[1]*T2;
t = tn + tt;
}
return t;
}
//-----------------------------------------------------------------------------
void FERigidWallSurface::UpdateNormals()
{
int i, j, jp1, jm1;
int N = Nodes();
int NE = Elements();
for (i=0; i<N; ++i) m_nu[i] = vec3d(0,0,0);
vec3d y[FEElement::MAX_NODES], e1, e2;
for (i=0; i<NE; ++i)
{
FESurfaceElement& el = Element(i);
int ne = el.Nodes();
for (j=0; j<ne; ++j) y[j] = Node(el.m_lnode[j]).m_rt;
for (j=0; j<ne; ++j)
{
jp1 = (j+1)%ne;
jm1 = (j+ne-1)%ne;
e1 = y[jp1] - y[j];
e2 = y[jm1] - y[j];
m_nu[el.m_lnode[j]] -= e1 ^ e2;
}
}
for (i=0; i<N; ++i) m_nu[i].unit();
}
//-----------------------------------------------------------------------------
void FERigidWallSurface::Serialize(DumpStream &ar)
{
FESurface::Serialize(ar);
if (ar.IsSaving())
{
ar << m_gap;
ar << m_nu;
ar << m_rs;
ar << m_rsp;
ar << m_Lm;
ar << m_M;
ar << m_Lt;
ar << m_off;
ar << m_eps;
}
else
{
ar >> m_gap;
ar >> m_nu;
ar >> m_rs;
ar >> m_rsp;
ar >> m_Lm;
ar >> m_M;
ar >> m_Lt;
ar >> m_off;
ar >> m_eps;
zero(m_pme);
}
}
//-----------------------------------------------------------------------------
void FERigidWallSurface::UnpackLM(FEElement& el, vector<int>& lm)
{
int N = el.Nodes();
lm.resize(N*3);
for (int i=0; i<N; ++i)
{
int n = el.m_node[i];
FENode& node = m_pMesh->Node(n);
vector<int>& id = node.m_ID;
lm[3*i ] = id[m_dofX];
lm[3*i+1] = id[m_dofY];
lm[3*i+2] = id[m_dofZ];
}
}
///////////////////////////////////////////////////////////////////////////////
// FERigidWallInterface
///////////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
//! constructor
FERigidWallInterface::FERigidWallInterface(FEModel* pfem) : FEContactInterface(pfem), m_ss(pfem), m_plane(pfem)
{
static int count = 1;
SetID(count++);
m_eps = 0;
m_atol = 0;
m_d = 0.0;
};
//-----------------------------------------------------------------------------
//! Initializes the rigid wall interface data
bool FERigidWallInterface::Init()
{
// create the surface
if (m_ss.Init() == false) return false;
// initialize rigid surface
m_plane.Init();
return true;
}
//-----------------------------------------------------------------------------
//! build the matrix profile for use in the stiffness matrix
void FERigidWallInterface::BuildMatrixProfile(FEGlobalMatrix& K)
{
FEModel& fem = *GetFEModel();
// get the DOFS
const int dof_X = fem.GetDOFIndex("x");
const int dof_Y = fem.GetDOFIndex("y");
const int dof_Z = fem.GetDOFIndex("z");
const int dof_RU = fem.GetDOFIndex("Ru");
const int dof_RV = fem.GetDOFIndex("Rv");
const int dof_RW = fem.GetDOFIndex("Rw");
vector<int> lm(6);
for (int j=0; j<m_ss.Nodes(); ++j)
{
if (m_ss.m_gap[j] >= 0)
{
lm[0] = m_ss.Node(j).m_ID[dof_X];
lm[1] = m_ss.Node(j).m_ID[dof_Y];
lm[2] = m_ss.Node(j).m_ID[dof_Z];
lm[3] = m_ss.Node(j).m_ID[dof_RU];
lm[4] = m_ss.Node(j).m_ID[dof_RV];
lm[5] = m_ss.Node(j).m_ID[dof_RW];
K.build_add(lm);
}
}
}
//-----------------------------------------------------------------------------
void FERigidWallInterface::Activate()
{
// don't forget to call the base class
FEContactInterface::Activate();
// project slave surface onto master surface
ProjectSurface(m_ss);
}
//-----------------------------------------------------------------------------
//! Projects the slave surface onto the master plane
void FERigidWallInterface::ProjectSurface(FERigidWallSurface& ss)
{
vec3d r, q;
// surface normal
vec3d np;
// loop over all slave nodes
for (int i=0; i<m_ss.Nodes(); ++i)
{
// get the nodal position
r = m_ss.Node(i).m_rt;
// project this node onto the plane
q = m_plane.Project(r);
// get the local surface normal
np = m_plane.Normal(q);
// calculate offset
q += np*m_d;
// the slave normal is set to the master element normal
m_ss.m_nu[i] = np;
// calculate initial gap
m_ss.m_gap[i] = -(np*(r - q)) + m_ss.m_off[i];
}
}
//-----------------------------------------------------------------------------
//! Updates rigid wall data
void FERigidWallInterface::Update(int niter, const FETimeInfo& tp)
{
// project slave surface onto master surface
ProjectSurface(m_ss);
}
//-----------------------------------------------------------------------------
void FERigidWallInterface::Residual(FEGlobalVector& R, const FETimeInfo& tp)
{
int j, k, m, n;
int nseln;
double *Gr, *Gs;
// jacobian
double detJ;
vec3d dxr, dxs;
vec3d rt[FEElement::MAX_NODES], r0[FEElement::MAX_NODES];
double* w;
// normal force
double tn;
// element contact force vector
// note that this assumes that the element to which the integration node
// connects is a four noded quadrilateral
vector<double> fe(3);
// the lm array for this force vector
vector<int> lm(3);
// the en array
vector<int> en(1);
vector<int> sLM;
// penalty value
double pen = m_eps, eps;
// loop over all slave facets
int ne = m_ss.Elements();
for (j=0; j<ne; ++j)
{
// get the slave element
FESurfaceElement& sel = m_ss.Element(j);
// get the element's LM vector
m_ss.UnpackLM(sel, sLM);
nseln = sel.Nodes();
for (int i=0; i<nseln; ++i)
{
r0[i] = m_ss.GetMesh()->Node(sel.m_node[i]).m_r0;
rt[i] = m_ss.GetMesh()->Node(sel.m_node[i]).m_rt;
}
w = sel.GaussWeights();
// loop over slave element nodes (which are the integration points as well)
for (n=0; n<nseln; ++n)
{
Gr = sel.Gr(n);
Gs = sel.Gs(n);
m = sel.m_lnode[n];
// see if this node's constraint is active
// that is, if it has a master element associated with it
// if (ss.Lm[m] >= 0)
{
// calculate jacobian
dxr = dxs = vec3d(0,0,0);
for (k=0; k<nseln; ++k)
{
dxr.x += Gr[k]*r0[k].x;
dxr.y += Gr[k]*r0[k].y;
dxr.z += Gr[k]*r0[k].z;
dxs.x += Gs[k]*r0[k].x;
dxs.y += Gs[k]*r0[k].y;
dxs.z += Gs[k]*r0[k].z;
}
detJ = (dxr ^ dxs).norm();
// get slave node normal force
eps = pen*m_ss.m_eps[m];
tn = m_ss.m_Lm[m] + eps*m_ss.m_gap[m];
tn = MBRACKET(tn);
// get the slave node normal
vec3d& nu = m_ss.m_nu[m];
// calculate force vector
fe[0] = detJ*w[n]*tn*nu.x;
fe[1] = detJ*w[n]*tn*nu.y;
fe[2] = detJ*w[n]*tn*nu.z;
// fill the lm array
lm[0] = sLM[n*3 ];
lm[1] = sLM[n*3+1];
lm[2] = sLM[n*3+2];
// fill the en array
en[0] = sel.m_node[n];
// assemble into global force vector
R.Assemble(en, lm, fe);
}
}
}
}
//-----------------------------------------------------------------------------
//! This function calculates the stiffness contribution for the rigid wall
//! interface.
//! \todo I think there are a couple of stiffness terms missing in this formulation
void FERigidWallInterface::StiffnessMatrix(FESolver* psolver, const FETimeInfo& tp)
{
int j, k, l, n, m;
int nseln, ndof;
matrix ke;
vector<int> lm(3);
vector<int> en(1);
double *Gr, *Gs, *w;
vec3d rt[FEElement::MAX_NODES], r0[FEElement::MAX_NODES];
double detJ, tn;
vec3d dxr, dxs;
double N[3];
double gap, Lm;
vector<int> sLM;
// penalty value
double pen = m_eps, eps;
// loop over all slave elements
int ne = m_ss.Elements();
for (j=0; j<ne; ++j)
{
FESurfaceElement& se = m_ss.Element(j);
// get the element's LM vector
m_ss.UnpackLM(se, sLM);
nseln = se.Nodes();
for (int i=0; i<nseln; ++i)
{
r0[i] = m_ss.GetMesh()->Node(se.m_node[i]).m_r0;
rt[i] = m_ss.GetMesh()->Node(se.m_node[i]).m_rt;
}
w = se.GaussWeights();
// loop over all integration points (that is nodes)
for (n=0; n<nseln; ++n)
{
Gr = se.Gr(n);
Gs = se.Gs(n);
m = se.m_lnode[n];
// see if this node's constraint is active
// that is, if it has a master element associated with it
// if (ss.Lm[m] >= 0)
{
// calculate jacobian
dxr = dxs = vec3d(0,0,0);
for (k=0; k<nseln; ++k)
{
dxr.x += Gr[k]*r0[k].x;
dxr.y += Gr[k]*r0[k].y;
dxr.z += Gr[k]*r0[k].z;
dxs.x += Gs[k]*r0[k].x;
dxs.y += Gs[k]*r0[k].y;
dxs.z += Gs[k]*r0[k].z;
}
detJ = (dxr ^ dxs).norm();
// slave gap
gap = m_ss.m_gap[m];
// lagrange multiplier
Lm = m_ss.m_Lm[m];
// get slave node normal force
eps = pen*m_ss.m_eps[m];
tn = m_ss.m_Lm[m] + eps*m_ss.m_gap[m];
tn = MBRACKET(tn);
// get the slave node normal
vec3d& nu = m_ss.m_nu[m];
// set up the N vector
N[0] = nu.x;
N[1] = nu.y;
N[2] = nu.z;
ndof = 3;
// fill stiffness matrix
// TODO: I don't think this is correct, since
// if the rigid wall is not a plance, some terms
// are probably missing
ke.resize(ndof, ndof);
for (k=0; k<ndof; ++k)
for (l=0; l<ndof; ++l)
ke[k][l] = w[n]*detJ*eps*HEAVYSIDE(Lm+eps*gap)*N[k]*N[l];
// create lm array
lm[0] = sLM[n*3 ];
lm[1] = sLM[n*3+1];
lm[2] = sLM[n*3+2];
// create the en array
en[0] = se.m_node[n];
// assemble stiffness matrix
psolver->AssembleStiffness(en, lm, ke);
}
}
}
}
//-----------------------------------------------------------------------------
bool FERigidWallInterface::Augment(int naug, const FETimeInfo& tp)
{
// make sure we need to augment
if (!m_blaugon) return true;
int i;
double Lm;
bool bconv = true;
// penalty value
double pen = m_eps, eps;
// calculate initial norms
double normL0 = 0;
for (i=0; i<m_ss.Nodes(); ++i) normL0 += m_ss.m_Lm[i]*m_ss.m_Lm[i];
normL0 = sqrt(normL0);
// update Lagrange multipliers and calculate current norms
double normL1 = 0;
double normgc = 0;
int N = 0;
for (i=0; i<m_ss.Nodes(); ++i)
{
// update Lagrange multipliers
eps = pen*m_ss.m_eps[i];
Lm = m_ss.m_Lm[i] + eps*m_ss.m_gap[i];
Lm = MBRACKET(Lm);
normL1 += Lm*Lm;
if (m_ss.m_gap[i] > 0)
{
normgc += m_ss.m_gap[i]*m_ss.m_gap[i];
++N;
}
}
if (N==0) N = 1;
normL1 = sqrt(normL1);
normgc = sqrt(normgc / N);
// check convergence of constraints
felog.printf(" rigid wall interface # %d\n", GetID());
felog.printf(" CURRENT REQUIRED\n");
double pctn = 0;
if (fabs(normL1) > 1e-10) pctn = fabs((normL1 - normL0)/normL1);
felog.printf(" normal force : %15le %15le\n", pctn, m_atol);
felog.printf(" gap function : %15le ***\n", normgc);
if (pctn >= m_atol)
{
bconv = false;
for (i=0; i<m_ss.Nodes(); ++i)
{
// update Lagrange multipliers
eps = pen*m_ss.m_eps[i];
Lm = m_ss.m_Lm[i] + eps*m_ss.m_gap[i];
m_ss.m_Lm[i] = MBRACKET(Lm);
}
}
return bconv;
}
//-----------------------------------------------------------------------------
void FERigidWallInterface::Serialize(DumpStream &ar)
{
FEContactInterface::Serialize(ar);
m_ss.Serialize(ar);
m_plane.Serialize(ar);
}
| 24.117925 | 111 | 0.563596 | [
"vector"
] |
98b435b05aeedf1175628ecf007edce4c3b1f0a8 | 2,034 | hpp | C++ | ql/methods/finitedifferences/meshers/uniformgridmesher.hpp | jiangjiali/QuantLib | 37c98eccfa18a95acb1e98b276831641be92b38e | [
"BSD-3-Clause"
] | 3,358 | 2015-12-18T02:56:17.000Z | 2022-03-31T02:42:47.000Z | ql/methods/finitedifferences/meshers/uniformgridmesher.hpp | jiangjiali/QuantLib | 37c98eccfa18a95acb1e98b276831641be92b38e | [
"BSD-3-Clause"
] | 965 | 2015-12-21T10:35:28.000Z | 2022-03-30T02:47:00.000Z | ql/methods/finitedifferences/meshers/uniformgridmesher.hpp | jiangjiali/QuantLib | 37c98eccfa18a95acb1e98b276831641be92b38e | [
"BSD-3-Clause"
] | 1,663 | 2015-12-17T17:45:38.000Z | 2022-03-31T07:58:29.000Z | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2008 Andreas Gaida
Copyright (C) 2008 Ralph Schreyer
Copyright (C) 2008 Klaus Spanderen
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
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 license for more details.
*/
/*! \file uniformgridmesher.hpp
\brief uniform grid mesher
*/
#ifndef quantlib_uniform_grid_mesher_hpp
#define quantlib_uniform_grid_mesher_hpp
#include <ql/methods/finitedifferences/meshers/fdmmesher.hpp>
#include <ql/methods/finitedifferences/operators/fdmlinearopiterator.hpp>
#include <memory>
namespace QuantLib {
class UniformGridMesher : public FdmMesher {
public:
UniformGridMesher(
const ext::shared_ptr<FdmLinearOpLayout> & index,
const std::vector<std::pair<Real, Real> > & boundaries);
Real dplus(const FdmLinearOpIterator&, Size direction) const override {
return dx_[direction];
}
Real dminus(const FdmLinearOpIterator&, Size direction) const override {
return dx_[direction];
}
Real location(const FdmLinearOpIterator& iter, Size direction) const override {
return locations_[direction][iter.coordinates()[direction]];
}
Disposable<Array> locations(Size direction) const override;
private:
std::unique_ptr<Real[]> dx_;
std::vector<std::vector<Real> > locations_;
};
}
#endif
| 33.344262 | 87 | 0.711898 | [
"vector"
] |
98b67be0c98497701304534830ae67ffa3fc5c68 | 3,314 | cpp | C++ | editor/editor_core/gui/gui.cpp | ValtoForks/EtherealEngine | ab769803dcd71a61c2805afd259959b62fcdc1ff | [
"BSD-2-Clause"
] | 791 | 2016-11-04T14:13:41.000Z | 2022-03-20T20:47:31.000Z | editor/editor_core/gui/gui.cpp | ValtoForks/EtherealEngine | ab769803dcd71a61c2805afd259959b62fcdc1ff | [
"BSD-2-Clause"
] | 28 | 2016-12-01T05:59:30.000Z | 2021-03-20T09:49:26.000Z | editor/editor_core/gui/gui.cpp | ValtoForks/EtherealEngine | ab769803dcd71a61c2805afd259959b62fcdc1ff | [
"BSD-2-Clause"
] | 151 | 2016-12-21T09:44:43.000Z | 2022-03-31T13:42:18.000Z | #include "gui.h"
#include <vector>
namespace gui
{
static std::vector<std::shared_ptr<void>> s_textures;
void Image(texture_info info, const ImVec2& _size, const ImVec2& _uv0 /*= ImVec2(0.0f, 0.0f) */,
const ImVec2& _uv1 /*= ImVec2(1.0f, 1.0f) */,
const ImVec4& _tintCol /*= ImVec4(1.0f, 1.0f, 1.0f, 1.0f) */,
const ImVec4& _borderCol /*= ImVec4(0.0f, 0.0f, 0.0f, 0.0f) */)
{
s_textures.push_back(info.texture);
ImVec2 uv0 = _uv0;
ImVec2 uv1 = _uv1;
if(info.texture && info.is_rt)
{
if(info.is_origin_bl)
{
uv0 = {0.0f, 1.0f};
uv1 = {1.0f, 0.0f};
}
}
ImGui::Image(info.texture.get(), _size, uv0, uv1, _tintCol, _borderCol);
}
bool ImageButton(texture_info info, const ImVec2& _size, const ImVec2& _uv0 /*= ImVec2(0.0f, 0.0f) */,
const ImVec2& _uv1 /*= ImVec2(1.0f, 1.0f) */, int _framePadding /*= -1 */,
const ImVec4& _bgCol /*= ImVec4(0.0f, 0.0f, 0.0f, 0.0f) */,
const ImVec4& _tintCol /*= ImVec4(1.0f, 1.0f, 1.0f, 1.0f) */)
{
s_textures.push_back(info.texture);
ImVec2 uv0 = _uv0;
ImVec2 uv1 = _uv1;
if(info.texture && info.is_rt)
{
if(info.is_origin_bl)
{
uv0 = {0.0f, 1.0f};
uv1 = {1.0f, 0.0f};
}
}
return ImGui::ImageButton(info.texture.get(), _size, uv0, uv1, _framePadding, _bgCol, _tintCol);
}
bool ImageButtonEx(texture_info info, const ImVec2& size, const char* tooltip, bool selected, bool enabled)
{
s_textures.push_back(info.texture);
return ImGui::ImageButtonEx(info.texture.get(), size, tooltip, selected, enabled);
}
void ImageWithAspect(texture_info info, const ImVec2& texture_size, const ImVec2& size, const ImVec2& _uv0,
const ImVec2& _uv1, const ImVec4& tint_col, const ImVec4& border_col)
{
s_textures.push_back(info.texture);
ImVec2 uv0 = _uv0;
ImVec2 uv1 = _uv1;
if(info.texture && info.is_rt)
{
if(info.is_origin_bl)
{
uv0 = {0.0f, 1.0f};
uv1 = {1.0f, 0.0f};
}
}
return ImGui::ImageWithAspect(info.texture.get(), texture_size, size, uv0, uv1, tint_col, border_col);
}
int ImageButtonWithAspectAndLabel(texture_info info, const ImVec2& texture_size, const ImVec2& size,
const ImVec2& _uv0, const ImVec2& _uv1, bool selected, bool* edit_label,
const char* label, char* buf, size_t buf_size,
ImGuiInputTextFlags flags /*= 0*/)
{
s_textures.push_back(info.texture);
ImVec2 uv0 = _uv0;
ImVec2 uv1 = _uv1;
if(info.texture && info.is_rt)
{
if(info.is_origin_bl)
{
uv0 = {0.0f, 1.0f};
uv1 = {1.0f, 0.0f};
}
}
return ImGui::ImageButtonWithAspectAndLabel(info.texture.get(), texture_size, size, uv0, uv1, selected,
edit_label, label, buf, buf_size, flags);
}
void CleanupTextures()
{
s_textures.clear();
}
bool ImageButtonWithAspectAndTextDOWN(texture_info info, const std::string& name, const ImVec2& texture_size,
const ImVec2& image_size, const ImVec2& _uv0, const ImVec2& _uv1,
int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col)
{
s_textures.push_back(info.texture);
ImVec2 uv0 = _uv0;
ImVec2 uv1 = _uv1;
if(info.texture && info.is_rt)
{
if(info.is_origin_bl)
{
uv0 = {0.0f, 1.0f};
uv1 = {1.0f, 0.0f};
}
}
return ImGui::ImageButtonWithAspectAndTextDOWN(info.texture.get(), name, texture_size, image_size, uv0,
uv1, frame_padding, bg_col, tint_col);
}
}
| 27.616667 | 109 | 0.664756 | [
"vector"
] |
98b7d26158918ff9cf7b857af3df3de29e9a4501 | 23,296 | cpp | C++ | src/caffe/openpose/layers/oPVideoLayer.cpp | CMU-Perceptual-Computing-Lab/openpose_caffe_train | 40c03c8cd050dce7e70834f5dfb796427dea2ebc | [
"MIT-CMU"
] | 26 | 2019-10-02T10:39:12.000Z | 2021-12-08T07:27:50.000Z | src/caffe/openpose/layers/oPVideoLayer.cpp | CMU-Perceptual-Computing-Lab/openpose_caffe_train | 40c03c8cd050dce7e70834f5dfb796427dea2ebc | [
"MIT-CMU"
] | 6 | 2019-11-08T02:44:42.000Z | 2021-03-06T05:13:24.000Z | src/caffe/openpose/layers/oPVideoLayer.cpp | CMU-Perceptual-Computing-Lab/openpose_caffe_train | 40c03c8cd050dce7e70834f5dfb796427dea2ebc | [
"MIT-CMU"
] | 22 | 2019-10-11T02:36:41.000Z | 2022-03-18T01:35:12.000Z | #ifdef USE_OPENCV
#include <opencv2/core/core.hpp>
#endif // USE_OPENCV
#include <stdint.h>
#include <vector>
#include "caffe/data_transformer.hpp"
#include "caffe/layers/data_layer.hpp"
#include "caffe/util/benchmark.hpp"
// OpenPose: added
#include <chrono>
#include <numeric> // std::accumulate
#include <stdexcept>
#include "caffe/util/io.hpp" // DecodeDatum, DecodeDatumNative
#include "caffe/openpose/getLine.hpp"
#include "caffe/openpose/layers/oPVideoLayer.hpp"
// OpenPose: added end
#include <iostream>
using namespace std;
namespace caffe {
template <typename Dtype>
OPVideoLayer<Dtype>::OPVideoLayer(const LayerParameter& param) :
BasePrefetchingDataLayer<Dtype>(param),
// offset_(),
offsetBackground(), // OpenPose: added
// offsetSecond(), // OpenPose: added
op_transform_param_(param.op_transform_param()) // OpenPose: added
{
// OpenPose: commented
// db_.reset(db::GetDB(param.data_param().backend()));
// db_->Open(param.data_param().source(), db::READ);
// cursor_.reset(db_->NewCursor());
// OpenPose: commented end
// OpenPose: added
// Set mSources, mModels, and mProbabilites
mSources = split(param.op_transform_param().sources(), DELIMITER);
mModels = split(param.op_transform_param().models(), DELIMITER);
splitFloating(mProbabilities, param.op_transform_param().probabilities(), DELIMITER);
// If only 1 model specified --> repeat for each source
if (mModels.size() == 1 && mSources.size() > 1)
mModels.resize(mSources.size(), mModels[0]);
// Sanity checks
for (const auto& probability : mProbabilities)
if (probability < 0 || probability > 1)
throw std::runtime_error{"Some probabilities is not in the range [0,1]"
+ getLine(__LINE__, __FUNCTION__, __FILE__)};
if (mSources.size() != mProbabilities.size())
throw std::runtime_error{"Error: mSources.size() != mProbabilities.size()"
+ getLine(__LINE__, __FUNCTION__, __FILE__)};
if (mSources.size() != mModels.size())
throw std::runtime_error{"Error: mSources.size() != mModels.size()"
+ getLine(__LINE__, __FUNCTION__, __FILE__)};
// Initialize cursor and DB
mDbs.resize(mSources.size());
mCursors.resize(mSources.size());
for (auto i = 0u ; i < mCursors.size() ; i++)
{
mDbs[i].reset(db::GetDB(param.data_param().backend()));
mDbs[i]->Open(mSources[i], db::READ);
mCursors[i].reset(mDbs[i]->NewCursor()); // OpenPose: commented
}
// Initialize other variables
mCounterTimer.resize(mSources.size(), 0);
mCounterTimerBkg = 0;
mOffsets.resize(mSources.size(), 0);
// Set up negatives DB
if (!op_transform_param_.source_background().empty())
{
backgroundDb = true;
onlyBackgroundProbability = op_transform_param_.prob_only_background();
CHECK_GE(onlyBackgroundProbability, 0.f);
CHECK_LT(onlyBackgroundProbability, 1.f);
dbBackground.reset(db::GetDB(DataParameter_DB::DataParameter_DB_LMDB));
dbBackground->Open(op_transform_param_.source_background(), db::READ);
cursorBackground.reset(dbBackground->NewCursor());
}
else
{
backgroundDb = false;
onlyBackgroundProbability = 0.f;
}
// Sanity checks
const auto totalProbabilities = std::accumulate(mProbabilities.begin(), mProbabilities.end(), 0.f);
if (std::abs(totalProbabilities + onlyBackgroundProbability - 1.f) > 1e-6)
throw std::runtime_error{
"Probabilities sum up something different to 100%: "
+ std::to_string(100*(totalProbabilities + onlyBackgroundProbability))
+ getLine(__LINE__, __FUNCTION__, __FILE__)};
// Timer
mDuration = 0;
mCounter = 0;
// Input Type
if(param.op_transform_param().input_type().size()){
mInputType = split(param.op_transform_param().input_type(), DELIMITER);
if(mInputType.size() != mDbs.size()) throw std::runtime_error("Input Type error");
}
mFrameSize = param.op_transform_param().frame_size();
// OpenPose: added end
}
template <typename Dtype>
OPVideoLayer<Dtype>::~OPVideoLayer()
{
this->StopInternalThread();
}
template <typename Dtype>
void OPVideoLayer<Dtype>::DataLayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top)
{
const int batch_size = this->layer_param_.data_param().batch_size();
const int frame_size = this->mFrameSize;
// Read a data point, and use it to initialize the top blob.
Datum datum;
// datum.ParseFromString(cursor_->value()); // OpenPose: commented
datum.ParseFromString(mCursors[0]->value()); // OpenPose: added
// OpenPose: added
mOPDataTransformers.resize(mSources.size());
for (auto i = 0u ; i < mOPDataTransformers.size() ; i++)
mOPDataTransformers[i].reset(
new OPDataTransformer<Dtype>(op_transform_param_, this->phase_, mModels[i], mInputType[i]));
// mOPDataTransformer->InitRand();
// Force color
bool forceColor = this->layer_param_.data_param().force_encoded_color();
if ((forceColor && DecodeDatum(&datum, true)) || DecodeDatumNative(&datum))
LOG(INFO) << "Decoding Datum";
// Multi Image shape (Data layer is ([frame*batch * 3 * 368 * 38])) - Set Data size
const int width = this->phase_ != TRAIN ? datum.width() : this->layer_param_.op_transform_param().crop_size_x();
const int height = this->phase_ != TRAIN ? datum.height() : this->layer_param_.op_transform_param().crop_size_y();
std::vector<int> topShape{batch_size * frame_size, 3, height, width};
top[0]->Reshape(topShape);
// Set output and prefetch size
this->transformed_data_.Reshape(topShape[0], topShape[1], topShape[2], topShape[3]);
for (int i = 0; i < this->prefetch_.size(); ++i)
this->prefetch_[i]->data_.Reshape(topShape);
LOG(INFO) << "Video shape: " << topShape[0] << ", " << topShape[1] << ", " << topShape[2] << ", " << topShape[3];
// Labels
if (this->output_labels_)
{
const int stride = this->layer_param_.op_transform_param().stride();
const int numberChannels = this->mOPDataTransformers[0]->getNumberChannels();
for (auto i = 0u ; i < this->mOPDataTransformers.size() ; i++)
CHECK(this->mOPDataTransformers[i]->getNumberChannels() == this->mOPDataTransformers[0]->getNumberChannels())
<< "Are you using compatible models? " << this->mOPDataTransformers[i]->getNumberChannels()
<< " vs. " << this->mOPDataTransformers[0]->getNumberChannels()
<< " channels (models " << mModels[i] << " vs. " << mModels[0] << ")";
std::vector<int> labelShape{batch_size * frame_size, numberChannels, height/stride, width/stride};
top[1]->Reshape(labelShape);
for (int i = 0; i < this->prefetch_.size(); ++i)
this->prefetch_[i]->label_.Reshape(labelShape);
this->transformed_label_.Reshape(labelShape[0], labelShape[1], labelShape[2], labelShape[3]);
LOG(INFO) << "Label shape: " << labelShape[0] << ", " << labelShape[1] << ", " << labelShape[2] << ", " << labelShape[3];
}
else
throw std::runtime_error{"output_labels_ must be set to true" + getLine(__LINE__, __FUNCTION__, __FILE__)};
}
template <typename Dtype>
bool OPVideoLayer<Dtype>::Skip(const int index)
{
int size = Caffe::solver_count();
int rank = Caffe::solver_rank();
bool keep = (mOffsets[index] % size) == rank ||
// In test mode, only rank 0 runs, so avoid skipping
this->layer_param_.phase() == TEST;
return !keep;
}
// OpenPose: added
template<typename Dtype>
void OPVideoLayer<Dtype>::Next(const int index)
{
auto& cursor = mCursors.at(index);
cursor->Next();
if (!cursor->valid())
{
LOG_IF(INFO, Caffe::root_solver())
<< "Restarting second data prefetching from start.";
cursor->SeekToFirst();
}
mOffsets[index]++;
}
template<typename Dtype>
void OPVideoLayer<Dtype>::NextBackground()
{
assert(backgroundDb);
cursorBackground->Next();
if (!cursorBackground->valid())
{
LOG_IF(INFO, Caffe::root_solver())
<< "Restarting negatives data prefetching from start.";
cursorBackground->SeekToFirst();
}
offsetBackground++;
}
template <typename Dtype>
bool OPVideoLayer<Dtype>::SkipBackground()
{
int size = Caffe::solver_count();
int rank = Caffe::solver_rank();
bool keep = (offsetBackground % size) == rank ||
// In test mode, only rank 0 runs, so avoid skipping
this->layer_param_.phase() == TEST;
return !keep;
}
template <typename Dtype>
int getRandomIndex(const std::vector<Dtype>& probabilities, const Dtype onlyBackgroundProbability)
{
const float dice = static_cast <float> (rand()) / static_cast <float> (RAND_MAX); //[0,1]
auto accumulated = Dtype(0);
for (auto i = 0u ; i < probabilities.size() ; i++)
{
accumulated += probabilities[i];
// Choose i
if (dice < accumulated)
return i;
}
// Choose background
return -1;
}
// This function is called on prefetch thread
template<typename Dtype>
void OPVideoLayer<Dtype>::load_batch(Batch<Dtype>* batch)
{
CPUTimer batch_timer;
batch_timer.Start();
double read_time = 0;
double trans_time = 0;
CPUTimer timer;
CHECK(batch->data_.count());
CHECK(this->transformed_data_.count());
const int batch_size = this->layer_param_.data_param().batch_size();
// OpenPose: added
auto* topLabel = batch->label_.mutable_cpu_data();
// OpenPose: added ended
Datum datum;
Datum datumBackground;
// OpenPose: added - Batch within
const auto randomIndex = getRandomIndex(mProbabilities, onlyBackgroundProbability);
const auto desiredDbIsBkg = randomIndex == -1;
// OpenPose: added ended
for (int item_id = 0; item_id < batch_size; ++item_id) {
timer.Start();
// OpenPose: commended
// while (Skip()) {
// Next();
// }
// datum.ParseFromString(cursor_->value());
// OpenPose: commended ended
// OpenPose: added
auto inputType = this->mInputType[std::max(0, randomIndex)];
auto oPDataTransformerPtr = this->mOPDataTransformers[std::max(0, randomIndex)]; // If bkg --> Use 0
// If chosen dataset i
if (!desiredDbIsBkg) // i.e., if randomIndex >= 0
{
mCounterTimer[randomIndex]++;
while (Skip(randomIndex))
Next(randomIndex);
// datum.ParseFromString(cursor_->value());
datum.ParseFromString(mCursors[randomIndex]->value());
}
// If chosen only-bkg
else
{
mCounterTimerBkg++;
CHECK(backgroundDb);
}
if (backgroundDb)
{
while (SkipBackground())
NextBackground();
datumBackground.ParseFromString(cursorBackground->value());
}
// OpenPose: added ended
read_time += timer.MicroSeconds();
if (item_id == 0) {
// OpenPose: added
// this->transformed_data_.Reshape({1, 3, height, width});
// top_shape[0] = batch_size;
const int width = this->phase_ != TRAIN ? datum.width()
: this->layer_param_.op_transform_param().crop_size_x();
const int height = this->phase_ != TRAIN ? datum.height()
: this->layer_param_.op_transform_param().crop_size_y();
batch->data_.Reshape({batch_size * mFrameSize, 3, height, width});
// OpenPose: added ended
// OpenPose: commented
// // Reshape according to the first datum of each batch
// // on single input batches allows for inputs of varying dimension.
// // Use data_transformer to infer the expected blob shape from datum.
// vector<int> top_shape = this->data_transformer_->InferBlobShape(datum);
// this->transformed_data_.Reshape(top_shape);
// // Reshape batch according to the batch_size.
// top_shape[0] = batch_size;
// batch->data_.Reshape(top_shape);
// OpenPose: commented ended
}
// Apply data transformations (mirror, scale, crop...)
timer.Start();
// OpenPose: added
// Image
// const int offset = batch->data_.offset(item_id);
auto* topData = batch->data_.mutable_cpu_data();
this->transformed_data_.set_cpu_data(topData);
// Label
// const int offsetLabel = batch->label_.offset(item_id);
this->transformed_label_.set_cpu_data(topLabel);
// Process image & label
const auto begin = std::chrono::high_resolution_clock::now();
if(inputType == "image")
oPDataTransformerPtr->TransformVideoSF(item_id, mFrameSize, &(this->transformed_data_),
&(this->transformed_label_),
datum, datumBackground, randomIndex);
else
throw std::runtime_error("Not implemented");
// if (backgroundDb)
// oPDataTransformerPtr->Transform(
// &(this->transformed_data_), &(this->transformed_label_), mDistanceAverage, mDistanceSigma,
// mDistanceAverageCounter, randomIndex, (desiredDbIsBkg ? nullptr : &datum), &datumBackground);
// else
// oPDataTransformerPtr->Transform(
// &(this->transformed_data_), &(this->transformed_label_), mDistanceAverage, mDistanceSigma,
// mDistanceAverageCounter, randomIndex, (desiredDbIsBkg ? nullptr : &datum));
const auto end = std::chrono::high_resolution_clock::now();
mDuration += std::chrono::duration_cast<std::chrono::nanoseconds>(end-begin).count();
// DB i
if (!desiredDbIsBkg) // i.e., if randomIndex >= 0
Next(randomIndex);
// If bkg DB included
if (backgroundDb)
NextBackground();
trans_time += timer.MicroSeconds();
// OpenPose: added ended
// OpenPose: commented
// this->data_transformer_->Transform(datum, &(this->transformed_data_));
// // Copy label.
// if (this->output_labels_) {
// Dtype* topLabel = batch->label_.mutable_cpu_data();
// topLabel[item_id] = datum.label();
// }
// trans_time += timer.MicroSeconds();
// Next();
// OpenPose: commented ended
}
// Timer (every 20 iterations x batch size)
mCounter++;
const auto repeatEveryXVisualizations = 4;
if (mCounter % (20*repeatEveryXVisualizations) == 0)
{
std::string text = "Time: " + std::to_string(mDuration/repeatEveryXVisualizations * 1e-9) + "s";
mCounter = 0;
mDuration = 0;
const auto accumulatedCounters = float(
std::accumulate(mCounterTimer.begin(), mCounterTimer.end(), mCounterTimerBkg));
for (auto i = 0u ; i < mCounterTimer.size() ; i++)
{
text += "\t" + mModels.at(i) + ": ";
text += std::to_string(mCounterTimer.at(i)/accumulatedCounters);
}
text += "\tRatioBkg: " + std::to_string(mCounterTimerBkg/accumulatedCounters);
std::cout << text; // << std::endl;
std::cout << "\n" << std::endl;
}
timer.Stop();
batch_timer.Stop();
DLOG(INFO) << "Prefetch batch: " << batch_timer.MilliSeconds() << " ms.";
DLOG(INFO) << " Read time: " << read_time / 1000 << " ms.";
DLOG(INFO) << "Transform time: " << trans_time / 1000 << " ms.";
std::cout << "DONE!!" << std::endl;
// Video Test
auto oPDataTransformerPtr = this->mOPDataTransformers[std::max(0, randomIndex)];
oPDataTransformerPtr->TestVideo(mFrameSize, &(this->transformed_data_), &(this->transformed_label_));
std::cout << "VIDEO" << std::endl;
exit(-1);
// CPUTimer batch_timer;
// batch_timer.Start();
// double read_time = 0;
// double trans_time = 0;
// CPUTimer timer;
// CHECK(batch->data_.count());
// CHECK(this->transformed_data_.count());
// const int batch_size = this->layer_param_.data_param().batch_size();
// // Get Label pointer [Label shape: 20, 132, 46, 46]
// auto* topLabel = batch->label_.mutable_cpu_data();
// for(int i=0; i<Batch<float>::extra_labels_count; i++)
// batch->extra_labels_[i].mutable_cpu_data();
// // OpenPose: added
// float video_or_image = 0.0;
// if(AProbability || BProbability) video_or_image = static_cast <float> (rand()) / static_cast <float> (RAND_MAX); //[0,1]
// //video_or_image = 1.0;
// //Change code so that its in image mode doesnt mix?
// bool desiredDbIs1 = false, desiredDbIs2 = false, desiredDbIs3 = false;
// bool desiredDbIsA = false, desiredDbIsB = false;
// //sample_dbs(desiredDbIs1, desiredDbIs2, desiredDbIs3);
// // Sample Outside
// if(video_or_image >= this->layer_param_.op_transform_param().video_or_image()){
// sample_dbs(desiredDbIs1, desiredDbIs2, desiredDbIs3);
// }else{
// sample_ab(desiredDbIsA, desiredDbIsB);
// }
// // Sample lmdb for video?
// Datum datum;
// Datum datumBackground;
// for (int item_id = 0; item_id < batch_size; ++item_id) {
// //const float dice = static_cast <float> (rand()) / static_cast <float> (RAND_MAX); //[0,1]
// //const auto desiredDbIs1 = !secondDb || (dice <= (1-secondProbability));
//// if(video_or_image >= this->layer_param_.op_transform_param().video_or_image()){
//// sample_dbs(desiredDbIs1, desiredDbIs2, desiredDbIs3);
//// }else{
//// if(item_id == 0) sample_ab(desiredDbIsA, desiredDbIsB);
//// }
// // Read from desired DB - DB1, DB2 or BG
// timer.Start();
// auto oPDataTransformerPtr = this->mOPDataTransformer;
// if (desiredDbIs1)
// {
// mOnes++;
// while (Skip())
// Next();
// datum.ParseFromString(cursor_->value());
// }
// // 2nd DB
// else if (desiredDbIs2)
// {
// oPDataTransformerPtr = this->mOPDataTransformerSecondary;
// mTwos++;
// while (SkipSecond())
// NextSecond();
// datum.ParseFromString(cursorSecond->value());
// }
// // 3rd DB
// else if (desiredDbIs3)
// {
// oPDataTransformerPtr = this->mOPDataTransformerTertiary;
// mThrees++;
// while (SkipThird())
// NextThird();
// datum.ParseFromString(cursorThird->value());
// }
// // A DB
// else if (desiredDbIsA)
// {
// oPDataTransformerPtr = this->mOPDataTransformerA;
// mAs++;
// while (SkipA())
// NextA();
// datum.ParseFromString(cursorA->value());
// }
// // B DB
// else if (desiredDbIsB)
// {
// oPDataTransformerPtr = this->mOPDataTransformerB;
// mBs++;
// while (SkipB())
// NextB();
// datum.ParseFromString(cursorB->value());
// }
// if (backgroundDb)
// {
// NextBackground();
// datumBackground.ParseFromString(cursorBackground->value());
// }
// read_time += timer.MicroSeconds();
// // First item
// if (item_id == 0) {
// const int width = this->phase_ != TRAIN ? datum.width() : this->layer_param_.op_transform_param().crop_size_x();
// const int height = this->phase_ != TRAIN ? datum.height() : this->layer_param_.op_transform_param().crop_size_y();
// batch->data_.Reshape({batch_size * frame_size, 3, height, width});
// }
// // Read in data
// timer.Start();
// VSeq vs;
// const int offset = batch->data_.offset(item_id);
// auto* topData = batch->data_.mutable_cpu_data();
// this->transformed_data_.set_cpu_data(topData);
// // Label
// const int offsetLabel = batch->label_.offset(item_id);
// this->transformed_label_.set_cpu_data(topLabel);
// // Process image & label
// const auto begin = std::chrono::high_resolution_clock::now();
// if (backgroundDb){
// if(desiredDbIs1)
// oPDataTransformerPtr->TransformVideoJSON(item_id, frame_size, vs, &(this->transformed_data_),
// &(this->transformed_label_),
// datum, &datumBackground);
// else if (desiredDbIs2 || desiredDbIs3)
// oPDataTransformerPtr->TransformVideoSF(item_id, frame_size, vs, &(this->transformed_data_),
// &(this->transformed_label_),
// datum, &datumBackground);
// else if (desiredDbIsA || desiredDbIsB)
// oPDataTransformerPtr->TransformVideoSF(item_id, frame_size, vs, &(this->transformed_data_),
// &(this->transformed_label_),
// datum, &datumBackground, false);
// }else{
// throw std::runtime_error("Not implemented");
// }
// const auto end = std::chrono::high_resolution_clock::now();
// mDuration += std::chrono::duration_cast<std::chrono::nanoseconds>(end-begin).count();
// // Advance to next data
// if (desiredDbIs1)
// Next();
// else if (desiredDbIs2)
// NextSecond();
// else if (desiredDbIs3)
// NextThird();
// else if (desiredDbIsA)
// NextA();
// else if (desiredDbIsB)
// NextB();
// trans_time += timer.MicroSeconds();
// }
// // Testing Optional
// //if(vCounter == 2){
// //auto oPDataTransformerPtr = this->mOPDataTransformer;
// //oPDataTransformerPtr->Test(frame_size, &(this->transformed_data_), &(this->transformed_label_));
// //}
// //boost::this_thread::sleep_for(boost::chrono::milliseconds(1000));
// //std::cout << "Loaded Data" << std::endl;
// // Timer (every 20 iterations x batch size)
// mCounter++;
// vCounter++;
// const auto repeatEveryXVisualizations = 2;
// if (mCounter == 20*repeatEveryXVisualizations)
// {
// std::cout << "Time: " << mDuration/repeatEveryXVisualizations * 1e-9 << "s\t"
// << "Ratio: " << mOnes/float(mOnes+mTwos) << std::endl;
// mDuration = 0;
// mCounter = 0;
// }
// timer.Stop();
// batch_timer.Stop();
// DLOG(INFO) << "Prefetch batch: " << batch_timer.MilliSeconds() << " ms.";
// DLOG(INFO) << " Read time: " << read_time / 1000 << " ms.";
// DLOG(INFO) << "Transform time: " << trans_time / 1000 << " ms.";
}
INSTANTIATE_CLASS(OPVideoLayer);
REGISTER_LAYER_CLASS(OPVideo);
} // namespace caffe
| 40.444444 | 129 | 0.595467 | [
"shape",
"vector",
"model",
"transform"
] |
98bacbfb06f4d4cddd413dc4042434fadab4dea3 | 15,370 | cpp | C++ | src/tests/accuracy_test_mixed_radices.cpp | ddeka2910/clFFT | 7b060b4f27ac22f95c17790476503f622ffea4c6 | [
"Apache-2.0"
] | 406 | 2015-02-01T07:32:29.000Z | 2022-03-31T15:21:54.000Z | src/tests/accuracy_test_mixed_radices.cpp | ddeka2910/clFFT | 7b060b4f27ac22f95c17790476503f622ffea4c6 | [
"Apache-2.0"
] | 169 | 2015-01-01T00:06:42.000Z | 2021-12-01T19:15:45.000Z | src/tests/accuracy_test_mixed_radices.cpp | ddeka2910/clFFT | 7b060b4f27ac22f95c17790476503f622ffea4c6 | [
"Apache-2.0"
] | 183 | 2015-01-05T02:21:16.000Z | 2022-03-14T08:25:39.000Z | /* ************************************************************************
* Copyright 2013 Advanced Micro Devices, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ************************************************************************/
#include <gtest/gtest.h>
#include<math.h>
#include "test_constants.h"
#include "fftw_transform.h"
#include "cl_transform.h"
#include "accuracy_test_common.h"
#include <stdexcept>
#include <vector>
class mixed_radix : public ::testing::TestWithParam<size_t> {
protected:
mixed_radix(){}
virtual ~mixed_radix(){}
virtual void SetUp(){}
virtual void TearDown(){}
};
template< typename T, typename cl_T, typename fftw_T >
void mixed_radix_complex_to_complex( size_t problem_size )
{
try
{
if(verbose) std::cout << "Now testing problem size " << problem_size << std::endl;
std::vector<size_t> lengths;
lengths.push_back( problem_size );
size_t batch = 500;
std::vector<size_t> input_strides;
std::vector<size_t> output_strides;
size_t input_distance = 0;
size_t output_distance = 0;
layout::buffer_layout_t in_layout = layout::complex_planar;
layout::buffer_layout_t out_layout = layout::complex_planar;
placeness::placeness_t placeness = placeness::in_place;
direction::direction_t direction = direction::forward;
data_pattern pattern = sawtooth;
complex_to_complex<T, cl_T, fftw_T>( pattern, direction, lengths, batch, input_strides, output_strides, input_distance, output_distance, in_layout, out_layout, placeness );
}
catch( const std::exception& err ) {
handle_exception(err);
}
}
TEST_P( mixed_radix, single_precision_complex_to_complex_auto_generated ) {
size_t problem_size = GetParam();
RecordProperty("problem_size", (int)problem_size);
mixed_radix_complex_to_complex<float, cl_float, fftwf_complex>(problem_size);
}
TEST_P( mixed_radix, double_precision_complex_to_complex_auto_generated ) {
size_t problem_size = GetParam();
RecordProperty("problem_size", (int)problem_size);
mixed_radix_complex_to_complex<double, cl_double, fftw_complex>(problem_size);
}
template< typename T, typename cl_T, typename fftw_T >
void mixed_radix_real_to_hermitian( size_t problem_size )
{
try
{
if(verbose) std::cout << "Now testing problem size " << problem_size << std::endl;
std::vector<size_t> lengths;
lengths.push_back( problem_size );
size_t batch = 1;
std::vector<size_t> input_strides;
std::vector<size_t> output_strides;
size_t input_distance = 0;
size_t output_distance = 0;
layout::buffer_layout_t layout = layout::hermitian_interleaved;
placeness::placeness_t placeness = placeness::in_place;
data_pattern pattern = sawtooth;
real_to_complex<T, cl_T, fftw_T>( pattern, lengths, batch, input_strides, output_strides, input_distance, output_distance, layout, placeness );
}
catch( const std::exception& err ) {
handle_exception(err);
}
}
TEST_P( mixed_radix, single_precision_real_to_hermitian_auto_generated ) {
size_t problem_size = GetParam();
RecordProperty("problem_size", (int)problem_size);
mixed_radix_real_to_hermitian<float, cl_float, fftwf_complex>(problem_size);
}
TEST_P( mixed_radix, double_precision_real_to_hermitian_auto_generated ) {
size_t problem_size = GetParam();
RecordProperty("problem_size", (int)problem_size);
mixed_radix_real_to_hermitian<double, cl_double, fftw_complex>(problem_size);
}
template< typename T, typename cl_T, typename fftw_T >
void mixed_radix_hermitian_to_real( size_t problem_size )
{
try
{
if(verbose) std::cout << "Now testing problem size " << problem_size << std::endl;
std::vector<size_t> lengths;
lengths.push_back( problem_size );
size_t batch = 1;
std::vector<size_t> input_strides;
std::vector<size_t> output_strides;
size_t input_distance = 0;
size_t output_distance = 0;
layout::buffer_layout_t layout = layout::hermitian_interleaved;
placeness::placeness_t placeness = placeness::in_place;
data_pattern pattern = sawtooth;
complex_to_real<T, cl_T, fftw_T>( pattern, lengths, batch, input_strides, output_strides, input_distance, output_distance, layout, placeness );
}
catch( const std::exception& err ) {
handle_exception(err);
}
}
TEST_P( mixed_radix, single_precision_hermitian_to_real_auto_generated ) {
size_t problem_size = GetParam();
RecordProperty("problem_size", (int)problem_size);
mixed_radix_hermitian_to_real<float, cl_float, fftwf_complex>(problem_size);
}
TEST_P( mixed_radix, double_precision_hermitian_to_real_auto_generated ) {
size_t problem_size = GetParam();
RecordProperty("problem_size", (int)problem_size);
mixed_radix_hermitian_to_real<double, cl_double, fftw_complex>(problem_size);
}
class Supported_Fft_Sizes
{
public:
std::vector<size_t> sizes;
const size_t max_mixed_radices_to_test;
Supported_Fft_Sizes()
: max_mixed_radices_to_test( 4096 )
{
size_t i=0, j=0, k=0, l=0, m=0, n=0;
size_t sum, sumi, sumj, sumk, suml, summ, sumn;
sumi = 1; i = 0;
while(1)
{
sumj = 1; j = 0;
while(1)
{
sumk = 1; k = 0;
while(1)
{
suml = 1; l = 0;
while(1)
{
summ = 1; m = 0;
while (1)
{
sumn = 1; n = 0;
while (1)
{
sum = (sumi*sumj*sumk*suml*summ*sumn);
if (sum > max_mixed_radices_to_test) break;
sizes.push_back(sum);
n++;
sumn *= 2;
}
if(n == 0) break;
m++;
summ *= 3;
}
if( (m == 0) && (n == 0) ) break;
l++;
suml *= 5;
}
if( (l == 0) && (m == 0) && (n == 0) ) break;
k++;
sumk *= 7;
}
if( (k == 0) && (l == 0) && (m == 0) && (n == 0) ) break;
j++;
sumj *= 11;
}
if( (j == 0) && (k == 0) && (l == 0) && (m == 0) && (n == 0) ) break;
i++;
sumi *= 13;
}
}
} supported_sizes;
INSTANTIATE_TEST_CASE_P(
mixed_radices,
mixed_radix,
::testing::ValuesIn( supported_sizes.sizes )
);
// ============================================== //
// the following is a place to stick static tests //
// with mixed radices. the tests will most likely //
// be created in response to failed random tests. //
// ============================================== //
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
class accuracy_test_mixed_single : public ::testing::Test {
protected:
accuracy_test_mixed_single(){}
virtual ~accuracy_test_mixed_single(){}
virtual void SetUp(){}
virtual void TearDown(){
}
};
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
class accuracy_test_mixed_double : public ::testing::Test {
protected:
accuracy_test_mixed_double(){}
virtual ~accuracy_test_mixed_double(){}
virtual void SetUp(){}
virtual void TearDown(){
}
};
// *****************************************************
// *****************************************************
template< class T, class cl_T, class fftw_T >
void hermitian_to_real_transforms_with_non_unit_output_strides_should_pass()
{
std::vector<size_t> lengths;
lengths.push_back( 10 );
size_t batch = 1;
std::vector<size_t> input_strides;
size_t input_distance = 0;
std::vector<size_t> output_strides;
output_strides.push_back( 2 );
size_t output_distance = 0;
layout::buffer_layout_t layout = layout::hermitian_planar;
placeness::placeness_t placeness = placeness::out_of_place;
data_pattern pattern = sawtooth;
complex_to_real<T, cl_T, fftw_T>( pattern, lengths, batch, input_strides, output_strides, input_distance, output_distance, layout, placeness );
}
TEST_F(accuracy_test_mixed_single, hermitian_to_real_transforms_with_non_unit_output_strides_should_pass)
{
try { hermitian_to_real_transforms_with_non_unit_output_strides_should_pass< float, cl_float, fftwf_complex >(); }
catch( const std::exception& err ) { handle_exception(err); }
}
TEST_F(accuracy_test_mixed_double, hermitian_to_real_transforms_with_non_unit_output_strides_should_pass)
{
try { hermitian_to_real_transforms_with_non_unit_output_strides_should_pass< double, cl_double, fftw_complex >(); }
catch( const std::exception& err ) { handle_exception(err); }
}
// *****************************************************
// *****************************************************
template< class T, class cl_T, class fftw_T >
void hermitian_to_real_transforms_with_non_unit_input_strides_should_pass()
{
std::vector<size_t> lengths;
lengths.push_back( 6 );
lengths.push_back( 67500 );
size_t batch = 1;
std::vector<size_t> input_strides;
input_strides.push_back( 2 );
input_strides.push_back( 12 );
size_t input_distance = 810074;
std::vector<size_t> output_strides;
size_t output_distance = 0;
layout::buffer_layout_t layout = layout::hermitian_planar;
placeness::placeness_t placeness = placeness::out_of_place;
data_pattern pattern = sawtooth;
complex_to_real<T, cl_T, fftw_T>( pattern, lengths, batch, input_strides, output_strides, input_distance, output_distance, layout, placeness );
}
TEST_F(accuracy_test_mixed_single, hermitian_to_real_transforms_with_non_unit_input_strides_should_pass)
{
try { hermitian_to_real_transforms_with_non_unit_input_strides_should_pass< float, cl_float, fftwf_complex >(); }
catch( const std::exception& err ) { handle_exception(err); }
}
TEST_F(accuracy_test_mixed_double, hermitian_to_real_transforms_with_non_unit_input_strides_should_pass)
{
try { hermitian_to_real_transforms_with_non_unit_input_strides_should_pass< double, cl_double, fftw_complex >(); }
catch( const std::exception& err ) { handle_exception(err); }
}
// *****************************************************
// *****************************************************
template< class T, class cl_T, class fftw_T >
void small_targeted_real_to_hermitian_transform()
{
std::vector<size_t> lengths;
lengths.push_back( 15 );
lengths.push_back( 2 );
size_t batch = 2;
std::vector<size_t> input_strides;
input_strides.push_back( 1 );
input_strides.push_back( 16 );
size_t input_distance = 32;
std::vector<size_t> output_strides;
output_strides.push_back( 1 );
output_strides.push_back( 8 );
size_t output_distance = 16;
layout::buffer_layout_t layout = layout::hermitian_interleaved;
placeness::placeness_t placeness = placeness::in_place;
data_pattern pattern = sawtooth;
real_to_complex<T, cl_T, fftw_T>( pattern, lengths, batch, input_strides, output_strides, input_distance, output_distance, layout, placeness );
}
TEST_F(accuracy_test_mixed_single, small_targeted_real_to_hermitian_transform)
{
try { small_targeted_real_to_hermitian_transform< float, cl_float, fftwf_complex >(); }
catch( const std::exception& err ) { handle_exception(err); }
}
TEST_F(accuracy_test_mixed_double, small_targeted_real_to_hermitian_transform)
{
try { small_targeted_real_to_hermitian_transform< double, cl_double, fftw_complex >(); }
catch( const std::exception& err ) { handle_exception(err); }
}
// *****************************************************
// *****************************************************
template< class T, class cl_T, class fftw_T >
void larger_targeted_real_to_hermitian_transform()
{
std::vector<size_t> lengths;
lengths.push_back( 15 );
lengths.push_back( 4500 );
size_t batch = 2;
std::vector<size_t> input_strides;
input_strides.push_back( 1 );
input_strides.push_back( 16 );
size_t input_distance = 72000;
std::vector<size_t> output_strides;
output_strides.push_back( 1 );
output_strides.push_back( 8 );
size_t output_distance = 36000;
layout::buffer_layout_t layout = layout::hermitian_interleaved;
placeness::placeness_t placeness = placeness::in_place;
data_pattern pattern = sawtooth;
real_to_complex<T, cl_T, fftw_T>( pattern, lengths, batch, input_strides, output_strides, input_distance, output_distance, layout, placeness );
}
TEST_F(accuracy_test_mixed_single, larger_targeted_real_to_hermitian_transform)
{
try { larger_targeted_real_to_hermitian_transform< float, cl_float, fftwf_complex >(); }
catch( const std::exception& err ) { handle_exception(err); }
}
TEST_F(accuracy_test_mixed_double, larger_targeted_real_to_hermitian_transform)
{
try { larger_targeted_real_to_hermitian_transform< double, cl_double, fftw_complex >(); }
catch( const std::exception& err ) { handle_exception(err); }
}
// *****************************************************
// *****************************************************
template< class T, class cl_T, class fftw_T >
void another_targeted_real_to_hermitian_transform()
{
std::vector<size_t> lengths;
lengths.push_back( 30 );
lengths.push_back( 10125 );
size_t batch = 1;
std::vector<size_t> input_strides;
input_strides.push_back( 1 );
input_strides.push_back( 32 );
size_t input_distance = 324000;
std::vector<size_t> output_strides;
output_strides.push_back( 1 );
output_strides.push_back( 16 );
size_t output_distance = 162000;
layout::buffer_layout_t layout = layout::hermitian_interleaved;
placeness::placeness_t placeness = placeness::in_place;
data_pattern pattern = sawtooth;
real_to_complex<T, cl_T, fftw_T>( pattern, lengths, batch, input_strides, output_strides, input_distance, output_distance, layout, placeness );
}
TEST_F(accuracy_test_mixed_single, another_targeted_real_to_hermitian_transform)
{
try { another_targeted_real_to_hermitian_transform< float, cl_float, fftwf_complex >(); }
catch( const std::exception& err ) { handle_exception(err); }
}
TEST_F(accuracy_test_mixed_double, another_targeted_real_to_hermitian_transform)
{
try { another_targeted_real_to_hermitian_transform< double, cl_double, fftw_complex >(); }
catch( const std::exception& err ) { handle_exception(err); }
}
// *****************************************************
// *****************************************************
template< class T, class cl_T, class fftw_T >
void possible_driver_bug_1D_length_375_fails()
{
std::vector<size_t> lengths;
lengths.push_back( 375 );
size_t batch = 1;
std::vector<size_t> input_strides;
size_t input_distance = 0;
std::vector<size_t> output_strides;
size_t output_distance = 0;
layout::buffer_layout_t layout = layout::hermitian_planar;
placeness::placeness_t placeness = placeness::out_of_place;
data_pattern pattern = sawtooth;
real_to_complex<T, cl_T, fftw_T>( pattern, lengths, batch, input_strides, output_strides, input_distance, output_distance, layout, placeness );
}
TEST_F(accuracy_test_mixed_single, possible_driver_bug_1D_length_375_fails)
{
try { possible_driver_bug_1D_length_375_fails< float, cl_float, fftwf_complex >(); }
catch( const std::exception& err ) { handle_exception(err); }
}
TEST_F(accuracy_test_mixed_double, possible_driver_bug_1D_length_375_fails)
{
try { possible_driver_bug_1D_length_375_fails< double, cl_double, fftw_complex >(); }
catch( const std::exception& err ) { handle_exception(err); }
} | 31.887967 | 174 | 0.693689 | [
"vector"
] |
98bfc4b5813482a14b99a8369ef68d37ffddd523 | 9,235 | cpp | C++ | InputParameters/input_params_list.cpp | glenco/SLsimLib | fb7a3c450d2487a823fa3f0ae8c8ecf7945c3ebb | [
"MIT"
] | 2 | 2017-03-22T13:18:32.000Z | 2021-05-01T01:54:31.000Z | InputParameters/input_params_list.cpp | glenco/SLsimLib | fb7a3c450d2487a823fa3f0ae8c8ecf7945c3ebb | [
"MIT"
] | 49 | 2016-10-05T03:08:38.000Z | 2020-11-03T15:39:26.000Z | InputParameters/input_params_list.cpp | glenco/SLsimLib | fb7a3c450d2487a823fa3f0ae8c8ecf7945c3ebb | [
"MIT"
] | 1 | 2017-07-10T08:52:53.000Z | 2017-07-10T08:52:53.000Z | #include "../include/InputParams.h"
#include <set>
typedef std::set<std::string> labels_t;
typedef std::map<std::string, std::pair<std::string, std::string> > defaults_t;
namespace
{
// array of standard parameters
const char* parameter_list[][3] = {
// General
{"outputfile", "output", ""},
{"deflection_off", "0", "switches deflection off (but not kappa and gamma, ie. Born approximation)"},
{"lensing_off", "0", "switches all lensing off"},
{"read_redshift_planes", "0", "reads in the redshifts of the lensing planes from a file"},
{"redshift_planes_file", "Z.txt", "an asci file with redshifts of the planes, excluding the source redshift"},
{"z_lens", "0.42", "lens redshift"},
{"z_source", "3.62", "source redshift"},
// Cosmology
{"Omega_matter", "0.3", "Matter energy density fraction"},
{"Omega_lambda", "0.7", "Lambda energy density fraction"},
{"Omega_baryon", "0", "Baryon energy density fraction"},
{"Omega_neutrino", "0", "Neutrino energy density fraction"},
{"hubble", "0.73", "Hubble constant H/100"},
{"sigma_8", "0.8", "Sigma_8 constant for large scale structure"},
// Main halos type
{"main_halo_on", "1", "insert a main halo into the simulation"},
{"main_DM_halo_type", "DummyLens", "main halo type: nolens, NFW, PseudoNFW, PowerLaw, NSIE, AnaLens, UniLens, MOKALens, DummyLens, Hernquist, Jaffe"},
{"main_galaxy_halo_type", "0", "if set, a main halo galaxy profile is chosen: 0 or none, 1 or NSIE"},
// Pixelized Mass maps
{"pixelmaps_on","0","Input one or more pixelized density maps"},
{"pixelmaps_input_file","surfacedensity.fits","Density map(s) to be read in as main lens. This can be a single map (*.fits) or a file with a list of fits files."},
{"pixelmap_padding_factor","4","The factor by which the map is zero padded when doing FFTS."},
{"pixelmap_zeromean","true","By default the mean surface density is subtracted from the map. Set to false to turn this off"},
// MultiDarkMap lenses
//{"PixelizedDensityMap_input_file", "PixelizedMapFiles.txt", "list of MOKA FITS files for MultiDark-like simulations"},
// Field halos
{"field_off", "0", "turn off field halos"},
{"field_Nplanes", "10", "number of field halo planes"},
// Field halos type
{"field_internal_profile", "NFW", "field halo type: nolens, NFW, PseudoNFW, PowerLaw, NSIE, AnaLens, UniLens, DummyLens"},
{"field_internal_profile_galaxy", "0", "if set, a field halo galaxy profile is chosen: 0 or none, 1 or NSIE, 2 or PowerLaw, 3 or Hernquist, 4 or Jaffe"},
{"field_internal_profile_galaxy_slope", "-1", "slope of the field halo galaxy PowerLaw profile"},
{"field_prof_internal_slope_pnfw", "2", "slope of the PseudoNFW profile"},
{"field_prof_internal_slope_pl", "-1", "slope of the field halo PowerLaw profile"},
// Field halos from a mass function
{"field_mass_func_type", "1", "mass function type, 0: Press-Schechter, 1: Sheth-Tormen, 2: PowerLaw"},
{"field_mass_func_alpha", "2", "Only valid with field_mass_func_type = PowerLaw"},
{"field_fov", "1.0e4", "random light cone field of view in square arcseconds"},
{"field_buffer", "1.0", "in physical Mpc"},
{"field_min_mass", "1.0e9", "min mass of the halos in the light cone in solar masses"},
// Field halos from an input file
{"field_input_simulation_path", "halos.txt", "if set, the light cone is read from an input file or files in this directory"},
{"field_input_simulation_format", "MillenniumObs", "if set, format of halo input data: MillenniumObs, MultiDarkHalos, this is subject to changes"},
{"field_input_simulation_center_RA", "0.0","Optional: right ascension in degrees for the center of the simulation, 0 if not included"},
{"field_input_simulation_center_DEC","0.0","Optional: declination in degrees the center of the simulation, 0 if not included"},
{"field_input_simulation_radius","0.0","Optional: set radius (in degrees) of simulated field radians, infinite (size of input lightcone) if not included"},
// Main halos
{"main_mass", "1e15", "main halo mass"},
{"main_zlens", "0.42", "main halo redshift"},
{"main_Rsize", "1.0", "main halo radius"},
{"main_concentration", "5", "main halo concentration parameter"},
{"main_slope", "1", "main halo slope"},
{"main_sigma", "250", "velocity dispersion in km/s"},
{"main_core", "1.0E-5", "core radius in Mpc"},
{"main_axis_ratio", "1.0", "axis ratio for elliptical models, < 1"},
{"main_ellip_method", "Pseudo", "method to make an isotropic halo elliptical: 0 Fourier, 1 or Pseudo, 2 or Schramm, 3 or Keeton"},
{"main_pos_angle", "0", "inclination angle in degrees"},
{"main_rscale", "", ""},
// AnaNSIE perturbations
{"main_NDistortionModes", "0", "number of ellipsoid distortion modes"},
{"main_perturb_beta", "1.0", ""},
{"main_perturb_kappa", "0.03", ""},
{"main_perturb_gamma", "0.03", ""},
{"main_perturb_monopole", "0.0", ""},
{"main_perturb_quadrapole", "0.005", ""},
{"main_perturb_hexopole", "0.005", ""},
{"main_perturb_octopole", "0.01", ""},
// AnaNSIE substructures
{"main_sub_Ndensity", "0.0e6", "number density of substructure"},
{"main_sub_beta", "-1.0", ""},
{"main_sub_alpha", "-1.9", ""},
{"main_sub_Rsize", "0.5e-3", ""},
{"main_sub_mass_max", "1.0e9", ""},
{"main_sub_mass_min", "1.0e6", ""},
{"main_sub_type", "1", ""},
// Stars
{"main_stars_N", "0", "number of stars to be implanted"},
{"main_stars_fraction", "0.5", "stellar mass fraction"},
{"main_stars_mass", "0.5", "star mass in solar masses"},
{"main_stars_mass_function", "", ""},
{"main_stars_min_mass", "", ""},
{"main_stars_max_mass", "", ""},
{"main_stars_bending_point", "", ""},
{"main_stars_lo_mass_slope", "", ""},
{"main_stars_hi_mass_slope", "", ""},
// MOKA lens halo model
{"MOKA_input_file", "moka.fits", "MOKA FITS file"},
{"MOKA_input_params", "1", "read parameters from MOKA FITS header"},
{"MOKA_analyze", "0", ""},
{"MOKA_background_field", "0", ""},
// Uniform lens halo model
{"kappa_uniform", "", ""},
{"gamma_uniform_1", "", ""},
{"gamma_uniform_2", "", ""},
//
{"zsource_reference", "2.0", "reference redshift for halo quantities that depend on source z"},
// Type of source SB model
{"SourceSBType", "Uniform", "Uniform, Gaussian, BLR_Disk, BLR_Sph1, BLR_Sph2"},
// Gaussian source model
{"gauss_r2", "0.0", ""},
// BLR source model
{"source_BHmass", "1.0e9", "BH mass of the quasar"},
{"source_gamma", "-0.5", ""},
{"source_inclin", "35.0", ""},
{"source_opening_ang", "10", ""},
{"source_r_in", "5.0e-9", ""},
{"source_r_out", "5.0e-6", ""},
{"source_nuo", "6.17284e14", ""},
{"source_fK", "", ""},
// SourceMultiAnaGalaxy & Sky
{"source_input_galaxy_file", "sources.txt", "Millennium sources input file"},
{"source_band", "", ""},
{"source_mag_limit", "30", "minimum magnitude for sources"},
{"source_sb_limit", "0", "minimum surface brightness for sources in mags per arcsec"},
{"shapelets_folder", "","Shapelets sources input folder"},
{"shapelets_band", "","Shapelets band for initialisation"},
// QSO data
{"QSO_kcorrection_file","","Table with k-correction in the i band for quasars as a function of redshift"},
{"QSO_colors_file","","Table with SDSS colors for quasars as a function of redshift"},
};
// create a set of all labels from the parameter list
labels_t get_labels()
{
labels_t labels;
for(std::size_t i = 0; i < sizeof(parameter_list)/sizeof(const char*[3]); ++i)
labels.insert(parameter_list[i][0]);
return labels;
}
// create a map of all default values and comments from the parameter list
defaults_t get_defaults()
{
defaults_t defaults;
for(std::size_t i = 0; i < sizeof(parameter_list)/sizeof(const char*[3]); ++i)
defaults.insert(std::make_pair(parameter_list[i][0], std::make_pair(parameter_list[i][1], parameter_list[i][2])));
return defaults;
}
// get the list of currently known labels
labels_t& labels()
{
static labels_t labels = get_labels();
return labels;
}
// get the list of currently known defaults
defaults_t& defaults()
{
static defaults_t defaults = get_defaults();
return defaults;
}
}
/**
* \brief Lists all acceptable input parameters with description
*/
InputParams InputParams::sample()
{
// TODO: load only a given subset of all parameters as sample
// load defaults for sample parameters
InputParams params;
for(defaults_t::iterator it = defaults().begin(); it != defaults().end(); ++it)
params.put(it->first, it->second.first, it->second.second);
return params;
}
/**
* Add a given parameter with default value and comment.
*/
void InputParams::add(std::string label, std::string value, std::string comment)
{
// don't add empty parameters
if(label.empty())
return;
// add the label to the set of known labels
labels().insert(label);
// add the default values
if(!value.empty() || !comment.empty())
defaults().insert(std::make_pair(label, std::make_pair(value, comment)));
}
/**
* Check if a parameter label exists.
*/
bool InputParams::is_known(const std::string& name)
{
return (labels().find(name) != labels().end());
}
| 40.327511 | 168 | 0.667244 | [
"model"
] |
98c23947cd960262310eacfea92bed203184e97a | 2,293 | hpp | C++ | di/abstract_builder.hpp | sal-vage/d-injection | 85289edba0f7f91ef7ebccb8b3ab7f24d89ac79f | [
"BSL-1.0"
] | null | null | null | di/abstract_builder.hpp | sal-vage/d-injection | 85289edba0f7f91ef7ebccb8b3ab7f24d89ac79f | [
"BSL-1.0"
] | 6 | 2016-01-24T18:07:34.000Z | 2016-01-24T18:10:52.000Z | di/abstract_builder.hpp | sal-vage/d-injection | 85289edba0f7f91ef7ebccb8b3ab7f24d89ac79f | [
"BSL-1.0"
] | null | null | null | // Copyright Adam Lach 2012
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef DI_ABSTRACT_BUILDER_HPP
#define DI_ABSTRACT_BUILDER_HPP
#include <di/configurable.hpp>
namespace di {
/**
* Abstract Builder provides convinient abstraction for building objects of abstract or concrete types.
* The main advantage of using abstract_builder is the possibility to mock build methods. If the user does not
* need mocking or can test building using other means (checking injections directly) then using more convinient
* generic_builder is advised.
*/
template<typename T>
class abstract_builder : public di::configurable<T> {
public:
/**
* @brief Performs injections and calls constructed() on subject.
* @pre Injections required by the instance object were provided to the builder.
* @post All provided injections have been injected, subject<T...>::constucted() has been called.
* @throw requirement_not_satisfied Depending on diagnostics method chosen.
* @param instance of builder's corresponding subject.
*/
virtual void build(T& instance) = 0;
/**
* @see di::configurable::use
*/
template<typename U>
abstract_builder<T>& use(U& object) {
(void) di::configurable<T>::use(object);
return *this;
}
/**
* @see di::configurable::use
*/
template<template <typename> class SPtr, typename U>
abstract_builder<T>& use(const SPtr<U>& object) {
(void) di::configurable<T>::use(object);
return *this;
}
/**
* @see di::configurable::replace
*/
template<typename U>
abstract_builder<T>& replace(U& object, size_t at=0) {
(void) di::configurable<T>::replace(object,at);
return *this;
}
/**
* @see di::configurable::replace
*/
template<template <typename> class SPtr, typename U>
abstract_builder<T>& replace(const SPtr<U>& object, size_t at=0) {
(void) di::configurable<T>::replace(object,at);
return *this;
}
/**
* @see di::configurable::remove
*/
template<typename U>
abstract_builder<T>& remove(size_t at=0) {
(void) di::configurable<T>::template remove<U>(at);
return *this;
}
};
} //namspace di
#endif //DI_ABSTRACT_BUILDER_HPP
| 28.308642 | 113 | 0.692106 | [
"object"
] |
98c652b592a856dc1d313818566700a776752ee0 | 5,958 | cpp | C++ | 07. Text Detection with OpenCV CPP/main.cpp | japgo/Machine-Vision-Test | dd098e44555d52030cedde64d1d7a491ba217d62 | [
"Unlicense"
] | null | null | null | 07. Text Detection with OpenCV CPP/main.cpp | japgo/Machine-Vision-Test | dd098e44555d52030cedde64d1d7a491ba217d62 | [
"Unlicense"
] | null | null | null | 07. Text Detection with OpenCV CPP/main.cpp | japgo/Machine-Vision-Test | dd098e44555d52030cedde64d1d7a491ba217d62 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/dnn.hpp>
#pragma comment( lib, "opencv_imgproc400d.lib" )
#pragma comment( lib, "opencv_highgui400d.lib" )
#pragma comment( lib, "opencv_dnn400d.lib" )
#pragma comment( lib, "opencv_core400d.lib" )
#pragma comment( lib, "opencv_video400d.lib" )
#pragma comment( lib, "opencv_videoio400d.lib" )
using namespace cv;
using namespace cv::dnn;
const char* keys =
"{ help h | | Print help message. }"
"{ input i | | Path to input image or video file. Skip this argument to capture frames from a camera.}"
"{ model m | | Path to a binary .pb file contains trained network.}"
"{ width | 320 | Preprocess input image by resizing to a specific width. It should be multiple by 32. }"
"{ height | 320 | Preprocess input image by resizing to a specific height. It should be multiple by 32. }"
"{ thr | 0.5 | Confidence threshold. }"
"{ nms | 0.4 | Non-maximum suppression threshold. }";
void decode( const Mat& scores, const Mat& geometry, float scoreThresh,
std::vector<RotatedRect>& detections, std::vector<float>& confidences );
int main( int argc, char** argv )
{
// Parse command line arguments.
CommandLineParser parser( argc, argv, keys );
parser.about( "Use this script to run TensorFlow implementation (https://github.com/argman/EAST) of "
"EAST: An Efficient and Accurate Scene Text Detector (https://arxiv.org/abs/1704.03155v2)" );
if( argc == 1 || parser.has( "help" ) )
{
//parser.printMessage();
//return 0;
}
float confThreshold = parser.get<float>( "thr" );
float nmsThreshold = parser.get<float>( "nms" );
int inpWidth = parser.get<int>( "width" );
int inpHeight = parser.get<int>( "height" );
String model = parser.get<String>( "model" );
model = "frozen_east_text_detection.pb";
if( !parser.check() )
{
parser.printErrors();
return 1;
}
CV_Assert( !model.empty() );
// Load network.
Net net = readNet( model );
// Open a video file or an image file or a camera stream.
VideoCapture cap;
String input = "C:\\scenetext01.jpg";
cap.open( input );
//cap.open( 0 );
//if( parser.has( "input" ) ) {
// String input = parser.get<String>( "input" );
// input = "C:\\alphabet.bmp";
// cap.open( input );
//}
//else
// cap.open( 0 );
static const std::string kWinName = "EAST: An Efficient and Accurate Scene Text Detector";
namedWindow( kWinName, WINDOW_NORMAL );
std::vector<Mat> outs;
std::vector<String> outNames( 2 );
outNames[ 0 ] = "feature_fusion/Conv_7/Sigmoid";
outNames[ 1 ] = "feature_fusion/concat_3";
Mat frame, blob;
while( waitKey( 1 ) < 0 )
{
cap >> frame;
if( frame.empty() )
{
waitKey();
break;
}
blobFromImage( frame, blob, 1.0, Size( inpWidth, inpHeight ), Scalar( 123.68, 116.78, 103.94 ), true, false );
net.setInput( blob );
net.forward( outs, outNames );
Mat scores = outs[ 0 ];
Mat geometry = outs[ 1 ];
// Decode predicted bounding boxes.
std::vector<RotatedRect> boxes;
std::vector<float> confidences;
decode( scores, geometry, confThreshold, boxes, confidences );
// Apply non-maximum suppression procedure.
std::vector<int> indices;
NMSBoxes( boxes, confidences, confThreshold, nmsThreshold, indices );
// Render detections.
Point2f ratio( ( float )frame.cols / inpWidth, ( float )frame.rows / inpHeight );
for( size_t i = 0; i < indices.size(); ++i )
{
RotatedRect& box = boxes[ indices[ i ] ];
Point2f vertices[ 4 ];
box.points( vertices );
for( int j = 0; j < 4; ++j )
{
vertices[ j ].x *= ratio.x;
vertices[ j ].y *= ratio.y;
}
for( int j = 0; j < 4; ++j )
line( frame, vertices[ j ], vertices[ ( j + 1 ) % 4 ], Scalar( 0, 255, 0 ), 1 );
}
// Put efficiency information.
std::vector<double> layersTimes;
double freq = getTickFrequency() / 1000;
double t = net.getPerfProfile( layersTimes ) / freq;
std::string label = format( "Inference time: %.2f ms", t );
putText( frame, label, Point( 0, 15 ), FONT_HERSHEY_SIMPLEX, 0.5, Scalar( 0, 255, 0 ) );
imshow( kWinName, frame );
}
return 0;
}
void decode( const Mat& scores, const Mat& geometry, float scoreThresh,
std::vector<RotatedRect>& detections, std::vector<float>& confidences )
{
detections.clear();
CV_Assert( scores.dims == 4 ); CV_Assert( geometry.dims == 4 ); CV_Assert( scores.size[ 0 ] == 1 );
CV_Assert( geometry.size[ 0 ] == 1 ); CV_Assert( scores.size[ 1 ] == 1 ); CV_Assert( geometry.size[ 1 ] == 5 );
CV_Assert( scores.size[ 2 ] == geometry.size[ 2 ] ); CV_Assert( scores.size[ 3 ] == geometry.size[ 3 ] );
const int height = scores.size[ 2 ];
const int width = scores.size[ 3 ];
for( int y = 0; y < height; ++y )
{
const float* scoresData = scores.ptr<float>( 0, 0, y );
const float* x0_data = geometry.ptr<float>( 0, 0, y );
const float* x1_data = geometry.ptr<float>( 0, 1, y );
const float* x2_data = geometry.ptr<float>( 0, 2, y );
const float* x3_data = geometry.ptr<float>( 0, 3, y );
const float* anglesData = geometry.ptr<float>( 0, 4, y );
for( int x = 0; x < width; ++x )
{
float score = scoresData[ x ];
if( score < scoreThresh )
continue;
// Decode a prediction.
// Multiple by 4 because feature maps are 4 time less than input image.
float offsetX = x * 4.0f, offsetY = y * 4.0f;
float angle = anglesData[ x ];
float cosA = std::cos( angle );
float sinA = std::sin( angle );
float h = x0_data[ x ] + x2_data[ x ];
float w = x1_data[ x ] + x3_data[ x ];
Point2f offset( offsetX + cosA * x1_data[ x ] + sinA * x2_data[ x ],
offsetY - sinA * x1_data[ x ] + cosA * x2_data[ x ] );
Point2f p1 = Point2f( -sinA * h, -cosA * h ) + offset;
Point2f p3 = Point2f( -cosA * w, sinA * w ) + offset;
RotatedRect r( 0.5f * ( p1 + p3 ), Size2f( w, h ), -angle * 180.0f / ( float )CV_PI );
detections.push_back( r );
confidences.push_back( score );
}
}
} | 33.661017 | 112 | 0.637462 | [
"geometry",
"render",
"vector",
"model"
] |
98caa35e160c96f61226822d2cb0d4f3f8705857 | 11,661 | cpp | C++ | devel/game/GameSequences.cpp | madeso/hopper | ccf330c8f400678f5f5dceea25c0374ed99be511 | [
"WTFPL"
] | null | null | null | devel/game/GameSequences.cpp | madeso/hopper | ccf330c8f400678f5f5dceea25c0374ed99be511 | [
"WTFPL"
] | null | null | null | devel/game/GameSequences.cpp | madeso/hopper | ccf330c8f400678f5f5dceea25c0374ed99be511 | [
"WTFPL"
] | 2 | 2019-04-26T03:00:59.000Z | 2022-01-04T17:36:28.000Z |
#include "GameSequences.h"
#include "game.h"
/** @brief CGameSequence
*
* @todo: document this function
*/
CGameSequence::CGameSequence( CGame* game) {
mDone = false;
mGame = game;
}
/** @brief ~CGameSequence
*
* @todo: document this function
*/
CGameSequence::~CGameSequence() {
}
/*
* For parts that need initialisation after object creation.
*/
void CGameSequence::init() {}
/** @brief done
*
* @todo: document this function
*/
bool CGameSequence::done() {
return( mDone );
}
// ------------------------------------------------------------------------
/** @brief CTimedGameSequence
*
* @todo: document this function
*/
CTimedGameSequence::CTimedGameSequence( CGame* game, int duration):
CGameSequence( game ) {
mDuration = new CDelay( duration );
}
/** @brief ~CTimedGameSequence
*
* @todo: document this function
*/
CTimedGameSequence::~CTimedGameSequence() {
delete( mDuration );
}
void CTimedGameSequence::init() {
mDuration->restart();
}
bool CTimedGameSequence::isOver() {
mDone = mDuration->isOver();
return( mDone );
}
// --------------------------------------------------------------------------
CGameOverSequence::CGameOverSequence( CGame* game ): CGameSequence( game ) {
mGame->switchCameraController( new CRotateAroundCameraController( mGame->getCamera(), mGame->getShip() ) );
mGame->switchShipController( new CEmptyShipController( mGame->getShip() ) );
}
bool CGameOverSequence::done() {
return( true );
}
CWaitForInputSequence::CWaitForInputSequence( CGame* game ): CGameSequence( game ) {
mGameMessageWindow = new CGameMessageWindow();
}
CWaitForInputSequence::~CWaitForInputSequence() {
delete( mGameMessageWindow );
}
void CWaitForInputSequence::init() {
mGameMessageWindow->setMessage( "Press [Thrust] or [Fire] to continue." );
}
bool CWaitForInputSequence::done() {
if( CInputManager::getInstance()->isReleased( IMP_THRUST )
|| CInputManager::getInstance()->isReleased( IMR_FIRE ) ) {
mGame->setStatus( GS_END );
mDone = true;
}
return( mDone );
}
CPauseSequence::CPauseSequence( CGame* game ): CTimedGameSequence( game, 2000 ) { }
bool CPauseSequence::done() {
return( isOver() );
}
// --------------------------------------------------------------------------
CLandingGameplaySequence::CLandingGameplaySequence( CGame* game ): CGameSequence( game ) {
mGame->switchCameraController( new CBehindCameraController( mGame->getCamera(), mGame->getShip() ));
mGame->switchShipController( new CPlayerControlledShipController(mGame->getShip() ));
}
bool CLandingGameplaySequence::done() {
mGame->gameplay();
switch( mGame->getStatus() ) {
case GS_GAMEOVER: /* CGame::GAMEOVER */
mGame->addSequence( "gameover", new CGameOverSequence( mGame ) );
mGame->addSequence( "pause", new CPauseSequence( mGame ) );
mGame->addSequence( "waitforinput", new CWaitForInputSequence( mGame ), "pause" );
mDone = true;
break;
case GS_GAMEWON: /* CGame::GAMEWON */
mGame->addSequence( "gamewon", new CLandingWonSequence( mGame ) );
mGame->addSequence( "pause", new CPauseSequence( mGame ) );
mGame->addSequence( "waitforinput", new CWaitForInputSequence( mGame ), "pause" );
mDone = true;
break;
case GS_REFUELING:
mGame->addSequence( "refueling", new CRefuelingSequence( mGame ) );
mDone = true;
break;
}
return( mDone );
}
// --------------------------------------------------------------------------
#include "hoppersounds.h"
CRefuelingSequence::CRefuelingSequence( CGame* game ): CGameSequence( game ) {
mGame->switchCameraController( new CRotateAroundCameraController( mGame->getCamera(), mGame->getShip(), 3 ));
mGame->switchShipController( new CEmptyShipController(mGame->getShip() ));
mSoundRefuel=new CSound3D( SOUND_REFUEL, true );
mSoundRefuel->setPosition( mGame->getShip()->getPosition() );
mSoundRefuel->play();
}
CRefuelingSequence::~CRefuelingSequence() {
delete( mSoundRefuel );
}
void CRefuelingSequence::init() {
}
bool CRefuelingSequence::done() {
CShip* ship = mGame->getShip();
if( ship->getFuel() < 100 ) {
ship->refuel( CTimeManager::getInstance()->getTimeFactor()/10.f );
return( false );
}
else {
CSoundManager::getInstance()->play3D( SOUND_REFUEL_OK, ship->getPosition(), 1 );
mSoundRefuel->stop();
mGame->addSequence( "Landing Gameplay", new CLandingGameplaySequence( mGame ) );
mGame->setStatus( GS_GAMEPLAY );
return( true );
}
}
// --------------------------------------------------------------------------
CLandingWonSequence::CLandingWonSequence( CGame* game ): CGameSequence( game ) {
mGame->switchCameraController( new CRotateAroundCameraController( mGame->getCamera(), mGame->getShip() ));
mGame->switchShipController( new CEmptyShipController( mGame->getShip() ));
}
bool CLandingWonSequence::done() {
return( true );
}
// ========================================================================
#include "AIShipControllers.h"
CRacingPreStartSequence::CRacingPreStartSequence( CGame* game ): CGameSequence( game ) {
CLevel* level = mGame->getLevel();
CShip* ship = mGame->getShip();
mGame->switchShipController( new CAutoHoverShipController( mGame->getShip() ));
mMessageWindow = new CGameMessageWindow();
mMessageWindow->setMessage("Press Thrust to continue" );
// build list of rings
std::vector< CRing* > rings;
for ( CLevel::GameObjectList::const_iterator i = level->mGameObjectList.begin(); i != level->mGameObjectList.end(); ++i ) {
if( (*i).actor ) {
if ( typeid( *(( *i ).actor ) ) == typeid( CRing ) ) {
rings.push_back( static_cast<CRing*>((*i).actor) );
}
}
}
// init of the camera path controller
CTrackCameraController* camController = new CTrackCameraController( mGame->getCamera() );
mGame->switchCameraController( camController );
camController->addKey( ship->getPosition() + Ogre::Vector3( 10, 10, 0 ), ship->getPosition() );
camController->addKey( ship->getPosition() + Ogre::Vector3( 0, 10, 10 ), ship->getPosition() );
camController->addKey( ship->getPosition() + Ogre::Vector3( 0, 5, 0 ), (*rings.begin())->getPosition() );
for( std::vector<CRing*>::const_iterator i = rings.begin(); i != rings.end(); ++i ) {
if( (i+1) != rings.end() ) {
camController->addKey( (*i)->getPosition(), (*(i+1))->getPosition() );
} else {
camController->addKey( (*i)->getPosition(), ship->getPosition() );
}
}
// copy of the first two positions
camController->addKey( ship->getPosition() + Ogre::Vector3( 10, 10, 0 ), ship->getPosition() );
camController->addKey( ship->getPosition() + Ogre::Vector3( 0, 10, 10 ), ship->getPosition() );
}
// --------------------------------------------------------------------------
CRacingPreStartSequence::~CRacingPreStartSequence() {
delete( mMessageWindow );
}
bool CRacingPreStartSequence::done() {
if( CInputManager::getInstance()->isReleased( IMP_THRUST )
|| CInputManager::getInstance()->isReleased( IMR_FIRE ) ) {
mDone = true;
mGame->addSequence( "racing sequence", new CRacingStartSequence(mGame ) );
}
return( mDone );
}
// --------------------------------------------------------------------------
CRacingStartSequence::CRacingStartSequence( CGame* game ): CTimedGameSequence( game, 5000 ) {
mGame->switchShipController( new CAutoHoverShipController( mGame->getShip() ));
mGame->switchCameraController( new CRotateAroundCameraController( mGame->getCamera(), mGame->getShip() ));
mCountDown = new CCountDown();
mDoGo = true;
}
void CRacingStartSequence::init() {
}
CRacingStartSequence::~CRacingStartSequence() {
delete( mCountDown );
}
bool CRacingStartSequence::done() {
if( mDoGo && mCountDown->done() ) {
mGame->addSequence( "gameplay", new CRacingGameplaySequence( mGame ) );
mDoGo = false;
}
return( isOver() );
}
// --------------------------------------------------------------------------
CRacingGameplaySequence::CRacingGameplaySequence( CGame* game ): CGameSequence( game ) {
mGame->switchShipController( new CPlayerControlledShipController( mGame->getShip() ) );
mGame->switchCameraController( new CBehindCameraController( mGame->getCamera(), mGame->getShip() ) );
}
bool CRacingGameplaySequence::done() {
mGame->gameplay();
switch( mGame->getStatus() ) {
case GS_GAMEOVER: /* CGame::GAMEOVER */
mGame->addSequence( "gameover", new CGameOverSequence( mGame ) );
mGame->addSequence( "pause", new CPauseSequence( mGame ) );
mGame->addSequence( "waitforinput", new CWaitForInputSequence( mGame ), "pause" );
mDone = true;
break;
case GS_GAMEWON: /* CGame::GAMEWON */
mGame->addSequence( "gamewon", new CRacingWonSequence( mGame ) );
mGame->addSequence( "pause", new CPauseSequence( mGame ) );
mGame->addSequence( "waitforinput", new CWaitForInputSequence( mGame ), "pause" );
mDone = true;
break;
}
return( mDone );
}
// --------------------------------------------------------------------------
CRacingWonSequence::CRacingWonSequence( CGame* game ): CGameSequence( game ) {
mGame->switchShipController( new CAutoHoverShipController( mGame->getShip() ));
mGame->switchCameraController( new CRotateAroundCameraController( mGame->getCamera(), mGame->getShip() ));
}
bool CRacingWonSequence::done() {
return( true );
}
// =================================================================================
// =================================================================================
/*
Tutorial sequences :
Start => camera animation ? message ? image showing yaw/pitch/roll ?
Thrust message => Interface box explaining that only thrusting is activated
( Thrust sequence => camera animation showing boxes ? )
Thrust gameplay
Orientation message => message "no thrust"
Orientation sequence => gameplay
Roll message => message "only roll"
( Roll sequence ? => showing rings ? )
Roll gameplay
Pitch message => "only pitch"
( Pitch sequence ? => camera movement showing rings ? )
Pitch gameplay
End => message "well done" ( + camera movement ? )
*/
CTutorialCompleteSequence::CTutorialCompleteSequence( CGame* game ): CTimedGameSequence( game, 5000 ) {
mGame->switchCameraController( new CRotateAroundCameraController( mGame->getCamera(), mGame->getShip() ));
mGame->switchShipController( new CEmptyShipController( mGame->getShip() ) );
}
bool CTutorialCompleteSequence::done() {
return( isOver() );
}
CTutorialGameplaySequence::CTutorialGameplaySequence( CGame* game ): CGameSequence( game ) {
//mGame->switchCameraController( new CBehindCameraController( mGame->getCamera(), mGame->getShip() ) );
//mGame->switchShipController( new CPlayerControlledShipController( mGame->getShip() ) );
}
bool CTutorialGameplaySequence::done() {
mGame->gameplay();
if( mGame->getStatus() == GS_END ) {
mDone=true;
mGame->addSequence( "tutorial_complete", new CTutorialCompleteSequence( mGame ) );
}
return( mDone );
}
| 25.405229 | 127 | 0.602178 | [
"object",
"vector"
] |
98cd6ee76b4b2c4092b15b80541da365f7e4a2a4 | 4,011 | cc | C++ | core/src/extcmd/command_server.cc | joe4568/centreon-broker | daf454371520989573c810be1f6dfca40979a75d | [
"Apache-2.0"
] | null | null | null | core/src/extcmd/command_server.cc | joe4568/centreon-broker | daf454371520989573c810be1f6dfca40979a75d | [
"Apache-2.0"
] | null | null | null | core/src/extcmd/command_server.cc | joe4568/centreon-broker | daf454371520989573c810be1f6dfca40979a75d | [
"Apache-2.0"
] | null | null | null | /*
** Copyright 2015 Centreon
**
** 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.
**
** For more information : contact@centreon.com
*/
#include <QLocalSocket>
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/extcmd/command_client.hh"
#include "com/centreon/broker/extcmd/command_request.hh"
#include "com/centreon/broker/extcmd/command_result.hh"
#include "com/centreon/broker/extcmd/command_server.hh"
#include "com/centreon/broker/extcmd/plaintext_command_parser.hh"
#include "com/centreon/broker/extcmd/json_command_parser.hh"
#include "com/centreon/broker/extcmd/server_socket.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/processing/feeder.hh"
using namespace com::centreon::broker;
using namespace com::centreon::broker::extcmd;
/**
* Constructor.
*
* @param[in] prot The protocol used by this server.
* @param[in] socket_file Socket file.
* @param[in] cache Endpoint persistent cache.
*/
command_server::command_server(
protocol prot,
std::string const& socket_file,
misc::shared_ptr<persistent_cache> cache)
: io::endpoint(true),
_listener_thread(NULL),
_protocol(prot),
_socket_file(socket_file) {
(void)cache;
}
/**
* Destructor.
*/
command_server::~command_server() {
if (_listener_thread) {
_listener_thread->exit();
_listener_thread->wait();
delete _listener_thread;
}
}
/**
* Wait for a new connection to local socket.
*
* @return New client object if available, null pointer otherwise.
*/
misc::shared_ptr<io::stream> command_server::open() {
// Initialization.
if (!_socket.get()) {
// Listen on socket.
::remove(_socket_file.c_str());
_socket.reset(new server_socket(_socket_file));
// Create command listener.
_listener = new command_listener;
// Create command parser.
if (_protocol == json)
_parser = new json_command_parser(*_listener);
else
_parser = new plaintext_command_parser(*_listener);
// Create listener thread.
uset<unsigned int> write_filters;
write_filters.insert(command_request::static_type());
write_filters.insert(command_result::static_type());
_listener_thread = new processing::feeder(
"(external commands)",
_listener,
uset<unsigned int>(),
write_filters);
_listener_thread->start();
}
// Wait for incoming connections.
logging::debug(logging::medium)
<< "command: waiting for new connection";
if (!_socket->has_pending_connections()) {
bool timedout(false);
_socket->wait_for_new_connection(1000, &timedout);
if (!_socket->has_pending_connections()) {
if (timedout)
return (misc::shared_ptr<io::stream>());
else
throw (exceptions::msg()
<< "command: error while waiting on client on file '"
<< _socket_file << "': " << _socket->error_string());
}
}
// Accept new client.
int incoming(_socket->next_pending_connection());
if (incoming < 0)
throw (exceptions::msg() << "command: could not accept client: "
<< _socket->error_string());
logging::info(logging::medium) << "command: new client connected";
misc::shared_ptr<io::stream>
new_client(new command_client(incoming, *_parser.data()));
return (new_client);
}
| 33.425 | 75 | 0.664921 | [
"object"
] |
98d0e622a871abe78d74678560d992993003f753 | 4,571 | cc | C++ | ThirdParty/webrtc/src/webrtc/modules/audio_coding/main/acm2/acm_dump_unittest.cc | JokeJoe8806/licode-windows | 2bfdaf6e87669df2b9960da50c6800bc3621b80b | [
"MIT"
] | 8 | 2018-12-27T14:57:13.000Z | 2021-04-07T07:03:15.000Z | ThirdParty/webrtc/src/webrtc/modules/audio_coding/main/acm2/acm_dump_unittest.cc | JokeJoe8806/licode-windows | 2bfdaf6e87669df2b9960da50c6800bc3621b80b | [
"MIT"
] | 1 | 2019-03-13T01:35:03.000Z | 2020-10-08T04:13:04.000Z | ThirdParty/webrtc/src/webrtc/modules/audio_coding/main/acm2/acm_dump_unittest.cc | JokeJoe8806/licode-windows | 2bfdaf6e87669df2b9960da50c6800bc3621b80b | [
"MIT"
] | 9 | 2018-12-28T11:45:12.000Z | 2021-05-11T02:15:31.000Z | /*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifdef RTC_AUDIOCODING_DEBUG_DUMP
#include <stdio.h>
#include <string>
#include <vector>
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/base/scoped_ptr.h"
#include "webrtc/modules/audio_coding/main/acm2/acm_dump.h"
#include "webrtc/system_wrappers/interface/clock.h"
#include "webrtc/test/test_suite.h"
#include "webrtc/test/testsupport/fileutils.h"
#include "webrtc/test/testsupport/gtest_disable.h"
// Files generated at build-time by the protobuf compiler.
#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
#include "external/webrtc/webrtc/modules/audio_coding/dump.pb.h"
#else
#include "webrtc/audio_coding/dump.pb.h"
#endif
namespace webrtc {
// Test for the acm dump class. Dumps some RTP packets to disk, then reads them
// back to see if they match.
class AcmDumpTest : public ::testing::Test {
public:
void VerifyResults(const ACMDumpEventStream& parsed_stream,
size_t packet_size) {
// Verify the result.
EXPECT_EQ(5, parsed_stream.stream_size());
const ACMDumpEvent& start_event = parsed_stream.stream(2);
ASSERT_TRUE(start_event.has_type());
EXPECT_EQ(ACMDumpEvent::DEBUG_EVENT, start_event.type());
EXPECT_TRUE(start_event.has_timestamp_us());
EXPECT_FALSE(start_event.has_packet());
ASSERT_TRUE(start_event.has_debug_event());
auto start_debug_event = start_event.debug_event();
ASSERT_TRUE(start_debug_event.has_type());
EXPECT_EQ(ACMDumpDebugEvent::LOG_START, start_debug_event.type());
ASSERT_TRUE(start_debug_event.has_message());
for (int i = 0; i < parsed_stream.stream_size(); i++) {
if (i == 2) {
// This is the LOG_START packet that was already verified.
continue;
}
const ACMDumpEvent& test_event = parsed_stream.stream(i);
ASSERT_TRUE(test_event.has_type());
EXPECT_EQ(ACMDumpEvent::RTP_EVENT, test_event.type());
EXPECT_TRUE(test_event.has_timestamp_us());
EXPECT_FALSE(test_event.has_debug_event());
ASSERT_TRUE(test_event.has_packet());
const ACMDumpRTPPacket& test_packet = test_event.packet();
ASSERT_TRUE(test_packet.has_direction());
if (i <= 1) {
EXPECT_EQ(ACMDumpRTPPacket::INCOMING, test_packet.direction());
} else if (i >= 3) {
EXPECT_EQ(ACMDumpRTPPacket::OUTGOING, test_packet.direction());
}
ASSERT_TRUE(test_packet.has_rtp_data());
ASSERT_EQ(packet_size, test_packet.rtp_data().size());
for (size_t i = 0; i < packet_size; i++) {
EXPECT_EQ(rtp_packet_[i],
static_cast<uint8_t>(test_packet.rtp_data()[i]));
}
}
}
void Run(int packet_size, int random_seed) {
rtp_packet_.clear();
rtp_packet_.reserve(packet_size);
srand(random_seed);
// Fill the packet vector with random data.
for (int i = 0; i < packet_size; i++) {
rtp_packet_.push_back(rand());
}
// Find the name of the current test, in order to use it as a temporary
// filename.
auto test_info = ::testing::UnitTest::GetInstance()->current_test_info();
const std::string temp_filename =
test::OutputPath() + test_info->test_case_name() + test_info->name();
// When log_dumper goes out of scope, it causes the log file to be flushed
// to disk.
{
rtc::scoped_ptr<AcmDump> log_dumper(AcmDump::Create());
log_dumper->LogRtpPacket(true, rtp_packet_.data(), rtp_packet_.size());
log_dumper->LogRtpPacket(true, rtp_packet_.data(), rtp_packet_.size());
log_dumper->StartLogging(temp_filename, 10000000);
log_dumper->LogRtpPacket(false, rtp_packet_.data(), rtp_packet_.size());
log_dumper->LogRtpPacket(false, rtp_packet_.data(), rtp_packet_.size());
}
// Read the generated file from disk.
ACMDumpEventStream parsed_stream;
ASSERT_EQ(true, AcmDump::ParseAcmDump(temp_filename, &parsed_stream));
VerifyResults(parsed_stream, packet_size);
// Clean up temporary file - can be pretty slow.
remove(temp_filename.c_str());
}
std::vector<uint8_t> rtp_packet_;
};
TEST_F(AcmDumpTest, DumpAndRead) {
Run(256, 321);
}
} // namespace webrtc
#endif // RTC_AUDIOCODING_DEBUG_DUMP
| 36.568 | 79 | 0.703566 | [
"vector"
] |
98d873566e32c015a1177031aac671491c383c61 | 6,542 | cc | C++ | SimCalorimetry/HcalZeroSuppressionProducers/src/HcalRealisticZS.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 13 | 2015-11-30T15:49:45.000Z | 2022-02-08T16:11:30.000Z | SimCalorimetry/HcalZeroSuppressionProducers/src/HcalRealisticZS.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 640 | 2015-02-11T18:55:47.000Z | 2022-03-31T14:12:23.000Z | SimCalorimetry/HcalZeroSuppressionProducers/src/HcalRealisticZS.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 51 | 2015-08-11T21:01:40.000Z | 2022-03-30T07:31:34.000Z | #include "CalibFormats/HcalObjects/interface/HcalDbRecord.h"
#include "DataFormats/Common/interface/EDCollection.h"
#include "DataFormats/Common/interface/Handle.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/Utilities/interface/Exception.h"
#include "HcalRealisticZS.h"
#include <iostream>
#include <memory>
HcalRealisticZS::HcalRealisticZS(edm::ParameterSet const &conf)
: inputLabel_(conf.getParameter<std::string>("digiLabel")) {
bool markAndPass = conf.getParameter<bool>("markAndPass");
bool useInstanceLabels = conf.getParameter<bool>("useInstanceLabels");
// register for data access
tok_hbhe_ = consumes<HBHEDigiCollection>(edm::InputTag(inputLabel_));
tok_ho_ = consumes<HODigiCollection>(edm::InputTag(inputLabel_));
tok_hf_ = consumes<HFDigiCollection>(edm::InputTag(inputLabel_));
tok_hfQIE10_ =
consumes<QIE10DigiCollection>(edm::InputTag(inputLabel_, useInstanceLabels ? "HFQIE10DigiCollection" : ""));
tok_hbheQIE11_ =
consumes<QIE11DigiCollection>(edm::InputTag(inputLabel_, useInstanceLabels ? "HBHEQIE11DigiCollection" : ""));
tok_dbService_ = esConsumes<HcalDbService, HcalDbRecord>();
bool use1ts_ = conf.getParameter<bool>("use1ts");
std::vector<int> tmp = conf.getParameter<std::vector<int>>("HBregion");
if (tmp[0] < 0 || tmp[0] > 9 || tmp[1] < 0 || tmp[1] > 9 || tmp[0] > tmp[1]) {
edm::LogError("HcalZeroSuppression") << "ZS(HB) region error: " << tmp[0] << ":" << tmp[1];
tmp[0] = 0;
tmp[1] = 9;
}
std::pair<int, int> HBsearchTS(tmp[0], tmp[1]);
tmp = conf.getParameter<std::vector<int>>("HEregion");
if (tmp[0] < 0 || tmp[0] > 9 || tmp[1] < 0 || tmp[1] > 9 || tmp[0] > tmp[1]) {
edm::LogError("HcalZeroSuppression") << "ZS(HE) region error: " << tmp[0] << ":" << tmp[1];
tmp[0] = 0;
tmp[1] = 9;
}
std::pair<int, int> HEsearchTS(tmp[0], tmp[1]);
tmp = conf.getParameter<std::vector<int>>("HOregion");
if (tmp[0] < 0 || tmp[0] > 9 || tmp[1] < 0 || tmp[1] > 9 || tmp[0] > tmp[1]) {
edm::LogError("HcalZeroSuppression") << "ZS(HO) region error: " << tmp[0] << ":" << tmp[1];
tmp[0] = 0;
tmp[1] = 9;
}
std::pair<int, int> HOsearchTS(tmp[0], tmp[1]);
tmp = conf.getParameter<std::vector<int>>("HFregion");
if (tmp[0] < 0 || tmp[0] > 9 || tmp[1] < 0 || tmp[1] > 9 || tmp[0] > tmp[1]) {
edm::LogError("HcalZeroSuppression") << "ZS(HF) region error: " << tmp[0] << ":" << tmp[1];
tmp[0] = 0;
tmp[1] = 9;
}
std::pair<int, int> HFsearchTS(tmp[0], tmp[1]);
// this constructor will be called if useConfigZSvalues is set to 1 in
// HcalZeroSuppressionProducers/python/hcalDigisRealistic_cfi.py
// which means that channel-by-channel ZS thresholds from DB will NOT be used
if (conf.getParameter<int>("useConfigZSvalues")) {
algo_ = std::make_unique<HcalZSAlgoRealistic>(markAndPass,
use1ts_,
conf.getParameter<int>("HBlevel"),
conf.getParameter<int>("HElevel"),
conf.getParameter<int>("HOlevel"),
conf.getParameter<int>("HFlevel"),
HBsearchTS,
HEsearchTS,
HOsearchTS,
HFsearchTS);
} else {
algo_ = std::make_unique<HcalZSAlgoRealistic>(markAndPass, use1ts_, HBsearchTS, HEsearchTS, HOsearchTS, HFsearchTS);
}
produces<HBHEDigiCollection>();
produces<HODigiCollection>();
produces<HFDigiCollection>();
produces<QIE10DigiCollection>("HFQIE10DigiCollection");
produces<QIE11DigiCollection>("HBHEQIE11DigiCollection");
}
HcalRealisticZS::~HcalRealisticZS() { algo_->clearDbService(); }
void HcalRealisticZS::produce(edm::Event &e, const edm::EventSetup &eventSetup) {
edm::Handle<HBHEDigiCollection> hbhe;
edm::Handle<HODigiCollection> ho;
edm::Handle<HFDigiCollection> hf;
edm::Handle<QIE10DigiCollection> hfQIE10;
edm::Handle<QIE11DigiCollection> hbheQIE11;
edm::ESHandle<HcalDbService> conditions = eventSetup.getHandle(tok_dbService_);
algo_->setDbService(conditions.product());
e.getByToken(tok_hbhe_, hbhe);
// create empty output
std::unique_ptr<HBHEDigiCollection> zs_hbhe(new HBHEDigiCollection);
e.getByToken(tok_ho_, ho);
// create empty output
std::unique_ptr<HODigiCollection> zs_ho(new HODigiCollection);
e.getByToken(tok_hf_, hf);
// create empty output
std::unique_ptr<HFDigiCollection> zs_hf(new HFDigiCollection);
e.getByToken(tok_hfQIE10_, hfQIE10);
e.getByToken(tok_hbheQIE11_, hbheQIE11);
// create empty output
std::unique_ptr<HBHEDigiCollection> zs_hbheUpgrade(new HBHEDigiCollection);
std::unique_ptr<HFDigiCollection> zs_hfUpgrade(new HFDigiCollection);
std::unique_ptr<QIE10DigiCollection> zs_hfQIE10(new QIE10DigiCollection(hfQIE10->samples()));
std::unique_ptr<QIE11DigiCollection> zs_hbheQIE11(new QIE11DigiCollection(hbheQIE11->samples()));
// run the algorithm
algo_->suppress(*(hbhe.product()), *zs_hbhe);
algo_->suppress(*(ho.product()), *zs_ho);
algo_->suppress(*(hf.product()), *zs_hf);
algo_->suppress(*(hfQIE10.product()), *zs_hfQIE10);
algo_->suppress(*(hbheQIE11.product()), *zs_hbheQIE11);
edm::LogInfo("HcalZeroSuppression") << "Suppression (HBHE) input " << hbhe->size() << " digis, output "
<< zs_hbhe->size() << " digis"
<< " (HO) input " << ho->size() << " digis, output " << zs_ho->size() << " digis"
<< " (HF) input " << hf->size() << " digis, output " << zs_hf->size() << " digis"
<< " (HFQIE10) input " << hfQIE10->size() << " digis, output "
<< zs_hfQIE10->size() << " digis"
<< " (HBHEQIE11) input " << hbheQIE11->size() << " digis, output "
<< zs_hbheQIE11->size() << " digis";
// return result
e.put(std::move(zs_hbhe));
e.put(std::move(zs_ho));
e.put(std::move(zs_hf));
e.put(std::move(zs_hfQIE10), "HFQIE10DigiCollection");
e.put(std::move(zs_hbheQIE11), "HBHEQIE11DigiCollection");
}
| 43.90604 | 120 | 0.61174 | [
"vector"
] |
98d90a221147b0ea609cdf4a16a7b0d3d2a5c7d1 | 7,280 | cpp | C++ | src/recog/Eigenfaces.cpp | dacap/loseface | 677f46b9da3e11be3b75e3a35f5ca3f1b8df6d52 | [
"MIT"
] | 2 | 2017-11-01T09:09:20.000Z | 2020-01-22T04:56:46.000Z | src/recog/Eigenfaces.cpp | dacap/loseface | 677f46b9da3e11be3b75e3a35f5ca3f1b8df6d52 | [
"MIT"
] | null | null | null | src/recog/Eigenfaces.cpp | dacap/loseface | 677f46b9da3e11be3b75e3a35f5ca3f1b8df6d52 | [
"MIT"
] | 1 | 2019-01-24T12:13:24.000Z | 2019-01-24T12:13:24.000Z | // Copyright (C) 2008-2010 David Capello
//
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.
#include <iostream>
#include <fstream>
#include "recog/Eigenfaces.h"
#include "recog/recog_util.h"
using namespace recog;
//////////////////////////////////////////////////////////////////////
Eigenfaces::Eigenfaces(SubjectsList& subjects)
: m_pixelsPerImage(subjects.getImageWidth() *
subjects.getImageHeight())
, m_imageCount(subjects.getImageCount())
, m_dataSet(m_pixelsPerImage, // rows
m_imageCount) // columns
{
// colocamos los niveles de grises de cada imagen en dataSet
for (int j=0; j<m_imageCount; j++) {
Vector<double> faceImage = image2vector(subjects.getImage(j).get());
m_dataSet.setCol(j, faceImage);
}
// calculamos la media de todas las caras
m_dataSet.meanCol(m_meanFace);
// quitamos la media a cada pixel (dataSet termina siendo los datos
// de las imágenes pero con media nula)
for (int j=0; j<m_imageCount; ++j) {
for (int i=0; i<m_pixelsPerImage; ++i)
m_dataSet(i, j) -= m_meanFace(i);
}
}
Eigenfaces::~Eigenfaces()
{
}
void Eigenfaces::save(const char* filename) const
{
using namespace std;
unsigned eigenvalues_size = m_eigenvalues.size();
unsigned meanFace_size = m_meanFace.size();
unsigned eigenvectors_rows = m_eigenvectors.rows();
unsigned eigenvectors_cols = m_eigenvectors.cols();
unsigned eigenfaces_rows = m_eigenfaces.rows();
unsigned eigenfaces_cols = m_eigenfaces.cols();
ofstream f(filename, ios::binary);
f.write((char*)&eigenvalues_size, sizeof(unsigned));
f.write((char*)m_eigenvalues.getRaw(), sizeof(double)*eigenvalues_size);
f.write((char*)&meanFace_size, sizeof(unsigned));
f.write((char*)m_meanFace.getRaw(), sizeof(double)*meanFace_size);
f.write((char*)&eigenvectors_rows, sizeof(unsigned));
f.write((char*)&eigenvectors_cols, sizeof(unsigned));
f.write((char*)m_eigenvectors.getRaw(), sizeof(double)*eigenvectors_rows*eigenvectors_cols);
f.write((char*)&eigenfaces_rows, sizeof(unsigned));
f.write((char*)&eigenfaces_cols, sizeof(unsigned));
f.write((char*)m_eigenfaces.getRaw(), sizeof(double)*eigenfaces_rows*eigenfaces_cols);
}
void Eigenfaces::load(const char* filename)
{
using namespace std;
ifstream f(filename, ios::binary);
unsigned eigenvalues_size;
unsigned meanFace_size;
unsigned eigenvectors_rows;
unsigned eigenvectors_cols;
unsigned eigenfaces_rows;
unsigned eigenfaces_cols;
f.read((char*)&eigenvalues_size, sizeof(unsigned));
m_eigenvalues.resize(eigenvalues_size);
f.read((char*)m_eigenvalues.getRaw(), sizeof(double)*eigenvalues_size);
f.read((char*)&meanFace_size, sizeof(unsigned));
m_meanFace.resize(meanFace_size);
f.read((char*)m_meanFace.getRaw(), sizeof(double)*meanFace_size);
f.read((char*)&eigenvectors_rows, sizeof(unsigned));
f.read((char*)&eigenvectors_cols, sizeof(unsigned));
m_eigenvectors.resize(eigenvectors_rows, eigenvectors_cols);
f.read((char*)m_eigenvectors.getRaw(), sizeof(double)*eigenvectors_rows*eigenvectors_cols);
f.read((char*)&eigenfaces_rows, sizeof(unsigned));
f.read((char*)&eigenfaces_cols, sizeof(unsigned));
m_eigenfaces.resize(eigenfaces_rows, eigenfaces_cols);
f.read((char*)m_eigenfaces.getRaw(), sizeof(double)*eigenfaces_rows*eigenfaces_cols);
m_eigenfaceComponents = eigenfaces_cols;
}
/// Calculate eivenvalues and sort them in descendant order.
///
bool Eigenfaces::calculateEigenvalues()
{
// Obtener la matriz de covarianza de MxM para calcular sus
// eigenvectores (donde M es la cantidad de fotos de
// entrenamiento). Así evitamos calcular los N eigenvectores de la
// matriz de covarianza real (una matriz de NxN, A*At, donde N es la
// cantidad de pixeles)
Matrix<double> covarianceMatrix;
m_dataSet.getTranspose(covarianceMatrix);
covarianceMatrix *= m_dataSet;
std::cout << "covarianceMatrix = " << covarianceMatrix.rows() << " x " << covarianceMatrix.cols() << "\n";
// calcular los eigenvectores que sirven para formar las eigenfaces
// por medio de una combinación lineal
try {
covarianceMatrix.eig_sym(m_eigenvalues,
m_eigenvectors);
}
catch (std::exception& e) {
return false;
}
// ordenar los eigenvectores según su correspondiente eigenvalor
// (un eigenvalor más grande es más significante)
for (int i=0; i<m_eigenvalues.size(); ++i) { // TODO reemplazar con un qsort?
for (int j=i+1; j<m_eigenvalues.size(); ++j) {
if (std::fabs(m_eigenvalues(j)) > std::fabs(m_eigenvalues(i))) {
// intercambiar eigenvalores
std::swap(m_eigenvalues(i), m_eigenvalues(j));
// intercambiar eigenvectores
{
Vector<double> aux = m_eigenvectors.getCol(j);
m_eigenvectors.setCol(j, m_eigenvectors.getCol(i));
m_eigenvectors.setCol(i, aux);
}
}
}
}
#if 1
std::cout << "----------------------------------------------------------------------\n";
std::cout << "Eigenvalores (" << m_eigenvalues.size() << "):\n";
double accum = 0.0, total = 0.0;
for (int i=0; i<m_eigenvalues.size(); ++i)
total += m_eigenvalues(i);
std::cout << 0 << "\t" << 0 << "\n";
for (int i=0; i<m_eigenvalues.size(); ++i) {
accum += m_eigenvalues(i);
std::cout << (i+1) << "\t" << (accum/total) << "\t" << "\n";
}
std::cout << "----------------------------------------------------------------------\n";
#endif
}
/// Calculates the eigenfaces.
///
/// @warning You have to call #calculateEigenvalues before.
///
bool Eigenfaces::calculateEigenfaces(int components)
{
assert(components > 0 && components <= m_eigenvalues.size());
m_eigenfaceComponents = components;
// Calculate eigenfaces...
m_eigenfaces.resize(m_pixelsPerImage, // rows
m_eigenfaceComponents); // columns
Vector<double> eigenface(m_pixelsPerImage);
for (int i=0; i<m_eigenfaceComponents; ++i) {
eigenface.zero();
for (int j=0; j<m_imageCount; ++j)
eigenface += m_eigenvectors(i, j) * m_dataSet.getCol(j);
m_eigenfaces.setCol(i, eigenface);
}
return true;
}
/// Devuelve la cantidad de componentes de eigenfaces que deberían ser
/// necesarios para la cantidad de información que se desea representar.
///
/// @param levelOfInfo
/// 1.0 significa toda la información, 0.8 un 80% de la información, etc.
/// @return
/// La cantidad de componentes para las eigenfaces. Supuestamente
/// usted luego debería llamar a #calculateEigenfaces con el valor
/// retornado.
///
int Eigenfaces::getNumComponentsFor(double levelOfInfo) const
{
double total = 0.0;
for (int i=0; i<m_eigenvalues.size(); ++i)
total += m_eigenvalues(i);
double accum = 0.0;
for (int i=0; i<m_eigenvalues.size(); ++i) {
accum += m_eigenvalues(i);
if (accum/total >= levelOfInfo)
return i+1;
}
return m_eigenvalues.size();
}
/// Proyecta la imagen @a faceImage en el eigenspace, devolviendo su
/// correspondiente "facespacePoint".
///
Vector<double> Eigenfaces::projectInEigenspace(Vector<double>& faceImage) const
{
Vector<double> eigenspacePoint(m_eigenfaceComponents);
for (int k=0; k<m_eigenfaceComponents; ++k)
eigenspacePoint(k) = m_eigenfaces.getCol(k) * (faceImage - m_meanFace);
return eigenspacePoint;
}
| 31.652174 | 108 | 0.684753 | [
"vector"
] |
98eb1c72b82e86b39aa9629ab850c1b39e3eb2e8 | 4,853 | hpp | C++ | source/vulkan/runtime_vk.hpp | ZachHembree/reshade | b0278661b8b78d060d432f94abe04df33296457b | [
"BSD-3-Clause"
] | null | null | null | source/vulkan/runtime_vk.hpp | ZachHembree/reshade | b0278661b8b78d060d432f94abe04df33296457b | [
"BSD-3-Clause"
] | null | null | null | source/vulkan/runtime_vk.hpp | ZachHembree/reshade | b0278661b8b78d060d432f94abe04df33296457b | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2014 Patrick Mours. All rights reserved.
* License: https://github.com/crosire/reshade#license
*/
#pragma once
#include "runtime.hpp"
#include "render_vk.hpp"
namespace reshade::vulkan
{
class runtime_impl : public api::api_object_impl<VkSwapchainKHR, runtime>
{
static const uint32_t NUM_QUERY_FRAMES = 4;
static const uint32_t MAX_IMAGE_DESCRIPTOR_SETS = 128; // TODO: Check if these limits are enough
static const uint32_t MAX_EFFECT_DESCRIPTOR_SETS = 50 * 2 * 4; // 50 resources, 4 passes
public:
runtime_impl(device_impl *device, command_queue_impl *graphics_queue);
~runtime_impl();
api::device *get_device() final { return _device_impl; }
api::command_queue *get_command_queue() final { return _queue_impl; }
bool on_init(VkSwapchainKHR swapchain, const VkSwapchainCreateInfoKHR &desc, HWND hwnd);
void on_reset();
void on_present(VkQueue queue, const uint32_t swapchain_image_index, std::vector<VkSemaphore> &wait);
bool on_present(VkQueue queue, VkImage source, VkFormat source_format, VkSampleCountFlags source_samples, const VkRect2D ®ion, uint32_t layer_index, HWND hwnd, std::vector<VkSemaphore> &wait);
bool capture_screenshot(uint8_t *buffer) const final;
void update_texture_bindings(const char *semantic, api::resource_view_handle srv) final;
private:
bool init_effect(size_t index) final;
void unload_effect(size_t index) final;
void unload_effects() final;
bool init_texture(texture &texture) final;
void upload_texture(const texture &texture, const uint8_t *pixels) final;
void destroy_texture(texture &texture) final;
void generate_mipmaps(const struct tex_data *impl);
void render_technique(technique &technique) final;
void wait_for_command_buffers();
void set_debug_name(uint64_t object, VkDebugReportObjectTypeEXT type, const char *name) const;
inline void set_debug_name_image(VkImage image, const char *name) const { set_debug_name((uint64_t)image, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, name); }
inline void set_debug_name_buffer(VkBuffer buffer, const char *name) const { set_debug_name((uint64_t)buffer, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, name); }
VkImage create_image(uint32_t width, uint32_t height, uint32_t levels, VkFormat format,
VkImageUsageFlags usage, VmaMemoryUsage mem_usage,
VkImageCreateFlags flags = 0, VmaAllocationCreateFlags mem_flags = 0, VmaAllocation *out_mem = nullptr);
VkBuffer create_buffer(VkDeviceSize size,
VkBufferUsageFlags usage, VmaMemoryUsage mem_usage,
VkBufferCreateFlags flags = 0, VmaAllocationCreateFlags mem_flags = 0, VmaAllocation *out_mem = nullptr);
VkImageView create_image_view(VkImage image, VkFormat format, uint32_t levels, VkImageAspectFlags aspect);
device_impl *const _device_impl;
const VkDevice _device;
command_queue_impl *const _queue_impl;
VkQueue _queue = VK_NULL_HANDLE;
command_list_immediate_impl *const _cmd_impl;
uint32_t _queue_sync_index = 0;
VkSemaphore _queue_sync_semaphores[NUM_QUERY_FRAMES] = {};
#ifndef NDEBUG
mutable bool _wait_for_idle_happened = false;
#endif
uint32_t _swap_index = 0;
VkFormat _backbuffer_format = VK_FORMAT_UNDEFINED;
VkExtent2D _render_area = {};
VkRenderPass _default_render_pass[2] = {};
std::vector<VkImage> _swapchain_images;
std::vector<VkImageView> _swapchain_views;
std::vector<VkFramebuffer> _swapchain_frames;
VkImage _backbuffer_image = VK_NULL_HANDLE;
VkImageView _backbuffer_image_view[2] = {};
VkImage _empty_depth_image = VK_NULL_HANDLE;
VkImageView _empty_depth_image_view = VK_NULL_HANDLE;
std::vector<VmaAllocation> _allocations;
VkImage _effect_stencil = VK_NULL_HANDLE;
VkFormat _effect_stencil_format = VK_FORMAT_UNDEFINED;
VkImageView _effect_stencil_view = VK_NULL_HANDLE;
std::vector<struct effect_data> _effect_data;
VkDescriptorPool _effect_descriptor_pool = VK_NULL_HANDLE;
VkDescriptorSetLayout _effect_descriptor_layout = VK_NULL_HANDLE;
std::unordered_map<size_t, VkSampler> _effect_sampler_states;
std::unordered_map<std::string, VkImageView> _texture_semantic_bindings;
#if RESHADE_GUI
static const uint32_t NUM_IMGUI_BUFFERS = 4;
bool init_imgui_resources();
void render_imgui_draw_data(ImDrawData *draw_data) final;
struct imgui_resources
{
VkSampler sampler = VK_NULL_HANDLE;
VkPipeline pipeline = VK_NULL_HANDLE;
VkPipelineLayout pipeline_layout = VK_NULL_HANDLE;
VkDescriptorPool descriptor_pool = VK_NULL_HANDLE;
VkDescriptorSetLayout descriptor_layout = VK_NULL_HANDLE;
VkBuffer indices[NUM_IMGUI_BUFFERS] = {};
VkBuffer vertices[NUM_IMGUI_BUFFERS] = {};
VmaAllocation indices_mem[NUM_IMGUI_BUFFERS] = {};
VmaAllocation vertices_mem[NUM_IMGUI_BUFFERS] = {};
int num_indices[NUM_IMGUI_BUFFERS] = {};
int num_vertices[NUM_IMGUI_BUFFERS] = {};
} _imgui;
#endif
};
}
| 39.778689 | 197 | 0.791469 | [
"object",
"vector"
] |
98ed4534b74e8c99d790b09b7dbea3d4344f4508 | 6,807 | cpp | C++ | ext/cvcontour.cpp | bantic/ruby-opencv | ac60fe86705d15358c9358d715addb0012caeffb | [
"BSD-3-Clause"
] | 2 | 2015-11-05T19:53:20.000Z | 2018-02-17T14:58:22.000Z | ext/cvcontour.cpp | bantic/ruby-opencv | ac60fe86705d15358c9358d715addb0012caeffb | [
"BSD-3-Clause"
] | null | null | null | ext/cvcontour.cpp | bantic/ruby-opencv | ac60fe86705d15358c9358d715addb0012caeffb | [
"BSD-3-Clause"
] | null | null | null | /************************************************************
cvcontour.cpp -
$Author: lsxi $
Copyright (C) 2007 Masakazu Yonekura
************************************************************/
#include "cvcontour.h"
/*
* Document-class: OpenCV::CvContour
*
* Contour.
* CvMat#find_contours
*/
__NAMESPACE_BEGIN_OPENCV
__NAMESPACE_BEGIN_CVCONTOUR
#define APPROX_POLY_OPTION(op) NIL_P(op) ? rb_const_get(rb_class(), rb_intern("APPROX_OPTION")) : rb_funcall(rb_const_get(rb_class(), rb_intern("APPROX_OPTION")), rb_intern("merge"), 1, op)
#define APPROX_POLY_METHOD(op) CVMETHOD("APPROX_POLY_METHOD", rb_hash_aref(op, ID2SYM(rb_intern("method"))), CV_POLY_APPROX_DP)
#define APPROX_POLY_ACCURACY(op) NUM2DBL(rb_hash_aref(op, ID2SYM(rb_intern("accuracy"))))
#define APPROX_POLY_RECURSIVE(op) ({VALUE _recursive = rb_hash_aref(op, ID2SYM(rb_intern("recursive"))); NIL_P(_recursive) ? 0 : _recursive == Qfalse ? 0 : 1;})
VALUE rb_klass;
VALUE
rb_class()
{
return rb_klass;
}
void
define_ruby_class()
{
if (rb_klass)
return;
/*
* opencv = rb_define_module("OpenCV");
* cvseq = rb_define_class_under(opencv, "CvSeq");
* curve = rb_define_module_under(opencv, "Curve");
* pointset = rb_define_module_under(opencv, "PointSet");
*
* note: this comment is used by rdoc.
*/
VALUE opencv = rb_module_opencv();
VALUE cvseq = cCvSeq::rb_class();
VALUE curve = mCurve::rb_module();
VALUE pointset = mPointSet::rb_module();
rb_klass = rb_define_class_under(opencv, "CvContour", cvseq);
rb_include_module(rb_klass, curve);
rb_include_module(rb_klass, pointset);
VALUE approx_option = rb_hash_new();
rb_define_const(rb_klass, "APPROX_OPTION", approx_option);
rb_hash_aset(approx_option, ID2SYM(rb_intern("method")), INT2FIX(CV_POLY_APPROX_DP));
rb_hash_aset(approx_option, ID2SYM(rb_intern("accuracy")), rb_float_new(1.0));
rb_hash_aset(approx_option, ID2SYM(rb_intern("recursive")), Qfalse);
rb_define_private_method(rb_klass, "initialize", RUBY_METHOD_FUNC(rb_initialize), -1);
rb_define_method(rb_klass, "rect", RUBY_METHOD_FUNC(rb_rect), 0);
rb_define_method(rb_klass, "color", RUBY_METHOD_FUNC(rb_color), 0);
rb_define_method(rb_klass, "color=", RUBY_METHOD_FUNC(rb_set_color), 1);
rb_define_method(rb_klass, "reserved", RUBY_METHOD_FUNC(rb_reserved), 0);
rb_define_method(rb_klass, "approx_poly", RUBY_METHOD_FUNC(rb_approx_poly), -1);
rb_define_alias(rb_klass, "approx", "approx_poly");
rb_define_method(rb_klass, "bounding_rect", RUBY_METHOD_FUNC(rb_bounding_rect), 0);
rb_define_method(rb_klass, "create_tree", RUBY_METHOD_FUNC(rb_create_tree), -1);
rb_define_method(rb_klass, "in?", RUBY_METHOD_FUNC(rb_in_q), 1);
rb_define_method(rb_klass, "measure_distance", RUBY_METHOD_FUNC(rb_measure_distance), 1);
}
VALUE
rb_initialize(int argc, VALUE *argv, VALUE self)
{
/*
VALUE storage;
CvSeq *seq = 0;
rb_scan_args(argc, argv, "01", &storage);
storage = CHECK_CVMEMSTORAGE(storage);
seq = cvCreateSeq(CV_SEQ_ELTYPE_POINT, sizeof(CvSeq), sizeof(CvPoint), CVMEMSTORAGE(storage));
DATA_PTR(self) = seq;
resist_root_object(seq, storage);
st_insert(cCvSeq::seqblock_klass, (st_data_t)seq, (st_data_t)klass);
*/
return self;
}
VALUE
rb_rect(VALUE self)
{
return cCvRect::new_object(CVCONTOUR(self)->rect);
}
VALUE
rb_color(VALUE self)
{
return INT2NUM(CVCONTOUR(self)->color);
}
VALUE
rb_set_color(VALUE self, VALUE color)
{
CVCONTOUR(self)->color = NUM2INT(color);
return self;
}
VALUE
rb_reserved(VALUE self)
{
return rb_ary_new3(3,
INT2NUM(CVCONTOUR(self)->reserved[0]),
INT2NUM(CVCONTOUR(self)->reserved[1]),
INT2NUM(CVCONTOUR(self)->reserved[2]));
}
/*
* call-seq:
* approx_poly(<i>approx_poly_option</i>) -> cvcontour
*
* Approximates polygonal curve(s) with desired precision.
* <i>approx_poly_option</i> should be Hash include these keys.
* :method - Approximation method.
* :dp - corresponds to Douglas-Peucker algorithm.
* :accuracy - approximation accuracy. (high-accuracy will create more simple contours)
* :recursive - (default false)
* If not nil or false, the function approximates all chains that access can be obtained to
* from self by h_next or v_next links. If 0, approximated this one.
*/
VALUE
rb_approx_poly(int argc, VALUE *argv, VALUE self)
{
VALUE approx_poly_option, storage;
rb_scan_args(argc, argv, "01", &approx_poly_option);
approx_poly_option = APPROX_POLY_OPTION(approx_poly_option);
storage = cCvMemStorage::new_object();
CvSeq *contour = cvApproxPoly(CVCONTOUR(self), sizeof(CvContour), CVMEMSTORAGE(storage),
APPROX_POLY_METHOD(approx_poly_option),
APPROX_POLY_ACCURACY(approx_poly_option),
APPROX_POLY_RECURSIVE(approx_poly_option));
return cCvSeq::new_sequence(cCvContour::rb_class(), contour, cCvPoint::rb_class(), storage);
}
/*
* call-seq:
* bounding_rect -> rect
*
* Calculates up-right bounding rectangle of point set.
*
*/
VALUE
rb_bounding_rect(VALUE self)
{
return cCvRect::new_object(cvBoundingRect(CVCONTOUR(self), 1));
}
/*
* call-seq:
* create_tree([threshold = 0.0]) -> cvcontourtree
*
* Creates hierarchical representation of contour.
* If the parameter <i>threshold</i> is less than or equal to 0,
* the method creates full binary tree representation.
* If the threshold is greater than 0, the function creates
* representation with the precision threshold:
*/
VALUE
rb_create_tree(int argc, VALUE *argv, VALUE self)
{
VALUE threshold, storage;
rb_scan_args(argc, argv, "01", &threshold);
storage = cCvMemStorage::new_object();
CvContourTree *tree = cvCreateContourTree(CVSEQ(self), CVMEMSTORAGE(storage), IF_DBL(threshold, 0.0));
return cCvSeq::new_sequence(cCvContourTree::rb_class(), (CvSeq*)tree, cCvPoint::rb_class(), storage);
}
/*
* call-seq:
* in?(<i>point</i>) -> true or nil or false
*
* Determines whether the <i>point</i> is inside contour(true), outside(false), or lies on an edge(nil).
*/
VALUE
rb_in_q(VALUE self, VALUE point)
{
double n = cvPointPolygonTest(CVARR(self), VALUE_TO_CVPOINT2D32F(point), 0);
return n == 0 ? Qnil : n > 0 ? Qtrue : Qfalse;
}
/*
* call-seq:
* measure_distance(<i>point</i>) -> float
*
* Return distance between the point and the nearest contour edge.
*/
VALUE
rb_measure_distance(VALUE self, VALUE point)
{
return rb_float_new(cvPointPolygonTest(CVARR(self), VALUE_TO_CVPOINT2D32F(point), 1));
}
VALUE new_object()
{
VALUE storage = cCvMemStorage::new_object();
CvSeq *seq = cvCreateSeq(CV_SEQ_CONTOUR, sizeof(CvContour), sizeof(CvPoint), CVMEMSTORAGE(storage));
VALUE object = cCvSeq::new_sequence(cCvContour::rb_class(), seq, cCvPoint::rb_class(), storage);
return object;
}
__NAMESPACE_END_CVCONTOUR
__NAMESPACE_END_OPENCV
| 31.224771 | 189 | 0.718378 | [
"object"
] |
98f3c101d79da3f867c22cb3985087cd0d71820a | 13,219 | cpp | C++ | test/direct_bt/test_lfringbuffer01.cpp | xranby/direct_bt | 135a8cce2307df1c899eac5f25527aadcd529687 | [
"MIT"
] | 1 | 2020-09-04T18:44:13.000Z | 2020-09-04T18:44:13.000Z | test/direct_bt/test_lfringbuffer01.cpp | xranby/direct_bt-1 | 135a8cce2307df1c899eac5f25527aadcd529687 | [
"MIT"
] | null | null | null | test/direct_bt/test_lfringbuffer01.cpp | xranby/direct_bt-1 | 135a8cce2307df1c899eac5f25527aadcd529687 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cassert>
#include <cinttypes>
#include <cstring>
#include <memory>
#include <cppunit.h>
#include <direct_bt/UUID.hpp>
#include <direct_bt/Ringbuffer.hpp>
#include <direct_bt/LFRingbuffer.hpp>
using namespace direct_bt;
class Integer {
public:
int value;
Integer(int v) : value(v) {}
Integer(const Integer &o) noexcept = default;
Integer(Integer &&o) noexcept = default;
Integer& operator=(const Integer &o) noexcept = default;
Integer& operator=(Integer &&o) noexcept = default;
operator int() const {
return value;
}
int intValue() const { return value; }
static Integer valueOf(const int i) { return Integer(i); }
};
std::shared_ptr<Integer> NullInteger = nullptr;
typedef std::shared_ptr<Integer> SharedType;
typedef Ringbuffer<SharedType> SharedTypeRingbuffer;
typedef LFRingbuffer<SharedType, nullptr> SharedTypeLFRingbuffer;
// Test examples.
class Cppunit_tests : public Cppunit {
private:
std::shared_ptr<SharedTypeRingbuffer> createEmpty(int initialCapacity) {
return std::shared_ptr<SharedTypeRingbuffer>(new SharedTypeLFRingbuffer(initialCapacity));
}
std::shared_ptr<SharedTypeRingbuffer> createFull(const std::vector<std::shared_ptr<Integer>> & source) {
return std::shared_ptr<SharedTypeRingbuffer>(new SharedTypeLFRingbuffer(source));
}
std::vector<SharedType> createIntArray(const int capacity, const int startValue) {
std::vector<SharedType> array(capacity);
for(int i=0; i<capacity; i++) {
array[i] = SharedType(new Integer(startValue+i));
}
return array;
}
void readTestImpl(Ringbuffer<SharedType> &rb, bool clearRef, int capacity, int len, int startValue) {
(void) clearRef;
int preSize = rb.getSize();
CHECKM("Wrong capacity "+rb.toString(), capacity, rb.capacity());
CHECKTM("Too low capacity to read "+std::to_string(len)+" elems: "+rb.toString(), capacity-len >= 0);
CHECKTM("Too low size to read "+std::to_string(len)+" elems: "+rb.toString(), preSize >= len);
CHECKTM("Is empty "+rb.toString(), !rb.isEmpty());
for(int i=0; i<len; i++) {
SharedType svI = rb.get();
CHECKTM("Empty at read #"+std::to_string(i+1)+": "+rb.toString(), svI!=nullptr);
CHECKM("Wrong value at read #"+std::to_string(i+1)+": "+rb.toString(), startValue+i, svI->intValue());
}
CHECKM("Invalid size "+rb.toString(), preSize-len, rb.getSize());
CHECKTM("Invalid free slots after reading "+std::to_string(len)+": "+rb.toString(), rb.getFreeSlots()>= len);
CHECKTM("Is full "+rb.toString(), !rb.isFull());
}
void writeTestImpl(Ringbuffer<SharedType> &rb, int capacity, int len, int startValue) {
int preSize = rb.getSize();
CHECKM("Wrong capacity "+rb.toString(), capacity, rb.capacity());
CHECKTM("Too low capacity to write "+std::to_string(len)+" elems: "+rb.toString(), capacity-len >= 0);
CHECKTM("Too low size to write "+std::to_string(len)+" elems: "+rb.toString(), preSize+len <= capacity);
CHECKTM("Is full "+rb.toString(), !rb.isFull());
for(int i=0; i<len; i++) {
std::string m = "Buffer is full at put #"+std::to_string(i)+": "+rb.toString();
CHECKTM(m, rb.put( SharedType( new Integer(startValue+i) ) ) );
}
CHECKM("Invalid size "+rb.toString(), preSize+len, rb.getSize());
CHECKTM("Is empty "+rb.toString(), !rb.isEmpty());
}
void moveGetPutImpl(Ringbuffer<SharedType> &rb, int pos) {
CHECKTM("RB is empty "+rb.toString(), !rb.isEmpty());
for(int i=0; i<pos; i++) {
CHECKM("MoveFull.get failed "+rb.toString(), i, rb.get()->intValue());
CHECKTM("MoveFull.put failed "+rb.toString(), rb.put( SharedType( new Integer(i) ) ) );
}
}
void movePutGetImpl(Ringbuffer<SharedType> &rb, int pos) {
CHECKTM("RB is full "+rb.toString(), !rb.isFull());
for(int i=0; i<pos; i++) {
CHECKTM("MoveEmpty.put failed "+rb.toString(), rb.put( SharedType( new Integer(600+i) ) ) );
CHECKM("MoveEmpty.get failed "+rb.toString(), 600+i, rb.get()->intValue());
}
}
void test01_FullRead() {
int capacity = 11;
std::vector<SharedType> source = createIntArray(capacity, 0);
std::shared_ptr<SharedTypeRingbuffer> rb = createFull(source);
fprintf(stderr, "test01_FullRead: Created / %s\n", rb->toString().c_str());
CHECKM("Not full size "+rb->toString(), capacity, rb->getSize());
CHECKTM("Not full "+rb->toString(), rb->isFull());
readTestImpl(*rb, true, capacity, capacity, 0);
fprintf(stderr, "test01_FullRead: PostRead / %s\n", rb->toString().c_str());
CHECKTM("Not empty "+rb->toString(), rb->isEmpty());
}
void test02_EmptyWrite() {
int capacity = 11;
std::shared_ptr<Ringbuffer<SharedType>> rb = createEmpty(capacity);
fprintf(stderr, "test01_EmptyWrite: Created / %s\n", rb->toString().c_str());
CHECKM("Not zero size "+rb->toString(), 0, rb->getSize());
CHECKTM("Not empty "+rb->toString(), rb->isEmpty());
writeTestImpl(*rb, capacity, capacity, 0);
fprintf(stderr, "test01_EmptyWrite: PostWrite / %s\n", rb->toString().c_str());
CHECKM("Not full size "+rb->toString(), capacity, rb->getSize());
CHECKTM("Not full "+rb->toString(), rb->isFull());
readTestImpl(*rb, true, capacity, capacity, 0);
fprintf(stderr, "test01_EmptyWrite: PostRead / %s\n", rb->toString().c_str());
CHECKTM("Not empty "+rb->toString(), rb->isEmpty());
}
void test03_FullReadReset() {
int capacity = 11;
std::vector<SharedType> source = createIntArray(capacity, 0);
std::shared_ptr<Ringbuffer<SharedType>> rb = createFull(source);
fprintf(stderr, "test01_FullReadReset: Created / %s\n", rb->toString().c_str());
CHECKTM("Not full "+rb->toString(), rb->isFull());
rb->reset(source);
fprintf(stderr, "test01_FullReadReset: Post Reset w/ source / %s\n", rb->toString().c_str());
CHECKTM("Not full "+rb->toString(), rb->isFull());
readTestImpl(*rb, false, capacity, capacity, 0);
fprintf(stderr, "test01_FullReadReset: Post Read / %s\n", rb->toString().c_str());
CHECKTM("Not empty "+rb->toString(), rb->isEmpty());
rb->reset(source);
fprintf(stderr, "test01_FullReadReset: Post Reset w/ source / %s\n", rb->toString().c_str());
CHECKTM("Not full "+rb->toString(), rb->isFull());
readTestImpl(*rb, false, capacity, capacity, 0);
fprintf(stderr, "test01_FullReadReset: Post Read / %s\n", rb->toString().c_str());
CHECKTM("Not empty "+rb->toString(), rb->isEmpty());
}
void test04_EmptyWriteClear() {
int capacity = 11;
std::shared_ptr<Ringbuffer<SharedType>> rb = createEmpty(capacity);
CHECKTM("Not empty "+rb->toString(), rb->isEmpty());
rb->clear();
CHECKTM("Not empty "+rb->toString(), rb->isEmpty());
writeTestImpl(*rb, capacity, capacity, 0);
CHECKTM("Not full "+rb->toString(), rb->isFull());
readTestImpl(*rb, false, capacity, capacity, 0);
CHECKTM("Not empty "+rb->toString(), rb->isEmpty());
rb->clear();
CHECKTM("Not empty "+rb->toString(), rb->isEmpty());
writeTestImpl(*rb, capacity, capacity, 0);
CHECKTM("Not full "+rb->toString(), rb->isFull());
readTestImpl(*rb, false, capacity, capacity, 0);
CHECKTM("Not empty "+rb->toString(), rb->isEmpty());
}
void test05_ReadResetMid01() {
int capacity = 11;
std::vector<SharedType> source = createIntArray(capacity, 0);
std::shared_ptr<Ringbuffer<SharedType>> rb = createFull(source);
CHECKTM("Not full "+rb->toString(), rb->isFull());
rb->reset(source);
CHECKTM("Not full "+rb->toString(), rb->isFull());
readTestImpl(*rb, false, capacity, 5, 0);
CHECKTM("Is empty "+rb->toString(), !rb->isEmpty());
CHECKTM("Is Full "+rb->toString(), !rb->isFull());
rb->reset(source);
CHECKTM("Not full "+rb->toString(), rb->isFull());
readTestImpl(*rb, false, capacity, capacity, 0);
CHECKTM("Not empty "+rb->toString(), rb->isEmpty());
}
void test06_ReadResetMid02() {
int capacity = 11;
std::vector<SharedType> source = createIntArray(capacity, 0);
std::shared_ptr<Ringbuffer<SharedType>> rb = createFull(source);
CHECKTM("Not full "+rb->toString(), rb->isFull());
rb->reset(source);
CHECKTM("Not full "+rb->toString(), rb->isFull());
moveGetPutImpl(*rb, 5);
readTestImpl(*rb, false, capacity, 5, 5);
CHECKTM("Is empty "+rb->toString(), !rb->isEmpty());
CHECKTM("Is Full "+rb->toString(), !rb->isFull());
rb->reset(source);
CHECKTM("Not full "+rb->toString(), rb->isFull());
readTestImpl(*rb, false, capacity, capacity, 0);
CHECKTM("Not empty "+rb->toString(), rb->isEmpty());
}
void test_GrowFullImpl(int initialCapacity, int pos) {
int growAmount = 5;
int grownCapacity = initialCapacity+growAmount;
std::vector<SharedType> source = createIntArray(initialCapacity, 0);
std::shared_ptr<Ringbuffer<SharedType>> rb = createFull(source);
for(int i=0; i<initialCapacity; i++) {
SharedType svI = rb->get();
CHECKTM("Empty at read #"+std::to_string(i+1)+": "+rb->toString(), svI!=nullptr);
CHECKM("Wrong value at read #"+std::to_string(i+1)+": "+rb->toString(), (0+i)%initialCapacity, svI->intValue());
}
CHECKM("Not zero size "+rb->toString(), 0, rb->getSize());
rb->reset(source);
CHECKM("Not orig size "+rb->toString(), initialCapacity, rb->getSize());
moveGetPutImpl(*rb, pos);
// PRINTM("X02 "+rb->toString());
// rb->dump(stderr, "X02");
rb->recapacity(grownCapacity);
CHECKM("Wrong capacity "+rb->toString(), grownCapacity, rb->capacity());
CHECKM("Not orig size "+rb->toString(), initialCapacity, rb->getSize());
CHECKTM("Is full "+rb->toString(), !rb->isFull());
CHECKTM("Is empty "+rb->toString(), !rb->isEmpty());
// PRINTM("X03 "+rb->toString());
// rb->dump(stderr, "X03");
for(int i=0; i<growAmount; i++) {
CHECKTM("Buffer is full at put #"+std::to_string(i)+": "+rb->toString(), rb->put( SharedType( new Integer(100+i) ) ) );
}
CHECKM("Not new size "+rb->toString(), grownCapacity, rb->getSize());
CHECKTM("Not full "+rb->toString(), rb->isFull());
for(int i=0; i<initialCapacity; i++) {
SharedType svI = rb->get();
// PRINTM("X05["+std::to_string(i)+"]: "+rb->toString()+", svI-null: "+std::to_string(svI==nullptr));
CHECKTM("Empty at read #"+std::to_string(i+1)+": "+rb->toString(), svI!=nullptr);
CHECKM("Wrong value at read #"+std::to_string(i+1)+": "+rb->toString(), (pos+i)%initialCapacity, svI->intValue());
}
for(int i=0; i<growAmount; i++) {
SharedType svI = rb->get();
// PRINTM("X07["+std::to_string(i)+"]: "+rb->toString()+", svI-null: "+std::to_string(svI==nullptr));
CHECKTM("Empty at read #"+std::to_string(i+1)+": "+rb->toString(), svI!=nullptr);
CHECKM("Wrong value at read #"+std::to_string(i+1)+": "+rb->toString(), 100+i, svI->intValue());
}
CHECKM("Not zero size "+rb->toString(), 0, rb->getSize());
CHECKTM("Not empty "+rb->toString(), rb->isEmpty());
CHECKTM("Is full "+rb->toString(), !rb->isFull());
}
public:
void test20_GrowFull01_Begin() {
test_GrowFullImpl(11, 0);
}
void test21_GrowFull02_Begin1() {
test_GrowFullImpl(11, 0+1);
}
void test22_GrowFull03_Begin2() {
test_GrowFullImpl(11, 0+2);
}
void test23_GrowFull04_Begin3() {
test_GrowFullImpl(11, 0+3);
}
void test24_GrowFull05_End() {
test_GrowFullImpl(11, 11-1);
}
void test25_GrowFull11_End1() {
test_GrowFullImpl(11, 11-1-1);
}
void test26_GrowFull12_End2() {
test_GrowFullImpl(11, 11-1-2);
}
void test27_GrowFull13_End3() {
test_GrowFullImpl(11, 11-1-3);
}
void test_list() override {
test01_FullRead();
test02_EmptyWrite();
test03_FullReadReset();
test04_EmptyWriteClear();
test05_ReadResetMid01();
test06_ReadResetMid02();
test20_GrowFull01_Begin();
test21_GrowFull02_Begin1();
test22_GrowFull03_Begin2();
test23_GrowFull04_Begin3();
test24_GrowFull05_End();
test25_GrowFull11_End1();
test26_GrowFull12_End2();
test27_GrowFull13_End3();
}
};
int main(int argc, char *argv[]) {
(void)argc;
(void)argv;
Cppunit_tests test1;
return test1.run();
}
| 39.225519 | 131 | 0.596187 | [
"vector"
] |
98f57600bd78294e7fffbb4d8612c71b8ad7a333 | 3,345 | cpp | C++ | benchmark/vector/misc/push.cpp | ikrima/immer | 2076affd9d814afc019ba8cd8c2b18a6c79c9589 | [
"BSL-1.0"
] | 12,278 | 2015-01-29T17:11:33.000Z | 2022-03-31T21:12:00.000Z | benchmark/vector/misc/push.cpp | ikrima/immer | 2076affd9d814afc019ba8cd8c2b18a6c79c9589 | [
"BSL-1.0"
] | 9,469 | 2015-01-30T05:33:07.000Z | 2022-03-31T16:17:21.000Z | benchmark/vector/misc/push.cpp | ikrima/immer | 2076affd9d814afc019ba8cd8c2b18a6c79c9589 | [
"BSL-1.0"
] | 892 | 2015-01-29T16:26:19.000Z | 2022-03-20T07:44:30.000Z | //
// immer: immutable data structures for C++
// Copyright (C) 2016, 2017, 2018 Juan Pedro Bolivar Puente
//
// This software is distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt
//
#include "benchmark/vector/push.hpp"
#include <immer/array.hpp>
#include <immer/flex_vector.hpp>
#include <immer/vector_transient.hpp>
#include <immer/vector.hpp>
#if IMMER_BENCHMARK_EXPERIMENTAL
#include <immer/experimental/dvektor.hpp>
#endif
#include <immer/heap/gc_heap.hpp>
#include <immer/refcount/no_refcount_policy.hpp>
#include <immer/refcount/unsafe_refcount_policy.hpp>
#include <vector>
#include <list>
#include <numeric>
#if IMMER_BENCHMARK_STEADY
#define QUARK_ASSERT_ON 0
#include <steady/steady_vector.h>
#endif
#if IMMER_BENCHMARK_LIBRRB
extern "C" {
#define restrict __restrict__
#include <rrb.h>
#undef restrict
}
#endif
#if IMMER_BENCHMARK_LIBRRB
NONIUS_BENCHMARK("librrb", benchmark_push_librrb)
NONIUS_BENCHMARK("t/librrb", benchmark_push_mut_librrb)
#endif
NONIUS_BENCHMARK("std::vector", benchmark_push_mut_std<std::vector<unsigned>>())
NONIUS_BENCHMARK("std::list", benchmark_push_mut_std<std::list<unsigned>>())
NONIUS_BENCHMARK("m/vector/5B", benchmark_push_move<immer::vector<unsigned,def_memory,5>>())
NONIUS_BENCHMARK("m/vector/GC", benchmark_push_move<immer::vector<unsigned,gc_memory,5>>())
NONIUS_BENCHMARK("m/vector/NO", benchmark_push_move<immer::vector<unsigned,basic_memory,5>>())
NONIUS_BENCHMARK("t/vector/5B", benchmark_push_mut<immer::vector<unsigned,def_memory,5>>())
NONIUS_BENCHMARK("t/vector/GC", benchmark_push_mut<immer::vector<unsigned,gc_memory,5>>())
NONIUS_BENCHMARK("t/vector/NO", benchmark_push_mut<immer::vector<unsigned,basic_memory,5>>())
NONIUS_BENCHMARK("t/vector/UN", benchmark_push_mut<immer::vector<unsigned,unsafe_memory,5>>())
NONIUS_BENCHMARK("flex/5B", benchmark_push<immer::flex_vector<unsigned,def_memory,5>>())
NONIUS_BENCHMARK("flex_s/GC", benchmark_push<immer::flex_vector<std::size_t,gc_memory,5>>())
NONIUS_BENCHMARK("vector/4B", benchmark_push<immer::vector<unsigned,def_memory,4>>())
NONIUS_BENCHMARK("vector/5B", benchmark_push<immer::vector<unsigned,def_memory,5>>())
NONIUS_BENCHMARK("vector/6B", benchmark_push<immer::vector<unsigned,def_memory,6>>())
NONIUS_BENCHMARK("vector/GC", benchmark_push<immer::vector<unsigned,gc_memory,5>>())
NONIUS_BENCHMARK("vector/NO", benchmark_push<immer::vector<unsigned,basic_memory,5>>())
NONIUS_BENCHMARK("vector/UN", benchmark_push<immer::vector<unsigned,unsafe_memory,5>>())
#if IMMER_BENCHMARK_EXPERIMENTAL
NONIUS_BENCHMARK("dvektor/4B", benchmark_push<immer::dvektor<unsigned,def_memory,4>>())
NONIUS_BENCHMARK("dvektor/5B", benchmark_push<immer::dvektor<unsigned,def_memory,5>>())
NONIUS_BENCHMARK("dvektor/6B", benchmark_push<immer::dvektor<unsigned,def_memory,6>>())
NONIUS_BENCHMARK("dvektor/GC", benchmark_push<immer::dvektor<unsigned,gc_memory,5>>())
NONIUS_BENCHMARK("dvektor/NO", benchmark_push<immer::dvektor<unsigned,basic_memory,5>>())
NONIUS_BENCHMARK("dvektor/UN", benchmark_push<immer::dvektor<unsigned,unsafe_memory,5>>())
#endif
NONIUS_BENCHMARK("array", benchmark_push<immer::array<unsigned>>())
#if IMMER_BENCHMARK_STEADY
NONIUS_BENCHMARK("steady", benchmark_push<steady::vector<unsigned>>())
#endif
| 39.821429 | 94 | 0.784454 | [
"vector"
] |
98fc96345702174385d82bd37beea54c5d77714e | 33,647 | cpp | C++ | src/loottablecondition.cpp | IoeCmcomc/MCDatapacker | 5099d6ac2e0b15f4d61235b5b5ec41a847f588a1 | [
"Apache-2.0"
] | 2 | 2021-08-17T14:06:53.000Z | 2022-01-29T14:14:59.000Z | src/loottablecondition.cpp | IoeCmcomc/MCDatapacker | 5099d6ac2e0b15f4d61235b5b5ec41a847f588a1 | [
"Apache-2.0"
] | 1 | 2021-06-20T20:12:10.000Z | 2021-06-24T03:22:53.000Z | src/loottablecondition.cpp | IoeCmcomc/MCDatapacker | 5099d6ac2e0b15f4d61235b5b5ec41a847f588a1 | [
"Apache-2.0"
] | null | null | null | #include "loottablecondition.h"
#include "ui_loottablecondition.h"
#include "mainwindow.h"
#include "inventoryitem.h"
#include "numberproviderdelegate.h"
#include "itemconditiondialog.h"
#include "locationconditiondialog.h"
#include "entityconditiondialog.h"
#include "globalhelpers.h"
#include <QDialog>
#include <QDoubleSpinBox>
LootTableCondition::LootTableCondition(QWidget *parent) :
QFrame(parent),
ui(new Ui::LootTableCondition) {
ui->setupUi(this);
if (MainWindow::getCurGameVersion() < QVersionNumber(1, 17)) {
qobject_cast<QListView*>(ui->conditionTypeCombo->view())
->setRowHidden(15, true);
static_cast<QStandardItemModel*>(ui->conditionTypeCombo->model())->item(
15, 0)->setEnabled(false);
}
connect(ui->conditionTypeCombo,
qOverload<int>(&QComboBox::currentIndexChanged),
this, &LootTableCondition::onTypeChanged);
MainWindow *mainWin = nullptr;
for (auto *wid : qApp->topLevelWidgets()) {
if (wid->objectName() == QStringLiteral("MainWindow")) {
mainWin = qobject_cast<MainWindow*>(wid);
break;
}
}
if (mainWin) {
connect(mainWin, &MainWindow::curDirChanged,
this, &LootTableCondition::onCurDirChanged);
}
connect(&predRefWatcher, &QFileSystemWatcher::directoryChanged,
this, &LootTableCondition::setupRefCombo);
initBlockStatesPage();
ui->damageSrc_entityPropBtn->assignDialogClass<EntityConditionDialog>();
ui->damageSrc_directPropBtn->assignDialogClass<EntityConditionDialog>();
ui->entity_propBtn->assignDialogClass<EntityConditionDialog>();
initEntityScoresPage();
ui->matchTool_propBtn->assignDialogClass<ItemConditionDialog>();
ui->location_propBtn->assignDialogClass<LocationConditionDialog>();
initRandChancePage();
setupRefCombo();
initTableBonusPage();
ui->time_valueInput->setModes(NumberProvider::ExactAndRange);
initToolEnchantPage();
}
LootTableCondition::~LootTableCondition() {
delete ui;
}
QJsonObject LootTableCondition::toJson() const {
QJsonObject root;
root.insert("condition", "minecraft:" +
condTypes[ui->conditionTypeCombo->currentIndex()]);
switch (ui->conditionTypeCombo->currentIndex()) {
case 0: { /*Block states */
if (ui->blockState_blockCombo->currentIndex() != 0) {
auto invItem = ui->blockState_blockCombo->currentData(
Qt::UserRole + 1).value<InventoryItem>();
root.insert("block", invItem.getNamespacedID());
}
QJsonObject states = LocationConditionDialog::jsonFromStateTable(
ui->blockState_table);
if (!states.isEmpty())
root.insert("properties", states);
break;
}
case 1: { /*Damage sources */
QJsonObject pred;
ui->damageSrc_explosionCheck->insertToJsonObject(pred, "is_explosion");
ui->damageSrc_projectileCheck->insertToJsonObject(pred,
"is_projectile");
ui->damageSrc_fireCheck->insertToJsonObject(pred, "is_fire");
ui->damageSrc_lightningCheck->insertToJsonObject(pred, "is_lightning");
ui->damageSrc_magicCheck->insertToJsonObject(pred, "is_magic");
ui->damageSrc_starvationCheck->insertToJsonObject(pred,
"bypasses_magic");
ui->damageSrc_bypassArmorCheck->insertToJsonObject(pred,
"bypasses_invulnerability");
if (!ui->damageSrc_entityPropBtn->getData().isEmpty())
pred.insert("source_entity",
ui->damageSrc_entityPropBtn->getData());
if (!ui->damageSrc_directPropBtn->getData().isEmpty())
pred.insert("direct_entity",
ui->damageSrc_directPropBtn->getData());
if (!pred.isEmpty())
root.insert("predicate", pred);
break;
}
case 2: { /*Entity properites */
root.insert("entity",
entityTargets[ui->entity_typeCombo->currentIndex()]);
if (!ui->entity_propBtn->getData().isEmpty())
root.insert("predicate", ui->entity_propBtn->getData());
break;
}
case 3: { /*Entity scores */
root.insert("entity",
entityTargets[ui->entityScores_typeCombo->currentIndex()]);
QJsonObject scores;
for (auto row = 0; row < ui->entityScores_table->rowCount(); ++row) {
auto objective = ui->entityScores_table->item(row, 0)->text();
auto value = ui->entityScores_table->item(row, 1)->
data(ExtendedRole::NumberProviderRole).toJsonValue();
scores.insert(objective, value);
}
if (!scores.isEmpty())
root.insert("scores", scores);
break;
}
case 4: { /*Killed by player */
if (ui->playerKill_invertedCheck->isChecked())
root.insert("inverse", true);
break;
}
case 5: { /*Location */
if (!ui->location_xOffset->isUnset())
root.insert("offsetX", ui->location_xOffset->value());
if (!ui->location_yOffset->isUnset())
root.insert("offsetY", ui->location_yOffset->value());
if (!ui->location_zOffset->isUnset())
root.insert("offsetZ", ui->location_zOffset->value());
if (!ui->location_propBtn->getData().isEmpty())
root.insert("predicate", ui->location_propBtn->getData());
break;
}
case 6: { /*Nested conditions */
QJsonArray terms;
int childCount = ui->nested_dataInterface->entriesCount();
if (childCount != 0) {
for (const auto child : ui->nested_dataInterface->json()) {
auto &&cond = child.toObject();
if (ui->nested_andRadio->isChecked())
addInvertCondition(cond);
terms.push_back(cond);
}
root.insert("terms", terms);
if (ui->nested_invertedCheck->isChecked()) {
if (ui->nested_orRadio->isChecked())
addInvertCondition(root);
} else {
if (ui->nested_andRadio->isChecked())
addInvertCondition(root);
}
auto rootMap = root.toVariantMap();
simplifyCondition(rootMap);
root = QJsonObject::fromVariantMap(rootMap);
}
break;
}
case 7: { /*Match tool */
if (!ui->matchTool_propBtn->getData().isEmpty())
root.insert("predicate", ui->matchTool_propBtn->getData());
break;
}
case 8: { /*Random chance (with looting) */
root.insert("chance", ui->randChance_spinBox->value());
if (ui->randChance_lootingCheck->isChecked()) {
root.insert("condition", "minecraft:random_chance_with_looting");
root.insert("looting_multiplier",
ui->randChance_lootingInput->value());
}
break;
}
case 9: {/*Reference */
if (!ui->ref_nameCombo->currentText().isEmpty())
root.insert("name", ui->ref_nameCombo->currentText());
break;
}
case 10: {/*Survives Explosion */
break;
}
case 11: {/*Table bonus */
root.insert("enchantment", ui->tableBonus_enchantCombo->currentData(
Qt::UserRole + 1).toString());
QJsonArray chances;
for (int i = 0; i < tableBonusModel.rowCount(); ++i) {
auto chance =
tableBonusModel.item(i, 0)->data(Qt::DisplayRole).toJsonValue();
chances.push_back(chance);
}
if (!chances.isEmpty())
root.insert("chances", chances);
break;
}
case 12: {/*Time */
root.insert("value", ui->time_valueInput->toJson());
if (ui->time_periodSpinBox->value() > 0)
root.insert("period", ui->time_periodSpinBox->value());
break;
}
case 13: {/*Tool enchantment */
QJsonArray enchantments;
for (int i = 0; i < ui->toolEnchant_table->rowCount(); ++i) {
auto id =
ui->toolEnchant_table->item(i,
0)->data(Qt::UserRole +
1).toString();
auto levels = ui->toolEnchant_table->item(i, 1)->
data(ExtendedRole::NumberProviderRole).toJsonValue();
enchantments.push_back(
QJsonObject({ { QStringLiteral("enchantment"), id },
{ QStringLiteral("levels"), levels } }));
}
if (!enchantments.isEmpty())
root.insert("enchantments", enchantments);
break;
}
case 14: {/*Weather */
ui->weather_rainingCheck->insertToJsonObject(root, "raining");
ui->weather_thunderCheck->insertToJsonObject(root, "thundering");
break;
}
case 15: { /* Value check */
if (ui->value_valueInput->isCurrentlyUnset())
break;
if (ui->value_rangeInput->isCurrentlyUnset())
break;
root.insert(QLatin1String("value"), ui->value_valueInput->toJson());
root.insert(QLatin1String("range"), ui->value_rangeInput->toJson());
break;
}
}
return root;
}
void LootTableCondition::fromJson(const QJsonObject &root, bool redirected) {
resetAll();
if (!root.contains(QLatin1String("condition")))
return;
auto valueMap = root.toVariantMap();
simplifyCondition(valueMap);
auto value = QJsonObject::fromVariantMap(valueMap);
QString condType = value["condition"].toString();
Glhp::removePrefix(condType, "minecraft:");
bool isRandChanceWithLoot = false;
bool singleInverted = false;
if (condType.endsWith("random_chance_with_looting")) {
condType = "random_chance";
isRandChanceWithLoot = true;
} else if (condType.endsWith("inverted")) {
condType = "alternative";
singleInverted = true;
}
int condIndex = condTypes.indexOf(condType);
const auto &&model =
static_cast<QStandardItemModel*>(ui->conditionTypeCombo->model());
const auto &&item = model->item(condIndex, 0);
if (!item->isEnabled())
return;
ui->conditionTypeCombo->setCurrentIndex(condIndex);
reset(condIndex);
switch (condIndex) {
case 0: { /*Block states */
if (value.contains("block"))
setupComboFrom(ui->blockState_blockCombo, QVariant::fromValue
(InventoryItem(value["block"].toString())));
if (value.contains("properties")) {
QJsonObject states = value["properties"].toObject();
LocationConditionDialog::setupStateTableFromJson(
ui->blockState_table,
states);
}
break;
}
case 1: { /*Damage sources */
if (value.contains("predicate")) {
QJsonObject pred = value["predicate"].toObject();
ui->damageSrc_explosionCheck->setupFromJsonObject(pred,
"is_explosion");
ui->damageSrc_projectileCheck->setupFromJsonObject(pred,
"is_projectile");
ui->damageSrc_fireCheck->setupFromJsonObject(pred, "is_fire");
ui->damageSrc_lightningCheck->setupFromJsonObject(pred,
"is_lightning");
ui->damageSrc_magicCheck->setupFromJsonObject(pred, "is_magic");
ui->damageSrc_starvationCheck->setupFromJsonObject(pred,
"bypasses_magic");
ui->damageSrc_bypassArmorCheck->setupFromJsonObject(pred,
"bypasses_invulnerability");
if (pred.contains("source_entity"))
ui->damageSrc_entityPropBtn->setData(
pred["source_entity"].toObject());
if (pred.contains("direct_entity"))
ui->damageSrc_directPropBtn->setData(
pred["direct_entity"].toObject());
}
break;
}
case 2: { /*Entity properites */
if (value.contains("entity"))
ui->entity_typeCombo->setCurrentIndex
(entityTargets.indexOf(value["entity"].toString()));
if (value.contains("predicate"))
ui->entity_propBtn->setData(value["predicate"].toObject());
break;
}
case 3: { /*Entity scores */
if (value.contains("entity"))
ui->entityScores_typeCombo->setCurrentIndex
(entityTargets.indexOf(value["entity"].toString()));
if (value.contains("scores")) {
QJsonObject scores = value["scores"].toObject();
for (const auto &objective : scores.keys()) {
auto *objectiveItem =
new QTableWidgetItem(objective);
auto *valueItem = new QTableWidgetItem();
valueItem->setData(ExtendedRole::NumberProviderRole,
scores[objective].toVariant());
appendRowToTableWidget(ui->entityScores_table,
{ objectiveItem, valueItem });
}
}
break;
}
case 4: { /*Killed by player */
if (value.contains("inverse"))
ui->playerKill_invertedCheck->setChecked(value["inverse"].toBool());
break;
}
case 5: { /*Location */
if (value.contains("offsetX"))
ui->location_xOffset->setValue(value["offsetX"].toInt());
if (value.contains("offsetY"))
ui->location_yOffset->setValue(value["offsetY"].toInt());
if (value.contains("offsetZ"))
ui->location_zOffset->setValue(value["offsetZ"].toInt());
if (value.contains("predicate"))
ui->location_propBtn->setData(value["predicate"].toObject());
break;
}
case 6: { /*Nested conditions */
if (singleInverted && value.contains("term")) {
ui->nested_dataInterface->setJson({ value["term"].toObject() });
ui->nested_orRadio->setChecked(true);
ui->nested_invertedCheck->setChecked(true);
} else if (value.contains("terms")) {
QJsonArray terms = value["terms"].toArray();
bool areTermsInverted = true;
for (const auto termRef : terms) {
const QJsonObject &&term = termRef.toObject();
if (!(term.contains("condition")
&& term["condition"].toString().endsWith("inverted")))
areTermsInverted = false;
}
/*qDebug() << "areTermsInverted" << areTermsInverted; */
for (QJsonValueRef && termRef : terms) {
QJsonObject &&term = termRef.toObject();
if (!term.contains("condition"))
continue;
if (areTermsInverted) {
auto sub = term["term"].toObject();
if (!sub.isEmpty())
term = sub;
}
termRef = term;
}
if (!ui->nested_dataInterface->mainWidget())
initNestedCondPage();
ui->nested_dataInterface->setJson(terms);
if (redirected) {
if (areTermsInverted) {
ui->nested_andRadio->setChecked(true);
ui->nested_invertedCheck->setChecked(false);
} else {
ui->nested_orRadio->setChecked(true);
ui->nested_invertedCheck->setChecked(true);
}
} else {
if (areTermsInverted) {
ui->nested_andRadio->setChecked(true);
ui->nested_invertedCheck->setChecked(true);
} else {
ui->nested_orRadio->setChecked(true);
ui->nested_invertedCheck->setChecked(false);
}
}
}
break;
}
case 7: { /*Match tool */
if (value.contains("predicate"))
ui->matchTool_propBtn->setData(value["predicate"].toObject());
break;
}
case 8: { /*Random chance (with looting) */
if (value.contains("chance"))
ui->randChance_spinBox->setValue(value["chance"].toDouble());
ui->randChance_lootingCheck->setChecked(isRandChanceWithLoot);
if (isRandChanceWithLoot && value.contains("looting_multiplier"))
ui->randChance_lootingInput->setValue(
value["looting_multiplier"].toDouble());
break;
}
case 9: {/*Reference */
if (value.contains("name"))
ui->ref_nameCombo->setCurrentText(value["name"].toString());
break;
}
case 10: {/*Survives explosion */
break;
}
case 11: {/*Table bonus */
if (value.contains("enchantment"))
setupComboFrom(ui->tableBonus_enchantCombo,
value["enchantment"].toString());
if (value.contains("chances")) {
QJsonArray chances = value["chances"].toArray();
for (auto chanceRef : chances) {
auto *chanceItem = new QStandardItem();
chanceItem->setData(chanceRef.toDouble(), Qt::DisplayRole);
tableBonusModel.appendRow(chanceItem);
}
}
break;
}
case 12: {/*Time */
if (value.contains("value"))
ui->time_valueInput->fromJson(value["value"]);
if (value.contains("period") && value["period"].toInt() > 0)
ui->time_periodSpinBox->setValue(value["period"].toInt());
break;
}
case 13: {/*Tool enchantment */
if (value.contains("enchantments")) {
QJsonArray enchantments = value["enchantments"].toArray();
for (auto enchantment : enchantments) {
auto enchantObj = enchantment.toObject();
if (enchantObj.isEmpty()) continue;
if (!enchantObj.contains(QStringLiteral("enchantment"))) {
continue;
}
auto enchantId =
enchantObj[QStringLiteral("enchantment")].toString();
if (!enchantId.contains(QStringLiteral(":")))
enchantId = QStringLiteral("minecraft:") + enchantId;
auto indexes = enchantmentsModel.match(
enchantmentsModel.index(0, 0), Qt::UserRole + 1, enchantId);
if (indexes.isEmpty()) continue;
auto *enchantItem = new QTableWidgetItem();
enchantItem->setData(Qt::UserRole + 1, enchantId);
enchantItem->setText(indexes[0].data(Qt::DisplayRole).toString());
enchantItem->setFlags(enchantItem->flags() &
~Qt::ItemIsEditable);
auto *levelsItem = new QTableWidgetItem();
levelsItem->setData(ExtendedRole::NumberProviderRole,
enchantObj.value(QStringLiteral("levels")));
appendRowToTableWidget(ui->toolEnchant_table,
{ enchantItem, levelsItem });
}
}
break;
}
case 14: {/*Weather */
ui->weather_rainingCheck->setupFromJsonObject(value, "raining");
ui->weather_thunderCheck->setupFromJsonObject(value, "thundering");
break;
}
case 15: { /* Value check */
if (MainWindow::getCurGameVersion() >= QVersionNumber(1, 17)) {
if (value.contains(QLatin1String("value")))
ui->value_valueInput->fromJson(value[QLatin1String("value")]);
if (value.contains(QLatin1String("range")))
ui->value_rangeInput->fromJson(value[QLatin1String("range")]);
}
break;
}
default:
break;
}
}
void LootTableCondition::onTypeChanged(const int &i) {
ui->stackedWidget->setCurrentIndex(i);
const int nestedConditionIndex = 6;
if ((i == nestedConditionIndex) && !ui->nested_dataInterface->mainWidget())
initNestedCondPage();
}
void LootTableCondition::onCurDirChanged(const QDir &dir) {
if (!predRefWatcher.directories().isEmpty())
predRefWatcher.removePaths(predRefWatcher.directories());
predRefWatcher.addPath(dir.path());
predRefWatcher.directories();
setupRefCombo();
}
void LootTableCondition::reset(int index) {
switch (index) {
case 0: { /*Block states */
ui->blockState_blockCombo->setCurrentIndex(0);
ui->blockState_table->setRowCount(0);
break;
}
case 1: { /*Damage sources */
ui->damageSrc_explosionCheck->unset();
ui->damageSrc_projectileCheck->unset();
ui->damageSrc_fireCheck->unset();
ui->damageSrc_lightningCheck->unset();
ui->damageSrc_magicCheck->unset();
ui->damageSrc_starvationCheck->unset();
ui->damageSrc_bypassArmorCheck->unset();
ui->damageSrc_entityPropBtn->reset();
ui->damageSrc_directPropBtn->reset();
break;
}
case 2: { /*Entity properites */
ui->entity_typeCombo->setCurrentIndex(0);
ui->entity_propBtn->reset();
break;
}
case 3: { /*Entity scores */
ui->entityScores_typeCombo->setCurrentIndex(0);
ui->entityScores_table->setRowCount(0);
break;
}
case 4: { /*Killed by player */
ui->playerKill_invertedCheck->setChecked(false);
break;
}
case 5: { /*Location */
ui->location_xOffset->unset();
ui->location_yOffset->unset();
ui->location_zOffset->unset();
ui->location_propBtn->reset();
break;
}
case 6: { /*Nested conditions */
if (ui->nested_dataInterface->mainWidget())
ui->nested_dataInterface->setJson({});
break;
}
case 7: { /*Match tool */
ui->matchTool_propBtn->reset();
break;
}
case 8: { /*Random chance (with looting) */
ui->randChance_spinBox->setValue(0);
ui->randChance_lootingCheck->setChecked(false);
ui->randChance_lootingInput->setValue(1);
break;
}
case 9: {/*Reference */
ui->ref_nameCombo->setCurrentText("");
break;
}
case 10: {/*Survives Explosion */
break;
}
case 11: {/*Table bonus */
ui->tableBonus_enchantCombo->setCurrentIndex(0);
clearModelExceptHeaders(tableBonusModel);
break;
}
case 12: {/*Time */
ui->time_valueInput->unset();
ui->time_periodSpinBox->setValue(0);
break;
}
case 13: {/*Tool enchantment */
ui->toolEnchant_table->setRowCount(0);
break;
}
case 14: {/*Weather */
ui->weather_rainingCheck->unset();
ui->weather_thunderCheck->unset();
break;
}
case 15: { /* Value check */
ui->value_valueInput->unset();
ui->value_rangeInput->unset();
break;
}
default:
break;
}
}
void LootTableCondition::clearModelExceptHeaders(QStandardItemModel &model) {
QVector<QStandardItem*> headers;
for (int i = 0; i < model.columnCount(); ++i) {
headers << model.takeHorizontalHeaderItem(i);
}
model.clear();
for (int i = 0; i < headers.count(); ++i)
model.setHorizontalHeaderItem(i, headers[i]);
}
void LootTableCondition::setDepth(int value) {
depth = value;
}
void LootTableCondition::resetAll() {
for (int i = 0; i < ui->stackedWidget->count(); ++i)
reset(i);
ui->conditionTypeCombo->setCurrentIndex(0);
}
void LootTableCondition::changeEvent(QEvent *event) {
QFrame::changeEvent(event);
if (event->type() == QEvent::LanguageChange) {
ui->retranslateUi(this);
}
}
void LootTableCondition::blockStates_onAdded() {
if (ui->blockState_stateEdit->text().isEmpty()
|| ui->blockState_valueEdit->text().isEmpty())
return;
QTableWidgetItem *stateItem = new QTableWidgetItem(
ui->blockState_stateEdit->text());
QTableWidgetItem *valueItem = new QTableWidgetItem(
ui->blockState_valueEdit->text());
appendRowToTableWidget(ui->blockState_table, { stateItem, valueItem });
}
void LootTableCondition::entityScores_onAdded() {
if (ui->entityScores_objectiveEdit->text().isEmpty())
return;
auto *objItem = new QTableWidgetItem(
ui->entityScores_objectiveEdit->text());
auto *valueItem = new QTableWidgetItem();
auto json = ui->entityScores_valueInput->toJson();
valueItem->setData(ExtendedRole::NumberProviderRole, json);
appendRowToTableWidget(ui->entityScores_table, { objItem, valueItem });
}
void LootTableCondition::setupRefCombo() {
/*qDebug() << "setupRefCombo"; */
if (condRefsModel.rowCount() > 0)
condRefsModel.clear();
auto predRefIDs = Glhp::fileIdList(QDir::currentPath(),
"predicates");
for (const auto &predRef : qAsConst(predRefIDs))
condRefsModel.appendRow(new QStandardItem(predRef));
ui->ref_nameCombo->setModel(&condRefsModel);
}
void LootTableCondition::tableBonus_onAdded() {
QStandardItem *chanceItem = new QStandardItem();
chanceItem->setData(ui->tableBonus_chanceSpinBox->value(),
Qt::DisplayRole);
tableBonusModel.appendRow(chanceItem);
}
void LootTableCondition::toolEnchant_onAdded() {
if (ui->toolEnchant_levelsInput->minValue() == 0
|| ui->toolEnchant_levelsInput->maxValue() == 0) {
return;
}
QString enchantmentText = ui->toolEnchant_enchantCombo->currentText();
if (!ui->toolEnchant_table->findItems(enchantmentText,
Qt::MatchExactly).isEmpty())
return;
QTableWidgetItem *enchantItem = new QTableWidgetItem(enchantmentText);
enchantItem->setData(Qt::UserRole + 1, ui->toolEnchant_enchantCombo->
currentData(Qt::UserRole + 1));
enchantItem->setFlags(enchantItem->flags() & ~Qt::ItemIsEditable);
QTableWidgetItem *levelsItem = new QTableWidgetItem();
auto json = ui->toolEnchant_levelsInput->toJson();
levelsItem->setData(ExtendedRole::NumberProviderRole, json);
appendRowToTableWidget(ui->toolEnchant_table, { enchantItem, levelsItem });
}
void LootTableCondition::initBlockStatesPage() {
auto blocksInfo = MainWindow::getMCRInfo("block");
blocksModel.appendRow(new QStandardItem(tr("(not set)")));
for (const auto &key : blocksInfo.keys()) {
InventoryItem invItem(key);
QStandardItem *item = new QStandardItem();
item->setIcon(QIcon(invItem.getPixmap()));
if (invItem.getName().isEmpty()) {
auto name = blocksInfo.value(key).toMap().value("name").toString();
item->setText(name);
} else {
item->setText(invItem.getName());
}
QVariant vari;
vari.setValue(invItem);
item->setData(vari, Qt::UserRole + 1);
blocksModel.appendRow(item);
}
ui->blockState_blockCombo->setModel(&blocksModel);
ui->blockState_table->installEventFilter(&viewFilter);
connect(ui->blockState_addBtn, &QPushButton::clicked,
this, &LootTableCondition::blockStates_onAdded);
}
void LootTableCondition::initEntityScoresPage() {
ui->entityScores_valueInput->setModes(
NumberProvider::ExactAndRange);
auto *delegate = new NumberProviderDelegate(this);
delegate->setInputModes(NumberProvider::ExactAndRange);
ui->entityScores_table->setItemDelegate(delegate);
ui->entityScores_table->installEventFilter(new ViewEventFilter(this));
connect(ui->entityScores_addBtn, &QPushButton::clicked,
this, &LootTableCondition::entityScores_onAdded);
}
void LootTableCondition::initNestedCondPage() {
auto *cond = new LootTableCondition();
/*cond->setMinimumHeight(500); */
/*cond->setIsModular(true); */
ui->nested_dataInterface->setMainWidget(cond);
ui->nested_dataInterface->mapToSetter(
cond, qOverload<const QJsonObject &>(&LootTableCondition::fromJson));
ui->nested_dataInterface->mapToGetter(&LootTableCondition::toJson, cond);
}
void LootTableCondition::initRandChancePage() {
connect(ui->randChance_slider, &QSlider::valueChanged, [ = ](int value) {
ui->randChance_spinBox->setValue((double)value / 100);
});
connect(ui->randChance_spinBox,
qOverload<double>(&QDoubleSpinBox::valueChanged),
[ = ](double value) {
ui->randChance_slider->setValue(qRound(value * 100));
});
connect(ui->randChance_lootingCheck,
&QCheckBox::toggled, [ = ](bool checked) {
ui->randChance_lootingLabel->setEnabled(checked);
ui->randChance_lootingInput->setEnabled(checked);
});
}
void LootTableCondition::initTableBonusPage() {
initComboModelView("enchantment", enchantmentsModel,
ui->tableBonus_enchantCombo, false);
ui->toolEnchant_enchantCombo->setModel(&enchantmentsModel);
ui->tableBonus_listView->setModel(&tableBonusModel);
ui->tableBonus_listView->installEventFilter(&viewFilter);
connect(ui->tableBonus_chanceSlider,
&QSlider::valueChanged, [ = ](int value) {
ui->tableBonus_chanceSpinBox->setValue((double)value / 100);
});
connect(ui->tableBonus_chanceSpinBox,
qOverload<double>(&QDoubleSpinBox::valueChanged),
[ = ](double value) {
ui->tableBonus_chanceSlider->setValue(qRound(value * 100));
});
connect(ui->tableBonus_addBtn, &QPushButton::clicked,
this, &LootTableCondition::tableBonus_onAdded);
}
void LootTableCondition::initToolEnchantPage() {
ui->toolEnchant_levelsInput->setModes(NumberProvider::Range);
auto *delegate = new NumberProviderDelegate(this);
delegate->setInputModes(NumberProvider::ExactAndRange);
ui->toolEnchant_table->setItemDelegate(delegate);
ui->toolEnchant_table->installEventFilter(&viewFilter);
connect(ui->toolEnchant_addBtn, &QPushButton::clicked,
this, &LootTableCondition::toolEnchant_onAdded);
}
void LootTableCondition::addInvertCondition(QJsonObject &json) const {
json = QJsonObject({ { "condition", "minecraft:inverted" },
{ "term", json } });
}
void LootTableCondition::simplifyCondition(QVariantMap &condMap,
int depth) const {
/*const QString tab = QString(" ").repeated(depth); */
/*qDebug().noquote() << tab << "simplifyCondJson" << depth; */
if (condMap.contains("condition")) {
/*
qDebug().noquote() << tab << "main condition:" <<
condMap["condition"].toString();
*/
if (condMap["condition"].toString().endsWith("inverted")) {
auto &subRef = condMap["term"];
auto sub = subRef.toMap();
if (sub.contains("condition")) {
/*qDebug().noquote() << tab << "sub condition:" << */
sub["condition"].toString();
if (sub["condition"].toString().endsWith("inverted")) {
auto subTerm = sub["term"].toMap();
condMap = subTerm;
simplifyCondition(condMap, depth + 2);
} else if (sub["condition"].toString().endsWith("alternative"))
{
auto &subTermsRef = sub["terms"];
auto subTerms = subTermsRef.toList();
/*qDebug().noquote() << tab << "sub terms count:" << */
subTerms.count();
if (subTerms.count() > 1) {
for (auto &termRef : subTerms) {
auto term = termRef.toMap();
simplifyCondition(term, depth + 2);
termRef.setValue(term);
}
subTermsRef.setValue(subTerms);
subRef.setValue(sub);
} else if (subTerms.count() == 1) {
auto term = subTerms[0].toMap();
sub = term;
subRef.setValue(sub);
simplifyCondition(condMap, depth + 1);
}
}
}
} else if (condMap["condition"].toString().endsWith("alternative")) {
auto &subsRef = condMap["terms"];
auto subs = subsRef.toList();
/*qDebug().noquote() << tab << "subs count:" << subs.count(); */
if (subs.count() > 1) {
for (auto &termRef : subs) {
auto term = termRef.toMap();
simplifyCondition(term, depth + 1);
termRef.setValue(term);
}
subsRef.setValue(subs);
} else if (subs.count() == 1) {
auto term = subs[0].toMap();
condMap = term;
simplifyCondition(condMap, depth + 1);
}
}
}
/*qDebug().noquote() << tab << "end" << depth; */
}
| 36.652505 | 92 | 0.572859 | [
"model"
] |
98fd013f7717e88a134f0c192de351a94d06b930 | 865 | hpp | C++ | src/Client/Editor/ObjectMapperFactory.hpp | Marukyu/NecroEdit | 4b2380cc3417c6578476a213e05f4cbc846e5a77 | [
"MIT",
"Unlicense"
] | 13 | 2016-04-02T14:21:49.000Z | 2021-01-10T17:32:43.000Z | src/Client/Editor/ObjectMapperFactory.hpp | Marukyu/NecroEdit | 4b2380cc3417c6578476a213e05f4cbc846e5a77 | [
"MIT",
"Unlicense"
] | 24 | 2016-04-02T12:08:39.000Z | 2021-01-27T01:21:58.000Z | src/Client/Editor/ObjectMapperFactory.hpp | Marukyu/NecroEdit | 4b2380cc3417c6578476a213e05f4cbc846e5a77 | [
"MIT",
"Unlicense"
] | 6 | 2016-04-02T12:05:28.000Z | 2017-05-10T14:13:39.000Z | #ifndef SRC_CLIENT_EDITOR_OBJECTMAPPERFACTORY_HPP_
#define SRC_CLIENT_EDITOR_OBJECTMAPPERFACTORY_HPP_
#include <Client/Editor/SelectionPanel.hpp>
#include <Client/LevelRenderer/ObjectAppearance.hpp>
#include <Shared/Level/Object.hpp>
#include <vector>
/**
* Creates object mappers for selector widgets.
*
* Mappers are lists of vertex representations of objects that can be placed inside a selector widget, allowing the user
* to select items from a visual grid.
*/
class ObjectMapperFactory
{
public:
ObjectMapperFactory(const ObjectAppearanceManager & objectAppearance);
~ObjectMapperFactory();
SelectionPanel::Mapper generateObjectMapper(const std::vector<Object> & objects) const;
private:
SelectionPanel::Mapper generateMapper(std::vector<SelectionPanel::ItemEntry> entries) const;
const ObjectAppearanceManager * objectAppearance;
};
#endif
| 27.903226 | 120 | 0.808092 | [
"object",
"vector"
] |
98fff2778341b0a96bdf25410205175c435ddc61 | 969 | cpp | C++ | C++/0149-Max-Points-on-a-Line/soln.cpp | wyaadarsh/LeetCode-Solutions | 3719f5cb059eefd66b83eb8ae990652f4b7fd124 | [
"MIT"
] | 5 | 2020-07-24T17:48:59.000Z | 2020-12-21T05:56:00.000Z | C++/0149-Max-Points-on-a-Line/soln.cpp | zhangyaqi1989/LeetCode-Solutions | 2655a1ffc8678ad1de6c24295071308a18c5dc6e | [
"MIT"
] | null | null | null | C++/0149-Max-Points-on-a-Line/soln.cpp | zhangyaqi1989/LeetCode-Solutions | 2655a1ffc8678ad1de6c24295071308a18c5dc6e | [
"MIT"
] | 2 | 2020-07-24T17:49:01.000Z | 2020-08-31T19:57:35.000Z | class Solution {
public:
int maxPoints(vector<vector<int>>& points) {
int ans = 0;
int n = points.size();
for (vector<int> & A : points) {
map<pair<int, int>, int> slopes;
int x0 = A[0], y0 = A[1];
int nsames = 0;
int ninfs = 0;
for(vector<int> & point : points) {
int x1 = point[0], y1 = point[1];
if (x0 == x1 and y0 == y1) {
++nsames;
} else if (x0 == x1) {
++ninfs;
} else {
int dy = y1 - y0, dx = x1 - x0;
int g = __gcd(dy, dx);
++slopes[{dx / g, dy / g}];
}
}
int mx = ninfs;
for(auto & p : slopes) {
if (p.second > mx) mx = p.second;
}
if (mx + nsames > ans) ans = mx + nsames;
}
return ans;
}
};
| 30.28125 | 54 | 0.351909 | [
"vector"
] |
c707b78b84af0835bcf28fd0c218f7a2d23f86d6 | 9,232 | cpp | C++ | octree/Octree/Octree.cpp | yhexie/O-CNN | 33cdf50d103385e6c1019e29abc7dbe11f900970 | [
"MIT"
] | 2 | 2020-11-19T03:33:12.000Z | 2020-11-19T03:33:30.000Z | octree/Octree/Octree.cpp | wzh77/O-CNN | 33cdf50d103385e6c1019e29abc7dbe11f900970 | [
"MIT"
] | null | null | null | octree/Octree/Octree.cpp | wzh77/O-CNN | 33cdf50d103385e6c1019e29abc7dbe11f900970 | [
"MIT"
] | 1 | 2020-11-19T03:33:20.000Z | 2020-11-19T03:33:20.000Z | #include "Octree.h"
#include <algorithm>
#include <fstream>
#include <iostream>
void Octree::build(const int depth, const int full_layer,
const int npt, const float* bbmin, const float* bbmax,
const float* pts, const float* normals, const int* labels)
{
// init
full_layer_ = full_layer < 1 ? 1 : full_layer;
depth_ = full_layer < depth ? depth : full_layer;
set_bbox(bbmin, bbmax);
children_.clear();
children_.resize(depth + 1);
keys_.clear();
keys_.resize(depth + 1);
// preprocess, get key and sort
vector<uint32> node_keys, sorted_idx;
vector<float> weights;
processing_points(node_keys, sorted_idx, weights, pts, npt);
// get unique key
vector<uint32> unique_idx;
unique_key(node_keys, unique_idx);
// build tree
// build layer 0 to full_layer_depth_
for (int curr_depth = 0; curr_depth <= full_layer_; curr_depth++)
{
vector<int>& children = children_[curr_depth];
vector<uint32>& keys = keys_[curr_depth];
int n = 1 << 3 * curr_depth;
keys.resize(n, -1); children.resize(n, -1);
for (int i = 0; i < n; i++)
{
keys[i] = i;
if (curr_depth != full_layer_)
{
children[i] = i;
}
}
}
// build layers
for (int curr_depth = depth_; curr_depth > full_layer_; --curr_depth)
{
// compute parent key, i.e. keys of layer (curr_depth -1)
int n = node_keys.size();
vector<uint32> parent_keys(n);
#pragma omp parallel for
for (int i = 0; i < n; i++)
{
parent_keys[i] = node_keys[i] >> 3;
}
// compute unique parent key
vector<uint32> parent_pidx;
unique_key(parent_keys, parent_pidx);
// augment children keys and create nodes
int np = parent_keys.size();
int nch = np << 3;
vector<int>& children = children_[curr_depth];
vector<uint32>& keys = keys_[curr_depth];
children.resize(nch, -1);
keys.resize(nch, 0);
for (int i = 0; i < nch; i++)
{
int j = i >> 3;
keys[i] = (parent_keys[j] << 3) | (i % 8);
}
// compute base address for each node
vector<uint32> addr(nch);
for (int i = 0; i < np; i++)
{
for (uint32 j = parent_pidx[i]; j < parent_pidx[i + 1]; j++)
{
addr[j] = i << 3;
}
}
// set children pointer and parent pointer
#pragma omp parallel for
for (int i = 0; i < n; i++)
{
// address
uint32 k = (node_keys[i] & 7u) | addr[i];
// set children pointer for layer curr_depth
children[k] = i;
}
// save data and prepare for the following iteration
node_keys.swap(parent_keys);
}
// set the children for the layer full_layer_depth_
// Now the node_keys are the key for full_layer
if (depth_ > full_layer_)
{
for (int i = 0; i < node_keys.size(); i++)
{
uint32 j = node_keys[i];
children_[full_layer_][j] = i;
}
}
// splat normal (according to Ps, Ns, pnum, pidx)
splat_normal(normals, weights, sorted_idx, unique_idx, children_[depth_]);
if(labels != nullptr)
splat_label(labels, weights, sorted_idx, unique_idx, children_[depth_]);
}
bool Octree::save(std::string& filename)
{
std::ofstream outfile(filename, std::ios::binary);
if (!outfile) return false;
vector<int> node_num;
for (auto& keys : keys_)
{
node_num.push_back(keys.size());
}
vector<int> node_num_accu(depth_ + 2, 0);
for (int i = 1; i < depth_ + 2; ++i)
{
node_num_accu[i] = node_num_accu[i - 1] + node_num[i - 1];
}
int total_node_num = node_num_accu[depth_ + 1];
int final_node_num = node_num[depth_];
// calc key
std::vector<int> key(total_node_num), children(total_node_num);
int idx = 0;
for (int d = 0; d <= depth_; ++d)
{
vector<uint32>& keys = keys_[d];
for (int i =0; i < keys.size(); ++i)
{
// calc point
uint32 k = keys[i], pt[3];
compute_pt(pt, k, d);
// compress
unsigned char* ptr = reinterpret_cast<unsigned char*>(&key[idx]);
ptr[0] = static_cast<unsigned char>(pt[0]);
ptr[1] = static_cast<unsigned char>(pt[1]);
ptr[2] = static_cast<unsigned char>(pt[2]);
ptr[3] = static_cast<unsigned char>(d);
// children
children[idx] = children_[d][i];
// update index
idx++;
}
}
// write
outfile.write((char*)&total_node_num, sizeof(int));
outfile.write((char*)&final_node_num, sizeof(int));
outfile.write((char*)&depth_, sizeof(int));
outfile.write((char*)&full_layer_, sizeof(int));
outfile.write((char*)node_num.data(), sizeof(int)*(depth_ + 1));
outfile.write((char*)node_num_accu.data(), sizeof(int)*(depth_ + 2));
outfile.write((char*)key.data(), sizeof(int)*total_node_num);
outfile.write((char*)children.data(), sizeof(int)*total_node_num);
outfile.write((char*)data_.data(), sizeof(float) * 3 * final_node_num);
if (!label_.empty())
{
outfile.write((char*)label_.data(), label_.size()*sizeof(int));
}
outfile.close();
return true;
}
void Octree::set_bbox(const float* bbmin, const float* bbmax)
{
float center[3];
scale_ = -1.0e20;
for (int i = 0; i < 3; ++i)
{
float dis = bbmax[i] - bbmin[i];
if (dis > scale_) scale_ = dis;
center[i] = (bbmin[i] + bbmax[i])*0.5;
}
// set the bounding box and place the object in the center
float radius = scale_ * 0.5;
for (int i = 0; i < 3; ++i)
{
bbmax_[i] = center[i] + radius;
bbmin_[i] = center[i] - radius;
}
}
void Octree::processing_points(vector<uint32>& sorted_keys,
vector<uint32>& sorted_idx, vector<float>& weights,
const float* pts, const int npt)
{
sorted_keys.resize(npt);
sorted_idx.resize(npt);
weights.resize(npt);
vector<uint64> code(npt);
const float mul = float(1 << depth_) / scale_;
#pragma omp parallel for
for (int i = 0; i < npt; i++)
{
// normalize coordinate
uint32 pt[3];
weights[i] = 1.0f;
for (int j = 0; j < 3; j++)
{
float tmp = (pts[i * 3 + j] - bbmin_[j]) * mul;
pt[j] = tmp;
weights[i] *= bspline(float(pt[j]) + 0.5f - tmp);
}
// calc key
uint32 key;
compute_key(key, pt, depth_);
// generate code
uint32* ptr = (uint32*)(&code[i]);
ptr[0] = i;
ptr[1] = key;
}
// sort all sample points
std::sort(code.begin(), code.end());
// unpack the code
#pragma omp parallel for
for (int i = 0; i < npt; i++)
{
uint32* ptr = (uint32*)(&code[i]);
sorted_idx[i] = ptr[0];
sorted_keys[i] = ptr[1];
}
}
void Octree::unique_key(vector<uint32>& keys, vector<uint32>& idx)
{
// init
idx.clear();
idx.push_back(0);
// unique
int n = keys.size(), j = 1;
for (int i = 1; i < n; i++)
{
if (keys[i] != keys[i - 1])
{
idx.push_back(i);
keys[j++] = keys[i];
}
}
keys.resize(j);
idx.push_back(n);
}
inline void Octree::compute_key(uint32& key, const uint32* pt, const int depth)
{
key = 0;
for (int i = 0; i < depth; i++)
{
uint32 mask = 1u << i;
for (int j = 0; j < 3; j++)
{
key |= (pt[j] & mask) << (2 * i + 2 - j);
}
}
}
inline void Octree::compute_pt(uint32* pt, const uint32& key, const int depth)
{
// init
for (int i = 0; i < 3; pt[i++] = 0u);
// convert
for (int i = 0; i < depth; i++)
{
for (int j = 0; j < 3; j++)
{
// bit mask
uint32 mask = 1u << (3 * i + 2 - j);
// put the bit to position i
pt[j] |= (key & mask) >> (2 * i + 2 - j);
}
}
}
inline float Octree::bspline(float x)
{
if (x < -1.5f)
{
return 0;
}
else if (x < -0.5f)
{
return 0.5f * (x + 1.5f) * (x + 1.5f);
}
else if ( x < 0.5f)
{
return 0.75f - x * x;
}
else if (x <= 1.5f)
{
return 0.5f * (x - 1.5f) * (x - 1.5f);
}
else
{
return 0;
}
}
void Octree::splat_normal(const float* normals, const vector<float>& weights,
const vector<uint32>& sorted_idx, const vector<uint32>& unique_idx,
const vector<int>& children)
{
int n = children.size();
data_.resize(3 * n);
#pragma omp parallel for
for (int i = 0; i < n; i++)
{
int t = children[i];
vector<float> Nw(3, 0.0);
if (t != -1)
{
for (int j = unique_idx[t]; j < unique_idx[t + 1]; j++)
{
int h = sorted_idx[j];
Nw[0] += weights[h] * normals[3 * h];
Nw[1] += weights[h] * normals[3 * h + 1];
Nw[2] += weights[h] * normals[3 * h + 2];
}
float len = sqrt(Nw[0] * Nw[0] + Nw[1] * Nw[1] + Nw[2] * Nw[2]);
if (len < ESP) len = ESP;
Nw[0] /= len;
Nw[1] /= len;
Nw[2] /= len;
}
data_[i] = Nw[0];
data_[n + i] = Nw[1];
data_[2 * n + i] = Nw[2];
}
}
void Octree::splat_label(const int* labels, const vector<float>& weights,
const vector<uint32>& sorted_idx, const vector<uint32>& unique_idx,
const vector<int>& children)
{
int n = children.size();
int nl = *std::max_element(labels, labels + n) + 1;
label_.clear();
label_.resize(n, -1);
#pragma omp parallel for
for (int i = 0; i < n; i++)
{
int t = children[i];
if (t == -1) continue;
vector<float> Lw(nl, 0);
for (int j = unique_idx[t]; j < unique_idx[t + 1]; j++)
{
int h = sorted_idx[j];
Lw[labels[h]] += weights[h];
}
label_[i] = 0;
float v = Lw[0];
for (int j = 1; j < nl; ++j)
{
if (Lw[j] > v)
{
v = Lw[j];
label_[i] = j;
}
}
}
}
| 23.254408 | 80 | 0.573115 | [
"object",
"vector"
] |
c70ada2f0332177fa80287f63546c7a9072127f5 | 1,349 | cpp | C++ | QT/SubwayForQt/QTDropDownButton.cpp | qyxlxr/LINSANforQt | 5c426d556ce1cd8f4fa3234b58768d8bc783b266 | [
"MIT"
] | 3 | 2018-12-05T09:14:39.000Z | 2021-03-01T12:34:14.000Z | QT/SubwayForQt/QTDropDownButton.cpp | qyxlxr/routeDesignByDijkstra | 5c426d556ce1cd8f4fa3234b58768d8bc783b266 | [
"MIT"
] | null | null | null | QT/SubwayForQt/QTDropDownButton.cpp | qyxlxr/routeDesignByDijkstra | 5c426d556ce1cd8f4fa3234b58768d8bc783b266 | [
"MIT"
] | null | null | null | #include "QTDropDownButton.h"
QTDropDownButton::QTDropDownButton(QString text, QWidget *parent) :
QPushButton(text, parent)
{
setFlat(true);
menu_ = new QMenu();
setMenu(menu_);
connect(menu_, SIGNAL(aboutToShow()), this, SLOT(menuAboutToShow()));
connect(menu_, SIGNAL(triggered(QAction*)), this, SLOT(menuTriggered(QAction*)));
setStyleSheet("QPushButton {text-align: left; font-family: Arial; font-size: 13pt; color: #808080; border: 1px solid gray; padding: 5px;}"
"QPushButton::menu-indicator {subcontrol-origin: padding; subcontrol-position: right center; right:5px;}");
menu_->setStyleSheet("QLabel {font-family: Arial; font-size: 13pt; padding: 5px 0 5px 0; background-color: transparent;}"
"QLabel:hover {background-color: rgb(51, 153, 255);}");
}
void QTDropDownButton::addItem(QString text)
{
if (!menu_)
return;
QWidgetAction* wa1 = new QWidgetAction(menu_);
QLabel* l1 = new QLabel(text);
wa1->setDefaultWidget(l1);
menu_->addAction(wa1);
}
void QTDropDownButton::menuAboutToShow()
{
if (menu_)
{
menu_->setFixedWidth(this->width());
}
}
void QTDropDownButton::menuTriggered(QAction *action)
{
if (!action)
return;
QWidgetAction* qwa = dynamic_cast<QWidgetAction*>(action);
if (!qwa)
return;
QLabel* ql = dynamic_cast<QLabel*>(qwa->defaultWidget());
if (!ql)
return;
setText(ql->text());
} | 25.45283 | 139 | 0.716086 | [
"solid"
] |
c70b728535beb16ac7e7ecdcd2afcaece9c4d0d1 | 4,096 | cpp | C++ | Sources/AlgoritmoFleury.cpp | Globson/TP-II-Grafos | cd6624638f2f6ec632635a07dda09fe643bd4209 | [
"MIT"
] | null | null | null | Sources/AlgoritmoFleury.cpp | Globson/TP-II-Grafos | cd6624638f2f6ec632635a07dda09fe643bd4209 | [
"MIT"
] | null | null | null | Sources/AlgoritmoFleury.cpp | Globson/TP-II-Grafos | cd6624638f2f6ec632635a07dda09fe643bd4209 | [
"MIT"
] | null | null | null | #include "../Headers/AlgoritmoFleury.hpp"
void AlgoritmoFleury::DFS(int x,bool Visitados[]){ // busca por um vizinho não visitado
Visitados[x] = true; //marca todos os vertices visitados
vector<int>::iterator it;
for(it = GrafoInterno->Arestas[x].begin(); it != GrafoInterno->Arestas[x].end(); it++){
if(!Visitados[*it]){
DFS(*it,Visitados);
}
}
}
void AlgoritmoFleury::VerificaEuleriano(Grafo *Grafo){ // Função verifica se grafo é euleriano
this->GrafoInterno = Grafo;
if(!VerificaConexo()){ // Verifica se todas as arestas sao acessiveis
cout<<" -->Grafo nao euleriano<--"<<endl<<endl;
return;
}
int aux=0;
for(int i=0;i<GrafoInterno->V;i++){
if(GrafoInterno->obterGrau(i)%2 == 1){
aux++; //Quantidade de vertices de grau impar
}
}
if(aux>2){ //se maior que 2 grafo nao pode ser euleriano
cout<<" -->Grafo nao euleriano<--"<<endl<<endl;
return;
}
if(aux==2){ // se exatamente igual a 2 grafo é semi-euleriano
cout<<" -->Grafo semi-euleriano<--"<<endl<<endl;
cout<<"Impressao da trilha euleriana:"<<endl;
EscolheArestaImprime();
return;
}
else{ //caso seja menor que 2, o grafo é euleriano
cout<<" -->Grafo euleriano<--"<<endl<<endl;
cout<<"Impressao do ciclo euleriano:"<<endl;
EscolheArestaImprime();
return;
}
}
bool AlgoritmoFleury::VerificaConexo(){ //Função para verificar se é possivel acessar todas as arestas apartir de um dado vertice
bool Visitados[GrafoInterno->V]; //Vetor para marcar vertices visitados
for(int i=0;i<GrafoInterno->V;i++){
Visitados[i]=false;
}
int j;
for(j=0;j<GrafoInterno->V;j++){
if(!GrafoInterno->Arestas[j].empty()){
break; //caso alguma aresta seja encontrada no grafo, o for será interrompido
}
}
if(j==GrafoInterno->V){ //Caso o for nao seja interrompido
return false; // O grafo não possui nenhuma aresta
}
DFS(j,Visitados);
for(int i=0;i<GrafoInterno->V;i++){
if ((!Visitados[i]) && GrafoInterno->obterGrau(i) > 0){ //Se algum vertice nao for visitado e possuir alguma aresta, o grafo é disconexo.
return false;
}
}
return true;
}
void AlgoritmoFleury::EscolheArestaImprime(){ //Função para escolher uma aresta inicial e em seguida começar a impressão do ciclo ou trilha.
int VerticeInicial = 0;
for(int i=0;i<GrafoInterno->V;i++){
if(GrafoInterno->obterGrau(i)%2==1){ //Prioriza começar por vertices de grau impar.
VerticeInicial = i;
break;
}
}
ImprimePasseioEuleriano(VerticeInicial); // Chama impressao
}
int AlgoritmoFleury::QuantVerticesVisitados(bool Visitados[]){ // Função que retorna quantos vertices foram visitados.
int aux=0;
for(int i=0;i<GrafoInterno->V;i++){
if(Visitados[i]){
aux++;
}
}
return aux;
}
bool AlgoritmoFleury::ArestaValida(int i, int j){ //Retorna true caso aresta não seja uma ponte, false caso seja.
if(GrafoInterno->obterGrau(i)==1){
return true;
}
bool Visitados1[GrafoInterno->V]; //Vetores de visitados para comparações
bool Visitados2[GrafoInterno->V];
for(int i=0;i<GrafoInterno->V;i++){
Visitados1[i] = false;
Visitados2[i] = false;
}
DFS(i,Visitados1);
GrafoInterno->removeAresta(i,j);
DFS(i,Visitados2); //São computados os vetores de visitados um com a aresta e outro sem.
GrafoInterno->adicionarAresta(i,j);
return QuantVerticesVisitados(Visitados1) > QuantVerticesVisitados(Visitados2) ? false : true; //Caso a quantidade de vertices visitados forem maiores ou igual, aresta não é uma ponte.
}
void AlgoritmoFleury::ImprimePasseioEuleriano(int VerticeInicio){ //Impressão de caminho ou ciclo euleriano
for(int i=0;i<GrafoInterno->obterGrau(VerticeInicio);i++){
int x = GrafoInterno->Arestas[VerticeInicio].at(i);
if(ArestaValida(VerticeInicio,x)){
cout<<"\t("<<(VerticeInicio+1)<<")<==>("<<(x+1)<<")"<<endl;
GrafoInterno->removeAresta(VerticeInicio, x); //Aresta impressa é removida
ImprimePasseioEuleriano(x); //Processo é chamado recursivamente
}
}
}
| 35.617391 | 187 | 0.669678 | [
"vector"
] |
c70e822cd9bf6230bc7d86bb5dc4d5a160ab9511 | 12,746 | cpp | C++ | src/gpu/GrTextStrike.cpp | yinquan529/platform-external-skia | 1adfb847fe565e53d2e26e35b04c8dc112b7513a | [
"BSD-3-Clause"
] | 1 | 2016-05-04T10:08:50.000Z | 2016-05-04T10:08:50.000Z | src/gpu/GrTextStrike.cpp | yinquan529/platform-external-skia | 1adfb847fe565e53d2e26e35b04c8dc112b7513a | [
"BSD-3-Clause"
] | null | null | null | src/gpu/GrTextStrike.cpp | yinquan529/platform-external-skia | 1adfb847fe565e53d2e26e35b04c8dc112b7513a | [
"BSD-3-Clause"
] | 1 | 2020-01-16T03:34:53.000Z | 2020-01-16T03:34:53.000Z | /*
* Copyright 2010 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrAtlas.h"
#include "GrGpu.h"
#include "GrRectanizer.h"
#include "GrTextStrike.h"
#include "GrTextStrike_impl.h"
#include "SkString.h"
#if SK_DISTANCEFIELD_FONTS
#include "edtaa3.h"
#endif
///////////////////////////////////////////////////////////////////////////////
#define FONT_CACHE_STATS 0
#if FONT_CACHE_STATS
static int g_PurgeCount = 0;
#endif
GrFontCache::GrFontCache(GrGpu* gpu) : fGpu(gpu) {
gpu->ref();
for (int i = 0; i < kAtlasCount; ++i) {
fAtlasMgr[i] = NULL;
}
fHead = fTail = NULL;
}
GrFontCache::~GrFontCache() {
fCache.deleteAll();
for (int i = 0; i < kAtlasCount; ++i) {
delete fAtlasMgr[i];
}
fGpu->unref();
#if FONT_CACHE_STATS
GrPrintf("Num purges: %d\n", g_PurgeCount);
#endif
}
static GrPixelConfig mask_format_to_pixel_config(GrMaskFormat format) {
static const GrPixelConfig sPixelConfigs[] = {
kAlpha_8_GrPixelConfig,
kRGB_565_GrPixelConfig,
kSkia8888_GrPixelConfig,
kSkia8888_GrPixelConfig
};
SK_COMPILE_ASSERT(SK_ARRAY_COUNT(sPixelConfigs) == kMaskFormatCount, array_size_mismatch);
return sPixelConfigs[format];
}
static int mask_format_to_atlas_index(GrMaskFormat format) {
static const int sAtlasIndices[] = {
GrFontCache::kA8_AtlasType,
GrFontCache::k565_AtlasType,
GrFontCache::k8888_AtlasType,
GrFontCache::k8888_AtlasType
};
SK_COMPILE_ASSERT(SK_ARRAY_COUNT(sAtlasIndices) == kMaskFormatCount, array_size_mismatch);
SkASSERT(sAtlasIndices[format] < GrFontCache::kAtlasCount);
return sAtlasIndices[format];
}
GrTextStrike* GrFontCache::generateStrike(GrFontScaler* scaler,
const Key& key) {
GrMaskFormat format = scaler->getMaskFormat();
GrPixelConfig config = mask_format_to_pixel_config(format);
int atlasIndex = mask_format_to_atlas_index(format);
if (NULL == fAtlasMgr[atlasIndex]) {
fAtlasMgr[atlasIndex] = SkNEW_ARGS(GrAtlasMgr, (fGpu, config));
}
GrTextStrike* strike = SkNEW_ARGS(GrTextStrike,
(this, scaler->getKey(), format, fAtlasMgr[atlasIndex]));
fCache.insert(key, strike);
if (fHead) {
fHead->fPrev = strike;
} else {
SkASSERT(NULL == fTail);
fTail = strike;
}
strike->fPrev = NULL;
strike->fNext = fHead;
fHead = strike;
return strike;
}
void GrFontCache::freeAll() {
fCache.deleteAll();
for (int i = 0; i < kAtlasCount; ++i) {
delete fAtlasMgr[i];
fAtlasMgr[i] = NULL;
}
fHead = NULL;
fTail = NULL;
}
void GrFontCache::purgeStrike(GrTextStrike* strike) {
const GrFontCache::Key key(strike->fFontScalerKey);
fCache.remove(key, strike);
this->detachStrikeFromList(strike);
delete strike;
}
void GrFontCache::purgeExceptFor(GrTextStrike* preserveStrike) {
SkASSERT(NULL != preserveStrike);
GrTextStrike* strike = fTail;
bool purge = true;
GrMaskFormat maskFormat = preserveStrike->fMaskFormat;
while (strike) {
if (strike == preserveStrike || maskFormat != strike->fMaskFormat) {
strike = strike->fPrev;
continue;
}
GrTextStrike* strikeToPurge = strike;
strike = strikeToPurge->fPrev;
if (purge) {
// keep purging if we won't free up any atlases with this strike.
purge = strikeToPurge->fAtlas.isEmpty();
this->purgeStrike(strikeToPurge);
}
}
#if FONT_CACHE_STATS
++g_PurgeCount;
#endif
}
void GrFontCache::freePlotExceptFor(GrTextStrike* preserveStrike) {
SkASSERT(NULL != preserveStrike);
GrTextStrike* strike = fTail;
GrMaskFormat maskFormat = preserveStrike->fMaskFormat;
while (strike) {
if (strike == preserveStrike || maskFormat != strike->fMaskFormat) {
strike = strike->fPrev;
continue;
}
GrTextStrike* strikeToPurge = strike;
strike = strikeToPurge->fPrev;
if (strikeToPurge->removeUnusedPlots()) {
if (strikeToPurge->fAtlas.isEmpty()) {
this->purgeStrike(strikeToPurge);
}
break;
}
}
}
#ifdef SK_DEBUG
void GrFontCache::validate() const {
int count = fCache.count();
if (0 == count) {
SkASSERT(!fHead);
SkASSERT(!fTail);
} else if (1 == count) {
SkASSERT(fHead == fTail);
} else {
SkASSERT(fHead != fTail);
}
int count2 = 0;
const GrTextStrike* strike = fHead;
while (strike) {
count2 += 1;
strike = strike->fNext;
}
SkASSERT(count == count2);
count2 = 0;
strike = fTail;
while (strike) {
count2 += 1;
strike = strike->fPrev;
}
SkASSERT(count == count2);
}
#endif
#ifdef SK_DEVELOPER
void GrFontCache::dump() const {
static int gDumpCount = 0;
for (int i = 0; i < kAtlasCount; ++i) {
if (NULL != fAtlasMgr[i]) {
GrTexture* texture = fAtlasMgr[i]->getTexture();
if (NULL != texture) {
SkString filename;
filename.printf("fontcache_%d%d.png", gDumpCount, i);
texture->savePixels(filename.c_str());
}
}
}
++gDumpCount;
}
#endif
///////////////////////////////////////////////////////////////////////////////
#ifdef SK_DEBUG
static int gCounter;
#endif
#if SK_DISTANCEFIELD_FONTS
#define DISTANCE_FIELD_PAD 4
#define DISTANCE_FIELD_RANGE (4.0)
#endif
/*
The text strike is specific to a given font/style/matrix setup, which is
represented by the GrHostFontScaler object we are given in getGlyph().
We map a 32bit glyphID to a GrGlyph record, which in turn points to a
atlas and a position within that texture.
*/
GrTextStrike::GrTextStrike(GrFontCache* cache, const GrKey* key,
GrMaskFormat format,
GrAtlasMgr* atlasMgr) : fPool(64), fAtlas(atlasMgr) {
fFontScalerKey = key;
fFontScalerKey->ref();
fFontCache = cache; // no need to ref, it won't go away before we do
fAtlasMgr = atlasMgr; // no need to ref, it won't go away before we do
fMaskFormat = format;
#ifdef SK_DEBUG
// GrPrintf(" GrTextStrike %p %d\n", this, gCounter);
gCounter += 1;
#endif
}
// these signatures are needed because they're used with
// SkTDArray::visitAll() (see destructor & removeUnusedAtlases())
static void free_glyph(GrGlyph*& glyph) { glyph->free(); }
static void invalidate_glyph(GrGlyph*& glyph) {
if (glyph->fPlot && glyph->fPlot->drawToken().isIssued()) {
glyph->fPlot = NULL;
}
}
GrTextStrike::~GrTextStrike() {
fFontScalerKey->unref();
fCache.getArray().visitAll(free_glyph);
#ifdef SK_DEBUG
gCounter -= 1;
// GrPrintf("~GrTextStrike %p %d\n", this, gCounter);
#endif
}
GrGlyph* GrTextStrike::generateGlyph(GrGlyph::PackedID packed,
GrFontScaler* scaler) {
SkIRect bounds;
if (!scaler->getPackedGlyphBounds(packed, &bounds)) {
return NULL;
}
GrGlyph* glyph = fPool.alloc();
#if SK_DISTANCEFIELD_FONTS
// expand bounds to hold full distance field data
if (fUseDistanceField) {
bounds.fLeft -= DISTANCE_FIELD_PAD;
bounds.fRight += DISTANCE_FIELD_PAD;
bounds.fTop -= DISTANCE_FIELD_PAD;
bounds.fBottom += DISTANCE_FIELD_PAD;
}
#endif
glyph->init(packed, bounds);
fCache.insert(packed, glyph);
return glyph;
}
bool GrTextStrike::removeUnusedPlots() {
fCache.getArray().visitAll(invalidate_glyph);
return fAtlasMgr->removeUnusedPlots(&fAtlas);
}
bool GrTextStrike::getGlyphAtlas(GrGlyph* glyph, GrFontScaler* scaler) {
#if 0 // testing hack to force us to flush our cache often
static int gCounter;
if ((++gCounter % 10) == 0) return false;
#endif
SkASSERT(glyph);
SkASSERT(scaler);
SkASSERT(fCache.contains(glyph));
SkASSERT(NULL == glyph->fPlot);
SkAutoRef ar(scaler);
int bytesPerPixel = GrMaskFormatBytesPerPixel(fMaskFormat);
GrPlot* plot;
#if SK_DISTANCEFIELD_FONTS
if (fUseDistanceField) {
SkASSERT(1 == bytesPerPixel);
// we've already expanded the glyph dimensions to match the final size
// but must shrink back down to get the packed glyph data
int dfWidth = glyph->width();
int dfHeight = glyph->height();
int width = dfWidth - 2*DISTANCE_FIELD_PAD;
int height = dfHeight - 2*DISTANCE_FIELD_PAD;
size_t stride = width*bytesPerPixel;
size_t size = width * height * bytesPerPixel;
SkAutoSMalloc<1024> storage(size);
if (!scaler->getPackedGlyphImage(glyph->fPackedID, width, height, stride, storage.get())) {
return false;
}
// alloc storage for distance field glyph
size_t dfSize = dfWidth * dfHeight * bytesPerPixel;
SkAutoSMalloc<1024> dfStorage(dfSize);
// copy glyph into distance field storage
sk_bzero(dfStorage.get(), dfSize);
unsigned char* ptr = (unsigned char*) storage.get();
unsigned char* dfPtr = (unsigned char*) dfStorage.get();
size_t dfStride = dfWidth*bytesPerPixel;
dfPtr += DISTANCE_FIELD_PAD*dfStride;
dfPtr += DISTANCE_FIELD_PAD*bytesPerPixel;
for (int i = 0; i < height; ++i) {
memcpy(dfPtr, ptr, stride);
dfPtr += dfStride;
ptr += stride;
}
// generate distance field data
SkAutoSMalloc<1024> distXStorage(dfWidth*dfHeight*sizeof(short));
SkAutoSMalloc<1024> distYStorage(dfWidth*dfHeight*sizeof(short));
SkAutoSMalloc<1024> outerDistStorage(dfWidth*dfHeight*sizeof(double));
SkAutoSMalloc<1024> innerDistStorage(dfWidth*dfHeight*sizeof(double));
SkAutoSMalloc<1024> gxStorage(dfWidth*dfHeight*sizeof(double));
SkAutoSMalloc<1024> gyStorage(dfWidth*dfHeight*sizeof(double));
short* distX = (short*) distXStorage.get();
short* distY = (short*) distYStorage.get();
double* outerDist = (double*) outerDistStorage.get();
double* innerDist = (double*) innerDistStorage.get();
double* gx = (double*) gxStorage.get();
double* gy = (double*) gyStorage.get();
dfPtr = (unsigned char*) dfStorage.get();
EDTAA::computegradient(dfPtr, dfWidth, dfHeight, gx, gy);
EDTAA::edtaa3(dfPtr, gx, gy, dfWidth, dfHeight, distX, distY, outerDist);
for (int i = 0; i < dfWidth*dfHeight; ++i) {
*dfPtr = 255 - *dfPtr;
dfPtr++;
}
dfPtr = (unsigned char*) dfStorage.get();
sk_bzero(gx, sizeof(double)*dfWidth*dfHeight);
sk_bzero(gy, sizeof(double)*dfWidth*dfHeight);
EDTAA::computegradient(dfPtr, dfWidth, dfHeight, gx, gy);
EDTAA::edtaa3(dfPtr, gx, gy, dfWidth, dfHeight, distX, distY, innerDist);
for (int i = 0; i < dfWidth*dfHeight; ++i) {
unsigned char val;
double outerval = outerDist[i];
if (outerval < 0.0) {
outerval = 0.0;
}
double innerval = innerDist[i];
if (innerval < 0.0) {
innerval = 0.0;
}
double dist = outerval - innerval;
if (dist <= -DISTANCE_FIELD_RANGE) {
val = 255;
} else if (dist > DISTANCE_FIELD_RANGE) {
val = 0;
} else {
val = (unsigned char)((DISTANCE_FIELD_RANGE-dist)*128.0/DISTANCE_FIELD_RANGE);
}
*dfPtr++ = val;
}
// copy to atlas
plot = fAtlasMgr->addToAtlas(&fAtlas, dfWidth, dfHeight, dfStorage.get(),
&glyph->fAtlasLocation);
} else {
#endif
size_t size = glyph->fBounds.area() * bytesPerPixel;
SkAutoSMalloc<1024> storage(size);
if (!scaler->getPackedGlyphImage(glyph->fPackedID, glyph->width(),
glyph->height(),
glyph->width() * bytesPerPixel,
storage.get())) {
return false;
}
plot = fAtlasMgr->addToAtlas(&fAtlas, glyph->width(),
glyph->height(), storage.get(),
&glyph->fAtlasLocation);
#if SK_DISTANCEFIELD_FONTS
}
#endif
if (NULL == plot) {
return false;
}
glyph->fPlot = plot;
return true;
}
| 30.347619 | 99 | 0.599953 | [
"object"
] |
c70e89d710726c7f5da7bc7943d8bed4a14420b5 | 28,453 | cpp | C++ | node/Peer.cpp | allieae/ZeroTierOne | 80391c33eb8abbd984b8f0d1bd7db2c63e88d833 | [
"RSA-MD"
] | 1 | 2021-11-29T11:57:36.000Z | 2021-11-29T11:57:36.000Z | node/Peer.cpp | iDoXtreme/ZeroTierOne | bb84c9b65cd180e7de0f4718cd6030ada0b2bbba | [
"RSA-MD"
] | 1 | 2020-01-27T21:25:50.000Z | 2020-01-27T21:25:50.000Z | node/Peer.cpp | iDoXtreme/ZeroTierOne | bb84c9b65cd180e7de0f4718cd6030ada0b2bbba | [
"RSA-MD"
] | 1 | 2021-10-09T16:14:31.000Z | 2021-10-09T16:14:31.000Z | /*
* Copyright (c)2019 ZeroTier, Inc.
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2023-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
*/
/****/
#include "../version.h"
#include "Constants.hpp"
#include "Peer.hpp"
#include "Node.hpp"
#include "Switch.hpp"
#include "Network.hpp"
#include "SelfAwareness.hpp"
#include "Packet.hpp"
#include "Trace.hpp"
#include "InetAddress.hpp"
#include "RingBuffer.hpp"
#include "Utils.hpp"
namespace ZeroTier {
static unsigned char s_freeRandomByteCounter = 0;
Peer::Peer(const RuntimeEnvironment *renv,const Identity &myIdentity,const Identity &peerIdentity) :
RR(renv),
_lastReceive(0),
_lastNontrivialReceive(0),
_lastTriedMemorizedPath(0),
_lastDirectPathPushSent(0),
_lastDirectPathPushReceive(0),
_lastCredentialRequestSent(0),
_lastWhoisRequestReceived(0),
_lastEchoRequestReceived(0),
_lastCredentialsReceived(0),
_lastTrustEstablishedPacketReceived(0),
_lastSentFullHello(0),
_lastACKWindowReset(0),
_lastQoSWindowReset(0),
_lastMultipathCompatibilityCheck(0),
_freeRandomByte((unsigned char)((uintptr_t)this >> 4) ^ ++s_freeRandomByteCounter),
_uniqueAlivePathCount(0),
_localMultipathSupported(false),
_remoteMultipathSupported(false),
_canUseMultipath(false),
_vProto(0),
_vMajor(0),
_vMinor(0),
_vRevision(0),
_id(peerIdentity),
_directPathPushCutoffCount(0),
_credentialsCutoffCount(0),
_linkIsBalanced(false),
_linkIsRedundant(false),
_remotePeerMultipathEnabled(false),
_lastAggregateStatsReport(0),
_lastAggregateAllocation(0)
{
if (!myIdentity.agree(peerIdentity,_key,ZT_PEER_SECRET_KEY_LENGTH))
throw ZT_EXCEPTION_INVALID_ARGUMENT;
}
void Peer::received(
void *tPtr,
const SharedPtr<Path> &path,
const unsigned int hops,
const uint64_t packetId,
const unsigned int payloadLength,
const Packet::Verb verb,
const uint64_t inRePacketId,
const Packet::Verb inReVerb,
const bool trustEstablished,
const uint64_t networkId)
{
const int64_t now = RR->node->now();
_lastReceive = now;
switch (verb) {
case Packet::VERB_FRAME:
case Packet::VERB_EXT_FRAME:
case Packet::VERB_NETWORK_CONFIG_REQUEST:
case Packet::VERB_NETWORK_CONFIG:
case Packet::VERB_MULTICAST_FRAME:
_lastNontrivialReceive = now;
break;
default:
break;
}
if (trustEstablished) {
_lastTrustEstablishedPacketReceived = now;
path->trustedPacketReceived(now);
}
{
Mutex::Lock _l(_paths_m);
recordIncomingPacket(tPtr, path, packetId, payloadLength, verb, now);
if (_canUseMultipath) {
if (path->needsToSendQoS(now)) {
sendQOS_MEASUREMENT(tPtr, path, path->localSocket(), path->address(), now);
}
for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
if (_paths[i].p) {
_paths[i].p->processBackgroundPathMeasurements(now);
}
}
}
}
if (hops == 0) {
// If this is a direct packet (no hops), update existing paths or learn new ones
bool havePath = false;
{
Mutex::Lock _l(_paths_m);
for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
if (_paths[i].p) {
if (_paths[i].p == path) {
_paths[i].lr = now;
havePath = true;
break;
}
} else break;
}
}
bool attemptToContact = false;
if ((!havePath)&&(RR->node->shouldUsePathForZeroTierTraffic(tPtr,_id.address(),path->localSocket(),path->address()))) {
Mutex::Lock _l(_paths_m);
// Paths are redundant if they duplicate an alive path to the same IP or
// with the same local socket and address family.
bool redundant = false;
unsigned int replacePath = ZT_MAX_PEER_NETWORK_PATHS;
for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
if (_paths[i].p) {
if ( (_paths[i].p->alive(now)) && ( ((_paths[i].p->localSocket() == path->localSocket())&&(_paths[i].p->address().ss_family == path->address().ss_family)) || (_paths[i].p->address().ipsEqual2(path->address())) ) ) {
redundant = true;
break;
}
// If the path is the same address and port, simply assume this is a replacement
if ( (_paths[i].p->address().ipsEqual2(path->address()))) {
replacePath = i;
break;
}
} else break;
}
// If the path isn't a duplicate of the same localSocket AND we haven't already determined a replacePath,
// then find the worst path and replace it.
if (!redundant && replacePath == ZT_MAX_PEER_NETWORK_PATHS) {
int replacePathQuality = 0;
for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
if (_paths[i].p) {
const int q = _paths[i].p->quality(now);
if (q > replacePathQuality) {
replacePathQuality = q;
replacePath = i;
}
} else {
replacePath = i;
break;
}
}
}
if (replacePath != ZT_MAX_PEER_NETWORK_PATHS) {
if (verb == Packet::VERB_OK) {
RR->t->peerLearnedNewPath(tPtr,networkId,*this,path,packetId);
_paths[replacePath].lr = now;
_paths[replacePath].p = path;
_paths[replacePath].priority = 1;
} else {
attemptToContact = true;
}
}
}
if (attemptToContact) {
attemptToContactAt(tPtr,path->localSocket(),path->address(),now,true);
path->sent(now);
RR->t->peerConfirmingUnknownPath(tPtr,networkId,*this,path,packetId,verb);
}
}
// If we have a trust relationship periodically push a message enumerating
// all known external addresses for ourselves. If we already have a path this
// is done less frequently.
if (this->trustEstablished(now)) {
const int64_t sinceLastPush = now - _lastDirectPathPushSent;
if (sinceLastPush >= ((hops == 0) ? ZT_DIRECT_PATH_PUSH_INTERVAL_HAVEPATH : ZT_DIRECT_PATH_PUSH_INTERVAL)) {
_lastDirectPathPushSent = now;
std::vector<InetAddress> pathsToPush(RR->node->directPaths());
if (pathsToPush.size() > 0) {
std::vector<InetAddress>::const_iterator p(pathsToPush.begin());
while (p != pathsToPush.end()) {
Packet *const outp = new Packet(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS);
outp->addSize(2); // leave room for count
unsigned int count = 0;
while ((p != pathsToPush.end())&&((outp->size() + 24) < 1200)) {
uint8_t addressType = 4;
switch(p->ss_family) {
case AF_INET:
break;
case AF_INET6:
addressType = 6;
break;
default: // we currently only push IP addresses
++p;
continue;
}
outp->append((uint8_t)0); // no flags
outp->append((uint16_t)0); // no extensions
outp->append(addressType);
outp->append((uint8_t)((addressType == 4) ? 6 : 18));
outp->append(p->rawIpData(),((addressType == 4) ? 4 : 16));
outp->append((uint16_t)p->port());
++count;
++p;
}
if (count) {
outp->setAt(ZT_PACKET_IDX_PAYLOAD,(uint16_t)count);
outp->compress();
outp->armor(_key,true);
path->send(RR,tPtr,outp->data(),outp->size(),now);
}
delete outp;
}
}
}
}
}
void Peer::recordOutgoingPacket(const SharedPtr<Path> &path, const uint64_t packetId,
uint16_t payloadLength, const Packet::Verb verb, int64_t now)
{
_freeRandomByte += (unsigned char)(packetId >> 8); // grab entropy to use in path selection logic for multipath
if (_canUseMultipath) {
path->recordOutgoingPacket(now, packetId, payloadLength, verb);
}
}
void Peer::recordIncomingPacket(void *tPtr, const SharedPtr<Path> &path, const uint64_t packetId,
uint16_t payloadLength, const Packet::Verb verb, int64_t now)
{
if (_canUseMultipath) {
if (path->needsToSendAck(now)) {
sendACK(tPtr, path, path->localSocket(), path->address(), now);
}
path->recordIncomingPacket(now, packetId, payloadLength, verb);
}
}
void Peer::computeAggregateProportionalAllocation(int64_t now)
{
float maxStability = 0;
float totalRelativeQuality = 0;
float maxThroughput = 1;
float maxScope = 0;
float relStability[ZT_MAX_PEER_NETWORK_PATHS];
float relThroughput[ZT_MAX_PEER_NETWORK_PATHS];
memset(&relStability, 0, sizeof(relStability));
memset(&relThroughput, 0, sizeof(relThroughput));
// Survey all paths
for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
if (_paths[i].p) {
relStability[i] = _paths[i].p->lastComputedStability();
relThroughput[i] = (float)_paths[i].p->maxLifetimeThroughput();
maxStability = relStability[i] > maxStability ? relStability[i] : maxStability;
maxThroughput = relThroughput[i] > maxThroughput ? relThroughput[i] : maxThroughput;
maxScope = _paths[i].p->ipScope() > maxScope ? _paths[i].p->ipScope() : maxScope;
}
}
// Convert to relative values
for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
if (_paths[i].p) {
relStability[i] /= maxStability ? maxStability : 1;
relThroughput[i] /= maxThroughput ? maxThroughput : 1;
float normalized_ma = Utils::normalize((float)_paths[i].p->ackAge(now), 0, ZT_PATH_MAX_AGE, 0, 10);
float age_contrib = exp((-1)*normalized_ma);
float relScope = ((float)(_paths[i].p->ipScope()+1) / (maxScope + 1));
float relQuality =
(relStability[i] * (float)ZT_PATH_CONTRIB_STABILITY)
+ (fmaxf(1.0f, relThroughput[i]) * (float)ZT_PATH_CONTRIB_THROUGHPUT)
+ relScope * (float)ZT_PATH_CONTRIB_SCOPE;
relQuality *= age_contrib;
// Arbitrary cutoffs
relQuality = relQuality > (1.00f / 100.0f) ? relQuality : 0.0f;
relQuality = relQuality < (99.0f / 100.0f) ? relQuality : 1.0f;
totalRelativeQuality += relQuality;
_paths[i].p->updateRelativeQuality(relQuality);
}
}
// Convert set of relative performances into an allocation set
for(uint16_t i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
if (_paths[i].p) {
_paths[i].p->updateComponentAllocationOfAggregateLink((unsigned char)((_paths[i].p->relativeQuality() / totalRelativeQuality) * 255));
}
}
}
int Peer::computeAggregateLinkPacketDelayVariance()
{
float pdv = 0.0;
for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
if (_paths[i].p) {
pdv += _paths[i].p->relativeQuality() * _paths[i].p->packetDelayVariance();
}
}
return (int)pdv;
}
int Peer::computeAggregateLinkMeanLatency()
{
int ml = 0;
int pathCount = 0;
for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
if (_paths[i].p) {
pathCount++;
ml += (int)(_paths[i].p->relativeQuality() * _paths[i].p->meanLatency());
}
}
return ml / pathCount;
}
int Peer::aggregateLinkPhysicalPathCount()
{
std::map<std::string, bool> ifnamemap;
int pathCount = 0;
int64_t now = RR->node->now();
for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
if (_paths[i].p && _paths[i].p->alive(now)) {
if (!ifnamemap[_paths[i].p->getName()]) {
ifnamemap[_paths[i].p->getName()] = true;
pathCount++;
}
}
}
return pathCount;
}
int Peer::aggregateLinkLogicalPathCount()
{
int pathCount = 0;
int64_t now = RR->node->now();
for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
if (_paths[i].p && _paths[i].p->alive(now)) {
pathCount++;
}
}
return pathCount;
}
SharedPtr<Path> Peer::getAppropriatePath(int64_t now, bool includeExpired)
{
Mutex::Lock _l(_paths_m);
unsigned int bestPath = ZT_MAX_PEER_NETWORK_PATHS;
/**
* Send traffic across the highest quality path only. This algorithm will still
* use the old path quality metric from protocol version 9.
*/
if (!_canUseMultipath) {
long bestPathQuality = 2147483647;
for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
if (_paths[i].p) {
if ((includeExpired)||((now - _paths[i].lr) < ZT_PEER_PATH_EXPIRATION)) {
const long q = _paths[i].p->quality(now) / _paths[i].priority;
if (q <= bestPathQuality) {
bestPathQuality = q;
bestPath = i;
}
}
} else break;
}
if (bestPath != ZT_MAX_PEER_NETWORK_PATHS) {
return _paths[bestPath].p;
}
return SharedPtr<Path>();
}
for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
if (_paths[i].p) {
_paths[i].p->processBackgroundPathMeasurements(now);
}
}
/**
* Randomly distribute traffic across all paths
*/
int numAlivePaths = 0;
int numStalePaths = 0;
if (RR->node->getMultipathMode() == ZT_MULTIPATH_RANDOM) {
int alivePaths[ZT_MAX_PEER_NETWORK_PATHS];
int stalePaths[ZT_MAX_PEER_NETWORK_PATHS];
memset(&alivePaths, -1, sizeof(alivePaths));
memset(&stalePaths, -1, sizeof(stalePaths));
for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
if (_paths[i].p) {
if (_paths[i].p->alive(now)) {
alivePaths[numAlivePaths] = i;
numAlivePaths++;
}
else {
stalePaths[numStalePaths] = i;
numStalePaths++;
}
}
}
unsigned int r = _freeRandomByte;
if (numAlivePaths > 0) {
int rf = r % numAlivePaths;
return _paths[alivePaths[rf]].p;
}
else if(numStalePaths > 0) {
// Resort to trying any non-expired path
int rf = r % numStalePaths;
return _paths[stalePaths[rf]].p;
}
}
/**
* Proportionally allocate traffic according to dynamic path quality measurements
*/
if (RR->node->getMultipathMode() == ZT_MULTIPATH_PROPORTIONALLY_BALANCED) {
if ((now - _lastAggregateAllocation) >= ZT_PATH_QUALITY_COMPUTE_INTERVAL) {
_lastAggregateAllocation = now;
computeAggregateProportionalAllocation(now);
}
// Randomly choose path according to their allocations
float rf = _freeRandomByte;
for(int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
if (_paths[i].p) {
if (rf < _paths[i].p->allocation()) {
bestPath = i;
_pathChoiceHist.push(bestPath); // Record which path we chose
break;
}
rf -= _paths[i].p->allocation();
}
}
if (bestPath < ZT_MAX_PEER_NETWORK_PATHS) {
return _paths[bestPath].p;
}
}
return SharedPtr<Path>();
}
char *Peer::interfaceListStr()
{
std::map<std::string, int> ifnamemap;
char tmp[32];
const int64_t now = RR->node->now();
char *ptr = _interfaceListStr;
bool imbalanced = false;
memset(_interfaceListStr, 0, sizeof(_interfaceListStr));
int alivePathCount = aggregateLinkLogicalPathCount();
for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
if (_paths[i].p && _paths[i].p->alive(now)) {
int ipv = _paths[i].p->address().isV4();
// If this is acting as an aggregate link, check allocations
float targetAllocation = 1.0f / (float)alivePathCount;
float currentAllocation = 1.0f;
if (alivePathCount > 1) {
currentAllocation = (float)_pathChoiceHist.countValue(i) / (float)_pathChoiceHist.count();
if (fabs(targetAllocation - currentAllocation) > ZT_PATH_IMBALANCE_THRESHOLD) {
imbalanced = true;
}
}
char *ipvStr = ipv ? (char*)"ipv4" : (char*)"ipv6";
sprintf(tmp, "(%s, %s, %.3f)", _paths[i].p->getName(), ipvStr, currentAllocation);
// Prevent duplicates
if(ifnamemap[_paths[i].p->getName()] != ipv) {
memcpy(ptr, tmp, strlen(tmp));
ptr += strlen(tmp);
*ptr = ' ';
ptr++;
ifnamemap[_paths[i].p->getName()] = ipv;
}
}
}
ptr--; // Overwrite trailing space
if (imbalanced) {
sprintf(tmp, ", is asymmetrical");
memcpy(ptr, tmp, sizeof(tmp));
} else {
*ptr = '\0';
}
return _interfaceListStr;
}
void Peer::introduce(void *const tPtr,const int64_t now,const SharedPtr<Peer> &other) const
{
unsigned int myBestV4ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
unsigned int myBestV6ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
long myBestV4QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
long myBestV6QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
unsigned int theirBestV4ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
unsigned int theirBestV6ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
long theirBestV4QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
long theirBestV6QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
for(int i=0;i<=ZT_INETADDRESS_MAX_SCOPE;++i) {
myBestV4ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
myBestV6ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
myBestV4QualityByScope[i] = 2147483647;
myBestV6QualityByScope[i] = 2147483647;
theirBestV4ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
theirBestV6ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
theirBestV4QualityByScope[i] = 2147483647;
theirBestV6QualityByScope[i] = 2147483647;
}
Mutex::Lock _l1(_paths_m);
for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
if (_paths[i].p) {
const long q = _paths[i].p->quality(now) / _paths[i].priority;
const unsigned int s = (unsigned int)_paths[i].p->ipScope();
switch(_paths[i].p->address().ss_family) {
case AF_INET:
if (q <= myBestV4QualityByScope[s]) {
myBestV4QualityByScope[s] = q;
myBestV4ByScope[s] = i;
}
break;
case AF_INET6:
if (q <= myBestV6QualityByScope[s]) {
myBestV6QualityByScope[s] = q;
myBestV6ByScope[s] = i;
}
break;
}
} else break;
}
Mutex::Lock _l2(other->_paths_m);
for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
if (other->_paths[i].p) {
const long q = other->_paths[i].p->quality(now) / other->_paths[i].priority;
const unsigned int s = (unsigned int)other->_paths[i].p->ipScope();
switch(other->_paths[i].p->address().ss_family) {
case AF_INET:
if (q <= theirBestV4QualityByScope[s]) {
theirBestV4QualityByScope[s] = q;
theirBestV4ByScope[s] = i;
}
break;
case AF_INET6:
if (q <= theirBestV6QualityByScope[s]) {
theirBestV6QualityByScope[s] = q;
theirBestV6ByScope[s] = i;
}
break;
}
} else break;
}
unsigned int mine = ZT_MAX_PEER_NETWORK_PATHS;
unsigned int theirs = ZT_MAX_PEER_NETWORK_PATHS;
for(int s=ZT_INETADDRESS_MAX_SCOPE;s>=0;--s) {
if ((myBestV6ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)&&(theirBestV6ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)) {
mine = myBestV6ByScope[s];
theirs = theirBestV6ByScope[s];
break;
}
if ((myBestV4ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)&&(theirBestV4ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)) {
mine = myBestV4ByScope[s];
theirs = theirBestV4ByScope[s];
break;
}
}
if (mine != ZT_MAX_PEER_NETWORK_PATHS) {
unsigned int alt = (unsigned int)RR->node->prng() & 1; // randomize which hint we send first for black magickal NAT-t reasons
const unsigned int completed = alt + 2;
while (alt != completed) {
if ((alt & 1) == 0) {
Packet outp(_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
outp.append((uint8_t)0);
other->_id.address().appendTo(outp);
outp.append((uint16_t)other->_paths[theirs].p->address().port());
if (other->_paths[theirs].p->address().ss_family == AF_INET6) {
outp.append((uint8_t)16);
outp.append(other->_paths[theirs].p->address().rawIpData(),16);
} else {
outp.append((uint8_t)4);
outp.append(other->_paths[theirs].p->address().rawIpData(),4);
}
outp.armor(_key,true);
_paths[mine].p->send(RR,tPtr,outp.data(),outp.size(),now);
} else {
Packet outp(other->_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
outp.append((uint8_t)0);
_id.address().appendTo(outp);
outp.append((uint16_t)_paths[mine].p->address().port());
if (_paths[mine].p->address().ss_family == AF_INET6) {
outp.append((uint8_t)16);
outp.append(_paths[mine].p->address().rawIpData(),16);
} else {
outp.append((uint8_t)4);
outp.append(_paths[mine].p->address().rawIpData(),4);
}
outp.armor(other->_key,true);
other->_paths[theirs].p->send(RR,tPtr,outp.data(),outp.size(),now);
}
++alt;
}
}
}
inline void Peer::processBackgroundPeerTasks(const int64_t now)
{
// Determine current multipath compatibility with other peer
if ((now - _lastMultipathCompatibilityCheck) >= ZT_PATH_QUALITY_COMPUTE_INTERVAL) {
//
// Cache number of available paths so that we can short-circuit multipath logic elsewhere
//
// We also take notice of duplicate paths (same IP only) because we may have
// recently received a direct path push from a peer and our list might contain
// a dead path which hasn't been fully recognized as such. In this case we
// don't want the duplicate to trigger execution of multipath code prematurely.
//
// This is done to support the behavior of auto multipath enable/disable
// without user intervention.
//
int currAlivePathCount = 0;
int duplicatePathsFound = 0;
for (unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
if (_paths[i].p) {
currAlivePathCount++;
for (unsigned int j=0;j<ZT_MAX_PEER_NETWORK_PATHS;++j) {
if (_paths[i].p && _paths[j].p && _paths[i].p->address().ipsEqual2(_paths[j].p->address()) && i != j) {
duplicatePathsFound+=1;
break;
}
}
}
}
_uniqueAlivePathCount = (currAlivePathCount - (duplicatePathsFound / 2));
_lastMultipathCompatibilityCheck = now;
_localMultipathSupported = ((RR->node->getMultipathMode() != ZT_MULTIPATH_NONE) && (ZT_PROTO_VERSION > 9));
_remoteMultipathSupported = _vProto > 9;
// If both peers support multipath and more than one path exist, we can use multipath logic
_canUseMultipath = _localMultipathSupported && _remoteMultipathSupported && (_uniqueAlivePathCount > 1);
}
}
void Peer::sendACK(void *tPtr,const SharedPtr<Path> &path,const int64_t localSocket,const InetAddress &atAddress,int64_t now)
{
Packet outp(_id.address(),RR->identity.address(),Packet::VERB_ACK);
uint32_t bytesToAck = path->bytesToAck();
outp.append<uint32_t>(bytesToAck);
if (atAddress) {
outp.armor(_key,false);
RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
} else {
RR->sw->send(tPtr,outp,false);
}
path->sentAck(now);
}
void Peer::sendQOS_MEASUREMENT(void *tPtr,const SharedPtr<Path> &path,const int64_t localSocket,const InetAddress &atAddress,int64_t now)
{
const int64_t _now = RR->node->now();
Packet outp(_id.address(),RR->identity.address(),Packet::VERB_QOS_MEASUREMENT);
char qosData[ZT_PATH_MAX_QOS_PACKET_SZ];
int16_t len = path->generateQoSPacket(_now,qosData);
outp.append(qosData,len);
if (atAddress) {
outp.armor(_key,false);
RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
} else {
RR->sw->send(tPtr,outp,false);
}
path->sentQoS(now);
}
void Peer::sendHELLO(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now)
{
Packet outp(_id.address(),RR->identity.address(),Packet::VERB_HELLO);
outp.append((unsigned char)ZT_PROTO_VERSION);
outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
outp.append(now);
RR->identity.serialize(outp,false);
atAddress.serialize(outp);
outp.append((uint64_t)RR->topology->planetWorldId());
outp.append((uint64_t)RR->topology->planetWorldTimestamp());
const unsigned int startCryptedPortionAt = outp.size();
std::vector<World> moons(RR->topology->moons());
std::vector<uint64_t> moonsWanted(RR->topology->moonsWanted());
outp.append((uint16_t)(moons.size() + moonsWanted.size()));
for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
outp.append((uint8_t)m->type());
outp.append((uint64_t)m->id());
outp.append((uint64_t)m->timestamp());
}
for(std::vector<uint64_t>::const_iterator m(moonsWanted.begin());m!=moonsWanted.end();++m) {
outp.append((uint8_t)World::TYPE_MOON);
outp.append(*m);
outp.append((uint64_t)0);
}
outp.cryptField(_key,startCryptedPortionAt,outp.size() - startCryptedPortionAt);
RR->node->expectReplyTo(outp.packetId());
if (atAddress) {
outp.armor(_key,false); // false == don't encrypt full payload, but add MAC
RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
} else {
RR->sw->send(tPtr,outp,false); // false == don't encrypt full payload, but add MAC
}
}
void Peer::attemptToContactAt(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now,bool sendFullHello)
{
if ( (!sendFullHello) && (_vProto >= 5) && (!((_vMajor == 1)&&(_vMinor == 1)&&(_vRevision == 0))) ) {
Packet outp(_id.address(),RR->identity.address(),Packet::VERB_ECHO);
RR->node->expectReplyTo(outp.packetId());
outp.armor(_key,true);
RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
} else {
sendHELLO(tPtr,localSocket,atAddress,now);
}
}
void Peer::tryMemorizedPath(void *tPtr,int64_t now)
{
if ((now - _lastTriedMemorizedPath) >= ZT_TRY_MEMORIZED_PATH_INTERVAL) {
_lastTriedMemorizedPath = now;
InetAddress mp;
if (RR->node->externalPathLookup(tPtr,_id.address(),-1,mp))
attemptToContactAt(tPtr,-1,mp,now,true);
}
}
unsigned int Peer::doPingAndKeepalive(void *tPtr,int64_t now)
{
unsigned int sent = 0;
Mutex::Lock _l(_paths_m);
const bool sendFullHello = ((now - _lastSentFullHello) >= ZT_PEER_PING_PERIOD);
_lastSentFullHello = now;
processBackgroundPeerTasks(now);
// Emit traces regarding aggregate link status
if (_canUseMultipath) {
int alivePathCount = aggregateLinkPhysicalPathCount();
if ((now - _lastAggregateStatsReport) > ZT_PATH_AGGREGATE_STATS_REPORT_INTERVAL) {
_lastAggregateStatsReport = now;
if (alivePathCount) {
RR->t->peerLinkAggregateStatistics(NULL,*this);
}
} if (alivePathCount < 2 && _linkIsRedundant) {
_linkIsRedundant = !_linkIsRedundant;
RR->t->peerLinkNoLongerRedundant(NULL,*this);
} if (alivePathCount > 1 && !_linkIsRedundant) {
_linkIsRedundant = !_linkIsRedundant;
RR->t->peerLinkNowRedundant(NULL,*this);
}
}
// Right now we only keep pinging links that have the maximum priority. The
// priority is used to track cluster redirections, meaning that when a cluster
// redirects us its redirect target links override all other links and we
// let those old links expire.
long maxPriority = 0;
for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
if (_paths[i].p)
maxPriority = std::max(_paths[i].priority,maxPriority);
else break;
}
unsigned int j = 0;
for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
if (_paths[i].p) {
// Clean expired and reduced priority paths
if ( ((now - _paths[i].lr) < ZT_PEER_PATH_EXPIRATION) && (_paths[i].priority == maxPriority) ) {
if ((sendFullHello)||(_paths[i].p->needsHeartbeat(now))) {
attemptToContactAt(tPtr,_paths[i].p->localSocket(),_paths[i].p->address(),now,sendFullHello);
_paths[i].p->sent(now);
sent |= (_paths[i].p->address().ss_family == AF_INET) ? 0x1 : 0x2;
}
if (i != j)
_paths[j] = _paths[i];
++j;
}
} else break;
}
if (canUseMultipath()) {
while(j < ZT_MAX_PEER_NETWORK_PATHS) {
_paths[j].lr = 0;
_paths[j].p.zero();
_paths[j].priority = 1;
++j;
}
}
return sent;
}
void Peer::clusterRedirect(void *tPtr,const SharedPtr<Path> &originatingPath,const InetAddress &remoteAddress,const int64_t now)
{
SharedPtr<Path> np(RR->topology->getPath(originatingPath->localSocket(),remoteAddress));
RR->t->peerRedirected(tPtr,0,*this,np);
attemptToContactAt(tPtr,originatingPath->localSocket(),remoteAddress,now,true);
{
Mutex::Lock _l(_paths_m);
// New priority is higher than the priority of the originating path (if known)
long newPriority = 1;
for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
if (_paths[i].p) {
if (_paths[i].p == originatingPath) {
newPriority = _paths[i].priority;
break;
}
} else break;
}
newPriority += 2;
// Erase any paths with lower priority than this one or that are duplicate
// IPs and add this path.
unsigned int j = 0;
for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
if (_paths[i].p) {
if ((_paths[i].priority >= newPriority)&&(!_paths[i].p->address().ipsEqual2(remoteAddress))) {
if (i != j)
_paths[j] = _paths[i];
++j;
}
}
}
if (j < ZT_MAX_PEER_NETWORK_PATHS) {
_paths[j].lr = now;
_paths[j].p = np;
_paths[j].priority = newPriority;
++j;
while (j < ZT_MAX_PEER_NETWORK_PATHS) {
_paths[j].lr = 0;
_paths[j].p.zero();
_paths[j].priority = 1;
++j;
}
}
}
}
void Peer::resetWithinScope(void *tPtr,InetAddress::IpScope scope,int inetAddressFamily,int64_t now)
{
Mutex::Lock _l(_paths_m);
for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
if (_paths[i].p) {
if ((_paths[i].p->address().ss_family == inetAddressFamily)&&(_paths[i].p->ipScope() == scope)) {
attemptToContactAt(tPtr,_paths[i].p->localSocket(),_paths[i].p->address(),now,false);
_paths[i].p->sent(now);
_paths[i].lr = 0; // path will not be used unless it speaks again
}
} else break;
}
}
} // namespace ZeroTier
| 32.223103 | 220 | 0.688117 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.