hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count 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 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 77k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count 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 7 1.05M | avg_line_length float64 1.21 653k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b6e5b96b3b9a80bf364e304c2adacf3ba49033fd | 554 | hpp | C++ | chratos/chratos_node/daemon.hpp | chratos-system/chratos | caf1b608a21ccc7b13726a64497036ab53f837b3 | [
"BSD-2-Clause"
] | 2 | 2018-09-10T16:28:16.000Z | 2020-02-13T17:44:43.000Z | chratos/chratos_node/daemon.hpp | chratos-system/chratos | caf1b608a21ccc7b13726a64497036ab53f837b3 | [
"BSD-2-Clause"
] | null | null | null | chratos/chratos_node/daemon.hpp | chratos-system/chratos | caf1b608a21ccc7b13726a64497036ab53f837b3 | [
"BSD-2-Clause"
] | 2 | 2018-08-27T13:00:56.000Z | 2018-10-16T21:54:13.000Z | #include <chratos/node/node.hpp>
#include <chratos/node/rpc.hpp>
namespace chratos_daemon
{
class daemon
{
public:
void run (boost::filesystem::path const &);
};
class daemon_config
{
public:
daemon_config (boost::filesystem::path const &);
bool deserialize_json (bool &, boost::property_tree::ptree &);
void serialize_json (boost::property_tree::ptree &);
bool upgrade_json (unsigned, boost::property_tree::ptree &);
bool rpc_enable;
chratos::rpc_config rpc;
chratos::node_config node;
bool opencl_enable;
chratos::opencl_config opencl;
};
}
| 22.16 | 63 | 0.749097 |
b6e6b03c6aec479a89fd0f21a6e2e0b311c44c75 | 20,841 | cpp | C++ | third_party/omr/compiler/optimizer/OMROptimization.cpp | xiacijie/omr-wala-linkage | a1aff7aef9ed131a45555451abde4615a04412c1 | [
"Apache-2.0"
] | null | null | null | third_party/omr/compiler/optimizer/OMROptimization.cpp | xiacijie/omr-wala-linkage | a1aff7aef9ed131a45555451abde4615a04412c1 | [
"Apache-2.0"
] | null | null | null | third_party/omr/compiler/optimizer/OMROptimization.cpp | xiacijie/omr-wala-linkage | a1aff7aef9ed131a45555451abde4615a04412c1 | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* Copyright (c) 2000, 2019 IBM Corp. and others
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at http://eclipse.org/legal/epl-2.0
* or the Apache License, Version 2.0 which accompanies this distribution
* and is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License, v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception [1] and GNU General Public
* License, version 2 with the OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] http://openjdk.java.net/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
*******************************************************************************/
#include "optimizer/OMROptimization.hpp"
#include <stddef.h>
#include <stdint.h>
#include "codegen/CodeGenerator.hpp"
#include "codegen/FrontEnd.hpp"
#include "compile/Compilation.hpp"
#include "cs2/allocator.h"
#include "env/IO.hpp"
#include "il/Block.hpp"
#include "il/DataTypes.hpp"
#include "il/ILOpCodes.hpp"
#include "il/ILOps.hpp"
#include "il/Node.hpp"
#include "il/Node_inlines.hpp"
#include "il/TreeTop.hpp"
#include "il/TreeTop_inlines.hpp"
#include "infra/Assert.hpp"
#include "infra/Cfg.hpp"
#include "infra/CfgEdge.hpp"
#include "optimizer/OptimizationManager.hpp"
#include "optimizer/Optimizations.hpp"
#include "optimizer/Optimization_inlines.hpp"
#include "optimizer/Optimizer.hpp"
#include "optimizer/Simplifier.hpp"
#include "optimizer/TransformUtil.hpp"
#define MAX_DEPTH_FOR_SMART_ANCHORING 3
// called once before perform is executed
void
OMR::Optimization::prePerform()
{
self()->prePerformOnBlocks();
}
// called once after perform is executed
void
OMR::Optimization::postPerform()
{
self()->postPerformOnBlocks();
}
TR::CodeGenerator *
OMR::Optimization::cg()
{
return self()->comp()->cg();
}
TR_FrontEnd *
OMR::Optimization::fe()
{
return self()->comp()->fe();
}
TR_Debug *
OMR::Optimization::getDebug()
{
return self()->comp()->getDebug();
}
TR::SymbolReferenceTable *
OMR::Optimization::getSymRefTab()
{
return self()->comp()->getSymRefTab();
}
TR_Memory *
OMR::Optimization::trMemory()
{
return self()->comp()->trMemory();
}
TR_StackMemory
OMR::Optimization::trStackMemory()
{
return self()->comp()->trStackMemory();
}
TR_HeapMemory
OMR::Optimization::trHeapMemory()
{
return self()->comp()->trHeapMemory();
}
TR_PersistentMemory *
OMR::Optimization::trPersistentMemory()
{
return self()->comp()->trPersistentMemory();
}
TR::Allocator
OMR::Optimization::allocator()
{
return self()->comp()->allocator();
}
OMR::Optimizations
OMR::Optimization::id()
{
return self()->manager()->id();
}
const char *
OMR::Optimization::name()
{
return self()->manager()->name();
}
void
OMR::Optimization::setTrace(bool trace)
{
self()->manager()->setTrace(trace);
}
bool
OMR::Optimization::getLastRun()
{
return self()->manager()->getLastRun();
}
void
OMR::Optimization::requestOpt(OMR::Optimizations optNum, bool value, TR::Block *block)
{
TR::OptimizationManager *manager = self()->optimizer()->getOptimization(optNum);
if (manager)
manager->setRequested(value, block);
}
// useful utility functions for opts
void
OMR::Optimization::requestDeadTreesCleanup(bool value, TR::Block *block)
{
self()->requestOpt(OMR::deadTreesElimination, value, block);
self()->requestOpt(OMR::trivialDeadTreeRemoval, value, block);
}
//---------------------------------------------------------------------
// Prepare to replace a node by changing its opcode.
// Use/def information and value number information must be given a
// chance to update themselves.
// The reference counts on all children must be decremented.
//
void
OMR::Optimization::prepareToReplaceNode(TR::Node * node)
{
// Value number information will be invalid after this optimization
//
self()->optimizer()->prepareForNodeRemoval(node);
node->removeAllChildren();
}
void
OMR::Optimization::prepareToReplaceNode(TR::Node * node, TR::ILOpCodes opcode)
{
TR::Node::recreate(node, opcode);
self()->prepareToReplaceNode(node);
}
/**
* Anchor all first level children of a given node, use this if you are to replace the node
* param node The node whose children is to be anchored
* param anchorTree The tree before which the anchor trees are to be inserted
*/
void
OMR::Optimization::anchorAllChildren(TR::Node * node, TR::TreeTop *anchorTree)
{
TR_ASSERT(anchorTree != NULL, "Can't anchor children to a NULL TR::TreeTop\n");
if (self()->trace())
traceMsg(self()->comp(), "%sanchoring children of node [" POINTER_PRINTF_FORMAT "]\n", self()->optDetailString(), node);
for (int i = 0; i <node->getNumChildren(); i++)
{
TR::TreeTop *tt = TR::TreeTop::create(self()->comp(), TR::Node::create(TR::treetop, 1, node->getChild(i)));
if (self()->trace())
traceMsg(self()->comp(), "TreeTop [" POINTER_PRINTF_FORMAT "] is created to anchor child [" POINTER_PRINTF_FORMAT "]\n", tt, node->getChild(i));
anchorTree->insertBefore(tt);
}
}
/** anchorChildren
* Only anchor order dependent children
* \param node Root node whose children is to be anchored
* \param anchorTree Tree before which anchor trees will be placed
*/
void
OMR::Optimization::anchorChildren(TR::Node *node, TR::TreeTop* anchorTree, uint32_t depth, bool hasCommonedAncestor, TR::Node* replacement)
{
TR::Node *prevChild = NULL;
// remaining path will be anchored to the original ancestor
if (node == replacement)
return;
if (!hasCommonedAncestor)
{
if (self()->trace())
traceMsg(self()->comp(),"set hasCommonedAncestor = true as %s %p has refCount %d > 1\n",
node->getOpCode().getName(),node,node->getReferenceCount());
hasCommonedAncestor = (node->getReferenceCount() > 1);
}
for (int j = node->getNumChildren()-1; j >= 0; --j)
{
TR::Node *child = node->getChild(j);
if (prevChild != child) // quite common for anchor to be called with two equal children
{
if (self()->nodeIsOrderDependent(child, depth, hasCommonedAncestor))
{
dumpOptDetails(self()->comp(), "%sanchor child %s [" POINTER_PRINTF_FORMAT "] at depth %d before %s [" POINTER_PRINTF_FORMAT "]\n",
self()->optDetailString(),child->getOpCode().getName(),child,depth,anchorTree->getNode()->getOpCode().getName(),anchorTree->getNode());
self()->generateAnchor(child, anchorTree);
}
else
{
self()->anchorChildren(child, anchorTree, depth + 1, hasCommonedAncestor, replacement); // skipped current child, so recurse its subtree
}
}
prevChild = child;
}
}
void
OMR::Optimization::generateAnchor(TR::Node *node, TR::TreeTop* anchorTree)
{
TR_ASSERT(anchorTree != NULL, "Can't anchor children to a NULL TR::TreeTop\n");
anchorTree->insertBefore(TR::TreeTop::create(self()->comp(),
TR::Node::create(TR::treetop, 1, node)));
}
void
OMR::Optimization::anchorNode(TR::Node *node, TR::TreeTop* anchorTree)
{
if (node->getOpCode().isLoadConst() && node->anchorConstChildren())
{
for (int32_t i=0; i < node->getNumChildren(); i++)
{
self()->generateAnchor(node->getChild(i), anchorTree);
}
}
else if (!node->getOpCode().isLoadConst())
{
self()->generateAnchor(node, anchorTree);
}
}
extern void createGuardSiteForRemovedGuard(TR::Compilation *comp, TR::Node* ifNode);
/**
* Folds a given if in IL. This method does NOT update CFG
* The callers should handle any updates to CFG or call
* conditionalToUnconditional
*/
bool
OMR::Optimization::removeOrconvertIfToGoto(TR::Node* &node, TR::Block* block, int takeBranch, TR::TreeTop* curTree, TR::TreeTop*& reachableTarget, TR::TreeTop*& unreachableTarget, const char* opt_details)
{
// Either change the conditional branch to an unconditional one or remove
// it altogether.
// In either case the CFG must be updated to reflect the change.
//
#ifdef J9_PROJECT_SPECIFIC
// doesn't matter taken or untaken, if it's a profiled guard we need to make sure the AOT relocation is created
createGuardSiteForRemovedGuard(self()->comp(), node);
#endif
if (takeBranch)
{
// Change the if into a goto
//
if (!performTransformation(self()->comp(), "%sChanging node [" POINTER_PRINTF_FORMAT "] %s into goto \n", opt_details, node, node->getOpCode().getName()))
return false;
self()->anchorChildren(node, curTree);
self()->prepareToReplaceNode(node);
TR::Node::recreate(node, TR::Goto);
reachableTarget = node->getBranchDestination();
unreachableTarget = block->getExit()->getNextTreeTop();
}
else
{
// Remove this node
//
if (!performTransformation(self()->comp(), "%sRemoving fall-through compare node [" POINTER_PRINTF_FORMAT "] %s\n", opt_details, node, node->getOpCode().getName()))
return false;
self()->anchorChildren(node, curTree);
reachableTarget = block->getExit()->getNextTreeTop();
unreachableTarget = node->getBranchDestination();
// Don't call remove node as we can't suppress the removal with performTransformation any more
self()->prepareToStopUsingNode(node, curTree);
node->removeAllChildren();
node = NULL;
}
return true;
}
/**
* Folds a given if by updating IL, CFG and Structures.
* If the removal of the edge caused the part of the CFG to become unreachable
* (orphaned), it will remove the subgraph.
*
* The callers should be aware that the block containing the if tree might be
* removed as well and handle such a scenario appropriately
*/
TR::CFGEdge*
OMR::Optimization::changeConditionalToUnconditional(TR::Node*& node, TR::Block* block, int takeBranch, TR::TreeTop* curTree, const char* opt_details)
{
TR::TreeTop *reachableTarget, *unreachableTarget;
if (!self()->removeOrconvertIfToGoto(node, block, takeBranch, curTree, reachableTarget, unreachableTarget, opt_details))
return NULL;
// Now "unreachableTarget" contains the branch destination that is NOT being
// taken.
//
TR::CFG * cfg = self()->comp()->getFlowGraph();
TR::CFGEdge* edge = NULL;
bool blocksWereRemoved = false;
if (cfg)
{
if (unreachableTarget != reachableTarget)
{
TR_ASSERT(unreachableTarget->getNode()->getOpCodeValue() == TR::BBStart, "Simplifier, expected BBStart");
TR_SuccessorIterator ei(block);
for (edge = ei.getFirst(); edge != NULL; edge = ei.getNext())
if (edge->getTo() == unreachableTarget->getNode()->getBlock())
{
blocksWereRemoved = cfg->removeEdge(edge);
break;
}
}
}
else if (takeBranch)
{
// There is no CFG so we may be dealing with extended basic blocks.
// Remove all non-fence treetops from here to the end of the block
//
for (TR::TreeTop * treeTop = block->getLastRealTreeTop(), * prevTreeTop;
treeTop->getNode() != node;
treeTop = prevTreeTop)
{
prevTreeTop = treeTop->getPrevRealTreeTop();
TR::TransformUtil::removeTree(self()->comp(), treeTop);
blocksWereRemoved = true;
}
}
return edge;
}
/**
* Prepare to stop using a node
*/
void
OMR::Optimization::prepareToStopUsingNode(TR::Node * node, TR::TreeTop* anchorTree, bool anchorChildrenNeeded)
{
if (anchorChildrenNeeded && node->getOpCodeValue() != TR::treetop)
{
self()->anchorChildren(node, anchorTree);
}
if (node->getReferenceCount() <= 1)
{
self()->optimizer()->prepareForNodeRemoval(node);
}
}
/**
* In the special case of replacing a node with its child then anchoring is not
* needed for the replacing child (as it and any children of its own will
* remain anchored)
*
* So if all of the node's other children are constants then no anchoring at
* all is required when replacing.
*/
TR::Node *
OMR::Optimization::replaceNodeWithChild(TR::Node *node, TR::Node *child, TR::TreeTop* anchorTree, TR::Block *block, bool correctBCDPrecision)
{
#ifdef J9_PROJECT_SPECIFIC
if (correctBCDPrecision &&
node->getType().isBCD() && child->getType().isBCD() &&
node->getDecimalPrecision() != child->getDecimalPrecision())
{
// The extra work for BCD (packed,zoned etc) nodes on a replace node is ensuring
// that the precision of the replacing node (child) matches the precision of the replaced
// node (node).
// If 'child' has a different precision than 'node' then the parent of 'node', if it is call
// for example, will pass too many or too few digits to its callee (even digits known to be zero
// are significant to calls to ensure the callee can demarshal the arguments correctly).
// If the 'child' truncates then there is the danger that this truncating side-effect will be lost unless
// a bcd modPrecOp is inserted.
// If correctBCDPrecision=false then the caller has guaranteed that there is no danger of a child truncation
// or widening causing any problems.
//
// This transformation is required for correctness so do not provide a performTransformation
int32_t childIndex = -1;
for (int32_t i=0; i < node->getNumChildren(); i++)
{
if (node->getChild(i) == child)
{
childIndex = i;
}
else if (node->getChild(i)->getOpCode().isLoadConst() && node->getChild(i)->anchorConstChildren())
{
for (int32_t j=0; j < node->getChild(i)->getNumChildren(); j++)
{
self()->anchorNode(node->getChild(i)->getChild(j), anchorTree);
}
}
else if (!node->getChild(i)->getOpCode().isLoadConst() &&
node->getChild(i)->getOpCodeValue() != TR::loadaddr)
{
self()->anchorNode(node->getChild(i), anchorTree);
}
}
if (childIndex == -1)
{
TR_ASSERT(false,"could not find child under node in replaceBCDNodeWithChild\n");
return node;
}
if (node->getReferenceCount() > 1)
{
TR::Node *newNode = TR::Node::create(TR::ILOpCode::modifyPrecisionOpCode(child->getDataType()), 1, child);
newNode->setDecimalPrecision(node->getDecimalPrecision());
dumpOptDetails(self()->comp(), "%sPrecision mismatch when replacing parent %s [" POINTER_PRINTF_FORMAT "] with child %s [" POINTER_PRINTF_FORMAT "] so create new parent %s [" POINTER_PRINTF_FORMAT "]\n",
self()->optDetailString(),node->getOpCode().getName(),node,child->getOpCode().getName(),child,newNode->getOpCode().getName(),newNode);
return self()->replaceNode(node, newNode, anchorTree, false); // needAnchor=false
}
else
{
dumpOptDetails(self()->comp(), "%sPrecision mismatch when replacing parent %s [" POINTER_PRINTF_FORMAT "] with child %s [" POINTER_PRINTF_FORMAT "] so change parent op to ",
self()->optDetailString(),node->getOpCode().getName(),node,child->getOpCode().getName(),child);
TR_ASSERT(node->getReferenceCount() == 1,"node %p refCount should be 1 and not %d\n",node,node->getReferenceCount());
child->incReferenceCount();
// zd2pd <- node - change to zdModifyPrecision (must use child type as modPrec is being applied to the child)
// zdX <- child
//
self()->prepareToReplaceNode(node, TR::ILOpCode::modifyPrecisionOpCode(child->getDataType()));
node->setNumChildren(1);
node->setChild(0, child);
dumpOptDetails(self()->comp(), "%s\n",node->getOpCode().getName());
if (self()->id() == OMR::treeSimplification)
return ((TR::Simplifier *) self())->simplify(node, block);
else
return node;
}
}
else
#endif
{
TR_ASSERT(node->hasChild(child),"node %p is not a child of node %p\n",child,node);
bool needAnchor = false;
for (int32_t i = 0; i < node->getNumChildren(); i++)
{
// skip anchoring for 1) the input 'child' 2) constants with no children 3) loadaddrs
if (node->getChild(i) != child &&
(!node->getChild(i)->getOpCode().isLoadConst() || node->getChild(i)->anchorConstChildren()) &&
node->getChild(i)->getOpCodeValue() != TR::loadaddr)
{
needAnchor = true;
break;
}
}
return self()->replaceNode(node, child, anchorTree, needAnchor);
}
}
/**
* Common routine to replace the node by another
*
* This routine replaces one use of this node by adjusting reference counts and
* returning the replacing node. It is assumed that the caller will replace the
* reference to the original node with the replacing node. The visit count on
* the original node is reset so that it is visited again on the next reference.
*/
TR::Node *
OMR::Optimization::replaceNode(TR::Node * node, TR::Node *other, TR::TreeTop *anchorTree, bool anchorChildren)
{
if (!performTransformation(self()->comp(), "%sReplace node [" POINTER_PRINTF_FORMAT "] %s by [" POINTER_PRINTF_FORMAT "] %s\n", self()->optDetailString(), node, node->getOpCode().getName(), other, other->getOpCode().getName()))
{
if(other->getReferenceCount() == 0)
{
// Because the replacement node will not be used and it does not currently exist in the compilation unit,
// it should be destroyed.
other->removeAllChildren();
}
return node;
}
// Increment the reference count on the replacing node, since it will be
// getting a new reference.
//
other->incReferenceCount();
// This must be done AFTER
// incrementing the count on the replacing node in case the replacing node is
// a child of the original node. Otherwise we can end up deleting
// use/def info from the child (in prepareForNodeRemoval)
// Adjust usedef and value number information if this node is not going to
// be used any more.
//
self()->prepareToStopUsingNode(node, anchorTree, anchorChildren);
// Decrement the reference count on the original node. This must be done AFTER
// incrementing the count on the replacing node in case the replacing node is
// a child of the original node. In this case we don't want the count on the
// replacing node to go to zero.
//
node->recursivelyDecReferenceCount();
// If the original node still has other uses make sure it is re-visited
// so the other references to it can be fixed up too.
//
if (node->getReferenceCount() > 0)
node->setVisitCount(0);
return other;
}
/**
* Common routine to remove the node from the tree
*/
void
OMR::Optimization::removeNode(TR::Node * node, TR::TreeTop *anchorTree)
{
// Reduce the reference counts of all children.
//
if (performTransformation(self()->comp(), "%sRemoving redundant node [" POINTER_PRINTF_FORMAT "] %s\n", self()->optDetailString(), node, node->getOpCode().getName()))
{
self()->prepareToStopUsingNode(node, anchorTree);
node->removeAllChildren();
}
}
bool
OMR::Optimization::nodeIsOrderDependent(TR::Node *node, uint32_t depth, bool hasCommonedAncestor)
{
// While it may be tempting to use futureUseCount here, futureUseCount isn't well maintained in simplifier
// and so shouldn't be used for functional items such as to anchor or not anchor a node. FutureUseCount
// should only be used as a heuristic for optimizations.
bool constNeedsAnchor = node->getOpCode().isLoadConst() && node->anchorConstChildren();
return ((node->getOpCode().isLoad() && node->getOpCode().hasSymbolReference() &&
((node->getReferenceCount() > 1) || hasCommonedAncestor)) ||
((!node->getOpCode().isLoadConst() || constNeedsAnchor) && depth >= MAX_DEPTH_FOR_SMART_ANCHORING));
}
| 36.057093 | 230 | 0.64685 |
b6e747e98efbae07098d7fecd8734f2aacbde5f4 | 605 | cpp | C++ | Ball.cpp | f-prime/SFMLPong | 281e3a76d1d8f80a86f890ade78d789f2af09b0a | [
"WTFPL"
] | 1 | 2018-08-29T16:45:29.000Z | 2018-08-29T16:45:29.000Z | Ball.cpp | f-prime/SFMLPong | 281e3a76d1d8f80a86f890ade78d789f2af09b0a | [
"WTFPL"
] | null | null | null | Ball.cpp | f-prime/SFMLPong | 281e3a76d1d8f80a86f890ade78d789f2af09b0a | [
"WTFPL"
] | null | null | null | #include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include "Ball.hpp"
Ball::Ball(sf::RenderWindow& window):window(window) {
this->ball = sf::RectangleShape(sf::Vector2f(5, 5));
this->direction = 1;
this->speed = 5;
this->angle = 0;
this->setPos(400, 300);
}
void Ball::setPos(int x, int y) {
this->pos_x = x;
this->pos_y = y;
this->ball.setPosition(x, y);
}
void Ball::setAngle(float angle) {
this->angle = angle;
}
void Ball::setDirection(int direction) {
}
void Ball::setSpeed(int speed) {
}
void Ball::render() {
this->window.draw(this->ball);
}
| 16.805556 | 56 | 0.62314 |
b6e7c2d8d635b8d2618c1ab12877d03218257eeb | 1,077 | cpp | C++ | CCTV/CCTV/CCTVSet.cpp | DNATUNA/opencvProject | 6afd9b11f98c86b8e41d3bf44115f2d9bc62b970 | [
"BSD-3-Clause"
] | 1 | 2019-01-24T04:37:41.000Z | 2019-01-24T04:37:41.000Z | CCTV/CCTV/CCTVSet.cpp | DNATUNA/2018opencvProject | 6afd9b11f98c86b8e41d3bf44115f2d9bc62b970 | [
"BSD-3-Clause"
] | null | null | null | CCTV/CCTV/CCTVSet.cpp | DNATUNA/2018opencvProject | 6afd9b11f98c86b8e41d3bf44115f2d9bc62b970 | [
"BSD-3-Clause"
] | null | null | null | #include<opencv\cv.h>
#include<opencv\highgui.h>
#include<cstdio>
int main(){
CvCapture* capture = cvCaptureFromCAM(0);
if (!capture){
printf("the video file was not found.");
return 0;
}
int width = (int)cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
int height = (int)cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
CvSize frameSize = cvSize(width, height);
IplImage* grayImage = cvCreateImage(frameSize, IPL_DEPTH_8U, 1);
IplImage* sumImage = cvCreateImage(frameSize, IPL_DEPTH_32F, 1);
cvZero(sumImage);
IplImage* frame = NULL;
int nFrameCount = 0;
for (;;)
{
frame = cvQueryFrame(capture);
if (!frame) break;
cvCvtColor(frame, grayImage, CV_BGR2GRAY);
cvAcc(grayImage, sumImage, NULL);
cvShowImage("grayImage", grayImage);
char chKey = cvWaitKey(50);
if (chKey == 27)
break;
nFrameCount++;
}
cvScale(sumImage, sumImage, 1.0 / nFrameCount);
cvSaveImage("CctvBaseFile.jpg", sumImage);
cvDestroyAllWindows();
cvReleaseImage(&sumImage);
cvReleaseImage(&grayImage);
cvReleaseCapture(&capture);
return 0;
} | 22.914894 | 75 | 0.723305 |
b6eb39ef45bc5c2f56339e4c9849eee6c477b6e3 | 1,711 | cxx | C++ | src/converter/fix_helper.cxx | abdelkaderamar/fix2xml | fa781b747a8e40ed4c2d3dee8294fb51654f7428 | [
"MIT"
] | 1 | 2019-09-26T12:08:19.000Z | 2019-09-26T12:08:19.000Z | src/converter/fix_helper.cxx | abdelkaderamar/fix2xml | fa781b747a8e40ed4c2d3dee8294fb51654f7428 | [
"MIT"
] | null | null | null | src/converter/fix_helper.cxx | abdelkaderamar/fix2xml | fa781b747a8e40ed4c2d3dee8294fb51654f7428 | [
"MIT"
] | 1 | 2020-12-11T04:11:44.000Z | 2020-12-11T04:11:44.000Z | #include "fix_helper.hxx"
#include <quickfix/FixFieldNumbers.h>
#include <algorithm>
#include <functional>
#include <vector>
namespace fix2xml {
using namespace std;
//-----------------------------------------------------------------------------
void msg_to_list(const FIX::Message &fix_msg,
const FIX::DataDictionary &fix_dict,
multiset<string> &fields_set, list<multiset<string>> &ls) {
ls.push_back(fieldmap_to_list(fix_msg.getHeader(), fix_dict, ls));
fields_set = fieldmap_to_list(fix_msg, fix_dict, ls);
}
//-----------------------------------------------------------------------------
multiset<string> fieldmap_to_list(const FIX::FieldMap &fix_msg,
const FIX::DataDictionary &fix_dict,
list<multiset<string>> &ls) {
// Insert all the fields that are not NumInGroup in the multiset fields_set
multiset<string> fields_set;
for (auto it = fix_msg.begin(); it != fix_msg.end(); ++it) {
if (it->getField() == FIX::FIELD::MsgType)
continue;
FIX::TYPE::Type fix_type;
if (fix_dict.getFieldType(it->getField(), fix_type) &&
(fix_type == FIX::TYPE::NumInGroup))
continue;
fields_set.insert(it->getString());
}
// For each group insert its fields (as multiset) in the list ls
for (auto it = fix_msg.g_begin(); it != fix_msg.g_end(); ++it) {
const vector<FIX::FieldMap *> &groups = it->second;
for (size_t i = 0; i < groups.size(); ++i) {
ls.push_back(fieldmap_to_list(*groups[i], fix_dict, ls));
}
}
return fields_set;
}
//-----------------------------------------------------------------------------
} // end namespace fix2xml
| 34.22 | 79 | 0.548802 |
b6f2464ac1f220f4d92948ee29510bccaf768fc8 | 2,030 | cpp | C++ | DS/DS/graph/bellman_ford.cpp | puneet222/Data-Structures | c5c460739c7423cce53685c5557c97c70ca1d171 | [
"Apache-2.0"
] | null | null | null | DS/DS/graph/bellman_ford.cpp | puneet222/Data-Structures | c5c460739c7423cce53685c5557c97c70ca1d171 | [
"Apache-2.0"
] | null | null | null | DS/DS/graph/bellman_ford.cpp | puneet222/Data-Structures | c5c460739c7423cce53685c5557c97c70ca1d171 | [
"Apache-2.0"
] | null | null | null | #include<iostream>
#include<stdio.h>
#include<queue>
#include<malloc.h>
#include<limits.h>
using namespace std ;
struct graph{
int v ;
int e ;
int **wgh ;
} ;
struct graph *weightMatrix(int vertices , int edges)
{
struct graph *g = new graph ;
g -> v = vertices ;
g -> e = edges ;
g -> wgh = (int **)malloc(sizeof(int *)*(g -> v)) ;
for (int i = 0; i < g -> v; ++i)
{
g -> wgh[i] = (int *)malloc(sizeof(int)*(g -> v)) ;
}
int u , v ;
for(u = 0 ; u < g -> v ; u++)
{
for(v = 0 ; v < g -> v ; v++)
{
g -> wgh[u][v] = 0 ;
}
}
for (int i = 0; i < g -> e; ++i)
{
printf("Enter the vertices u and v such that there is an edge u -> v is there : ");
cin >> u >> v ;
int w ;
cout << "\nEnter the weight of the edge : " ;
cin >> w ;
g -> wgh[u][v] = w ;
}
return g ;
}
void printGraph(struct graph *g)
{
int u , v ;
for(u = 0 ; u < g -> v ; u++)
{
for(v = 0 ; v < g -> v ; v++)
{
printf(" %d ", g -> wgh[u][v]);
}
printf("\n");
}
}
void shortestpath(struct graph *g , int * distance , int *path , int s)
{
queue <int> Q ;
int qarr[g -> v] ;
for (int i = 0; i < g -> v; ++i)
{
distance[i] = INT_MAX ;
qarr[i] = 0 ;
}
distance[s] = 0 ;
Q.push(s) ;
qarr[s] = 1 ;
while(!Q.empty())
{
int v = Q.front() ;
Q.pop() ;
qarr[v] = 0 ;
for (int i = 0; i < g -> v; ++i)
{
if(g -> wgh[v][i])
{
int dnew = distance[v] + g -> wgh[v][i] ;
if(distance[i] > dnew)
{
distance[i] = dnew ;
path[i] = v ;
if(qarr[i] == 0)
{
Q.push(i) ;
qarr[i] == 1 ;
}
}
}
}
}
}
int main()
{
int v , e ;
printf("Enter number of vertices and edges in the graph : ");
scanf("%d%d" , &v , &e) ;
struct graph *g = weightMatrix(v , e) ;
printGraph(g);
int distance[g -> v] ;
int path[g -> v] ;
int s ;
printf("Enter the source from where you want to find the shortest path to all other nodes : ");
cin >> s ;
shortestpath(g , distance , path , s) ;
for (int i = 0; i < g -> v; ++i)
{
printf(" %d ", distance[i]);
}
} | 17.964602 | 96 | 0.484236 |
b6f37f224de07b2b6fbcd897a1d9b8df7744e108 | 151 | cpp | C++ | serialRW/main.cpp | codinggg/tools | 196043db7a46cda4d35547eb85a2449d52528c7e | [
"MIT"
] | null | null | null | serialRW/main.cpp | codinggg/tools | 196043db7a46cda4d35547eb85a2449d52528c7e | [
"MIT"
] | null | null | null | serialRW/main.cpp | codinggg/tools | 196043db7a46cda4d35547eb85a2449d52528c7e | [
"MIT"
] | null | null | null | #include <QApplication>
#include "serial.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
serial se;
return a.exec();
}
| 13.727273 | 32 | 0.629139 |
b6f669662fc07113ef4dc65531cf932b8353b1f9 | 2,127 | cpp | C++ | 1. Деревья поиска/0.2. Удалить из дерева #3535/[OK]169443.cpp | godnoTA/acm.bsu.by | 3e1cf1c545c691de82b5e1d2e0768b41ea581734 | [
"Unlicense"
] | 19 | 2018-05-19T16:37:14.000Z | 2022-03-23T20:13:43.000Z | 1. Деревья поиска/0.2. Удалить из дерева #3535/[OK]169443.cpp | godnoTA/acm.bsu.by | 3e1cf1c545c691de82b5e1d2e0768b41ea581734 | [
"Unlicense"
] | 6 | 2020-05-07T21:06:48.000Z | 2020-06-05T17:52:57.000Z | 1. Деревья поиска/0.2. Удалить из дерева #3535/[OK]169443.cpp | godnoTA/acm.bsu.by | 3e1cf1c545c691de82b5e1d2e0768b41ea581734 | [
"Unlicense"
] | 31 | 2019-03-01T21:41:38.000Z | 2022-03-27T17:56:39.000Z | #include<iostream>
#include<fstream>
using namespace std;
//Входной и выходной файлы
ifstream in("input.txt");
ofstream out("output.txt");
struct node{
int key;
node *left;
node *right;
};
void push(int a,node *&t)
{
if (t == NULL)
{
t = new node; //Выделяем память
t -> key = a; //Кладем в выделенное место аргумент a
t -> left = t -> right = NULL; //Очищаем память для следующего роста
}
if ((a > t->key)&&(t->right == NULL))
{
t->right = new node();
t->right->key = a;
t->right->left = NULL;
t->right->right = NULL;
}
else if ((a > t->key)&&(t->right != NULL))
{
push(a, t->right);
}
if ((a < t->key)&&(t->left == NULL))
{
t->left = new node();
t->left->key = a;
t->left->left = NULL;
t->left->right = NULL;
}
else if ((a < t->key)&&(t->left != NULL))
{
push(a, t->left);
}
}
node*& findmin(node *& min) {
if (min->left == NULL)
return min;
return findmin(min->left);
}
node*& del(int val,node *&Tree_) {
if (Tree_ == NULL) {
return Tree_;
}
if (val < Tree_->key)
Tree_->left = del(val,Tree_->left);
else {
if (val > Tree_->key) {
Tree_->right = del(val, Tree_->right);
}
else {
if (Tree_->left != NULL && Tree_->right != NULL) {
Tree_->key = findmin(Tree_->right)->key;
Tree_->right = del(Tree_->key, Tree_->right);
}
else {
if (Tree_->left != NULL)
Tree_ = Tree_->left;
else
Tree_ = Tree_->right;
}
}
}
return Tree_;
}
void output (node *&tree)
{
if (tree==NULL)
return; //Если дерево пустое, то отображать нечего, выходим
else //Иначе
{
out<<tree->key<<endl; //И записываем элемент
output(tree->left);//С помощью рекурсивного посещаем левое поддерево
//for (int i=0;i<a;++i)
//a--;
}
output(tree->right); //С помощью рекурсии посещаем правое поддерево
}
int main()
{
setlocale(LC_ALL, ".1251");
node* tree = NULL;
int val;
in>>val;
while (!in.eof()){
int l;
in >> l;
push(l, tree);
}
del(val,tree);
output(tree);
return 0;
}
| 19.694444 | 77 | 0.535966 |
b6f7f2f06130d095c5b2a916d993ecd6bd4f62f6 | 833 | cpp | C++ | 机试/动态规划/leetcode123.cpp | codehuanglei/- | 933a55b5c5a49163f12e0c39b4edfa9c4f01678f | [
"MIT"
] | null | null | null | 机试/动态规划/leetcode123.cpp | codehuanglei/- | 933a55b5c5a49163f12e0c39b4edfa9c4f01678f | [
"MIT"
] | null | null | null | 机试/动态规划/leetcode123.cpp | codehuanglei/- | 933a55b5c5a49163f12e0c39b4edfa9c4f01678f | [
"MIT"
] | null | null | null | class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size() == 0){
return 0;
}
int len = prices.size();
vector<vector<int>> dp(len, vector<int>(5));
dp[0][0] = 0;
dp[0][1] = -prices[0];
dp[0][2] = 0;
dp[0][3] = -prices[0];
dp[0][4] = 0;
for(int i = 1; i < prices.size(); i++){
dp[i][0] = dp[i-1][0]; //初始状态
dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i]); //第一次买入
dp[i][2] = max(dp[i-1][2], dp[i-1][1] + prices[i]); //第一次卖出
dp[i][3] = max(dp[i-1][3], dp[i-1][2] - prices[i]);//第二次买入
dp[i][4] = max(dp[i-1][4], dp[i-1][3] + prices[i]);//第二次卖出
}
return max(max( max(dp[len-1][0], dp[len-1][1]), max(dp[len-1][2], dp[len-1][3]) ), dp[len-1][4]);
}
}; | 36.217391 | 105 | 0.421369 |
b6f8e89b7854ae190ce4fb84d665ae55b410da1d | 21,275 | cc | C++ | tests/unit/speech_recog_test.cc | CPqD/asr-sdk-cpp | ca1d0a81a250f54c272b6bc39d2a1c5a1c9f58a1 | [
"Apache-2.0"
] | 4 | 2017-10-12T20:09:31.000Z | 2021-05-24T13:46:26.000Z | tests/unit/speech_recog_test.cc | CPqD/asr-sdk-cpp | ca1d0a81a250f54c272b6bc39d2a1c5a1c9f58a1 | [
"Apache-2.0"
] | null | null | null | tests/unit/speech_recog_test.cc | CPqD/asr-sdk-cpp | ca1d0a81a250f54c272b6bc39d2a1c5a1c9f58a1 | [
"Apache-2.0"
] | 4 | 2017-10-04T14:30:11.000Z | 2022-02-25T10:13:06.000Z | /*****************************************************************************
* Copyright 2017 CPqD. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include <gtest/gtest.h>
#include "test_config.h"
#include <chrono>
#include <string>
#include <thread>
#include <cpqd/asr-client/file_audio_source.h>
#include <cpqd/asr-client/buffer_audio_source.h>
#include <cpqd/asr-client/recognition_config.h>
#include <cpqd/asr-client/recognition_exception.h>
#include <cpqd/asr-client/speech_recog.h>
#ifndef NO_INPUT_TIMEOUT_MS
#define NO_INPUT_TIMEOUT_MS 1000
#endif
/*
* ok: basicGrammar
* ok: basicGrammarClearVoice
* ok: recognizeNoSpeech (NO_MATCH)
* ok: recognizeNoInput
* ok: recognizeBufferAudioSource
* ok: recognizeBufferBlockRead
* ok: recognizeMaxWaitSeconds
* ok: closeWhileRecognize
* ok: closeWithoutRecognize
* ok: cancelWhileRecognize
* ok: cancelNoRecognize
* ok: waitRecognitionResult
* ok: waitRecognitionResultDuplicateTest
* ok: duplicateRecognize
* ok: multipleRecognize
* ok-ish: connectOnRecognize (doesn't test connection per se, only the object status)
* ok-ish: multipleAutoClose (doesn't test connection per se, only the object status)
* ok: sessionTimeout
*/
/* Most common recognizer configuration */
std::unique_ptr<SpeechRecognizer> defaultBuild(){
std::unique_ptr<RecognitionConfig> config =
RecognitionConfig::Builder().build();
return SpeechRecognizer::Builder()
.serverUrl(test::server_url)
.recogConfig(std::move(config))
.credentials(test::username, test::password)
.maxWaitSeconds(30)
.build();
}
/*Class for simulating noInputTimeout*/
class DelayedFileAudioSource: public FileAudioSource {
public:
DelayedFileAudioSource(const std::string& file_name,
AudioFormat fmt = AudioFormat())
: FileAudioSource(file_name, fmt)
{}
int read(std::vector<char>& buffer) {
std::this_thread::sleep_for(
std::chrono::milliseconds(NO_INPUT_TIMEOUT_MS + 10)
);
return FileAudioSource::read(buffer);
}
};
TEST(RecognizerTest, basicGrammar) {
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::audio_phone_8k);
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder().addFromURI(test::grammar_phone_uri).build();
std::unique_ptr<SpeechRecognizer> asr = defaultBuild();
asr->recognize(audio, std::move(lm));
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
asr->close();
ASSERT_LT(0, result.size());
bool at_least_one_high_confidence = false;
for (RecognitionResult& res : result) {
if(res.getCode() != RecognitionResult::Code::RECOGNIZED) continue;
at_least_one_high_confidence = true;
for (RecognitionResult::Alternative& alt : res.getAlternatives()) {
std::cout << "alt.getConfidence(): " << alt.getConfidence() << std::endl;
ASSERT_GE(alt.getConfidence(), 90);
}
}
ASSERT_EQ(true, at_least_one_high_confidence) << "No results with high confidence!";
}
TEST(NoGrammarTest, basicGrammarClearVoice) {
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::previsao_tempo_8k);
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder().addFromURI(test::slm_uri).build();
std::unique_ptr<SpeechRecognizer> asr = defaultBuild();
asr->recognize(audio, std::move(lm));
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
asr->close();
ASSERT_LT(0, result.size());
bool at_least_one_high_confidence = false;
for (RecognitionResult& res : result) {
if(res.getCode() != RecognitionResult::Code::RECOGNIZED) continue;
at_least_one_high_confidence = true;
for (RecognitionResult::Alternative& alt : res.getAlternatives()) {
std::cout << "alt.getConfidence(): " << alt.getConfidence() << std::endl;
ASSERT_GE(alt.getConfidence(), 90);
}
}
ASSERT_EQ(true, at_least_one_high_confidence) << "No results with high confidence!";
}
TEST(NoGrammarTest, recognizeNoSpeech) {
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::audio_silence_8k);
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder().addFromURI(test::slm_uri).build();
std::unique_ptr<SpeechRecognizer> asr = defaultBuild();
asr->recognize(audio, std::move(lm));
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
EXPECT_EQ(RecognitionResult::Code::NO_SPEECH, result[0].getCode());
asr->close();
}
TEST(RecognizerTest, recognizeNoInput) {
std::unique_ptr<RecognitionConfig> config =
RecognitionConfig::Builder()
.noInputTimeoutEnabled(true)
.noInputTimeoutMilliseconds(NO_INPUT_TIMEOUT_MS)
.startInputTimers(true)
.build();
// Making a buffer with delayed read to simulate no input timeout
std::shared_ptr<DelayedFileAudioSource> audio =
std::make_shared<DelayedFileAudioSource>(test::audio_silence_8k);
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder().addFromURI(test::grammar_phone_uri).build();
std::unique_ptr<SpeechRecognizer> asr = SpeechRecognizer::Builder()
.serverUrl(test::server_url)
.recogConfig(std::move(config))
.credentials(test::username,
test::password)
.maxWaitSeconds(30)
.build();
asr->recognize(audio, std::move(lm));
std::vector<RecognitionResult> res = asr->waitRecognitionResult();
EXPECT_EQ(RecognitionResult::Code::NO_INPUT_TIMEOUT, res[0].getCode());
asr->close();
}
TEST(RecognizerTest, recognizeBufferAudioSource) {
std::unique_ptr<RecognitionConfig> config =
RecognitionConfig::Builder()
.noInputTimeoutEnabled(false)
.build();
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder().addFromURI(test::slm_uri).build();
std::unique_ptr<SpeechRecognizer> asr = SpeechRecognizer::Builder()
.serverUrl(test::server_url)
.recogConfig(std::move(config))
.credentials(test::username,
test::password)
.maxWaitSeconds(30)
.build();
static long buffer_size = 200000; // Longer than audio_phone_8k
std::ifstream ifs;
ifs.open(test::audio_phone_8k_raw);
// Reading file content
std::vector<char> audio_content;
if (!ifs.eof() && !ifs.fail())
{
ifs.seekg(0, std::ios_base::end);
std::streampos fileSize = ifs.tellg();
audio_content.resize(fileSize);
ifs.seekg(0, std::ios_base::beg);
ifs.read(&audio_content[0], fileSize);
}
// Assert that file content is smaller than buffer size
ASSERT_LT(audio_content.size(), buffer_size);
// Writing content smaller than buffer_size
AudioFormat fmt;
fmt.fileFormat = AudioFileFormat::RAW;
fmt.bits_per_sample_ = 16;
std::shared_ptr<BufferAudioSource> audio =
std::make_shared<BufferAudioSource>(fmt, buffer_size);
asr->recognize(audio, std::move(lm));
audio->write(audio_content);
audio->finish();
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
asr->close();
// Assert that there's at least one valid result
ASSERT_GT(result.size(), 0);
}
TEST(RecognizerTest, recognizeBufferBlockRead) {
std::unique_ptr<RecognitionConfig> config =
RecognitionConfig::Builder()
.noInputTimeoutEnabled(false)
.build();
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder().addFromURI(test::slm_uri).build();
std::unique_ptr<SpeechRecognizer> asr = SpeechRecognizer::Builder()
.serverUrl(test::server_url)
.recogConfig(std::move(config))
.credentials(test::username,
test::password)
.maxWaitSeconds(30)
.build();
char buffer[4000]; // Shorter than previsao-tempo-8k.raw
// Audio instance
AudioFormat fmt;
fmt.fileFormat = AudioFileFormat::RAW;
fmt.bits_per_sample_ = 16;
std::shared_ptr<BufferAudioSource> audio =
std::make_shared<BufferAudioSource>(fmt, 4000);
asr->recognize(audio, std::move(lm));
// Writing and blocking audio. For each 2000 samples (250ms), wait 300ms
std::ifstream ifs;
ifs.open(test::previsao_tempo_8k_raw);
ifs.read(buffer, 4000);
do {
audio->write(buffer, 4000);
std::this_thread::sleep_for(std::chrono::milliseconds(300));
ifs.read(buffer, 4000);
} while (ifs.gcount() != 0);
audio->finish();
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
asr->close();
// Assert that there's at least one valid result
ASSERT_GT(result.size(), 0);
}
TEST(RecognizerTest, recognizeMaxWaitSeconds) {
std::unique_ptr<RecognitionConfig> config =
RecognitionConfig::Builder().build();
std::shared_ptr<AudioSource> audio =
std::make_shared<DelayedFileAudioSource>(test::previsao_tempo_8k);
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder().addFromURI(test::slm_uri).build();
std::unique_ptr<SpeechRecognizer> asr = SpeechRecognizer::Builder()
.serverUrl(test::server_url)
.recogConfig(std::move(config))
.credentials(test::username,
test::password)
.maxWaitSeconds(1)
.build();
asr->recognize(audio, std::move(lm));
try {
asr->waitRecognitionResult();
FAIL() << "Expected RecognitionException";
} catch (RecognitionException& err) {
EXPECT_EQ(err.getCode(), RecognitionError::Code::FAILURE);
} catch(...) {
FAIL() << "Expected RecognitionException";
}
}
TEST(RecognizerTest, closeWhileRecognize) {
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::previsao_tempo_8k);
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder().addFromURI(test::slm_uri).build();
std::unique_ptr<SpeechRecognizer> asr = defaultBuild();
asr->recognize(audio, std::move(lm));
std::this_thread::sleep_for(std::chrono::milliseconds(100));
asr->close();
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
ASSERT_EQ(result.size(), 0);
}
TEST(RecognizerTest, closeWithoutRecognize) {
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::previsao_tempo_8k);
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder().addFromURI(test::slm_uri).build();
std::unique_ptr<SpeechRecognizer> asr = defaultBuild();
asr->close();
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
ASSERT_EQ(result.size(), 0);
}
TEST(RecognizerTest,cancelNoRecognize) {
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::previsao_tempo_8k);
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder().addFromURI(test::slm_uri).build();
std::unique_ptr<SpeechRecognizer> asr = defaultBuild();
asr->cancelRecognition();
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
asr->close();
ASSERT_EQ(result.size(), 0);
}
TEST(RecognizerTest,cancelWhileRecognize) {
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::previsao_tempo_8k);
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder().addFromURI(test::slm_uri).build();
std::unique_ptr<SpeechRecognizer> asr = defaultBuild();
asr->recognize(audio, std::move(lm));
std::this_thread::sleep_for(std::chrono::milliseconds(300));
asr->cancelRecognition();
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
asr->close();
ASSERT_EQ(result.size(), 0);
}
TEST(RecognizerTest, waitRecognitionResultNoRecognizerTest) {
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::previsao_tempo_8k);
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder().addFromURI(test::slm_uri).build();
std::unique_ptr<SpeechRecognizer> asr = defaultBuild();
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
asr->close();
ASSERT_EQ(result.size(), 0);
}
TEST(RecognizerTest, waitRecognitionResultDuplicateTest) {
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::previsao_tempo_8k);
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder().addFromURI(test::slm_uri).build();
std::unique_ptr<SpeechRecognizer> asr = defaultBuild();
asr->recognize(audio, std::move(lm));
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
ASSERT_GT(result.size(), 0);
result = asr->waitRecognitionResult();
ASSERT_EQ(result.size(), 0);
}
TEST(RecognizerTest, duplicateRecognize) {
std::unique_ptr<SpeechRecognizer> asr = defaultBuild();
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::audio_phone_8k);
auto lm = LanguageModelList::Builder().addFromURI(test::slm_uri).build();
asr->recognize(audio, std::move(lm));
std::shared_ptr<AudioSource> audio2 =
std::make_shared<FileAudioSource>(test::previsao_tempo_8k);
auto lm2 = LanguageModelList::Builder().addFromURI(test::slm_uri).build();
std::this_thread::sleep_for(std::chrono::milliseconds(120));
ASSERT_THROW(asr->recognize(audio2, std::move(lm2)), RecognitionException);
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
ASSERT_GT(result.size(), 0);
}
TEST(RecognizerTest, multipleRecognize) {
std::unique_ptr<SpeechRecognizer> asr = defaultBuild();
for (auto i = 0; i < 3; ++i) {
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder()
.addFromURI(test::grammar_phone_uri)
.build();
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::audio_phone_8k);
asr->recognize(audio, std::move(lm));
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
bool at_least_one_recognized = false;
for (RecognitionResult& res : result) {
if(res.getCode() == RecognitionResult::Code::RECOGNIZED)
at_least_one_recognized = true;
}
ASSERT_EQ(true, at_least_one_recognized);
}
}
TEST(RecognizerTest, multipleConnectOnRecognize) {
std::unique_ptr<RecognitionConfig> config =
RecognitionConfig::Builder().build();
std::unique_ptr<SpeechRecognizer> asr = SpeechRecognizer::Builder()
.serverUrl(test::server_url)
.recogConfig(std::move(config))
.credentials("asrdev", "inova")
.maxWaitSeconds(30)
.connectOnRecognize(true)
.build();
ASSERT_EQ(false, asr->isOpen()) <<
"Connection should stay closed until 1st recognition!";
int wait_secs[] = {2, 2, 6};
for (auto i = 0; i < 3; ++i) {
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder()
.addFromURI(test::grammar_phone_uri)
.build();
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::audio_phone_8k);
asr->recognize(audio, std::move(lm));
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
ASSERT_EQ(true, asr->isOpen()) <<
"Connection should stay open after 1st recognition!";
bool at_least_one_recognized = false;
for (RecognitionResult& res : result) {
if(res.getCode() == RecognitionResult::Code::RECOGNIZED)
at_least_one_recognized = true;
}
ASSERT_EQ(true, at_least_one_recognized);
std::this_thread::sleep_for(std::chrono::seconds(wait_secs[i]));
}
}
TEST(RecognizerTest, multipleAutoClose) {
std::unique_ptr<RecognitionConfig> config =
RecognitionConfig::Builder().build();
std::unique_ptr<SpeechRecognizer> asr = SpeechRecognizer::Builder()
.serverUrl(test::server_url)
.recogConfig(std::move(config))
.credentials("asrdev", "inova")
.maxWaitSeconds(30)
.connectOnRecognize(true)
.autoClose(true)
.build();
ASSERT_EQ(false, asr->isOpen()) <<
"Connection should stay closed until recognition!";
int wait_secs[] = {2, 2, 6};
for (auto i = 0; i < 3; ++i) {
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder()
.addFromURI(test::grammar_phone_uri)
.build();
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::audio_phone_8k);
asr->recognize(audio, std::move(lm));
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
ASSERT_EQ(false, asr->isOpen()) <<
"Connection should close after every recognition!";;
bool at_least_one_recognized = false;
for (RecognitionResult& res : result) {
if(res.getCode() == RecognitionResult::Code::RECOGNIZED)
at_least_one_recognized = true;
}
ASSERT_EQ(true, at_least_one_recognized);
std::this_thread::sleep_for(std::chrono::seconds(wait_secs[i]));
}
}
TEST(RecognizerTest, sessionTimeout) {
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::audio_phone_8k);
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder().addFromURI(test::grammar_phone_uri).build();
std::unique_ptr<SpeechRecognizer> asr = defaultBuild();
asr->recognize(audio, std::move(lm));
std::this_thread::sleep_for(std::chrono::seconds(65));
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
asr->close();
ASSERT_LT(0, result.size());
bool at_least_one_recognized = false;
for (RecognitionResult& res : result) {
if(res.getCode() == RecognitionResult::Code::RECOGNIZED)
at_least_one_recognized = true;
}
ASSERT_EQ(true, at_least_one_recognized);
}
TEST(GrammarInline, Recog) {
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::audio_yes_16k);
std::string str_gram = "#ABNF 1.0 UTF-8;\n"
"language pt-BR;\n"
"tag-format <semantics/1.0>;\n"
"mode voice;\n"
"root $root;\n"
"$root = sim | não;\n";
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder()
.addInlineGrammar(str_gram)
.build();
std::unique_ptr<SpeechRecognizer> asr = defaultBuild();
asr->recognize(audio, std::move(lm));
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
asr->close();
ASSERT_GT(result.size(), 0);
}
TEST(GrammarInline, WrongGrammar) {
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::audio_yes_16k);
std::string str_gram = "#ABNF 1.0 UTF-8;\n"
"language pt-BR;\n"
"tag-format <semantics/1.0>;\n"
"mode voice;\n"
"root $rodfot;\n"
"$root = sim | não;\n";
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder()
.addInlineGrammar(str_gram)
.build();
try {
std::unique_ptr<SpeechRecognizer> asr = defaultBuild();
asr->recognize(audio, std::move(lm));
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
asr->close();
} catch (RecognitionException& e) {
} catch (...) {
FAIL() << "Expected error on start recognition";
}
}
TEST(GrammarInline, TwoGrammars) {
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::audio_yes_16k);
std::unique_ptr<LanguageModelList> lm;
try {
std::string str_gram = "#ABNF 1.0 UTF-8;\n"
"language pt-BR;\n"
"tag-format <semantics/1.0>;\n"
"mode voice;\n"
"root $root;\n"
"$root = sim | não;\n";
lm = LanguageModelList::Builder()
.addInlineGrammar(str_gram)
.addInlineGrammar(str_gram)
.build();
} catch (RecognitionException& e) {
return;
} catch (...) {
FAIL() << "Expected error on LanguageModelList";
}
}
TEST(GrammarInline, InlineAndUri) {
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::audio_yes_16k);
std::unique_ptr<LanguageModelList> lm;
try {
std::string str_gram = "#ABNF 1.0 UTF-8;\n"
"language pt-BR;\n"
"tag-format <semantics/1.0>;\n"
"mode voice;\n"
"root $root;\n"
"$root = sim | não;\n";
lm = LanguageModelList::Builder()
.addInlineGrammar(str_gram)
.addFromURI(test::grammar_phone_uri)
.build();
} catch (RecognitionException& e) {
return;
} catch (...) {
FAIL() << "Expected error on LanguageModelList";
}
}
| 33.769841 | 88 | 0.676193 |
b6fb19c28ec6bab8291643f67434843fb09d55bf | 3,231 | cpp | C++ | docs/tests/graph.cpp | nyorain/tokonoma | b3a4264ef4f9f40487c2f3280812bf7513b914bb | [
"MIT"
] | 23 | 2019-07-11T14:47:39.000Z | 2021-12-24T09:56:24.000Z | docs/tests/graph.cpp | nyorain/tokonoma | b3a4264ef4f9f40487c2f3280812bf7513b914bb | [
"MIT"
] | null | null | null | docs/tests/graph.cpp | nyorain/tokonoma | b3a4264ef4f9f40487c2f3280812bf7513b914bb | [
"MIT"
] | 4 | 2021-04-06T18:20:43.000Z | 2022-01-15T09:20:45.000Z | #include "bugged.hpp"
#include <deferred/graph.hpp>
TEST(basic) {
FrameGraph graph;
auto& pass1 = graph.addPass();
vk::Image img1;
vk::Image img2;
auto& out1 = pass1.addOut(syncScopeFlex, img1);
auto& out2 = pass1.addOut(syncScopeFlex, img2);
auto scope2 = SyncScope {
vk::PipelineStageBits::computeShader,
vk::ImageLayout::shaderReadOnlyOptimal,
vk::AccessBits::shaderRead,
};
auto& pass2 = graph.addPass();
pass2.addIn(out1, scope2);
auto scope3 = SyncScope {
vk::PipelineStageBits::fragmentShader,
vk::ImageLayout::shaderReadOnlyOptimal,
vk::AccessBits::shaderRead,
};
auto& pass3 = graph.addPass();
pass3.addIn(out1, scope3);
pass3.addIn(out2, scope3);
graph.compute();
// test
auto& order = graph.order();
EXPECT(graph.check(), true);
EXPECT(order.size(), 3u);
EXPECT(order[0].pass, &pass1);
EXPECT(order[1].pass, &pass2);
EXPECT(order[2].pass, &pass3);
EXPECT(order[0].barriers.size(), 0u);
EXPECT(order[1].barriers.size(), 0u);
EXPECT(order[2].barriers.size(), 0u);
EXPECT(graph.check(), true);
}
TEST(outOfOrder) {
FrameGraph graph;
vk::Image img1;
vk::Image img2;
auto& pass1 = graph.addPass();
auto& pass3 = graph.addPass();
auto& pass2 = graph.addPass();
auto scope2 = SyncScope {
vk::PipelineStageBits::computeShader,
vk::ImageLayout::general,
vk::AccessBits::shaderRead | vk::AccessBits::shaderWrite
};
auto scope3 = SyncScope {
vk::PipelineStageBits::fragmentShader,
vk::ImageLayout::shaderReadOnlyOptimal,
vk::AccessBits::shaderRead,
};
auto& out1 = pass1.addOut(syncScopeFlex, img1);
auto& out2 = pass1.addOut(syncScopeFlex, img2);
pass3.addIn(out2, scope3);
auto& out3 = pass2.addInOut(out1, scope2);
pass3.addIn(out3, scope3);
graph.compute();
// test
EXPECT(graph.check(), true);
auto& order = graph.order();
EXPECT(order.size(), 3u);
EXPECT(order[0].pass, &pass1);
EXPECT(order[1].pass, &pass2);
EXPECT(order[2].pass, &pass3);
EXPECT(order[0].barriers.size(), 0u);
EXPECT(order[1].barriers.size(), 0u);
EXPECT(order[2].barriers.size(), 1u);
auto& b = order[2].barriers[0];
EXPECT(b.src, scope2);
EXPECT(b.dst, scope3);
EXPECT(b.target, &out3);
EXPECT(graph.check(), true);
}
TEST(cycle) {
FrameGraph graph;
vk::Image img1;
auto& pass = graph.addPass();
auto& out = pass.addOut(syncScopeFlex, img1);
pass.addIn(out, syncScopeFlex);
EXPECT(graph.check(), false);
}
TEST(cycle2) {
FrameGraph graph;
vk::Image img1;
vk::Image img2;
auto& pass1 = graph.addPass();
auto& pass2 = graph.addPass();
auto& out1 = pass1.addOut(syncScopeFlex, img1);
pass2.addIn(out1, syncScopeFlex);
auto& out2 = pass2.addOut(syncScopeFlex, img2);
pass1.addIn(out2, syncScopeFlex);
EXPECT(graph.check(), false);
}
TEST(badDep) {
FrameGraph graph;
vk::Image img1;
auto& pass1 = graph.addPass();
auto& out1 = pass1.addOut(syncScopeFlex, img1);
auto scope2 = SyncScope {
vk::PipelineStageBits::computeShader,
vk::ImageLayout::general,
vk::AccessBits::shaderRead | vk::AccessBits::shaderWrite
};
auto& pass2 = graph.addPass();
auto& out2 = pass2.addInOut(out1, scope2);
auto& pass3 = graph.addPass();
pass3.addIn(out1, syncScopeFlex);
pass3.addIn(out2, syncScopeFlex);
EXPECT(graph.check(), false);
}
| 23.078571 | 58 | 0.692974 |
b6fbfbcd376fa5bc3b2a981074d82b19475e59ea | 644 | cpp | C++ | native/code/src/gdnative/GodotLibrary.cpp | Chery-cake/base_gdnative | c6c1d60dcf3c6f8a7d70e6ca7eceb7b40efbe93e | [
"MIT"
] | null | null | null | native/code/src/gdnative/GodotLibrary.cpp | Chery-cake/base_gdnative | c6c1d60dcf3c6f8a7d70e6ca7eceb7b40efbe93e | [
"MIT"
] | null | null | null | native/code/src/gdnative/GodotLibrary.cpp | Chery-cake/base_gdnative | c6c1d60dcf3c6f8a7d70e6ca7eceb7b40efbe93e | [
"MIT"
] | null | null | null | #include <Godot.hpp>
#include <AutoRegister.hpp>
/** GDNative Initialize **/
extern "C" void GDN_EXPORT godot_gdnative_init(godot_gdnative_init_options *o) {
godot::Godot::gdnative_init(o);
}
/** GDNative Terminate **/
extern "C" void GDN_EXPORT godot_gdnative_terminate(godot_gdnative_terminate_options *o) {
godot::Godot::gdnative_terminate(o);
}
/** NativeScript Initialize **/
extern "C" void GDN_EXPORT godot_nativescript_init(void *handle) {
godot::Godot::nativescript_init(handle);
//utility classes
//classes
//sub classes
AutoRegister::register_classes();
AutoRegister::generate_gdns("scripts", "gdnativelibrary");
}
| 21.466667 | 90 | 0.754658 |
b6ffd38232e34a6c633d9472a60fc53d10602b17 | 1,380 | cpp | C++ | llvm/lib/Target/PTX/PTXRegisterInfo.cpp | clairechingching/ScaffCC | 737ae90f85d9fe79819d66219747d27efa4fa5b9 | [
"BSD-2-Clause"
] | 3 | 2019-02-12T04:14:39.000Z | 2020-11-05T08:46:20.000Z | llvm/lib/Target/PTX/PTXRegisterInfo.cpp | clairechingching/ScaffCC | 737ae90f85d9fe79819d66219747d27efa4fa5b9 | [
"BSD-2-Clause"
] | 1 | 2020-02-22T09:59:21.000Z | 2020-02-22T09:59:21.000Z | llvm/lib/Target/PTX/PTXRegisterInfo.cpp | clairechingching/ScaffCC | 737ae90f85d9fe79819d66219747d27efa4fa5b9 | [
"BSD-2-Clause"
] | 1 | 2020-05-15T12:53:42.000Z | 2020-05-15T12:53:42.000Z | //===-- PTXRegisterInfo.cpp - PTX Register Information --------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the PTX implementation of the TargetRegisterInfo class.
//
//===----------------------------------------------------------------------===//
#include "PTXRegisterInfo.h"
#include "PTX.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#define GET_REGINFO_TARGET_DESC
#include "PTXGenRegisterInfo.inc"
using namespace llvm;
PTXRegisterInfo::PTXRegisterInfo(PTXTargetMachine &TM,
const TargetInstrInfo &tii)
// PTX does not have a return address register.
: PTXGenRegisterInfo(0), TII(tii) {
}
void PTXRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator /*II*/,
int /*SPAdj*/,
RegScavenger * /*RS*/) const {
llvm_unreachable("FrameIndex should have been previously eliminated!");
}
| 35.384615 | 80 | 0.588406 |
8e05cb6da00cf835ee44dbc77bfd1da9a6871ed1 | 1,217 | cpp | C++ | L9/17_JavaCpp_/03ObjectsInMemory/c_HeapInstance/1/FooBar.cpp | DeirdreHegarty/advanced_OOP | e62d8f2274422d3da9064e2576e2adc414eccee1 | [
"MIT"
] | null | null | null | L9/17_JavaCpp_/03ObjectsInMemory/c_HeapInstance/1/FooBar.cpp | DeirdreHegarty/advanced_OOP | e62d8f2274422d3da9064e2576e2adc414eccee1 | [
"MIT"
] | null | null | null | L9/17_JavaCpp_/03ObjectsInMemory/c_HeapInstance/1/FooBar.cpp | DeirdreHegarty/advanced_OOP | e62d8f2274422d3da9064e2576e2adc414eccee1 | [
"MIT"
] | null | null | null | /*
//Header file declarations reproduced here
// for quick access
//FooBar.h
class Bar{
public:
void doBarThing();
};
class Foo
{ //The default-access specifier is private in C++
Bar *aBar; //hence 'aBar' pointer is private
public:
virtual ~Foo();
void createBar();
void useBar();
void deleteBar();
};
*/
/*
* IMPORTANT: This is a lesson in how _NOT_ to write your C++
* Object creation/manipulation code.
*/
//[FooBar.cpp]
#include <iostream>
#include "FooBar.h"
using namespace std;
Foo::~Foo(){ // "Destructor"
cout<< "Foo() destructor" << endl;
}
//What happens if you call this twice: i.e. there's no
// garbage-collector in C++
void Foo::createBar(){
cout<<"createBar() running"<<endl;
aBar = new Bar();
}
//What if you call this before calling 'createBar()'?
// What would 'aBar' be pointing to?
void Foo::useBar(){
cout<<"useBar(): calling aBar->doBarThing()"<<endl;
aBar->doBarThing();
}
void Foo::deleteBar(){
cout<<"deleteBar(): delete aBar"<<endl;
delete aBar;
}
void Bar::doBarThing(){
cout<<"Bar::doBarThing()"<<endl;
} | 23.403846 | 62 | 0.579293 |
8e07241468fe38fce70be538f51e493f0382cfe9 | 17,809 | cpp | C++ | gmsh/Geo/SOrientedBoundingBox.cpp | Poofee/fastFEM | 14eb626df973e2123604041451912c867ab7188c | [
"MIT"
] | 4 | 2019-05-06T09:35:08.000Z | 2021-05-14T16:26:45.000Z | gmsh/Geo/SOrientedBoundingBox.cpp | Poofee/fastFEM | 14eb626df973e2123604041451912c867ab7188c | [
"MIT"
] | null | null | null | gmsh/Geo/SOrientedBoundingBox.cpp | Poofee/fastFEM | 14eb626df973e2123604041451912c867ab7188c | [
"MIT"
] | 1 | 2019-06-28T09:23:43.000Z | 2019-06-28T09:23:43.000Z | // Gmsh - Copyright (C) 1997-2019 C. Geuzaine, J.-F. Remacle
//
// See the LICENSE.txt file for license information. Please report all
// issues on https://gitlab.onelab.info/gmsh/gmsh/issues.
//
// Contributor(s):
// Bastien Gorissen
//
#include <algorithm>
#include <cmath>
#include <time.h>
#include "GmshConfig.h"
#include "SOrientedBoundingBox.h"
#include "fullMatrix.h"
#include "SBoundingBox3d.h"
#if defined(HAVE_MESH)
#include "DivideAndConquer.h"
#endif
double SOrientedBoundingRectangle::area() { return size[0] * size[1]; }
SOrientedBoundingRectangle::SOrientedBoundingRectangle()
: center(2, 0.0), size(2, 0.0), axisX(2, 0.0), axisY(2, 0.0)
{
}
void SOrientedBoundingBox::fillp()
{
double dx = 0.5 * size[0];
double dy = 0.5 * size[1];
double dz = 0.5 * size[2];
p1x = center[0] - (axisX[0] * dx) - (axisY[0] * dy) - (axisZ[0] * dz);
p1y = center[1] - (axisX[1] * dx) - (axisY[1] * dy) - (axisZ[1] * dz);
p1z = center[2] - (axisX[2] * dx) - (axisY[2] * dy) - (axisZ[2] * dz);
p2x = center[0] + (axisX[0] * dx) - (axisY[0] * dy) - (axisZ[0] * dz);
p2y = center[1] + (axisX[1] * dx) - (axisY[1] * dy) - (axisZ[1] * dz);
p2z = center[2] + (axisX[2] * dx) - (axisY[2] * dy) - (axisZ[2] * dz);
p3x = center[0] - (axisX[0] * dx) + (axisY[0] * dy) - (axisZ[0] * dz);
p3y = center[1] - (axisX[1] * dx) + (axisY[1] * dy) - (axisZ[1] * dz);
p3z = center[2] - (axisX[2] * dx) + (axisY[2] * dy) - (axisZ[2] * dz);
p4x = center[0] + (axisX[0] * dx) + (axisY[0] * dy) - (axisZ[0] * dz);
p4y = center[1] + (axisX[1] * dx) + (axisY[1] * dy) - (axisZ[1] * dz);
p4z = center[2] + (axisX[2] * dx) + (axisY[2] * dy) - (axisZ[2] * dz);
p5x = center[0] - (axisX[0] * dx) - (axisY[0] * dy) + (axisZ[0] * dz);
p5y = center[1] - (axisX[1] * dx) - (axisY[1] * dy) + (axisZ[1] * dz);
p5z = center[2] - (axisX[2] * dx) - (axisY[2] * dy) + (axisZ[2] * dz);
p6x = center[0] + (axisX[0] * dx) - (axisY[0] * dy) + (axisZ[0] * dz);
p6y = center[1] + (axisX[1] * dx) - (axisY[1] * dy) + (axisZ[1] * dz);
p6z = center[2] + (axisX[2] * dx) - (axisY[2] * dy) + (axisZ[2] * dz);
p7x = center[0] - (axisX[0] * dx) + (axisY[0] * dy) + (axisZ[0] * dz);
p7y = center[1] - (axisX[1] * dx) + (axisY[1] * dy) + (axisZ[1] * dz);
p7z = center[2] - (axisX[2] * dx) + (axisY[2] * dy) + (axisZ[2] * dz);
p8x = center[0] + (axisX[0] * dx) + (axisY[0] * dy) + (axisZ[0] * dz);
p8y = center[1] + (axisX[1] * dx) + (axisY[1] * dy) + (axisZ[1] * dz);
p8z = center[2] + (axisX[2] * dx) + (axisY[2] * dy) + (axisZ[2] * dz);
}
SOrientedBoundingBox::SOrientedBoundingBox()
{
center = SVector3();
size = SVector3();
axisX = SVector3();
axisY = SVector3();
axisZ = SVector3();
fillp();
}
SOrientedBoundingBox::SOrientedBoundingBox(SVector3 ¢er_, double sizeX,
double sizeY, double sizeZ,
const SVector3 &axisX_,
const SVector3 &axisY_,
const SVector3 &axisZ_)
{
center = center_;
size = SVector3(sizeX, sizeY, sizeZ);
axisX = axisX_;
axisX.normalize();
axisY = axisY_;
axisY.normalize();
axisZ = axisZ_;
axisZ.normalize();
fillp();
}
SOrientedBoundingBox::SOrientedBoundingBox(SOrientedBoundingBox *other)
{
size = other->getSize();
axisX = other->getAxis(0);
axisY = other->getAxis(1);
axisZ = other->getAxis(2);
center = other->getCenter();
fillp();
}
SVector3 SOrientedBoundingBox::getAxis(int axis) const
{
SVector3 ret;
switch(axis) {
case 0: ret = axisX; break;
case 1: ret = axisY; break;
case 2: ret = axisZ; break;
}
return ret;
}
bool SOrientedBoundingBox::intersects(SOrientedBoundingBox &obb) const
{
SVector3 collide_axes[15];
for(int i = 0; i < 3; i++) {
collide_axes[i] = getAxis(i);
collide_axes[i + 3] = obb.getAxis(i);
}
SVector3 sizes[2];
sizes[0] = getSize();
sizes[1] = obb.getSize();
for(std::size_t i = 0; i < 3; i++) {
for(std::size_t j = 3; j < 6; j++) {
collide_axes[3 * i + j + 3] = crossprod(collide_axes[i], collide_axes[j]);
}
}
SVector3 T = obb.getCenter() - getCenter();
for(std::size_t i = 0; i < 15; i++) {
double val = 0.0;
for(std::size_t j = 0; j < 6; j++) {
val += 0.5 * (sizes[j < 3 ? 0 : 1])(j % 3) *
std::abs(dot(collide_axes[j], collide_axes[i]));
}
if(std::abs(dot(collide_axes[i], T)) > val) { return false; }
}
return true;
}
SOrientedBoundingBox *
SOrientedBoundingBox::buildOBB(std::vector<SPoint3> &vertices)
{
#if defined(HAVE_MESH)
int num_vertices = vertices.size();
// First organize the data
std::set<SPoint3> unique;
unique.insert(vertices.begin(), vertices.end());
num_vertices = unique.size();
fullMatrix<double> data(3, num_vertices);
fullVector<double> mean(3);
fullVector<double> vmins(3);
fullVector<double> vmaxs(3);
mean.setAll(0);
vmins.setAll(DBL_MAX);
vmaxs.setAll(-DBL_MAX);
size_t idx = 0;
for(std::set<SPoint3>::iterator uIter = unique.begin(); uIter != unique.end();
++uIter) {
const SPoint3 &pp = *uIter;
for(int d = 0; d < 3; d++) {
data(d, idx) = pp[d];
vmins(d) = std::min(vmins(d), pp[d]);
vmaxs(d) = std::max(vmaxs(d), pp[d]);
mean(d) += pp[d];
}
idx++;
}
for(int i = 0; i < 3; i++) { mean(i) /= num_vertices; }
// Get the deviation from the mean
fullMatrix<double> B(3, num_vertices);
for(int i = 0; i < 3; i++) {
for(int j = 0; j < num_vertices; j++) { B(i, j) = data(i, j) - mean(i); }
}
// Compute the covariance matrix
fullMatrix<double> covariance(3, 3);
B.mult(B.transpose(), covariance);
covariance.scale(1. / (num_vertices - 1));
/*
Msg::Debug("Covariance matrix");
Msg::Debug("%f %f %f", covariance(0,0),covariance(0,1),covariance(0,2) );
Msg::Debug("%f %f %f", covariance(1,0),covariance(1,1),covariance(1,2) );
Msg::Debug("%f %f %f", covariance(2,0),covariance(2,1),covariance(2,2) );
*/
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
if(std::abs(covariance(i, j)) < 10e-16) covariance(i, j) = 0;
}
}
fullMatrix<double> left_eigv(3, 3);
fullMatrix<double> right_eigv(3, 3);
fullVector<double> real_eig(3);
fullVector<double> img_eig(3);
covariance.eig(real_eig, img_eig, left_eigv, right_eigv, true);
// Now, project the data in the new basis.
fullMatrix<double> projected(3, num_vertices);
left_eigv.transpose().mult(data, projected);
// Get the size of the box in the new direction
fullVector<double> mins(3);
fullVector<double> maxs(3);
for(int i = 0; i < 3; i++) {
mins(i) = DBL_MAX;
maxs(i) = -DBL_MAX;
for(int j = 0; j < num_vertices; j++) {
maxs(i) = std::max(maxs(i), projected(i, j));
mins(i) = std::min(mins(i), projected(i, j));
}
}
// double means[3];
double sizes[3];
// Note: the size is computed in the box's coordinates!
for(int i = 0; i < 3; i++) {
sizes[i] = maxs(i) - mins(i);
// means[i] = (maxs(i) - mins(i)) / 2.;
}
if(sizes[0] == 0 && sizes[1] == 0) {
// Entity is a straight line...
SVector3 center;
SVector3 Axis1;
SVector3 Axis2;
SVector3 Axis3;
Axis1[0] = left_eigv(0, 0);
Axis1[1] = left_eigv(1, 0);
Axis1[2] = left_eigv(2, 0);
Axis2[0] = left_eigv(0, 1);
Axis2[1] = left_eigv(1, 1);
Axis2[2] = left_eigv(2, 1);
Axis3[0] = left_eigv(0, 2);
Axis3[1] = left_eigv(1, 2);
Axis3[2] = left_eigv(2, 2);
center[0] = (vmaxs(0) + vmins(0)) / 2.0;
center[1] = (vmaxs(1) + vmins(1)) / 2.0;
center[2] = (vmaxs(2) + vmins(2)) / 2.0;
return new SOrientedBoundingBox(center, sizes[0], sizes[1], sizes[2], Axis1,
Axis2, Axis3);
}
// We take the smallest component, then project the data on the plane defined
// by the other twos
int smallest_comp = 0;
if(sizes[0] <= sizes[1] && sizes[0] <= sizes[2])
smallest_comp = 0;
else if(sizes[1] <= sizes[0] && sizes[1] <= sizes[2])
smallest_comp = 1;
else if(sizes[2] <= sizes[0] && sizes[2] <= sizes[1])
smallest_comp = 2;
// The projection has been done circa line 161.
// We just ignore the coordinate corresponding to smallest_comp.
std::vector<SPoint2 *> points;
for(int i = 0; i < num_vertices; i++) {
SPoint2 *p = new SPoint2(projected(smallest_comp == 0 ? 1 : 0, i),
projected(smallest_comp == 2 ? 1 : 2, i));
bool keep = true;
for(std::vector<SPoint2 *>::iterator point = points.begin();
point != points.end(); point++) {
if(std::abs((*p)[0] - (**point)[0]) < 10e-10 &&
std::abs((*p)[1] - (**point)[1]) < 10e-10) {
keep = false;
break;
}
}
if(keep) { points.push_back(p); }
else {
delete p;
}
}
// Find the convex hull from a delaunay triangulation of the points
DocRecord record(points.size());
record.numPoints = points.size();
srand((unsigned)time(0));
for(std::size_t i = 0; i < points.size(); i++) {
record.points[i].where.h =
points[i]->x() + (10e-6) * sizes[smallest_comp == 0 ? 1 : 0] *
(-0.5 + ((double)rand()) / RAND_MAX);
record.points[i].where.v =
points[i]->y() + (10e-6) * sizes[smallest_comp == 2 ? 1 : 0] *
(-0.5 + ((double)rand()) / RAND_MAX);
record.points[i].adjacent = nullptr;
}
try {
record.MakeMeshWithPoints();
} catch(const char *err) {
Msg::Error("%s", err);
}
std::vector<Segment> convex_hull;
for(int i = 0; i < record.numTriangles; i++) {
Segment segs[3];
segs[0].from = record.triangles[i].a;
segs[0].to = record.triangles[i].b;
segs[1].from = record.triangles[i].b;
segs[1].to = record.triangles[i].c;
segs[2].from = record.triangles[i].c;
segs[2].to = record.triangles[i].a;
for(int j = 0; j < 3; j++) {
bool okay = true;
for(std::vector<Segment>::iterator seg = convex_hull.begin();
seg != convex_hull.end(); seg++) {
if(((*seg).from == segs[j].from && (*seg).from == segs[j].to)
// FIXME:
// || ((*seg).from == segs[j].to && (*seg).from == segs[j].from)
) {
convex_hull.erase(seg);
okay = false;
break;
}
}
if(okay) { convex_hull.push_back(segs[j]); }
}
}
// Now, examinate all the directions given by the edges of the convex hull
// to find the one that lets us build the least-area bounding rectangle for
// then points.
fullVector<double> axis(2);
axis(0) = 1;
axis(1) = 0;
fullVector<double> axis2(2);
axis2(0) = 0;
axis2(1) = 1;
SOrientedBoundingRectangle least_rectangle;
least_rectangle.center[0] = 0.0;
least_rectangle.center[1] = 0.0;
least_rectangle.size[0] = -1.0;
least_rectangle.size[1] = 1.0;
fullVector<double> segment(2);
fullMatrix<double> rotation(2, 2);
for(std::vector<Segment>::iterator seg = convex_hull.begin();
seg != convex_hull.end(); seg++) {
// segment(0) = record.points[(*seg).from].where.h -
// record.points[(*seg).to].where.h; segment(1) =
// record.points[(*seg).from].where.v - record.points[(*seg).to].where.v;
segment(0) = points[(*seg).from]->x() - points[(*seg).to]->x();
segment(1) = points[(*seg).from]->y() - points[(*seg).to]->y();
segment.scale(1.0 / segment.norm());
double cosine = axis(0) * segment(0) + segment(1) * axis(1);
double sine = axis(1) * segment(0) - segment(1) * axis(0);
// double sine = axis(0)*segment(1) - segment(0)*axis(1);
rotation(0, 0) = cosine;
rotation(0, 1) = sine;
rotation(1, 0) = -sine;
rotation(1, 1) = cosine;
// TODO C++11 std::numeric_limits<double>
double max_x = -DBL_MAX;
double min_x = DBL_MAX;
double max_y = -DBL_MAX;
double min_y = DBL_MAX;
for(int i = 0; i < record.numPoints; i++) {
fullVector<double> pnt(2);
// pnt(0) = record.points[i].where.h;
// pnt(1) = record.points[i].where.v;
pnt(0) = points[i]->x();
pnt(1) = points[i]->y();
fullVector<double> rot_pnt(2);
rotation.mult(pnt, rot_pnt);
if(rot_pnt(0) < min_x) min_x = rot_pnt(0);
if(rot_pnt(0) > max_x) max_x = rot_pnt(0);
if(rot_pnt(1) < min_y) min_y = rot_pnt(1);
if(rot_pnt(1) > max_y) max_y = rot_pnt(1);
}
/**/
fullVector<double> center_rot(2);
fullVector<double> center_before_rot(2);
center_before_rot(0) = (max_x + min_x) / 2.0;
center_before_rot(1) = (max_y + min_y) / 2.0;
fullMatrix<double> rotation_inv(2, 2);
rotation_inv(0, 0) = cosine;
rotation_inv(0, 1) = -sine;
rotation_inv(1, 0) = sine;
rotation_inv(1, 1) = cosine;
rotation_inv.mult(center_before_rot, center_rot);
fullVector<double> axis_rot1(2);
fullVector<double> axis_rot2(2);
rotation_inv.mult(axis, axis_rot1);
rotation_inv.mult(axis2, axis_rot2);
if((least_rectangle.area() == -1) ||
(max_x - min_x) * (max_y - min_y) < least_rectangle.area()) {
least_rectangle.size[0] = max_x - min_x;
least_rectangle.size[1] = max_y - min_y;
least_rectangle.center[0] = (max_x + min_x) / 2.0;
least_rectangle.center[1] = (max_y + min_y) / 2.0;
least_rectangle.center[0] = center_rot(0);
least_rectangle.center[1] = center_rot(1);
least_rectangle.axisX[0] = axis_rot1(0);
least_rectangle.axisX[1] = axis_rot1(1);
// least_rectangle.axisX[0] = segment(0);
// least_rectangle.axisX[1] = segment(1);
least_rectangle.axisY[0] = axis_rot2(0);
least_rectangle.axisY[1] = axis_rot2(1);
}
}
// TODO C++11 std::numeric_limits<double>::min() / max()
double min_pca = DBL_MAX;
double max_pca = -DBL_MAX;
for(int i = 0; i < num_vertices; i++) {
min_pca = std::min(min_pca, projected(smallest_comp, i));
max_pca = std::max(max_pca, projected(smallest_comp, i));
}
double center_pca = (max_pca + min_pca) / 2.0;
double size_pca = (max_pca - min_pca);
double raw_data[3][5];
raw_data[0][0] = size_pca;
raw_data[1][0] = least_rectangle.size[0];
raw_data[2][0] = least_rectangle.size[1];
raw_data[0][1] = center_pca;
raw_data[1][1] = least_rectangle.center[0];
raw_data[2][1] = least_rectangle.center[1];
for(int i = 0; i < 3; i++) {
raw_data[0][2 + i] = left_eigv(i, smallest_comp);
raw_data[1][2 + i] =
least_rectangle.axisX[0] * left_eigv(i, smallest_comp == 0 ? 1 : 0) +
least_rectangle.axisX[1] * left_eigv(i, smallest_comp == 2 ? 1 : 2);
raw_data[2][2 + i] =
least_rectangle.axisY[0] * left_eigv(i, smallest_comp == 0 ? 1 : 0) +
least_rectangle.axisY[1] * left_eigv(i, smallest_comp == 2 ? 1 : 2);
}
// Msg::Info("Test 1 : %f
// %f",least_rectangle.center[0],least_rectangle.center[1]);
// Msg::Info("Test 2 : %f
// %f",least_rectangle.axisY[0],least_rectangle.axisY[1]);
int tri[3];
if(size_pca > least_rectangle.size[0]) {
// P > R0
if(size_pca > least_rectangle.size[1]) {
// P > R1
tri[0] = 0;
if(least_rectangle.size[0] > least_rectangle.size[1]) {
// R0 > R1
tri[1] = 1;
tri[2] = 2;
}
else {
// R1 > R0
tri[1] = 2;
tri[2] = 1;
}
}
else {
// P < R1
tri[0] = 2;
tri[1] = 0;
tri[2] = 1;
}
}
else { // P < R0
if(size_pca < least_rectangle.size[1]) {
// P < R1
tri[2] = 0;
if(least_rectangle.size[0] > least_rectangle.size[1]) {
tri[0] = 1;
tri[1] = 2;
}
else {
tri[0] = 2;
tri[1] = 1;
}
}
else {
tri[0] = 1;
tri[1] = 0;
tri[2] = 2;
}
}
SVector3 size;
SVector3 center;
SVector3 Axis1;
SVector3 Axis2;
SVector3 Axis3;
for(int i = 0; i < 3; i++) {
size[i] = raw_data[tri[i]][0];
center[i] = raw_data[tri[i]][1];
Axis1[i] = raw_data[tri[0]][2 + i];
Axis2[i] = raw_data[tri[1]][2 + i];
Axis3[i] = raw_data[tri[2]][2 + i];
}
SVector3 aux1;
SVector3 aux2;
SVector3 aux3;
for(int i = 0; i < 3; i++) {
aux1(i) = left_eigv(i, smallest_comp);
aux2(i) = left_eigv(i, smallest_comp == 0 ? 1 : 0);
aux3(i) = left_eigv(i, smallest_comp == 2 ? 1 : 2);
}
center = aux1 * center_pca + aux2 * least_rectangle.center[0] +
aux3 * least_rectangle.center[1];
// center[1] = -center[1];
/*
Msg::Info("Box center : %f %f %f",center[0],center[1],center[2]);
Msg::Info("Box size : %f %f %f",size[0],size[1],size[2]);
Msg::Info("Box axis 1 : %f %f %f",Axis1[0],Axis1[1],Axis1[2]);
Msg::Info("Box axis 2 : %f %f %f",Axis2[0],Axis2[1],Axis2[2]);
Msg::Info("Box axis 3 : %f %f %f",Axis3[0],Axis3[1],Axis3[2]);
Msg::Info("Volume : %f", size[0]*size[1]*size[2]);
*/
return new SOrientedBoundingBox(center, size[0], size[1], size[2], Axis1,
Axis2, Axis3);
#else
Msg::Error("SOrientedBoundingBox requires mesh module");
return 0;
#endif
}
double SOrientedBoundingBox::compare(SOrientedBoundingBox &obb1,
SOrientedBoundingBox &obb2)
{
// "center term"
double center_term = norm(obb1.getCenter() - obb2.getCenter());
// "size term"
double size_term = 0.0;
for(int i = 0; i < 3; i++) {
if(obb1.getSize()(i) + obb2.getSize()(i) != 0) {
size_term += std::abs(obb1.getSize()(i) - obb2.getSize()(i)) /
(obb1.getSize()(i) + obb2.getSize()(i));
}
}
// "orientation term"
double orientation_term = 0.0;
for(int i = 0; i < 3; i++) {
orientation_term += 1 - std::abs(dot(obb1.getAxis(i), obb2.getAxis(i)));
}
return center_term + size_term + orientation_term;
}
| 30.758204 | 80 | 0.563479 |
8e07633464a0d666535aa331121e742093136dfd | 21,396 | cc | C++ | PhysicsTools/Heppy/src/Davismt2.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | PhysicsTools/Heppy/src/Davismt2.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | PhysicsTools/Heppy/src/Davismt2.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | // #ifndef MT2_BISECT_C
// #define MT2_BISECT_C
/***********************************************************************/
/* */
/* Finding mt2 by Bisection */
/* */
/* Authors: Hsin-Chia Cheng, Zhenyu Han */
/* Dec 11, 2008, v1.01a */
/* */
/***********************************************************************/
/*******************************************************************************
Usage:
1. Define an object of type "mt2":
mt2_bisect::mt2 mt2_event;
2. Set momenta and the mass of the invisible particle, mn:
mt2_event.set_momenta( pa, pb, pmiss );
mt2_event.set_mass( mn );
where array pa[0..2], pb[0..2], pmiss[0..2] contains (mass,px,py)
for the visible particles and the missing momentum. pmiss[0] is not used.
All quantities are given in double.
3. Use Davismt2::get_mt2() to obtain the value of mt2:
double mt2_value = mt2_event.get_mt2();
*******************************************************************************/
#include "PhysicsTools/Heppy/interface/Davismt2.h"
// ClassImp(Davismt2);
using namespace std;
namespace heppy {
/*The user can change the desired precision below, the larger one of the following two definitions is used. Relative precision less than 0.00001 is not guaranteed to be
achievable--use with caution*/
const float Davismt2::RELATIVE_PRECISION = 0.00001;
const float Davismt2::ABSOLUTE_PRECISION = 0.0;
const float Davismt2::ZERO_MASS = 0.0;
const float Davismt2::MIN_MASS = 0.1;
const float Davismt2::SCANSTEP = 0.1;
Davismt2::Davismt2() {
solved = false;
momenta_set = false;
mt2_b = 0.;
scale = 1.;
verbose = 1;
}
Davismt2::~Davismt2() {}
double Davismt2::get_mt2() {
if (!momenta_set) {
cout << "Davismt2::get_mt2() ==> Please set momenta first!" << endl;
return 0;
}
if (!solved)
mt2_bisect();
return mt2_b * scale;
}
void Davismt2::set_momenta(double* pa0, double* pb0, double* pmiss0) {
solved = false; //reset solved tag when momenta are changed.
momenta_set = true;
ma = fabs(pa0[0]); // mass cannot be negative
if (ma < ZERO_MASS)
ma = ZERO_MASS;
pax = pa0[1];
pay = pa0[2];
masq = ma * ma;
Easq = masq + pax * pax + pay * pay;
Ea = sqrt(Easq);
mb = fabs(pb0[0]);
if (mb < ZERO_MASS)
mb = ZERO_MASS;
pbx = pb0[1];
pby = pb0[2];
mbsq = mb * mb;
Ebsq = mbsq + pbx * pbx + pby * pby;
Eb = sqrt(Ebsq);
pmissx = pmiss0[1];
pmissy = pmiss0[2];
pmissxsq = pmissx * pmissx;
pmissysq = pmissy * pmissy;
// set ma>= mb
if (masq < mbsq) {
double temp;
temp = pax;
pax = pbx;
pbx = temp;
temp = pay;
pay = pby;
pby = temp;
temp = Ea;
Ea = Eb;
Eb = temp;
temp = Easq;
Easq = Ebsq;
Ebsq = temp;
temp = masq;
masq = mbsq;
mbsq = temp;
temp = ma;
ma = mb;
mb = temp;
}
//normalize max{Ea, Eb} to 100
if (Ea > Eb)
scale = Ea / 100.;
else
scale = Eb / 100.;
if (sqrt(pmissxsq + pmissysq) / 100 > scale)
scale = sqrt(pmissxsq + pmissysq) / 100;
//scale = 1;
double scalesq = scale * scale;
ma = ma / scale;
mb = mb / scale;
masq = masq / scalesq;
mbsq = mbsq / scalesq;
pax = pax / scale;
pay = pay / scale;
pbx = pbx / scale;
pby = pby / scale;
Ea = Ea / scale;
Eb = Eb / scale;
Easq = Easq / scalesq;
Ebsq = Ebsq / scalesq;
pmissx = pmissx / scale;
pmissy = pmissy / scale;
pmissxsq = pmissxsq / scalesq;
pmissysq = pmissysq / scalesq;
mn = mn_unscale / scale;
mnsq = mn * mn;
if (ABSOLUTE_PRECISION > 100. * RELATIVE_PRECISION)
precision = ABSOLUTE_PRECISION;
else
precision = 100. * RELATIVE_PRECISION;
}
void Davismt2::set_mn(double mn0) {
solved = false; //reset solved tag when mn is changed.
mn_unscale = fabs(mn0); //mass cannot be negative
mn = mn_unscale / scale;
mnsq = mn * mn;
}
void Davismt2::print() {
cout << " Davismt2::print() ==> pax = " << pax * scale << "; pay = " << pay * scale << "; ma = " << ma * scale
<< ";" << endl;
cout << " Davismt2::print() ==> pbx = " << pbx * scale << "; pby = " << pby * scale << "; mb = " << mb * scale
<< ";" << endl;
cout << " Davismt2::print() ==> pmissx = " << pmissx * scale << "; pmissy = " << pmissy * scale << ";" << endl;
cout << " Davismt2::print() ==> mn = " << mn_unscale << ";" << endl;
}
//special case, the visible particle is massless
void Davismt2::mt2_massless() {
//rotate so that pay = 0
double theta, s, c;
theta = atan(pay / pax);
s = sin(theta);
c = cos(theta);
double pxtemp, pytemp;
Easq = pax * pax + pay * pay;
Ebsq = pbx * pbx + pby * pby;
Ea = sqrt(Easq);
Eb = sqrt(Ebsq);
pxtemp = pax * c + pay * s;
pax = pxtemp;
pay = 0;
pxtemp = pbx * c + pby * s;
pytemp = -s * pbx + c * pby;
pbx = pxtemp;
pby = pytemp;
pxtemp = pmissx * c + pmissy * s;
pytemp = -s * pmissx + c * pmissy;
pmissx = pxtemp;
pmissy = pytemp;
a2 = 1 - pbx * pbx / (Ebsq);
b2 = -pbx * pby / (Ebsq);
c2 = 1 - pby * pby / (Ebsq);
d21 = (Easq * pbx) / Ebsq;
d20 = -pmissx + (pbx * (pbx * pmissx + pby * pmissy)) / Ebsq;
e21 = (Easq * pby) / Ebsq;
e20 = -pmissy + (pby * (pbx * pmissx + pby * pmissy)) / Ebsq;
f22 = -(Easq * Easq / Ebsq);
f21 = -2 * Easq * (pbx * pmissx + pby * pmissy) / Ebsq;
f20 = mnsq + pmissxsq + pmissysq - (pbx * pmissx + pby * pmissy) * (pbx * pmissx + pby * pmissy) / Ebsq;
double Deltasq0 = 0;
double Deltasq_low, Deltasq_high;
int nsols_high, nsols_low;
Deltasq_low = Deltasq0 + precision;
nsols_low = nsols_massless(Deltasq_low);
if (nsols_low > 1) {
mt2_b = (double)sqrt(Deltasq0 + mnsq);
return;
}
/*
if( nsols_massless(Deltasq_high) > 0 )
{
mt2_b = (double) sqrt(mnsq+Deltasq0);
return;
}*/
//look for when both parablos contain origin
double Deltasq_high1, Deltasq_high2;
Deltasq_high1 = 2 * Eb * sqrt(pmissx * pmissx + pmissy * pmissy + mnsq) - 2 * pbx * pmissx - 2 * pby * pmissy;
Deltasq_high2 = 2 * Ea * mn;
if (Deltasq_high1 < Deltasq_high2)
Deltasq_high = Deltasq_high2;
else
Deltasq_high = Deltasq_high1;
nsols_high = nsols_massless(Deltasq_high);
int foundhigh;
if (nsols_high == nsols_low) {
foundhigh = 0;
double minmass, maxmass;
minmass = mn;
maxmass = sqrt(mnsq + Deltasq_high);
for (double mass = minmass + SCANSTEP; mass < maxmass; mass += SCANSTEP) {
Deltasq_high = mass * mass - mnsq;
nsols_high = nsols_massless(Deltasq_high);
if (nsols_high > 0) {
foundhigh = 1;
Deltasq_low = (mass - SCANSTEP) * (mass - SCANSTEP) - mnsq;
break;
}
}
if (foundhigh == 0) {
if (verbose > 0)
cout << "Davismt2::mt2_massless() ==> Deltasq_high not found at event " << nevt << endl;
mt2_b = (double)sqrt(Deltasq_low + mnsq);
return;
}
}
if (nsols_high == nsols_low) {
if (verbose > 0)
cout << "Davismt2::mt2_massless() ==> error: nsols_low=nsols_high=" << nsols_high << endl;
if (verbose > 0)
cout << "Davismt2::mt2_massless() ==> Deltasq_high=" << Deltasq_high << endl;
if (verbose > 0)
cout << "Davismt2::mt2_massless() ==> Deltasq_low= " << Deltasq_low << endl;
mt2_b = sqrt(mnsq + Deltasq_low);
return;
}
double minmass, maxmass;
minmass = sqrt(Deltasq_low + mnsq);
maxmass = sqrt(Deltasq_high + mnsq);
while (maxmass - minmass > precision) {
double Delta_mid, midmass, nsols_mid;
midmass = (minmass + maxmass) / 2.;
Delta_mid = midmass * midmass - mnsq;
nsols_mid = nsols_massless(Delta_mid);
if (nsols_mid != nsols_low)
maxmass = midmass;
if (nsols_mid == nsols_low)
minmass = midmass;
}
mt2_b = minmass;
return;
}
int Davismt2::nsols_massless(double Dsq) {
double delta;
delta = Dsq / (2 * Easq);
d1 = d11 * delta;
e1 = e11 * delta;
f1 = f12 * delta * delta + f10;
d2 = d21 * delta + d20;
e2 = e21 * delta + e20;
f2 = f22 * delta * delta + f21 * delta + f20;
double a, b;
if (pax > 0)
a = Ea / Dsq;
else
a = -Ea / Dsq;
if (pax > 0)
b = -Dsq / (4 * Ea) + mnsq * Ea / Dsq;
else
b = Dsq / (4 * Ea) - mnsq * Ea / Dsq;
double A4, A3, A2, A1, A0;
A4 = a * a * a2;
A3 = 2 * a * b2 / Ea;
A2 = (2 * a * a2 * b + c2 + 2 * a * d2) / (Easq);
A1 = (2 * b * b2 + 2 * e2) / (Easq * Ea);
A0 = (a2 * b * b + 2 * b * d2 + f2) / (Easq * Easq);
long double A3sq;
A3sq = A3 * A3;
/*
long double A0sq, A1sq, A2sq, A3sq, A4sq;
A0sq = A0*A0;
A1sq = A1*A1;
A2sq = A2*A2;
A3sq = A3*A3;
A4sq = A4*A4;
*/
long double B3, B2, B1, B0;
B3 = 4 * A4;
B2 = 3 * A3;
B1 = 2 * A2;
B0 = A1;
long double C2, C1, C0;
C2 = -(A2 / 2 - 3 * A3sq / (16 * A4));
C1 = -(3 * A1 / 4. - A2 * A3 / (8 * A4));
C0 = -A0 + A1 * A3 / (16 * A4);
long double D1, D0;
D1 = -B1 - (B3 * C1 * C1 / C2 - B3 * C0 - B2 * C1) / C2;
D0 = -B0 - B3 * C0 * C1 / (C2 * C2) + B2 * C0 / C2;
long double E0;
E0 = -C0 - C2 * D0 * D0 / (D1 * D1) + C1 * D0 / D1;
long double t1, t2, t3, t4, t5;
//find the coefficients for the leading term in the Sturm sequence
t1 = A4;
t2 = A4;
t3 = C2;
t4 = D1;
t5 = E0;
int nsol;
nsol = signchange_n(t1, t2, t3, t4, t5) - signchange_p(t1, t2, t3, t4, t5);
if (nsol < 0)
nsol = 0;
return nsol;
}
void Davismt2::mt2_bisect() {
solved = true;
cout.precision(11);
//if masses are very small, use code for massless case.
if (masq < MIN_MASS && mbsq < MIN_MASS) {
mt2_massless();
return;
}
double Deltasq0;
Deltasq0 = ma * (ma + 2 * mn); //The minimum mass square to have two ellipses
// find the coefficients for the two quadratic equations when Deltasq=Deltasq0.
a1 = 1 - pax * pax / (Easq);
b1 = -pax * pay / (Easq);
c1 = 1 - pay * pay / (Easq);
d1 = -pax * (Deltasq0 - masq) / (2 * Easq);
e1 = -pay * (Deltasq0 - masq) / (2 * Easq);
a2 = 1 - pbx * pbx / (Ebsq);
b2 = -pbx * pby / (Ebsq);
c2 = 1 - pby * pby / (Ebsq);
d2 = -pmissx + pbx * (Deltasq0 - mbsq) / (2 * Ebsq) + pbx * (pbx * pmissx + pby * pmissy) / (Ebsq);
e2 = -pmissy + pby * (Deltasq0 - mbsq) / (2 * Ebsq) + pby * (pbx * pmissx + pby * pmissy) / (Ebsq);
f2 = pmissx * pmissx + pmissy * pmissy -
((Deltasq0 - mbsq) / (2 * Eb) + (pbx * pmissx + pby * pmissy) / Eb) *
((Deltasq0 - mbsq) / (2 * Eb) + (pbx * pmissx + pby * pmissy) / Eb) +
mnsq;
// find the center of the smaller ellipse
double x0, y0;
x0 = (c1 * d1 - b1 * e1) / (b1 * b1 - a1 * c1);
y0 = (a1 * e1 - b1 * d1) / (b1 * b1 - a1 * c1);
// Does the larger ellipse contain the smaller one?
double dis = a2 * x0 * x0 + 2 * b2 * x0 * y0 + c2 * y0 * y0 + 2 * d2 * x0 + 2 * e2 * y0 + f2;
if (dis <= 0.01) {
mt2_b = (double)sqrt(mnsq + Deltasq0);
return;
}
/* find the coefficients for the two quadratic equations */
/* coefficients for quadratic terms do not change */
/* coefficients for linear and constant terms are polynomials of */
/* delta=(Deltasq-m7sq)/(2 E7sq) */
d11 = -pax;
e11 = -pay;
f10 = mnsq;
f12 = -Easq;
d21 = (Easq * pbx) / Ebsq;
d20 = ((masq - mbsq) * pbx) / (2. * Ebsq) - pmissx + (pbx * (pbx * pmissx + pby * pmissy)) / Ebsq;
e21 = (Easq * pby) / Ebsq;
e20 = ((masq - mbsq) * pby) / (2. * Ebsq) - pmissy + (pby * (pbx * pmissx + pby * pmissy)) / Ebsq;
f22 = -Easq * Easq / Ebsq;
f21 = (-2 * Easq * ((masq - mbsq) / (2. * Eb) + (pbx * pmissx + pby * pmissy) / Eb)) / Eb;
f20 = mnsq + pmissx * pmissx + pmissy * pmissy -
((masq - mbsq) / (2. * Eb) + (pbx * pmissx + pby * pmissy) / Eb) *
((masq - mbsq) / (2. * Eb) + (pbx * pmissx + pby * pmissy) / Eb);
//Estimate upper bound of mT2
//when Deltasq > Deltasq_high1, the larger encloses the center of the smaller
double p2x0, p2y0;
double Deltasq_high1;
p2x0 = pmissx - x0;
p2y0 = pmissy - y0;
Deltasq_high1 = 2 * Eb * sqrt(p2x0 * p2x0 + p2y0 * p2y0 + mnsq) - 2 * pbx * p2x0 - 2 * pby * p2y0 + mbsq;
//Another estimate, if both ellipses enclose the origin, Deltasq > mT2
double Deltasq_high2, Deltasq_high21, Deltasq_high22;
Deltasq_high21 =
2 * Eb * sqrt(pmissx * pmissx + pmissy * pmissy + mnsq) - 2 * pbx * pmissx - 2 * pby * pmissy + mbsq;
Deltasq_high22 = 2 * Ea * mn + masq;
if (Deltasq_high21 < Deltasq_high22)
Deltasq_high2 = Deltasq_high22;
else
Deltasq_high2 = Deltasq_high21;
//pick the smaller upper bound
double Deltasq_high;
if (Deltasq_high1 < Deltasq_high2)
Deltasq_high = Deltasq_high1;
else
Deltasq_high = Deltasq_high2;
double Deltasq_low; //lower bound
Deltasq_low = Deltasq0;
//number of solutions at Deltasq_low should not be larger than zero
if (nsols(Deltasq_low) > 0) {
//cout << "Davismt2::mt2_bisect() ==> nsolutions(Deltasq_low) > 0"<<endl;
mt2_b = (double)sqrt(mnsq + Deltasq0);
return;
}
int nsols_high, nsols_low;
nsols_low = nsols(Deltasq_low);
int foundhigh;
//if nsols_high=nsols_low, we missed the region where the two ellipse overlap
//if nsols_high=4, also need a scan because we may find the wrong tangent point.
nsols_high = nsols(Deltasq_high);
if (nsols_high == nsols_low || nsols_high == 4) {
//foundhigh = scan_high(Deltasq_high);
foundhigh = find_high(Deltasq_high);
if (foundhigh == 0) {
if (verbose > 0)
cout << "Davismt2::mt2_bisect() ==> Deltasq_high not found at event " << nevt << endl;
mt2_b = sqrt(Deltasq_low + mnsq);
return;
}
}
while (sqrt(Deltasq_high + mnsq) - sqrt(Deltasq_low + mnsq) > precision) {
double Deltasq_mid, nsols_mid;
//bisect
Deltasq_mid = (Deltasq_high + Deltasq_low) / 2.;
nsols_mid = nsols(Deltasq_mid);
// if nsols_mid = 4, rescan for Deltasq_high
if (nsols_mid == 4) {
Deltasq_high = Deltasq_mid;
//scan_high(Deltasq_high);
find_high(Deltasq_high);
continue;
}
if (nsols_mid != nsols_low)
Deltasq_high = Deltasq_mid;
if (nsols_mid == nsols_low)
Deltasq_low = Deltasq_mid;
}
mt2_b = (double)sqrt(mnsq + Deltasq_high);
return;
}
int Davismt2::find_high(double& Deltasq_high) {
double x0, y0;
x0 = (c1 * d1 - b1 * e1) / (b1 * b1 - a1 * c1);
y0 = (a1 * e1 - b1 * d1) / (b1 * b1 - a1 * c1);
double Deltasq_low = (mn + ma) * (mn + ma) - mnsq;
do {
double Deltasq_mid = (Deltasq_high + Deltasq_low) / 2.;
int nsols_mid = nsols(Deltasq_mid);
if (nsols_mid == 2) {
Deltasq_high = Deltasq_mid;
return 1;
} else if (nsols_mid == 4) {
Deltasq_high = Deltasq_mid;
continue;
} else if (nsols_mid == 0) {
d1 = -pax * (Deltasq_mid - masq) / (2 * Easq);
e1 = -pay * (Deltasq_mid - masq) / (2 * Easq);
d2 = -pmissx + pbx * (Deltasq_mid - mbsq) / (2 * Ebsq) + pbx * (pbx * pmissx + pby * pmissy) / (Ebsq);
e2 = -pmissy + pby * (Deltasq_mid - mbsq) / (2 * Ebsq) + pby * (pbx * pmissx + pby * pmissy) / (Ebsq);
f2 = pmissx * pmissx + pmissy * pmissy -
((Deltasq_mid - mbsq) / (2 * Eb) + (pbx * pmissx + pby * pmissy) / Eb) *
((Deltasq_mid - mbsq) / (2 * Eb) + (pbx * pmissx + pby * pmissy) / Eb) +
mnsq;
// Does the larger ellipse contain the smaller one?
double dis = a2 * x0 * x0 + 2 * b2 * x0 * y0 + c2 * y0 * y0 + 2 * d2 * x0 + 2 * e2 * y0 + f2;
if (dis < 0)
Deltasq_high = Deltasq_mid;
else
Deltasq_low = Deltasq_mid;
}
} while (Deltasq_high - Deltasq_low > 0.001);
return 0;
}
int Davismt2::scan_high(double& Deltasq_high) {
int foundhigh = 0;
int nsols_high;
// double Deltasq_low;
double tempmass, maxmass;
tempmass = mn + ma;
maxmass = sqrt(mnsq + Deltasq_high);
if (nevt == 32334)
cout << "Davismt2::scan_high() ==> Deltasq_high = " << Deltasq_high << endl; // ???
for (double mass = tempmass + SCANSTEP; mass < maxmass; mass += SCANSTEP) {
Deltasq_high = mass * mass - mnsq;
nsols_high = nsols(Deltasq_high);
if (nsols_high > 0) {
// Deltasq_low = (mass-SCANSTEP)*(mass-SCANSTEP) - mnsq;
foundhigh = 1;
break;
}
}
return foundhigh;
}
int Davismt2::nsols(double Dsq) {
double delta = (Dsq - masq) / (2 * Easq);
//calculate coefficients for the two quadratic equations
d1 = d11 * delta;
e1 = e11 * delta;
f1 = f12 * delta * delta + f10;
d2 = d21 * delta + d20;
e2 = e21 * delta + e20;
f2 = f22 * delta * delta + f21 * delta + f20;
//obtain the coefficients for the 4th order equation
//devided by Ea^n to make the variable dimensionless
long double A4, A3, A2, A1, A0;
A4 = -4 * a2 * b1 * b2 * c1 + 4 * a1 * b2 * b2 * c1 + a2 * a2 * c1 * c1 + 4 * a2 * b1 * b1 * c2 -
4 * a1 * b1 * b2 * c2 - 2 * a1 * a2 * c1 * c2 + a1 * a1 * c2 * c2;
A3 = (-4 * a2 * b2 * c1 * d1 + 8 * a2 * b1 * c2 * d1 - 4 * a1 * b2 * c2 * d1 - 4 * a2 * b1 * c1 * d2 +
8 * a1 * b2 * c1 * d2 - 4 * a1 * b1 * c2 * d2 - 8 * a2 * b1 * b2 * e1 + 8 * a1 * b2 * b2 * e1 +
4 * a2 * a2 * c1 * e1 - 4 * a1 * a2 * c2 * e1 + 8 * a2 * b1 * b1 * e2 - 8 * a1 * b1 * b2 * e2 -
4 * a1 * a2 * c1 * e2 + 4 * a1 * a1 * c2 * e2) /
Ea;
A2 = (4 * a2 * c2 * d1 * d1 - 4 * a2 * c1 * d1 * d2 - 4 * a1 * c2 * d1 * d2 + 4 * a1 * c1 * d2 * d2 -
8 * a2 * b2 * d1 * e1 - 8 * a2 * b1 * d2 * e1 + 16 * a1 * b2 * d2 * e1 + 4 * a2 * a2 * e1 * e1 +
16 * a2 * b1 * d1 * e2 - 8 * a1 * b2 * d1 * e2 - 8 * a1 * b1 * d2 * e2 - 8 * a1 * a2 * e1 * e2 +
4 * a1 * a1 * e2 * e2 - 4 * a2 * b1 * b2 * f1 + 4 * a1 * b2 * b2 * f1 + 2 * a2 * a2 * c1 * f1 -
2 * a1 * a2 * c2 * f1 + 4 * a2 * b1 * b1 * f2 - 4 * a1 * b1 * b2 * f2 - 2 * a1 * a2 * c1 * f2 +
2 * a1 * a1 * c2 * f2) /
Easq;
A1 = (-8 * a2 * d1 * d2 * e1 + 8 * a1 * d2 * d2 * e1 + 8 * a2 * d1 * d1 * e2 - 8 * a1 * d1 * d2 * e2 -
4 * a2 * b2 * d1 * f1 - 4 * a2 * b1 * d2 * f1 + 8 * a1 * b2 * d2 * f1 + 4 * a2 * a2 * e1 * f1 -
4 * a1 * a2 * e2 * f1 + 8 * a2 * b1 * d1 * f2 - 4 * a1 * b2 * d1 * f2 - 4 * a1 * b1 * d2 * f2 -
4 * a1 * a2 * e1 * f2 + 4 * a1 * a1 * e2 * f2) /
(Easq * Ea);
A0 = (-4 * a2 * d1 * d2 * f1 + 4 * a1 * d2 * d2 * f1 + a2 * a2 * f1 * f1 + 4 * a2 * d1 * d1 * f2 -
4 * a1 * d1 * d2 * f2 - 2 * a1 * a2 * f1 * f2 + a1 * a1 * f2 * f2) /
(Easq * Easq);
long double A3sq;
/*
long double A0sq, A1sq, A2sq, A3sq, A4sq;
A0sq = A0*A0;
A1sq = A1*A1;
A2sq = A2*A2;
A4sq = A4*A4;
*/
A3sq = A3 * A3;
long double B3, B2, B1, B0;
B3 = 4 * A4;
B2 = 3 * A3;
B1 = 2 * A2;
B0 = A1;
long double C2, C1, C0;
C2 = -(A2 / 2 - 3 * A3sq / (16 * A4));
C1 = -(3 * A1 / 4. - A2 * A3 / (8 * A4));
C0 = -A0 + A1 * A3 / (16 * A4);
long double D1, D0;
D1 = -B1 - (B3 * C1 * C1 / C2 - B3 * C0 - B2 * C1) / C2;
D0 = -B0 - B3 * C0 * C1 / (C2 * C2) + B2 * C0 / C2;
long double E0;
E0 = -C0 - C2 * D0 * D0 / (D1 * D1) + C1 * D0 / D1;
long double t1, t2, t3, t4, t5;
//find the coefficients for the leading term in the Sturm sequence
t1 = A4;
t2 = A4;
t3 = C2;
t4 = D1;
t5 = E0;
//The number of solutions depends on diffence of number of sign changes for x->Inf and x->-Inf
int nsol;
nsol = signchange_n(t1, t2, t3, t4, t5) - signchange_p(t1, t2, t3, t4, t5);
//Cannot have negative number of solutions, must be roundoff effect
if (nsol < 0)
nsol = 0;
return nsol;
}
//inline
int Davismt2::signchange_n(long double t1, long double t2, long double t3, long double t4, long double t5) {
int nsc;
nsc = 0;
if (t1 * t2 > 0)
nsc++;
if (t2 * t3 > 0)
nsc++;
if (t3 * t4 > 0)
nsc++;
if (t4 * t5 > 0)
nsc++;
return nsc;
}
//inline
int Davismt2::signchange_p(long double t1, long double t2, long double t3, long double t4, long double t5) {
int nsc;
nsc = 0;
if (t1 * t2 < 0)
nsc++;
if (t2 * t3 < 0)
nsc++;
if (t3 * t4 < 0)
nsc++;
if (t4 * t5 < 0)
nsc++;
return nsc;
}
} // namespace heppy
| 31.008696 | 171 | 0.509348 |
8e07bad7c48cced67ed1bb63bfa534f09f6a4132 | 1,964 | hpp | C++ | dev/Basic/long/database/entity/DevelopmentPlan.hpp | gusugusu1018/simmobility-prod | d30a5ba353673f8fd35f4868c26994a0206a40b6 | [
"MIT"
] | 50 | 2018-12-21T08:21:38.000Z | 2022-01-24T09:47:59.000Z | dev/Basic/long/database/entity/DevelopmentPlan.hpp | gusugusu1018/simmobility-prod | d30a5ba353673f8fd35f4868c26994a0206a40b6 | [
"MIT"
] | 2 | 2018-12-19T13:42:47.000Z | 2019-05-13T04:11:45.000Z | dev/Basic/long/database/entity/DevelopmentPlan.hpp | gusugusu1018/simmobility-prod | d30a5ba353673f8fd35f4868c26994a0206a40b6 | [
"MIT"
] | 27 | 2018-11-28T07:30:34.000Z | 2022-02-05T02:22:26.000Z | /*
* DevelopmentPlan.hpp
*
* Created on: Dec 22, 2015
* Author: gishara
*/
#pragma once
#include "Common.hpp"
#include "Types.hpp"
namespace sim_mob {
namespace long_term {
class DevelopmentPlan {
public:
DevelopmentPlan(BigSerial fmParcelId = INVALID_ID, BigSerial templateId = INVALID_ID,int unitTypeId = 0, int numUnits = 0, std::tm simulationDate = std::tm(), std::tm constructionStartDate = std::tm(), std::tm launchDate = std::tm());
virtual ~DevelopmentPlan();
DevelopmentPlan( const DevelopmentPlan &source);
/**
* Assign operator.
* @param source to assign.
* @return DevelopmentPlan instance reference.
*/
DevelopmentPlan& operator=(const DevelopmentPlan& source);
/**
* Getters and Setters
*/
BigSerial getFmParcelId() const;
int getNumUnits() const;
const std::tm& getSimulationDate() const;
int getUnitTypeId() const;
const std::tm& getLaunchDate() const;
const std::tm& getConstructionStartDate() const;
BigSerial getTemplateId() const;
void setFmParcelId(BigSerial fmParcelId);
void setNumUnits(int numUnits);
void setSimulationDate(const std::tm& simulationDate);
void setUnitTypeId(int unitTypeId);
void setLaunchDate(const std::tm& launchDate);
void setConstructionStartDate(const std::tm& constructionStartDate) ;
void setTemplateId(BigSerial templateId);
private:
friend class DevelopmentPlanDao;
private:
BigSerial fmParcelId;
BigSerial templateId;
int unitTypeId;
int numUnits;
std::tm simulationDate;
std::tm constructionStartDate;
std::tm launchDate;
};
}
}
| 31.677419 | 246 | 0.586049 |
8e088785a57c9cdd56c5d1336d4b561c74e6883d | 5,064 | cxx | C++ | TOF/TOFbase/AliTOFRawMap.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | TOF/TOFbase/AliTOFRawMap.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | TOF/TOFbase/AliTOFRawMap.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | /**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
/////////////////////////////////////////////////////////////////////////
// //
// AliTOFRawMap class //
// //
// It enables fast check if the TDC channel was already engaged //
// for a measurement. //
// The index of a AliTOFrawData is saved in the each rawdatamap "cell" //
// (there is an offset +1, because the index can be zero and //
// zero means empty cell. //
// //
/////////////////////////////////////////////////////////////////////////
#include "TClonesArray.h"
#include "AliLog.h"
#include "AliTOFGeometry.h"
#include "AliTOFRawMap.h"
ClassImp(AliTOFRawMap)
AliTOFRawMap::AliTOFRawMap():
TObject(),
fNtrm(-1),
fNtrmChain(-1),
fNtdc(-1),
fNtdcChannel(-1),
fRawData(0x0),
fMaxIndex(-1),
fRawMap(0x0)
{
//
// Default ctor
//
}
////////////////////////////////////////////////////////////////////////
AliTOFRawMap::AliTOFRawMap(TClonesArray *dig)://, AliTOFGeometry *tofGeom:
TObject(),
fNtrm(AliTOFGeometry::NTRM()+2),
fNtrmChain(AliTOFGeometry::NChain()),
fNtdc(AliTOFGeometry::NTdc()),
fNtdcChannel(AliTOFGeometry::NCh()),
fRawData(dig),
fMaxIndex(-1),
fRawMap(0x0)
{
//
// ctor
//
// of course, these constants must not be hardwired
// change later
fMaxIndex = fNtrm*fNtrmChain*fNtdc*fNtdcChannel;
fRawMap = new Int_t[fMaxIndex];
Clear();
}
////////////////////////////////////////////////////////////////////////
AliTOFRawMap::~AliTOFRawMap()
{
//
// Destructor
//
if (fRawMap)
delete[] fRawMap;
}
////////////////////////////////////////////////////////////////////////
void AliTOFRawMap::Clear(const char *)
{
//
// Clear hitmap
//
memset(fRawMap,0,sizeof(int)*fMaxIndex);
}
////////////////////////////////////////////////////////////////////////
Int_t AliTOFRawMap::CheckedIndex(const Int_t * const slot) const
{
//
// Return checked indices for vol
//
Int_t index =
slot[0]*fNtrmChain*fNtdc*fNtdcChannel + // TRM
slot[1]*fNtdc*fNtdcChannel + // TRM chain
slot[2]*fNtdcChannel + // TDC
slot[3]; // TDC channel
if (index >= fMaxIndex) {
AliError("CheckedIndex - input outside bounds");
return -1;
} else {
return index;
}
}
////////////////////////////////////////////////////////////////////////
void AliTOFRawMap::SetHit(Int_t *slot, Int_t idigit)
{
//
// Assign digit to pad vol
//
// 0 means empty pad, we need to shift indeces by 1
fRawMap[CheckedIndex(slot)]=idigit+1;
}
////////////////////////////////////////////////////////////////////////
void AliTOFRawMap::SetHit(Int_t *slot)
{
//
// Assign last digit to channel slot
//
// 0 means empty pad, we need to shift indeces by 1
fRawMap[CheckedIndex(slot)]=fRawData->GetLast()+1;
}
////////////////////////////////////////////////////////////////////////
Int_t AliTOFRawMap::GetHitIndex(Int_t *slot) const
{
//
// Get contents of channel slot
//
// 0 means empty pad, we need to shift indeces by 1
return fRawMap[CheckedIndex(slot)]-1;
}
////////////////////////////////////////////////////////////////////////
TObject* AliTOFRawMap::GetHit(Int_t *slot) const
{
//
// Get pointer to object at alot
// return 0 if vol out of bounds
Int_t index = GetHitIndex(slot);
return (index <0) ? 0 : fRawData->UncheckedAt(index);
}
////////////////////////////////////////////////////////////////////////
FlagType AliTOFRawMap::TestHit(Int_t *slot) const
{
//
// Check if hit cell is empty, used or unused
//
Int_t inf = fRawMap[CheckedIndex(slot)];
if (inf > 0) {
return kUsed;
} else if (inf == 0) {
return kEmpty;
} else {
return kUnused;
}
}
| 28.772727 | 76 | 0.463073 |
8e08daffcf5d0d0d495089a41cb8900f3d15d331 | 650 | cpp | C++ | Chapter_13/Figures/Fig_13_8.cpp | mtrdazzo/Deitel | 4efc02147a1768125d2e27d7d68f664c4628cdc5 | [
"MIT"
] | 1 | 2021-09-07T19:23:24.000Z | 2021-09-07T19:23:24.000Z | Chapter_13/Figures/Fig_13_8.cpp | mtrdazzo/Deitel | 4efc02147a1768125d2e27d7d68f664c4628cdc5 | [
"MIT"
] | null | null | null | Chapter_13/Figures/Fig_13_8.cpp | mtrdazzo/Deitel | 4efc02147a1768125d2e27d7d68f664c4628cdc5 | [
"MIT"
] | null | null | null | /**
* @file Fig_13_8.cpp
* @author Matthew J Randazzo (mtrdazzo@gmail.com)
* @brief width member function of classes istream and ostream
* @version 0.1
* @date 2020-07-19
*
* @copyright Copyright (c) 2020
*
*/
#include <iostream>
int main() {
int widthValue{4};
char sentence[10];
std::cout << "Enter a sequence:\n";
std::cin.width(5); // input only 5 characters from sentence
// set field width, then display characters based on that width
while (std::cin >> sentence) {
std::cout.width(widthValue++);
std::cout << sentence << "\n";
std::cin.width(5);
}
return EXIT_SUCCESS;
} | 21.666667 | 67 | 0.615385 |
8e09c3050af11576e808b35c4254aa250b22992a | 3,437 | cpp | C++ | Trees/BinaryTree/foldablebinarytree/foldablebinarytree.cpp | UltraProton/Placement-Prepration | cc70f174c4410c254ce0469737a884fffdc81164 | [
"MIT"
] | null | null | null | Trees/BinaryTree/foldablebinarytree/foldablebinarytree.cpp | UltraProton/Placement-Prepration | cc70f174c4410c254ce0469737a884fffdc81164 | [
"MIT"
] | 3 | 2020-05-08T18:02:51.000Z | 2020-05-09T08:37:35.000Z | Trees/BinaryTree/foldablebinarytree/foldablebinarytree.cpp | UltraProton/PlacementPrep | cc70f174c4410c254ce0469737a884fffdc81164 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
/* You would want to remove below 3 lines if your compiler
supports bool, true and false */
#define bool int
#define true 1
#define false 0
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
node(int x){
data = x;
left = right = NULL;
}
};
/* converts a tree to its mrror image */
void mirror(struct node* node);
/* returns true if structure of two trees a and b is same
Only structure is considered for comparison, not data! */
bool isStructSame(struct node *a, struct node *b);
/* Returns true if the given tree is foldable */
bool isFoldable(struct node *root);
/* UTILITY FUNCTIONS */
/* Change a tree so that the roles of the left and
right pointers are swapped at every node.
See http://www.geeksforgeeks.org/?p=662 for details */
void mirror(struct node* node)
{
if (node==NULL)
return;
else
{
struct node* temp;
/* do the subtrees */
mirror(node->left);
mirror(node->right);
/* swap the pointers in this node */
temp = node->left;
node->left = node->right;
node->right = temp;
}
}
void insert(struct node *root,int n1,int n2,char lr)
{
if(root==NULL)
return;
if(root->data==n1)
{
switch(lr)
{
case 'L': root->left=new node(n2);
break;
case 'R': root->right=new node(n2);
break;
}
}
else
{
insert(root->left,n1,n2,lr);
insert(root->right,n1,n2,lr);
}
}
/* Driver program to test mirror() */
int main(void)
{
/* The constructed binary tree is
1
/ \
2 3
\ /
4 5
*/
int t,k;
cin>>t;
while(t--)
{
int n;
cin>>n;
struct node *root=NULL;
while(n--)
{
char lr;
int n1,n2;
cin>>n1>>n2;
cin>>lr;
if(root==NULL)
{
root=new node(n1);
switch(lr){
case 'L': root->left=new node(n2);
break;
case 'R': root->right=new node(n2);
break;
}
}
else
{
insert(root,n1,n2,lr);
}
}
if(isFoldable(root) == 1)
{ cout<<"Yes"<<endl; }
else
{ cout<<"No"<<endl; }
getchar();
}
return 0;
}
/*This is a function problem.You only need to complete the function given below*/
/* Returns true if the given tree is foldable */
/* A binary tree node has data, pointer to left child
and a pointer to right child */
bool is_structurally_symmetric(struct node *a ,struct node *b){
if(!a && !b){
return true;
}
if(!a || !b){
return false;
}
bool l_ans= is_structurally_symmetric(a->left,b->right);
bool r_ans= is_structurally_symmetric(a->right, b->left);
if(l_ans && r_ans){
return true;
}
else{
return false;
}
}
bool isFoldable(struct node *root){
// if(root){
// bool x= is_structurally_symmetric(root->left, root->right);
// bool l_ans= isFoldable(root->left);
// bool r_ans= isFoldable(root->right);
// if(l_ans && r_ans){
// return true;
// }
// else{
// return false;
// }
// }
// return false;
bool ans= is_structurally_symmetric(root->left, root->right);
return ans;
} | 21.347826 | 81 | 0.551644 |
8e0a7e06d8dc19dff9e3ddc30d095372b9ce0452 | 26 | cpp | C++ | tests/environment.cpp | TheQuantumPhysicist/HttpRpcRelay | 810d9ed8907b4c769faa432ba7f829445b8d6f9f | [
"MIT"
] | null | null | null | tests/environment.cpp | TheQuantumPhysicist/HttpRpcRelay | 810d9ed8907b4c769faa432ba7f829445b8d6f9f | [
"MIT"
] | null | null | null | tests/environment.cpp | TheQuantumPhysicist/HttpRpcRelay | 810d9ed8907b4c769faa432ba7f829445b8d6f9f | [
"MIT"
] | null | null | null | #include "environment.h"
| 13 | 25 | 0.730769 |
8e0b642cd53e9e136944340e6f8368a9ae096647 | 3,381 | cpp | C++ | TAO/tests/Bug_3748_Regression/Test_Protocols_Hooks.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 36 | 2015-01-10T07:27:33.000Z | 2022-03-07T03:32:08.000Z | TAO/tests/Bug_3748_Regression/Test_Protocols_Hooks.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 2 | 2018-08-13T07:30:51.000Z | 2019-02-25T03:04:31.000Z | TAO/tests/Bug_3748_Regression/Test_Protocols_Hooks.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 38 | 2015-01-08T14:12:06.000Z | 2022-01-19T08:33:00.000Z | // -*- C++ -*-
//
// $Id: Test_Protocols_Hooks.cpp 91648 2010-09-08 13:25:56Z johnnyw $
//
#include "Test_Protocols_Hooks.h"
#include "TestC.h"
Test_Protocols_Hooks::Test_Protocols_Hooks (void)
: failure_count_ (0)
{
}
Test_Protocols_Hooks::~Test_Protocols_Hooks (void)
{
}
void
Test_Protocols_Hooks::init_hooks (TAO_ORB_Core *)
{
// No-op.
}
CORBA::Boolean
Test_Protocols_Hooks::set_client_network_priority (IOP::ProfileId,
TAO_Stub *)
{
return false;
}
CORBA::Boolean
Test_Protocols_Hooks::set_server_network_priority (IOP::ProfileId,
CORBA::Policy *)
{
return false;
}
void
Test_Protocols_Hooks::server_protocol_properties_at_orb_level (
TAO_IIOP_Protocol_Properties &)
{
if (++this->failure_count_ < Test::expected_failure_number)
throw ::CORBA::INTERNAL ();
}
void
Test_Protocols_Hooks::client_protocol_properties_at_orb_level (
TAO_IIOP_Protocol_Properties &)
{
// No-op.
}
void
Test_Protocols_Hooks::server_protocol_properties_at_orb_level (
TAO_UIOP_Protocol_Properties &)
{
// No-op.
}
void
Test_Protocols_Hooks::client_protocol_properties_at_orb_level (
TAO_UIOP_Protocol_Properties &)
{
// No-op.
}
void
Test_Protocols_Hooks::server_protocol_properties_at_orb_level (
TAO_SHMIOP_Protocol_Properties &)
{
// No-op.
}
void
Test_Protocols_Hooks::client_protocol_properties_at_orb_level (
TAO_SHMIOP_Protocol_Properties &)
{
// No-op.
}
void
Test_Protocols_Hooks::server_protocol_properties_at_orb_level (
TAO_DIOP_Protocol_Properties &)
{
// No-op.
}
void
Test_Protocols_Hooks::client_protocol_properties_at_orb_level (
TAO_DIOP_Protocol_Properties &)
{
// No-op.
}
void
Test_Protocols_Hooks::server_protocol_properties_at_orb_level (
TAO_SCIOP_Protocol_Properties &)
{
// No-op.
}
void
Test_Protocols_Hooks::client_protocol_properties_at_orb_level (
TAO_SCIOP_Protocol_Properties &)
{
// No-op.
}
CORBA::Long
Test_Protocols_Hooks::get_dscp_codepoint (void)
{
return -1;
}
void
Test_Protocols_Hooks::get_selector_hook (
CORBA::Policy *,
CORBA::Boolean &,
CORBA::Short &)
{
// No-op.
}
void
Test_Protocols_Hooks::get_selector_bands_policy_hook (
CORBA::Policy *,
CORBA::Short,
CORBA::Short &,
CORBA::Short &,
bool &
)
{
// No-op.
}
int
Test_Protocols_Hooks::get_thread_CORBA_priority (CORBA::Short &)
{
return -1;
}
int
Test_Protocols_Hooks::get_thread_native_priority (
CORBA::Short &)
{
return -1;
}
int
Test_Protocols_Hooks::get_thread_CORBA_and_native_priority (
CORBA::Short &,
CORBA::Short &)
{
return -1;
}
int
Test_Protocols_Hooks::get_thread_implicit_CORBA_priority (CORBA::Short &)
{
return -1;
}
int
Test_Protocols_Hooks::restore_thread_CORBA_and_native_priority (
CORBA::Short,
CORBA::Short
)
{
return -1;
}
int
Test_Protocols_Hooks::set_thread_CORBA_priority (CORBA::Short)
{
return -1;
}
ACE_STATIC_SVC_DEFINE (Test_Protocols_Hooks,
ACE_TEXT ("Test_Protocols_Hooks"),
ACE_SVC_OBJ_T,
&ACE_SVC_NAME (Test_Protocols_Hooks),
ACE_Service_Type::DELETE_THIS
| ACE_Service_Type::DELETE_OBJ,
0)
ACE_FACTORY_DEFINE (ACE_Local_Service, Test_Protocols_Hooks)
| 18.080214 | 73 | 0.696539 |
8e0b9590dd090921dfd51bf8831426402488f77c | 1,115 | hpp | C++ | src/volt/gpu/d3d12/d3d12.hpp | voltengine/volt | fbefe2e0a8e461b6130ffe926870c4848bd6e7d1 | [
"MIT"
] | null | null | null | src/volt/gpu/d3d12/d3d12.hpp | voltengine/volt | fbefe2e0a8e461b6130ffe926870c4848bd6e7d1 | [
"MIT"
] | null | null | null | src/volt/gpu/d3d12/d3d12.hpp | voltengine/volt | fbefe2e0a8e461b6130ffe926870c4848bd6e7d1 | [
"MIT"
] | null | null | null | #pragma once
#include <volt/gpu/enums.hpp>
namespace volt::gpu::d3d12 {
extern std::unordered_map<HRESULT, std::string> result_messages;
extern std::unordered_map<command_types, D3D12_COMMAND_LIST_TYPE> command_list_types;
template<command_types T>
constexpr D3D12_COMMAND_LIST_TYPE command_list_type;
template<>
constexpr D3D12_COMMAND_LIST_TYPE command_list_type<command_type::rasterization> = D3D12_COMMAND_LIST_TYPE_DIRECT;
template<>
constexpr D3D12_COMMAND_LIST_TYPE command_list_type<command_type::compute> = D3D12_COMMAND_LIST_TYPE_COMPUTE;
template<>
constexpr D3D12_COMMAND_LIST_TYPE command_list_type<command_type::copy> = D3D12_COMMAND_LIST_TYPE_COPY;
extern std::unordered_map<memory_type, D3D12_HEAP_TYPE> heap_types;
}
#define VOLT_D3D12_CHECK(expression, message)\
{\
::HRESULT result = expression;\
VOLT_ASSERT(result == S_OK, message + ('\n' + ::volt::gpu::d3d12::result_messages[result]))\
}
#ifdef VOLT_GPU_DEBUG
#define VOLT_D3D12_DEBUG_CHECK(expression, message) VOLT_D3D12_CHECK(expression, message)
#else
#define VOLT_D3D12_DEBUG_CHECK(expression, message) expression;
#endif
| 30.135135 | 114 | 0.821525 |
8e0f910636ef878151394c403e6a3de3879d1de8 | 401 | cpp | C++ | exemplos/5_Repeticao/soma-ate-0.cpp | danielgs83/cpe-unb | f958d2a4899a8d4d5c1465637d1d1b10610661e4 | [
"CC0-1.0"
] | 1 | 2022-02-04T17:16:50.000Z | 2022-02-04T17:16:50.000Z | exemplos/5_Repeticao/soma-ate-0.cpp | danielgs83/cpe-unb | f958d2a4899a8d4d5c1465637d1d1b10610661e4 | [
"CC0-1.0"
] | null | null | null | exemplos/5_Repeticao/soma-ate-0.cpp | danielgs83/cpe-unb | f958d2a4899a8d4d5c1465637d1d1b10610661e4 | [
"CC0-1.0"
] | null | null | null | #include <iostream>
using namespace std;
int main() {
int soma, parcela;
soma = 0;
cout << "numero a ser somado (0 para sair): ";
cin >> parcela; //leitura do primeiro numero
while (parcela != 0) {
soma += parcela; //acumula
cout << "numero a ser somado (0 para sair): ";
cin >> parcela; //leitura do proximo numero
}
cout << "Soma: " << soma << endl;
return 0;
}
| 17.434783 | 50 | 0.586035 |
8e0ffef18e846b6a08b69ae0c7a5c108185c7c95 | 2,027 | cpp | C++ | cpp/backtracking/The_knights_tour_problem.cpp | banerjeesoumya15/AlgoBook | 79fcbd0631a6f1fbe24a8d3627550d1ec9ad605c | [
"MIT"
] | 191 | 2020-09-28T10:00:20.000Z | 2022-03-06T14:36:55.000Z | cpp/backtracking/The_knights_tour_problem.cpp | banerjeesoumya15/AlgoBook | 79fcbd0631a6f1fbe24a8d3627550d1ec9ad605c | [
"MIT"
] | 210 | 2020-09-28T10:06:36.000Z | 2022-03-05T03:44:24.000Z | cpp/backtracking/The_knights_tour_problem.cpp | banerjeesoumya15/AlgoBook | 79fcbd0631a6f1fbe24a8d3627550d1ec9ad605c | [
"MIT"
] | 320 | 2020-09-28T09:56:14.000Z | 2022-02-12T16:45:57.000Z | #include <bits/stdc++.h>
using namespace std;
//a function to check whether a grid is valid or not
bool isvalid(int x, int y, int **tour, int n){
return(x>=0 && y>=0 && x<n && y<n && tour[x][y]==-1);
}
//function to solve the tour
bool solve_knighttour(int x, int y, int moves,int n, int **tour, int nxt_x[8], int nxt_y[8]){
//if moves are equal to no of grids then solved (base case)
if(moves==n*n){
return true;
}
//variables for the next grid
int new_x, new_y;
for(int k=0; k<n; k++){
//updating next grid
new_x = x + nxt_x[k];
new_y = y + nxt_y[k];
//checking for validity
if(isvalid(new_x, new_y, tour, n)){
tour[new_x][new_y] = moves;
if(solve_knighttour(new_x, new_y, moves+1, n, tour, nxt_x, nxt_y))
return true;
else
//back tracking
tour[new_x][new_y] = -1;
}
}
//if not found return false
return false;
}
//function to print the solution
void print(int **tour,int n){
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
cout << tour[i][j] <<" ";
}
cout << endl;
}
}
int main(){
int n = 8;
int **tour = new int *[n]; //matrix for the knights tour
for(int i=0; i<n; i++){
tour[i] = new int [n];
for(int j=0; j<n; j++){
tour[i][j] = -1; //mark all the points as -1
}
}
//knight is initially here(0,0)
tour[0][0] = 0;
//next coordinates of x and y for the knight
int nxt_x_move[8] = {2, 1, -1, -2, -2, -1, 1, 2};
int nxt_y_move[8] = {1, 2, 2, 1, -1, -2, -2, -1};
//start exploring the matrix by function call starting from (0,0)
if(solve_knighttour(0, 0, 1, n, tour, nxt_x_move, nxt_y_move)){
//if the tour exists then a function call for printing.
print(tour, n);
return 0;
}
else{
cout << "No tour found!!" <<endl;
}
return 0;
}
| 27.767123 | 93 | 0.510607 |
8e11f514fbf9d3a021bc436e68abee51dd29ae11 | 3,955 | cpp | C++ | tests/TestWord.cpp | SergioRosello/OSO | bbd3c6a95b1c2388732babc6a540c07034cce026 | [
"MIT"
] | 1 | 2019-10-14T07:25:32.000Z | 2019-10-14T07:25:32.000Z | tests/TestWord.cpp | SergioRosello/OSO | bbd3c6a95b1c2388732babc6a540c07034cce026 | [
"MIT"
] | null | null | null | tests/TestWord.cpp | SergioRosello/OSO | bbd3c6a95b1c2388732babc6a540c07034cce026 | [
"MIT"
] | null | null | null | #include "gtest/gtest.h"
#include "../include/Selection.h"
namespace OSO {
// The fixture for testing class Foo.
class WordTest : public ::testing::Test {
protected:
// You can remove any or all of the following functions if its body
// is empty.
WordTest() {
// You can do set-up work for each test here.
}
~WordTest() override {
// You can do clean-up work that doesn't throw exceptions here.
}
// If the constructor and destructor are not enough for setting up
// and cleaning up each test, you can define the following methods:
void SetUp() override {
// Code here will be called immediately after the constructor (right
// before each test).
}
void TearDown() override {
// Code here will be called immediately after each test (right
// before the destructor).
}
// Objects declared here can be used by all tests in the test suite for Foo.
};
TEST_F(WordTest, CheckWordSizeIsCorrect) {
Cell firstLetter = Cell(Coordinates(0, 3), 'H');
Cell secondLetter = Cell(Coordinates(0, 2), 'O');
Cell thirdLetter = Cell(Coordinates(0, 1), 'L');
Cell lastLetter = Cell(Coordinates(0, 0), 'A');
Selection word = Selection(firstLetter, lastLetter);
EXPECT_EQ(word.GetSize(), 4);
}
TEST_F(WordTest, CheckWordOrientationSizeIsCorrect) {
// North
Cell firstNorthLetter = Cell(Coordinates(0, 2), 'O');
Cell secondNorthLetter = Cell(Coordinates(0, 1), 'S');
Cell thirdNorthLetter = Cell(Coordinates(0, 0), 'O');
Selection northWord = Selection(firstNorthLetter, thirdNorthLetter);
EXPECT_EQ(northWord.GetSize(), 3);
// North-East
Cell firstNorthEastLetter = Cell(Coordinates(0, 2), 'O');
Cell secondNorthEastLetter = Cell(Coordinates(1, 2), 'S');
Cell thirdNorthEastLetter = Cell(Coordinates(2, 0), 'O');
Selection northEastWord = Selection(firstNorthEastLetter, thirdNorthEastLetter);
EXPECT_EQ(northEastWord.GetSize(), 3);
// East
Cell firstEastLetter = Cell(Coordinates(0, 0), 'O');
Cell secondEastLetter = Cell(Coordinates(1, 0), 'S');
Cell thirdEastLetter = Cell(Coordinates(2, 0), 'O');
Selection eastWord = Selection(firstEastLetter, thirdEastLetter);
EXPECT_EQ(eastWord.GetSize(), 3);
// South-East
Cell firstSouthEastLetter = Cell(Coordinates(0, 0), 'O');
Cell secondSouthEastLetter = Cell(Coordinates(1, 1), 'S');
Cell thirdSouthEastLetter = Cell(Coordinates(2, 2), 'O');
Selection southEastWord = Selection(firstSouthEastLetter, thirdSouthEastLetter);
EXPECT_EQ(southEastWord.GetSize(), 3);
// South
Cell firstSouthLetter = Cell(Coordinates(0, 0), 'O');
Cell secondSouthLetter = Cell(Coordinates(0, 1), 'S');
Cell thirdSouthLetter = Cell(Coordinates(0, 2), 'O');
Selection southWord = Selection(firstSouthLetter, thirdSouthLetter);
EXPECT_EQ(southWord.GetSize(), 3);
// Sout-West
Cell firstSouthWestLetter = Cell(Coordinates(2, 0), 'O');
Cell secondSouthWestLetter = Cell(Coordinates(1, 1), 'S');
Cell thirdSouthWestLetter = Cell(Coordinates(0, 2), 'O');
Selection southWestWord = Selection(firstSouthWestLetter, thirdSouthWestLetter);
EXPECT_EQ(southWestWord.GetSize(), 3);
// West
Cell firstWestLetter = Cell(Coordinates(2, 0), 'O');
Cell secondWestLetter = Cell(Coordinates(1, 0), 'S');
Cell thirdWestLetter = Cell(Coordinates(0, 0), 'O');
Selection westWord = Selection(firstWestLetter, thirdWestLetter);
EXPECT_EQ(westWord.GetSize(), 3);
// North-West
Cell firstNorthWestLetter = Cell(Coordinates(2, 2), 'O');
Cell secondNorthWestLetter = Cell(Coordinates(1, 1), 'S');
Cell thirdNorthWestLetter = Cell(Coordinates(0, 0), 'O');
Selection northWestWord = Selection(firstNorthWestLetter, thirdNorthWestLetter);
EXPECT_EQ(northWestWord.GetSize(), 3);
}
} // namespace
| 34.692982 | 84 | 0.672566 |
8e1250f35886ace8a9135303cfb8532ee7dde5fb | 4,415 | cpp | C++ | src/test/git/TestGitClientImpl.cpp | TNG/mustard-cli | aa8db4e923271546b46a1f9a71778b3bed1efe3a | [
"Apache-2.0"
] | 7 | 2019-04-12T07:13:32.000Z | 2021-09-22T20:53:44.000Z | src/test/git/TestGitClientImpl.cpp | TNG/mustard-cli | aa8db4e923271546b46a1f9a71778b3bed1efe3a | [
"Apache-2.0"
] | 2 | 2020-07-21T05:01:13.000Z | 2020-08-14T15:38:17.000Z | src/test/git/TestGitClientImpl.cpp | TNG/mustard-cli | aa8db4e923271546b46a1f9a71778b3bed1efe3a | [
"Apache-2.0"
] | 1 | 2020-07-21T05:03:09.000Z | 2020-07-21T05:03:09.000Z | #include <gtest/gtest.h>
#include <Depend.h>
#include "../../main/git/GitClientImpl.h"
#include "GitTestEnvironment.h"
using namespace testing;
class TestGitClientImpl: public Test
{
public:
GitClientImpl gitClient;
};
TEST_F ( TestGitClientImpl, Unit_GetHeadCommit )
{
GitTestEnvironment testEnv;
testEnv.createFileAndCommit ( "test" );
EXPECT_TRUE ( gitClient.workingDirectoryIsClean() );
}
TEST_F ( TestGitClientImpl, Unit_WorkingDirIsClean_No )
{
GitTestEnvironment testEnv;
testEnv.createFileAndCommit ( "test" );
testEnv.run ( "touch anotherone" );
EXPECT_FALSE ( gitClient.workingDirectoryIsClean() );
}
TEST_F ( TestGitClientImpl, Unit_FindMergeBase )
{
GitTestEnvironment testEnv;
testEnv.createFileAndCommit ( "test" );
const Commitish expectedMergeBase = gitClient.getHeadCommit();
testEnv.run ( "git checkout -q -b feature" );
testEnv.createFileAndCommit ( "featureFile" );
testEnv.run ( "git checkout -q master" );
testEnv.createFileAndCommit ( "masterDevelopment" );
EXPECT_STRNE ( expectedMergeBase.c_str(), gitClient.getHeadCommit().c_str() );
const Commitish mergeBase = gitClient.getMergeBase ( "feature", "master" );
EXPECT_STREQ ( expectedMergeBase.c_str(), mergeBase.c_str() );
}
TEST_F ( TestGitClientImpl, Unit_GitReset )
{
GitTestEnvironment testEnv;
testEnv.createFileAndCommit ( "someFile" );
testEnv.createFileAndCommit ( "someOtherFile" );
EXPECT_TRUE ( gitClient.workingDirectoryIsClean() );
testEnv.run ( "git branch future" );
gitClient.reset ( "HEAD^" );
testEnv.run ( "touch someOtherFile" );
EXPECT_FALSE ( gitClient.workingDirectoryIsClean() );
gitClient.reset ( "future" );
EXPECT_TRUE ( gitClient.workingDirectoryIsClean() );
}
TEST_F ( TestGitClientImpl, Unit_GetConfigValue )
{
GitTestEnvironment testEnv;
const string expectedValue = "someValue";
const string keyPath = "category.key";
testEnv.run ( "git config --add " + keyPath + " " + expectedValue );
const string valueFromConfig = gitClient.getConfigValue ( keyPath );
EXPECT_STREQ ( expectedValue.c_str(), valueFromConfig.c_str() );
}
TEST_F ( TestGitClientImpl, Unit_GetDiff )
{
GitTestEnvironment testEnv;
testEnv.createFileAndCommit ( "myFile" );
testEnv.run ( "echo someMoreContent >> myFile" );
testEnv.run ( "git commit -m 'some more stuff'" );
testEnv.run ( "echo lessContent >> myFile" );
const string diff = gitClient.getDiff();
const string expectedDiff = "diff --git a/myFile b/myFile\n"
"index e69de29..6924897 100644\n"
"--- a/myFile\n"
"+++ b/myFile\n"
"@@ -0,0 +1,2 @@\n"
"+someMoreContent\n"
"+lessContent\n"
"";
EXPECT_STREQ ( expectedDiff.c_str(), diff.c_str() );
}
TEST_F ( TestGitClientImpl, Unit_getFeatureBranchOnOrigin )
{
GitTestEnvironment testEnv;
GitTestEnvironment remoteEnv ( "/tmp/remoteTestEnv" );
testEnv.run ( "git remote add origin /tmp/remoteTestEnv" );
testEnv.createFileAndCommit ( "testFile" );
testEnv.run ( "git checkout -b feature 2>/dev/null" );
testEnv.createFileAndCommit ( "anotherTestFile" );
testEnv.run ( "git push -u origin HEAD 2>/dev/null" );
const Commitish featureCommit ( gitClient.getHeadCommit() );
testEnv.createFileAndCommit ( "yetAnotherTestFile" );
ASSERT_EQ ( featureCommit, gitClient.getFeatureBranchOnOrigin() );
ASSERT_NE ( featureCommit, gitClient.getHeadCommit() );
}
TEST_F ( TestGitClientImpl, Unit_getFeatureBranchOnOrigin_CommitMessageWithBrackets )
{
GitTestEnvironment testEnv;
GitTestEnvironment remoteEnv ( "/tmp/remoteTestEnv" );
testEnv.run ( "git remote add origin /tmp/remoteTestEnv" );
testEnv.createFileAndCommit ( "testFile" );
testEnv.run ( "git checkout -b feature 2>/dev/null" );
testEnv.run ( "touch anotherTestFile" );
testEnv.run ( "git add anotherTestFile" );
testEnv.run ( "git commit -m '[log] Another test file has been created [blah]'" );
testEnv.run ( "git push -u origin HEAD 2>/dev/null" );
const Commitish featureCommit ( gitClient.getHeadCommit() );
ASSERT_EQ ( featureCommit, gitClient.getFeatureBranchOnOrigin() );
}
| 34.76378 | 86 | 0.671574 |
8e162cb1124cae1e7130e2f70a1789d04925c119 | 448 | cc | C++ | example/linux/flutter/generated_plugin_registrant.cc | jainris/flutter_audio_desktop | 63d5823facbab34358875c6722874f950eb10393 | [
"MIT"
] | 50 | 2020-09-13T12:13:40.000Z | 2022-02-26T03:36:45.000Z | example/linux/flutter/generated_plugin_registrant.cc | jainris/flutter_audio_desktop | 63d5823facbab34358875c6722874f950eb10393 | [
"MIT"
] | 28 | 2020-09-23T05:29:26.000Z | 2021-03-17T11:21:11.000Z | example/linux/flutter/generated_plugin_registrant.cc | jainris/flutter_audio_desktop | 63d5823facbab34358875c6722874f950eb10393 | [
"MIT"
] | 16 | 2020-09-14T07:12:29.000Z | 2021-10-13T23:52:12.000Z | //
// Generated file. Do not edit.
//
#include "generated_plugin_registrant.h"
#include <flutter_audio_desktop/flutter_audio_desktop_plugin.h>
void fl_register_plugins(FlPluginRegistry* registry) {
g_autoptr(FlPluginRegistrar) flutter_audio_desktop_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterAudioDesktopPlugin");
flutter_audio_desktop_plugin_register_with_registrar(flutter_audio_desktop_registrar);
}
| 32 | 89 | 0.841518 |
8e1788ea9d52b0333d00766225789530cdb08ec7 | 19,774 | hpp | C++ | library/grammar/string.hpp | grandquista/chimera | 2a5326afc866d878517f2b0f5df2bf6cba20f4eb | [
"MIT"
] | 2 | 2017-12-14T07:05:06.000Z | 2021-02-07T03:31:27.000Z | library/grammar/string.hpp | grandquista/chimera | 2a5326afc866d878517f2b0f5df2bf6cba20f4eb | [
"MIT"
] | 149 | 2018-08-06T13:14:46.000Z | 2019-11-19T02:00:56.000Z | library/grammar/string.hpp | grandquista/chimera | 2a5326afc866d878517f2b0f5df2bf6cba20f4eb | [
"MIT"
] | null | null | null | // Copyright (c) 2017 Adam Grandquist <grandquista@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//! parse definitions for string tokens.
#pragma once
#include <algorithm>
#include <cstdint>
#include <numeric>
#include <string>
#include <string_view>
#include <gsl/gsl>
#include <tao/pegtl.hpp>
#include <tao/pegtl/contrib/unescape.hpp>
#include "asdl/asdl.hpp"
#include "grammar/exprfwd.hpp"
#include "grammar/flags.hpp"
#include "grammar/oper.hpp"
#include "grammar/rules.hpp"
#include "grammar/whitespace.hpp"
#include "object/object.hpp"
namespace chimera {
namespace library {
namespace grammar {
namespace token {
using namespace std::literals;
struct StringHolder : rules::VariantCapture<object::Object> {
std::string string;
template <typename String>
void apply(String &&in) {
string.append(std::forward<String>(in));
}
};
struct LiteralChar : plus<not_one<'\0', '{', '}'>> {};
template <>
struct Action<LiteralChar> {
template <typename Input, typename Top>
static void apply(const Input &in, Top &&top) {
top.apply(in.string());
}
};
template <flags::Flag Option>
using FExpression =
sor<list_tail<sor<ConditionalExpression<Option>, StarExpr<Option>>,
Comma<Option>>,
YieldExpr<Option>>;
struct Conversion : one<'a', 'r', 's'> {};
template <>
struct Action<Conversion> {
template <typename Input, typename Top>
static void apply(const Input &in, Top &&top) {
asdl::FormattedValue formattedValue{
top.template pop<asdl::ExprImpl>(),
asdl::FormattedValue::STR,
{}};
switch (in.peek_char()) {
case 'a':
formattedValue.conversion = asdl::FormattedValue::ASCII;
break;
case 'r':
formattedValue.conversion = asdl::FormattedValue::REPR;
break;
case 's':
formattedValue.conversion = asdl::FormattedValue::STR;
break;
default:
break;
}
top.push(std::move(formattedValue));
}
};
template <flags::Flag Option>
struct FormatSpec;
template <flags::Flag Option>
using ReplacementField =
if_must<LBrt<Option>, FExpression<Option>,
opt<one<'!'>, Conversion>,
opt<one<':'>, FormatSpec<Option>>, RBrt<Option>>;
template <flags::Flag Option>
struct FormatSpec
: star<sor<LiteralChar, one<0>, ReplacementField<Option>>> {};
template <flags::Flag Option>
struct Action<FormatSpec<Option>> {
template <typename Top>
static void apply0(Top &&top) {
auto formatSpec = top.template pop<asdl::ExprImpl>();
auto expr = top.template pop<asdl::ExprImpl>();
if (std::holds_alternative<asdl::FormattedValue>(*expr.value)) {
std::get<asdl::FormattedValue>(*expr.value).format_spec =
std::move(formatSpec);
top.push(std::move(expr));
} else {
top.push(asdl::FormattedValue{std::move(expr),
asdl::FormattedValue::STR,
std::move(formatSpec)});
}
}
};
struct LeftFLiteral : String<'{', '{'> {};
template <>
struct Action<LeftFLiteral> {
template <typename Top>
static void apply0(Top &&top) {
top.apply("{"sv);
}
};
struct RightFLiteral : String<'}', '}'> {};
template <>
struct Action<RightFLiteral> {
template <typename Top>
static void apply0(Top &&top) {
top.apply("}"sv);
}
};
struct FLiteral : plus<sor<LiteralChar, LeftFLiteral, RightFLiteral>> {
using Transform = StringHolder;
};
template <>
struct Action<FLiteral> {
template <typename Top>
static void apply0(Top &&top) {
top.push(object::Object(object::String(top.string), {}));
}
};
template <flags::Flag Option>
using FString =
must<star<sor<FLiteral, ReplacementField<Option>>>, eof>;
template <typename Chars>
struct SingleChars : plus<Chars> {};
template <typename Chars>
struct Action<SingleChars<Chars>> {
template <typename Input, typename Top>
static void apply(const Input &in, Top &&top) {
top.apply(in.string());
}
};
template <unsigned Len>
struct Hexseq : rep<Len, ranges<'0', '9', 'a', 'f', 'A', 'F'>> {};
template <unsigned Len>
struct Action<Hexseq<Len>> {
template <typename Input, typename Top>
static void apply(const Input &in, Top &&top) {
std::string string;
if (tao::pegtl::unescape::utf8_append_utf32(
string, tao::pegtl::unescape::unhex_string<std::uint32_t>(
in.begin(), in.end()))) {
top.apply(std::move(string));
}
}
};
template <char Open, unsigned Len>
using UTF = seq<one<Open>, Hexseq<Len>>;
struct Octseq : seq<range<'0', '7'>, rep_opt<2, range<'0', '7'>>> {};
template <>
struct Action<Octseq> {
template <typename Input, typename Top>
static void apply(const Input &in, Top &&top) {
std::string string;
if (tao::pegtl::unescape::utf8_append_utf32(
string, std::accumulate(
in.begin(), in.end(), std::uint32_t(0),
[](const auto init, const auto c) {
return (init << 2) |
static_cast<std::uint32_t>(c - '0');
}))) {
top.apply(std::move(string));
}
}
};
struct EscapeControl : one<'a', 'b', 'f', 'n', 'r', 't', 'v'> {};
template <>
struct Action<EscapeControl> {
template <typename Input, typename Top>
static void apply(const Input &in, Top &&top) {
switch (in.peek_char()) {
case 'a':
top.apply("\a"sv);
break;
case 'b':
top.apply("\b"sv);
break;
case 'f':
top.apply("\f"sv);
break;
case 'n':
top.apply("\n"sv);
break;
case 'r':
top.apply("\r"sv);
break;
case 't':
top.apply("\t"sv);
break;
case 'v':
top.apply("\v"sv);
break;
default:
Expects(false);
}
}
};
template <typename Chars>
struct EscapeIgnore : seq<Chars> {};
template <typename Chars>
struct Action<EscapeIgnore<Chars>> {
template <typename Input, typename Top>
static void apply(const Input &in, Top &&top) {
top.apply(R"(\)"sv);
top.apply(in.string());
}
};
using Escape = one<'\\'>;
using XEscapeseq = UTF<'x', 2>;
template <typename Chars, typename... Escapes>
using Escapeseq = sor<Escapes..., XEscapeseq, Octseq, Eol,
EscapeControl, EscapeIgnore<Chars>>;
template <typename Chars, typename... Escapes>
using Item = seq<if_then_else<Escape, Escapeseq<Chars, Escapes...>,
SingleChars<minus<Chars, Escape>>>,
discard>;
template <typename Chars>
using RawItem = if_then_else<Escape, Chars, Chars>;
template <typename Triple, typename Chars, typename... Escapes>
using Long = if_must<
Triple,
until<Triple, Item<seq<not_at<Triple>, Chars>, Escapes...>>>;
template <typename Triple, typename Chars>
struct LongRaw
: if_must<Triple,
until<Triple, RawItem<seq<not_at<Triple>, Chars>>>> {};
template <typename Triple, typename Chars>
struct Action<LongRaw<Triple, Chars>> {
template <typename Input, typename Top>
static void apply(const Input &in, Top &&top) {
std::string_view view(in.begin(), in.size());
view.remove_prefix(3);
view.remove_suffix(3);
top.apply(view);
}
};
template <typename Quote, typename Chars, typename... Escapes>
using Short =
if_must<Quote,
until<Quote, Item<minus<seq<not_at<Quote>, Chars>, Eol>,
Escapes...>>>;
template <typename Quote, typename Chars>
struct ShortRaw
: if_must<Quote,
until<Quote,
RawItem<minus<seq<not_at<Quote>, Chars>, Eol>>>> {};
template <typename Quote, typename Chars>
struct Action<ShortRaw<Quote, Chars>> {
template <typename Input, typename Top>
static void apply(const Input &in, Top &&top) {
std::string_view view(in.begin(), in.size());
view.remove_prefix(1);
view.remove_suffix(1);
top.apply(view);
}
};
using TripleSingle = rep<3, one<'\''>>;
using TripleDouble = rep<3, one<'"'>>;
using Single = one<'\''>;
using Double = one<'"'>;
template <typename Chars>
using Raw =
sor<LongRaw<TripleDouble, Chars>, LongRaw<TripleSingle, Chars>,
ShortRaw<Double, Chars>, ShortRaw<Single, Chars>>;
template <typename Chars, typename... Escapes>
using Escaped = sor<Long<TripleDouble, Chars, Escapes...>,
Long<TripleSingle, Chars, Escapes...>,
Short<Double, Chars, Escapes...>,
Short<Single, Chars, Escapes...>>;
using UTF16Escape = UTF<'u', 4>;
using UTF32Escape = UTF<'U', 8>;
struct UName : star<not_one<'}'>> {};
template <>
struct Action<UName> {
template <typename Input, typename Top>
static void apply(const Input &in, Top &&top) {
top.apply(in.string());
}
};
using UNameEscape = if_must<String<'N', '{'>, UName, one<'}'>>;
template <typename Prefix, typename RawPrefix, typename Chars,
typename... Escapes>
using StringImpl = sor<seq<RawPrefix, Raw<Chars>>,
seq<Prefix, Escaped<Chars, Escapes...>>>;
using BytesPrefix = one<'b', 'B'>;
using BytesRawPrefix = sor<seq<one<'r', 'R'>, one<'b', 'B'>>,
seq<one<'b', 'B'>, one<'r', 'R'>>>;
template <flags::Flag Option>
struct Bytes
: plus<Token<Option, StringImpl<BytesPrefix, BytesRawPrefix,
range<0, 0b1111111>>>> {
struct Transform : rules::VariantCapture<object::Object> {
object::Bytes bytes;
template <typename String>
void apply(String &&in) {
for (const auto &byte : in) {
bytes.emplace_back(static_cast<std::uint8_t>(byte));
}
}
};
};
template <flags::Flag Option>
struct Action<Bytes<Option>> {
template <typename Top>
static void apply0(Top &&top) {
top.push(object::Object(std::move(top.bytes), {}));
}
};
using StrPrefix = opt<one<'u', 'U'>>;
using StrRawPrefix = one<'r', 'R'>;
template <flags::Flag Option>
struct DocString
: plus<Token<Option,
StringImpl<StrPrefix, StrRawPrefix, any, UTF16Escape,
UTF32Escape, UNameEscape>>> {
using Transform = StringHolder;
};
template <flags::Flag Option>
struct Action<DocString<Option>> {
template <typename Top>
static void apply0(Top &&top) {
top.push(object::Object(object::String(top.string), {}));
}
};
using JoinedStrPrefix = one<'f', 'F'>;
using JoinedStrRawPrefix = sor<seq<one<'r', 'R'>, one<'f', 'F'>>,
seq<one<'f', 'F'>, one<'r', 'R'>>>;
struct PartialString
: plus<StringImpl<StrPrefix, StrRawPrefix, any, UTF16Escape,
UTF32Escape, UNameEscape>> {
struct Transform {
std::string string;
template <typename Outer>
void success(Outer &&outer) {
outer.push(std::move(string));
}
template <typename String>
void apply(String &&in) {
string.append(std::forward<String>(in));
}
};
};
template <flags::Flag Option>
struct FormattedString
: seq<StringImpl<JoinedStrPrefix, JoinedStrRawPrefix, any,
UTF16Escape, UTF32Escape, UNameEscape>> {
struct Transform : rules::Stack<asdl::ExprImpl> {
std::string string;
template <typename Outer>
void success(Outer &&outer) {
if (auto s = size(); s > 0) {
asdl::JoinedStr joinedStr;
joinedStr.values.reserve(s);
transform<asdl::ExprImpl>(std::back_inserter(joinedStr.values));
outer.push(std::move(joinedStr));
}
}
template <typename String>
void apply(String &&in) {
string.append(std::forward<String>(in));
}
};
};
template <flags::Flag Option>
struct Action<FormattedString<Option>> {
template <typename Input, typename Top>
static void apply(const Input &in, Top &&top) {
auto result = tao::pegtl::parse_nested<
FString<flags::list<flags::DISCARD, flags::IMPLICIT>>, Action,
Normal>(in,
tao::pegtl::memory_input<>(top.string.c_str(),
top.string.size(),
"<f_string>"),
std::forward<Top>(top));
Ensures(result);
}
};
template <flags::Flag Option>
struct JoinedStrOne
: plus<Token<Option, sor<PartialString, FormattedString<Option>>>> {
using Transform = rules::VariantCapture<std::string, asdl::JoinedStr>;
};
template <flags::Flag Option>
struct Action<JoinedStrOne<Option>> {
using State = std::variant<std::string, asdl::JoinedStr>;
struct Visitor {
auto operator()(std::string &&value, std::string &&element) {
value.append(element);
return State{std::move(value)};
}
auto operator()(std::string &&value, asdl::JoinedStr &&joinedStr) {
joinedStr.values.emplace(
joinedStr.values.begin(),
object::Object(object::String(value), {}));
return State{std::move(joinedStr)};
}
auto operator()(asdl::JoinedStr &&value, std::string &&element) {
value.values.emplace_back(
object::Object(object::String(element), {}));
return State{std::move(value)};
}
auto operator()(asdl::JoinedStr &&value,
asdl::JoinedStr &&joinedStr) {
std::move(joinedStr.values.begin(), joinedStr.values.end(),
std::back_inserter(value.values));
return State{std::move(value)};
}
};
template <typename Top>
static void apply0(Top &&top) {
State value;
for (auto &&element : top.vector()) {
value =
std::visit(Visitor{}, std::move(value), std::move(element));
}
std::visit(top, std::move(value));
}
};
template <flags::Flag Option>
struct JoinedStr : seq<JoinedStrOne<Option>> {
struct Transform
: rules::Stack<std::string, asdl::JoinedStr, object::Object> {
struct Push {
using State = std::variant<asdl::JoinedStr, object::Object>;
State operator()(std::string && /*value*/) { Expects(false); }
auto operator()(asdl::JoinedStr &&value) {
return State{std::move(value)};
}
auto operator()(object::Object &&value) {
return State{std::move(value)};
}
};
template <typename Outer>
void success(Outer &&outer) {
std::visit(outer, std::visit(Push{}, pop()));
}
};
};
template <flags::Flag Option>
struct Action<JoinedStr<Option>> {
struct Push {
using State = std::variant<asdl::JoinedStr, object::Object>;
auto operator()(std::string &&value) {
return State{object::Object(object::String(value), {})};
}
auto operator()(asdl::JoinedStr &&value) {
return State{std::move(value)};
}
auto operator()(object::Object &&value) {
return State{std::move(value)};
}
};
template <typename Top>
static void apply0(Top &&top) {
std::visit(top, std::visit(Push{}, top.pop()));
}
};
} // namespace token
template <flags::Flag Option>
struct DocString : seq<token::DocString<Option>, sor<NEWLINE, at<Eolf>>> {
using Transform =
rules::ReshapeCapture<asdl::DocString, object::Object>;
};
template <flags::Flag Option>
struct STRING : sor<token::Bytes<Option>, token::JoinedStr<Option>> {};
} // namespace grammar
} // namespace library
} // namespace chimera
| 40.02834 | 80 | 0.51148 |
8e19451dbab2934f8cf55793fc1999021ad77ba2 | 23,113 | cxx | C++ | TUHKMgen/AliGenUHKM.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | TUHKMgen/AliGenUHKM.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | TUHKMgen/AliGenUHKM.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | /////////////////////////////////////////////////////////////////////////////
// Generator using UHKM 3.0 as an external generator. //
// ( only the HYDJET++ part is implemented for a moment) //
// temporary link: //
// http://lav01.sinp.msu.ru/~igor/hydjet++/hydjet++.txt //
// The main UHKM options are accessable through this interface. //
// Uses the TUHKMgen implementation of TGenerator. //
// Author of the first implementation: Sergey Zaporozhets //
// (zaporozh@sunhe.jinr.ru) //
// Futhers modifications were made by //
// Ionut Cristian Arsene (i.c.arsene@fys.uio.no) //
// & Malinina Liudmila(malinina@lav01.sinp.msu.ru) using as an example //
// AliGenTherminator.cxx created by Adam Kisiel //
// //
////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <string>
#include "TUHKMgen.h"
#ifndef DATABASE_PDG
#include "DatabasePDG.h"
#endif
#ifndef PARTICLE_PDG
#include "ParticlePDG.h"
#endif
#include <TLorentzVector.h>
#include <TPDGCode.h>
#include <TParticle.h>
#include <TClonesArray.h>
#include <TMCProcess.h>
#include <TDatabasePDG.h>
#include <TSystem.h>
#include "AliGenUHKM.h"
#include "AliRun.h"
#include "AliConst.h"
#include "AliDecayer.h"
#include "AliGenEventHeader.h"
#include "AliGenHijingEventHeader.h"
#include "AliLog.h"
using namespace std;
ClassImp(AliGenUHKM)
//_______________________________________
AliGenUHKM::AliGenUHKM()
:AliGenMC(),
fTrials(0),
fUHKMgen(0),
fHydjetParams(),
fStableFlagged(0)
{
// Default constructor setting up default reasonable parameter values
// for central Pb+Pb collisions at 5.5TeV
// LHC
fHydjetParams.fSqrtS=5500; //LHC
fHydjetParams.fAw=207;//Pb-Pb
fHydjetParams.fBmin=0.;
fHydjetParams.fBmax=0.5; //0-5% centrality
fHydjetParams.fT = 0.170;
fHydjetParams.fMuB = 0.0;
fHydjetParams.fMuS = 0.0;
fHydjetParams.fMuI3 = 0.0;
fHydjetParams.fThFO = 0.130;
fHydjetParams.fMu_th_pip = 0.0;
fHydjetParams.fSeed=0;
fHydjetParams.fTau=10.;
fHydjetParams.fSigmaTau=3.;
fHydjetParams.fR=11.;
fHydjetParams.fYlmax=4.0;
fHydjetParams.fUmax=1.1;
fHydjetParams.fDelta=0.;
fHydjetParams.fEpsilon=0.;
fHydjetParams.fWeakDecay=0; //>=0 on ,-1 off
fHydjetParams.fEtaType=1;//gaus
fHydjetParams.fCorrS=1.;
fHydjetParams.fNhsel=2;
fHydjetParams.fIshad=1;
fHydjetParams.fPtmin=7.0;
fHydjetParams.fT0=0.8;
fHydjetParams.fTau0=0.1;
fHydjetParams.fNf=0;
fHydjetParams.fIenglu=0;
fHydjetParams.fIanglu=0;
/* RHIC
fHydjetParams.fSqrtS=200; //RHIC
fHydjetParams.fAw=197;//Au-Au
fHydjetParams.fBmin=0.;
fHydjetParams.fBmax=0.5; //0-5% centrality
fHydjetParams.fT = 0.165;
fHydjetParams.fMuB = 0.0285;
fHydjetParams.fMuS = 0.007;
fHydjetParams.fMuI3 = -0.001;
fHydjetParams.fThFO = 0.100;
fHydjetParams.fMu_th_pip = 0.053;
fHydjetParams.fSeed=0;
fHydjetParams.fTau=8.;
fHydjetParams.fSigmaTau=2.;
fHydjetParams.fR=10.;
fHydjetParams.fYlmax=3.3;
fHydjetParams.fUmax=1.1;
fHydjetParams.fDelta=0.;
fHydjetParams.fEpsilon=0.;
fHydjetParams.fWeakDecay=0; //>=0 on ,-1 off
fHydjetParams.fEtaType=1;//gaus
fHydjetParams.fCorrS=1.;
fHydjetParams.fNhsel=2;
fHydjetParams.fIshad=0;
fHydjetParams.fPtmin=3.4;
fHydjetParams.fT0=0.3;
fHydjetParams.fTau0=0.4;
fHydjetParams.fNf=2;
fHydjetParams.fIenglu=0;
fHydjetParams.fIanglu=0;
*/
strncpy(fParticleFilename, Form("%s/TUHKMgen/UHKM/particles.data", gSystem->Getenv("ALICE_ROOT")), 255);
strncpy(fDecayFilename, Form("%s/TUHKMgen/UHKM/tabledecay.txt", gSystem->Getenv("ALICE_ROOT")), 255);
for(Int_t i=0; i<500; i++) {
fStableFlagPDG[i] = 0;
fStableFlagStatus[i] = kFALSE;
}
fStableFlagged = 0;
}
//_______________________________________
AliGenUHKM::AliGenUHKM(Int_t npart)
:AliGenMC(npart),
fTrials(0),
fUHKMgen(0),
fHydjetParams(),
fStableFlagged(0)
{
// Constructor specifying the size of the particle table
// and setting up default reasonable parameter values
// for central Pb+Pb collisions at 5.5TeV
fName = "UHKM";
fTitle= "Particle Generator using UHKM 3.0";
fNprimaries = 0;
//LHC
fHydjetParams.fSqrtS=5500; //LHC
fHydjetParams.fAw=207;//Pb-Pb
fHydjetParams.fBmin=0.;
fHydjetParams.fBmax=0.5; //0-5% centrality
fHydjetParams.fT = 0.170;
fHydjetParams.fMuB = 0.0;
fHydjetParams.fMuS = 0.0;
fHydjetParams.fMuI3 = 0.0;
fHydjetParams.fThFO = 0.130;
fHydjetParams.fMu_th_pip = 0.0;
fHydjetParams.fSeed=0;
fHydjetParams.fTau=10.;
fHydjetParams.fSigmaTau=3.;
fHydjetParams.fR=11.;
fHydjetParams.fYlmax=4.0;
fHydjetParams.fUmax=1.1;
fHydjetParams.fDelta=0.;
fHydjetParams.fEpsilon=0.;
fHydjetParams.fWeakDecay=0; //>=0 on ,-1 off
fHydjetParams.fEtaType=1;//gaus
fHydjetParams.fCorrS=1.;
fHydjetParams.fNhsel=2;
fHydjetParams.fIshad=1;
fHydjetParams.fPtmin=7.0;
fHydjetParams.fT0=0.8;
fHydjetParams.fTau0=0.1;
fHydjetParams.fNf=0;
fHydjetParams.fIenglu=0;
fHydjetParams.fIanglu=0;
/*RHIC
fHydjetParams.fSqrtS=200; //RHIC
fHydjetParams.fAw=197;//Au-Au
fHydjetParams.fBmin=0.;
fHydjetParams.fBmax=0.5; //0-5% centrality
fHydjetParams.fT = 0.165;
fHydjetParams.fMuB = 0.0285;
fHydjetParams.fMuS = 0.007;
fHydjetParams.fMuI3 = -0.001;
fHydjetParams.fThFO = 0.100;
fHydjetParams.fMu_th_pip = 0.053;
fHydjetParams.fSeed=0;
fHydjetParams.fTau=8.;
fHydjetParams.fSigmaTau=2.;
fHydjetParams.fR=10.;
fHydjetParams.fYlmax=3.3;
fHydjetParams.fUmax=1.1;
fHydjetParams.fDelta=0.;
fHydjetParams.fEpsilon=0.;
fHydjetParams.fWeakDecay=0;//>=0 on ,-1 off
fHydjetParams.fEtaType=1;//gaus
fHydjetParams.fCorrS=1.;
fHydjetParams.fNhsel=2;
fHydjetParams.fIshad=1;
fHydjetParams.fPtmin=3.4;
fHydjetParams.fT0=0.3;
fHydjetParams.fTau0=0.4;
fHydjetParams.fNf=2;
fHydjetParams.fIenglu=0;
fHydjetParams.fIanglu=0;
*/
strncpy(fParticleFilename, Form("%s/TUHKMgen/UHKM/particles.data", gSystem->Getenv("ALICE_ROOT")), 255);
strncpy(fDecayFilename, Form("%s/TUHKMgen/UHKM/tabledecay.txt", gSystem->Getenv("ALICE_ROOT")), 255);
for(Int_t i=0; i<500; i++) {
fStableFlagPDG[i] = 0;
fStableFlagStatus[i] = kFALSE;
}
fStableFlagged = 0;
}
//__________________________________________
AliGenUHKM::~AliGenUHKM()
{
// Destructor, do nothing
// delete fParticles;
}
void AliGenUHKM::SetAllParametersRHIC()
{
// Set reasonable default parameters for 0-5% central Au+Au collisions
// at 200 GeV at RHIC
SetEcms(200.0); // RHIC top energy
SetAw(197); // Au+Au
SetBmin(0.0); // 0%
SetBmax(0.5); // 5%
SetChFrzTemperature(0.165); // T_ch = 165 MeV
SetMuB(0.0285); // mu_B = 28.5 MeV
SetMuS(0.007); // mu_S = 7 MeV
SetMuQ(-0.001); // mu_Q = -1 MeV
SetThFrzTemperature(0.100); // T_th = 100 MeV
SetMuPionThermal(0.053); // mu_th_pion = 53 MeV
SetSeed(0); // use UNIX time
SetTauB(8.0); // tau = 8 fm/c
SetSigmaTau(2.0); // sigma_tau = 2 fm/c
SetRmaxB(10.0); // fR = 10 fm
SetYlMax(3.3); // fYmax = 3.3
SetEtaRMax(1.1); // Umax = 1.1
SetMomAsymmPar(0.0); // delta = 0.0
SetCoordAsymmPar(0.0); // epsilon = 0.0
// SetFlagWeakDecay(0); // weak decay on (<0 off !!!)
SetEtaType(1); // gaus distributed with fYmax dispersion (0 means boost invariant)
SetGammaS(1.0); // gammaS = 1.0 (no strangeness canonical suppresion)
SetPyquenNhsel(2); // hydro on, jets on, jet quenching on
SetPyquenShad(1); // shadowing on (0 off)
SetPyquenPtmin(3.4); // ptmin = 3.4 GeV/c
SetPyquenT0(0.3); // T0 = 300 MeV
SetPyquenTau0(0.4); // tau0 = 0.4 fm/c
SetPyquenNf(2); // 2 flavours
SetPyquenIenglu(0); // radiative and collisional energy loss
SetPyquenIanglu(0); // small gluon angular distribution
}
void AliGenUHKM::SetAllParametersLHC()
{
// Set reasonable default parameters for 0-5% central Pb+Pb collisions
// at 5.5 TeV at LHC
SetEcms(5500.0); // LHC
SetAw(207); // Pb+Pb
SetBmin(0.0); // 0%
SetBmax(0.5); // 5%
SetChFrzTemperature(0.170); // T_ch = 170 MeV
SetMuB(0.0); // mu_B = 0 MeV
SetMuS(0.0); // mu_S = 0 MeV
SetMuQ(0.0); // mu_Q = 0 MeV
SetThFrzTemperature(0.130); // T_th = 130 MeV
SetMuPionThermal(0.0); // mu_th_pion = 0 MeV
SetSeed(0); // use UNIX time
SetTauB(10.0); // tau = 10 fm/c
SetSigmaTau(3.0); // sigma_tau = 3 fm/c
SetRmaxB(11.0); // fR = 11 fm
SetYlMax(4.0); // fYmax = 4.0
SetEtaRMax(1.1); // Umax = 1.1
SetMomAsymmPar(0.0); // delta = 0.0
SetCoordAsymmPar(0.0); // epsilon = 0.0
// SetFlagWeakDecay(0); // weak decay on (<0 off !!!)
SetEtaType(1); // gaus distributed with fYmax dispersion (0 means boost invariant)
SetGammaS(1.0); // gammaS = 1.0 (no strangeness canonical suppresion)
SetPyquenNhsel(2); // hydro on, jets on, jet quenching on
SetPyquenShad(1); // shadowing on (0 off)
SetPyquenPtmin(7.0); // ptmin = 7.0 GeV/c
SetPyquenT0(0.8); // T0 = 800 MeV
SetPyquenTau0(0.1); // tau0 = 0.4 fm/c
SetPyquenNf(0); // 0 flavours
SetPyquenIenglu(0); // radiative and collisional energy loss
SetPyquenIanglu(0); // small gluon angular distribution
}
//_________________________________________
void AliGenUHKM::Init()
{
// Initialization of the TGenerator::TUHKMgen interface object.
// Model input parameters are transmited to the TUHKMgen object which forwards them
// further to the model.
// HYDJET++ is initialized (average multiplicities are calculated, particle species definitions and decay
// channels are loaded, etc.)
SetMC(new TUHKMgen());
fUHKMgen = (TUHKMgen*) fMCEvGen;
SetAllParameters();
AliGenMC::Init();
fUHKMgen->Initialize();
CheckPDGTable();
fUHKMgen->Print();
}
//________________________________________
void AliGenUHKM::Generate()
{
// Generate one HYDJET++ event, get the output and push particles further
// to AliRoot's stack
Float_t polar[3] = {0,0,0};
Float_t origin[3] = {0,0,0};
Float_t origin0[3] = {0,0,0};
Float_t time0 = 0.;
Float_t p[3];
Float_t v[3];
Float_t mass=0.0, energy=0.0;
Vertex();
for(Int_t j=0; j<3; j++) origin0[j] = fVertex[j];
time0 = fTime;
// Generate the event and import particles
fUHKMgen->GenerateEvent();
fUHKMgen->ImportParticles(&fParticles,"All");
Int_t np = fParticles.GetEntriesFast();
Int_t nt = 0;
// Handle the IDs of particles on the stack
Int_t* idsOnStack = new Int_t[np];
Int_t* newPos = new Int_t[np];
for(Int_t i=0; i<np; i++) {
newPos[i] = i;
idsOnStack[i] = -1;
}
// Generate a random phi used to rotate the whole event
Double_t eventRotation = gRandom->Rndm()*TMath::Pi();
TParticle *iparticle;
Double_t partMomPhi=0.0, partPt=0.0;
Double_t partVtxPhi=0.0, partVtxR=0.0;
//_________ Loop for particles in the stack
for(Int_t i=0; i<np; i++) {
iparticle = (TParticle*)fParticles.At(i);
Int_t kf = iparticle->GetPdgCode();
Bool_t hasMother = (iparticle->GetFirstMother() >= 0);
Bool_t hasDaughter = (iparticle->GetNDaughters() > 0);
if(hasDaughter) {
// This particle has decayed
// It will not be tracked
// Add it only once with coordinates not
// smeared with primary vertex position
// rotate the direction of the particle
partMomPhi = TMath::ATan2(iparticle->Py(), iparticle->Px());
partPt = TMath::Hypot(iparticle->Px(), iparticle->Py());
p[0] = partPt*TMath::Cos(partMomPhi+eventRotation);
p[1] = partPt*TMath::Sin(partMomPhi+eventRotation);
p[2] = iparticle->Pz();
mass = TDatabasePDG::Instance()->GetParticle(kf)->Mass();
energy = sqrt(mass*mass + p[0]*p[0] + p[1]*p[1] + p[2]*p[2]);
// rotate the freezeout point
partVtxPhi = TMath::ATan2(iparticle->Vy(), iparticle->Vx());
partVtxR = TMath::Hypot(iparticle->Vx(), iparticle->Vy());
v[0] = partVtxR*TMath::Cos(partVtxPhi + eventRotation);
v[1] = partVtxR*TMath::Cos(partVtxPhi + eventRotation);
v[2] = iparticle->Vz();
Float_t time = iparticle->T();
Int_t imo = -1;
if(hasMother) {
imo = iparticle->GetFirstMother(); //index of mother particle in fParticles
} // if has mother
Bool_t trackFlag = kFALSE; // tFlag is kFALSE --> do not track the particle
PushTrack(trackFlag, (imo>=0 ? idsOnStack[imo] : imo), kf,
p[0], p[1], p[2], energy,
v[0], v[1], v[2], time,
polar[0], polar[1], polar[2],
(hasMother ? kPDecay : kPNoProcess), nt);
idsOnStack[i] = nt;
fNprimaries++;
KeepTrack(nt);
}
else {
// This is a final state particle
// It will be tracked
// Add it TWICE to the stack !!!
// First time with event-wide coordinates (for femtoscopy) -
// this one will not be tracked
// Second time with event-wide c0ordinates and vertex smearing
// this one will be tracked
// rotate the direction of the particle
partMomPhi = TMath::ATan2(iparticle->Py(), iparticle->Px());
partPt = TMath::Hypot(iparticle->Px(), iparticle->Py());
p[0] = partPt*TMath::Cos(partMomPhi+eventRotation);
p[1] = partPt*TMath::Sin(partMomPhi+eventRotation);
p[2] = iparticle->Pz();
energy = sqrt(mass*mass + p[0]*p[0] + p[1]*p[1] + p[2]*p[2]);
// rotate the freezeout point
partVtxPhi = TMath::ATan2(iparticle->Vy(), iparticle->Vx());
partVtxR = TMath::Hypot(iparticle->Vx(), iparticle->Vy());
v[0] = partVtxR*TMath::Cos(partVtxPhi + eventRotation);
v[1] = partVtxR*TMath::Cos(partVtxPhi + eventRotation);
v[2] = iparticle->Vz();
Int_t type = iparticle->GetStatusCode(); // 1-from jet / 0-from hydro
Int_t coeffT=1;
if(type==1) coeffT=-1; //to separate particles from jets
Int_t imo = -1;
if(hasMother) {
imo = iparticle->GetFirstMother();
} // if has mother
Bool_t trackFlag = kFALSE; // tFlag = kFALSE --> do not track this one, its for femtoscopy
PushTrack(trackFlag, (imo>=0 ? idsOnStack[imo] : imo), kf,
p[0], p[1], p[2], energy,
v[0], v[1], v[2], (iparticle->T())*coeffT, // freeze-out time is negative if the particle comes from jet
polar[0], polar[1], polar[2],
hasMother ? kPDecay:kPNoProcess, nt);
idsOnStack[i] = nt;
fNprimaries++;
KeepTrack(nt);
origin[0] = origin0[0]+v[0];
origin[1] = origin0[1]+v[1];
origin[2] = origin0[2]+v[2];
Float_t time = time0+iparticle->T();
imo = nt;
trackFlag = fTrackIt; // Track this particle, unless otherwise specified by fTrackIt
PushTrack(trackFlag, imo, kf,
p[0], p[1], p[2], energy,
origin[0], origin[1], origin[2], time,
polar[0], polar[1], polar[2],
hasMother ? kPDecay:kPNoProcess, nt);
fNprimaries++;
KeepTrack(nt);
}
}
SetHighWaterMark(fNprimaries);
TArrayF eventVertex;
eventVertex.Set(3);
eventVertex[0] = origin0[0];
eventVertex[1] = origin0[1];
eventVertex[2] = origin0[2];
Float_t eventTime = time0;
// Builds the event header, to be called after each event
AliGenEventHeader* header = new AliGenHijingEventHeader("UHKM");
Double_t b = 0.;
Double_t npart = 0;
Double_t nbin = 0;
fUHKMgen->GetCentrality(b, npart, nbin);
printf("********** %13.3f %13.3f %13.3f \n", b, npart, nbin);
((AliGenHijingEventHeader*) header)->SetNProduced(fNprimaries);
((AliGenHijingEventHeader*) header)->SetPrimaryVertex(eventVertex);
((AliGenHijingEventHeader*) header)->SetInteractionTime(eventTime);
((AliGenHijingEventHeader*) header)->SetImpactParameter(b);
((AliGenHijingEventHeader*) header)->SetTotalEnergy(0.0);
((AliGenHijingEventHeader*) header)->SetHardScatters(0);
((AliGenHijingEventHeader*) header)->SetParticipants(Int_t(npart), 0);
((AliGenHijingEventHeader*) header)->SetCollisions(Int_t(nbin), 0, 0, 0);
((AliGenHijingEventHeader*) header)->SetSpectators(0, 0, 0, 0);
((AliGenHijingEventHeader*) header)->SetReactionPlaneAngle(0);//evrot);
header->SetPrimaryVertex(fVertex);
header->SetInteractionTime(fTime);
AddHeader(header);
fCollisionGeometry = (AliGenHijingEventHeader*) header;
delete [] idsOnStack;
delete [] newPos;
}
void AliGenUHKM::Copy(TObject &) const
{
Fatal("Copy","Not implemented!\n");
}
void AliGenUHKM::SetAllParameters() {
// Forward all input parameters to the TGenerator::TUHKMgen object
fUHKMgen->SetEcms(fHydjetParams.fSqrtS);
fUHKMgen->SetBmin(fHydjetParams.fBmin);
fUHKMgen->SetBmax(fHydjetParams.fBmax);
fUHKMgen->SetAw(fHydjetParams.fAw);
fUHKMgen->SetSeed(fHydjetParams.fSeed);
fUHKMgen->SetChFrzTemperature(fHydjetParams.fT);
fUHKMgen->SetMuB(fHydjetParams.fMuB);
fUHKMgen->SetMuS(fHydjetParams.fMuS);
fUHKMgen->SetMuQ(fHydjetParams.fMuI3);
fUHKMgen->SetTauB(fHydjetParams.fTau);
fUHKMgen->SetThFrzTemperature(fHydjetParams.fThFO);
fUHKMgen->SetMuPionThermal(fHydjetParams.fMu_th_pip);
fUHKMgen->SetSigmaTau(fHydjetParams.fSigmaTau);
fUHKMgen->SetRmaxB(fHydjetParams.fR);
fUHKMgen->SetYlMax(fHydjetParams.fYlmax);
fUHKMgen->SetEtaRMax(fHydjetParams.fUmax);
fUHKMgen->SetMomAsymmPar(fHydjetParams.fDelta);
fUHKMgen->SetCoordAsymmPar(fHydjetParams.fEpsilon);
fUHKMgen->SetGammaS(fHydjetParams.fCorrS);
fUHKMgen->SetEtaType(fHydjetParams.fEtaType);
fUHKMgen->SetFlagWeakDecay(fHydjetParams.fWeakDecay);
//PYQUEN parameters
fUHKMgen->SetPyquenNhsel(fHydjetParams.fNhsel);
fUHKMgen->SetPyquenShad(fHydjetParams.fIshad);
fUHKMgen->SetPyquenPtmin(fHydjetParams.fPtmin);
fUHKMgen->SetPyquenT0(fHydjetParams.fT0);
fUHKMgen->SetPyquenTau0(fHydjetParams.fTau0);
fUHKMgen->SetPyquenNf(fHydjetParams.fNf);
fUHKMgen->SetPyquenIenglu(fHydjetParams.fIenglu);
fUHKMgen->SetPyquenIanglu(fHydjetParams.fIanglu);
fUHKMgen->SetPDGParticleFile(fParticleFilename);
fUHKMgen->SetPDGDecayFile(fDecayFilename);
// fUHKMgen->SetUseCharmParticles(fUseCharmParticles);
// fUHKMgen->SetMinimumWidth(fMinWidth);
// fUHKMgen->SetMaximumWidth(fMaxWidth);
// fUHKMgen->SetMinimumMass(fMinMass);
// fUHKMgen->SetMaximumMass(fMaxMass);
// cout << "AliGenUHKM::Init() no. stable flagged particles = " << fStableFlagged << endl;
for(Int_t i=0; i<fStableFlagged; i++) {
// cout << "AliGenUHKM::Init() flag no. " << i
// << " PDG = " << fStableFlagPDG[i]
// << " flag = " << fStableFlagStatus[i] << endl;
fUHKMgen->SetPDGParticleStable(fStableFlagPDG[i], fStableFlagStatus[i]);
}
cout<<" Print all parameters "<<endl;
cout<<" SqrtS = "<<fHydjetParams.fSqrtS<<endl;
cout<<" Bmin = "<< fHydjetParams.fBmin<<endl;
cout<<" Bmax= "<<fHydjetParams.fBmax<<endl;
cout<<" Aw= "<<fHydjetParams.fAw<<endl;
cout<<" Seed= "<<fHydjetParams.fSeed<<endl;
cout<<" ---Stat-model parameters----------- "<<endl;
cout<<" ChFrzTemperature= "<<fHydjetParams.fT<<endl;
cout<<" MuB= "<<fHydjetParams.fMuB<<endl;
cout<<" MuS= "<<fHydjetParams.fMuS<<endl;
cout<<" MuQ= "<<fHydjetParams.fMuI3<<endl;
cout<<" TauB= "<<fHydjetParams.fTau<<endl;
cout<<" ThFrzTemperature= "<<fHydjetParams.fThFO<<endl;
cout<<" MuPionThermal= "<<fHydjetParams.fMu_th_pip<<endl;
cout<<"-----Volume parameters -------------- "<<endl;
cout<<" SigmaTau= "<<fHydjetParams.fSigmaTau<<endl;
cout<<" RmaxB= "<<fHydjetParams.fR<<endl;
cout<<" YlMax= "<<fHydjetParams.fYlmax<<endl;
cout<<" EtaRMax= "<<fHydjetParams.fUmax<<endl;
cout<<" MomAsymmPar= "<<fHydjetParams.fDelta<<endl;
cout<<" CoordAsymmPar= "<<fHydjetParams.fEpsilon<<endl;
cout<<" --------Flags------ "<<endl;
cout<<" GammaS= "<<fHydjetParams.fCorrS<<endl;
cout<<" EtaType= "<<fHydjetParams.fEtaType<<endl;
cout<<" FlagWeakDecay= "<<fHydjetParams.fWeakDecay<<endl;
cout<<"----PYQUEN parameters---"<<endl;
cout<<" Nhsel= "<<fHydjetParams.fNhsel<<endl;
cout<<" Shad= "<<fHydjetParams.fIshad<<endl;
cout<<" Ptmin= "<<fHydjetParams.fPtmin<<endl;
cout<<" T0= "<<fHydjetParams.fT0<<endl;
cout<<" Tau0= "<<fHydjetParams.fTau0<<endl;
cout<<" Nf= "<<fHydjetParams.fNf<<endl;
cout<<" Ienglu= "<<fHydjetParams.fIenglu<<endl;
cout<<" Ianglu= "<<fHydjetParams.fIanglu<<endl;
// cout<<"----PDG table parameters---"<<endl;
// cout<<" UseCharmParticles= "<<fUseCharmParticles<<endl;
// cout<<" MinimumWidth= "<<fMinWidth<<endl;
// cout<<" MaximumWidth= "<<fMaxWidth<<endl;
// cout<<" MinimumMass= "<<fMinMass<<endl;
// cout<<" MaximumMass= "<<fMaxMass<<endl;
// cout << "AliGenUHKM::SetAllParameters() OUT" << endl;
}
// add the additional PDG codes from UHKM(SHARE table) to ROOT's table
void AliGenUHKM::CheckPDGTable() {
// Add temporarely all particle definitions from HYDJET++ which miss in the ROOT's PDG tables
// to the TDatabasePDG table.
DatabasePDG *uhkmPDG = fUHKMgen->PDGInfo(); // UHKM's PDG table
TParticlePDG *rootTestParticle;
ParticlePDG *uhkmTestParticle;
// loop over all particles in the SHARE table
for(Int_t i=0; i<uhkmPDG->GetNParticles(); i++) {
// get a particle specie
uhkmTestParticle = uhkmPDG->GetPDGParticleByIndex(i);
// check if this code exists in ROOT's table
rootTestParticle = TDatabasePDG::Instance()->GetParticle(uhkmTestParticle->GetPDG());
if(!rootTestParticle) { // if not then add it to the ROOT's PDG database
TDatabasePDG::Instance()->AddParticle(uhkmTestParticle->GetName(), uhkmTestParticle->GetName(),
uhkmTestParticle->GetMass(), uhkmTestParticle->GetElectricCharge(),
(uhkmTestParticle->GetWidth()<1e-10 ? kTRUE : kFALSE),
uhkmTestParticle->GetWidth(),
(Int_t(uhkmTestParticle->GetBaryonNumber())==0 ? "meson" : "baryon"),
uhkmTestParticle->GetPDG());
if(uhkmTestParticle->GetWidth()<1e-10)
cout << uhkmTestParticle->GetPDG() << " with mass "
<< TDatabasePDG::Instance()->GetParticle(uhkmTestParticle->GetPDG())->Mass()
<< TDatabasePDG::Instance()->GetParticle(uhkmTestParticle->GetPDG())->Width() << endl;
}
} // end for
}
| 35.287023 | 109 | 0.637304 |
8e19f72fb5aa9c9e2c6dcc6fd006fdb906053580 | 321 | cpp | C++ | CodeChef/Begginer-Problems/FACTRL2.cpp | annukamat/My-Competitive-Journey | adb13a5723483cde13e5f3859b3a7ad840b86c97 | [
"MIT"
] | 7 | 2018-11-08T11:39:27.000Z | 2020-09-10T17:50:57.000Z | CodeChef/Begginer-Problems/FACTRL2.cpp | annukamat/My-Competitive-Journey | adb13a5723483cde13e5f3859b3a7ad840b86c97 | [
"MIT"
] | null | null | null | CodeChef/Begginer-Problems/FACTRL2.cpp | annukamat/My-Competitive-Journey | adb13a5723483cde13e5f3859b3a7ad840b86c97 | [
"MIT"
] | 2 | 2019-09-16T14:34:03.000Z | 2019-10-12T19:24:00.000Z | #include <iostream>
#include <vector>
using namespace std;
long long int fact(int n){
if(n==1 || n==0){
return 1;
}else{
return n*fact(n-1);
}
}
int main(){
int t,n;
cin>>t;
vector<int>a;
while(t--){
cin>>n;
cout<<fact(n)<<"\n";
}
return 0;
} | 13.956522 | 28 | 0.457944 |
8e1b77a1b41375bf2e83aaaa75576ef7a55dea34 | 16,114 | cc | C++ | LuaKitProject/src/Projects/common/common/business_client_thread_impl.cc | andrewvmail/luakit | edbadd7824bd17b6a430d8323f255d404498c27a | [
"MIT"
] | 321 | 2018-06-17T03:52:46.000Z | 2022-03-18T02:34:52.000Z | LuaKitProject/src/Projects/common/common/business_client_thread_impl.cc | andrewvmail/luakit | edbadd7824bd17b6a430d8323f255d404498c27a | [
"MIT"
] | 19 | 2018-06-26T10:37:45.000Z | 2020-12-09T03:16:45.000Z | LuaKitProject/src/Projects/common/common/business_client_thread_impl.cc | andrewvmail/luakit | edbadd7824bd17b6a430d8323f255d404498c27a | [
"MIT"
] | 58 | 2018-06-21T10:43:03.000Z | 2022-03-29T12:42:11.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "common/business_client_thread_impl.h"
#include <string>
#include "base/atomicops.h"
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/lazy_instance.h"
#include "base/message_loop/message_loop.h"
#include "base/message_loop/message_loop_proxy.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/threading/thread_restrictions.h"
#include "common/business_client_thread_delegate.h"
#include "tools/lua_helpers.h"
extern "C" {
#include "lua.h"
#include "lauxlib.h"
#include "lstate.h"
}
namespace {
struct BusinessThreadGlobals {
BusinessThreadGlobals()
: blocking_pool(new base::SequencedWorkerPool(3, "BusinessBlocking")) {
}
// This lock protects |threads|. Do not read or modify that array
// without holding this lock. Do not block while holding this lock.
base::Lock lock;
// This array is protected by |lock|. The threads are not owned by this
// array. Typically, the threads are owned on the UI thread by
// content::BusinessMainLoop. BusinessThreadImpl objects remove themselves from
// this array upon destruction.
std::vector<BusinessThreadImpl*> threads;
std::vector<lua_State*> luaStates;
// Only atomic operations are used on this array. The delegates are not owned
// by this array, rather by whoever calls BusinessThread::SetDelegate.
std::vector<content::BusinessThreadDelegate*> thread_delegates;
const scoped_refptr<base::SequencedWorkerPool> blocking_pool;
};
base::LazyInstance<BusinessThreadGlobals>::Leaky
g_globals = LAZY_INSTANCE_INITIALIZER;
} // namespace
BusinessThreadImpl::BusinessThreadImpl(BusinessThreadID identifier,const char * thread_name)
: Thread(thread_name),
identifier_(identifier) {
BusinessThreadGlobals& globals = g_globals.Get();
globals.threads.push_back(NULL);
globals.luaStates.push_back(NULL);
globals.thread_delegates.push_back(NULL);
Initialize();
}
BusinessThreadImpl::BusinessThreadImpl(BusinessThreadID identifier,
base::MessageLoop* message_loop)
: Thread(message_loop->thread_name().c_str()),
identifier_(identifier) {
BusinessThreadGlobals& globals = g_globals.Get();
globals.threads.push_back(NULL);
globals.luaStates.push_back(NULL);
globals.thread_delegates.push_back(NULL);
set_message_loop(message_loop);
Initialize();
}
// static
void BusinessThreadImpl::ShutdownThreadPool() {
BusinessThreadGlobals& globals = g_globals.Get();
globals.blocking_pool->Shutdown();
}
void BusinessThreadImpl::Init() {
BusinessThreadGlobals& globals = g_globals.Get();
using base::subtle::AtomicWord;
AtomicWord* storage =
reinterpret_cast<AtomicWord*>(&globals.thread_delegates[identifier_]);
AtomicWord stored_pointer = base::subtle::NoBarrier_Load(storage);
content::BusinessThreadDelegate* delegate =
reinterpret_cast<content::BusinessThreadDelegate*>(stored_pointer);
if (delegate)
delegate->Init();
}
void BusinessThreadImpl::CleanUp() {
BusinessThreadGlobals& globals = g_globals.Get();
using base::subtle::AtomicWord;
AtomicWord* storage =
reinterpret_cast<AtomicWord*>(&globals.thread_delegates[identifier_]);
AtomicWord stored_pointer = base::subtle::NoBarrier_Load(storage);
content::BusinessThreadDelegate* delegate =
reinterpret_cast<content::BusinessThreadDelegate*>(stored_pointer);
if (delegate)
delegate->CleanUp();
}
void BusinessThreadImpl::Initialize() {
BusinessThreadGlobals& globals = g_globals.Get();
base::AutoLock lock(globals.lock);
DCHECK(identifier_ >= 0 && identifier_ < BusinessThread::getThreadCount());
DCHECK(globals.threads[identifier_] == NULL);
globals.threads[identifier_] = this;
if(identifier_ == UI){
lua_State* luaState = luaL_newstate();
luaInit(luaState);
DLOG(INFO) << "UI luaL_newstate" << identifier_;
globals.luaStates[identifier_] = luaState;
}
}
BusinessThreadImpl::~BusinessThreadImpl() {
// All Thread subclasses must call Stop() in the destructor. This is
// doubly important here as various bits of code check they are on
// the right BusinessThread.
Stop();
BusinessThreadGlobals& globals = g_globals.Get();
base::AutoLock lock(globals.lock);
globals.threads[identifier_] = NULL;
#ifndef NDEBUG
// Double check that the threads are ordered correctly in the enumeration.
for (int i = identifier_ + 1; i < BusinessThread::getThreadCount(); ++i) {
DCHECK(!globals.threads[i]) <<
"Threads must be listed in the reverse order that they die";
}
#endif
}
void BusinessThreadImpl::ThreadMain(){
BusinessThreadGlobals& globals = g_globals.Get();
lua_State* luaState = luaL_newstate();
luaInit(luaState);
LOG(INFO) << "BusinessThreadImpl::ThreadMain luaL_newstate" << identifier_;
globals.luaStates[identifier_] = luaState;
Thread::ThreadMain();
}
// static
bool BusinessThreadImpl::PostTaskHelper(
BusinessThreadID identifier,
const tracked_objects::Location& from_here,
const base::Closure& task,
base::TimeDelta delay,
bool nestable) {
DCHECK(identifier >= 0 && identifier < BusinessThread::getThreadCount());
// Optimization: to avoid unnecessary locks, we listed the ID enumeration in
// order of lifetime. So no need to lock if we know that the other thread
// outlives this one.
// Note: since the array is so small, ok to loop instead of creating a map,
// which would require a lock because std::map isn't thread safe, defeating
// the whole purpose of this optimization.
BusinessThreadID current_thread;
bool guaranteed_to_outlive_target_thread =
GetCurrentThreadIdentifier(¤t_thread) &&
current_thread <= identifier;
BusinessThreadGlobals& globals = g_globals.Get();
if (!guaranteed_to_outlive_target_thread)
globals.lock.Acquire();
base::MessageLoop* message_loop = globals.threads[identifier] ?
globals.threads[identifier]->message_loop() : NULL;
if (message_loop) {
if (nestable) {
message_loop->PostDelayedTask(from_here, task, delay);
} else {
message_loop->PostNonNestableDelayedTask(from_here, task, delay);
}
}
if (!guaranteed_to_outlive_target_thread)
globals.lock.Release();
return !!message_loop;
}
// An implementation of MessageLoopProxy to be used in conjunction
// with BusinessThread.
class BusinessThreadMessageLoopProxy : public base::MessageLoopProxy {
public:
explicit BusinessThreadMessageLoopProxy(BusinessThreadID identifier)
: id_(identifier) {
}
// MessageLoopProxy implementation.
// virtual bool PostDelayedTask(
// const tracked_objects::Location& from_here,
// const base::Closure& task, int64 delay_ms) OVERRIDE {
// return BusinessThread::PostDelayedTask(id_, from_here, task, delay_ms);
// }
virtual bool PostDelayedTask(
const tracked_objects::Location& from_here,
const base::Closure& task, base::TimeDelta delay) OVERRIDE {
return BusinessThread::PostDelayedTask(id_, from_here, task, delay);
}
// virtual bool PostNonNestableDelayedTask(
// const tracked_objects::Location& from_here,
// const base::Closure& task,
// int64 delay_ms) OVERRIDE {
// return BusinessThread::PostNonNestableDelayedTask(id_, from_here, task,
// delay_ms);
// }
virtual bool PostNonNestableDelayedTask(
const tracked_objects::Location& from_here,
const base::Closure& task,
base::TimeDelta delay) OVERRIDE {
return BusinessThread::PostNonNestableDelayedTask(id_, from_here, task,
delay);
}
virtual bool RunsTasksOnCurrentThread() const OVERRIDE {
return BusinessThread::CurrentlyOn(id_);
}
protected:
virtual ~BusinessThreadMessageLoopProxy() {}
private:
BusinessThreadID id_;
DISALLOW_COPY_AND_ASSIGN(BusinessThreadMessageLoopProxy);
};
// static
bool BusinessThread::PostBlockingPoolTask(
const tracked_objects::Location& from_here,
const base::Closure& task) {
return g_globals.Get().blocking_pool->PostWorkerTask(from_here, task);
}
bool BusinessThread::PostBlockingPoolTaskAndReply(
const tracked_objects::Location& from_here,
const base::Closure& task,
const base::Closure& reply) {
return g_globals.Get().blocking_pool->PostTaskAndReply(
from_here, task, reply);
}
// static
bool BusinessThread::PostBlockingPoolSequencedTask(
const std::string& sequence_token_name,
const tracked_objects::Location& from_here,
const base::Closure& task) {
return g_globals.Get().blocking_pool->PostNamedSequencedWorkerTask(
sequence_token_name, from_here, task);
}
// static
base::SequencedWorkerPool* BusinessThread::GetBlockingPool() {
return g_globals.Get().blocking_pool;
}
// static
bool BusinessThread::IsWellKnownThread(BusinessThreadID identifier) {
if (g_globals == NULL)
return false;
BusinessThreadGlobals& globals = g_globals.Get();
base::AutoLock lock(globals.lock);
return (identifier >= 0 && identifier < BusinessThread::getThreadCount() &&
globals.threads[identifier]);
}
// static
bool BusinessThread::CurrentlyOn(BusinessThreadID identifier) {
// We shouldn't use MessageLoop::current() since it uses LazyInstance which
// may be deleted by ~AtExitManager when a WorkerPool thread calls this
// function.
// http://crbug.com/63678
base::ThreadRestrictions::ScopedAllowSingleton allow_singleton;
BusinessThreadGlobals& globals = g_globals.Get();
base::AutoLock lock(globals.lock);
DCHECK(identifier >= 0 && identifier < BusinessThread::getThreadCount());
return globals.threads[identifier] &&
globals.threads[identifier]->message_loop() ==
base::MessageLoop::current();
}
// static
bool BusinessThread::IsMessageLoopValid(BusinessThreadID identifier) {
if (g_globals == NULL)
return false;
BusinessThreadGlobals& globals = g_globals.Get();
base::AutoLock lock(globals.lock);
DCHECK(identifier >= 0 && identifier < BusinessThread::getThreadCount());
return globals.threads[identifier] &&
globals.threads[identifier]->message_loop();
}
// static
bool BusinessThread::PostTask(BusinessThreadID identifier,
const tracked_objects::Location& from_here,
const base::Closure& task) {
return BusinessThreadImpl::PostTaskHelper(
identifier, from_here, task, base::TimeDelta(), true);
}
// static
bool BusinessThread::PostDelayedTask(BusinessThreadID identifier,
const tracked_objects::Location& from_here,
const base::Closure& task,
int64 delay_ms) {
return BusinessThreadImpl::PostTaskHelper(
identifier,
from_here,
task,
base::TimeDelta::FromMilliseconds(delay_ms),
true);
}
// static
bool BusinessThread::PostDelayedTask(BusinessThreadID identifier,
const tracked_objects::Location& from_here,
const base::Closure& task,
base::TimeDelta delay) {
return BusinessThreadImpl::PostTaskHelper(
identifier, from_here, task, delay, true);
}
// static
bool BusinessThread::PostNonNestableTask(
BusinessThreadID identifier,
const tracked_objects::Location& from_here,
const base::Closure& task) {
return BusinessThreadImpl::PostTaskHelper(
identifier, from_here, task, base::TimeDelta(), false);
}
// static
bool BusinessThread::PostNonNestableDelayedTask(
BusinessThreadID identifier,
const tracked_objects::Location& from_here,
const base::Closure& task,
int64 delay_ms) {
return BusinessThreadImpl::PostTaskHelper(
identifier,
from_here,
task,
base::TimeDelta::FromMilliseconds(delay_ms),
false);
}
// static
bool BusinessThread::PostNonNestableDelayedTask(
BusinessThreadID identifier,
const tracked_objects::Location& from_here,
const base::Closure& task,
base::TimeDelta delay) {
return BusinessThreadImpl::PostTaskHelper(
identifier, from_here, task, delay, false);
}
// static
bool BusinessThread::PostTaskAndReply(
BusinessThreadID identifier,
const tracked_objects::Location& from_here,
const base::Closure& task,
const base::Closure& reply) {
return GetMessageLoopProxyForThread(identifier)->PostTaskAndReply(from_here,
task,
reply);
}
// static
bool BusinessThread::GetCurrentThreadIdentifier(BusinessThreadID* identifier) {
if (g_globals == NULL)
return false;
// We shouldn't use MessageLoop::current() since it uses LazyInstance which
// may be deleted by ~AtExitManager when a WorkerPool thread calls this
// function.
// http://crbug.com/63678
base::ThreadRestrictions::ScopedAllowSingleton allow_singleton;
base::MessageLoop* cur_message_loop = base::MessageLoop::current();
BusinessThreadGlobals& globals = g_globals.Get();
for (int i = 0; i < BusinessThread::getThreadCount(); ++i) {
if (globals.threads[i] &&
globals.threads[i]->message_loop() == cur_message_loop) {
*identifier = globals.threads[i]->identifier_;
return true;
}
}
return false;
}
bool BusinessThread::GetThreadIdentifierByName(BusinessThreadID* identifier, std::string name) {
if (g_globals == NULL)
return false;
// We shouldn't use MessageLoop::current() since it uses LazyInstance which
// may be deleted by ~AtExitManager when a WorkerPool thread calls this
// function.
// http://crbug.com/63678
base::ThreadRestrictions::ScopedAllowSingleton allow_singleton;
BusinessThreadGlobals& globals = g_globals.Get();
for (int i = 0; i < BusinessThread::getThreadCount(); ++i) {
if (globals.threads[i] &&
globals.threads[i]->thread_name() == name) {
*identifier = globals.threads[i]->identifier_;
return true;
}
}
return false;
}
lua_State* BusinessThread::GetCurrentThreadLuaState(){
base::MessageLoop* cur_message_loop = base::MessageLoop::current();
BusinessThreadGlobals& globals = g_globals.Get();
for (int i = 0; i < BusinessThread::getThreadCount(); ++i) {
if (globals.threads[i] &&
globals.threads[i]->message_loop() == cur_message_loop) {
return globals.luaStates[i];
}
}
return NULL;
}
int BusinessThread::getThreadCount(){
BusinessThreadGlobals& globals = g_globals.Get();
return (int)globals.threads.size();
}
// static
scoped_refptr<base::MessageLoopProxy>
BusinessThread::GetMessageLoopProxyForThread(BusinessThreadID identifier) {
scoped_refptr<base::MessageLoopProxy> proxy(
new BusinessThreadMessageLoopProxy(identifier));
return proxy;
}
// static
base::MessageLoop* BusinessThread::UnsafeGetMessageLoopForThread(BusinessThreadID identifier) {
if (g_globals == NULL)
return NULL;
BusinessThreadGlobals& globals = g_globals.Get();
base::AutoLock lock(globals.lock);
base::Thread* thread = globals.threads[identifier];
DCHECK(thread);
base::MessageLoop* loop = thread->message_loop();
return loop;
}
// static
void BusinessThread::SetDelegate(BusinessThreadID identifier,
content::BusinessThreadDelegate* delegate) {
using base::subtle::AtomicWord;
BusinessThreadGlobals& globals = g_globals.Get();
AtomicWord* storage = reinterpret_cast<AtomicWord*>(
&globals.thread_delegates[identifier]);
AtomicWord old_pointer = base::subtle::NoBarrier_AtomicExchange(
storage, reinterpret_cast<AtomicWord>(delegate));
// This catches registration when previously registered.
DCHECK(!delegate || !old_pointer);
}
| 34.139831 | 96 | 0.707459 |
8e1f39860ad53ee845c9229cd700b5083a830a9c | 651 | cpp | C++ | Online Judges/Huxley/93GatoNoChapeu.cpp | NelsonGomesNeto/ProgramC | e743b1b869f58f7f3022d18bac00c5e0b078562e | [
"MIT"
] | 3 | 2018-12-18T13:39:42.000Z | 2021-06-23T18:05:18.000Z | Online Judges/Huxley/93GatoNoChapeu.cpp | NelsonGomesNeto/ProgramC | e743b1b869f58f7f3022d18bac00c5e0b078562e | [
"MIT"
] | 1 | 2018-11-02T21:32:40.000Z | 2018-11-02T22:47:12.000Z | Online Judges/Huxley/93GatoNoChapeu.cpp | NelsonGomesNeto/ProgramC | e743b1b869f58f7f3022d18bac00c5e0b078562e | [
"MIT"
] | 6 | 2018-10-27T14:07:52.000Z | 2019-11-14T13:49:29.000Z | #include <bits/stdc++.h>
#define lli long long int
int main()
{
lli height, working;
while (scanf("%lld %lld", &height, &working) && !(!height && !working))
{
for (lli n = 1, c = 1, cc = 1, h = height, pile = height; n < height;)
{
// printf("%lld %lld %lld\n", n, c, h);
if (h == 1) { printf("0 1\n"); break; }
c *= n;
h /= (n + 1);
pile += c * h;
if (h <= 1 && c != working)
n ++, c = 1, cc = 1, h = height, pile = height;
else if (h != 1) cc += c;
else if (h == 1 && c == working)
{
printf("%lld %lld\n", cc, pile);
break;
}
}
}
return(0);
} | 24.111111 | 74 | 0.428571 |
8e20ae742e2e67402b240670ebd6aeed26f4edb8 | 3,840 | hpp | C++ | Demos/Tests/TestBase/Camera.hpp | DhirajWishal/Flint | 0750bd515de0b5cc3d23f7c2282c50ca483dff24 | [
"Apache-2.0"
] | null | null | null | Demos/Tests/TestBase/Camera.hpp | DhirajWishal/Flint | 0750bd515de0b5cc3d23f7c2282c50ca483dff24 | [
"Apache-2.0"
] | 1 | 2021-10-30T11:19:53.000Z | 2021-10-30T11:19:54.000Z | Demos/Tests/TestBase/Camera.hpp | DhirajWishal/Flint | 0750bd515de0b5cc3d23f7c2282c50ca483dff24 | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 Dhiraj Wishal
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "GraphicsCore/Device.hpp"
#include <glm/glm.hpp>
namespace Flint
{
/**
* Flint editor camera matrix.
*/
struct CameraMatrix
{
CameraMatrix(const glm::mat4& view, const glm::mat4& projection) : mViewMatrix(view), mProjectionMatrix(projection) {}
glm::mat4 mViewMatrix = glm::mat4(1);
glm::mat4 mProjectionMatrix = glm::mat4(1);
};
/**
* Flint editor camera.
*/
class Camera
{
public:
Camera();
/**
* Move the camera to the front.
*/
void MoveFront(uint64 delta);
/**
* Move the camera to the back.
*/
void MoveBack(uint64 delta);
/**
* Move the camera to the left.
*/
void MoveLeft(uint64 delta);
/**
* Move the camera to the right.
*/
void MoveRight(uint64 delta);
/**
* Handle mouse position.
*
* @param position The mouse position.
*/
void MousePosition(FExtent2D<float> position);
/**
* Update the camera.
* This updates all the vectors and matrices.
*/
void Update();
/**
* Get the default view projection matrices.
*
* @return The camera matrix.
*/
CameraMatrix GetMatrix() const { return CameraMatrix(viewMatrix, projectionMatrix); }
/**
* Reset the first mouse boolean value to its default (true).
*/
void ResetFirstMouse();
/**
* Set the camera aspect ratio.
*
* @param extent The display extent.
*/
void SetAspectRatio(FBox2D extent);
public:
/**
* Get the camera position.
*
* @return The position vector.
*/
const glm::vec3 GetPosition() const { return mPosition; }
/**
* Set the camera position.
*
* @param position The camera position.
*/
void SetPosition(glm::vec3 position) { mPosition = position; }
/**
* Get the camera up vector.
*
* @return The camera up vector.
*/
const glm::vec3 GetCameraUp() const { return mUp; }
/**
* Get the camera front vector.
*
* @return The camera front vector.
*/
const glm::vec3 GetCameraFront() const { return mFront; }
/**
* Set the camera's range (far and near plane).
*
* @param near The near plane.
* @param far The far plane.
*/
void SetCameraRange(float near, float far) { mCameraNear = near, mCameraFar = far; }
/**
* Get the camera range.
*
* @return The near and far plane.
*/
const std::pair<float, float> GetCameraRange() const { return { mCameraNear, mCameraFar }; }
/**
* Get the camera pitch and yaw values.
*
* @return The rotation values.
*/
const std::pair<float, float> GetPitchYaw() const { return { mPitch, mYaw }; }
/**
* Set the camera view matrix.
*
* @param mat The matrix to set.
*/
void SetViewMatrix(glm::mat4 mat) { viewMatrix = mat; }
/**
* Set the movement bias.
*
* @param bias The bias to set.
*/
void SetMovementBias(const float bias) { mMovementBias = bias; }
/**
* Get the movement bias.
*
* @return The movement bias.
*/
float& GetMovementBias() { return mMovementBias; }
private:
glm::mat4 viewMatrix = glm::mat4(1);
glm::mat4 projectionMatrix = glm::mat4(1);
glm::vec3 mPosition = glm::vec3{ 0.0f, 1.0f, 0.0f };
glm::vec3 mUp = glm::vec3{ 0.0f, 1.0f, 0.0f };
glm::vec3 mFront = glm::vec3{ 0.0f, 0.0f, -1.0f };
glm::vec3 mRight = glm::vec3{ 1.0f, 0.0f, 0.0f };
glm::vec3 mWorldUp = glm::vec3{ 0.0f, 1.0f, 0.0f };
float mMovementBias = 0.05f;
float mFieldOfView = 60.0f;
float mAspectRatio = 0.5f;
float mCameraFar = 256.0f;
float mCameraNear = 0.001f;
float mAngelX = 0.0f;
float mAngelY = 0.0f;
float mAngelZ = 0.0f;
float mLastX = 0.0f;
float mLastY = 0.0f;
float mYaw = 90.0f;
float mPitch = 0.0f;
uint32 mWindowWidth = 0;
uint32 mWindowHeight = 0;
bool bFirstMouse = true;
};
} | 20.645161 | 120 | 0.622396 |
8e22e8d5c0651e4c65a88720de2083de7edd2054 | 7,199 | cc | C++ | systems/controllers/pid_controlled_system.cc | RobotLocomotion/drake-python3.7 | ae397a4c6985262d23e9675b9bf3927c08d027f5 | [
"BSD-3-Clause"
] | 2 | 2021-02-25T02:01:02.000Z | 2021-03-17T04:52:04.000Z | systems/controllers/pid_controlled_system.cc | RobotLocomotion/drake-python3.7 | ae397a4c6985262d23e9675b9bf3927c08d027f5 | [
"BSD-3-Clause"
] | null | null | null | systems/controllers/pid_controlled_system.cc | RobotLocomotion/drake-python3.7 | ae397a4c6985262d23e9675b9bf3927c08d027f5 | [
"BSD-3-Clause"
] | 1 | 2021-06-13T12:05:39.000Z | 2021-06-13T12:05:39.000Z | #include "drake/systems/controllers/pid_controlled_system.h"
#include "drake/common/default_scalars.h"
#include "drake/common/drake_assert.h"
#include "drake/systems/primitives/saturation.h"
namespace drake {
namespace systems {
namespace controllers {
template <typename T>
PidControlledSystem<T>::PidControlledSystem(std::unique_ptr<System<T>> plant,
double Kp, double Ki, double Kd,
int state_output_port_index,
int plant_input_port_index)
: state_output_port_index_(state_output_port_index),
plant_input_port_index_{plant_input_port_index} {
const int input_size = plant->get_input_port(plant_input_port_index_).size();
const Eigen::VectorXd Kp_v = Eigen::VectorXd::Ones(input_size) * Kp;
const Eigen::VectorXd Ki_v = Eigen::VectorXd::Ones(input_size) * Ki;
const Eigen::VectorXd Kd_v = Eigen::VectorXd::Ones(input_size) * Kd;
const MatrixX<double> selector = MatrixX<double>::Identity(
plant->get_input_port(plant_input_port_index_).size() * 2,
plant->get_input_port(plant_input_port_index_).size() * 2);
Initialize(std::move(plant), selector, Kp_v, Ki_v, Kd_v);
}
template <typename T>
PidControlledSystem<T>::PidControlledSystem(std::unique_ptr<System<T>> plant,
const Eigen::VectorXd& Kp,
const Eigen::VectorXd& Ki,
const Eigen::VectorXd& Kd,
int state_output_port_index,
int plant_input_port_index)
: PidControlledSystem(
std::move(plant),
MatrixX<double>::Identity(2 * Kp.size(), 2 * Kp.size()), Kp, Ki, Kd,
state_output_port_index, plant_input_port_index) {}
template <typename T>
PidControlledSystem<T>::PidControlledSystem(
std::unique_ptr<System<T>> plant, const MatrixX<double>& feedback_selector,
double Kp, double Ki, double Kd, int state_output_port_index,
int plant_input_port_index)
: state_output_port_index_(state_output_port_index),
plant_input_port_index_{plant_input_port_index} {
const int input_size = plant->get_input_port(plant_input_port_index_).size();
const Eigen::VectorXd Kp_v = Eigen::VectorXd::Ones(input_size) * Kp;
const Eigen::VectorXd Ki_v = Eigen::VectorXd::Ones(input_size) * Ki;
const Eigen::VectorXd Kd_v = Eigen::VectorXd::Ones(input_size) * Kd;
Initialize(std::move(plant), feedback_selector, Kp_v, Ki_v, Kd_v);
}
template <typename T>
PidControlledSystem<T>::PidControlledSystem(
std::unique_ptr<System<T>> plant, const MatrixX<double>& feedback_selector,
const Eigen::VectorXd& Kp, const Eigen::VectorXd& Ki,
const Eigen::VectorXd& Kd, int state_output_port_index,
int plant_input_port_index)
: state_output_port_index_(state_output_port_index),
plant_input_port_index_{plant_input_port_index} {
Initialize(std::move(plant), feedback_selector, Kp, Ki, Kd);
}
template <typename T>
void PidControlledSystem<T>::Initialize(
std::unique_ptr<System<T>> plant, const MatrixX<double>& feedback_selector,
const Eigen::VectorXd& Kp, const Eigen::VectorXd& Ki,
const Eigen::VectorXd& Kd) {
DRAKE_DEMAND(plant != nullptr);
DiagramBuilder<T> builder;
plant_ = builder.template AddSystem(std::move(plant));
DRAKE_ASSERT(plant_->num_input_ports() >= 1);
DRAKE_ASSERT(plant_->num_output_ports() >= 1);
// state_output_port_index_ will be checked by the get_output_port call below.
auto input_ports =
ConnectController(plant_->get_input_port(plant_input_port_index_),
plant_->get_output_port(state_output_port_index_),
feedback_selector, Kp, Ki, Kd, &builder);
builder.ExportInput(input_ports.control_input_port);
builder.ExportInput(input_ports.state_input_port);
for (int i=0; i < plant_->num_output_ports(); i++) {
builder.ExportOutput(plant_->get_output_port(i));
}
builder.BuildInto(this);
}
template <typename T>
typename PidControlledSystem<T>::ConnectResult
PidControlledSystem<T>::ConnectController(
const InputPort<T>& plant_input,
const OutputPort<T>& plant_output,
const MatrixX<double>& feedback_selector, const Eigen::VectorXd& Kp,
const Eigen::VectorXd& Ki, const Eigen::VectorXd& Kd,
DiagramBuilder<T>* builder) {
auto controller = builder->template AddSystem<PidController<T>>(
feedback_selector,
Kp, Ki, Kd);
auto plant_input_adder =
builder->template AddSystem<Adder<T>>(2, plant_input.size());
builder->Connect(plant_output, controller->get_input_port_estimated_state());
builder->Connect(controller->get_output_port_control(),
plant_input_adder->get_input_port(0));
builder->Connect(plant_input_adder->get_output_port(), plant_input);
return ConnectResult{
plant_input_adder->get_input_port(1),
controller->get_input_port_desired_state()};
}
template <typename T>
typename PidControlledSystem<T>::ConnectResult
PidControlledSystem<T>::ConnectController(
const InputPort<T>& plant_input,
const OutputPort<T>& plant_output,
const Eigen::VectorXd& Kp, const Eigen::VectorXd& Ki,
const Eigen::VectorXd& Kd,
DiagramBuilder<T>* builder) {
return ConnectController(plant_input, plant_output,
MatrixX<double>::Identity(plant_output.size(), plant_output.size()),
Kp, Ki, Kd, builder);
}
template <typename T>
typename PidControlledSystem<T>::ConnectResult
PidControlledSystem<T>::ConnectControllerWithInputSaturation(
const InputPort<T>& plant_input,
const OutputPort<T>& plant_output,
const MatrixX<double>& feedback_selector, const Eigen::VectorXd& Kp,
const Eigen::VectorXd& Ki, const Eigen::VectorXd& Kd,
const VectorX<T>& min_plant_input, const VectorX<T>& max_plant_input,
DiagramBuilder<T>* builder) {
auto saturation = builder->template AddSystem<Saturation<T>>(
min_plant_input, max_plant_input);
builder->Connect(saturation->get_output_port(), plant_input);
return
PidControlledSystem<T>::ConnectController(saturation->get_input_port(),
plant_output, feedback_selector, Kp, Ki, Kd, builder);
}
template <typename T>
typename PidControlledSystem<T>::ConnectResult
PidControlledSystem<T>::ConnectControllerWithInputSaturation(
const InputPort<T>& plant_input,
const OutputPort<T>& plant_output,
const Eigen::VectorXd& Kp, const Eigen::VectorXd& Ki,
const Eigen::VectorXd& Kd, const VectorX<T>& min_plant_input,
const VectorX<T>& max_plant_input, DiagramBuilder<T>* builder) {
return ConnectControllerWithInputSaturation(plant_input, plant_output,
MatrixX<double>::Identity(plant_output.size(), plant_output.size()),
Kp, Ki, Kd, min_plant_input, max_plant_input, builder);
}
template <typename T>
PidControlledSystem<T>::~PidControlledSystem() {}
} // namespace controllers
} // namespace systems
} // namespace drake
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_NONSYMBOLIC_SCALARS(
class ::drake::systems::controllers::PidControlledSystem)
| 42.347059 | 80 | 0.711488 |
8e27b8f69bd4c6ef07d4ebdc6d55e6ba669c8e09 | 2,382 | cpp | C++ | Day12/12.cpp | Legolaszstudio/aoc2021 | dc2e341738e11a55232ae0f37aa0cc5625d8d831 | [
"BSD-3-Clause"
] | null | null | null | Day12/12.cpp | Legolaszstudio/aoc2021 | dc2e341738e11a55232ae0f37aa0cc5625d8d831 | [
"BSD-3-Clause"
] | null | null | null | Day12/12.cpp | Legolaszstudio/aoc2021 | dc2e341738e11a55232ae0f37aa0cc5625d8d831 | [
"BSD-3-Clause"
] | null | null | null | #include <string>
#include <fstream>
#include <sstream>
#include <deque>
#include <vector>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <set>
struct Graph {
std::unordered_map<std::string, std::vector<std::string>> tree;
//WARNING It is not the best option to store the entire solutions but I wanted to see all the combinations
std::vector<std::vector<std::string>> solutions;
};
void walkGraph(Graph& graph, std::string currentNode, std::vector<std::string> path, std::multiset<std::string> visited, bool partTwo);
void startSolving(Graph& graph, bool partTwo);
int main() {
Graph graph;
std::string line;
std::ifstream file("12.txt");
while (std::getline(file, line)) {
std::stringstream X(line);
std::string nodeName;
std::vector<std::string> temp = {};
while (std::getline(X, nodeName, '-')) {
temp.push_back(nodeName);
}
graph.tree[temp[0]].push_back(temp[1]);
graph.tree[temp[1]].push_back(temp[0]);
}
startSolving(graph, false);
int solution = graph.solutions.size();
std::cout << "There were " << solution << " possible solutions for part1" << std::endl;
std::cout << "To run second part press enter:" << std::endl << std::endl;
getchar();
graph.solutions = {};
startSolving(graph, true);
solution = graph.solutions.size();
std::cout << "There were " << solution << " possible solutions for part2" << std::endl;
return 0;
}
void startSolving(Graph& graph, bool partTwo) {
// Store solution
std::vector<std::string> path = {};
// Store visited nodes
std::multiset<std::string> visited = {};
// We visited twice
walkGraph(graph, "start", path, visited, partTwo);
}
void walkGraph(Graph& graph, std::string currentNode, std::vector<std::string> path, std::multiset<std::string> visited, bool partTwo) {
if (std::islower(currentNode[0])) {
if (visited.count(currentNode) == 1) { partTwo = false; }
visited.insert(currentNode);
}
path.push_back(currentNode);
if (currentNode == "end") {
graph.solutions.push_back(path);
//Uncomment to print solutions
//for (const auto& item : path) {
// std::cout << item << ",";
//}
//std::cout << std::endl;
} else {
for (const auto& item : graph.tree[currentNode]) {
if (item == "start") continue;
if (!visited.count(item) > 0 || (partTwo && visited.count(item) < 2)) {
walkGraph(graph, item, path, visited, partTwo);
}
}
}
} | 30.538462 | 136 | 0.669186 |
8e2ce4cd297c21145788a920086b875e6bc37617 | 12,262 | cpp | C++ | groups/bal/balb/balb_leakybucket.cpp | AlisdairM/bde | bc65db208c32513aa545080f57090cc39c608be0 | [
"Apache-2.0"
] | 1 | 2022-01-23T11:31:12.000Z | 2022-01-23T11:31:12.000Z | groups/bal/balb/balb_leakybucket.cpp | AlisdairM/bde | bc65db208c32513aa545080f57090cc39c608be0 | [
"Apache-2.0"
] | null | null | null | groups/bal/balb/balb_leakybucket.cpp | AlisdairM/bde | bc65db208c32513aa545080f57090cc39c608be0 | [
"Apache-2.0"
] | null | null | null | // balb_leakybucket.cpp -*-C++-*-
#include <balb_leakybucket.h>
#include <bsls_ident.h>
BSLS_IDENT_RCSID(balb_leakybucket.cpp,"$Id$ $CSID$")
#include <bsl_c_math.h>
namespace BloombergLP {
namespace {
bsls::Types::Uint64 calculateNumberOfUnitsToDrain(
bsls::Types::Uint64* fractionalUnitDrainedInNanoUnits,
bsls::Types::Uint64 drainRate,
const bsls::TimeInterval& timeInterval)
// Return the number of units that would be drained from a leaky bucket
// over the specified 'timeInterval' at the specified 'drainRate', plus the
// specified 'fractionalUnitDrainedInNanoUnits', representing a fractional
// remainder from a previous call to 'calculateNumberOfUnitsToDrain'. Load
// into 'fractionalUnitDrainedInNanoUnits' the fractional remainder
// (between 0.0 and 1.0, represented in nano-units) from this calculation.
// The behavior is undefined unless
// '0 <= *fractionalUnitDrainedInNanoUnits < 1000000000' (i.e., it
// represents a value between 0 and 1 unit) and
// 'timeInterval.seconds() * drainRate <= ULLONG_MAX'. Note that
// 'fractionalUnitDrainedInNanoUnits' is represented in nano-units to avoid
// using a floating point representation.
{
const bsls::Types::Uint64 k_NANOUNITS_PER_UNIT = 1000000000;
BSLS_ASSERT(static_cast<bsls::Types::Uint64>(timeInterval.seconds()) <=
ULLONG_MAX / drainRate);
BSLS_ASSERT(0 != fractionalUnitDrainedInNanoUnits);
BSLS_ASSERT(*fractionalUnitDrainedInNanoUnits < k_NANOUNITS_PER_UNIT);
bsls::Types::Uint64 units = drainRate * timeInterval.seconds();
units += (drainRate / k_NANOUNITS_PER_UNIT) * timeInterval.nanoseconds();
bsls::Types::Uint64 nanounits = 0;
// As long as rate is represented by a whole number, the fractional part
// of number of units to drain comes from fractional part of seconds of
// the time interval
nanounits = *fractionalUnitDrainedInNanoUnits +
(drainRate % k_NANOUNITS_PER_UNIT) * timeInterval.nanoseconds();
*fractionalUnitDrainedInNanoUnits = nanounits % k_NANOUNITS_PER_UNIT;
units += nanounits / k_NANOUNITS_PER_UNIT;
return units;
}
} // close unnamed namespace
namespace balb {
//------------------
// class LeakyBucket
//------------------
// CLASS METHODS
bsls::Types::Uint64 LeakyBucket::calculateCapacity(
bsls::Types::Uint64 drainRate,
const bsls::TimeInterval& timeWindow)
{
BSLS_ASSERT(1 == drainRate ||
timeWindow <= LeakyBucket::calculateDrainTime(ULLONG_MAX,
drainRate,
false));
bsls::Types::Uint64 fractionalUnitsInNanoUnits = 0;
bsls::Types::Uint64 capacity = calculateNumberOfUnitsToDrain(
&fractionalUnitsInNanoUnits,
drainRate,
timeWindow);
// Round the returned capacity to 1, which is okay, because it does not
// affect the drain rate.
return (0 != capacity) ? capacity : 1;
}
bsls::TimeInterval LeakyBucket::calculateDrainTime(
bsls::Types::Uint64 numUnits,
bsls::Types::Uint64 drainRate,
bool ceilFlag)
{
BSLS_ASSERT(drainRate > 1 || numUnits <= LLONG_MAX);
bsls::TimeInterval interval(0,0);
interval.addSeconds(numUnits / drainRate);
bsls::Types::Uint64 remUnits = numUnits % drainRate;
const double nanoSecs = static_cast<double>(remUnits) * 1e9 /
static_cast<double>(drainRate);
interval.addNanoseconds(static_cast<bsls::Types::Int64>(
ceilFlag ? ceil(nanoSecs) : floor(nanoSecs)));
return interval;
}
bsls::TimeInterval LeakyBucket::calculateTimeWindow(
bsls::Types::Uint64 drainRate,
bsls::Types::Uint64 capacity)
{
BSLS_ASSERT(drainRate > 0);
BSLS_ASSERT(drainRate > 1 || capacity <= LLONG_MAX);
bsls::TimeInterval window = LeakyBucket::calculateDrainTime(capacity,
drainRate,
true);
if (0 == window) {
window.addNanoseconds(1);
}
return window;
}
// CREATORS
LeakyBucket::LeakyBucket(bsls::Types::Uint64 drainRate,
bsls::Types::Uint64 capacity,
const bsls::TimeInterval& currentTime)
: d_drainRate(drainRate)
, d_capacity(capacity)
, d_unitsReserved(0)
, d_unitsInBucket(0)
, d_fractionalUnitDrainedInNanoUnits(0)
, d_lastUpdateTime(currentTime)
, d_statSubmittedUnits(0)
, d_statSubmittedUnitsAtLastUpdate(0)
, d_statisticsCollectionStartTime(currentTime)
{
BSLS_ASSERT_OPT(0 < d_drainRate);
BSLS_ASSERT_OPT(0 < d_capacity);
BSLS_ASSERT(LLONG_MIN != currentTime.seconds());
// Calculate the maximum interval between updates that would not cause the
// number of units drained to overflow an unsigned 64-bit integral type.
if (drainRate == 1) {
// 'd_maxUpdateInterval' is a signed 64-bit integral type that can't
// represent 'ULLONG_MAX' number of seconds, so we set
// 'd_maxUpdateInterval' to the maximum representable value when
// 'drainRate' is 1.
d_maxUpdateInterval = bsls::TimeInterval(LLONG_MAX, 999999999);
}
else {
d_maxUpdateInterval = LeakyBucket::calculateDrainTime(ULLONG_MAX,
drainRate,
false);
}
}
// MANIPULATORS
bsls::TimeInterval LeakyBucket::calculateTimeToSubmit(
const bsls::TimeInterval& currentTime)
{
bsls::Types::Uint64 usedUnits = d_unitsInBucket + d_unitsReserved;
// Return 0-length time interval if units can be submitted right now.
if (usedUnits < d_capacity) {
return bsls::TimeInterval(0, 0); // RETURN
}
updateState(currentTime);
// Return 0-length time interval if units can be submitted after the state
// has been updated.
if (d_unitsInBucket + d_unitsReserved < d_capacity) {
return bsls::TimeInterval(0, 0); // RETURN
}
bsls::TimeInterval timeToSubmit(0,0);
bsls::Types::Uint64 backlogUnits;
// From here, 'd_unitsInBucket + d_unitsReserved' is always greater than
// 'd_capacity'
backlogUnits = d_unitsInBucket + d_unitsReserved - d_capacity + 1;
timeToSubmit = LeakyBucket::calculateDrainTime(backlogUnits,
d_drainRate,
true);
// Return 1 nanosecond if the time interval was rounded to zero (in cases
// of high drain rates).
if (timeToSubmit == 0) {
timeToSubmit.addNanoseconds(1);
}
return timeToSubmit;
}
void LeakyBucket::setRateAndCapacity(bsls::Types::Uint64 newRate,
bsls::Types::Uint64 newCapacity)
{
BSLS_ASSERT_SAFE(0 < newRate);
BSLS_ASSERT_SAFE(0 < newCapacity);
d_drainRate = newRate;
d_capacity = newCapacity;
// Calculate the maximum interval between updates that would not cause the
// number of units drained to overflow an unsigned 64-bit integral type.
if (newRate == 1) {
d_maxUpdateInterval = bsls::TimeInterval(LLONG_MAX, 999999999);
}
else {
d_maxUpdateInterval = LeakyBucket::calculateDrainTime(ULLONG_MAX,
newRate,
false);
}
}
void LeakyBucket::updateState(const bsls::TimeInterval& currentTime)
{
BSLS_ASSERT(LLONG_MIN != currentTime.seconds());
bsls::TimeInterval delta = currentTime - d_lastUpdateTime;
d_statSubmittedUnitsAtLastUpdate = d_statSubmittedUnits;
// If delta is greater than the time it takes to drain the maximum number
// of units representable by 64 bit integral type, then reset
// 'unitsInBucket'.
if (delta > d_maxUpdateInterval) {
d_lastUpdateTime = currentTime;
d_unitsInBucket = 0;
d_fractionalUnitDrainedInNanoUnits = 0;
return; // RETURN
}
if (delta >= bsls::TimeInterval(0, 0)) {
bsls::Types::Uint64 units;
units = calculateNumberOfUnitsToDrain(
&d_fractionalUnitDrainedInNanoUnits,
d_drainRate,
delta);
if (units < d_unitsInBucket) {
d_unitsInBucket -= units;
}
else {
d_unitsInBucket = 0;
}
}
else {
// The delta maybe negative when the system clocks are updated. If the
// specified 'currentTime' precedes 'statisticsCollectionStartTime',
// adjust it to prevent the statistics collection interval from going
// negative.
if (currentTime < d_statisticsCollectionStartTime) {
d_statisticsCollectionStartTime = currentTime;
}
}
d_lastUpdateTime = currentTime;
}
bool LeakyBucket::wouldOverflow(const bsls::TimeInterval& currentTime)
{
updateState(currentTime);
if (1 > ULLONG_MAX - d_unitsInBucket - d_unitsReserved ||
d_unitsInBucket + d_unitsReserved + 1 > d_capacity) {
return true; // RETURN
}
return false;
}
// ACCESSORS
void LeakyBucket::getStatistics(bsls::Types::Uint64* submittedUnits,
bsls::Types::Uint64* unusedUnits) const
{
BSLS_ASSERT(0 != submittedUnits);
BSLS_ASSERT(0 != unusedUnits);
*submittedUnits = d_statSubmittedUnitsAtLastUpdate;
bsls::Types::Uint64 fractionalUnits = 0;
// 'monitoredInterval' can not be negative, as the 'updateState' method
// ensures that 'd_lastUpdateTime' always precedes
// 'statisticsCollectionStartTime'.
bsls::TimeInterval monitoredInterval = d_lastUpdateTime -
d_statisticsCollectionStartTime;
bsls::Types::Uint64 drainedUnits = calculateNumberOfUnitsToDrain(
&fractionalUnits,
d_drainRate,
monitoredInterval);
if (drainedUnits < d_statSubmittedUnitsAtLastUpdate) {
*unusedUnits = 0;
}
else {
*unusedUnits = drainedUnits - d_statSubmittedUnitsAtLastUpdate;
}
}
} // close package namespace
} // close enterprise namespace
// ----------------------------------------------------------------------------
// Copyright 2021 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
| 36.494048 | 79 | 0.576333 |
8e2efa1781bfb88bc7793216fa25a00987bde79b | 681 | cpp | C++ | framework/source/metadata_backward_compatibility.cpp | xrEngine512/interop | c80711fbbe08f350ad5d8058163770f57ed20b0c | [
"MIT"
] | null | null | null | framework/source/metadata_backward_compatibility.cpp | xrEngine512/interop | c80711fbbe08f350ad5d8058163770f57ed20b0c | [
"MIT"
] | 4 | 2017-05-31T12:34:10.000Z | 2018-10-13T18:53:03.000Z | framework/source/metadata_backward_compatibility.cpp | xrEngine512/MosaicFramework | c80711fbbe08f350ad5d8058163770f57ed20b0c | [
"MIT"
] | 1 | 2020-04-23T14:09:11.000Z | 2020-04-23T14:09:11.000Z | //
// Created by islam on 14.01.18.
//
#include "metadata_backward_compatibility.h"
#include "exceptions.h"
namespace interop {
module_metadata_t convert_metadata_to_current(const version_t & version, const void * metadata)
{
/** version of module's interop ABI matches version of node **/
if (version == interop_framework_abi_version_m) {
return *reinterpret_cast<const module_metadata_t *>(metadata);
} else {
throw error_t("unable to convert metadata of version " + version.to_string() +
" to current format version (" + interop_framework_abi_version_m.to_string() +
")");
}
}
} // namespace interop
| 32.428571 | 100 | 0.671072 |
8e3ed45500eab3fc875fa1d2d2cfc349273f1962 | 14,036 | hpp | C++ | Svc/UdpReceiver/test/ut/Handcode/GTestBase.hpp | SSteve/fprime | 12c478bd79c2c4ba2d9f9e634e47f8b6557c54a8 | [
"Apache-2.0"
] | 5 | 2019-10-22T03:41:02.000Z | 2022-01-16T12:48:31.000Z | Svc/UdpReceiver/test/ut/Handcode/GTestBase.hpp | SSteve/fprime | 12c478bd79c2c4ba2d9f9e634e47f8b6557c54a8 | [
"Apache-2.0"
] | 42 | 2021-06-10T23:31:10.000Z | 2021-06-25T00:35:31.000Z | Svc/UdpReceiver/test/ut/Handcode/GTestBase.hpp | SSteve/fprime | 12c478bd79c2c4ba2d9f9e634e47f8b6557c54a8 | [
"Apache-2.0"
] | 3 | 2020-09-05T18:17:21.000Z | 2020-11-15T04:06:24.000Z | // ======================================================================
// \title UdpReceiver/test/ut/GTestBase.hpp
// \author Auto-generated
// \brief hpp file for UdpReceiver component Google Test harness base class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef UdpReceiver_GTEST_BASE_HPP
#define UdpReceiver_GTEST_BASE_HPP
#include "TesterBase.hpp"
#include "gtest/gtest.h"
// ----------------------------------------------------------------------
// Macros for telemetry history assertions
// ----------------------------------------------------------------------
#define ASSERT_TLM_SIZE(size) \
this->assertTlm_size(__FILE__, __LINE__, size)
#define ASSERT_TLM_UR_PacketsReceived_SIZE(size) \
this->assertTlm_UR_PacketsReceived_size(__FILE__, __LINE__, size)
#define ASSERT_TLM_UR_PacketsReceived(index, value) \
this->assertTlm_UR_PacketsReceived(__FILE__, __LINE__, index, value)
#define ASSERT_TLM_UR_BytesReceived_SIZE(size) \
this->assertTlm_UR_BytesReceived_size(__FILE__, __LINE__, size)
#define ASSERT_TLM_UR_BytesReceived(index, value) \
this->assertTlm_UR_BytesReceived(__FILE__, __LINE__, index, value)
#define ASSERT_TLM_UR_PacketsDropped_SIZE(size) \
this->assertTlm_UR_PacketsDropped_size(__FILE__, __LINE__, size)
#define ASSERT_TLM_UR_PacketsDropped(index, value) \
this->assertTlm_UR_PacketsDropped(__FILE__, __LINE__, index, value)
#define ASSERT_TLM_UR_DecodeErrors_SIZE(size) \
this->assertTlm_UR_DecodeErrors_size(__FILE__, __LINE__, size)
#define ASSERT_TLM_UR_DecodeErrors(index, value) \
this->assertTlm_UR_DecodeErrors(__FILE__, __LINE__, index, value)
// ----------------------------------------------------------------------
// Macros for event history assertions
// ----------------------------------------------------------------------
#define ASSERT_EVENTS_SIZE(size) \
this->assertEvents_size(__FILE__, __LINE__, size)
#define ASSERT_EVENTS_UR_PortOpened_SIZE(size) \
this->assertEvents_UR_PortOpened_size(__FILE__, __LINE__, size)
#define ASSERT_EVENTS_UR_PortOpened(index, _port) \
this->assertEvents_UR_PortOpened(__FILE__, __LINE__, index, _port)
#define ASSERT_EVENTS_UR_SocketError_SIZE(size) \
this->assertEvents_UR_SocketError_size(__FILE__, __LINE__, size)
#define ASSERT_EVENTS_UR_SocketError(index, _error) \
this->assertEvents_UR_SocketError(__FILE__, __LINE__, index, _error)
#define ASSERT_EVENTS_UR_BindError_SIZE(size) \
this->assertEvents_UR_BindError_size(__FILE__, __LINE__, size)
#define ASSERT_EVENTS_UR_BindError(index, _error) \
this->assertEvents_UR_BindError(__FILE__, __LINE__, index, _error)
#define ASSERT_EVENTS_UR_RecvError_SIZE(size) \
this->assertEvents_UR_RecvError_size(__FILE__, __LINE__, size)
#define ASSERT_EVENTS_UR_RecvError(index, _error) \
this->assertEvents_UR_RecvError(__FILE__, __LINE__, index, _error)
#define ASSERT_EVENTS_UR_DecodeError_SIZE(size) \
this->assertEvents_UR_DecodeError_size(__FILE__, __LINE__, size)
#define ASSERT_EVENTS_UR_DecodeError(index, _stage, _error) \
this->assertEvents_UR_DecodeError(__FILE__, __LINE__, index, _stage, _error)
#define ASSERT_EVENTS_UR_DroppedPacket_SIZE(size) \
this->assertEvents_UR_DroppedPacket_size(__FILE__, __LINE__, size)
#define ASSERT_EVENTS_UR_DroppedPacket(index, _diff) \
this->assertEvents_UR_DroppedPacket(__FILE__, __LINE__, index, _diff)
namespace Svc {
//! \class UdpReceiverGTestBase
//! \brief Auto-generated base class for UdpReceiver component Google Test harness
//!
class UdpReceiverGTestBase :
public UdpReceiverTesterBase
{
protected:
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
//! Construct object UdpReceiverGTestBase
//!
UdpReceiverGTestBase(
#if FW_OBJECT_NAMES == 1
const char *const compName, /*!< The component name*/
const U32 maxHistorySize /*!< The maximum size of each history*/
#else
const U32 maxHistorySize /*!< The maximum size of each history*/
#endif
);
//! Destroy object UdpReceiverGTestBase
//!
virtual ~UdpReceiverGTestBase(void);
protected:
// ----------------------------------------------------------------------
// Telemetry
// ----------------------------------------------------------------------
//! Assert size of telemetry history
//!
void assertTlm_size(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 size /*!< The asserted size*/
) const;
protected:
// ----------------------------------------------------------------------
// Channel: UR_PacketsReceived
// ----------------------------------------------------------------------
//! Assert telemetry value in history at index
//!
void assertTlm_UR_PacketsReceived_size(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 size /*!< The asserted size*/
) const;
void assertTlm_UR_PacketsReceived(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 __index, /*!< The index*/
const U32& val /*!< The channel value*/
) const;
protected:
// ----------------------------------------------------------------------
// Channel: UR_BytesReceived
// ----------------------------------------------------------------------
//! Assert telemetry value in history at index
//!
void assertTlm_UR_BytesReceived_size(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 size /*!< The asserted size*/
) const;
void assertTlm_UR_BytesReceived(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 __index, /*!< The index*/
const U32& val /*!< The channel value*/
) const;
protected:
// ----------------------------------------------------------------------
// Channel: UR_PacketsDropped
// ----------------------------------------------------------------------
//! Assert telemetry value in history at index
//!
void assertTlm_UR_PacketsDropped_size(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 size /*!< The asserted size*/
) const;
void assertTlm_UR_PacketsDropped(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 __index, /*!< The index*/
const U32& val /*!< The channel value*/
) const;
protected:
// ----------------------------------------------------------------------
// Channel: UR_DecodeErrors
// ----------------------------------------------------------------------
//! Assert telemetry value in history at index
//!
void assertTlm_UR_DecodeErrors_size(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 size /*!< The asserted size*/
) const;
void assertTlm_UR_DecodeErrors(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 __index, /*!< The index*/
const U32& val /*!< The channel value*/
) const;
protected:
// ----------------------------------------------------------------------
// Events
// ----------------------------------------------------------------------
void assertEvents_size(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 size /*!< The asserted size*/
) const;
protected:
// ----------------------------------------------------------------------
// Event: UR_PortOpened
// ----------------------------------------------------------------------
void assertEvents_UR_PortOpened_size(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 size /*!< The asserted size*/
) const;
void assertEvents_UR_PortOpened(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 __index, /*!< The index*/
const U32 port
) const;
protected:
// ----------------------------------------------------------------------
// Event: UR_SocketError
// ----------------------------------------------------------------------
void assertEvents_UR_SocketError_size(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 size /*!< The asserted size*/
) const;
void assertEvents_UR_SocketError(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 __index, /*!< The index*/
const char *const error
) const;
protected:
// ----------------------------------------------------------------------
// Event: UR_BindError
// ----------------------------------------------------------------------
void assertEvents_UR_BindError_size(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 size /*!< The asserted size*/
) const;
void assertEvents_UR_BindError(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 __index, /*!< The index*/
const char *const error
) const;
protected:
// ----------------------------------------------------------------------
// Event: UR_RecvError
// ----------------------------------------------------------------------
void assertEvents_UR_RecvError_size(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 size /*!< The asserted size*/
) const;
void assertEvents_UR_RecvError(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 __index, /*!< The index*/
const char *const error
) const;
protected:
// ----------------------------------------------------------------------
// Event: UR_DecodeError
// ----------------------------------------------------------------------
void assertEvents_UR_DecodeError_size(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 size /*!< The asserted size*/
) const;
void assertEvents_UR_DecodeError(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 __index, /*!< The index*/
UdpReceiverComponentBase::DecodeStage stage,
const I32 error
) const;
protected:
// ----------------------------------------------------------------------
// Event: UR_DroppedPacket
// ----------------------------------------------------------------------
void assertEvents_UR_DroppedPacket_size(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 size /*!< The asserted size*/
) const;
void assertEvents_UR_DroppedPacket(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 __index, /*!< The index*/
const U32 diff
) const;
};
} // end namespace Svc
#endif
| 39.76204 | 100 | 0.558421 |
8e3f6cf476c45f2b7a7bef65b062dc198e4b0edc | 13,656 | hpp | C++ | server/http_context.hpp | photonmaster/scymnus | bcbf580091a730c63e15b67b6331705a281ba20b | [
"MIT"
] | 7 | 2021-08-19T01:11:21.000Z | 2021-08-31T15:25:51.000Z | server/http_context.hpp | photonmaster/scymnus | bcbf580091a730c63e15b67b6331705a281ba20b | [
"MIT"
] | null | null | null | server/http_context.hpp | photonmaster/scymnus | bcbf580091a730c63e15b67b6331705a281ba20b | [
"MIT"
] | null | null | null | #pragma once
#include <filesystem>
#include <fstream>
#include <charconv>
#include "core/named_tuple.hpp"
#include "core/traits.hpp"
#include "date_manager.hpp"
#include "external/json.hpp"
#include "http/http_common.hpp"
#include "http/query_parser.hpp"
#include "http_request.hpp"
#include "http_response.hpp"
#include "mime/mime.hpp"
#include "server/memory_resource_manager.hpp"
//#include "url/url.hpp"
#include "external/decimal_from.hpp"
namespace scymnus {
template <int Status> using status_t = std::integral_constant<int, Status>;
template <int Status> constexpr status_t<Status> status;
template <http_content_type ContentType>
using content_t = std::integral_constant<http_content_type, ContentType>;
template <http_content_type ContentType>
constexpr content_t<ContentType> content_type;
struct no_content {};
template <int Status, class T,
http_content_type ContentType = http_content_type::NONE>
struct meta_info {
static constexpr int status = Status;
static constexpr http_content_type content_type = ContentType;
};
struct context {
using allocator_type = std::pmr::polymorphic_allocator<char>;
std::pmr::string *output_buffer_;
explicit context(std::pmr::string *output_buffer,
allocator_type allocator = {})
: output_buffer_{output_buffer}, raw_url_{allocator}, req_{allocator},
res_{allocator} {}
const std::pmr::string &raw_url() const { return raw_url_; }
http_method method() const { return method_; }
// request related methods
const http_request &request() const { return req_; }
const std::pmr::string &request_body() const { return req_.body_; }
void add_request_header(const std::pmr::string &field,
const std::pmr::string &value) {
req_.headers_.emplace(field, value);
}
void add_request_header(std::pmr::string &&field, std::pmr::string &&value) {
req_.headers_.emplace(std::move(field), std::move(value));
}
// response related methods
const http_response &response() const { return res_; }
std::string_view response_body() const { return res_.body_; }
void add_response_header(const std::pmr::string &field,
const std::pmr::string &value) {
res_.headers_.emplace(field, value);
}
void add_response_header(std::pmr::string &&field, std::pmr::string &&value) {
res_.headers_.emplace(std::move(field), std::move(value));
}
template <http_content_type ContentType, int Status, int N, class... H>
auto write_as(status_t<Status> st, const char (&body)[N], H &&...headers) {
start_buffer_position_ = output_buffer_->size();
using json = nlohmann::json;
static_assert(ContentType != http_content_type::NONE,
"a content type, different from NONE, must be selected");
content_type = ContentType;
res_.status_code_ = st;
output_buffer_->append(status_codes.at(Status));
output_buffer_->append(to_string_view(ContentType));
for (auto &v : res_.headers_) {
output_buffer_->append(v.first);
output_buffer_->append(":");
output_buffer_->append(v.second);
output_buffer_->append("\r\n");
}
output_buffer_->append("Content-Length:");
char buff[24];
if constexpr (ContentType == http_content_type::JSON) {
json v = body;
auto payload = v.dump();
auto size = payload.size();
output_buffer_->append(decimal_from(size, buff));
//output_buffer_->append(fmt::format_int(size).c_str());
output_buffer_->append("\r\nServer:scymnus\r\n");
date_manager::instance().append_http_time(*output_buffer_);
output_buffer_->append(payload);
res_.body_ = {output_buffer_->end() - size, output_buffer_->end()};
} else {
output_buffer_->append(decimal_from(N-1, buff));
//output_buffer_->append(fmt::format_int(N - 1).c_str());
output_buffer_->append("\r\nServer:scymnus\r\n");
date_manager::instance().append_http_time(*output_buffer_);
output_buffer_->append(body);
res_.body_ = {output_buffer_->end() - N - 1, output_buffer_->end()};
}
return meta_info<Status, const char *, ContentType>{};
}
template <http_content_type ContentType, int Status, class T, class... H>
auto write_as(status_t<Status> st, T &&body, H &&...headers) {
static_assert(ContentType != http_content_type::NONE,
"a content type, different from NONE, must be selected");
start_buffer_position_ = output_buffer_->size();
using json = nlohmann::json;
content_type = ContentType;
if constexpr (is_string_like_v<T>) {
res_.status_code_ = st;
if constexpr (ContentType == http_content_type::JSON) {
if (json::accept(body)) {
write_response_headers(body.size());
output_buffer_->append(body);
res_.body_ = {output_buffer_->end() - body.size(),
output_buffer_->end()};
} else {
auto payload = json(std::forward<T>(body)).dump();
write_response_headers(payload.size());
output_buffer_->append(payload);
res_.body_ = {output_buffer_->end() - payload.size(),
output_buffer_->end()};
}
return meta_info<sizeof(T)?Status:0, T, http_content_type::JSON>{};
} else { // plain text
write_response_headers(body.size());
output_buffer_->append(body);
res_.body_ = {output_buffer_->end() - body.size(),
output_buffer_->end()};
return meta_info<sizeof(T)?Status:0, T, http_content_type::PLAIN_TEXT>{};
}
}
else if constexpr (std::is_constructible_v<json, std::remove_cv_t<T>>) {
static_assert(sizeof(T) && ContentType == http_content_type::JSON,
"content type must be JSON");
auto payload = json(std::forward<T>(body)).dump();
res_.status_code_ = st;
write_response_headers(payload.size());
output_buffer_->append(payload);
res_.body_ = {output_buffer_->end() - payload.size(),
output_buffer_->end()};
return meta_info<sizeof(T)?Status:0, T, ContentType>{};
}
else {
static_assert(!sizeof(T), "Type not supported");
}
};
template <int Status, int N, class... H>
auto write(status_t<Status> st, const char (&body)[N], H &&...headers) {
start_buffer_position_ = output_buffer_->size();
content_type = http_content_type::PLAIN_TEXT;
res_.status_code_ = st;
output_buffer_->append(status_codes.at(Status));
output_buffer_->append(to_string_view(http_content_type::PLAIN_TEXT));
for (auto &v : res_.headers_) {
output_buffer_->append(v.first);
output_buffer_->append(":");
output_buffer_->append(v.second);
output_buffer_->append("\r\n");
}
output_buffer_->append("Content-Length:");
char buff[24];
output_buffer_->append(decimal_from(N-1, buff));
//output_buffer_->append(fmt::format_int(N - 1).c_str());
output_buffer_->append("\r\nServer:scymnus\r\n");
date_manager::instance().append_http_time(*output_buffer_);
output_buffer_->append(body);
res_.body_ = {output_buffer_->end() - N - 1, output_buffer_->end()};
return meta_info<Status, const char *, http_content_type::PLAIN_TEXT>{};
}
template <int Status, class T, class... H>
auto write(status_t<Status> st, T &&body, H &&...headers) {
using json = nlohmann::json;
start_buffer_position_ = output_buffer_->size();
if constexpr (std::is_same_v<std::remove_cv_t<T>, std::string>) {
content_type = http_content_type::PLAIN_TEXT;
res_.status_code_ = st;
write_response_headers(body.size());
output_buffer_->append(body);
res_.body_ = {output_buffer_->end() - body.size(), output_buffer_->end()};
return meta_info<Status, T, http_content_type::PLAIN_TEXT>{};
} else if constexpr (std::is_constructible_v<json, std::remove_cv_t<T>>) {
json v = std::forward<T>(body);
auto payload = v.dump();
content_type = http_content_type::JSON;
res_.status_code_ = st;
write_response_headers(payload.size());
output_buffer_->append(payload);
res_.body_ = {output_buffer_->end() - payload.size(),
output_buffer_->end()};
return meta_info<Status, T, http_content_type::JSON>{};
}
else {
static_assert(!sizeof(T), "Type is not supported");
}
};
// for No Content
template <int Status, class... H>
[[deprecated("HTTP status code should be 204 when there is no content")]] auto
write(status_t<Status> st, H &&...headers) requires(Status == 200) {
write_no_content<Status>();
return meta_info<Status, no_content, http_content_type::NONE>{};
}
template <int Status, class... H>
auto write(status_t<Status> st, H &&...headers) requires(Status != 200) {
write_no_content<Status>();
return meta_info<Status, no_content, http_content_type::NONE>{};
}
void write_file(const std::filesystem::path &p) {
namespace fs = std::filesystem;
if (!p.has_filename() || !fs::exists(p)) {
write(status<404>);
return;
}
std::ifstream stream(p.c_str(), std::ios::binary);
std::string body(std::istreambuf_iterator<char>{stream}, {});
auto ct = mime_map::content_type(p.extension().string());
if (ct) {
std::pmr::string value{memory_resource_manager::instance().pool()};
value.append(*ct);
add_response_header("Content-Type", std::move(value));
}
res_.status_code_ = 200;
write_response_headers(body.size());
output_buffer_->append(body);
res_.body_ = {output_buffer_->end() - body.size(), output_buffer_->end()};
}
void write_response_headers(std::size_t size) {
if (res_.status_code_.value() == 200)
output_buffer_->append("HTTP/1.1 200 OK\r\n");
else {
auto status = status_codes.at(res_.status_code_.value_or(500), 500);
output_buffer_->append(status);
}
if (content_type != http_content_type::NONE)
output_buffer_->append(to_string_view(content_type));
for (auto &v : res_.headers_) {
output_buffer_->append(v.first);
output_buffer_->append(":");
output_buffer_->append(v.second);
output_buffer_->append("\r\n");
}
output_buffer_->append("Content-Length:");
char buff[24];
output_buffer_->append(decimal_from(size, buff));
//output_buffer_->append(fmt::format_int(size).c_str());
output_buffer_->append("\r\nServer:scymnus\r\n");
date_manager::instance().append_http_time(*output_buffer_);
}
// in case of an exception clear is called to clean up
// the output_buffer
// erase might throw an out of range exception if start_buffer_position is
// beyond end of string
void clear() noexcept {
if (is_response_written()){
res_.reset();
output_buffer_->erase(start_buffer_position_, std::string::npos);
}
}
void reset() {
query_.reset();
raw_url_.clear();
req_.reset();
res_.reset();
start_buffer_position_ = std::numeric_limits<size_t>::max();
}
bool is_response_written() {
return start_buffer_position_ != std::numeric_limits<size_t>::max();
}
// write support
query_string get_query_string() {
if (query_)
return query_.value();
query_ = query_string();
auto query_start = raw_url_.find('?');
if (query_start != std::string::npos && query_start != raw_url_.size()) {
query_.value().parse(
{raw_url_.data() + query_start + 1, raw_url_.size()});
}
return query_.value();
}
http_content_type content_type{http_content_type::NONE};
private:
friend class connection;
template <int Status> void write_no_content() {
start_buffer_position_ = output_buffer_->size();
res_.status_code_ = Status;
output_buffer_->append(status_codes.at(Status));
for (auto &v : res_.headers_) {
output_buffer_->append(v.first);
output_buffer_->append(":");
output_buffer_->append(v.second);
output_buffer_->append("\r\n");
}
output_buffer_->append("Content-Length:0");
output_buffer_->append("\r\nServer:scymnus\r\n");
date_manager::instance().append_http_time(*output_buffer_);
}
http_request req_;
http_response res_;
std::optional<query_string> query_;
http_method method_;
std::pmr::string raw_url_;
std::size_t start_buffer_position_{std::numeric_limits<size_t>::max()};
};
} // namespace scymnus
| 36.126984 | 89 | 0.603691 |
8e3fc245d1db558c8a00cf72a0a4d0f26e5e772f | 669 | cc | C++ | test/collections/btree_map.cc | Alexhuszagh/funxx | 9f6c1fae92d96a84282fc62be272f4dc1e1dba9b | [
"MIT",
"BSD-3-Clause"
] | 1 | 2017-07-21T22:58:38.000Z | 2017-07-21T22:58:38.000Z | test/collections/btree_map.cc | Alexhuszagh/funxx | 9f6c1fae92d96a84282fc62be272f4dc1e1dba9b | [
"MIT",
"BSD-3-Clause"
] | null | null | null | test/collections/btree_map.cc | Alexhuszagh/funxx | 9f6c1fae92d96a84282fc62be272f4dc1e1dba9b | [
"MIT",
"BSD-3-Clause"
] | null | null | null | // :copyright: (c) 2017 Alex Huszagh.
// :license: MIT, see LICENSE.md for more details.
/*
* \addtogroup Tests
* \brief B-tree map unittests.
*/
#include <pycpp/collections/btree_map.h>
#include <gtest/gtest.h>
PYCPP_USING_NAMESPACE
// TESTS
// -----
TEST(btree_map, constructor_null)
{
using map = btree_map<int, int>;
map m1, m2;
EXPECT_EQ(m1.size(), 0);
EXPECT_EQ(m2.size(), 0);
EXPECT_TRUE(m1.find(1) == m1.end());
EXPECT_TRUE(m2.find(1) == m2.end());
m1.insert(make_pair(1, 1));
EXPECT_EQ(m1.size(), 1);
EXPECT_EQ(m2.size(), 0);
EXPECT_TRUE(m1.find(1) != m1.end());
EXPECT_TRUE(m2.find(1) == m2.end());
}
| 20.272727 | 51 | 0.61136 |
8e44e5ce8037c084d185b31b2dfa3424701da62a | 2,905 | cpp | C++ | 2020/04.cpp | mdelorme/advent_of_code | 47142d501055fc0d36989db9b189be7e6756d779 | [
"Unlicense"
] | null | null | null | 2020/04.cpp | mdelorme/advent_of_code | 47142d501055fc0d36989db9b189be7e6756d779 | [
"Unlicense"
] | null | null | null | 2020/04.cpp | mdelorme/advent_of_code | 47142d501055fc0d36989db9b189be7e6756d779 | [
"Unlicense"
] | null | null | null | #include <bits/stdc++.h>
std::vector<std::string> passports;
bool is_valid(std::string str) {
str = str.substr(1);
std::istringstream iff(str);
bool valid=true;
try {
for (std::string s; iff >> s;) {
size_t pos = s.find(":");
std::string key = s.substr(0, pos);
std::string value = s.substr(pos+1);
if (key == "byr") {
int byr = std::stoi(value);
if (byr < 1920 || byr > 2002)
valid = false;
}
else if (key == "iyr") {
int iyr = std::stoi(value);
if (iyr < 2010 || iyr > 2020)
valid = false;
}
else if (key == "eyr") {
int eyr = std::stoi(value);
if (eyr < 2020 || eyr > 2030)
valid = false;
}
else if (key == "hgt") {
int height = std::stoi(value.substr(0, value.size()-2));
std::string unit = value.substr(value.size()-2);
if (unit == "in") {
valid = (height >= 59 && height <= 76);
}
else if (unit == "cm") {
valid = (height >= 150 && height <= 193);
}
else
valid = false;
}
else if (key == "hcl") {
std::regex regexp("#[[:xdigit:]]{6}");
valid = std::regex_match(value, regexp);
}
else if (key == "ecl"){
std::array<std::string, 7> valid_eyes {"amb", "blu", "brn", "gry", "grn", "hzl", "oth"};
valid = (std::find(valid_eyes.begin(), valid_eyes.end(), value) != valid_eyes.end());
}
else if (key == "pid") {
std::regex regexp("[[:digit:]]{9}");
valid = std::regex_match(value, regexp);
}
if (!valid)
return false;
}
}
catch(...) {
return false;
}
return valid;
}
void part1() {
uint nvalid=0;
std::string needed_keys[] {"byr", "iyr", "eyr", "hgt", "ecl", "hcl", "pid"};
for (auto p: passports) {
bool valid = true;
for (auto k: needed_keys) {
if (p.find(k) == std::string::npos) {
valid = false;
break;
}
}
if (valid)
nvalid++;
}
std::cout << "Part 1 : " << nvalid << std::endl;
}
void part2() {
uint nvalid=0;
std::string needed_keys[] {"byr", "iyr", "eyr", "hgt", "ecl", "hcl", "pid"};
for (auto p: passports) {
bool valid = true;
for (auto k: needed_keys) {
if (p.find(k) == std::string::npos) {
valid = false;
break;
}
}
if (valid && is_valid(p))
nvalid++;
}
std::cout << "Part 2 : " << nvalid << std::endl;
}
int main(int argc, char **argv) {
std::ifstream f_in;
f_in.open("04.in");
while (!f_in.eof()) {
std::string line;
std::getline(f_in, line);
std::string passport_line = "";
while (line != "") {
passport_line += " " + line;
std::getline(f_in, line);
}
passports.push_back(passport_line);
}
f_in.close();
part1();
part2();
return 0;
}
| 22.346154 | 96 | 0.483305 |
8e47d105a11187712c0cb262db1c1cccb0d83f5f | 7,731 | cpp | C++ | modules/build_seqset/correct_reads_test.cpp | spiralgenetics/biograph | 33c78278ce673e885f38435384f9578bfbf9cdb8 | [
"BSD-2-Clause"
] | 16 | 2021-07-14T23:32:31.000Z | 2022-03-24T16:25:15.000Z | modules/build_seqset/correct_reads_test.cpp | spiralgenetics/biograph | 33c78278ce673e885f38435384f9578bfbf9cdb8 | [
"BSD-2-Clause"
] | 9 | 2021-07-20T20:39:47.000Z | 2021-09-16T20:57:59.000Z | modules/build_seqset/correct_reads_test.cpp | spiralgenetics/biograph | 33c78278ce673e885f38435384f9578bfbf9cdb8 | [
"BSD-2-Clause"
] | 9 | 2021-07-15T19:38:35.000Z | 2022-01-31T19:24:56.000Z | #include "modules/build_seqset/correct_reads.h"
#include "modules/bio_base/dna_testutil.h"
#include "modules/build_seqset/part_repo.h"
#include "modules/io/config.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
namespace {
using namespace testing;
using namespace build_seqset;
using namespace dna_testutil;
} // namespace
class correct_reads_test : public Test {
public:
void SetUp() override {
static size_t n = 0;
boost::filesystem::create_directories(CONF_S(temp_root));
m_ref_path_prefix = CONF_S(temp_root) + "/ref";
m_ref_path_prefix += std::to_string(n);
m_repo_path = CONF_S(temp_root) + "/repo";
m_repo_path += std::to_string(n);
m_entries.emplace(m_depth, m_ref_path_prefix, m_repo_path);
m_entries->open_write_pass("initial");
++n;
}
void set_initial_repo(dna_slice seq) { m_entries->add_initial_repo(seq); }
void add_kmers(dna_slice seq) {
CHECK_GE(seq.size(), m_kmer_size);
for (auto it = seq.begin(); (it + m_kmer_size - 1) != seq.end(); ++it) {
m_kmers.insert(canonicalize(make_kmer(it, m_kmer_size), m_kmer_size));
}
m_first_kmers.insert(make_kmer(seq.begin(), m_kmer_size));
m_first_kmers.insert(make_kmer(seq.rcbegin(), m_kmer_size));
m_kmer_bases += seq.size();
}
void start_correction() {
m_ks.emplace(m_kmer_bases, m_kmer_size, get_maximum_mem_bytes(),
[&](const kmer_set::kmer_output_f& out_f, progress_handler_t) {
for (kmer_t k : m_kmers) {
unsigned flags = 0;
if (m_first_kmers.count(k)) {
flags |= kmer_set::k_fwd_starts_read;
}
if (m_first_kmers.count(rev_comp(k, m_kmer_size))) {
flags |= kmer_set::k_rev_starts_read;
}
out_f(k, flags);
}
});
m_entries->flush();
m_entries->open_write_pass("initial");
m_cr.emplace(*m_entries, *m_ks, m_params);
m_cr->add_initial_repo();
}
void add_read(dna_slice seq) {
unaligned_read r;
r.sequence = seq.as_string();
corrected_read c;
m_cr->correct(r, c);
}
void load_repo() {
m_cr.reset();
m_entries->flush();
}
std::set<dna_sequence> stored_sequences() {
CHECK(m_entries);
std::set<dna_sequence> seqs;
std::mutex mu;
m_entries->for_each_partition("initial",
[&](const part_repo::partition_ref& part) {
std::lock_guard<std::mutex> l(mu);
for (const auto& e : *part.main) {
seqs.insert(e.sequence());
}
});
return seqs;
}
Matcher<const std::set<dna_sequence>&> ContainsAllOf(const std::set<dna_sequence>& seqs) {
CHECK_GT(seqs.size(), 0);
Matcher<const std::set<dna_sequence>&> result = _;
for (const auto& seq : seqs) {
result = AllOf(result, Contains(seq));
}
return result;
}
protected:
std::string m_ref_path_prefix;
std::string m_repo_path;
size_t m_kmer_bases = 0;
std::set<kmer_t> m_kmers;
std::set<kmer_t> m_first_kmers;
boost::optional<kmer_set> m_ks;
boost::optional<part_repo> m_entries;
boost::optional<correct_reads> m_cr;
read_correction_params m_params;
unsigned m_depth = 1;
unsigned m_kmer_size = 2 * k_dna_test_sequence_length;
};
TEST_F(correct_reads_test, simple_fwd) {
add_kmers(tseq("bcde"));
add_kmers(dna_sequence("GA") + tseq("bcde") + dna_sequence("A"));
start_correction();
add_read(dna_sequence("GA") + tseq("bcde") + dna_sequence("A"));
load_repo();
std::set<dna_sequence> expected = {
dna_sequence("GA") + tseq("bcde") + dna_sequence("A"),
dna_sequence("A") + tseq("bcde") + dna_sequence("A"),
(dna_sequence("GA") + tseq("bcde") + dna_sequence("A")).rev_comp()};
EXPECT_THAT(stored_sequences(), ContainerEq(expected));
EXPECT_EQ(m_entries->repo_slice().size() / 4,
((dna_sequence("GA") + tseq("bcde") + dna_sequence("A")).size() + 3) / 4);
}
TEST_F(correct_reads_test, simple_rc) {
add_kmers(tseq("bcde"));
add_kmers(dna_sequence("A") + tseq("bcde") + dna_sequence("GA"));
start_correction();
add_read(dna_sequence("A") + tseq("bcde") + dna_sequence("GA"));
load_repo();
std::set<dna_sequence> expected = {
(dna_sequence("A") + tseq("bcde") + dna_sequence("GA")).rev_comp(),
(dna_sequence("A") + tseq("bcde") + dna_sequence("G")).rev_comp(),
(dna_sequence("A") + tseq("bcde") + dna_sequence("GA"))};
EXPECT_THAT(stored_sequences(), ContainerEq(expected));
EXPECT_EQ(m_entries->repo_slice().size() / 4,
((dna_sequence("A") + tseq("bcde") + dna_sequence("GA")).size() + 3) / 4);
}
TEST_F(correct_reads_test, fwd_in_repo) {
set_initial_repo(tseq("abcdefghij"));
add_kmers(tseq("abcd"));
add_kmers(tseq("ghij"));
start_correction();
add_read(tseq("abcd"));
add_read(tseq("ghij"));
load_repo();
std::set<dna_sequence> expected = {dna_sequence(tseq("abcd")), dna_sequence(tseq_rc("abcd")),
dna_sequence(tseq("ghij")), dna_sequence(tseq_rc("ghij"))};
EXPECT_THAT(stored_sequences(), ContainsAllOf(expected));
EXPECT_EQ(m_entries->repo_slice().size() / 4, (tseq("abcdefghij").size() + 3) / 4);
}
TEST_F(correct_reads_test, rc_in_repo) {
set_initial_repo(tseq_rc("abcdefghij"));
add_kmers(tseq("abcd"));
add_kmers(tseq("ghij"));
start_correction();
add_read(tseq("abcd"));
add_read(tseq("ghij"));
load_repo();
std::set<dna_sequence> expected = {
dna_sequence(tseq("abcd")), dna_sequence(tseq_rc("abcd")),
dna_sequence(tseq("ghij")), dna_sequence(tseq_rc("ghij"))};
EXPECT_THAT(stored_sequences(), ContainsAllOf(expected));
EXPECT_EQ(m_entries->repo_slice().size() / 4,
(tseq_rc("abcdefghij").size() + 3) / 4);
}
TEST_F(correct_reads_test, fwd_almost_in_repo) {
set_initial_repo(tseq("abcdefghij"));
add_kmers(dna_G + tseq("abcd"));
add_kmers((dna_G + tseq("abcd")).subseq(1, tseq("abcd").size() - 1));
add_kmers(tseq("ghij") + dna_G);
add_kmers((tseq("ghij") + dna_G).subseq(1, tseq("ghij").size() - 1));
start_correction();
add_read(dna_G + tseq("abcd"));
add_read(tseq("ghij") + dna_G);
load_repo();
std::set<dna_sequence> expected = {dna_sequence(dna_G + tseq("abcd")),
dna_sequence(tseq_rc("abcd") + dna_C),
dna_sequence(tseq("ghij") + dna_G),
dna_sequence(dna_C + tseq_rc("ghij"))};
EXPECT_THAT(stored_sequences(), ContainerEq(expected));
EXPECT_GT(m_entries->repo_slice().size() / 4,
(tseq("abcdefghij").size() + 3) / 4);
}
TEST_F(correct_reads_test, rev_almost_in_repo) {
set_initial_repo(tseq_rc("abcdefghij"));
add_kmers(dna_G + tseq("abcd"));
add_kmers((dna_G + tseq("abcd")).subseq(1, tseq("abcd").size() - 1));
add_kmers(tseq("ghij") + dna_G);
add_kmers((tseq("ghij") + dna_G).subseq(1, tseq("ghij").size() - 1));
start_correction();
add_read(dna_G + tseq("abcd"));
add_read(tseq("ghij") + dna_G);
load_repo();
std::set<dna_sequence> expected = {dna_sequence(dna_G + tseq("abcd")),
dna_sequence(tseq_rc("abcd") + dna_C),
dna_sequence(tseq("ghij") + dna_G),
dna_sequence(dna_C + tseq_rc("ghij"))};
EXPECT_THAT(stored_sequences(), ContainerEq(expected));
EXPECT_GT(m_entries->repo_slice().size() / 4,
(tseq("abcdefghij").size() + 3) / 4);
}
| 34.513393 | 96 | 0.608071 |
8e4db243cb4788f9aafac665ea049faaf53059e3 | 1,105 | cpp | C++ | Actividad2_recibe/ventanaarchivoexistente.cpp | adricatena/I2-puertoSerie | cb9efbde2bf30e517649e80a9ebb585449194287 | [
"MIT"
] | null | null | null | Actividad2_recibe/ventanaarchivoexistente.cpp | adricatena/I2-puertoSerie | cb9efbde2bf30e517649e80a9ebb585449194287 | [
"MIT"
] | null | null | null | Actividad2_recibe/ventanaarchivoexistente.cpp | adricatena/I2-puertoSerie | cb9efbde2bf30e517649e80a9ebb585449194287 | [
"MIT"
] | null | null | null | #include "ventanaarchivoexistente.h"
#include "ui_ventanaarchivoexistente.h"
VentanaArchivoExistente::VentanaArchivoExistente(QWidget *parent) :
QDialog(parent),
ui(new Ui::VentanaArchivoExistente)
{
ui->setupUi(this);
configuracion = new QSettings("Informatica II", "Actividad 2", this);
}
VentanaArchivoExistente::~VentanaArchivoExistente()
{
delete configuracion;
delete ui;
}
void VentanaArchivoExistente::on_btnAceptar_clicked()
{
if(ui->checkBoxSi->isChecked() && ui->checkBoxNo->isChecked())
{
msj.setText("Error! Ambas opciones estan seleccionadas.");
msj.exec();
}
else
{
if(ui->checkBoxNo->isChecked())
{
QString nombreViejo = configuracion->value("Nombre", "").toString();
QString nombreNuevo = nombreViejo.left(nombreViejo.lastIndexOf('/')) + ui->leNombreArchivo->text();
configuracion->setValue("Nombre", nombreNuevo);
}
QDialog::accept();
}
}
void VentanaArchivoExistente::on_btnCancelar_clicked()
{
close();
}
| 26.95122 | 112 | 0.640724 |
8e4f9a1fc9b1d1a49e96f9ef39fff5f0ef06b3c1 | 1,791 | cpp | C++ | dev/Gems/EMotionFX/Code/Tests/UI/LY-93621.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 1,738 | 2017-09-21T10:59:12.000Z | 2022-03-31T21:05:46.000Z | dev/Gems/EMotionFX/Code/Tests/UI/LY-93621.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 427 | 2017-09-29T22:54:36.000Z | 2022-02-15T19:26:50.000Z | dev/Gems/EMotionFX/Code/Tests/UI/LY-93621.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 671 | 2017-09-21T08:04:01.000Z | 2022-03-29T14:30:07.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <Tests/UI/CommandRunnerFixture.h>
namespace EMotionFX
{
INSTANTIATE_TEST_CASE_P(LY93621, CommandRunnerFixture,
::testing::Values(std::vector<std::string> {
R"str(CreateAnimGraph)str",
R"str(AnimGraphAddGroupParameter -animGraphID 0 -name Group0)str",
R"str(AnimGraphAdjustParameter -animGraphID 0 -name Group0 -newName Group01 -type {6B42666E-82D7-431E-807E-DA789C53AF05} -contents <ObjectStream version="3">
<Class name="GroupParameter" version="1" type="{6B42666E-82D7-431E-807E-DA789C53AF05}">
<Class name="Parameter" field="BaseClass1" version="1" type="{4AF0BAFC-98F8-4EA3-8946-4AD87D7F2A6C}">
<Class name="AZStd::string" field="name" value="Group01" type="{03AAAB3F-5C47-5A66-9EBC-D5FA4DB353C9}"/>
<Class name="AZStd::string" field="description" value="" type="{03AAAB3F-5C47-5A66-9EBC-D5FA4DB353C9}"/>
</Class>
<Class name="AZStd::vector" field="childParameters" type="{496E6454-2F91-5CDC-9771-3B589F3F8FEB}"/>
</Class>
</ObjectStream>)str",
}
));
} // end namespace EMotionFX
| 54.272727 | 169 | 0.646008 |
8e53f4f2c6c82933b403124f1fac80b47f2c14b7 | 5,556 | hpp | C++ | include/multi_trie_index.hpp | kampersanda/frechet_simsearch | c91e0b12f0acf5f8a563ec16d71bf76bc0dc169c | [
"MIT"
] | 7 | 2019-10-07T08:48:44.000Z | 2022-03-23T02:39:45.000Z | include/multi_trie_index.hpp | kampersanda/frechet_simsearch | c91e0b12f0acf5f8a563ec16d71bf76bc0dc169c | [
"MIT"
] | null | null | null | include/multi_trie_index.hpp | kampersanda/frechet_simsearch | c91e0b12f0acf5f8a563ec16d71bf76bc0dc169c | [
"MIT"
] | 1 | 2019-12-23T16:33:01.000Z | 2019-12-23T16:33:01.000Z | #pragma once
#include "trit_array_trie.hpp"
#include "vcode_array.hpp"
namespace frechet_simsearch {
template <class Point, uint32_t Length>
class MultiTrieIndex {
public:
using point_type = Point;
using vcode_trait_type = VCodeTraits<Length>;
using vint_type = typename vcode_trait_type::vint_type;
using hasher_type = FrechetHasher<Point, Length>;
using database_type = VCodeArray<Point, Length>;
using trie_type = TritArrayTrie;
public:
MultiTrieIndex() = default;
MultiTrieIndex(const std::vector<Curve<Point>>& curves, const Configure& cfg)
: m_indexes(cfg.buckets), m_bucket_begs(cfg.buckets + 1) {
const size_t n_curves = curves.size();
std::vector<uint8_t> codes_buf(n_curves * Length);
std::vector<const uint8_t*> codes(n_curves);
{
size_t i = 0;
m_database = std::make_unique<database_type>(curves, cfg, [&](const uint8_t* code) {
const size_t beg = i * Length;
std::copy(code, code + Length, &codes_buf[beg]);
codes[i++] = &codes_buf[beg];
});
}
uint32_t bkt_beg = 0;
for (uint32_t b = 0; b < cfg.buckets; ++b) {
m_bucket_begs[b] = bkt_beg;
bkt_beg += (b + Length) / cfg.buckets;
}
m_bucket_begs[cfg.buckets] = bkt_beg;
tfm::printfln("[MultiTrieIndex construction]");
for (uint32_t b = 0; b < cfg.buckets; ++b) {
uint32_t sub_length = m_bucket_begs[b + 1] - m_bucket_begs[b];
tfm::printfln("# bucket %d (L=%d)", b, sub_length);
m_indexes[b] = std::make_unique<trie_type>(codes, sub_length, cfg.reduction_threshold);
for (size_t i = 0; i < n_curves; ++i) {
codes[i] += sub_length;
}
tfm::printfln("# - %d nodes; %f values per leaf", //
m_indexes[b]->get_num_nodes(), m_indexes[b]->get_num_values_per_leaf());
}
m_candidates.reserve(1U << 16); // for range_search
}
~MultiTrieIndex() = default;
size_t range_search(const Curve<Point>& query_curve, uint32_t hamming_range, std::function<void(size_t)> fn) {
m_candidates.clear();
size_t num_candidates = 0;
const uint8_t* qcode = m_database->get_hasher().hash_code8(query_curve.points);
const vint_type* qvcode = vcode_trait_type::to_vints(qcode, DOMAIN_BITS);
const int32_t buckets = static_cast<int32_t>(m_indexes.size());
const int32_t gph_range = int32_t(hamming_range) - buckets + 1;
for (int32_t b = 0; b < buckets; ++b) {
if (gph_range + b < 0) {
continue;
}
const int32_t sub_range = (gph_range + b) / buckets;
const uint8_t* sub_qcode = qcode + m_bucket_begs[b];
m_indexes[b]->range_search(sub_qcode, sub_range, [&](uint32_t id) { m_candidates.push_back(id); });
}
std::sort(m_candidates.begin(), m_candidates.end());
uint32_t prev_id = uint32_t(-1);
for (size_t i = 0; i < m_candidates.size(); ++i) {
const uint32_t cand_id = m_candidates[i];
if (prev_id == cand_id) {
continue;
}
uint32_t hamming_dist =
vcode_trait_type::get_hamming_distance(qvcode, m_database->get(cand_id), DOMAIN_BITS);
if (hamming_dist <= hamming_range) {
fn(cand_id);
}
prev_id = cand_id;
++num_candidates;
}
return num_candidates;
}
// in bytes
size_t get_memory_usage() const {
return get_index_memory_usage() + get_database_memory_usage();
}
size_t get_index_memory_usage() const {
size_t memory = 0;
for (size_t b = 0; b < m_indexes.size(); ++b) {
memory += m_indexes[b]->get_memory_usage();
}
memory += m_bucket_begs.size() * sizeof(uint32_t);
return memory;
}
size_t get_database_memory_usage() const {
return m_database->get_memory_usage();
}
size_t get_ITLB() const {
return get_index_ITLB() + get_database_memory_usage();
}
size_t get_index_ITLB() const {
size_t memory = 0;
for (size_t b = 0; b < m_indexes.size(); ++b) {
memory += m_indexes[b]->get_ITLB();
}
memory += m_bucket_begs.size() * sizeof(uint32_t);
return memory;
}
size_t size() const {
return m_database->size();
}
const VCodeArray<Point, Length>& get_database() const {
return *m_database.get();
}
size_t get_num_nodes() const {
size_t num = 0;
for (size_t b = 0; b < m_indexes.size(); ++b) {
num += m_indexes[b]->get_num_nodes();
}
return num;
}
size_t get_num_inner_nodes() const {
size_t num = 0;
for (size_t b = 0; b < m_indexes.size(); ++b) {
num += m_indexes[b]->get_num_inner_nodes();
}
return num;
}
float get_num_values_per_leaf() const {
float sum = 0.0;
for (size_t b = 0; b < m_indexes.size(); ++b) {
sum += m_indexes[b]->get_num_values_per_leaf();
}
return sum / m_indexes.size();
}
private:
std::unique_ptr<database_type> m_database;
std::vector<std::unique_ptr<trie_type>> m_indexes;
std::vector<uint32_t> m_bucket_begs;
// for seach
std::vector<uint32_t> m_candidates;
};
} // namespace frechet_simsearch | 33.46988 | 114 | 0.578294 |
8e56d9e614f40f44f8657bdba23674583775c8bd | 2,620 | cpp | C++ | src/frame_transformation.cpp | sakshikakde/human-detector-and-tracker | 04e1fd08b858ababfa4fa91da8306890ef1d7d00 | [
"MIT"
] | null | null | null | src/frame_transformation.cpp | sakshikakde/human-detector-and-tracker | 04e1fd08b858ababfa4fa91da8306890ef1d7d00 | [
"MIT"
] | 3 | 2021-10-16T05:46:37.000Z | 2021-10-18T22:16:20.000Z | src/frame_transformation.cpp | sakshikakde/human-detector-and-tracker | 04e1fd08b858ababfa4fa91da8306890ef1d7d00 | [
"MIT"
] | 2 | 2021-10-06T02:52:31.000Z | 2021-10-06T05:16:28.000Z | /**
* MIT License
*
* Copyright (c) 2021 Anubhav Paras, Sakshi Kakde, Siddharth Telang
*
* 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.
*
* @file frame_transformation.cpp
* @author Anubhav Paras (anubhav@umd.edu)
* @author Sakshi Kakde (sakshi@umd.edu)
* @author Siddharth Telang (stelang@umd.edu)
* @brief Performs frame transformation
* @version 0.1
* @date 2021-10-25
*
* @copyright Copyright (c) 2021
*
*/
#include <frame_transformation.hpp>
FrameTransformation::FrameTransformation() {
// camera intrinsic matrix
this->K = Eigen::MatrixXf(3, 3);
this->K << 964.828979, 0, 643.788025, 0, 964.828979, 484.407990, 0, 0, 1;
this->T_c = Eigen::MatrixXf(3, 4);
this->T_c << 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0;
this->T_r = Eigen::MatrixXf(4, 4);;
this->T_r<< 0, 0, 1, 10, -1, 0, 0, 10, 0, -1, 0, 10, 0, 0, 0, 1;
// Projection matrix
this->P = this->K * this->T_c * this->T_r;
}
FrameTransformation::~FrameTransformation() {}
Coord3D FrameTransformation::getRobotFrame(Coord2D imageCoordinates) {
// logic goes here
// Calculate P inverse
Eigen::MatrixXf P_T = this->P.transpose();
Eigen::MatrixXf P_inv = P_T * (this->P * P_T).inverse();
// Image coordinates to homogenous coordinates
Eigen::MatrixXf x(3, 1);
x << imageCoordinates.x, imageCoordinates.y, 1;
Eigen::MatrixXf X = P_inv * x;
// populate Coord3D
Coord3D X_robot;
if (X(3, 0) != 0) {
X_robot.x = X(0, 0) / X(3, 0);
X_robot.y = X(1, 0) / X(3, 0);
X_robot.z = X(2, 0) / X(3, 0);
} else {
return Coord3D(0, 0, 0);
}
return X_robot;
}
| 35.890411 | 81 | 0.681679 |
8e5ae16a99a4d082dbe5b8f34c5a4c69add57ac0 | 2,282 | cc | C++ | conf_crawler/url_dedup/dedup_config.cc | WinterW/crawler_cpp | e0c8dba77233005b1ab13731d1cbcce274b70778 | [
"Apache-2.0"
] | null | null | null | conf_crawler/url_dedup/dedup_config.cc | WinterW/crawler_cpp | e0c8dba77233005b1ab13731d1cbcce274b70778 | [
"Apache-2.0"
] | null | null | null | conf_crawler/url_dedup/dedup_config.cc | WinterW/crawler_cpp | e0c8dba77233005b1ab13731d1cbcce274b70778 | [
"Apache-2.0"
] | 2 | 2020-09-12T13:50:38.000Z | 2020-09-16T15:55:14.000Z | /**
* @Copyright 2011 GanJi Inc.
* @file ganji/crawler/conf_crawler/url_dedup/dedup_config.cc
* @namespace ganji::crawler::conf_crawler::dedup
* @version 1.0
* @author lisizhong
* @date 2011-08-01
*
* 改动程序后, 请使用tools/cpplint/cpplint.py 检查代码是否符合编码规范!
* 遵循的编码规范请参考: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml
* Change Log:
*/
#include "conf_crawler/url_dedup/dedup_config.h"
#include <stdlib.h>
#include "util/config/config.h"
using std::string;
namespace ganji { namespace crawler { namespace conf_crawler { namespace dedup {
using ganji::util::config::Config;
int DedupConfig::CheckVal(int val, const string &name) {
if (val <= 0) {
fprintf(stderr, "%s:%d <= 0\n", name.c_str(), val);
exit(1);
}
return 0;
}
int DedupConfig::LoadConfig(const string &conf_file) {
Config conf;
conf.loadConfFile(conf_file);
conf.getItemValue(kDedupHost, dedup_host_);
conf.getItemValue(kDedupPort, dedup_port_);
conf.getItemValue(kNbThreadCount, nb_thread_count_);
conf.getItemValue(kBloomFilterMaxElem, bf_max_elem_);
string bf_fpf;
conf.getItemValue(kBloomFilterFPF, bf_fpf);
bf_fpf_ = atof(bf_fpf.c_str());
conf.getItemValue(kBucketCount, bucket_count_);
conf.getItemValue(kDayCount, day_count_);
conf.getItemValue(kMd5Path, md5_path_);
CheckVal(dedup_port_, "dedup_port_");
CheckVal(nb_thread_count_, "nb_thread_count_");
CheckVal(bf_max_elem_, "bf_max_elem_");
CheckVal(bucket_count_, "bucket_count_");
CheckVal(day_count_, "day_count_");
return 0;
}
void DedupConfig::PrintConfig() const {
fprintf(stdout, "--------------------------DedupConfig config--------------------------\n");
fprintf(stdout, "dedup host:%s\n", dedup_host_.c_str());
fprintf(stdout, "dedup port:%d\n", dedup_port_);
fprintf(stdout, "nb thread count:%d\n", nb_thread_count_);
fprintf(stdout, "bloom filter max elem:%d\n", bf_max_elem_);
fprintf(stdout, "bloom filter fpf:%f\n", bf_fpf_);
fprintf(stdout, "bucket count:%d\n", bucket_count_);
fprintf(stdout, "day count:%d\n", day_count_);
fprintf(stdout, "md5 path:%s\n", md5_path_.c_str());
fprintf(stdout, "--------------------------DedupConfig config--------------------------\n");
}
}}}}; ///< end of namespace ganji::crawler::conf_crawler::dedup
| 31.694444 | 94 | 0.689308 |
8e5b90c24846d9cb3ce2bc6863a6f6474e160be2 | 3,230 | cpp | C++ | GTraining/SortedArrayIterator.cpp | tzaffi/cpp | 43d99e70d8fa712f90ea0f6147774e4e0f2b11da | [
"MIT"
] | null | null | null | GTraining/SortedArrayIterator.cpp | tzaffi/cpp | 43d99e70d8fa712f90ea0f6147774e4e0f2b11da | [
"MIT"
] | null | null | null | GTraining/SortedArrayIterator.cpp | tzaffi/cpp | 43d99e70d8fa712f90ea0f6147774e4e0f2b11da | [
"MIT"
] | null | null | null | //
// Created by zeph on 12/4/16.
//
#include <vector>
/**
* Given two sorted Vectors, use the merge sort iteration method to iterate through the arrays
* and reduce from the union by applying the choice() function. For example, if:
* o choice = insertLeft() - always pick the left param (useful for union)
* o choice = insertLeftIfEqual() - pick the left param if both are equal (useful for intersection)
* o choice = insertLeftUnique() - always pick the left param if it is different from the previous insertion
* @tparam T - a comparable type
* @param a - an array of T's sorted in ascending order
* @param b - an array of T's sorted in ascending order
* @param insertChoice - a function that given T-values left and right and an aggregator vector to insert the
* choice into, provides logic for picking a choice and then inserts that choice into the aggreagator.
* Returns true iff a choice was inserted (false in the case when nothing was inserted)
* @param finishEarly - optional parameter defaulting to false. Set true if you want to finish early such
* as in the case of intersection.
* @return the aggregator vector from the reduction operator that was applied to a and b
*/
template <typename T>
inline std::vector<T> iterateAndReduce(const std::vector<T>& a,
const std::vector<T>& b,
bool insertChoice(const T& left, const T& right, std::vector<T>& aggregator),
bool finishEarly = false){
std::vector<T> aggregator;
auto i = a.cbegin(), j = b.cbegin();
while(i != a.cend() && j != b.cend()){
while(i != a.cend() && j != b.cend() && *i == *j){
insertChoice(*i, *j, aggregator);
++i, ++j;
}
while(i != a.cend() && j != b.cend() && *i < *j){
insertChoice(*i, *j, aggregator);
++i;
}
while(i != a.cend() && j != b.cend() && *j < *i){
insertChoice(*j, *i, aggregator);
++j;
}
}
if(!finishEarly){
while(i != a.cend()){
insertChoice(*i, *a.cbegin(), aggregator);
++i;
}
while(j != b.cend()){
insertChoice(*j, *b.cbegin(), aggregator);
++j;
}
}
return aggregator;
}
namespace Choosers{
template <typename T>
bool insertLeftIfEqual(const T& left, const T& right, std::vector<T>& aggregator){
if(left == right){
aggregator.push_back(left);
return true;
}
return false;
}
template <typename T>
bool insertLeftOrBothIfEqual (const T &left , const T &right , std::vector<T> &aggregator){
aggregator.push_back(left);
if(left == right){ aggregator.push_back(right); }
return true;
}
template <typename T>
bool insertLeftIfNewElement (const T &left , const T &right , std::vector<T> &aggregator){
auto lastInsertItr = aggregator.cend();
bool alreadyInserted = ( (lastInsertItr != aggregator.cbegin()) && (*(lastInsertItr-1) == left));
if(alreadyInserted){ return false; }
aggregator.push_back(left);
return true;
}
} | 39.390244 | 116 | 0.588854 |
8e5c5cf73edd2031dd4c597f8ce890c017208f5d | 3,459 | hh | C++ | include/tchecker/system/intvar.hh | arnabSur/tchecker | 24ba7703068a41c6e9c613b4ef80ad6c788e65bc | [
"MIT"
] | 7 | 2019-08-12T12:22:07.000Z | 2021-11-18T01:48:27.000Z | include/tchecker/system/intvar.hh | arnabSur/tchecker | 24ba7703068a41c6e9c613b4ef80ad6c788e65bc | [
"MIT"
] | 40 | 2019-07-03T04:31:19.000Z | 2022-03-31T03:40:43.000Z | include/tchecker/system/intvar.hh | arnabSur/tchecker | 24ba7703068a41c6e9c613b4ef80ad6c788e65bc | [
"MIT"
] | 8 | 2019-07-04T06:40:49.000Z | 2021-12-03T15:51:50.000Z | /*
* This file is a part of the TChecker project.
*
* See files AUTHORS and LICENSE for copyright details.
*
*/
#ifndef TCHECKER_SYSTEM_INTVAR_HH
#define TCHECKER_SYSTEM_INTVAR_HH
#include <limits>
#include <stdexcept>
#include <string>
#include <vector>
#include "tchecker/basictypes.hh"
#include "tchecker/system/attribute.hh"
#include "tchecker/variables/intvars.hh"
/*!
\file intvar.hh
\brief Bounded integer variables in systems
*/
namespace tchecker {
namespace system {
/*!
\class intvars_t
\brief Collection of bounded integer variables
*/
class intvars_t {
public:
/*!
\brief Add an integer variable
\param name : variable name
\param size : variable size (array of integer variables)
\param min : minimal value
\param max : maximal value
\param initial : initial calue
\param attr : attributes
\pre name is not a declared integer variable
\post variable name with minimal value min, maximal value max, initial value init and attributes attr has been added
\throw std::invalid_argument : if name is a declared integer variable
*/
void add_intvar(std::string const & name, tchecker::intvar_id_t size = 1,
tchecker::integer_t min = std::numeric_limits<tchecker::integer_t>::min(),
tchecker::integer_t max = std::numeric_limits<tchecker::integer_t>::max(),
tchecker::integer_t initial = std::numeric_limits<tchecker::integer_t>::min(),
tchecker::system::attributes_t const & attr = tchecker::system::attributes_t());
/*!
\brief Accessor
\param kind : kind of declared variable
\return number of declared bounded integer variables if kind = tchecker::VK_DECLARED,
number of flattened bounded integer variables if kind = tchecker::VK_FLATTENED
*/
inline tchecker::intvar_id_t intvars_count(enum tchecker::variable_kind_t kind) const
{
return _integer_variables.size(kind);
}
/*!
\brief Accessor
\param name : variable name
\return identifier of variable name
\throw std::invalid_argument : if name is not am integer variable
*/
inline tchecker::intvar_id_t intvar_id(std::string const & name) const { return _integer_variables.id(name); }
/*!
\brief Accessor
\param id : variable identifier
\return name of integer variable id
\throw std::invalid_argument : if id is not an integer variable
*/
inline std::string const & intvar_name(tchecker::intvar_id_t id) const { return _integer_variables.name(id); }
/*!
\brief Accessor
\param id : integer variable identifier
\return attributes of integer variable id
\throw std::invalid_argument : if id is not an integer variable
*/
tchecker::system::attributes_t const & intvar_attributes(tchecker::intvar_id_t id) const;
/*!
\brief Accessor
\param name : integer variable name
\return true if name is a declared integer variable, false otherwise
*/
bool is_intvar(std::string const & name) const;
/*!
\brief Accessor
\return integer variables
*/
inline tchecker::integer_variables_t const & integer_variables() const { return _integer_variables; }
private:
tchecker::integer_variables_t _integer_variables; /*!< Integer variables */
std::vector<tchecker::system::attributes_t> _integer_variables_attr; /*!< Integer variables attributes */
};
} // end of namespace system
} // end of namespace tchecker
#endif // TCHECKER_SYSTEM_INTVAR_HH
| 31.162162 | 119 | 0.713501 |
8e5eff5c63cdb00e353c2626a812851af7f7b89e | 5,673 | hpp | C++ | modules/gate_ops/bit_group/bit_group.hpp | ICHEC/QNLP | 2966c7f71e6979c7ddef62520c3749cf6473fabe | [
"Apache-2.0"
] | 29 | 2020-04-13T04:40:35.000Z | 2021-12-17T11:21:35.000Z | modules/gate_ops/bit_group/bit_group.hpp | ICHEC/QNLP | 2966c7f71e6979c7ddef62520c3749cf6473fabe | [
"Apache-2.0"
] | 6 | 2020-03-12T17:40:00.000Z | 2021-01-20T12:15:08.000Z | modules/gate_ops/bit_group/bit_group.hpp | ICHEC/QNLP | 2966c7f71e6979c7ddef62520c3749cf6473fabe | [
"Apache-2.0"
] | 9 | 2020-09-28T05:00:30.000Z | 2022-03-04T02:11:49.000Z | /**
* @file bit_group.hpp
* @author Lee J. O'Riordan (lee.oriordan@ichec.ie)
* @brief Implements grouping of bits to LSB side of register
* @version 0.1
* @date 2019-04-02
* @detailed This header file introduces routines for bit-wise shifting of set bits to the side of a register (ie |01010> -> |00011>).
* Note: yes, we are cheating to reset the qubits by Hadamrding and measuring in Z-basis. Uncompute steps to follow.
*
* @copyright Copyright (c) 2020
*/
#ifndef QNLP_BIT_GROUP
#define QNLP_BIT_GROUP
#include<algorithm>
namespace QNLP{
/**
* @brief Class definition for bit-wise grouping in register.
*
* @tparam SimulatorType
*/
template <class SimulatorType>
class BitGroup{
private:
/**
* @brief Swap the qubits if `qreg_idx0` is set and `qreg_idx1` is not.
* Uses Auxiliary qubits `qaux_idx` which are set to |10> at start and end of operations.
*
* @param qSim Quantum simulator object derived from SimulatorGeneral
* @param qreg_idx0 Index of qubit 0 in qSim qubit register
* @param qreg_idx1 Index of qubit 1 in qSim qubit register
* @param qaux_idx Indices of auxiliary qubits in qSim qubit register that are set to |10>
*/
static void q_ops(SimulatorType& qSim, std::size_t qreg_idx0, std::size_t qreg_idx1, const std::vector<std::size_t>& qaux_idx){
//Swap if C0 is set and C1 is not
qSim.applyGateCCX(qreg_idx0, qaux_idx[0], qaux_idx[1]);
qSim.applyGateCCX(qreg_idx1, qreg_idx0, qaux_idx[1]);
qSim.applyGateCSwap(qaux_idx[1], qreg_idx0, qreg_idx1);
//Reset Aux gate to |0>
qSim.applyGateH(qaux_idx[1]);
qSim.collapseToBasisZ(qaux_idx[1], 0);
}
/*
//@brief WIP:Swaps all qubits in register indices given by qreg_idx to their right-most positions.
// Method works from opposing ends of register and subregisters iteratively until all qubits are in the correct positions.
//
//@param qSim Quantum simulator object derived from SimulatorGeneral
//@param qreg_idx Indices of the qSim register to group to the LSB position.
//@param qaux_idx Indices of auxiliary qubits in qSim register
static void bit_swap_s2e(SimulatorType& qSim, const std::vector<std::size_t>& qreg_idx, const std::vector<std::size_t>& qaux_idx){
assert(qaux_idx.size() >= 2);
std::size_t num_qubits = qreg_idx.size();
//Apply the op from opposite ends of register working towards centre, reduce size from left, then repeat until 2 qubits remain.
qSim.applyGateX(qaux_idx[0]);
for(int num_offset=0; num_offset < qreg_idx.size()/2 + 1 + qreg_idx.size()%2; num_offset++){
for(std::size_t i=0; i < num_qubits/2 + num_qubits%2; i++){
if (i + num_offset == num_qubits - (i+1) + num_offset)
continue;
q_ops(qSim, qreg_idx[i + num_offset], qreg_idx[num_qubits - (i+1) + num_offset], qaux_idx);
}
num_qubits--;
}
qSim.applyGateX(qaux_idx[0]);
}*/
/**
* @brief Swaps all qubits in register indices given by qreg_idx to their right-most positions.
* Method works by pairing qubits using even-odd indexed cycles iteratively until all qubits are in the correct positions.
*
*
* @param qSim Quantum simulator object derived from SimulatorGeneral
* @param qreg_idx Indices of the qSim register to group to the LSB position.
* @param qaux_idx Indices of auxiliary qubits in qSim register in |00> state
*/
static void bit_swap_pair(SimulatorType& qSim, const std::vector<std::size_t>& qreg_idx, const std::vector<std::size_t>& qaux_idx, bool lsb){
bool isOdd = qreg_idx.size() % 2;
qSim.applyGateX(qaux_idx[0]);
for(std::size_t num_steps = 0; num_steps < qreg_idx.size(); num_steps++){
for(int i = 0; i < qreg_idx.size()-1; i+=2){
if(i + 1 + isOdd < qreg_idx.size()){
if(lsb)
q_ops(qSim, qreg_idx[i + isOdd], qreg_idx[i + 1 + isOdd], qaux_idx);
else
q_ops(qSim, qreg_idx[i + 1 + isOdd], qreg_idx[i + isOdd], qaux_idx);
}
}
isOdd = !isOdd;
}
qSim.applyGateX(qaux_idx[0]);
}
public:
/**
* @brief Swaps all qubits in register indices given by qreg_idx to their right-most positions.
* Method works by pairing qubits using even-odd indexed cycles iteratively until all qubits are in the correct positions.
* Intermediate qubit reset operation may not be realisable on all platforms (Hadarmard followed by SigmaZ projection to |0>)
*
* @param qSim Quantum simulator object derived from SimulatorGeneral
* @param qreg_idx Indices of the qSim register to group to the LSB position.
* @param qaux_idx Indices of auxiliary qubits in qSim register in |00> state
* @param lsb Indicates if to shift the values to the MSB or LSB equivalent positions.
*/
static void bit_group(SimulatorType& qSim, const std::vector<std::size_t>& qreg_idx, const std::vector<std::size_t>& qaux_idx, bool lsb=true){
bit_swap_pair(qSim, qreg_idx, qaux_idx, lsb);
}
};
}
#endif | 47.275 | 150 | 0.609907 |
8e6004c4560112cb7ade852df3b98d5e54497a23 | 12,526 | cpp | C++ | sift_1b.cpp | dbaranchuk/hnsw | 2bed1138a31eeb65ec705c92fb03cd2cdae6dece | [
"Apache-2.0"
] | 2 | 2017-12-17T14:18:25.000Z | 2020-01-15T09:15:43.000Z | sift_1b.cpp | dbaranchuk/hnsw | 2bed1138a31eeb65ec705c92fb03cd2cdae6dece | [
"Apache-2.0"
] | null | null | null | sift_1b.cpp | dbaranchuk/hnsw | 2bed1138a31eeb65ec705c92fb03cd2cdae6dece | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <queue>
#include <chrono>
#include "hnswlib.h"
#include <map>
#include <unordered_set>
using namespace std;
using namespace hnswlib;
class StopW {
std::chrono::steady_clock::time_point time_begin;
public:
StopW() {
time_begin = std::chrono::steady_clock::now();
}
float getElapsedTimeMicro() {
std::chrono::steady_clock::time_point time_end = std::chrono::steady_clock::now();
return (std::chrono::duration_cast<std::chrono::microseconds>(time_end - time_begin).count());
}
void reset() {
time_begin = std::chrono::steady_clock::now();
}
};
/*
* Author: David Robert Nadeau
* Site: http://NadeauSoftware.com/
* License: Creative Commons Attribution 3.0 Unported License
* http://creativecommons.org/licenses/by/3.0/deed.en_US
*/
#if defined(_WIN32)
#include <windows.h>
#include <psapi.h>
#elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))
#include <unistd.h>
#include <sys/resource.h>
#if defined(__APPLE__) && defined(__MACH__)
#include <mach/mach.h>
#elif (defined(_AIX) || defined(__TOS__AIX__)) || (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__)))
#include <fcntl.h>
#include <procfs.h>
#elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__)
#include <stdio.h>
#endif
#else
#error "Cannot define getPeakRSS( ) or getCurrentRSS( ) for an unknown OS."
#endif
/**
* Returns the peak (maximum so far) resident set size (physical
* memory use) measured in bytes, or zero if the value cannot be
* determined on this OS.
*/
size_t getPeakRSS()
{
#if defined(_WIN32)
/* Windows -------------------------------------------------- */
PROCESS_MEMORY_COUNTERS info;
GetProcessMemoryInfo(GetCurrentProcess(), &info, sizeof(info));
return (size_t)info.PeakWorkingSetSize;
#elif (defined(_AIX) || defined(__TOS__AIX__)) || (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__)))
/* AIX and Solaris ------------------------------------------ */
struct psinfo psinfo;
int fd = -1;
if ((fd = open("/proc/self/psinfo", O_RDONLY)) == -1)
return (size_t)0L; /* Can't open? */
if (read(fd, &psinfo, sizeof(psinfo)) != sizeof(psinfo))
{
close(fd);
return (size_t)0L; /* Can't read? */
}
close(fd);
return (size_t)(psinfo.pr_rssize * 1024L);
#elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))
/* BSD, Linux, and OSX -------------------------------------- */
struct rusage rusage;
getrusage(RUSAGE_SELF, &rusage);
#if defined(__APPLE__) && defined(__MACH__)
return (size_t)rusage.ru_maxrss;
#else
return (size_t)(rusage.ru_maxrss * 1024L);
#endif
#else
/* Unknown OS ----------------------------------------------- */
return (size_t)0L; /* Unsupported. */
#endif
}
/**
* Returns the current resident set size (physical memory use) measured
* in bytes, or zero if the value cannot be determined on this OS.
*/
size_t getCurrentRSS()
{
#if defined(_WIN32)
/* Windows -------------------------------------------------- */
PROCESS_MEMORY_COUNTERS info;
GetProcessMemoryInfo(GetCurrentProcess(), &info, sizeof(info));
return (size_t)info.WorkingSetSize;
#elif defined(__APPLE__) && defined(__MACH__)
/* OSX ------------------------------------------------------ */
struct mach_task_basic_info info;
mach_msg_type_number_t infoCount = MACH_TASK_BASIC_INFO_COUNT;
if (task_info(mach_task_self(), MACH_TASK_BASIC_INFO,
(task_info_t)&info, &infoCount) != KERN_SUCCESS)
return (size_t)0L; /* Can't access? */
return (size_t)info.resident_size;
#elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__)
/* Linux ---------------------------------------------------- */
long rss = 0L;
FILE* fp = NULL;
if ((fp = fopen("/proc/self/statm", "r")) == NULL)
return (size_t)0L; /* Can't open? */
if (fscanf(fp, "%*s%ld", &rss) != 1)
{
fclose(fp);
return (size_t)0L; /* Can't read? */
}
fclose(fp);
return (size_t)rss * (size_t)sysconf(_SC_PAGESIZE);
#else
/* AIX, BSD, Solaris, and Unknown OS ------------------------ */
return (size_t)0L; /* Unsupported. */
#endif
}
template <typename dist_t>
static void get_gt(unsigned int *massQA, size_t qsize, vector<std::priority_queue< std::pair<dist_t, labeltype >>> &answers,
size_t gt_dim, size_t k = 1)
{
(vector<std::priority_queue< std::pair<dist_t, labeltype >>>(qsize)).swap(answers);
for (int i = 0; i < qsize; i++) {
for (int j = 0; j < k; j++) {
answers[i].emplace(0.0f, massQA[gt_dim*i + j]);
}
}
}
template <typename dist_t, typename vtype>
static float test_approx(vtype *massQ, size_t nq, HierarchicalNSW<dist_t, vtype> &appr_alg,
size_t d, vector<std::priority_queue< std::pair<dist_t, labeltype >>> &answers,
size_t k)
{
size_t correct = 0;
size_t total = 0;
int res[k];
std::ofstream out("mysift_gt.ivecs", std::ios::binary);
//uncomment to test in parallel mode:
//#pragma omp parallel for
for (int i = 0; i < nq; i++) {
std::priority_queue< std::pair<dist_t, labeltype >> result;
result = appr_alg.searchKnn(massQ + d*i, k);
// std::priority_queue< std::pair<dist_t, labeltype >> gt(answers[i]);
// unordered_set <labeltype> g;
// total += gt.size();
// while (gt.size()) {
// g.insert(gt.top().second);
// gt.pop();
// }
int j = k-1;
while (result.size()) {
// if (g.find(result.top().second) != g.end())
// correct++;
res[j--] = result.top().second;
result.pop();
}
out.write((char *) &k, sizeof(uint32_t));
out.write((char *) res, k * sizeof(uint32_t));
}
return 1.0f*correct / total;
}
template <typename dist_t, typename vtype>
static void test_vs_recall(vtype *massQ, size_t qsize, HierarchicalNSW<dist_t, vtype> &appr_alg,
size_t vecdim, vector<std::priority_queue< std::pair<dist_t, labeltype >>> &answers,
size_t k)
{
vector<size_t> efs = {500};
// if (k < 30) {
// for (int i = k; i < 30; i++) efs.push_back(i);
// for (int i = 30; i < 100; i += 10) efs.push_back(i);
// for (int i = 100; i <= 500; i += 40) efs.push_back(i);
// }
// else if (k < 100) {
// for (int i = k; i < 100; i += 10) efs.push_back(i);
// for (int i = 100; i <= 500; i += 40) efs.push_back(i);
// } else
// for (int i = k; i <= 500; i += 40) efs.push_back(i);
for (size_t ef : efs) {
appr_alg.ef_ = ef;
appr_alg.dist_calc = 0;
appr_alg.nev9zka = 0.0;
appr_alg.hops0 = 0.0;
StopW stopw = StopW();
float recall = test_approx<dist_t, vtype>(massQ, qsize, appr_alg, vecdim, answers, k);
float time_us_per_query = stopw.getElapsedTimeMicro() / qsize;
float avr_dist_count = appr_alg.dist_calc*1.f / qsize;
cout << ef << "\t" << recall << "\t" << time_us_per_query << " us\t" << avr_dist_count << " dcs\t" << appr_alg.hops0 /*+ appr_alg.hops*/ << " hps\n";
if (recall > 1.0) {
cout << recall << "\t" << time_us_per_query << " us\t" << avr_dist_count << " dcs\n";
break;
}
}
cout << "Average distance from 0 level entry point to query: " << appr_alg.nev9zka << endl;
}
/**
* Main SIFT Test Function
*/
template <typename format>
static void readXvec(std::ifstream &input, format *mass, const int d, const int n = 1)
{
int in = 0;
for (int i = 0; i < n; i++) {
input.read((char *) &in, sizeof(int));
if (in != d) {
std::cout << i << " " << n << " " << in << " " << d << "file error\n";
exit(1);
}
input.read((char *)(mass+i*d), in * sizeof(format));
}
}
template <typename format>
static void loadXvecs(const char *path, format *mass, const int n, const int d)
{
ifstream input(path, ios::binary);
for (int i = 0; i < n; i++) {
int in = 0;
input.read((char *)&in, sizeof(int));
if (in != d) {
cout << "file error\n";
exit(1);
}
input.read((char *)(mass + i*d), in*sizeof(format));
}
input.close();
}
template<typename dist_t, typename vtype>
static void _hnsw_test(const char *path_data, const char *path_q,
const char *path_gt, const char *path_info, const char *path_edges,
L2SpaceType l2SpaceType,
const int k, const int vecsize, const int qsize,
const int vecdim, const int efConstruction, const int M)
{
const std::map<size_t, std::pair<size_t, size_t>> M_map = {{vecsize, {M, 2*M}}};
//
const std::vector<size_t> elements_per_level;// = {100000000, 5000000, 250000, 12500, 625, 32};
//cout << "Loading GT:\n";
//const int gt_dim = 100;
//std::vector<unsigned int> massQA(qsize * gt_dim);
//loadXvecs<unsigned int>(path_gt, massQA.data(), qsize, gt_dim);
cout << "Loading queries:\n";
std::vector<vtype> massQ(qsize * vecdim);
loadXvecs<vtype>(path_q, massQ.data(), qsize, vecdim);
SpaceInterface<dist_t> *l2space;
switch(l2SpaceType) {
case L2SpaceType::Float:
l2space = dynamic_cast<SpaceInterface<dist_t> *>(new L2Space(vecdim));
break;
case L2SpaceType::Int:
l2space = dynamic_cast<SpaceInterface<dist_t> *>(new L2SpaceI(vecdim));
break;
}
HierarchicalNSW<dist_t, vtype> *appr_alg;
if (exists_test(path_info) && exists_test(path_edges)) {
appr_alg = new HierarchicalNSW<dist_t, vtype>(l2space, path_info, path_data, path_edges);
cout << "Actual memory usage: " << getCurrentRSS() / 1000000 << " Mb \n";
} else {
cout << "Building index:\n";
size_t j1 = 0;
appr_alg = new HierarchicalNSW<dist_t, vtype>(l2space, vecsize, M, 2*M, efConstruction);
StopW stopw = StopW();
StopW stopw_full = StopW();
cout << "Adding elements\n";
ifstream input(path_data, ios::binary);
vtype mass[vecdim];
readXvec<vtype>(input, mass, vecdim);
appr_alg->addPoint((void *) mass, j1);
size_t report_every = 1000000;
#pragma omp parallel for
for (int i = 1; i < vecsize; i++) {
vtype mass[vecdim];
#pragma omp critical
{
readXvec<vtype>(input, mass, vecdim);
if (++j1 % report_every == 0) {
cout << j1 / (0.01 * vecsize) << " %, "
<< report_every / (1000.0 * 1e-6 * stopw.getElapsedTimeMicro()) << " kips " << " Mem: "
<< getCurrentRSS() / 1000000 << " Mb \n";
stopw.reset();
}
}
appr_alg->addPoint((void *) (mass), (size_t) j1);
}
input.close();
cout << "Build time:" << 1e-6 * stopw_full.getElapsedTimeMicro() << " seconds\n";
appr_alg->SaveInfo(path_info);
appr_alg->SaveEdges(path_edges);
}
//appr_alg->count_repeated_edges();
//appr_alg->printListsize();
//appr_alg->check_connectivity(massQA, qsize);
//appr_alg->printNumElements();
vector<std::priority_queue< std::pair<dist_t, labeltype >>> answers;
//cout << "Parsing gt:\n";
//get_gt<dist_t>(massQA.data(), qsize, answers, gt_dim, k);
cout << "Loaded gt\n";
test_vs_recall<dist_t, vtype>(massQ.data(), qsize, *appr_alg, vecdim, answers, k);
cout << "Actual memory usage: " << getCurrentRSS() / 1000000 << " Mb \n";
delete l2space;
}
void hnsw_test(const char *l2space_type, const char *path_data, const char *path_q,
const char *path_gt, const char *path_info, const char *path_edges,
const int k, const int vecsize, const int qsize,
const int vecdim, const int efConstruction, const int M)
{
if (!strcmp (l2space_type, "int"))
_hnsw_test<int, unsigned char>(path_data, path_q, path_gt, path_info, path_edges, L2SpaceType::Int,
k, vecsize, qsize, vecdim, efConstruction, M);
else if (!strcmp (l2space_type, "float"))
_hnsw_test<float, float>(path_data, path_q, path_gt, path_info, path_edges, L2SpaceType::Float,
k, vecsize, qsize, vecdim, efConstruction, M);
} | 34.13079 | 151 | 0.586779 |
8e60171a198c91c1f18eba310410edbff7d07090 | 4,895 | cpp | C++ | ngraph/frontend/onnx_import/src/utils/onnx_internal.cpp | kenkoyanagi/openvino | 864b3ba62fb86e685c847ca84016043cdea870c5 | [
"Apache-2.0"
] | 1 | 2021-04-22T07:28:03.000Z | 2021-04-22T07:28:03.000Z | ngraph/frontend/onnx_import/src/utils/onnx_internal.cpp | kenkoyanagi/openvino | 864b3ba62fb86e685c847ca84016043cdea870c5 | [
"Apache-2.0"
] | 105 | 2020-06-04T00:23:29.000Z | 2022-02-21T13:04:33.000Z | ngraph/frontend/onnx/onnx_import/src/utils/onnx_internal.cpp | mpapaj/openvino | 37b46de1643a2ba6c3b6a076f81d0a47115ede7e | [
"Apache-2.0"
] | 3 | 2021-04-25T06:52:41.000Z | 2021-05-07T02:01:44.000Z | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <onnx/onnx_pb.h>
#include "core/graph.hpp"
#include "core/model.hpp"
#include "core/null_node.hpp"
#include "core/transform.hpp"
#include "onnx_import/onnx_framework_node.hpp"
#include "onnx_import/utils/onnx_internal.hpp"
namespace ngraph
{
namespace onnx_import
{
namespace detail
{
void remove_dangling_parameters(std::shared_ptr<Function>& function)
{
const auto parameters = function->get_parameters();
for (auto parameter : parameters)
{
const auto parameter_users = parameter->get_users();
// if a Parameter is connected to a ONNXFrameworkNode that was not converted
// during convert_function it means, this Parameter is dangling and we can
// remove it from function
const bool is_dangling_parameter = std::all_of(
parameter_users.begin(),
parameter_users.end(),
[](const std::shared_ptr<ngraph::Node>& node) -> bool {
return std::dynamic_pointer_cast<frontend::ONNXFrameworkNode>(node) !=
nullptr;
});
if (is_dangling_parameter)
{
function->remove_parameter(parameter);
}
}
}
void remove_dangling_results(std::shared_ptr<Function>& function)
{
const auto results = function->get_results();
for (auto result : results)
{
// we can remove Result from function if after function conversion,
// Result is connected to NullNode only
const auto result_inputs = result->input_values();
const bool is_dangling_result =
std::all_of(result_inputs.begin(),
result_inputs.end(),
[](const Output<ngraph::Node>& node) -> bool {
return ngraph::op::is_null(node);
});
if (is_dangling_result)
{
function->remove_result(result);
}
}
}
void convert_decoded_function(std::shared_ptr<Function> function)
{
for (const auto& node : function->get_ordered_ops())
{
if (auto raw_node =
std::dynamic_pointer_cast<frontend::ONNXFrameworkNode>(node))
{
if (auto subgraph_node =
std::dynamic_pointer_cast<frontend::ONNXSubgraphFrameworkNode>(
node))
{
subgraph_node->infer_inputs_from_parent();
convert_decoded_function(subgraph_node->get_subgraph_body());
}
const auto& onnx_node = raw_node->get_onnx_node();
OutputVector ng_nodes{onnx_node.get_ng_nodes()};
if (ng_nodes.size() > raw_node->get_output_size())
{
ng_nodes.resize(raw_node->get_output_size());
}
replace_node(raw_node, ng_nodes);
}
else
{
// Have to revalidate node because new intpus can affect shape/type
// propagation for already translated nodes
node->revalidate_and_infer_types();
}
}
remove_dangling_parameters(function);
remove_dangling_results(function);
}
std::shared_ptr<Function> import_onnx_model(ONNX_NAMESPACE::ModelProto& model_proto,
const std::string& model_path)
{
transform::expand_onnx_functions(model_proto);
transform::fixup_legacy_operators(model_proto);
transform::update_external_data_paths(model_proto, model_path);
auto p_model_proto = common::make_unique<ONNX_NAMESPACE::ModelProto>(model_proto);
auto model = common::make_unique<Model>(std::move(p_model_proto));
Graph graph{std::move(model)};
return graph.convert();
}
} // namespace detail
} // namespace onnx_import
} // namespace ngraph
| 43.705357 | 98 | 0.489275 |
769fc25c2db959e7739f02dfbd9b42abdccf62af | 1,315 | hh | C++ | src/motor/introspect/api/motor/introspect/node/reference.hh | motor-dev/Motor | 98cb099fe1c2d31e455ed868cc2a25eae51e79f0 | [
"BSD-3-Clause"
] | null | null | null | src/motor/introspect/api/motor/introspect/node/reference.hh | motor-dev/Motor | 98cb099fe1c2d31e455ed868cc2a25eae51e79f0 | [
"BSD-3-Clause"
] | null | null | null | src/motor/introspect/api/motor/introspect/node/reference.hh | motor-dev/Motor | 98cb099fe1c2d31e455ed868cc2a25eae51e79f0 | [
"BSD-3-Clause"
] | null | null | null | /* Motor <motor.devel@gmail.com>
see LICENSE for detail */
#ifndef MOTOR_INTROSPECT_NODE_REFERENCE_HH_
#define MOTOR_INTROSPECT_NODE_REFERENCE_HH_
/**************************************************************************************************/
#include <motor/introspect/stdafx.h>
#include <motor/introspect/node/node.hh>
namespace Motor { namespace Meta { namespace AST {
class Namespace;
class motor_api(INTROSPECT) Reference : public Node
{
friend class Object;
private:
const inamespace m_referenceName;
ref< const Node > m_node;
Meta::Value m_value;
protected:
virtual minitl::tuple< raw< const Meta::Method >, bool > getCall(DbContext & context)
const override;
virtual ConversionCost distance(const Type& type) const override;
virtual bool doResolve(DbContext & context) override;
virtual void doEval(const Type& expectedType, Value& result) const override;
virtual void doVisit(Node::Visitor & visitor) const override;
public:
Reference(const inamespace& name);
~Reference();
const inamespace& name() const
{
return m_referenceName;
}
};
}}} // namespace Motor::Meta::AST
/**************************************************************************************************/
#endif
| 29.222222 | 100 | 0.591635 |
76a412372c85c9f49be328ce89adba110ab8bef5 | 56,487 | cpp | C++ | src/test/analysis.cpp | akazachk/vpc | 2339159e963b30287f780b6c03202fcbf0e9c131 | [
"MIT"
] | 6 | 2019-03-18T00:22:43.000Z | 2022-03-16T19:21:21.000Z | src/test/analysis.cpp | akazachk/vpc | 2339159e963b30287f780b6c03202fcbf0e9c131 | [
"MIT"
] | 14 | 2019-03-18T03:30:53.000Z | 2020-10-08T15:32:45.000Z | src/test/analysis.cpp | akazachk/vpc | 2339159e963b30287f780b6c03202fcbf0e9c131 | [
"MIT"
] | 2 | 2021-10-05T17:44:29.000Z | 2021-11-04T20:45:01.000Z | /**
* @file analysis.cpp
* @author A. M. Kazachkov
* @date 2019-03-04
*/
#include "analysis.hpp"
// COIN-OR
#include <OsiSolverInterface.hpp>
#include <OsiCuts.hpp>
#include <CglGMI.hpp>
// Project files
#include "BBHelper.hpp"
#include "CglVPC.hpp"
#include "CutHelper.hpp"
#include "Disjunction.hpp"
#include "PartialBBDisjunction.hpp"
#include "PRLP.hpp"
#include "SolverHelper.hpp"
#include "VPCParameters.hpp"
using namespace VPCParametersNamespace;
#include "utility.hpp" // isInfinity, stringValue
const int countBoundInfoEntries = 11;
const int countGapInfoEntries = 4;
const int countSummaryBBInfoEntries = 4 * 2;
const int countFullBBInfoEntries = static_cast<int>(BB_INFO_CONTENTS.size()) * 4 * 2;
const int countOrigProbEntries = 13;
const int countPostCutProbEntries = 10;
const int countDisjInfoEntries = 12;
const int countCutInfoEntries = 10;
const int countObjInfoEntries = 1 + 4 * static_cast<int>(CglVPC::ObjectiveType::NUM_OBJECTIVE_TYPES);
const int countFailInfoEntries = 1 + static_cast<int>(CglVPC::FailureType::NUM_FAILURE_TYPES);
const int countParamInfoEntries = intParam::NUM_INT_PARAMS + doubleParam::NUM_DOUBLE_PARAMS + stringParam::NUM_STRING_PARAMS;
int countTimeInfoEntries = 0; // set in printHeader
const int countVersionInfoEntries = 5;
const int countExtraInfoEntries = 4;
void printHeader(const VPCParameters& params,
const std::vector<std::string>& time_name,
const char SEP) {
FILE* logfile = params.logfile;
if (logfile == NULL)
return;
countTimeInfoEntries = time_name.size();
// First line of the header details the categories of information displayed
std::string tmpstring = "";
fprintf(logfile, "%c", SEP);
fprintf(logfile, "%s", "PARAM INFO");
tmpstring.assign(countParamInfoEntries, SEP);
fprintf(logfile, "%s", tmpstring.c_str());
fprintf(logfile, "%s", "BOUND INFO");
tmpstring.assign(countBoundInfoEntries, SEP);
fprintf(logfile, "%s", tmpstring.c_str());
fprintf(logfile, "%s", "GAP INFO");
tmpstring.assign(countGapInfoEntries, SEP);
fprintf(logfile, "%s", tmpstring.c_str());
fprintf(logfile, "%s", "BB INFO");
tmpstring.assign(countSummaryBBInfoEntries, SEP);
fprintf(logfile, "%s", tmpstring.c_str());
fprintf(logfile, "%s", "ORIG PROB");
tmpstring.assign(countOrigProbEntries, SEP);
fprintf(logfile, "%s", tmpstring.c_str());
fprintf(logfile, "%s", "POST-CUT PROB");
tmpstring.assign(countPostCutProbEntries, SEP);
fprintf(logfile, "%s", tmpstring.c_str());
fprintf(logfile, "%s", "DISJ INFO");
tmpstring.assign(countDisjInfoEntries, SEP);
fprintf(logfile, "%s", tmpstring.c_str());
fprintf(logfile, "%s", "CUT INFO");
tmpstring.assign(countCutInfoEntries, SEP);
fprintf(logfile, "%s", tmpstring.c_str());
fprintf(logfile, "%s", "OBJ INFO");
tmpstring.assign(countObjInfoEntries, SEP);
fprintf(logfile, "%s", tmpstring.c_str());
fprintf(logfile, "%s", "FAIL INFO");
tmpstring.assign(countFailInfoEntries, SEP);
fprintf(logfile, "%s", tmpstring.c_str());
fprintf(logfile, "%s", "FULL BB INFO");
tmpstring.assign(countFullBBInfoEntries, SEP);
fprintf(logfile, "%s", tmpstring.c_str());
fprintf(logfile, "%s", "TIME INFO");
tmpstring.assign(countTimeInfoEntries, SEP);
fprintf(logfile, "%s", tmpstring.c_str());
fprintf(logfile, "%s", "VERSION INFO");
tmpstring.assign(countVersionInfoEntries, SEP);
fprintf(logfile, "%s", tmpstring.c_str());
fprintf(logfile, "%s", "WRAP UP INFO");
tmpstring.assign(countExtraInfoEntries, SEP);
fprintf(logfile, "%s", tmpstring.c_str());
fprintf(logfile, "%s", "END");
fprintf(logfile, "\n");
fprintf(logfile, "%s%c", "INSTANCE", SEP);
{ // PARAM INFO
//printParams(params, logfile, 1); // names for int/double params
printParams(params, logfile, 7); // names for int/double/string params
} // PARAM INFO
{ // BOUND INFO
int count = 0;
fprintf(logfile, "%s%c", "LP OBJ", SEP); count++; // 1
fprintf(logfile, "%s%c", "BEST DISJ OBJ", SEP); count++; // 2
fprintf(logfile, "%s%c", "WORST DISJ OBJ", SEP); count++; // 3
fprintf(logfile, "%s%c", "IP OBJ", SEP); count++; // 4
fprintf(logfile, "%s%c", "NUM GMIC", SEP); count++; // 5
fprintf(logfile, "%s%c", "GMIC OBJ", SEP); count++; // 6
fprintf(logfile, "%s%c", "NUM L&PC", SEP); count++; // 7
fprintf(logfile, "%s%c", "L&PC OBJ", SEP); count++; // 8
fprintf(logfile, "%s%c", "NUM VPC", SEP); count++; // 9
fprintf(logfile, "%s%c", "VPC OBJ", SEP); count++; // 10
fprintf(logfile, "%s%c", "VPC+GMIC OBJ", SEP); count++; // 11
assert(count == countBoundInfoEntries);
} // BOUND INFO
{ // GAP INFO
int count = 0;
fprintf(logfile, "%s%c", "GMIC % GAP CLOSED", SEP); count++; // 1
fprintf(logfile, "%s%c", "L&PC % GAP CLOSED", SEP); count++; // 2
fprintf(logfile, "%s%c", "VPC % GAP CLOSED", SEP); count++; // 3
fprintf(logfile, "%s%c", "GMIC+VPC % GAP CLOSED", SEP); count++; // 4
assert(count == countGapInfoEntries);
} // GAP INFO
{ // BB INFO
int count = 0;
std::vector<std::string> nameVec = {"NODES", "TIME"};
for (auto name : nameVec) {
fprintf(logfile, "%s%c", ("FIRST REF " + name).c_str(), SEP); count++;
fprintf(logfile, "%s%c", ("FIRST REF+V " + name).c_str(), SEP); count++;
fprintf(logfile, "%s%c", ("BEST REF " + name).c_str(), SEP); count++;
fprintf(logfile, "%s%c", ("BEST REF+V " + name).c_str(), SEP); count++;
}
assert(count == countSummaryBBInfoEntries);
} // BB INFO
{ // ORIG PROB
int count = 0;
fprintf(logfile, "%s%c", "ROWS", SEP); count++;
fprintf(logfile, "%s%c", "COLS", SEP); count++;
fprintf(logfile, "%s%c", "NUM FRAC", SEP); count++;
fprintf(logfile, "%s%c", "MIN FRACTIONALITY", SEP); count++;
fprintf(logfile, "%s%c", "MAX FRACTIONALITY", SEP); count++;
fprintf(logfile, "%s%c", "EQ ROWS", SEP); count++;
fprintf(logfile, "%s%c", "BOUND ROWS", SEP); count++;
fprintf(logfile, "%s%c", "ASSIGN ROWS", SEP); count++;
fprintf(logfile, "%s%c", "FIXED COLS", SEP); count++;
fprintf(logfile, "%s%c", "GEN INT", SEP); count++;
fprintf(logfile, "%s%c", "BINARY", SEP); count++;
fprintf(logfile, "%s%c", "CONTINUOUS", SEP); count++;
fprintf(logfile, "%s%c", "A-DENSITY", SEP); count++;
assert(count == countOrigProbEntries);
} // ORIG PROB
{ // POST-CUT PROB
int count = 0;
fprintf(logfile, "%s%c", "NEW NUM FRAC", SEP); count++;
fprintf(logfile, "%s%c", "NEW MIN FRACTIONALITY", SEP); count++;
fprintf(logfile, "%s%c", "NEW MAX FRACTIONALITY", SEP); count++;
fprintf(logfile, "%s%c", "NEW A-DENSITY", SEP); count++;
fprintf(logfile, "%s%c", "ACTIVE GMIC (gmics)", SEP); count++;
fprintf(logfile, "%s%c", "ACTIVE VPC (gmics)", SEP); count++;
fprintf(logfile, "%s%c", "ACTIVE GMIC (vpcs)", SEP); count++;
fprintf(logfile, "%s%c", "ACTIVE VPC (vpcs)", SEP); count++;
fprintf(logfile, "%s%c", "ACTIVE GMIC (all cuts)", SEP); count++;
fprintf(logfile, "%s%c", "ACTIVE VPC (all cuts)", SEP); count++;
assert(count == countPostCutProbEntries);
} // POST-CUT PROB
{ // DISJ INFO
int count = 0;
fprintf(logfile, "%s%c", "NUM DISJ TERMS", SEP); count++;
fprintf(logfile, "%s%c", "NUM INTEGER SOL", SEP); count++;
fprintf(logfile, "%s%c", "NUM DISJ", SEP); count++;
// fprintf(logfile, "%s%c", "MIN DENSITY PRLP", SEP); count++;
// fprintf(logfile, "%s%c", "MAX DENSITY PRLP", SEP); count++;
fprintf(logfile, "%s%c", "AVG DENSITY PRLP", SEP); count++;
// fprintf(logfile, "%s%c", "MIN ROWS PRLP", SEP); count++;
// fprintf(logfile, "%s%c", "MAX ROWS PRLP", SEP); count++;
fprintf(logfile, "%s%c", "AVG ROWS PRLP", SEP); count++;
// fprintf(logfile, "%s%c", "MIN COLS PRLP", SEP); count++;
// fprintf(logfile, "%s%c", "MAX COLS PRLP", SEP); count++;
fprintf(logfile, "%s%c", "AVG COLS PRLP", SEP); count++;
// fprintf(logfile, "%s%c", "MIN POINTS PRLP", SEP); count++;
// fprintf(logfile, "%s%c", "MAX POINTS PRLP", SEP); count++;
fprintf(logfile, "%s%c", "AVG POINTS PRLP", SEP); count++;
// fprintf(logfile, "%s%c", "MIN RAYS PRLP", SEP); count++;
// fprintf(logfile, "%s%c", "MAX RAYS PRLP", SEP); count++;
fprintf(logfile, "%s%c", "AVG RAYS PRLP", SEP); count++;
fprintf(logfile, "%s%c", "AVG PARTIAL BB EXPLORED NODES", SEP); count++;
fprintf(logfile, "%s%c", "AVG PARTIAL BB PRUNED NODES", SEP); count++;
fprintf(logfile, "%s%c", "AVG PARTIAL BB MIN DEPTH", SEP); count++;
fprintf(logfile, "%s%c", "AVG PARTIAL BB MAX DEPTH", SEP); count++;
assert(count == countDisjInfoEntries);
} // DISJ INFO
{ // CUT INFO
int count = 0;
fprintf(logfile, "%s%c", "NUM ROUNDS", SEP); count++;
fprintf(logfile, "%s%c", "NUM CUTS", SEP); count++; // repeat, but it's ok
fprintf(logfile, "%s%c", "NUM ONE SIDED CUTS", SEP); count++;
fprintf(logfile, "%s%c", "NUM OPTIMALITY CUTS", SEP); count++;
fprintf(logfile, "%s%c", "MIN SUPPORT VPC", SEP); count++;
fprintf(logfile, "%s%c", "MAX SUPPORT VPC", SEP); count++;
fprintf(logfile, "%s%c", "AVG SUPPORT VPC", SEP); count++;
fprintf(logfile, "%s%c", "MIN SUPPORT GOMORY", SEP); count++;
fprintf(logfile, "%s%c", "MAX SUPPORT GOMORY", SEP); count++;
fprintf(logfile, "%s%c", "AVG SUPPORT GOMORY", SEP); count++;
assert(count == countCutInfoEntries);
} // CUT INFO
{ // OBJ INFO
// For each objective: num obj, num fails, num active
int count = 0;
fprintf(logfile, "%s%c", "NUM OBJ", SEP); count++;
for (int obj_ind = 0; obj_ind < static_cast<int>(CglVPC::ObjectiveType::NUM_OBJECTIVE_TYPES); obj_ind++) {
fprintf(logfile, "NUM OBJ %s%c", CglVPC::ObjectiveTypeName[obj_ind].c_str(), SEP); count++;
fprintf(logfile, "NUM CUTS %s%c", CglVPC::ObjectiveTypeName[obj_ind].c_str(), SEP); count++;
fprintf(logfile, "NUM FAILS %s%c", CglVPC::ObjectiveTypeName[obj_ind].c_str(), SEP); count++;
fprintf(logfile, "NUM ACTIVE %s%c", CglVPC::ObjectiveTypeName[obj_ind].c_str(), SEP); count++;
}
assert(count == countObjInfoEntries);
} // OBJ INFO
{ // FAIL INFO
int count = 0;
fprintf(logfile, "%s%c", "NUM FAILS", SEP); count++;
for (int fail_ind = 0; fail_ind < static_cast<int>(CglVPC::FailureType::NUM_FAILURE_TYPES); fail_ind++) {
fprintf(logfile, "%s%c", CglVPC::FailureTypeName[fail_ind].c_str(), SEP); count++;
}
assert(count == countFailInfoEntries);
} // FAIL INFO
{ // FULL BB INFO
int count = 0;
for (std::string name : BB_INFO_CONTENTS) {
fprintf(logfile, "%s%c", ("FIRST REF " + name).c_str(), SEP); count++;
fprintf(logfile, "%s%c", ("FIRST REF+V " + name).c_str(), SEP); count++;
fprintf(logfile, "%s%c", ("BEST REF " + name).c_str(), SEP); count++;
fprintf(logfile, "%s%c", ("BEST REF+V " + name).c_str(), SEP); count++;
fprintf(logfile, "%s%c", ("AVG REF " + name).c_str(), SEP); count++;
fprintf(logfile, "%s%c", ("AVG REF+V " + name).c_str(), SEP); count++;
}
for (std::string name : BB_INFO_CONTENTS) {
fprintf(logfile, "%s%c", ("ALL REF " + name).c_str(), SEP); count++;
}
for (std::string name : BB_INFO_CONTENTS) {
fprintf(logfile, "%s%c", ("ALL REF+V " + name).c_str(), SEP); count++;
}
assert(count == countFullBBInfoEntries);
} // FULL BB INFO
{ // TIME INFO
int count = 0;
for (int t = 0; t < (int) time_name.size(); t++) {
fprintf(logfile, "%s%c", time_name[t].c_str(), SEP); count++;
}
assert(count == countTimeInfoEntries);
} // TIME INFO
{ // VERSION INFO
fprintf(logfile, "%s%c", "vpc_version", SEP);
fprintf(logfile, "%s%c", "cbc_version", SEP);
fprintf(logfile, "%s%c", "clp_version", SEP);
fprintf(logfile, "%s%c", "gurobi_version", SEP);
fprintf(logfile, "%s%c", "cplex_version", SEP);
} // VERSION INFO
{ // WRAP UP INFO
fprintf(logfile, "%s%c", "ExitReason", SEP);
fprintf(logfile, "%s%c", "end_time_string", SEP);
fprintf(logfile, "%s%c", "time elapsed", SEP);
fprintf(logfile, "%s%c", "instname", SEP);
} // WRAP UP INFO
fprintf(logfile, "\n");
fflush(logfile);
} /* printHeader */
void printBoundAndGapInfo(const SummaryBoundInfo& boundInfo, FILE* logfile, const char SEP) {
if (!logfile)
return;
{ // BOUND INFO
int count = 0;
fprintf(logfile, "%s%c", stringValue(boundInfo.lp_obj, "%2.20f").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(boundInfo.best_disj_obj, "%2.20f").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(boundInfo.worst_disj_obj, "%2.20f").c_str(), SEP); count++;
if (!isInfinity(std::abs(boundInfo.ip_obj))) {
fprintf(logfile, "%s%c", stringValue(boundInfo.ip_obj, "%2.20f").c_str(), SEP); count++;
} else {
fprintf(logfile, "%c", SEP); count++;
}
fprintf(logfile, "%s%c", stringValue(boundInfo.num_gmic).c_str(), SEP); count++;
if (boundInfo.num_gmic > 0) {
fprintf(logfile, "%s%c", stringValue(boundInfo.gmic_obj, "%2.20f").c_str(), SEP); count++;
} else {
fprintf(logfile, "%c", SEP); count++;
}
fprintf(logfile, "%s%c", stringValue(boundInfo.num_lpc).c_str(), SEP); count++;
if (boundInfo.num_lpc > 0) {
fprintf(logfile, "%s%c", stringValue(boundInfo.lpc_obj, "%2.20f").c_str(), SEP); count++;
} else {
fprintf(logfile, "%c", SEP); count++;
}
fprintf(logfile, "%s%c", stringValue(boundInfo.num_vpc).c_str(), SEP); count++;
if (boundInfo.num_vpc > 0) {
fprintf(logfile, "%s%c", stringValue(boundInfo.vpc_obj, "%2.20f").c_str(), SEP); count++;
} else {
fprintf(logfile, "%c", SEP); count++;
}
if (!isInfinity(std::abs(boundInfo.gmic_vpc_obj))) {
fprintf(logfile, "%s%c", stringValue(boundInfo.gmic_vpc_obj, "%2.20f").c_str(), SEP); count++;
} else {
fprintf(logfile, "%c", SEP); count++;
}
assert(count == countBoundInfoEntries);
} // BOUND INFO
{ // GAP INFO
int count = 0;
if (!isInfinity(std::abs(boundInfo.ip_obj))) {
if (!isInfinity(std::abs(boundInfo.gmic_obj))) {
double val = 100. * (boundInfo.gmic_obj - boundInfo.lp_obj)
/ (boundInfo.ip_obj - boundInfo.lp_obj);
fprintf(logfile, "%s%c", stringValue(val, "%2.6f").c_str(), SEP); count++;
} else {
fprintf(logfile, "%c", SEP); count++; // gmic
}
if (!isInfinity(std::abs(boundInfo.lpc_obj))) {
double val = 100. * (boundInfo.lpc_obj - boundInfo.lp_obj)
/ (boundInfo.ip_obj - boundInfo.lp_obj);
fprintf(logfile, "%s%c", stringValue(val, "%2.6f").c_str(), SEP); count++;
} else {
fprintf(logfile, "%c", SEP); count++; // lpc
}
if (!isInfinity(std::abs(boundInfo.vpc_obj))) {
double val = 100. * (boundInfo.vpc_obj - boundInfo.lp_obj)
/ (boundInfo.ip_obj - boundInfo.lp_obj);
fprintf(logfile, "%s%c", stringValue(val, "%2.6f").c_str(), SEP); count++;
} else {
fprintf(logfile, "%c", SEP); count++; // vpc
}
if (!isInfinity(std::abs(boundInfo.gmic_vpc_obj))) {
double val = 100. * (boundInfo.gmic_vpc_obj - boundInfo.lp_obj)
/ (boundInfo.ip_obj - boundInfo.lp_obj);
fprintf(logfile, "%s%c", stringValue(val, "%2.6f").c_str(), SEP); count++;
} else {
fprintf(logfile, "%c", SEP); count++; // gmic_vpc
}
} else {
fprintf(logfile, "%c", SEP); count++; // gmic
fprintf(logfile, "%c", SEP); count++; // lpc
fprintf(logfile, "%c", SEP); count++; // vpc
fprintf(logfile, "%c", SEP); count++; // gmic+vpc
}
assert(count == countGapInfoEntries);
}
fflush(logfile);
} /* printBoundAndGapInfo */
void printSummaryBBInfo(const std::vector<SummaryBBInfo>& info_vec, FILE* logfile,
const bool print_blanks, const char SEP) {
if (!logfile)
return;
int count = 0;
for (auto info : info_vec) {
if (!print_blanks)
fprintf(logfile, "%ld%c", info.first_bb_info.nodes, SEP);
else
fprintf(logfile, "%c", SEP);
count++;
}
for (auto info : info_vec) {
if (!print_blanks)
fprintf(logfile, "%ld%c", info.best_bb_info.nodes, SEP);
else
fprintf(logfile, "%c", SEP);
count++;
}
for (auto info : info_vec) {
if (!print_blanks)
fprintf(logfile, "%2.3f%c", info.first_bb_info.time, SEP);
else
fprintf(logfile, "%c", SEP);
count++;
}
for (auto info : info_vec) {
if (!print_blanks)
fprintf(logfile, "%2.3f%c", info.best_bb_info.time, SEP);
else
fprintf(logfile, "%c", SEP);
count++;
}
fflush(logfile);
assert(count == countSummaryBBInfoEntries);
} /* printSummaryBBInfo */
void printFullBBInfo(const std::vector<SummaryBBInfo>& info_vec, FILE* logfile,
const bool print_blanks, const char SEP) {
if (!logfile)
return;
// const std::vector<bool> did_branch(info_vec.size());
// for (unsigned i = 0; i < info_vec.size(); i++) {
// did_branch[i] = info_vec[i].vec_bb_info.size() > 0;
// }
int count = 0;
if (!print_blanks) {
for (auto& info : info_vec) {
fprintf(logfile, "%s%c", stringValue(info.first_bb_info.obj, "%2.20f").c_str(), SEP);
count++;
}
for (auto& info : info_vec) {
fprintf(logfile, "%s%c", stringValue(info.best_bb_info.obj, "%2.20f").c_str(), SEP);
count++;
}
for (auto& info : info_vec) {
fprintf(logfile, "%s%c", stringValue(info.avg_bb_info.obj, "%2.20f").c_str(), SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%s%c", stringValue(info.first_bb_info.bound, "%2.20f").c_str(), SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%s%c", stringValue(info.best_bb_info.bound, "%2.20f").c_str(), SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%s%c", stringValue(info.avg_bb_info.bound, "%2.20f").c_str(), SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%ld%c", info.first_bb_info.iters, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%ld%c", info.best_bb_info.iters, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%ld%c", info.avg_bb_info.iters, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%ld%c", info.first_bb_info.nodes, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%ld%c", info.best_bb_info.nodes, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%ld%c", info.avg_bb_info.nodes, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%ld%c", info.first_bb_info.root_passes, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%ld%c", info.best_bb_info.root_passes, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%ld%c", info.avg_bb_info.root_passes, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.20f%c", info.first_bb_info.first_cut_pass, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.20f%c", info.best_bb_info.first_cut_pass, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.20f%c", info.avg_bb_info.first_cut_pass, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.20f%c", info.first_bb_info.last_cut_pass, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.20f%c", info.best_bb_info.last_cut_pass, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.20f%c", info.avg_bb_info.last_cut_pass, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%ld%c", info.first_bb_info.root_iters, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%ld%c", info.best_bb_info.root_iters, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%ld%c", info.avg_bb_info.root_iters, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.3f%c", info.first_bb_info.root_time, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.3f%c", info.best_bb_info.root_time, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.3f%c", info.avg_bb_info.root_time, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.3f%c", info.first_bb_info.last_sol_time, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.3f%c", info.best_bb_info.last_sol_time, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.3f%c", info.avg_bb_info.last_sol_time, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.3f%c", info.first_bb_info.time, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.3f%c", info.best_bb_info.time, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.3f%c", info.avg_bb_info.time, SEP);
count++;
}
// Finally, all
for (auto info : info_vec) {
std::vector<std::string> vec_str;
createStringFromBBInfoVec(info.vec_bb_info, vec_str);
for (unsigned i = 0; i < vec_str.size(); i++) {
fprintf(logfile, "%s%c", vec_str[i].c_str(), SEP);
count++;
}
}
} else {
for (unsigned i = 0; i < BB_INFO_CONTENTS.size() * info_vec.size() * 4; i++) {
fprintf(logfile, "%c", SEP); count++;
}
}
fflush(logfile);
assert(count == countFullBBInfoEntries);
} /* printFullBBInfo */
void printOrigProbInfo(const OsiSolverInterface* const solver, FILE* logfile,
const char SEP) {
if (!logfile)
return;
const int num_rows = solver->getNumRows();
const int num_cols = solver->getNumCols();
// Get row stats
int num_eq_rows = 0, num_bound_rows = 0, num_assign_rows = 0;
const CoinPackedMatrix* mat = solver->getMatrixByRow();
for (int row = 0; row < num_rows; row++) {
const double row_lb = solver->getRowLower()[row];
const double row_ub = solver->getRowUpper()[row];
if (isVal(row_lb, row_ub))
num_eq_rows++;
if (mat->getVectorSize(row) == 1) {
if (isVal(row_lb, row_ub))
num_assign_rows++;
else
num_bound_rows++;
}
}
// Calculate fractionality
int num_frac = 0;
int num_fixed = 0, num_gen_int = 0, num_bin = 0, num_cont = 0;
double min_frac = 1., max_frac = 0.;
for (int col = 0; col < num_cols; col++) {
const double col_lb = solver->getColLower()[col];
const double col_ub = solver->getColUpper()[col];
if (isVal(col_lb, col_ub))
num_fixed++;
if (!solver->isInteger(col)) {
num_cont++;
continue;
}
if (solver->isBinary(col))
num_bin++;
else
num_gen_int++;
const double val = solver->getColSolution()[col];
const double floorxk = std::floor(val);
const double ceilxk = std::ceil(val);
const double frac = CoinMin(val - floorxk, ceilxk - val);
if (!isVal(frac, 0., 1e-5)) {
num_frac++;
if (frac < min_frac)
min_frac = frac;
if (frac > max_frac)
max_frac = frac;
}
}
int count = 0;
fprintf(logfile, "%s%c", stringValue(num_rows).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(num_cols).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(num_frac).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(min_frac, "%.5f").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(max_frac, "%.5f").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(num_eq_rows).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(num_bound_rows).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(num_assign_rows).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(num_fixed).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(num_gen_int).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(num_bin).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(num_cont).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue((double) mat->getNumElements() / (num_rows * num_cols)).c_str(), SEP); count++;
fflush(logfile);
assert(count == countOrigProbEntries);
} /* printOrigProbInfo */
/**
* @details Assumed that solver is already with cuts added
*/
void printPostCutProbInfo(const OsiSolverInterface* const solver,
const SummaryCutInfo& cutInfoGMICs, const SummaryCutInfo& cutInfoVPCs,
FILE* logfile, const char SEP) {
if (!logfile)
return;
const int num_rows = solver->getNumRows();
const int num_cols = solver->getNumCols();
// Calculate fractionality
int num_frac = 0;
double min_frac = 1., max_frac = 0.;
for (int col = 0; col < num_cols; col++) {
if (!solver->isInteger(col)) {
continue;
}
const double val = solver->getColSolution()[col];
const double floorxk = std::floor(val);
const double ceilxk = std::ceil(val);
const double frac = CoinMin(val - floorxk, ceilxk - val);
if (!isVal(frac, 0., 1e-5)) {
num_frac++;
if (frac < min_frac)
min_frac = frac;
if (frac > max_frac)
max_frac = frac;
}
}
int count = 0;
fprintf(logfile, "%s%c", stringValue(num_frac).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(min_frac, "%.5f").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(max_frac, "%.5f").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue((double) solver->getMatrixByCol()->getNumElements() / (num_rows * num_cols)).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfoGMICs.num_active_gmic).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfoVPCs.num_active_gmic).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfoGMICs.num_active_vpc).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfoVPCs.num_active_vpc).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfoGMICs.num_active_all).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfoVPCs.num_active_all).c_str(), SEP); count++;
fflush(logfile);
assert(count == countPostCutProbEntries);
} /* printPostCutProbInfo */
void printDisjInfo(const SummaryDisjunctionInfo& disjInfo, FILE* logfile,
const char SEP) {
if (!logfile)
return;
int count = 0;
fprintf(logfile, "%s%c", stringValue(disjInfo.avg_num_terms, "%g").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(disjInfo.num_integer_sol, "%d").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(disjInfo.num_disj, "%d").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(disjInfo.avg_density_prlp, "%g").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(disjInfo.avg_num_rows_prlp, "%g").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(disjInfo.avg_num_cols_prlp, "%g").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(disjInfo.avg_num_points_prlp, "%g").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(disjInfo.avg_num_rays_prlp, "%g").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(disjInfo.avg_explored_nodes, "%g").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(disjInfo.avg_pruned_nodes, "%g").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(disjInfo.avg_min_depth, "%g").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(disjInfo.avg_max_depth, "%g").c_str(), SEP); count++;
fflush(logfile);
assert(count == countDisjInfoEntries);
} /* printDisjInfo */
void printCutInfo(const SummaryCutInfo& cutInfoGMICs,
const SummaryCutInfo& cutInfo, FILE* logfile, const char SEP) {
if (!logfile)
return;
{ // CUT INFO
int count = 0;
fprintf(logfile, "%s%c", stringValue(cutInfo.num_rounds).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfo.num_cuts).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfo.numCutsOfType[static_cast<int>(CglVPC::CutType::ONE_SIDED_CUT)]).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfo.numCutsOfType[static_cast<int>(CglVPC::CutType::OPTIMALITY_CUT)]).c_str(), SEP); count++;
if (cutInfo.num_cuts > 0) {
fprintf(logfile, "%s%c", stringValue(cutInfo.min_support).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfo.max_support).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfo.avg_support, "%.3f").c_str(), SEP); count++;
} else {
fprintf(logfile, "%s%c", stringValue(0).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(0).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(0).c_str(), SEP); count++;
}
if (cutInfoGMICs.num_cuts > 0) {
fprintf(logfile, "%s%c", stringValue(cutInfoGMICs.min_support).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfoGMICs.max_support).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfoGMICs.avg_support, "%.3f").c_str(), SEP); count++;
} else {
fprintf(logfile, "%s%c", stringValue(0).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(0).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(0).c_str(), SEP); count++;
}
assert(count == countCutInfoEntries);
} // CUT INFO
{ // OBJ INFO
int count = 0;
fprintf(logfile, "%s%c", stringValue(cutInfo.num_obj_tried).c_str(), SEP); count++;
for (int obj_ind = 0; obj_ind < static_cast<int>(CglVPC::ObjectiveType::NUM_OBJECTIVE_TYPES); obj_ind++) {
fprintf(logfile, "%s%c", stringValue(cutInfo.numObjFromHeur[obj_ind]).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfo.numCutsFromHeur[obj_ind]).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfo.numFailsFromHeur[obj_ind]).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfo.numActiveFromHeur[obj_ind]).c_str(), SEP); count++;
}
assert(count == countObjInfoEntries);
} // OBJ INFO
{ // FAIL INFO
int count = 0;
fprintf(logfile, "%s%c", stringValue(cutInfo.num_failures).c_str(), SEP); count++;
for (int fail_ind = 0; fail_ind < static_cast<int>(CglVPC::FailureType::NUM_FAILURE_TYPES); fail_ind++) {
fprintf(logfile, "%s%c", stringValue(cutInfo.numFails[fail_ind]).c_str(), SEP); count++;
}
assert(count == countFailInfoEntries);
} // FAIL INFO
fflush(logfile);
} /* printCutInfo */
/// @details Gets cut support size and updates min/max component of \p cutInfo
int checkCutDensity(
/// [in,out] Where to save min and max support
SummaryCutInfo& cutInfo,
/// [in] Row that we want to check
const OsiRowCut* const cut,
/// [in] What counts as a zero coefficient
const double EPS) {
int num_elem = cut->row().getNumElements();
const double* el = cut->row().getElements();
for (int i = 0; i < cut->row().getNumElements(); i++) {
if (isZero(el[i], EPS)) {
num_elem--;
}
}
if (num_elem < cutInfo.min_support)
cutInfo.min_support = num_elem;
if (num_elem > cutInfo.max_support)
cutInfo.max_support = num_elem;
return num_elem;
} // checkCutDensity
/// @brief Find active cuts, and also report density of cuts
bool checkCutActivity(
const OsiSolverInterface* const solver,
const OsiRowCut* const cut) {
if (solver && solver->isProvenOptimal()) {
const double activity = dotProduct(cut->row(), solver->getColSolution());
return isVal(activity, cut->rhs());
} else {
return false;
}
} /* checkCutActivity */
/**
* @details The cut properties we want to look at are:
* 1. Gap closed
* 2. Activity (after adding cuts)
* 3. Density
*/
void analyzeStrength(
const VPCParameters& params,
const OsiSolverInterface* const solver_gmic,
const OsiSolverInterface* const solver_vpc,
const OsiSolverInterface* const solver_all,
SummaryCutInfo& cutInfoGMICs, SummaryCutInfo& cutInfoVPCs,
const OsiCuts* const gmics, const OsiCuts* const vpcs,
const SummaryBoundInfo& boundInfo, std::string& output) {
cutInfoGMICs.num_active_gmic = 0;
cutInfoGMICs.num_active_vpc = 0;
cutInfoGMICs.num_active_all = 0;
cutInfoVPCs.num_active_gmic = 0;
cutInfoVPCs.num_active_vpc = 0;
cutInfoVPCs.num_active_all = 0;
cutInfoVPCs.numActiveFromHeur.resize(static_cast<int>(CglVPC::ObjectiveType::NUM_OBJECTIVE_TYPES), 0);
if (vpcs) {
const int num_vpcs = vpcs->sizeCuts();
int total_support = 0;
for (int cut_ind = 0; cut_ind < num_vpcs; cut_ind++) {
const OsiRowCut* const cut = vpcs->rowCutPtr(cut_ind);
if (checkCutActivity(solver_gmic, cut)) {
cutInfoVPCs.num_active_gmic++;
}
if (checkCutActivity(solver_vpc, cut)) {
cutInfoVPCs.num_active_vpc++;
cutInfoVPCs.numActiveFromHeur[static_cast<int>(cutInfoVPCs.objType[cut_ind])]++;
}
if (checkCutActivity(solver_all, cut)) {
cutInfoVPCs.num_active_all++;
}
total_support += checkCutDensity(cutInfoVPCs, cut, params.get(EPS) / 2.);
}
cutInfoVPCs.avg_support = (double) total_support / num_vpcs;
}
if (gmics) {
const int num_gmics = gmics->sizeCuts();
cutInfoGMICs.num_cuts = num_gmics;
int total_support = 0;
for (int cut_ind = 0; cut_ind < num_gmics; cut_ind++) {
const OsiRowCut* const cut = gmics->rowCutPtr(cut_ind);
if (checkCutActivity(solver_gmic, cut)) {
cutInfoGMICs.num_active_gmic++;
}
if (checkCutActivity(solver_vpc, cut)) {
cutInfoGMICs.num_active_vpc++;
}
if (checkCutActivity(solver_all, cut)) {
cutInfoGMICs.num_active_all++;
}
total_support += checkCutDensity(cutInfoGMICs, cut, params.get(EPS) / 2.);
}
cutInfoGMICs.avg_support = (double) total_support / num_gmics;
}
// Print results from adding cuts
int NAME_WIDTH = 25;
int NUM_DIGITS_BEFORE_DEC = 7;
int NUM_DIGITS_AFTER_DEC = 7;
const double INF = std::numeric_limits<double>::max();
char tmpstring[300];
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char),
"\n## Results from adding cuts ##\n");
output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*.*s%s\n",
NAME_WIDTH, NAME_WIDTH, "LP: ",
stringValue(boundInfo.lp_obj, "% -*.*g",
INF,
NUM_DIGITS_BEFORE_DEC,
NUM_DIGITS_AFTER_DEC).c_str());
output += tmpstring;
if (!isInfinity(std::abs(boundInfo.gmic_obj))) {
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char),
"%-*.*s%s (%d cuts", NAME_WIDTH, NAME_WIDTH, "GMICs: ",
stringValue(boundInfo.gmic_obj, "% -*.*g",
INF,
NUM_DIGITS_BEFORE_DEC,
NUM_DIGITS_AFTER_DEC).c_str(),
boundInfo.num_gmic);
output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char),
", %d active GMICs", cutInfoGMICs.num_active_gmic);
output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char),
", %d active VPCs", cutInfoVPCs.num_active_gmic);
output += tmpstring;
output += ")\n";
}
if (!isInfinity(std::abs(boundInfo.vpc_obj))) {
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char),
"%-*.*s%s (%d cuts", NAME_WIDTH, NAME_WIDTH, "VPCs: ",
stringValue(boundInfo.vpc_obj, "% -*.*g",
INF,
NUM_DIGITS_BEFORE_DEC,
NUM_DIGITS_AFTER_DEC).c_str(),
boundInfo.num_vpc);
output += tmpstring;
if (gmics && gmics->sizeCuts() > 0) {
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char),
", %d active GMICs", cutInfoGMICs.num_active_vpc);
output += tmpstring;
}
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char),
", %d active VPCs", cutInfoVPCs.num_active_vpc);
output += tmpstring;
output += ")\n";
}
if (boundInfo.num_gmic + boundInfo.num_lpc > 0) {
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char),
"%-*.*s%s (%d cuts", NAME_WIDTH, NAME_WIDTH, "All: ",
stringValue(boundInfo.all_cuts_obj, "% -*.*g", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str(),
boundInfo.num_gmic + boundInfo.num_lpc + boundInfo.num_vpc);
output += tmpstring;
if (gmics && gmics->sizeCuts() > 0) {
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char),
", %d active GMICs", cutInfoGMICs.num_active_all);
output += tmpstring;
}
if (vpcs && vpcs->sizeCuts() > 0) {
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char),
", %d active VPCs", cutInfoVPCs.num_active_all);
output += tmpstring;
}
output += ")\n";
}
if (!isInfinity(std::abs(boundInfo.best_disj_obj))) {
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*.*s%s\n",
NAME_WIDTH, NAME_WIDTH, "Disjunctive lb: ",
stringValue(boundInfo.best_disj_obj, "% -*.*g",
INF,
NUM_DIGITS_BEFORE_DEC,
NUM_DIGITS_AFTER_DEC).c_str());
output += tmpstring;
}
if (!isInfinity(std::abs(boundInfo.worst_disj_obj))) {
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*.*s%s\n",
NAME_WIDTH, NAME_WIDTH, "Disjunctive ub: ",
stringValue(boundInfo.worst_disj_obj, "% -*.*g",
INF,
NUM_DIGITS_BEFORE_DEC,
NUM_DIGITS_AFTER_DEC).c_str());
output += tmpstring;
}
if (!isInfinity(std::abs(boundInfo.ip_obj))) {
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*.*s%s\n",
NAME_WIDTH, NAME_WIDTH, "IP: ",
stringValue(boundInfo.ip_obj, "% -*.*g",
INF,
NUM_DIGITS_BEFORE_DEC,
NUM_DIGITS_AFTER_DEC).c_str());
output += tmpstring;
}
} /* analyzeStrength */
/** @details Branch-and-bound itself has already been performed */
void analyzeBB(const VPCParameters& params, SummaryBBInfo& info_nocuts,
SummaryBBInfo& info_mycuts, SummaryBBInfo& info_allcuts, std::string& output) {
if (params.get(BB_RUNS) == 0) {
return;
}
// B&B mode: ones bit = no_cuts, tens bit = w/vpcs, hundreds bit = w/gmics
const int mode_param = params.get(intParam::BB_MODE);
const int mode_ones = mode_param % 10;
const int mode_tens = (mode_param % 100 - (mode_param % 10)) / 10;
const int mode_hundreds = (mode_param % 1000 - (mode_param % 100)) / 100;
const bool branch_with_no_cuts = (mode_ones > 0);
const bool branch_with_vpcs = (mode_tens > 0) && (info_mycuts.num_cuts > 0);
const bool branch_with_gmics = (mode_hundreds > 0) && (info_allcuts.num_cuts > 0);
if (branch_with_no_cuts + branch_with_vpcs + branch_with_gmics == 0) {
return;
}
// Save results to string and also print to the logfile
const int NAME_WIDTH = 10; //25
const int NUM_DIGITS_BEFORE_DEC = 15; //10
const int NUM_DIGITS_AFTER_DEC = 2; //2
const double INF = 1e50; //params.get(doubleParam::INF);
const bool use_gurobi = use_bb_option(params.get(intParam::BB_STRATEGY), BB_Strategy_Options::gurobi);
const bool use_cplex = use_bb_option(params.get(intParam::BB_STRATEGY), BB_Strategy_Options::cplex);
const bool use_cbc = use_bb_option(params.get(intParam::BB_STRATEGY), BB_Strategy_Options::cbc);
const std::string SOLVER =
use_gurobi ? "Gur" :
(use_cplex ? "Cpx" :
(use_cbc ? "Cbc" : "")
);
char tmpstring[300];
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "\n## Branch-and-bound results ##\n"); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*s", NAME_WIDTH, ""); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*s", NUM_DIGITS_BEFORE_DEC, "Obj"); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*s", NUM_DIGITS_BEFORE_DEC, "Bound"); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*s", NUM_DIGITS_BEFORE_DEC, "Iters"); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*s", NUM_DIGITS_BEFORE_DEC, "Nodes"); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*s", NUM_DIGITS_BEFORE_DEC, "Root passes"); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*s", NUM_DIGITS_BEFORE_DEC, "First cut pass"); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*s", NUM_DIGITS_BEFORE_DEC, "Last cut pass"); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*s", NUM_DIGITS_BEFORE_DEC, "Root time"); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*s", NUM_DIGITS_BEFORE_DEC, "Last sol time"); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*s", NUM_DIGITS_BEFORE_DEC, "Time"); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "\n"); output += tmpstring;
if (branch_with_no_cuts) {
const std::string CURR_NAME = SOLVER;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*s", NAME_WIDTH, CURR_NAME.c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_nocuts.avg_bb_info.obj, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_nocuts.avg_bb_info.bound, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_nocuts.avg_bb_info.iters, "%-*ld", std::numeric_limits<long double>::max(), NUM_DIGITS_BEFORE_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_nocuts.avg_bb_info.nodes, "%-*ld", std::numeric_limits<long double>::max(), NUM_DIGITS_BEFORE_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_nocuts.avg_bb_info.root_passes, "%-*ld", std::numeric_limits<long double>::max(), NUM_DIGITS_BEFORE_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_nocuts.avg_bb_info.first_cut_pass, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_nocuts.avg_bb_info.last_cut_pass, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_nocuts.avg_bb_info.root_time, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_nocuts.avg_bb_info.last_sol_time, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_nocuts.avg_bb_info.time, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "\n"); output += tmpstring;
} // no cuts
if (branch_with_vpcs) {
const std::string CURR_NAME = SOLVER + "V";
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*s", NAME_WIDTH, CURR_NAME.c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_mycuts.avg_bb_info.obj, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_mycuts.avg_bb_info.bound, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_mycuts.avg_bb_info.iters, "%-*ld", std::numeric_limits<long double>::max(), NUM_DIGITS_BEFORE_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_mycuts.avg_bb_info.nodes, "%-*ld", std::numeric_limits<long double>::max(), NUM_DIGITS_BEFORE_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_mycuts.avg_bb_info.root_passes, "%-*ld", std::numeric_limits<long double>::max(), NUM_DIGITS_BEFORE_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_mycuts.avg_bb_info.first_cut_pass, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_mycuts.avg_bb_info.last_cut_pass, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_mycuts.avg_bb_info.root_time, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_mycuts.avg_bb_info.last_sol_time, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_mycuts.avg_bb_info.time, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "\n"); output += tmpstring;
} // vpcs
if (branch_with_gmics) {
const std::string CURR_NAME = SOLVER + "V+G";
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*s", NAME_WIDTH, CURR_NAME.c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_allcuts.avg_bb_info.obj, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_allcuts.avg_bb_info.bound, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_allcuts.avg_bb_info.iters, "%-*ld", std::numeric_limits<long double>::max(), NUM_DIGITS_BEFORE_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_allcuts.avg_bb_info.nodes, "%-*ld", std::numeric_limits<long double>::max(), NUM_DIGITS_BEFORE_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_allcuts.avg_bb_info.root_passes, "%-*ld", std::numeric_limits<long double>::max(), NUM_DIGITS_BEFORE_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_allcuts.avg_bb_info.first_cut_pass, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_allcuts.avg_bb_info.last_cut_pass, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_allcuts.avg_bb_info.root_time, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_allcuts.avg_bb_info.last_sol_time, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_allcuts.avg_bb_info.time, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "\n"); output += tmpstring;
} // gmics
} /* analyzeBB */
double getNumGomoryRounds(const VPCParameters& params,
const OsiSolverInterface* const origSolver,
const OsiSolverInterface* const postCutSolver) {
#ifdef TRACE
printf("\nGetting number rounds of Gomory cuts req'd to get bound.\n");
#endif
const int num_cuts = postCutSolver->getNumRows() - origSolver->getNumRows();
const double post_cut_opt = postCutSolver->getObjValue();
const int min_sic_rounds = (params.get(STRENGTHEN) == 2) ? 2 : 0;
int max_rounds = 1000;
int total_num_sics = 0;
int num_sic_rounds = 0;
double curr_sic_opt = 0.;
std::vector<int> numCutsByRoundSIC;
std::vector<double> boundByRoundSIC;
OsiSolverInterface* copySolver = origSolver->clone();
if (!copySolver->isProvenOptimal()) {
copySolver->initialSolve();
checkSolverOptimality(copySolver, false);
}
while (num_sic_rounds < min_sic_rounds
|| (lessThanVal(curr_sic_opt, post_cut_opt) && total_num_sics < num_cuts)) {
OsiCuts GMICs;
CglGMI gen;
gen.generateCuts(*copySolver, GMICs);
const int curr_num_cuts = GMICs.sizeCuts();
if (curr_num_cuts == 0)
break;
num_sic_rounds++;
total_num_sics += curr_num_cuts;
numCutsByRoundSIC.push_back(curr_num_cuts);
curr_sic_opt = applyCutsCustom(copySolver, GMICs, params.logfile);
boundByRoundSIC.push_back(curr_sic_opt);
// Other stopping conditions:
// Bound does not improve at all after one round
if (num_sic_rounds >= 2
&& !greaterThanVal(curr_sic_opt, boundByRoundSIC[num_sic_rounds - 2])) {
break;
}
// Bound does not significantly improve after five rounds
if (num_sic_rounds > 4) {
const double delta = curr_sic_opt - boundByRoundSIC[num_sic_rounds - 4];
if (!greaterThanVal(delta, 1e-3)) {
break;
}
}
} // do rounds of Gomory cuts
if (max_rounds < num_sic_rounds) {
max_rounds = boundByRoundSIC.size();
}
const double final_sic_bound = copySolver->getObjValue();
return final_sic_bound;
} /* getNumGomoryRounds */
void updateDisjInfo(SummaryDisjunctionInfo& disjInfo, const int num_disj, const CglVPC& gen) {
if (num_disj <= 0)
return;
const Disjunction* const disj = gen.getDisjunction();
const PRLP* const prlp = gen.getPRLP();
if (!prlp)
return;
disjInfo.num_disj = num_disj;
disjInfo.num_integer_sol += !(disj->integer_sol.empty());
disjInfo.avg_num_terms = (disjInfo.avg_num_terms * (num_disj - 1) + disj->num_terms) / num_disj;
disjInfo.avg_density_prlp = (disjInfo.avg_density_prlp * (num_disj - 1) + prlp->density) / num_disj;
disjInfo.avg_num_rows_prlp += (disjInfo.avg_num_rows_prlp * (num_disj - 1) + prlp->getNumRows()) / num_disj;
disjInfo.avg_num_cols_prlp += (disjInfo.avg_num_cols_prlp * (num_disj - 1) + prlp->getNumCols()) / num_disj;
disjInfo.avg_num_points_prlp += (disjInfo.avg_num_points_prlp * (num_disj - 1) + prlp->numPoints) / num_disj;
disjInfo.avg_num_rays_prlp += (disjInfo.avg_num_rays_prlp * (num_disj - 1) + prlp->numRays) / num_disj;
try {
const PartialBBDisjunction* const partialDisj =
dynamic_cast<const PartialBBDisjunction* const >(disj);
disjInfo.avg_explored_nodes += (disjInfo.avg_explored_nodes * (num_disj - 1) + partialDisj->data.num_nodes_on_tree) / num_disj;
disjInfo.avg_pruned_nodes += (disjInfo.avg_pruned_nodes * (num_disj - 1) + partialDisj->data.num_pruned_nodes) / num_disj;
disjInfo.avg_min_depth += (disjInfo.avg_min_depth * (num_disj - 1) + partialDisj->data.min_node_depth) / num_disj;
disjInfo.avg_max_depth += (disjInfo.avg_max_depth * (num_disj - 1) + partialDisj->data.max_node_depth) / num_disj;
} catch (std::exception& e) {
}
} /* updateDisjInfo */
/**
* @details Use this to add to cutInfo (but within one round,
* because the cutType and objType vectors are cleared in gen in each round
* (so tracking that based on isSetupForRepeatedUse does not work,
* and the old cutType and objType stored in cutInfo would be overwritten)
*/
void updateCutInfo(SummaryCutInfo& cutInfo, const CglVPC& gen) {
cutInfo.num_cuts += gen.num_cuts;
cutInfo.num_obj_tried += gen.num_obj_tried;
cutInfo.num_failures += gen.num_failures;
// For cutType and objType, what we do depends on whether the generator is setup for repeated use or not
if (gen.isSetupForRepeatedUse) {
cutInfo.cutType = gen.cutType;
cutInfo.objType = gen.objType;
} else {
cutInfo.cutType.insert(cutInfo.cutType.end(), gen.cutType.begin(), gen.cutType.end());
cutInfo.objType.insert(cutInfo.objType.end(), gen.objType.begin(), gen.objType.end());
}
if (cutInfo.numCutsOfType.size() > 0) {
for (int i = 0; i < static_cast<int>(CglVPC::CutType::NUM_CUT_TYPES); i++) {
cutInfo.numCutsOfType[i] += gen.numCutsOfType[i];
}
} else {
cutInfo.numCutsOfType = gen.numCutsOfType;
}
if (cutInfo.numCutsFromHeur.size() > 0) {
for (int i = 0; i < static_cast<int>(CglVPC::ObjectiveType::NUM_OBJECTIVE_TYPES); i++) {
cutInfo.numCutsFromHeur[i] += gen.numCutsFromHeur[i];
cutInfo.numObjFromHeur[i] += gen.numObjFromHeur[i];
cutInfo.numFailsFromHeur[i] += gen.numFailsFromHeur[i];
}
} else {
cutInfo.numCutsFromHeur = gen.numCutsFromHeur;
cutInfo.numObjFromHeur = gen.numObjFromHeur;
cutInfo.numFailsFromHeur = gen.numFailsFromHeur;
}
if (cutInfo.numFails.size() > 0) {
for (int i = 0; i < static_cast<int>(CglVPC::FailureType::NUM_FAILURE_TYPES); i++) {
cutInfo.numFails[i] += gen.numFails[i];
}
} else {
cutInfo.numFails = gen.numFails;
}
} /* updateCutInfo (within one round) */
/**
* @details Compute total number of cuts / objectives / failures of various types, as well as total activity
*/
void setCutInfo(SummaryCutInfo& cutInfo, const int num_rounds,
const SummaryCutInfo* const oldCutInfos) {
const int numCutTypes = static_cast<int>(CglVPC::CutType::NUM_CUT_TYPES);
const int numObjTypes = static_cast<int>(CglVPC::ObjectiveType::NUM_OBJECTIVE_TYPES);
const int numFailTypes = static_cast<int>(CglVPC::FailureType::NUM_FAILURE_TYPES);
cutInfo.num_cuts = 0;
cutInfo.num_active_gmic = 0;
cutInfo.num_active_vpc = 0;
cutInfo.num_active_all = 0;
cutInfo.num_obj_tried = 0;
cutInfo.num_failures = 0;
cutInfo.num_rounds = num_rounds;
cutInfo.cutType.resize(0);
cutInfo.objType.resize(0);
cutInfo.numCutsOfType.clear();
cutInfo.numCutsOfType.resize(numCutTypes, 0);
cutInfo.numCutsFromHeur.clear();
cutInfo.numCutsFromHeur.resize(numObjTypes, 0);
cutInfo.numObjFromHeur.clear();
cutInfo.numObjFromHeur.resize(numObjTypes, 0);
cutInfo.numFailsFromHeur.clear();
cutInfo.numFailsFromHeur.resize(numObjTypes, 0);
cutInfo.numActiveFromHeur.clear();
cutInfo.numActiveFromHeur.resize(numObjTypes, 0);
cutInfo.numFails.clear();
cutInfo.numFails.resize(numFailTypes, 0);
for (int round = 0; round < num_rounds; round++) {
cutInfo.num_cuts += oldCutInfos[round].num_cuts;
cutInfo.num_active_gmic += oldCutInfos[round].num_active_gmic;
cutInfo.num_active_vpc += oldCutInfos[round].num_active_vpc;
cutInfo.num_active_all += oldCutInfos[round].num_active_all;
cutInfo.num_obj_tried += oldCutInfos[round].num_obj_tried;
cutInfo.num_failures += oldCutInfos[round].num_failures;
for (int i = 0; i < numCutTypes; i++) {
cutInfo.numCutsOfType[i] += oldCutInfos[round].numCutsOfType[i];
}
for (int i = 0; i < numObjTypes; i++) {
cutInfo.numCutsFromHeur[i] += oldCutInfos[round].numCutsFromHeur[i];
cutInfo.numObjFromHeur[i] += oldCutInfos[round].numObjFromHeur[i];
cutInfo.numFailsFromHeur[i] += oldCutInfos[round].numFailsFromHeur[i];
}
if (oldCutInfos[round].numActiveFromHeur.size() > 0) {
for (int i = 0; i < numObjTypes; i++) {
cutInfo.numActiveFromHeur[i] += oldCutInfos[round].numActiveFromHeur[i];
}
}
for (int i = 0; i < numFailTypes; i++) {
cutInfo.numFails[i] += oldCutInfos[round].numFails[i];
}
}
cutInfo.cutType.resize(cutInfo.num_cuts);
cutInfo.objType.resize(cutInfo.num_cuts);
int cut_ind = 0;
for (int round = 0; round < num_rounds; round++) {
for (int i = 0; i < oldCutInfos[round].num_cuts; i++) {
cutInfo.cutType[cut_ind] = oldCutInfos[round].cutType[i];
cutInfo.objType[cut_ind] = oldCutInfos[round].objType[i];
cut_ind++;
}
}
} /* setCutInfo (merge from multiple rounds) */
| 45.849838 | 217 | 0.652876 |
76a4ece61a7d68d10de049ef4a74ce6bd9f37d37 | 1,494 | cpp | C++ | multiview/contrib/mosya_conics/src/IsCrossingWindow.cpp | prcvlabs/multiview | 1a03e14855292967ffb0c0ec7fff855c5abbc9d2 | [
"Apache-2.0"
] | 5 | 2021-09-03T23:12:08.000Z | 2022-03-04T21:43:32.000Z | multiview/contrib/mosya_conics/src/IsCrossingWindow.cpp | prcvlabs/multiview | 1a03e14855292967ffb0c0ec7fff855c5abbc9d2 | [
"Apache-2.0"
] | 3 | 2021-09-08T02:57:46.000Z | 2022-02-26T05:33:02.000Z | multiview/contrib/mosya_conics/src/IsCrossingWindow.cpp | prcvlabs/multiview | 1a03e14855292967ffb0c0ec7fff855c5abbc9d2 | [
"Apache-2.0"
] | 2 | 2021-09-26T03:14:40.000Z | 2022-01-26T06:42:52.000Z |
namespace mosya {
int IsCrossingWindow(M6x1 A, reals R)
/*
*/
{
reals RR,F0,x,y,det,Two=2.;
RR = R*R;
F0 = (A(0) + A(1) + A(1) + A(2))*RR + Two*(A(3) + A(4))*R + A(5);
if (((A(0) - A(1) - A(1) + A(2))*RR + Two*(A(3) - A(4))*R + A(5))*F0 <= 0) return(1);
if (((A(0) - A(1) - A(1) + A(2))*RR - Two*(A(3) - A(4))*R + A(5))*F0 <= 0) return(1);
if (((A(0) + A(1) + A(1) + A(2))*RR - Two*(A(3) + A(4))*R + A(5))*F0 <= 0) return(1);
y = -(A(1)*R+A(4))/A(2);
if (abs(y) < R) { if ((A(0)*RR + Two*A(1)*R*y + A(2)*y*y + Two*(A(3)*R + A(4)*y) + A(5))*F0 <= 0) return(1); }
y = (A(1)*R-A(4))/A(2);
if (abs(y) < R) { if ((A(0)*RR - Two*A(1)*R*y + A(2)*y*y - Two*(A(3)*R - A(4)*y) + A(5))*F0 <= 0) return(1); }
x = -(A(1)*R+A(3))/A(0);
if (abs(x) < R) { if ((A(0)*x*x + Two*A(1)*R*x + A(2)*RR + Two*(A(3)*x + A(4)*R) + A(5))*F0 <= 0) return(1); }
x = (A(1)*R-A(3))/A(0);
if (abs(x) < R) { if ((A(0)*x*x - Two*A(1)*R*x + A(2)*RR + Two*(A(3)*x - A(4)*R) + A(5))*F0 <= 0) return(1); }
det = A(0)*A(2) - A(1)*A(1); // determinant
if (abs(det)<1.e-100) return(0); // if singular, skip this step
x = (A(3)*A(2) - A(4)*A(1))/det;
y = (A(0)*A(4) - A(1)*A(3))/det;
if ((abs(x)<R) && (abs(y)<R)) { if ((A(0)*x*x + Two*A(1)*x*y + A(2)*y*y + Two*(A(3)*x + A(4)*y) + A(5))*F0 <= 0) return(1); }
return(0);
} // end of function IsCrossingWindow
} // namespace mosya
| 35.571429 | 132 | 0.390897 |
76a6fbb86df683ddd90b26466743ee20b8bee87b | 1,247 | cpp | C++ | C-Plus-Plus/Pancake_sort.cpp | MjCode01/DS-Algo-Point | 79d826fa63090014dfaab281e5170c25b86c6bbf | [
"MIT"
] | 1,148 | 2020-09-28T15:06:16.000Z | 2022-03-17T16:30:08.000Z | C-Plus-Plus/Pancake_sort.cpp | MjCode01/DS-Algo-Point | 79d826fa63090014dfaab281e5170c25b86c6bbf | [
"MIT"
] | 520 | 2020-09-28T18:34:26.000Z | 2021-10-30T17:06:43.000Z | C-Plus-Plus/Pancake_sort.cpp | MjCode01/DS-Algo-Point | 79d826fa63090014dfaab281e5170c25b86c6bbf | [
"MIT"
] | 491 | 2020-09-28T18:40:14.000Z | 2022-03-20T13:41:44.000Z | //This code is solely written by Arnav without any external sources.
// Pancake sort
#include<bits/stdc++.h>
using namespace std;
void flip(int arr[] , int i){
for(int j = 0 ; j <= (i / 2) ; j++)
{
int temp = arr[i-j] ;
arr[i-j] = arr[j] ;
arr[j] = temp ;
}
}
// time complexity = O(n) ; Space complexity = O(1)
void sort(int arr[] , int n){
int curr_size = n ;
while(curr_size > 0)
{
int max_index = max_element(arr , arr + curr_size) - arr; // time complexity = O(n) ; space complexity = O(1);
if(max_index !=curr_size -1)
{
flip(arr, max_index);
flip(arr, curr_size -1) ;}
curr_size-- ;
}
}
//time complexity = O(n * max(p, q)) where p is the time complexity of flip() and q is the complexity of max_element(); space complexity = O(1)
int main()
{
int n ; cin >> n ;
int a[n] ;
for(int i = 0 ; i < n ; i ++)
{
cin >> a[i] ;
}
sort(a , n);
for(int i = 0 ; i < n ; i ++)
{
cout << a[i] << " " ;
}
}
/* here n is the number of elements in the array to be sorted and a[0...n-1] is the array.
input example:
5
5 4 3 2 1
Output:
1 2 3 4 5
Overall time complexity = O(n*n) ; Overall Space complexity = O(1) */
| 18.338235 | 144 | 0.540497 |
76a97b05240b232ce4c2d9953ced0cdb79098a1e | 21,068 | cc | C++ | src/moorerror.cc | CHEN-Lin/OpenMoor | f463f586487b9023e7f3678c9d851000558b14d7 | [
"Apache-2.0"
] | 7 | 2019-02-10T07:03:45.000Z | 2022-03-04T16:09:38.000Z | src/moorerror.cc | CHEN-Lin/OpenMoor | f463f586487b9023e7f3678c9d851000558b14d7 | [
"Apache-2.0"
] | null | null | null | src/moorerror.cc | CHEN-Lin/OpenMoor | f463f586487b9023e7f3678c9d851000558b14d7 | [
"Apache-2.0"
] | 4 | 2018-03-01T14:34:52.000Z | 2018-06-14T12:13:55.000Z | // This file is part of OpenMOOR, an Open-source simulation program for MOORing
// systems in offshore renewable energy applications.
//
// Copyright 2018 Lin Chen <l.chen.tj@gmail.com> & Biswajit Basu <basub@tcd.ie>
//
// 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 "moorerror.h"
namespace moor {
std::string ErrorCategory::message(ErrorCode err)
{
switch (err)
{
case ErrorCode::SUCCESS:
return "Successful.";
case ErrorCode::MOORING_FILE_NONEXISTENT:
return "Failed to find main mooring file. It should be a xml file.";
case ErrorCode::MOORING_FILE_ERROR_PARSE:
return "Parse error found in main input xml file. Check xml format.";
case ErrorCode::MOORING_FILE_NO_CASE:
return "Root node of main input file must be 'case'.";
case ErrorCode::MOORING_FILE_INCOMPLETE:
return ("Incomplete components found in mooring input file. "
"Required are: 'constants', 'platform', 'connections', "
"'cables', 'structuralproperties', 'hydroproperties', "
"'seabedproperties', 'currents' and 'solvers'.");
case ErrorCode::MOORING_FILE_INCOMPLETE_CONSTANTS:
return ("Incomplete constants definition. Required are "
"'gravitationalacceleration', 'waterdensity' and "
"'waterdepth'.");
case ErrorCode::MOORING_FILE_NAN_CONSTANT:
return "NaN found in constant definitions.";
case ErrorCode::MOORING_FILE_INCOMPLETE_PLATFORM:
return ("Failed to find platform position definition or incomplete "
"position components provided. Position of the reference "
"point is required to have six component: 'x', 'y', 'z' "
"'roll', 'pitch' and 'yaw'.");
case ErrorCode::MOORING_FILE_NAN_PLATFORM_POSITION:
return "NaN found in platform position definition.";
case ErrorCode::MOORING_FILE_BAD_CONNECTIONS_NUM:
return ("Unacceptable 'number' of 'connections': "
"NaN or nonpositive.");
case ErrorCode::MOORING_FILE_NO_CONNECTION:
return "Failed to find at least one connection definition.";
case ErrorCode::MOORING_FILE_INCOMPLETE_CONNECTION_DEF:
return ("Incomplete connection definition. Required are 'id', "
"'type', 'x', 'y' and 'z'.");
case ErrorCode::MOORING_FILE_NAN_CONNECTION_DEF:
return "NaN found in connection 'id' or position components.";
case ErrorCode::MOORING_FILE_OUTOFRANGE_CONNECTION_ID:
return ("Found connection 'id' out of range of the 'number' of "
"'connections'. ");
case ErrorCode::MOORING_FILE_UNKNOWN_CONNECTION_TYPE:
return ("Found unknown connection 'type'. Currently supported "
"types are 'anchor' and 'fairlead'.");
case ErrorCode::MOORING_FILE_MISSED_REPEATED_CONNECTION_ID:
return ("Found connection missed or repeatedly defined. Check "
"connection 'id' and the 'number' of 'connections'.");
// Cable error.
case ErrorCode::MOORING_FILE_BAD_CABLES_NUM:
return "Unacceptable 'number' of 'cables': NaN or nonpositive.";
case ErrorCode::MOORING_FILE_NO_CABLE_DEF:
return "Failed to find at least one cable.";
case ErrorCode::MOORING_FILE_INCOMPLETE_CABLE_DEF:
return ("Incomplete cable definition. Required are: 'id', "
"'initialstatefile (can be empty)', 'icurrent', 'isolver', "
"'segmentlength', 'istructproperty', "
"'ihydroproperty', 'iseabedproperty', 'iconnection' and "
"'saveflag'.");
case ErrorCode::MOORING_FILE_NAN_CABLE_DEF:
return ("NaN found in cable 'id', 'icurrent', 'isolver', "
"'nodenumber', or 'saveflag'.");
case ErrorCode::MOORING_FILE_OUTOFRANGE_CABLE_ID:
return "Found cable 'id' out of range of the 'number' of 'cables'.";
case ErrorCode::MOORING_FILE_NAN_CABLE_LENGTH:
return "NaN found in cable 'segmentlength'.";
case ErrorCode::MOORING_FILE_NAN_CABLE_STRUCTPROP_INDEX:
return "NaN found in cable 'istructproperty'.";
case ErrorCode::MOORING_FILE_NAN_CABLE_HYDROPROP_INDEX:
return "NaN found in cable 'ihydroproperty'.";
case ErrorCode::MOORING_FILE_NAN_CABLE_SEABEDPROP_INDEX:
return "NaN found in cable 'iseabedproperty'.";
case ErrorCode::MOORING_FILE_NAN_CABLE_CONNECTION_INDEX:
return "NaN found in cable 'iconnection'.";
case ErrorCode::MOORING_FILE_BAD_CABLE_CONNECTION_INDEX:
return "Failed to find two connection indexes for a cable.";
case ErrorCode::MOORING_FILE_MISSED_REPEATED_CABLE_ID:
return ("Found cable missed or repeatedly defined. Check cable 'id'"
" and the 'number' of cables.");
// Structural property error.
case ErrorCode::MOORING_FILE_BAD_STRUCTPROPS_NUM:
return "Unacceptable number of 'structuralproperties'.";
case ErrorCode::MOORING_FILE_NO_STRUCTPROP:
return "Failed to find at least one 'structuralproperty'.";
case ErrorCode::MOORING_FILE_INCOMPLETE_STRUCTPROP_DEF:
return ("Incomplete 'structuralproperty' data. Required are: 'id', "
"'diameter', 'unitlengthmass', 'unitlengthweight', "
"'bendingstiffness', 'torsionalstiffness', and "
"'dampingcoefficient'");
case ErrorCode::MOORING_FILE_NAN_STRUCTPROP:
return "NaN found in 'structuralproperty'.";
case ErrorCode::MOORING_FILE_OUTOFRANGE_STRUCTPROP_ID:
return ("Found 'structuralproperty' out of range of the number of "
"'structuralproperties'.");
case ErrorCode::MOORING_FILE_MISSED_REPEATED_STRUCTPROP_ID:
return ("Found 'structuralproperty' missed or repeatedly defined. "
"Check 'structuralproperty' 'id' and the 'number' of "
"'structuralproperties'.");
// Hydro-property error.
case ErrorCode::MOORING_FILE_BAD_HYDROPROPS_NUM:
return ("Unacceptable number of 'hydroperoperties': "
"NaN or nonpositive.");
case ErrorCode::MOORING_FILE_NO_HYDROPROP:
return "Unable to find at least one 'hydroproperty'.";
case ErrorCode::MOORING_FILE_INCOMPLETE_HYDROPROP_DEF:
return ("Incomplete hydroproperty data. Required are 'id', "
"'addedmasscoefficient' and 'dragcoefficient'");
case ErrorCode::MOORING_FILE_NAN_HYDROPROP:
return "NaN found in 'hydroproperty' 'id'.";
case ErrorCode::MOORING_FILE_OUTOFRANGE_HYDROPROP_ID:
return "Found 'hydroproperty' 'id' out of range.";
case ErrorCode::MOORING_FIEL_INCOMPLETE_HYDRO_COEFFICIENTS:
return ("Incomplete addedmasscoefficient or dragcoefficient data."
"Required are 'tangential', 'normal' and 'binormal' "
"components");
case ErrorCode::MOORING_FIEL_NAN_HYDRO_COEFFICIENTS:
return ("NaN found in 'addedmasscoefficient' or 'dragcoefficient' "
"data");
case ErrorCode::MOORING_FILE_MISSED_REPEATED_HYDROPROP_ID:
return ("Found 'hydroproperty' missed or repeatedly defined. "
"Check 'hydroproperty' 'id' and the 'number' of "
"'hydroproperties'.");
// Seabed property error.
case ErrorCode::MOORING_FILE_BAD_SEABEDPROPS_NUM:
return "Unacceptable number of 'seabedproperties'.";
case ErrorCode::MOORING_FILE_NO_SEABEDPROP:
return "Unable to find at least one 'seabedproperty' definition.";
case ErrorCode::MOORING_FILE_INCOMPLETE_SEABEDPROP_DEF:
return ("Incomplete seabedproperty data. Required are 'id', "
"'dampingcoefficient' and 'stiffnesscoefficient'.");
case ErrorCode::MOORING_FILE_NAN_SEABEDPROP:
return ("NaN found in 'seabedproperty' data.");
case ErrorCode::MOORING_FILE_OUTOFRANGE_SEABEDPROP_ID:
return ("Seabedproperty 'id' is out of range!\n");
case ErrorCode::MOORING_FILE_MISSED_REPEATED_SEABEDPROP_ID:
return ("Found 'seabedproperty' missed or repeatedly defined. "
"Check 'seabedproperty' 'id' and the number of "
"'seabedproperties'.");
// Current error.
case ErrorCode::MOORING_FILE_BAD_CURRENTS_NUM:
return "Unacceptable of number of 'currents'.";
case ErrorCode::MOORING_FILE_NO_CURRENT:
return "Unable find at least one current definition";
case ErrorCode::MOORING_FILE_INCOMPLETE_CURRENT_DEF:
return ("Incomplete current data. Required are 'id', "
"'polyorder' and 'profilefile'.");
case ErrorCode::MOORING_FILE_NAN_CURRENT:
return "NaN found in current 'id' or 'polyorder'.";
case ErrorCode::MOORING_FILE_OUTOFRANGE_CURRENT_ID:
return "Found out of range current 'id'.";
case ErrorCode::MOORING_FILE_MISSED_REPEATED_CURRENT_ID:
return ("Found 'current' missed or repeatedly defined. "
"Check 'current' 'id' and the number of 'currents'.");
case ErrorCode::MOORING_FILE_BAD_CURRENT_DATA:
return ("Unacceptable current profile data or NaN found. Check "
"current data file. Current data file should have one line "
"of header and data matrix with 6 columns containing "
"three coordinates in global reference system and three "
"current velocities.");
// Solver error.
case ErrorCode::MOORING_FILE_BAD_SOLVERS_NUM:
return "Unacceptable number of 'solvers'.";
case ErrorCode::MOORING_FILE_NO_SOLVER:
return "Unable to find at least one 'solver' definition.";
case ErrorCode::MOORING_FILE_INCOMPLETE_SOLVER_DEF:
return ("Incomplete solver definition. Required are 'id', "
"'iterationnumberlimit', 'convergencetolerance', "
"'initialrelaxationfactor', 'relaxationincreasefactor', "
"'relaxationdecreasefactor' and 'lambdainfinity'");
case ErrorCode::MOORING_FILE_NAN_SOLVER:
return "NaN found in 'solver' definition.";
case ErrorCode::MOORING_FILE_OUTOFRANGE_SOLVER_ID:
return ("Found solver 'id' out of range of the 'number' of "
"'solvers'.");
case ErrorCode::MOORING_FILE_MISSED_REPEATED_SOLVER_ID:
return ("Found 'solver' missed or repeatedly defined. "
"Check 'solver' 'id' and the number of 'solvers'.");
// Setting error.
case ErrorCode::SETTING_FILE_NONEXISTENT:
return "Failed to find Setting.xml file.";
case ErrorCode::SETTING_FILE_ERROR_PARSE:
return "Found xml parse error in Setting.xml.";
case ErrorCode::SETTING_FILE_NO_SETTING_NODE:
return "Root node of Setting.xml must be setting.";
case ErrorCode::SETTING_FILE_NO_SIMULATION_TYPE:
return "Failed to find 'simulationtype' definition in Setting.xml.";
case ErrorCode::SETTING_FILE_UNKNOWN_SIMULATION_TYPE:
return ("Found unknown 'simulationtype'. Currently supported are "
"'shooting', 'relaxation', and 'forcedmotion'.");
case ErrorCode::SETTING_FILE_NO_MOORING_FILE_DEF:
return "Failed to find 'mooringinputfile' definition in Setting.xml.";
case ErrorCode::SETTING_FILE_NO_SHOOTING_PARA:
return "Unable to find 'shooting' parameter definition.";
case ErrorCode::SETTING_FILE_INCOMPLETE_SHOOTING_PARA:
return ("Incomplete parameters for shooting. Required are "
"'fairleadpositiontolerance', "
"'fairleadforcerelaxationfactor', "
"'fairleadpositioniterationlimit', "
"'platformpositioniterationlimit', "
"'platformdisplacementtolerance', "
"'platformdisplacementrelaxationfactor', "
"'cableoutofplanestiffness', "
"'platformhydrostaticstiffness' and "
"'platformotherload'.");
case ErrorCode::SETTING_FILE_NAN_SHOOTING_PARA:
return ("NaN found in shooting parameters: "
"'fairleadpositiontolerance', "
"'fairleadforcerelaxationfactor', "
"'fairleadpositioniterationlimit', "
"'platformpositioniterationlimit', "
"'platformdisplacementtolerance' or "
"'platformdisplacementrelaxationfactor'.");
case ErrorCode::SETTING_FILE_INCOMPLETE_SHOOTING_FAIRLEAD_TOLERANCE:
return ("Incomplete definition of 'shooting' parameter "
"fairleadpositiontolerance.");
case ErrorCode::SETTING_FILE_NAN_SHOOTING_FAIRLEAD_TOLERANCE:
return ("NaN found in 'shooting' parameter "
"'fairleadpositiontolerance'.");
case ErrorCode::SETTING_FILE_BAD_SHOOTING_STIFFNESS:
return ("NaN or not 36 elements found in "
"'platformhydrostaticstiffness' for "
"'shooting'.");
case ErrorCode::SETTING_FILE_BAD_SHOOTING_LOAD:
return ("NaN or not 6 elements found in 'platformotherload' for "
"'shooting'.");
case ErrorCode::SETTING_FILE_NO_RELAXATION_PARA:
return "Unable to find 'relaxation' parameter definition.";
case ErrorCode::SETTING_FILE_INCOMPLETE_RELAXATION:
return ("Incomplete parameters for 'relaxation'. Required are "
"'platformvelocitytolerance', 'cablevelocitytolerance', "
"'stoptime', 'timestep', 'platformmass', "
"'platformdamping', 'platformhydrostaticstiffness' and "
"'platformotherload'.");
case ErrorCode::SETTING_FILE_NAN_RELAXATION_PARA:
return ("NaN found in 'relaxation' parameters: "
"'platformvelocitytolerance', 'cablevelocitytolerance'"
"'stoptime', or 'timestep'.");
case ErrorCode::SETTING_FILE_BAD_RELAXATION_MASS:
return ("NaN or not 36 elements found in "
"'platformmass' for 'relaxtion'.");
case ErrorCode::SETTING_FILE_BAD_RELAXATION_DAMPING:
return ("NaN or not 36 elements found in "
"'platformdamping' for 'relaxtion'.");
case ErrorCode::SETTING_FILE_BAD_RELAXATION_STIFFNESS:
return ("NaN or not 36 elements found in "
"'platformhydrostaticstiffness' for 'relaxtion'.");
case ErrorCode::SETTING_FILE_BAD_RELAXATION_LOAD:
return ("NaN or not 6 elements found in 'platformotherload' for "
"'relaxtion'.");
case ErrorCode::SETTING_FILE_NO_MOTION:
return "Unable to find 'forcedmotion' node in Setting.xml.";
case ErrorCode::SETTING_FILE_NO_TIME_HISTORY:
return "Unable to find 'timehistory' file definition.";
// Validation of mooring input data.
case ErrorCode::MOORING_INVALID_CONSTANT:
return "Found nonpositive constants.";
case ErrorCode::MOORING_INVALID_CABLE_CURRENT_INDEX:
return "Cable 'icurrent' is out of range.";
case ErrorCode::MOORING_INVALID_CABLE_SOLVER_INDEX:
return "Cable 'isolver' is out of range.";
case ErrorCode::MOORING_INVALID_CABLE_NODE_NUM:
return "Cable 'nodenumber' is negative.";
case ErrorCode::MOORING_INVALID_CABLE_PROP_ASSOCIATION:
return ("Failed to find at least one group of cable length and "
"associated property or found inconsistent cable segments "
"and properties definitions.");
case ErrorCode::MOORING_INVALID_CABLE_CONNECTION_INDEX:
return ("Two same ends found for a cable or cable connection index "
"out of range. In addtion, currently, the first connection "
"must be an 'anchor' and the second must be a 'fairlead'.");
case ErrorCode::MOORING_INVALID_CABLE_SEGMENT_LENGTH:
return "Cable segmentlength should be positive.";
case ErrorCode::MOORING_INVALID_STRUCT_PROP:
return ("Positive values required for diameter, unitlengthmass, "
" unitlengthweight, and axialstiffness.");
case ErrorCode::MOORING_INVALID_HYDRO_COEFFICIENT:
return ("Nonnegative values required for bending stiffness, "
"torsional stiffness and damping coefficient.");
case ErrorCode::MOORING_INVALID_SEABED:
return ("Nonnegative values required hydrodynamic coefficients.");
case ErrorCode::MOORING_INVALID_CURRENT:
return ("Invalid current data. Required are that polyorder is "
"nonnegative and less then the number of profile data "
"points and at least one data point provided. In addition, "
"the Z coordinate should be negative and decreasing "
"monotonically");
case ErrorCode::MOORING_INVALID_SOLVER:
return ("Invalid solver found: iterationnumberlimit, "
"convergencetolerance, "
"initialrelaxationfactor, relaxationincreasefactor, "
"and relaxationdecreasefactor should be positive numbers; "
"relaxationincreasefactor and relaxationincreasefactor "
"should be no less than 1; lambdainfinity should not be equal "
"to 1 and often between -1 and 0.");
case ErrorCode::MOORING_INVALID_CABLE_STATE:
return ("Initial cable state matrix read successfully, however, "
"the cable coordinate is not valid. The cable coordinate "
"should be positive, begining with zero, increasing "
"monotonically and terminating with full cable length "
"consistent with the sum of segmentlength and at "
"least two nodes are required. Check the first column of "
"initial state file and the 'segmentlength'.");
case ErrorCode::SHOOTING_BAD_PARA:
return ("Found nonpositive tolerance or relaxation factor or "
"negative iteration limit in shooting control.");
case ErrorCode::RELAXATION_BAD_PARA:
return ("Found nonpositive tolerance, steptime, or timestep.");
case ErrorCode::CURRENT_FILE_NONEXISTENT:
return "Unable to find current profile data file.";
case ErrorCode::CURRENT_FILE_BAD_DATA:
return ("Found NaN or wrong column number (expect 6) of current "
"profile data.");
case ErrorCode::MOTION_FILE_NONEXISTENT:
return "Unable to find forcedmotion time history data.";
case ErrorCode::MOTION_FILE_BAD_DATA:
return ("Found NaN or wrong column number (expect 7) of forced "
"motion time history.");
case ErrorCode::FORCED_MOTION_BAD_TIME:
return "Found negative or decreasing time in the forced velocity.";
case ErrorCode::TIME_STEP_TOO_SMALL:
return "Time step too small, no need to update.";
case ErrorCode::SINGULAR_MATRIX_SOLVER:
return ("Singularity found in solving the cable equation. "
"Check input.");
case ErrorCode::NAN_CABLE_SOLUTION:
return ("NaN found in cable state solution.");
}
}
} // End of namespace moor.
| 45.8 | 83 | 0.623078 |
76ae2c05042d464bd907ab21b1c03582f2c8b85a | 2,001 | cpp | C++ | Sources/Internal/Platform/TemplateAndroid/JniExtensions.cpp | reven86/dava.engine | ca47540c8694668f79774669b67d874a30188c20 | [
"BSD-3-Clause"
] | 5 | 2020-02-11T12:04:17.000Z | 2022-01-30T10:18:29.000Z | Sources/Internal/Platform/TemplateAndroid/JniExtensions.cpp | reven86/dava.engine | ca47540c8694668f79774669b67d874a30188c20 | [
"BSD-3-Clause"
] | null | null | null | Sources/Internal/Platform/TemplateAndroid/JniExtensions.cpp | reven86/dava.engine | ca47540c8694668f79774669b67d874a30188c20 | [
"BSD-3-Clause"
] | 4 | 2019-11-28T19:24:34.000Z | 2021-08-24T19:12:50.000Z | #include "JniExtensions.h"
#if !defined(__DAVAENGINE_COREV2__)
#if defined(__DAVAENGINE_ANDROID__)
#include "Platform/TemplateAndroid/CorePlatformAndroid.h"
#include "UI/UIControlSystem.h"
#include "Math/Rect.h"
#include "Logger/Logger.h"
#include "Debug/DVAssert.h"
namespace DAVA
{
JniExtension::JniExtension()
{
CorePlatformAndroid* core = static_cast<CorePlatformAndroid*>(Core::Instance());
AndroidSystemDelegate* delegate = core->GetAndroidSystemDelegate();
vm = delegate->GetVM();
}
JniExtension::~JniExtension()
{
}
void JniExtension::SetJavaClass(JNIEnv* env, const char* className, jclass* gJavaClass, const char** gJavaClassName)
{
*gJavaClass = static_cast<jclass>(env->NewGlobalRef(env->FindClass(className)));
if (gJavaClassName)
*gJavaClassName = className;
}
jmethodID JniExtension::GetMethodID(const char* methodName, const char* paramCode) const
{
jclass javaClass = GetJavaClass();
DVASSERT(javaClass && "Not initialized Java class");
if (!javaClass)
return 0;
jmethodID mid = GetEnvironment()->GetStaticMethodID(javaClass, methodName, paramCode);
if (!mid)
{
Logger::Error("get method id of %s.%s%s error ", GetJavaClassName(), methodName, paramCode);
}
return mid;
}
JNIEnv* JniExtension::GetEnvironment() const
{
// right way to take JNIEnv
// JNIEnv is valid only for the thread where it was gotten.
// we shouldn't store JNIEnv.
JNIEnv* env;
if (JNI_EDETACHED == vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6))
{
Logger::Error("runtime_error(Thread is not attached to JNI)");
}
return env;
};
Rect JniExtension::V2P(const Rect& srcRect) const
{
Vector2 offset = UIControlSystem::Instance()->vcs->GetPhysicalDrawOffset();
Rect rect = UIControlSystem::Instance()->vcs->ConvertVirtualToPhysical(srcRect);
rect += offset;
return rect;
}
} //namespace DAVA
#endif // __DAVAENGINE_ANDROID__
#endif // __DAVAENGINE_COREV2__ | 26.328947 | 116 | 0.709645 |
76b1445040b47301c1d5ceb15e854fd7590c3876 | 574 | cpp | C++ | 3/3/35.cpp | Jamxscape/LearnCPlusPlus | 9770af743a2f6e9267421ff8fec93eb9d81c1f14 | [
"Apache-2.0"
] | null | null | null | 3/3/35.cpp | Jamxscape/LearnCPlusPlus | 9770af743a2f6e9267421ff8fec93eb9d81c1f14 | [
"Apache-2.0"
] | null | null | null | 3/3/35.cpp | Jamxscape/LearnCPlusPlus | 9770af743a2f6e9267421ff8fec93eb9d81c1f14 | [
"Apache-2.0"
] | null | null | null | //
// 35.cpp
// 3
//
// Created by 马元 on 2016/12/25.
// Copyright © 2016年 MaYuan. All rights reserved.
//大家提到LTC都佩服的不行,不过,如果竞赛只有这一个题目,我敢保证你和他绝对在一个水平线上你的任务是:计算方程x^2+y^2+z^2= num的一个正整数解。Input输入数据包含多个测试实例,每个实例占一行,仅仅包含一个小于等于10000的正整数num。Output对于每组测试数据,请按照x,y,z递增的顺序输出它的一个最小正整数解,每个实例的输出占一行,题目保证所有测试数据都有解。
#include <iostream>
using namespace std;
int main35()
{
int num,x,y,z;
cin>>num;
for(x=0;x<num;x++)
for(y=0;y<num;y++)
for(z=0;z<num;z++)
if(x*x+y*y+z*z==num)cout<<x<<" "<<y<<" "<<z<<endl;
cout<<endl;
return 0;
}
| 26.090909 | 196 | 0.627178 |
76b2c5fdc93414e954ec805be777754828ea48ef | 739 | cpp | C++ | src/VK/SemaphoreWrapper.cpp | razerx100/Terra | a30738149cb07325283c2da9ac7972f079cb4dbc | [
"MIT"
] | null | null | null | src/VK/SemaphoreWrapper.cpp | razerx100/Terra | a30738149cb07325283c2da9ac7972f079cb4dbc | [
"MIT"
] | null | null | null | src/VK/SemaphoreWrapper.cpp | razerx100/Terra | a30738149cb07325283c2da9ac7972f079cb4dbc | [
"MIT"
] | null | null | null | #include <SemaphoreWrapper.hpp>
#include <VKThrowMacros.hpp>
SemaphoreWrapper::SemaphoreWrapper(VkDevice device, size_t count)
: m_deviceRef(device), m_semaphores(count) {
VkSemaphoreCreateInfo semaphoreInfo = {};
semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
VkResult result;
for (size_t index = 0u; index < count; ++index)
VK_THROW_FAILED(result,
vkCreateSemaphore(device, &semaphoreInfo, nullptr, &m_semaphores[index])
);
}
SemaphoreWrapper::~SemaphoreWrapper() noexcept {
for (const auto semaphore : m_semaphores)
vkDestroySemaphore(m_deviceRef, semaphore, nullptr);
}
VkSemaphore SemaphoreWrapper::GetSemaphore(size_t index) const noexcept {
return m_semaphores[index];
}
| 29.56 | 76 | 0.759134 |
76b2d918729e127a4b073b29b126d91cd5f6e0d2 | 1,049 | cpp | C++ | Chapter_3/p3_16.cpp | aalogancheney/CPlusPlus_For_Everyone | 251247cf1f1ca169826179379831192fadfaa5f9 | [
"MIT"
] | null | null | null | Chapter_3/p3_16.cpp | aalogancheney/CPlusPlus_For_Everyone | 251247cf1f1ca169826179379831192fadfaa5f9 | [
"MIT"
] | null | null | null | Chapter_3/p3_16.cpp | aalogancheney/CPlusPlus_For_Everyone | 251247cf1f1ca169826179379831192fadfaa5f9 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
void ClearInputDisplayMessage(const string& message)
{
cout << message << endl;
cin.clear();
string ignore;
getline(cin, ignore);
}
int main(int argc, char *argv[])
{
cout << "Enter the employees name: ";
string name;
getline(cin, name);
while(cin.fail())
{
ClearInputDisplayMessage("Please enter a valid name: ");
getline(cin, name);
}
cout << "Enter the employees hourly wage: ";
double wage;
cin >> wage;
while(cin.fail())
{
ClearInputDisplayMessage("Please enter a valid wage: ");
cin >> wage;
}
cout << "How many hours did " << name << " work last week? ";
double hours;
cin >> hours;
while(cin.fail())
{
ClearInputDisplayMessage("Please enter a valid number of hours: ");
cin >> hours;
}
double totalPay = 0;
if(hours > 40)
{
totalPay += wage * 40 + wage * 1.5 * (hours - 40);
}
else
{
totalPay += wage * hours;
}
cout << name << "'s Paycheck: " << totalPay << endl;
return 0;
} | 16.919355 | 69 | 0.632984 |
76b4b622cd484e8969d77bfa2d4b292a7158258f | 2,880 | hpp | C++ | src/io/FileWriterInterface.hpp | spraetor/amdis2 | 53c45c81a65752a8fafbb54f9ae6724a86639dcd | [
"MIT"
] | 2 | 2018-07-04T16:44:04.000Z | 2021-01-03T07:26:27.000Z | src/io/FileWriterInterface.hpp | spraetor/amdis2 | 53c45c81a65752a8fafbb54f9ae6724a86639dcd | [
"MIT"
] | null | null | null | src/io/FileWriterInterface.hpp | spraetor/amdis2 | 53c45c81a65752a8fafbb54f9ae6724a86639dcd | [
"MIT"
] | null | null | null | /** \defgroup Output Output module
* @{ <img src="output.png"> @}
*/
#pragma once
#include <vector>
#include <string>
#include "AMDiS_fwd.hpp"
#include "Mesh.hpp"
namespace AMDiS
{
class FileWriterInterface
{
public:
FileWriterInterface()
: filename(""),
appendIndex(0),
indexLength(5),
indexDecimals(3),
createSubDir(-1),
tsModulo(1),
timeModulo(-1.0),
lastWriteTime(-1.0),
traverseLevel(-1),
traverseFlag(Mesh::CALL_LEAF_EL),
writeElement(NULL)
{}
virtual ~FileWriterInterface() {}
/** \brief
* Interface. Must be overridden in subclasses.
* \param time time index of solution std::vector.
* \param force enforces the output operation for the last timestep.
*/
virtual void writeFiles(AdaptInfo& adaptInfo, bool force,
int level = -1,
Flag traverseFlag = Mesh::CALL_LEAF_EL,
bool (*writeElem)(ElInfo*) = NULL) = 0;
/// Test whether timestep should be written
virtual bool doWriteTimestep(AdaptInfo& adaptInfo, bool force);
std::string getFilename()
{
return filename;
}
void setFilename(std::string n)
{
filename = n;
}
void setWriteModulo(int tsModulo_ = 1, double timeModulo_ = -1.0)
{
tsModulo = tsModulo_;
timeModulo = timeModulo_;
}
void setTraverseProperties(int level,
Flag flag,
bool (*writeElem)(ElInfo*))
{
traverseLevel = level;
traverseFlag |= flag;
writeElement = writeElem;
}
protected:
/// Reads all file writer dependend parameters from the init file.
virtual void readParameters(std::string name);
/// create a filename that includes the timestep and possibly a processor ID in parallel mode
#ifdef HAVE_PARALLEL_DOMAIN_AMDIS
void getFilename(AdaptInfo& adaptInfo, std::string& fn, std::string& paraFilename, std::string& postfix);
#else
void getFilename(AdaptInfo& adaptInfo, std::string& fn);
#endif
/// Used filename prefix.
std::string filename;
/// 0: Don't append time index to filename prefix.
/// 1: Append time index to filename prefix.
int appendIndex;
/// Total length of appended time index.
int indexLength;
/// Number of decimals in time index.
int indexDecimals;
/// create a subdirectory where to put the files
int createSubDir;
/// Timestep modulo: write only every tsModulo-th timestep!
int tsModulo;
/// Time modulo: write at first iteration after lastWriteTime + timeModulo
double timeModulo;
double lastWriteTime;
/// Traverse properties
int traverseLevel;
Flag traverseFlag;
bool (*writeElement)(ElInfo*);
};
} // end namespace AMDiS
| 25.263158 | 109 | 0.621875 |
76b4efc373f16d2ffbb1f048bf2b579d8d95c96f | 2,746 | cpp | C++ | Contrib-Intel/RSD-PSME-RMM/common/agent-framework/src/module/constants/rmm.cpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 5 | 2019-11-11T07:57:26.000Z | 2022-03-28T08:26:53.000Z | Contrib-Intel/RSD-PSME-RMM/common/agent-framework/src/module/constants/rmm.cpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 3 | 2019-09-05T21:47:07.000Z | 2019-09-17T18:10:45.000Z | Contrib-Intel/RSD-PSME-RMM/common/agent-framework/src/module/constants/rmm.cpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 11 | 2019-07-20T00:16:32.000Z | 2022-01-11T14:17:48.000Z | /*!
* @copyright
* Copyright (c) 2017-2019 Intel Corporation
*
* @copyright
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* @copyright
* http://www.apache.org/licenses/LICENSE-2.0
*
* @copyright
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* @file rmm.cpp
* @brief Contains RMM constants used all over the model
* */
#include "agent-framework/module/constants/rmm.hpp"
namespace agent_framework {
namespace model {
namespace literals {
constexpr const char Fan::STATUS[];
constexpr const char Fan::CURRENT_SPEED[];
constexpr const char Fan::FRU_INFO[];
constexpr const char Fan::OEM[];
constexpr const char Fan::FAN[];
constexpr const char Fan::PHYSICAL_CONTEXT[];
constexpr const char Fan::CURRENT_SPEED_UNITS[];
constexpr const char ThermalZone::ZONE[];
constexpr const char ThermalZone::STATUS[];
constexpr const char ThermalZone::VOLUMETRIC_AIRFLOW_CFM[];
constexpr const char ThermalZone::DESIRED_SPEED_PWM[];
constexpr const char ThermalZone::COLLECTIONS[];
constexpr const char ThermalZone::OEM[];
constexpr const char Psu::PSU[];
constexpr const char Psu::STATUS[];
constexpr const char Psu::FRU_INFO[];
constexpr const char Psu::OEM[];
constexpr const char Psu::POWER_SUPPLY_TYPE[];
constexpr const char Psu::LINE_INPUT_VOLTAGE_TYPE[];
constexpr const char Psu::LINE_INPUT_VOLTAGE_VOLTS[];
constexpr const char Psu::FIRMWARE_VERSION[];
constexpr const char Psu::LAST_POWER_OUTPUT_WATTS[];
constexpr const char Psu::POWER_CAPACITY_WATTS[];
constexpr const char Psu::INDICATOR_LED[];
constexpr const char Psu::REQUESTED_STATE[];
constexpr const char PowerZone::ZONE[];
constexpr const char PowerZone::STATUS[];
constexpr const char PowerZone::POWER_ALLOCATED[];
constexpr const char PowerZone::POWER_REQUESTED[];
constexpr const char PowerZone::POWER_AVAILABLE[];
constexpr const char PowerZone::POWER_CONSUMED[];
constexpr const char PowerZone::POWER_CAPACITY[];
constexpr const char PowerZone::COLLECTIONS[];
constexpr const char PowerZone::OEM[];
constexpr const char ChassisSensor::SENSOR[];
constexpr const char ChassisSensor::STATUS[];
constexpr const char ChassisSensor::READING[];
constexpr const char ChassisSensor::PHYSICAL_CONTEXT[];
constexpr const char ChassisSensor::READING_UNITS[];
constexpr const char ChassisSensor::SENSOR_NUMBER[];
constexpr const char ChassisSensor::OEM[];
}
}
}
| 34.325 | 75 | 0.776766 |
76b777a4b45c88e0548d0939d5c537fbebce4b59 | 269 | cpp | C++ | src/ComponentSet.cpp | Konijnendijk/Meadows-ECS | 5ee2619481086edaabcfa235e2455686cb854901 | [
"BSL-1.0",
"MIT"
] | 1 | 2017-11-22T11:39:25.000Z | 2017-11-22T11:39:25.000Z | src/ComponentSet.cpp | Konijnendijk/Meadows-ECS | 5ee2619481086edaabcfa235e2455686cb854901 | [
"BSL-1.0",
"MIT"
] | null | null | null | src/ComponentSet.cpp | Konijnendijk/Meadows-ECS | 5ee2619481086edaabcfa235e2455686cb854901 | [
"BSL-1.0",
"MIT"
] | null | null | null |
#include "ComponentSet.h"
using namespace Meadows;
ComponentSet::ComponentSet() : componentBitSet(ComponentRegistry::getNumRegisteredComponents()) {
}
ComponentSet::~ComponentSet() {
for (Component* component : components) {
delete(component);
}
}
| 17.933333 | 97 | 0.717472 |
76bc393e21a080577c2bc57cc5ae93e4b500e791 | 535 | cpp | C++ | spoj/HOTELS.cpp | amarlearning/CodeForces | 6625d3be21cb6a78b88c7521860d1da263e77121 | [
"Unlicense"
] | 3 | 2016-02-20T12:14:51.000Z | 2016-03-18T20:09:36.000Z | spoj/HOTELS.cpp | amarlearning/Codeforces | 6625d3be21cb6a78b88c7521860d1da263e77121 | [
"Unlicense"
] | null | null | null | spoj/HOTELS.cpp | amarlearning/Codeforces | 6625d3be21cb6a78b88c7521860d1da263e77121 | [
"Unlicense"
] | 2 | 2018-07-26T21:00:42.000Z | 2019-11-30T19:33:57.000Z | /*
Author : Amar Prakash Pandey
contact : http://amarpandey.me
*/
#include <bits/stdc++.h>
#define ll long long
#define MAX 1000005
using namespace std;
ll int A[MAX];
int main(int argc, char const *argv[]) {
ll int N, M, sum = 0;
scanf("%lld %lld", &N, &M);
for (ll int i = 0; i < N; ++i) {
scanf("%lld", &A[i]);
}
ll int l = 0, r = 0, ans = 0;
while(l < N) {
while(r < N && (sum + A[r]) <= M) {
sum += A[r];
r++;
}
ans = max(ans, sum);
sum -= A[l];
l++;
}
printf("%lld\n", ans);
return 0;
}
| 12.738095 | 40 | 0.506542 |
76be93f1975379ff4d2dbd50e15a7220270d08af | 304 | cpp | C++ | cc/tests/test1/submit.cpp | DragoonKiller/bruteforces | e6283b18c692a3726e7e52a6a60e64ddc903da91 | [
"MIT"
] | null | null | null | cc/tests/test1/submit.cpp | DragoonKiller/bruteforces | e6283b18c692a3726e7e52a6a60e64ddc903da91 | [
"MIT"
] | null | null | null | cc/tests/test1/submit.cpp | DragoonKiller/bruteforces | e6283b18c692a3726e7e52a6a60e64ddc903da91 | [
"MIT"
] | null | null | null |
static void this_is_a_function_in_brute_gen_in_all_hpp() { }
static void this_is_a_function_in_bits_hpp() { }
#include <bits/stdc++.h>
static void this_is_another_function_in_bits_hpp() { }
#include <chrono>
static void this_is_a_function_outof_brute_gen_in_all_hpp() { }
int main()
{
return 0;
} | 21.714286 | 63 | 0.776316 |
76c2f4df9cb8a71855172fdb7ebc46cab2b57915 | 8,603 | cpp | C++ | src/ui/SciControl/CScintillaController.cpp | masmullin2000/codeassistor | 82389e16dda7be522ee5370aae441724da2e9cf2 | [
"BSD-4-Clause"
] | null | null | null | src/ui/SciControl/CScintillaController.cpp | masmullin2000/codeassistor | 82389e16dda7be522ee5370aae441724da2e9cf2 | [
"BSD-4-Clause"
] | null | null | null | src/ui/SciControl/CScintillaController.cpp | masmullin2000/codeassistor | 82389e16dda7be522ee5370aae441724da2e9cf2 | [
"BSD-4-Clause"
] | null | null | null | /** title info */
#include "CScintillaController.h"
#include "ScintillaSend.h"
#include "common_defs.h"
/* colourizing defines */
#if PLATFORM == MAC
#define DEF_KEYW_1 "#FF627E"
#define DEF_KEYW_2 "#FF00FF"
#define DEF_NUM "#0000FF"
#define DEF_OP "#0000FF"
#define DEF_STRING "#EE9A4D"
#define DEF_STRING_EOL "#D4A9EE"
#define DEF_CHAR "#0022FF"
#define DEF_PREPRO "#C35617"
#define DEF_IDENT "#000000"
#define DEF_COMMENT "#777777"
#define DEF_COMMENT_2 "#444444"
#define DEF_MARGIN "#DADADA"
#define DEF_LINE_NO "#CFCFCF"
#else
#define DEF_KEYW_1 "#FF627E"
#define DEF_KEYW_2 "#FF00FF"
#define DEF_NUM "#AAAAFF"
#define DEF_OP "#DDAADD"
#define DEF_STRING "#EE9A4D"
#define DEF_STRING_EOL "#D4A9EE"
#define DEF_CHAR "#0022FF"
#define DEF_PREPRO "#C35617"
#define DEF_IDENT "#999988"
#define DEF_COMMENT "#777777"
#define DEF_COMMENT_2 "#444444"
#define DEF_MARGIN "#323232"
#define DEF_LINE_NO "#434343"
#endif
#define TAB_WIDTH 2
CScintillaController* CScintillaController::_me = NULL;
/* The CScintillaController is a singleton */
ScintillaController*
CScintillaController::getInstance()
{
if( !_me ) _me = new CScintillaController();
return _me;
}
void
CScintillaController::setDefaultEditor
(
void* sci,
fileType_t subtype
)
{
ScintillaSend* send = ScintillaSend::getInstance();
const char* keywordsToUse = NULL;
const char* secondaryKeywordsToUse = CStdLibrary;
ScintillaController::setDefaultEditor(sci,subtype);
#if PLATFORM != MAC
send->set(sci,SCI_STYLESETBACK,STYLE_DEFAULT,0);
send->set(sci,SCI_STYLESETFORE,STYLE_DEFAULT,0);
send->set(sci,SCI_SETCARETFORE,255,0);
send->set(sci,SCI_STYLECLEARALL,0,0);
#endif
// CPP is used, this is also good for ObjC/Java/C
send->set(sci,SCI_SETLEXER,SCLEX_CPP,0);
send->set(sci,SCI_SETSTYLEBITS,send->get(sci,SCI_GETSTYLEBITSNEEDED),0);
// tabs are replaced with spaces, tabs are 2 spaces wide
send->set(sci,SCI_SETUSETABS,0,0);
send->set(sci,SCI_SETTABWIDTH,TAB_WIDTH,0);
switch( subtype )
{
case CFILE:
keywordsToUse = CKeywords;
break;
case CPPFILE:
keywordsToUse = CppKeywords;
break;
case OBJCFILE:
keywordsToUse = ObjCKeywords;
break;
case OBJCPPFILE:
keywordsToUse = ObjCppKeywords;
break;
case HDFILE:
keywordsToUse = HKeywords;
break;
case JFILE:
keywordsToUse = JKeywords;
secondaryKeywordsToUse = JClasses;
break;
default:
keywordsToUse = "error";
}
send->set(sci,SCI_SETKEYWORDS,0,(void*)keywordsToUse);
send->set(sci,SCI_SETKEYWORDS,1,(void*)secondaryKeywordsToUse);
for( int i = 0; i <= SCE_C_USERLITERAL; i++ )
send->set(sci,SCI_STYLESETFORE,i,"#FFFFFF",true);
send->set(sci,SCI_SETSELFORE,true,255|255<<8|255<<16);
send->set(sci,SCI_SETSELBACK,true,64|64<<8|64<<16);
// set the font for strings (ie "this is a string" ) as itali
send->set(sci,SCI_STYLESETFONT,SCE_C_STRING,ITALIC_STRING);
send->set(sci,SCI_STYLESETITALIC,SCE_C_STRING,1);
send->set(sci,SCI_STYLESETBOLD,SCE_C_STRING,1);
send->set(sci,SCI_STYLESETSIZE,SCE_C_STRING,INITIAL_TEXT_SIZE);
// colourizing
// keywords
send->set(sci,SCI_STYLESETFORE,SCE_C_WORD,DEF_KEYW_1,true);
send->set(sci,SCI_STYLESETFORE,SCE_C_WORD|0x40,DEF_COMMENT,true);
// c standard lib
send->set(sci,SCI_STYLESETFORE,SCE_C_WORD2,DEF_KEYW_2,true);
send->set(sci,SCI_STYLESETFORE,SCE_C_WORD2|0x40,DEF_COMMENT,true);
// numbers
send->set(sci,SCI_STYLESETFORE,SCE_C_NUMBER,DEF_NUM,true);
send->set(sci,SCI_STYLESETFORE,SCE_C_NUMBER|0x40,DEF_COMMENT,true);
// operators/operations
send->set(sci,SCI_STYLESETFORE,SCE_C_OPERATOR,DEF_OP,true);
send->set(sci,SCI_STYLESETFORE,SCE_C_OPERATOR|0x40,DEF_COMMENT,true);
// strings
send->set(sci,SCI_STYLESETFORE,SCE_C_STRING,DEF_STRING,true);
send->set(sci,SCI_STYLESETFORE,SCE_C_STRING|0x40,DEF_COMMENT,true);
send->set(sci,SCI_STYLESETFORE,SCE_C_STRINGEOL,DEF_STRING_EOL,true);
send->set(sci,SCI_STYLESETFORE,SCE_C_STRINGEOL|0x40,DEF_COMMENT,true);
// 'a' characters
send->set(sci,SCI_STYLESETFORE,SCE_C_CHARACTER,DEF_CHAR,true);
send->set(sci,SCI_STYLESETFORE,SCE_C_CHARACTER|0x40,DEF_COMMENT,true);
// preprocessors #define/#include
send->set(sci,SCI_STYLESETFORE,SCE_C_PREPROCESSOR,DEF_PREPRO,true);
send->set(sci,SCI_STYLESETFORE,SCE_C_PREPROCESSOR|0x40,DEF_COMMENT,true);
// identifiers aka everything else
send->set(sci,SCI_STYLESETFORE,SCE_C_IDENTIFIER,DEF_IDENT,true);
send->set(sci,SCI_STYLESETFORE,SCE_C_IDENTIFIER|0x40,DEF_COMMENT,true);
// comments
send->set(sci,SCI_STYLESETFORE,SCE_C_COMMENT,DEF_COMMENT,true);
send->set(sci,SCI_STYLESETFORE,SCE_C_COMMENTLINE,DEF_COMMENT,true);
send->set(sci,SCI_STYLESETFORE,SCE_C_COMMENTDOC,DEF_COMMENT,true);
send->set(sci,SCI_STYLESETFORE,SCE_C_COMMENTLINEDOC,DEF_COMMENT,true);
send->set(sci,SCI_STYLESETFORE,SCE_C_COMMENTDOCKEYWORD,DEF_COMMENT_2,true);
send->set(sci,SCI_STYLESETFORE,SCE_C_COMMENTDOCKEYWORDERROR,DEF_COMMENT_2,true);
// send->set(sci,SCI_STYLESETFORE,SCE_C_GLOBALCLASS,"#FFFFFF",true);
// Line numbering
send->set(sci,SCI_STYLESETFORE,STYLE_LINENUMBER,DEF_IDENT,true);
send->set(sci,SCI_STYLESETBACK,STYLE_LINENUMBER,DEF_LINE_NO,true);
send->set(sci,SCI_SETMARGINTYPEN,0,SC_MARGIN_NUMBER);
send->set(sci,SCI_SETMARGINWIDTHN,0,48);
// long lines
send->set(sci,SCI_SETEDGEMODE,1,0);
send->set(sci,SCI_SETEDGECOLUMN,80,0);
// folding
send->set(sci,SCI_SETFOLDMARGINCOLOUR,true,DEF_MARGIN,true);
send->set(sci,SCI_SETFOLDMARGINHICOLOUR,true,DEF_MARGIN,true);
send->set(sci,SCI_SETMARGINWIDTHN,1,18);
send->set(sci,SCI_SETFOLDFLAGS,SC_FOLDFLAG_LINEAFTER_CONTRACTED,0);
send->set(sci,SCI_SETPROPERTY,"fold","1");
send->set(sci,SCI_SETPROPERTY,"fold.compact","0");
send->set(sci,SCI_SETPROPERTY,"fold.at.else","1");
send->set(sci,SCI_SETPROPERTY,"fold.preprocessor","1");
// these new preprocessor features aren't working out so well for me
send->set(sci,SCI_SETPROPERTY,"lexer.cpp.track.preprocessor","0");
send->set(sci,SCI_SETPROPERTY,"lexer.cpp.update.preprocessor","0");
send->set(sci,SCI_SETMARGINTYPEN, 1, SC_MARGIN_SYMBOL);
send->set(sci,SCI_SETMARGINMASKN, 1, SC_MASK_FOLDERS);
send->set(sci,SCI_MARKERDEFINE, SC_MARKNUM_FOLDEROPEN, SC_MARK_ARROWDOWN);
send->set(sci,SCI_MARKERDEFINE, SC_MARKNUM_FOLDER, SC_MARK_ARROW);
send->set(sci,SCI_MARKERDEFINE, SC_MARKNUM_FOLDERSUB, SC_MARK_EMPTY);
send->set(sci,SCI_MARKERDEFINE, SC_MARKNUM_FOLDERTAIL, SC_MARK_EMPTY);
send->set(sci,SCI_MARKERDEFINE, SC_MARKNUM_FOLDEREND, SC_MARK_EMPTY);
send->set(sci,SCI_MARKERDEFINE, SC_MARKNUM_FOLDEROPENMID, SC_MARK_EMPTY);
send->set(sci,SCI_MARKERDEFINE, SC_MARKNUM_FOLDERMIDTAIL, SC_MARK_EMPTY);
}
/*
Copyright (c) 2010, Michael Mullin <masmullin@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software
must display the following acknowledgement:
This product includes software developed by Michael Mullin <masmullin@gmail.com>.
4. Neither the name of Michael Mullin 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 MICHAEL MULLIN ''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 MICHAEL MULLIN 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.
*/
| 37.404348 | 84 | 0.749622 |
76c84ac58ffc95d332730ba9586637136a402d87 | 4,225 | cpp | C++ | ZEDModel.cpp | balder2046/WorldViewer | 088f7bfdbf3a4ac8ca82f301c26969e1b4db40f0 | [
"MIT"
] | null | null | null | ZEDModel.cpp | balder2046/WorldViewer | 088f7bfdbf3a4ac8ca82f301c26969e1b4db40f0 | [
"MIT"
] | null | null | null | ZEDModel.cpp | balder2046/WorldViewer | 088f7bfdbf3a4ac8ca82f301c26969e1b4db40f0 | [
"MIT"
] | null | null | null | #include <GL/glew.h>
#include <glm/detail/type_mat.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "ZEDModel.hpp"
#include "glm/glm.hpp"
void CheckGLError();
Zed3D::Zed3D() {
body_io.clear();
path_mem.clear();
vaoID = 0;
vboID = 0;
darktriID = 0;
allumtriID = 0;
}
Zed3D::~Zed3D() {
body_io.clear();
path_mem.clear();
}
void Zed3D::setPath(sl::Transform &Path,std::vector<sl::Translation> path_history) {
}
void Zed3D::draw(glm::mat4 &pm) {
shader.Use();
glBindVertexArray(vaoID);
glBindBuffer(GL_ARRAY_BUFFER,vboID);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,darktriID);
glUniform4f(shader("ObjColor"),DARK_COLOR.r,DARK_COLOR.g,DARK_COLOR.g,1.0f);
glDrawElements(GL_TRIANGLES,NB_DARK_TRIANGLES * 3,GL_UNSIGNED_SHORT,0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,allumtriID);
// const GLubyte *buf = gluErrorString(code);
glUniformMatrix4fv(shader("MVP"), 1, GL_FALSE, glm::value_ptr(pm));
glUniform4f(shader("ObjColor"),ALLUMINIUM_COLOR.r,ALLUMINIUM_COLOR.g,ALLUMINIUM_COLOR.b,1.0f);
glDrawElements(GL_TRIANGLES, NB_ALLUMINIUM_TRIANGLES * 3, GL_UNSIGNED_SHORT, 0);
glBindVertexArray(0);
shader.UnUse();
return;
// glPopMatrix();
}
struct Vertex_t
{
float x;
float y;
float z;
unsigned int color;
};
void Zed3D::init() {
sl::Transform path;
GLuint tt;
glGenVertexArrays(1,&vaoID);
glBindVertexArray(vaoID);
glGenBuffers(1,&vboID);
glBindBuffer(GL_ARRAY_BUFFER,vboID);
std::vector<Vertex_t> vertexs;
int vertcount = sizeof(verticesZed) / sizeof(float) / 3;
vertexs.resize(vertcount);
for (int i = 0; i < vertcount; ++i)
{
vertexs[i].x = verticesZed[3 * i] * 100.0f;
vertexs[i].y = verticesZed[3 * i + 1] * 100.0f;
vertexs[i].z = verticesZed[3 * i + 2] * 100.0f;
}
unsigned int darkcolor,alluminiumcolor;
darkcolor = glm::packUnorm4x8(glm::vec4(DARK_COLOR.r, DARK_COLOR.g, DARK_COLOR.b,1.0f));
alluminiumcolor = glm::packUnorm4x8(glm::vec4(ALLUMINIUM_COLOR.r, ALLUMINIUM_COLOR.g, ALLUMINIUM_COLOR.b,1.0f));
for (int i = 0; i < NB_ALLUMINIUM_TRIANGLES * 3; i += 3) {
for (int j = 0; j < 3; j++) {
double3color tmp;
int index = alluminiumTriangles[i + j] - 1;
vertexs[index].color = alluminiumcolor;
}
}
for (int i = 0; i < NB_DARK_TRIANGLES * 3; i += 3) {
for (int j = 0; j < 3; j++) {
int index = darkTriangles[i + j] - 1;
vertexs[index].color = darkcolor;
}
}
glBufferData(GL_ARRAY_BUFFER,sizeof(Vertex_t) * vertexs.size() ,&vertexs[0],GL_STATIC_DRAW);
glGenBuffers(1,&darktriID);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,darktriID);
std::vector<short> indexs;
indexs.resize(NB_DARK_TRIANGLES * 3);
for (int i = 0; i < NB_DARK_TRIANGLES * 3; i++)
{
indexs[i] = (short)darkTriangles[i] - 1;
}
glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(short) * indexs.size(),&indexs[0],GL_STATIC_DRAW);
glGenBuffers(1,&allumtriID);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,allumtriID);
indexs.resize(NB_ALLUMINIUM_TRIANGLES * 3);
for (int i = 0; i < NB_ALLUMINIUM_TRIANGLES * 3; ++i)
{
indexs[i] = (short)alluminiumTriangles[i] - 1;
}
glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(short) * indexs.size(), &indexs[0], GL_STATIC_DRAW);
shader.LoadFromFile(GL_VERTEX_SHADER, "shaders/shader.vert");
shader.LoadFromFile(GL_FRAGMENT_SHADER, "shaders/shader.frag");
//compile and link shader
shader.CreateAndLinkProgram();
shader.Use();
//add attributes and uniforms
shader.AddAttribute("vVertex");
shader.AddUniform("MVP");
shader.AddUniform("ObjColor");
shader.UnUse();
glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,sizeof(Vertex_t),(const void *)offsetof(Vertex_t,x));
glEnableVertexAttribArray(0);
glVertexAttribPointer(1,4,GL_BYTE,GL_TRUE,sizeof(Vertex_t),(const void *)offsetof(Vertex_t,color));
glEnableVertexAttribArray(1);
glBindVertexArray(0);
// setPath(path, path_mem);
}
| 31.296296 | 117 | 0.641657 |
76c8aee4977befd247672662a0830efb72cbde0c | 10,425 | cpp | C++ | source/printf.cpp | Rohansi/RaspberryPi | 8cc24fa49ae7842ee7a9df954fe9672d32826a4b | [
"MIT"
] | 3 | 2015-12-27T21:41:09.000Z | 2017-03-28T14:29:09.000Z | source/printf.cpp | Rohansi/RaspberryPi | 8cc24fa49ae7842ee7a9df954fe9672d32826a4b | [
"MIT"
] | null | null | null | source/printf.cpp | Rohansi/RaspberryPi | 8cc24fa49ae7842ee7a9df954fe9672d32826a4b | [
"MIT"
] | 2 | 2016-01-06T21:26:42.000Z | 2021-02-18T16:47:25.000Z | //
// Created by Daniel Lindberg on 2015-11-29.
//
#include <limits.h>
#include "string.h"
#include "printf.h"
#define MAX_INTEGER_SIZE 65
#define FLAG_LEFT_ADJUST 0x01
#define FLAG_ALWAYS_SIGN 0x02
#define FLAG_PREPEND_SPACE 0x04
#define FLAG_ALTERNATIVE 0x08
#define FLAG_PAD_WITH_ZERO 0x10
#define INPUT_TYPE_hh 0
#define INPUT_TYPE_h 1
#define INPUT_TYPE_none 2
#define INPUT_TYPE_l 3
#define INPUT_TYPE_ll 4
#define INPUT_TYPE_j 5
#define INPUT_TYPE_z 6
#define INPUT_TYPE_t 7
#define INPUT_TYPE_L 8
typedef struct {
char *buffer;
char *buffer_end;
} printf_state_t;
typedef struct {
int flags;
size_t min_width;
size_t precision;
int input_type;
int format;
} printf_format_t;
static size_t render_integer(char *buffer, int base, char ten, unsigned long long int val) {
size_t index = MAX_INTEGER_SIZE - 1;
buffer[index--] = '\0';
if (base > 10) {
do {
int mod = (int)(val % base);
if (mod < 10) {
buffer[index--] = (char)('0' + mod);
} else {
buffer[index--] = (char)(ten + mod - 10);
}
val /= base;
} while (val != 0);
} else {
do {
buffer[index--] = (char)('0' + val % base);
val /= base;
} while (val != 0);
}
return index + 1;
}
static inline const char *read_format_integer(const char *format) {
if (*format == '*') {
return format + 1;
}
while (*format >= '0' && *format <= '9') {
format++;
}
return format;
}
static inline int parse_format_integer(const char *beg, const char *end) {
int result = 0;
int multiplier = 1;
while (end != beg) {
end--;
result += multiplier * (*end - '0');
multiplier *= 10;
}
return result;
}
static inline void output_char(printf_state_t *state, char c) {
if (state->buffer != state->buffer_end) {
*state->buffer++ = c;
}
}
static inline void output_n_chars(printf_state_t *state, char c, size_t n) {
size_t left = state->buffer_end - state->buffer;
n = n > left ? left : n;
while (n--) {
*state->buffer++ = c;
}
}
static inline void output_string(printf_state_t *state, const char *str, size_t n) {
size_t left = state->buffer_end - state->buffer;
n = n > left ? left : n;
while (n--) {
*state->buffer++ = *str++;
}
}
static void write_string(printf_state_t *state, printf_format_t fmt, const char *val) {
size_t len = strlen(val);
size_t pad = 0;
if (fmt.precision != UINT_MAX && len > fmt.precision) {
len = (size_t)fmt.precision;
}
if (len < fmt.min_width) {
pad = fmt.min_width - len;
}
if (!(fmt.flags & FLAG_LEFT_ADJUST)) {
output_n_chars(state, ' ', pad);
}
output_string(state, val, len);
if (fmt.flags & FLAG_LEFT_ADJUST) {
output_n_chars(state, ' ', pad);
}
}
static void write_signed(printf_state_t *state, printf_format_t fmt, long long int val) {
char sign = '\0';
char buffer[MAX_INTEGER_SIZE];
size_t index;
size_t length;
size_t padding = 0;
size_t extra_zeroes = 0;
if (fmt.precision == 0 && val == 0) {
index = MAX_INTEGER_SIZE - 1;
length = 0;
buffer[MAX_INTEGER_SIZE - 1] = '\0';
} else {
if (val < 0) {
index = render_integer(buffer, 10, 'a', -val);
} else {
index = render_integer(buffer, 10, 'a', val);
}
length = MAX_INTEGER_SIZE - index - 1;
}
if (fmt.precision != UINT_MAX && length < fmt.precision) {
extra_zeroes = fmt.precision - length;
length += extra_zeroes;
}
if (val < 0 || fmt.flags & FLAG_PREPEND_SPACE || fmt.flags & FLAG_ALWAYS_SIGN) {
length += 1;
}
if (length < fmt.min_width) {
padding = fmt.min_width - length;
}
if (val < 0) {
sign = '-';
} else if (fmt.flags & FLAG_ALWAYS_SIGN) {
sign = '+';
} else if (fmt.flags & FLAG_PREPEND_SPACE) {
sign = ' ';
}
if (!(fmt.flags & FLAG_LEFT_ADJUST)) {
output_n_chars(state, ' ', padding);
}
if (sign != '\0') {
output_char(state, sign);
}
output_n_chars(state, '0', extra_zeroes);
output_string(state, buffer + index, MAX_INTEGER_SIZE - index - 1);
if (fmt.flags & FLAG_LEFT_ADJUST) {
output_n_chars(state, ' ', padding);
}
}
static void write_unsigned(printf_state_t *state, printf_format_t fmt, unsigned long long int val) {
int base = 10;
char ten = 'a';
char buffer[MAX_INTEGER_SIZE];
size_t index;
size_t length;
size_t padding = 0;
size_t extra_zeroes = 0;
if (fmt.format == 'o') {
base = 8;
} else if (fmt.format == 'x') {
base = 16;
} else if (fmt.format == 'X') {
base = 16;
ten = 'A';
}
index = render_integer(buffer, base, ten, val);
length = MAX_INTEGER_SIZE - index - 1;
if (fmt.format == 'o' && fmt.flags & FLAG_ALTERNATIVE) {
if (buffer[index] != '0') {
size_t extra_zero = length + 1;
fmt.precision = fmt.precision < extra_zero ? extra_zero : fmt.precision;
}
} else if (fmt.precision == 0 && val == 0) {
index = MAX_INTEGER_SIZE - 1;
length = 0;
buffer[MAX_INTEGER_SIZE - 1] = '\0';
}
if (fmt.precision != UINT_MAX && length < fmt.precision) {
extra_zeroes = fmt.precision - length;
length += extra_zeroes;
}
if (val != 0 && base == 16 && fmt.flags & FLAG_ALTERNATIVE) {
length += 2;
}
if (length < fmt.min_width) {
padding = fmt.min_width - length;
}
if (!(fmt.flags & FLAG_LEFT_ADJUST)) {
output_n_chars(state, ' ', padding);
}
if (val != 0 && base == 16 && fmt.flags & FLAG_ALTERNATIVE) {
output_char(state, '0');
output_char(state, (char) fmt.format);
}
output_n_chars(state, '0', extra_zeroes);
output_string(state, buffer + index, MAX_INTEGER_SIZE - index - 1);
if (fmt.flags & FLAG_LEFT_ADJUST) {
output_n_chars(state, ' ', padding);
}
}
int vsnprintf(char *buffer, size_t bufsz, const char *format, va_list arg) {
printf_state_t state;
state.buffer = buffer;
state.buffer_end = buffer + bufsz - 1;
while (1) {
char c = *format++;
if (c == '\0') {
break;
} else if (c != '%') {
output_char(&state, c);
} else {
printf_format_t fmt;
fmt.flags = 0;
// parse flags
while (1) {
switch (*format) {
case '-': format++; fmt.flags |= FLAG_LEFT_ADJUST; continue;
case '+': format++; fmt.flags |= FLAG_ALWAYS_SIGN; continue;
case ' ': format++; fmt.flags |= FLAG_PREPEND_SPACE; continue;
case '#': format++; fmt.flags |= FLAG_ALTERNATIVE; continue;
case '0': format++; fmt.flags |= FLAG_PAD_WITH_ZERO; continue;
}
break;
}
// parse minimum width
// TODO: duplicated code with precision
const char *min_width_beg = format;
format = read_format_integer(format);
const char *min_width_end = format;
fmt.min_width = *min_width_beg == '*' ? va_arg(arg, int) : parse_format_integer(min_width_beg, min_width_end);
// parse precision (if there is one)
if (*format != '.') {
fmt.precision = UINT_MAX;
} else {
format++;
const char *precision_beg = format;
format = read_format_integer(format);
const char *precision_end = format;
fmt.precision = *precision_beg == '*' ? va_arg(arg, int) : parse_format_integer(precision_beg, precision_end);
}
// parse input type modifier
switch (*format) {
case 'h': format++; fmt.input_type = *format == 'h' ? INPUT_TYPE_hh : INPUT_TYPE_h; break;
case 'l': format++; fmt.input_type = *format == 'l' ? INPUT_TYPE_ll : INPUT_TYPE_l; break;
case 'j': format++; fmt.input_type = INPUT_TYPE_j; break;
case 'z': format++; fmt.input_type = INPUT_TYPE_z; break;
case 't': format++; fmt.input_type = INPUT_TYPE_t; break;
case 'L': format++; fmt.input_type = INPUT_TYPE_L; break;
default:
fmt.input_type = INPUT_TYPE_none;
break;
}
if (fmt.input_type == INPUT_TYPE_hh || fmt.input_type == INPUT_TYPE_ll) {
format++;
}
char str_buf[2];
const char *str_val;
long long int signed_val;
unsigned long long int unsigned_val;
fmt.format = *format++;
switch (fmt.format) {
case 'c':
signed_val = va_arg(arg, int);
str_buf[0] = (char)signed_val;
str_buf[1] = '\0';
write_string(&state, fmt, str_buf);
break;
case 's':
str_val = va_arg(arg, const char *);
write_string(&state, fmt, str_val);
break;
case 'd': case 'i':
signed_val = va_arg(arg, int);
write_signed(&state, fmt, signed_val);
break;
case 'o': case 'x': case 'X': case 'u':
unsigned_val = va_arg(arg, unsigned int);
write_unsigned(&state, fmt, unsigned_val);
break;
case 'f': case 'F':
case 'e': case 'E':
case 'a': case 'A':
case 'g': case 'G':
case 'n':
case 'p':
// TODO: us
break;
}
}
}
*state.buffer++ = '\0';
return (int)(state.buffer - buffer);
}
int snprintf(char *buffer, size_t bufsz, const char *format, ...) {
va_list arg;
va_start(arg, format);
int ret = vsnprintf(buffer, bufsz, format, arg);
va_end(arg);
return ret;
}
| 28.561644 | 126 | 0.526331 |
76c94f79b5ba8720a93381adb8428d974c59c32e | 10,586 | cc | C++ | src/procps.cc | thlorenz/procps | b713185dc7b4c82d8cbc9f4be7e345f09df365bb | [
"MIT"
] | 5 | 2016-02-14T11:03:22.000Z | 2019-11-27T12:29:36.000Z | src/procps.cc | thlorenz/procps | b713185dc7b4c82d8cbc9f4be7e345f09df365bb | [
"MIT"
] | null | null | null | src/procps.cc | thlorenz/procps | b713185dc7b4c82d8cbc9f4be7e345f09df365bb | [
"MIT"
] | 9 | 2017-08-31T11:03:02.000Z | 2021-11-21T14:09:19.000Z | #include <node.h>
#include <nan.h>
#include "procps.h"
#include "proc/sysinfo.h"
#include "proc/whattime.h"
#include <cassert>
#include <time.h>
#include <sys/time.h>
using v8::FunctionTemplate;
using v8::Handle;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Number;
using v8::Integer;
using v8::Int32;
using v8::Uint32;
using v8::Array;
using v8::Value;
using v8::Function;
#define MAX_PROCS 5000
#define MAX_SLABS 1000
/*
* readproc
*/
/*
* By default readproc will consider all processes as valid to parse
* and return, but not actually fill in the cmdline, environ, and /proc/#/statm
* derived memory fields.
*
* `flags' (a bitwise-or of PROC_* below) modifies the default behavior.
*
* The "fill" options will cause more of the proc_t to be filled in.
*
* The "filter" options all use the second argument as the pointer to a list of objects:
* process status', process id's, user id's.
*
* The third argument is the length of the list (currently only used for lists of user
* id's since uid_t supports no convenient termination sentinel.)
*/
static proc_t **get_proctab(uint32_t flags) {
return readproctab(flags);
}
NAN_METHOD(Readproctab) {
NanScope();
// our JS API ensures we always pass flags (defaults if none were given)
Local<Integer> flags = args[0].As<Integer>();
assert(flags->IsUint32());
NanCallback *cb = new NanCallback(args[1].As<Function>());
proc_t **proctab = get_proctab(flags->Value());
int len = -1;
while(*(proctab + (++len)));
assert(len <= MAX_PROCS && "exceeded MAX_PROCS");
Local<Value> argv[MAX_PROCS];
for (int i = 0; i < len; i++) {
Proc *proc = new Proc(proctab[i]);
argv[i] = proc->Wrap();
}
// Passing result by calling function with arguments instead of populating
// and returning v8::Array since it's so much faster
// This technique came from node: https://github.com/joyent/node/blob/5344d0c1034b28f9e6de914430d8c8436ad85105/src/node_file.cc#L326
// (thanks @trevnorris for explaining it to me)
cb->Call(len, argv);
NanReturnUndefined();
}
/*
* sysinfo
*/
NAN_METHOD(Sysinfo_Meminfo) {
NanScope();
Local<Integer> shiftArg = args[0].As<Integer>();
assert(shiftArg->IsUint32());
unsigned long long shift = shiftArg->Value();
NanCallback *cb = new NanCallback(args[1].As<Function>());
meminfo();
#define X(field) NanNew<Uint32>((uint32_t) ((unsigned long long)(field) << 10) >> shift)
Local<Value> argv[] = {
/* all are unsigned long */
X(kb_main_buffers)
, X(kb_main_cached)
, X(kb_main_free)
, X(kb_main_total)
, X(kb_swap_free)
, X(kb_swap_total)
/* recently introduced */
, X(kb_high_free)
, X(kb_high_total)
, X(kb_low_free)
, X(kb_low_total)
/* 2.4.xx era */
, X(kb_active)
, X(kb_inact_laundry)
, X(kb_inact_dirty)
, X(kb_inact_clean)
, X(kb_inact_target)
, X(kb_swap_cached) /* late 2.4 and 2.6+ only */
/* derived values */
, X(kb_swap_used)
, X(kb_main_used)
/* 2.5.41+ */
, X(kb_writeback)
, X(kb_slab)
, X(nr_reversemaps)
, X(kb_committed_as)
, X(kb_dirty)
, X(kb_inactive)
, X(kb_mapped)
, X(kb_pagetables)
};
#undef X
cb->Call(sizeof(argv) / sizeof(argv[0]), argv);
NanReturnUndefined();
}
NAN_METHOD(Sysinfo_Vminfo) {
NanScope();
NanCallback *cb = new NanCallback(args[0].As<Function>());
vminfo();
#define X(field) NanNew<Uint32>((uint32_t)field)
Local<Value> argv[] = {
/* all are unsigned long */
X(vm_nr_dirty)
, X(vm_nr_writeback)
, X(vm_nr_pagecache)
, X(vm_nr_page_table_pages)
, X(vm_nr_reverse_maps)
, X(vm_nr_mapped)
, X(vm_nr_slab)
, X(vm_pgpgin)
, X(vm_pgpgout)
, X(vm_pswpin)
, X(vm_pswpout)
, X(vm_pgalloc)
, X(vm_pgfree)
, X(vm_pgactivate)
, X(vm_pgdeactivate)
, X(vm_pgfault)
, X(vm_pgmajfault)
, X(vm_pgscan)
, X(vm_pgrefill)
, X(vm_pgsteal)
, X(vm_kswapd_steal)
// next 3 as defined by the 2.5.52 kernel
, X(vm_pageoutrun)
, X(vm_allocstall)
};
#undef X
cb->Call(sizeof(argv) / sizeof(argv[0]), argv);
NanReturnUndefined();
}
NAN_METHOD(Sysinfo_Hertz) {
NanScope();
/* Herz is globally defined in sysinfo.c */
NanReturnValue(NanNew<Uint32>((uint32_t) Hertz));
}
NAN_METHOD(Sysinfo_Getstat) {
jiff cpu_use, cpu_nic, cpu_sys, cpu_idl, cpu_iow, cpu_xxx, cpu_yyy, cpu_zzz;
unsigned long pgpgin, pgpgout, pswpin, pswpout;
unsigned int intr, ctxt;
unsigned int running, blocked, btime, processes;
NanScope();
NanCallback *cb = new NanCallback(args[0].As<Function>());
getstat(&cpu_use, &cpu_nic, &cpu_sys, &cpu_idl,
&cpu_iow, &cpu_xxx, &cpu_yyy, &cpu_zzz,
&pgpgin, &pgpgout, &pswpin, &pswpout,
&intr, &ctxt,
&running, &blocked,
&btime, &processes);
// FIXME: currently converting 64-bit unigned long long to 32-bit
// this works as long as the machine we are looking up hasn't been up for a long time
// need to figure out how to correct this by correctly passing 64-bit number to JS layer
#define X(field) NanNew<Uint32>((uint32_t) field)
Local<Value> argv[] = {
X(cpu_use)
, X(cpu_nic)
, X(cpu_sys)
, X(cpu_idl)
, X(cpu_iow)
, X(cpu_xxx)
, X(cpu_yyy)
, X(cpu_zzz)
, X(pgpgin)
, X(pgpgout)
, X(pswpin)
, X(pswpout)
, X(intr)
, X(ctxt)
, X(running)
, X(blocked)
, X(btime)
, X(processes)
};
#undef X
cb->Call(sizeof(argv) / sizeof(argv[0]), argv);
NanReturnUndefined();
}
NAN_METHOD(Sysinfo_GetDiskStat) {
NanScope();
NanCallback *cb = new NanCallback(args[0].As<Function>());
disk_stat *disks;
partition_stat *partitions;
int ndisks = getdiskstat(&disks, &partitions);
int npartitions = getpartitions_num(disks, ndisks);
// disks
Local<Array> wrapDisks = NanNew<Array>(ndisks);
for (int i = 0; i < ndisks; i++) {
DiskStat *stat = new DiskStat(disks[i]);
wrapDisks->Set(i, stat->Wrap());
}
// partitions
Local<Array> wrapPartitions = NanNew<Array>(npartitions);
for (int i = 0; i < npartitions; i++) {
PartitionStat *stat = new PartitionStat(partitions[i]);
wrapPartitions->Set(i, stat->Wrap());
}
Local<Value> argv[] = { wrapDisks, wrapPartitions };
cb->Call(sizeof(argv) / sizeof(argv[0]), argv);
NanReturnUndefined();
}
// see deps/procps/uptime.c for how to determine uptime since
NAN_METHOD(Sysinfo_Uptime) {
NanScope();
NanCallback *cb = new NanCallback(args[0].As<Function>());
double uptime_secs, idle_secs;
uptime(&uptime_secs, &idle_secs);
Local<Value> argv[] = { NanNew<Number>(uptime_secs), NanNew<Number>(idle_secs) };
cb->Call(sizeof(argv) / sizeof(argv[0]), argv);
NanReturnUndefined();
}
NAN_METHOD(Sysinfo_UptimeSince) {
NanScope();
NanCallback *cb = new NanCallback(args[0].As<Function>());
double now, uptime_secs, idle_secs;
time_t up_since_secs;
struct tm *up_since;
struct timeval tim;
/* Get the current time and convert it to a double */
gettimeofday(&tim, NULL);
now = tim.tv_sec + (tim.tv_usec / 1000000.0);
/* Get the uptime and calculate when that was */
uptime(&uptime_secs, &idle_secs);
up_since_secs = (time_t) ((now - uptime_secs) + 0.5);
/* Show this */
up_since = localtime(&up_since_secs);
#define X(field) NanNew<Int32>((uint32_t) field)
Local<Value> argv[] = {
X(up_since->tm_year + 1900)
, X(up_since->tm_mon + 1)
, X(up_since->tm_mday)
, X(up_since->tm_hour)
, X(up_since->tm_min)
, X(up_since->tm_sec)
, X(up_since->tm_yday)
, X(up_since->tm_wday)
};
#undef X
cb->Call(sizeof(argv) / sizeof(argv[0]), argv);
NanReturnUndefined();
}
NAN_METHOD(Sysinfo_UptimeString) {
NanScope();
Local<Integer> human_readable = args[0].As<Integer>();
assert(human_readable->IsUint32());
NanCallback *cb = new NanCallback(args[1].As<Function>());
char* s = sprint_uptime(human_readable->Value());
Local<Value> argv[] = { NanNew<String>(s) };
cb->Call(1, argv);
NanReturnUndefined();
}
NAN_METHOD(Sysinfo_Loadavg) {
NanScope();
NanCallback *cb = new NanCallback(args[0].As<Function>());
double av[3];
loadavg(&av[0], &av[1], &av[2]);
#define X(field) NanNew<Number>(field)
Local<Value> argv[] = { X(av[0]), X(av[1]), X(av[2]) };
#undef X
cb->Call(sizeof(argv) / sizeof(argv[0]), argv);
NanReturnUndefined();
}
NAN_METHOD(Sysinfo_GetPidDigits) {
NanScope();
NanCallback *cb = new NanCallback(args[0].As<Function>());
unsigned digits = get_pid_digits();
Local<Value> argv[] = { NanNew<Uint32>(digits) };
cb->Call(1, argv);
NanReturnUndefined();
}
NAN_METHOD(Sysinfo_GetSlabInfo) {
NanScope();
NanCallback *cb = new NanCallback(args[0].As<Function>());
struct slab_cache *slabs;
unsigned int nSlab = getslabinfo(&slabs);
assert(nSlab <= MAX_SLABS && "exceeded MAX_SLABS");
Local<Value> argv[MAX_SLABS];
for (unsigned int i = 0; i < nSlab; i++) {
SlabCache *sc = new SlabCache(slabs[i]);
argv[i] = sc->Wrap();
}
cb->Call(nSlab, argv);
NanReturnUndefined();
}
void init(Handle<Object> exports) {
exports->Set(NanNew<String>("readproctab") , NanNew<FunctionTemplate>(Readproctab)->GetFunction());
exports->Set(NanNew<String>("sysinfo_meminfo") , NanNew<FunctionTemplate>(Sysinfo_Meminfo)->GetFunction());
exports->Set(NanNew<String>("sysinfo_vminfo") , NanNew<FunctionTemplate>(Sysinfo_Vminfo)->GetFunction());
exports->Set(NanNew<String>("sysinfo_Hertz") , NanNew<FunctionTemplate>(Sysinfo_Hertz)->GetFunction());
exports->Set(NanNew<String>("sysinfo_getstat") , NanNew<FunctionTemplate>(Sysinfo_Getstat)->GetFunction());
exports->Set(NanNew<String>("sysinfo_getdiskstat") , NanNew<FunctionTemplate>(Sysinfo_GetDiskStat)->GetFunction());
exports->Set(NanNew<String>("sysinfo_uptime") , NanNew<FunctionTemplate>(Sysinfo_Uptime)->GetFunction());
exports->Set(NanNew<String>("sysinfo_uptimesince") , NanNew<FunctionTemplate>(Sysinfo_UptimeSince)->GetFunction());
exports->Set(NanNew<String>("sysinfo_uptimestring") , NanNew<FunctionTemplate>(Sysinfo_UptimeString)->GetFunction());
exports->Set(NanNew<String>("sysinfo_loadavg") , NanNew<FunctionTemplate>(Sysinfo_Loadavg)->GetFunction());
exports->Set(NanNew<String>("sysinfo_getpiddigits") , NanNew<FunctionTemplate>(Sysinfo_GetPidDigits)->GetFunction());
exports->Set(NanNew<String>("sysinfo_getslabinfo") , NanNew<FunctionTemplate>(Sysinfo_GetSlabInfo)->GetFunction());
}
NODE_MODULE(procps, init)
| 26.59799 | 134 | 0.665029 |
76cebccee3d56683320f6a612249e7a872d7c0ac | 3,434 | cpp | C++ | willow/src/patterns/initaccumulatepattern.cpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 61 | 2020-07-06T17:11:46.000Z | 2022-03-12T14:42:51.000Z | willow/src/patterns/initaccumulatepattern.cpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 1 | 2021-02-25T01:30:29.000Z | 2021-11-09T11:13:14.000Z | willow/src/patterns/initaccumulatepattern.cpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 6 | 2020-07-15T12:33:13.000Z | 2021-11-07T06:55:00.000Z | // Copyright (c) 2020 Graphcore Ltd. All rights reserved.
#include <popart/error.hpp>
#include <popart/graph.hpp>
#include <popart/op/add.hpp>
#include <popart/op/init.hpp>
#include <popart/op/pad.hpp>
#include <popart/patterns/initaccumulatepattern.hpp>
#include <popart/patterns/patterns.hpp>
#include <popart/tensor.hpp>
#include <popart/tensorindex.hpp>
#include <popart/tensors.hpp>
namespace popart {
bool InitAccumulatePattern::matches(Op *op) const {
// Looking for element-wise binary op (two inputs checked).
if (!op->isConvertibleTo<ElementWiseBinaryOp>() or op->input->n() != 2) {
return false;
}
// Ignore ops for which inferTensorMappingToFrom has been modified already.
if (!op->settings.inferTensorMappingToFrom.empty()) {
return false;
}
const auto output = op->outTensor(AddOp::getOutIndex());
const auto arg0Idx = ElementWiseBinaryOp::getArg0InIndex();
const auto arg1Idx = ElementWiseBinaryOp::getArg1InIndex();
const auto arg0 = op->inTensor(arg0Idx);
const auto arg1 = op->inTensor(arg1Idx);
if (!arg0->hasProducer() || !arg1->hasProducer()) {
return false;
}
// Is the arg0 producer an Init op?
const auto arg0Producer = arg0->getProducer();
const auto arg0FromInit = arg0Producer->isConvertibleTo<InitOp>();
// Is the arg1 producer an Init op?
const auto arg1Producer = arg1->getProducer();
const auto arg1FromInit = arg1Producer->isConvertibleTo<InitOp>();
// One and only one argument should be from an InitOp.
if (!(arg0FromInit ^ arg1FromInit)) {
return false;
}
// Check for inplace modification (arg0).
uint32_t mods = 0;
for (auto reg : op->modifies(arg0Idx)) {
if (!reg.isEmpty()) {
++mods;
}
}
const auto inplace0 = (mods > 0);
// Check for inplace modification (arg1).
mods = 0;
for (auto reg : op->modifies(arg1Idx)) {
if (!reg.isEmpty()) {
++mods;
}
}
const auto inplace1 = (mods > 0);
// Ignore op if either operand is modified inplace.
if (inplace0 | inplace1) {
return false;
}
uint32_t ewbConsumers = 0;
uint32_t otherConsumers = 0;
for (auto consumer : output->consumers.getOps()) {
if (consumer->isConvertibleTo<ElementWiseBinaryOp>()) {
++ewbConsumers;
} else {
++otherConsumers;
}
}
// The output of this operation should be consumed by at least
// one ElementWiseBinary op and no other op type.
if (!ewbConsumers || otherConsumers) {
return false;
}
return true;
}
std::vector<const Tensor *> InitAccumulatePattern::touches(Op *op) const {
// This pattern affects the layout or relationship of both inputs.
return {op->input->tensor(0), op->input->tensor(1)};
}
bool InitAccumulatePattern::apply(Op *op) const {
const auto arg0Idx = ElementWiseBinaryOp::getArg0InIndex();
const auto arg1Idx = ElementWiseBinaryOp::getArg1InIndex();
const auto arg0 = op->inTensor(arg0Idx);
const auto arg0Producer = arg0->getProducer();
const auto arg0FromInit = arg0Producer->isConvertibleTo<InitOp>();
if (arg0FromInit) {
// Infer Arg0 layout from Arg1.
op->settings.inferTensorMappingToFrom.insert({arg0Idx, arg1Idx});
} else {
// Infer Arg1 layout from Arg0.
op->settings.inferTensorMappingToFrom.insert({arg1Idx, arg0Idx});
}
return true;
}
namespace {
static PatternCreator<InitAccumulatePattern>
InitAccumulatePattern("InitAccumulate");
}
} // namespace popart
| 28.147541 | 77 | 0.692196 |
76d4f57531e01891535353830596594b082f7844 | 2,064 | hpp | C++ | include/boost/simd/arch/common/scalar/function/if_else_zero.hpp | yaeldarmon/boost.simd | 561316cc54bdc6353ca78f3b6d7e9120acd11144 | [
"BSL-1.0"
] | null | null | null | include/boost/simd/arch/common/scalar/function/if_else_zero.hpp | yaeldarmon/boost.simd | 561316cc54bdc6353ca78f3b6d7e9120acd11144 | [
"BSL-1.0"
] | null | null | null | include/boost/simd/arch/common/scalar/function/if_else_zero.hpp | yaeldarmon/boost.simd | 561316cc54bdc6353ca78f3b6d7e9120acd11144 | [
"BSL-1.0"
] | null | null | null | //==================================================================================================
/*!
@file
@copyright 2015 NumScale SAS
@copyright 2015 J.T. Lapreste
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_IF_ELSE_ZERO_HPP_INCLUDED
#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_IF_ELSE_ZERO_HPP_INCLUDED
#include <boost/simd/constant/zero.hpp>
#include <boost/simd/function/scalar/is_nez.hpp>
#include <boost/dispatch/function/overload.hpp>
#include <boost/config.hpp>
namespace boost { namespace simd { namespace ext
{
BOOST_DISPATCH_OVERLOAD ( if_else_zero_
, (typename A0, typename A1)
, bd::cpu_
, bd::scalar_< logical_<A0> >
, bd::scalar_< bd::unspecified_<A1> >
)
{
BOOST_FORCEINLINE A1 operator() ( A0 a0, A1 const& a1) const BOOST_NOEXCEPT
{
return is_nez(a0) ? a1 : Zero<A1>();
}
};
BOOST_DISPATCH_OVERLOAD ( if_else_zero_
, (typename A0, typename A1)
, bd::cpu_
, bd::scalar_< bd::unspecified_<A0> >
, bd::scalar_< bd::unspecified_<A1> >
)
{
BOOST_FORCEINLINE A1 operator() ( A0 const& a0, A1 const& a1) const BOOST_NOEXCEPT
{
return is_nez(a0) ? a1 : Zero<A1>();
}
};
BOOST_DISPATCH_OVERLOAD ( if_else_zero_
, (typename A0)
, bd::cpu_
, bd::scalar_< bd::bool_<A0> >
, bd::scalar_< bd::bool_<A0> >
)
{
BOOST_FORCEINLINE bool operator() ( A0 a0, A0 a1) const BOOST_NOEXCEPT
{
return a0 ? a1 : false;
}
};
} } }
#endif
| 31.753846 | 100 | 0.493702 |
76e3c01117eab50b90b46fcac940cf4a60f2d3f7 | 47,332 | cxx | C++ | PWG/muondep/AliMuonAccEffSubmitter.cxx | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 114 | 2017-03-03T09:12:23.000Z | 2022-03-03T20:29:42.000Z | PWG/muondep/AliMuonAccEffSubmitter.cxx | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 19,637 | 2017-01-16T12:34:41.000Z | 2022-03-31T22:02:40.000Z | PWG/muondep/AliMuonAccEffSubmitter.cxx | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 1,021 | 2016-07-14T22:41:16.000Z | 2022-03-31T05:15:51.000Z | /**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include "AliMuonAccEffSubmitter.h"
#include "AliAnalysisTriggerScalers.h"
#include "AliCDBId.h"
#include "AliCDBManager.h"
#include "AliCDBStorage.h"
#include "AliLog.h"
#include "AliMuonOCDBSnapshotGenerator.h"
#include "TFile.h"
#include "TGrid.h"
#include "TGridResult.h"
#include "TMap.h"
#include "TMath.h"
#include "TObjString.h"
#include "TROOT.h"
#include "TString.h"
#include "TSystem.h"
#include <cassert>
#include <fstream>
#include <vector>
using std::ifstream;
/// \cond CLASSIMP
ClassImp(AliMuonAccEffSubmitter);
/// \endcond
//______________________________________________________________________________
AliMuonAccEffSubmitter::AliMuonAccEffSubmitter(Bool_t localOnly)
: AliMuonGridSubmitter(AliMuonGridSubmitter::kAccEff,localOnly),
fRatio(-1.0),
fFixedNofEvents(10000),
fMaxEventsPerChunk(5000),
fSplitMaxInputFileNumber(20),
fLogOutToKeep(""),
fRootOutToKeep(""),
fExternalConfig(""),
fSnapshotDir(""),
fUseAODMerging(kFALSE)
{
/// default ctor
SetupCommon(localOnly);
AliWarning("Using default constructor : you will probably need to call a few Set methods to properly configure the object before getting it to do anything usefull");
}
/// Normal constructor
///
/// \param generator name of the generator to be used (see \ref SetGenerator)
/// \param localOnly whether the generated files are meant to be used only locally (i.e. not on the Grid)
/// \param generatorVersion optional speficiation to trigger the setup of some external libraries
///
/// if generator contains "pythia8" and generatorVersion is given then
/// the pythiaversion must represent the integer part XXX of the
/// include directory $ALICE_ROOT/PYTHI8/pythiaXXX/include where the file
/// Analysis.h is to be found.
///
/// if generator contains "pythia6" then generatorVersion should be the
/// X.YY part of libpythia6.X.YY.so
//
//______________________________________________________________________________
AliMuonAccEffSubmitter::AliMuonAccEffSubmitter(const char* generator, Bool_t localOnly,
const char* generatorVersion)
: AliMuonGridSubmitter(AliMuonGridSubmitter::kAccEff,localOnly),
fRatio(-1.0),
fFixedNofEvents(10000),
fMaxEventsPerChunk(5000),
fSplitMaxInputFileNumber(20),
fLogOutToKeep(""),
fRootOutToKeep(""),
fExternalConfig(""),
fSnapshotDir(""),
fUseAODMerging(kFALSE)
{
SetupCommon(localOnly);
if ( TString(generator).Contains("pythia8",TString::kIgnoreCase) )
{
SetMaxEventsPerChunk(500); // 5000 is not reasonable with Pythia8 (and ITS+MUON...)
SetCompactMode(2); // keep AOD as for the time being the filtering driven from AODtrain.C cannot
// add SPD tracklets to muon AODs.
SetVar("VAR_USE_ITS_RECO","1");
SetupPythia8(generatorVersion);
SetVar("VAR_TRIGGER_CONFIGURATION","p-p");
}
if ( TString(generator).Contains("pythia6",TString::kIgnoreCase) )
{
SetMaxEventsPerChunk(500); // 5000 is not reasonable with Pythia6 (and ITS+MUON...)
SetCompactMode(2); // keep AOD as for the time being the filtering driven from AODtrain.C cannot
// add SPD tracklets to muon AODs.
SetupPythia6(generatorVersion);
SetVar("VAR_USE_ITS_RECO","1");
SetVar("VAR_TRIGGER_CONFIGURATION","p-p");
}
if ( TString(generator).Contains("Powheg") ) {
SetupCollision(5023);
SetupPowheg("Z");
}
SetGenerator(generator);
}
/// special mode to generate pseudo-ideal simulations
/// in order to compute a quick acc x eff
///
/// pseudo-ideal simulation means we :
/// - use ideal pedestals (mean 0, sigma 1)
/// - complete configuration (i.e. all manus are there)
/// - raw/full alignment
/// - do _not_ cut on the pad status, i.e. disregard occupancy, HV, LV or RejectList completely
///
/// we use the real RecoParam, but with a patch to change the status mask to disregard above problems
///
//______________________________________________________________________________
AliMuonAccEffSubmitter::AliMuonAccEffSubmitter(const char* generator,
Bool_t localOnly,
const char* pythia6version,
Int_t numberOfEventsForPseudoIdealSimulation,
Int_t maxEventsPerChunk)
: AliMuonGridSubmitter(AliMuonGridSubmitter::kAccEff,localOnly)
{
AliWarning("THIS IS A SPECIAL MODE TO GENERATE PSEUDO-IDEAL SIMULATIONS !");
SetupCommon(localOnly);
SetupPythia6(pythia6version);
SetMaxEventsPerChunk(maxEventsPerChunk);
SetGenerator(generator);
ShouldOverwriteFiles(true);
UseOCDBSnapshots(true);
SetVar("VAR_USE_ITS_RECO","0");
SetVar("VAR_TRIGGER_CONFIGURATION","p-p");
SetCompactMode(0);
SetAliPhysicsVersion("VO_ALICE@AliPhysics::v5-08-13o-01-1");
MakeNofEventsFixed(numberOfEventsForPseudoIdealSimulation);
// 2015 pp
// SetVar("VAR_SIM_ALIGNDATA","\"alien://folder=/alice/cern.ch/user/h/hupereir/CDB/LHC15Sim/Ideal\"");
// SetVar("VAR_REC_ALIGNDATA","\"alien://folder=/alice/cern.ch/user/h/hupereir/CDB/LHC15Sim/Residual\"");
SetVar("VAR_SIM_ALIGNDATA","\"alien://folder=/alice/cern.ch/user/j/jcastill/pp16wrk/LHC16_mcp1vsrealv2_tr_MisAlignCDB\"");
SetVar("VAR_REC_ALIGNDATA","\"alien://folder=/alice/data/2016/OCDB\"");
SetVar("VAR_MAKE_COMPACT_ESD","1");
}
//______________________________________________________________________________
AliMuonAccEffSubmitter::~AliMuonAccEffSubmitter()
{
// dtor
}
///______________________________________________________________________________
Bool_t AliMuonAccEffSubmitter::Generate(const char* jdlname) const
{
if ( TString(jdlname).Contains("merge",TString::kIgnoreCase) )
{
return GenerateMergeJDL(jdlname);
}
else
{
return GenerateRunJDL(jdlname);
}
}
///______________________________________________________________________________
Bool_t AliMuonAccEffSubmitter::GenerateMergeJDL(const char* name) const
{
/// Create the JDL for merging jobs
AliDebug(1,"");
std::ostream* os = CreateJDLFile(name);
if (!os)
{
return kFALSE;
}
Bool_t final = TString(name).Contains("final",TString::kIgnoreCase);
(*os) << "# Generated merging jdl (production mode)" << std::endl
<< "# $1 = run number" << std::endl
<< "# $2 = merging stage" << std::endl
<< "# Stage_<n>.xml made via: find <OutputDir> *Stage<n-1>/*root_archive.zip" << std::endl;
OutputToJDL(*os,"Packages",GetMapValue("AliPhysics"));
OutputToJDL(*os,"Executable",Form("%s/AOD_merge.sh",RemoteDir().Data()));
OutputToJDL(*os,"Price","1");
if ( final )
{
OutputToJDL(*os,"Jobtag","comment: AliMuonAccEffSubmitter final merging");
}
else
{
OutputToJDL(*os,"Jobtag","comment: AliMuonAccEffSubmitter merging stage $2");
}
OutputToJDL(*os,"Workdirectorysize","5000MB");
OutputToJDL(*os,"Validationcommand",Form("%s/validation_merge.sh",RemoteDir().Data()));
OutputToJDL(*os,"TTL","7200");
OutputToJDL(*os,"OutputArchive",
//"log_archive.zip:stderr,stdout@disk=1",
"root_archive.zip:AliAOD.root,AliAOD.Muons.root,Merged.QA.Data.root,AnalysisResults.root@disk=2"
);
OutputToJDL(*os,"Arguments",(final ? "2":"1")); // for AOD_merge.sh, 1 means intermediate merging stage, 2 means final merging
TObjArray files;
files.SetOwner(kTRUE);
TIter next(LocalFileList());
TObjString* file;
while ( ( file = static_cast<TObjString*>(next())) )
{
if ( file->TestBit(BIT(23)) )
{
files.Add(new TObjString(Form("LF:%s/%s",RemoteDir().Data(),file->String().Data())));
}
}
if ( final )
{
files.Add(new TObjString(Form("LF:%s/$1/wn.xml",MergedDir().Data())));
}
OutputToJDL(*os,"InputFile",files);
if ( !final )
{
OutputToJDL(*os,"OutputDir",Form("%s/$1/Stage_$2/#alien_counter_03i#",MergedDir().Data()));
OutputToJDL(*os,"InputDataCollection",Form("LF:%s/$1/Stage_$2.xml,nodownload",MergedDir().Data()));
OutputToJDL(*os,"split","se");
OutputToJDL(*os,"SplitMaxInputFileNumber",Form("%d",GetSplitMaxInputFileNumber()));
OutputToJDL(*os,"InputDataListFormat","xml-single");
OutputToJDL(*os,"InputDataList","wn.xml");
}
else
{
OutputToJDL(*os,"OutputDir",Form("%s/$1",MergedDir().Data()));
}
return kTRUE;
}
//______________________________________________________________________________
Bool_t AliMuonAccEffSubmitter::GenerateRunJDL(const char* name) const
{
/// Generate (locally) the JDL to perform the simulation+reco+aod filtering
/// (to be then copied to the grid and finally submitted)
AliDebug(1,"");
std::ostream* os = CreateJDLFile(name);
if (!os)
{
return kFALSE;
}
OutputToJDL(*os,"Packages",GetMapValue("Generator"),GetMapValue("AliPhysics"));
OutputToJDL(*os,"Jobtag","comment: AliMuonAccEffSubmitter RUN $1");
OutputToJDL(*os,"split","production:$2-$3");
OutputToJDL(*os,"Price","1");
OutputToJDL(*os,"OutputDir",Form("%s/$1/#alien_counter_03i#",RemoteDir().Data()));
OutputToJDL(*os,"Executable","/alice/bin/aliroot_new");
TObjArray files;
files.SetOwner(kTRUE);
TIter next(LocalFileList());
TObjString* file;
while ( ( file = static_cast<TObjString*>(next())) )
{
if ( !file->String().Contains("jdl",TString::kIgnoreCase) &&
!file->String().Contains("OCDB_") )
{
files.Add(new TObjString(Form("LF:%s/%s",RemoteDir().Data(),file->String().Data())));
}
}
if ( UseOCDBSnapshots() )
{
files.Add(new TObjString(Form("LF:%s/OCDB/$1/OCDB_sim.root",RemoteDir().Data())));
files.Add(new TObjString(Form("LF:%s/OCDB/$1/OCDB_rec.root",RemoteDir().Data())));
}
OutputToJDL(*os,"InputFile",files);
if ( fLogOutToKeep.IsNull() || fRootOutToKeep.IsNull() ) {
AliError(Form("Output files not correctly set. Log: %s Root: %s",fLogOutToKeep.Data(),fRootOutToKeep.Data()));
delete os;
return kFALSE;
}
else {
OutputToJDL(*os,"OutputArchive",fLogOutToKeep.Data(),fRootOutToKeep.Data());
}
OutputToJDL(*os,"splitarguments","--run $1 --event #alien_counter# --eventsPerJob $4");
OutputToJDL(*os,"Workdirectorysize","5000MB");
OutputToJDL(*os,"JDLVariables","Packages","OutputDir");
OutputToJDL(*os,"Validationcommand","/alice/validation/validation.sh");
if ( GetVar("VAR_GENERATOR").Contains("pythia",TString::kIgnoreCase) )
{
OutputToJDL(*os,"TTL","36000");
}
else
{
OutputToJDL(*os,"TTL","14400");
}
return kTRUE;
}
//______________________________________________________________________________
Bool_t AliMuonAccEffSubmitter::MakeOCDBSnapshots()
{
/// Run sim.C and rec.C in a special mode to generate OCDB snapshots
/// Can only be done after the templates have been copied locally
if (!IsValid()) return kFALSE;
if (!UseOCDBSnapshots()) return kTRUE;
if (!NofRuns()) return kFALSE;
AliDebug(1,"");
Bool_t ok(kTRUE);
const std::vector<int>& runs = RunList();
// we must create some default (perfect) objects for some calibration
// data so they'll be picked up by the snapshots
// : Pedestals, Config, OccupancyMap, HV, LV
AliMuonOCDBSnapshotGenerator ogen(runs[0],Form("local://%s/OCDB",gSystem->WorkingDirectory()),OCDBPath().Data());
ogen.CreateLocalOCDBWithDefaultObjects(kFALSE);
for ( std::vector<int>::size_type i = 0; i < runs.size() && ok; ++i )
{
Int_t runNumber = runs[i];
TString ocdbSim(Form("%s/OCDB/%d/OCDB_sim.root",LocalSnapshotDir().Data(),runNumber));
TString ocdbRec(Form("%s/OCDB/%d/OCDB_rec.root",LocalSnapshotDir().Data(),runNumber));
ok = kFALSE;
if ( !gSystem->AccessPathName(ocdbSim.Data()) &&
!gSystem->AccessPathName(ocdbRec.Data()) )
{
ok = kTRUE;
AliWarning(Form("Local OCDB snapshots already there for run %d. Will not redo them. If you want to force them, delete them by hand !",runNumber));
}
else
{
ok = ogen.CreateSnapshot(0,ocdbSim.Data(),GetVar("VAR_SIM_ALIGNDATA"))
&& ogen.CreateSnapshot(1,ocdbRec.Data(),GetVar("VAR_REC_ALIGNDATA"));
}
if (ok)
{
AddToLocalFileList(ocdbRec);
AddToLocalFileList(ocdbSim);
}
}
LocalFileList()->Print();
return ok;
}
//______________________________________________________________________________
Bool_t AliMuonAccEffSubmitter::Merge(Int_t stage, Bool_t dryRun)
{
/// Submit multiple merging jobs with the format "submit AOD_merge(_final).jdl run# (stage#)".
/// Also produce the xml collection before sending jobs
/// Initial AODs will be taken from RemoteDir/[RUNNUMBER] while the merged
/// ones will be put into MergedDir/[RUNNUMBER]
if (!RemoteDirectoryExists(MergedDir().Data())) {
AliError(Form("directory %s does not exist", MergedDir().Data()));
return kFALSE;
}
gGrid->Cd(MergedDir().Data());
TString jdl = MergeJDLName(stage==0);
if (!RemoteFileExists(jdl.Data()))
{
AliError(Form("file %s does not exist in %s\n", jdl.Data(), RemoteDir().Data()));
return kFALSE;
}
const std::vector<int>& runs = RunList();
if (runs.empty())
{
AliError("No run to work with");
return 0;
}
TString currRun;
TString reply = "";
gSystem->Exec("rm -f __failed__");
Bool_t failedRun = kFALSE;
for ( std::vector<int>::size_type i = 0; i < runs.size(); ++i )
{
Int_t run = runs[i];
AliInfo(Form("\n --- processing run %d ---\n", run));
TString runDir = Form("%s/%d", MergedDir().Data(), run);
if (!RemoteDirectoryExists(runDir.Data()))
{
AliInfo(Form(" - creating output directory %s\n", runDir.Data()));
gSystem->Exec(Form("alien_mkdir -p %s", runDir.Data()));
}
if (RemoteFileExists(Form("%s/root_archive.zip", runDir.Data())))
{
AliWarning(" ! final merging already done");
continue;
}
Int_t lastStage = GetLastStage(runDir.Data());
if (stage > 0 && stage != lastStage+1)
{
AliError(Form(" ! lastest merging stage = %d. Next must be stage %d or final stage\n", lastStage, lastStage+1));
continue;
}
TString wn = (stage > 0) ? Form("Stage_%d.xml", stage) : "wn.xml";
TString find = (lastStage == 0) ?
Form("alien_find -x %s %s/%d *root_archive.zip", wn.Data(), RemoteDir().Data(), run) :
Form("alien_find -x %s %s/%d/Stage_%d *root_archive.zip", wn.Data(), MergedDir().Data(), run, lastStage);
gSystem->Exec(Form("%s 1> %s 2>/dev/null", find.Data(), wn.Data()));
gSystem->Exec(Form("grep -c /event %s > __nfiles__", wn.Data()));
ifstream f2("__nfiles__");
TString nFiles;
nFiles.ReadLine(f2,kTRUE);
f2.close();
gSystem->Exec("rm -f __nfiles__");
printf(" - number of files to merge = %d\n", nFiles.Atoi());
if (nFiles.Atoi() == 0) {
printf(" ! collection of files to merge is empty\n");
gSystem->Exec(Form("rm -f %s", wn.Data()));
continue;
} else if (stage > 0 && nFiles.Atoi() <= GetSplitMaxInputFileNumber() && !reply.BeginsWith("y")) {
if (!reply.BeginsWith("n")) {
printf(" ! number of files to merge <= split level (%d). Continue? [Y/n] ", GetSplitMaxInputFileNumber());
fflush(stdout);
reply.Gets(stdin,kTRUE);
reply.ToLower();
}
if (reply.BeginsWith("n")) {
gSystem->Exec(Form("rm -f %s", wn.Data()));
continue;
} else reply = "y";
}
if (!dryRun)
{
TString dirwn = Form("%s/%s", runDir.Data(), wn.Data());
if (RemoteFileExists(dirwn.Data())) gGrid->Rm(dirwn.Data());
gSystem->Exec(Form("alien_cp file:%s alien://%s", wn.Data(), dirwn.Data()));
gSystem->Exec(Form("rm -f %s", wn.Data()));
}
TString query;
if (stage > 0) query = Form("submit %s %d %d", jdl.Data(), run, stage);
else query = Form("submit %s %d", jdl.Data(), run);
printf(" - %s ...", query.Data());
fflush(stdout);
if (dryRun)
{
AliInfo(" dry run");
continue;
}
Bool_t done = kFALSE;
TGridResult *res = gGrid->Command(query);
if (res)
{
TString cjobId1 = res->GetKey(0,"jobId");
if (!cjobId1.IsDec())
{
AliError(" FAILED");
gGrid->Stdout();
gGrid->Stderr();
}
else
{
AliInfo(Form(" DONE\n --> the job Id is: %s \n", cjobId1.Data()));
done = kTRUE;
}
delete res;
}
else
{
AliError(" FAILED");
}
if (!done)
{
gSystem->Exec(Form("echo %d >> __failed__", run));
failedRun = kTRUE;
}
}
if (failedRun)
{
AliInfo("\n--------------------\n");
AliInfo("list of failed runs:\n");
gSystem->Exec("cat __failed__");
gSystem->Exec("rm -f __failed__");
return kFALSE;
}
return kTRUE;
}
//______________________________________________________________________________
void AliMuonAccEffSubmitter::Print(Option_t* opt) const
{
/// Printout
AliMuonGridSubmitter::Print(opt);
if ( fRatio > 0 )
{
std::cout << std::endl << Form("-- For each run, will generate %5.2f times the number of real events for trigger %s",
fRatio,ReferenceTrigger().Data()) << std::endl;
}
else
{
std::cout << std::endl << Form("-- For each run, will generate %10d events",fFixedNofEvents) << std::endl;
}
std::cout << "-- MaxEventsPerChunk = " << fMaxEventsPerChunk << std::endl;
std::cout << "-- Will" << (UseOCDBSnapshots() ? "" : " NOT") << " use OCDB snaphosts" << std::endl;
}
//______________________________________________________________________________
Bool_t AliMuonAccEffSubmitter::Run(const char* mode)
{
/// mode can be one of (case insensitive)
///
/// LOCAL : copy the template files from the template directory to the local one
/// UPLOAD : copy the local files to the grid (requires LOCAL)
/// OCDB : make ocdb snapshots (requires LOCAL)
/// SUBMIT : submit the jobs (requires LOCAL + UPLOAD)
/// FULL : all of the above (requires all of the above)
///
/// TEST : as SUBMIT, but in dry mode (does not actually submit the jobs)
///
/// LOCALTEST : completely local test (including execution)
if (!IsValid()) return kFALSE;
TString smode(mode);
smode.ToUpper();
if ( smode == "FULL")
{
return ( Run("OCDB") && Run("UPLOAD") && Run("SUBMIT") );
}
if ( smode == "LOCAL")
{
return CopyTemplateFilesToLocal();
}
if ( smode == "UPLOAD" )
{
return (CopyLocalFilesToRemote());
}
if ( smode == "OCDB" )
{
Bool_t ok = Run("LOCAL");
if (ok)
{
ok = MakeOCDBSnapshots();
}
return ok;
}
if ( smode == "TEST" )
{
Bool_t ok = Run("OCDB") && Run("UPLOAD");
if ( ok )
{
ok = (Submit(kTRUE)>0);
}
return ok;
}
if ( smode == "FULL" )
{
Bool_t ok = Run("OCDB") && Run("UPLOAD");
if ( ok )
{
ok = (Submit(kFALSE)>0);
}
return ok;
}
if( smode == "SUBMIT" )
{
return (Submit(kFALSE)>0);
}
if ( smode == "LOCALTEST" )
{
Bool_t ok = Run("OCDB");
if ( ok )
{
ok = LocalTest();
}
return ok;
}
return kFALSE;
}
/// Set the variable to select the generator macro in Config.C
/// generator must contain the name of a macro (without the extension .C) containing
/// a function of the same name that returns a pointer to an AliGenerator.
/// (see the examples in the template directory). That macro must be compilable.
//______________________________________________________________________________
Bool_t AliMuonAccEffSubmitter::SetGenerator(const char* generator)
{
Invalidate();
TString generatorFile(Form("%s/%s.C",TemplateDir().Data(),generator));
Int_t nofMissingVariables(0);
// first check we indeed have such a macro
if (!gSystem->AccessPathName(generatorFile.Data()))
{
TObjArray* variables = GetVariables(generatorFile.Data());
TIter next(variables);
TObjString* var;
while ( ( var = static_cast<TObjString*>(next())) )
{
if ( !Vars()->GetValue(var->String()) )
{
++nofMissingVariables;
AliError(Form("file %s expect the variable %s to be defined, but we've not defined it !",generatorFile.Data(),var->String().Data()));
}
}
delete variables;
if ( !nofMissingVariables )
{
if (CheckCompilation(generatorFile.Data()))
{
Validate();
SetVar("VAR_GENERATOR",Form("%s",generator));
AddToTemplateFileList(Form("%s.C",generator));
return kTRUE;
}
}
else
{
return kFALSE;
}
}
else
{
AliError(Form("Can not work with the macro %s",generatorFile.Data()));
}
return kFALSE;
}
/// Sets the OCDB path to be used
//______________________________________________________________________________
void AliMuonAccEffSubmitter::SetOCDBPath(const char* ocdbPath)
{
SetMapKeyValue("OCDBPath",ocdbPath);
}
/// Change the remote directory used for snapshot
//______________________________________________________________________________
void AliMuonAccEffSubmitter::SetOCDBSnapshotDir(const char* dir)
{
if (gSystem->AccessPathName(Form("%s/OCDB",dir)))
{
AliError(Form("Snapshot top directory (%s) should contain an OCDB subdir with runnumbers in there",dir));
}
else
{
SetMapKeyValue("OCDBSnapshot",dir);
}
}
/// Specify that the number of simulated events to be produced should be proportional to
/// the number of real events of the given trigger.
/// \param trigger the reference trigger classname to be used
/// \param ratio the proportionality factor to be used (must be positive, can be < 1)
//______________________________________________________________________________
void AliMuonAccEffSubmitter::MakeNofEventsPropToTriggerCount(const char* trigger, Float_t ratio)
{
SetMapKeyValue("ReferenceTrigger",trigger);
fRatio = ratio;
}
/// Make the number of simulated events to be produced a specific one
//______________________________________________________________________________
void AliMuonAccEffSubmitter::MakeNofEventsFixed(Int_t nevents)
{
fFixedNofEvents = nevents;
fRatio=0.0;
SetMapKeyValue("ReferenceTrigger","");
}
//______________________________________________________________________________
Int_t AliMuonAccEffSubmitter::LocalTest()
{
/// Generate a local macro (simrun.sh) to execute locally a full scale test
/// Can only be used with a fixed number of events (and runnumber is fixed to zero)
if ( fRatio > 0 )
{
AliError("Can only work in local test with a fixed number of events");
return 0;
}
if ( fFixedNofEvents <= 0 )
{
AliError("Please fix the number of input events using MakeNofEventsFixed()");
return 0;
}
const std::vector<int>& runs = RunList();
if ( runs.empty() )
{
AliError("No run to work with");
return 0;
}
// std::cout << "Generating script to execute : ./simrun.sh" << std::endl;
//
// std::ofstream out("simrun.sh");
//
// out << "#!/bin/bash" << std::endl;
//// root.exe -b -q simrun.C --run <x> --chunk <y> --event <n>
// out << "root.exe -b -q simrun.C --run "<< runs[0] <<" --event " << fFixedNofEvents << std::endl;
//
// out.close();
gSystem->Exec("chmod +x simrun.sh");
gSystem->Exec("alien_cp alien:///alice/bin/aliroot_new file:");
gSystem->Exec("chmod u+x aliroot_new");
std::cout << "Cleaning up left-over files from previous simulation/reconstructions" << std::endl;
gSystem->Exec("rm -rf TrackRefs.root *.SDigits*.root Kinematics.root *.Hits.root geometry.root gphysi.dat Run*.tag.root HLT*.root *.ps *.Digits.root *.RecPoints.root galice.root *QA*.root Trigger.root *.log AliESD* AliAOD* *.d *.so *.stat pwgevents.lhe pwg*.dat pwg*.top pwhg_checklimits bornequiv FlavRegList");
if ( UseOCDBSnapshots() )
{
gSystem->Exec(Form("ln -si %s/OCDB/%d/OCDB_sim.root .",LocalSnapshotDir().Data(),runs[0]));
gSystem->Exec(Form("ln -si %s/OCDB/%d/OCDB_rec.root .",LocalSnapshotDir().Data(),runs[0]));
}
TString command = Form("./aliroot_new --run %i --event 1 --eventsPerJob %i", runs[0], fFixedNofEvents);
std::cout << "Executing the script : " << command.Data() << std::endl;
gSystem->Exec(command.Data());
return 1;
}
namespace {
void OutputRunList(const char* filename, const std::vector<int>& runlist)
{
/// output a runlist to ASCII file
std::ofstream out(filename);
for ( std::vector<int>::size_type j = 0; j < runlist.size(); ++j )
{
out << runlist[j] << std::endl;
}
}
}
//______________________________________________________________________________
void AliMuonAccEffSubmitter::SetCompactMode ( Int_t mode )
{
/// Set the compact mode:
/// 0 -> keep all root files + all logs
/// 1 -> keep only AOD.Muons + all logs
/// 2 -> keep only AODs and AOD.Muons + all logs
/// 10 -> keep all root files + stout,stderr
/// 11 -> keep only AOD.Muons + stout,stderr
/// 12 -> keep only AODs and AOD.Muons + stout,stderr
const char* allLogs = "stderr,stdout,*.log";
const char* minLogs = "stderr,stdout";
const char* allRoot = "galice*.root,Kinematics*.root,TrackRefs*.root,AliESDs.root,AliAOD.root,AliAOD.Muons.root,Merged.QA.Data.root,Run*.root";
const char* muonAodRoot = "AliAOD.Muons.root,Merged.QA.Data.root";
const char* aodRoot = "AliAOD.root,Merged.QA.Data.root";
fLogOutToKeep = "";
fRootOutToKeep = "";
switch (mode) {
case 0:
fLogOutToKeep = allLogs;
fRootOutToKeep = allRoot;
break;
case 1:
fLogOutToKeep = allLogs;
fRootOutToKeep = muonAodRoot;
break;
case 2:
fLogOutToKeep = allLogs;
fRootOutToKeep = aodRoot;
break;
case 10:
fLogOutToKeep = minLogs;
fRootOutToKeep = allRoot;
break;
case 11:
fLogOutToKeep = minLogs;
fRootOutToKeep = muonAodRoot;
break;
case 12:
fLogOutToKeep = minLogs;
fRootOutToKeep = aodRoot;
break;
default:
AliError(Form("Unknown CompactMode %i",mode));
break;
}
if ( ! fLogOutToKeep.IsNull() ) {
fLogOutToKeep.Prepend("log_archive.zip:");
fLogOutToKeep.Append("@disk=1");
}
if ( ! fRootOutToKeep.IsNull() ) {
fRootOutToKeep.Prepend("root_archive.zip:");
fRootOutToKeep.Append("@disk=2");
}
}
/// Initialize the variables to some default (possibly sensible) values
//____________________________________________________________________________
void AliMuonAccEffSubmitter::SetDefaultVariables()
{
SetVar("VAR_OCDB_PATH",Form("\"%s\"",OCDBPath().Data()));
SetVar("VAR_AOD_MERGE_FILES","\"AliAOD.root,AliAOD.Muons.root\"");
SetVar("VAR_EFFTASK_PTMIN","-1.");
SetVar("VAR_EXTRATASKS_CONFIGMACRO","\"\"");
SetVar("VAR_GENPARAM_INCLUDE","AliGenMUONlib.h");
SetVar("VAR_GENPARAM_NPART","1");
SetVar("VAR_GENPARAM_GENLIB_TYPE","AliGenMUONlib::kJpsi");
SetVar("VAR_GENPARAM_GENLIB_PARNAME","\"pPb 5.03\"");
SetVar("VAR_GENCORRHF_QUARK","5");
SetVar("VAR_GENCORRHF_ENERGY","5");
// some default values for J/psi
SetVar("VAR_GENPARAMCUSTOM_PDGPARTICLECODE","443");
// default values below are from J/psi p+Pb (from muon_calo pass)
SetVar("VAR_GENPARAMCUSTOM_Y_P0","4.08E5");
SetVar("VAR_GENPARAMCUSTOM_Y_P1","7.1E4");
SetVar("VAR_GENPARAMCUSTOM_PT_P0","1.13E9");
SetVar("VAR_GENPARAMCUSTOM_PT_P1","18.05");
SetVar("VAR_GENPARAMCUSTOM_PT_P2","2.05");
SetVar("VAR_GENPARAMCUSTOM_PT_P3","3.34");
// some default values for single muons
SetVar("VAR_GENPARAMCUSTOMSINGLE_PTMIN","0.3");
SetVar("VAR_GENPARAMCUSTOMSINGLE_PT_P0","135.137");
SetVar("VAR_GENPARAMCUSTOMSINGLE_PT_P1","0.555323");
SetVar("VAR_GENPARAMCUSTOMSINGLE_PT_P2","0.578374");
SetVar("VAR_GENPARAMCUSTOMSINGLE_PT_P3","10.1345");
SetVar("VAR_GENPARAMCUSTOMSINGLE_PT_P4","0.000232233");
SetVar("VAR_GENPARAMCUSTOMSINGLE_PT_P5","-0.924726");
SetVar("VAR_GENPARAMCUSTOMSINGLE_Y_P0","1.95551");
SetVar("VAR_GENPARAMCUSTOMSINGLE_Y_P1","-0.");
SetVar("VAR_GENPARAMCUSTOMSINGLE_Y_P2","-0.104761");
SetVar("VAR_GENPARAMCUSTOMSINGLE_Y_P3","0.");
SetVar("VAR_GENPARAMCUSTOMSINGLE_Y_P4","0.00311324");
// some default values for single muons ben
SetVar("VAR_GENPARAMCUSTOMSINGLEBEN_PTMIN","0.35");
SetVar("VAR_GENPARAMCUSTOMSINGLEBEN_PT_P0","135.137");
SetVar("VAR_GENPARAMCUSTOMSINGLEBEN_PT_P1","0.555323");
SetVar("VAR_GENPARAMCUSTOMSINGLEBEN_PT_P2","0.578374");
SetVar("VAR_GENPARAMCUSTOMSINGLEBEN_PT_P3","10.1345");
SetVar("VAR_GENPARAMCUSTOMSINGLEBEN_PT_P4","0.000232233");
SetVar("VAR_GENPARAMCUSTOMSINGLEBEN_PT_P5","-0.924726");
SetVar("VAR_GENPARAMCUSTOMSINGLEBEN_Y_P0","1.95551");
SetVar("VAR_GENPARAMCUSTOMSINGLEBEN_Y_P1","-0.104761");
SetVar("VAR_GENPARAMCUSTOMSINGLEBEN_Y_P2","0.00311324");
// some default values for GenBox
SetVar("VAR_GENMUBOX_PTMIN","0");
SetVar("VAR_GENMUBOX_PTMAX","20");
SetVar("VAR_GENMUBOX_YMIN","-4.1");
SetVar("VAR_GENMUBOX_YMAX","-2.4");
SetVar("VAR_PYTHIA8_CMS_ENERGY","8000");
SetVar("VAR_PYTHIA6_CMS_ENERGY","8000");
SetVar("VAR_POWHEG_INPUT","powheg_Z.input");
SetVar("VAR_POWHEG_EXEC","pwhg_main_Z");
SetVar("VAR_POWHEG_SCALE_EVENTS","1");
SetVar("VAR_PURELY_LOCAL","0");
SetVar("VAR_USE_RAW_ALIGN","1");
SetVar("VAR_SIM_ALIGNDATA","\"alien://folder=/alice/simulation/2008/v4-15-Release/Ideal\"");
SetVar("VAR_REC_ALIGNDATA","\"alien://folder=/alice/simulation/2008/v4-15-Release/Residual\"");
SetVar("VAR_USE_ITS_RECO","0");
SetVar("VAR_USE_MC_VERTEX","1");
SetVar("VAR_VERTEX_SIGMA_X","0.0025");
SetVar("VAR_VERTEX_SIGMA_Y","0.0029");
SetVar("VAR_TRIGGER_CONFIGURATION","");
SetVar("VAR_LHAPDF","liblhapdf");
SetVar("VAR_MUONMCMODE","1");
SetVar("VAR_PYTHIA8_SETENV","");
SetVar("VAR_PYTHIA6_SETENV","");
SetVar("VAR_NEEDS_PYTHIA6", "0");
SetVar("VAR_NEEDS_PYTHIA8", "0");
SetVar("VAR_MAKE_COMPACT_ESD","0");
}
/// Enter a mode where we don't need the Grid at all
/// Note that this is just for testing purposes as this is a bit
/// opposite to the very intent of this class ;-)
//____________________________________________________________________________
void AliMuonAccEffSubmitter::SetLocalOnly()
{
SetVar("VAR_OCDB_PATH","\"local://$ALICE_ROOT/OCDB\"");
SetVar("VAR_PURELY_LOCAL","1");
MakeNofEventsFixed(10);
}
/// Common setup (aka constructor) to the different ways to construct this object
//__________________________________________________________________________
void AliMuonAccEffSubmitter::SetupCommon(Bool_t localOnly)
{
UseOCDBSnapshots(kFALSE);
SetCompactMode(1);
AddIncludePath("-I$ALICE_ROOT/include");
SetOCDBPath("raw://");
SetDefaultVariables();
if (localOnly) {
SetLocalOnly();
}
SetLocalDirectory("Snapshot",LocalDir());
SetMaxEventsPerChunk(fMaxEventsPerChunk);
if (!localOnly)
{
MakeNofEventsPropToTriggerCount();
}
AddToTemplateFileList("CheckESD.C");
AddToTemplateFileList("CheckAOD.C");
AddToTemplateFileList("AODtrainsim.C", kTRUE);
// AddToTemplateFileList("validation.sh");
AddToTemplateFileList("Config.C");
AddToTemplateFileList("rec.C");
AddToTemplateFileList("sim.C");
AddToTemplateFileList("simrun.sh");
AddToTemplateFileList(RunJDLName().Data());
UseExternalConfig(fExternalConfig);
}
//______________________________________________________________________________
Bool_t AliMuonAccEffSubmitter::SetupCollision ( Double_t cmsEnergy, Int_t lhapdf, const char *nucleons, const char *collSystem, Int_t npdf, Int_t npdfErr )
{
/// Setup of the collision system
TString nucl(nucleons);
TString system(collSystem);
Bool_t checkConsistency = kTRUE;
if ( system.Contains("p") ) {
if ( ! nucl.Contains("p") ) checkConsistency = kFALSE;
if ( system == "pp" && nucl != "pp" ) checkConsistency = kFALSE;
}
if ( ! checkConsistency ) {
AliError(Form("Cannot have a %s nucleon collision in %s",nucleons,collSystem));
return kFALSE;
}
if ( system == "Pbp" && nucl == "pn" ) nucl = "np";
Int_t ih[2] = {1, 1};
for ( Int_t ipart=0; ipart<2; ipart++ ) {
if ( nucl[ipart] == 'n' ) ih[1-ipart] = 2;
}
Int_t zNumber[2] = {1,1};
Int_t aNumber[2] = {1,1};
if ( system == "pPb" || system == "PbPb" ) {
aNumber[0] = 208;
zNumber[0] = 82;
}
if ( system == "Pbp" || system == "PbPb") {
aNumber[1] = 208;
zNumber[1] = 82;
}
SetVar("VAR_PROJECTILE_NAME",Form("\"%s\"",(ih[0] == 2)?"n":"p"));
SetVar("VAR_PROJECTILE_A",Form("%i",aNumber[0]));
SetVar("VAR_PROJECTILE_Z",Form("%i",zNumber[0]));
SetVar("VAR_TARGET_NAME",Form("\"%s\"",(ih[1] == 2)?"n":"p"));
SetVar("VAR_TARGET_A",Form("%i",aNumber[1]));
SetVar("VAR_TARGET_Z",Form("%i",zNumber[1]));
SetVar("VAR_POWHEG_PROJECTILE",Form("%i",ih[0]));
SetVar("VAR_POWHEG_TARGET",Form("%i",ih[1]));
SetVar("VAR_PROJECTILE_ENERGY", Form("%gd0",cmsEnergy/2.));
SetVar("VAR_TARGET_ENERGY", Form("%gd0",cmsEnergy/2.));
// FIXME: this is ugly, but necessary to avoid a direct dependence on LHAPDF
const Int_t kNsets = 12;
Int_t lhaPdfSets[kNsets] = {19170,19150,19070,19050,80060,10040,10100,10050,10041,10042,10800,11000};
TString lhaPdfSetsPythia[kNsets] = {"kCTEQ4L","kCTEQ4M","kCTEQ5L","kCTEQ5M","kGRVLO98","kCTEQ6","kCTEQ61","kCTEQ6m","kCTEQ6l","kCTEQ6ll","kCT10","kCT10nlo"};
const Int_t kNnpdfSets = 4;
// EKS98 EPS08 EPS09LO EPS09NLO
Int_t npdfSetsPythia[kNnpdfSets] = {0, 8, 9, 19};
Int_t chosenSet = lhapdf;
if ( lhapdf >= kNsets ) {
for ( Int_t iset=0; iset<kNsets; iset++ ) {
if ( lhaPdfSets[iset] == lhapdf ) {
chosenSet = iset;
break;
}
}
}
if ( chosenSet >= kNsets ) {
AliError(Form("Cannot find PDF set %i",lhapdf));
return kFALSE;
}
Int_t chosenNpdfSet = npdf;
if ( npdf >= kNnpdfSets ) {
for ( Int_t iset=0; iset<kNnpdfSets; iset++ ) {
if ( npdfSetsPythia[iset] == npdf ) {
chosenNpdfSet = iset;
break;
}
}
}
if ( chosenNpdfSet >= kNnpdfSets ) {
AliError(Form("Cannot find PDF set %i",npdf));
return kFALSE;
}
SetVar("VAR_LHAPDF_STRUCFUNC_SET",lhaPdfSetsPythia[chosenSet].Data());
SetVar("VAR_NPDF_SET",Form("%i",npdfSetsPythia[chosenNpdfSet]));
SetVar("VAR_LHAPDF_SET",Form("%i",lhaPdfSets[chosenSet]));
SetVar("VAR_POWHEG_NPDF_SET",Form("%i",chosenNpdfSet));
SetVar("VAR_POWHEG_NPDF_ERR",Form("%i",npdfErr));
return kTRUE;
}
//______________________________________________________________________________
Bool_t AliMuonAccEffSubmitter::SetupPowheg ( const char *particle, const char* version )
{
/// Setup powheg
TString part(particle);
part.ToUpper();
TString pythiaProc = "";
TString baseName = "";
TString muonPtMin = "0.";
if ( part == "CHARM" ) {
pythiaProc = "kPyCharmPWHG";
SetVar("VAR_POWHEG_HVQ_MASS","1.5");
SetVar("VAR_POWHEG_HVQ_NCALL1","50000");
SetVar("VAR_POWHEG_HVQ_FOLDCSI","5");
baseName = "hvq";
}
else if ( part == "BEAUTY" ) {
pythiaProc = "kPyBeautyPWHG";
SetVar("VAR_POWHEG_HVQ_MASS","4.75");
SetVar("VAR_POWHEG_HVQ_NCALL1","10000");
SetVar("VAR_POWHEG_HVQ_FOLDCSI","2");
baseName = "hvq";
}
else if ( part == "WPLUS" || part == "WMINUS" ) {
pythiaProc = "kPyWPWHG";
SetVar("VAR_POWHEG_IDVECBOS",Form("%i",part.Contains("PLUS")?24:-24));
baseName = "W";
}
else if ( part == "Z" ) {
pythiaProc = "kPyWPWHG";
SetVar("VAR_POWHEG_ZMASS_LOW", "16");
muonPtMin = "8.";
baseName = "Z";
}
else {
AliError(Form("Unrecognized particle %s",particle));
return kFALSE;
}
TString powhegInput = Form("powheg_%s.input",baseName.Data());
SetVar("VAR_POWHEG_INPUT",powhegInput.Data());
SetVar("VAR_POWHEG_EXEC",Form("pwhg_main_%s",baseName.Data()));
SetVar("VAR_PYTHIA_POWHEG_PROCESS",pythiaProc.Data());
SetVar("VAR_CHILD_PT_MIN", muonPtMin.Data());
for ( Int_t ilist=0; ilist<2; ilist++ ) {
TObjArray* fileList = ( ilist == 0 ) ? TemplateFileList() : LocalFileList();
TIter next(fileList);
TObjString *str = 0x0;
while ( (str = static_cast<TObjString*>(next())) ) {
if ( str->String().Contains(".input") ) {
fileList->Remove(str);
break;
}
fileList->Compress();
}
}
AddToTemplateFileList(powhegInput.Data());
SetGeneratorPackage(Form("VO_ALICE@POWHEG::%s",version));
return kTRUE;
}
//______________________________________________________________________________
void AliMuonAccEffSubmitter::SetupPythia6 ( const char *version )
{
/// Setup pythia 6
SetVar("VAR_NEEDS_PYTHIA6", "1");
TString p6env = Form("gSystem->Load(\"libpythia6_%s\");",version);
SetVar("VAR_PYTHIA6_SETENV",p6env.Data());
gROOT->ProcessLine(p6env);
}
///______________________________________________________________________________
void AliMuonAccEffSubmitter::SetupPythia8 ( const char *version, const char* configStrings )
{
/// Setup pythia 6
SetVar("VAR_NEEDS_PYTHIA8", "1");
TString p8env = Form(" gSystem->Setenv(\"PYTHIA8DATA\", gSystem->ExpandPathName(\"$ALICE_ROOT/PYTHIA8/pythia%s/xmldoc\"));\n",version);
SetVar("VAR_PYTHIA8_SETENV",p8env.Data());
SetVar("VAR_PYTHIA8_SETUP_STRINGS",Form("\"%s\"",configStrings));
}
//______________________________________________________________________________
Int_t AliMuonAccEffSubmitter::SplitRunList(const char* inputList, int maxJobs)
{
/// In order to be able to submit, split a given runlist into chunks that will
/// fit within maxJobs (1500 for a typical user)
std::vector<int> runs;
AliAnalysisTriggerScalers tmp(inputList);
runs = tmp.GetRunList();
AliAnalysisTriggerScalers* ts(0x0);
std::vector<int> currentRunList;
int nJobs(0);
int nTotalJobs(0);
int nEvts(0);
int nFiles(0);
for (std::vector<int>::size_type i=0; i < runs.size(); ++i)
{
Int_t runNumber = runs[i];
Int_t nEvtRun(fFixedNofEvents);
if ( fRatio > 0 )
{
if (!ts)
{
AliInfo(Form("Creating AliAnalysisTriggerScalers from OCDB=%s",OCDBPath().Data()));
ts = new AliAnalysisTriggerScalers(runs,OCDBPath().Data());
}
AliAnalysisTriggerScalerItem* trigger = ts->GetTriggerScaler(runNumber, "L2A", ReferenceTrigger().Data());
if (!trigger)
{
AliError(Form("Could not get trigger %s for run %09d",ReferenceTrigger().Data(),runNumber));
continue;
}
nEvtRun = TMath::Nint(fRatio * trigger->Value());
}
Int_t nChunk = 1;
while (nEvtRun/nChunk+0.5 > MaxEventsPerChunk())
{
++nChunk;
}
Int_t nEvtChunk = TMath::Nint(nEvtRun/nChunk + 0.5);
nJobs += nChunk;
nTotalJobs += nChunk;
nEvts += nChunk*nEvtChunk;
if ( nJobs > maxJobs )
{
++nFiles;
OutputRunList(Form("%s.%d",inputList,nFiles),currentRunList);
nJobs = 0;
currentRunList.clear();
}
currentRunList.push_back(runNumber);
}
if ( !currentRunList.empty() )
{
++nFiles;
OutputRunList(Form("%s.%d",inputList,nFiles),currentRunList);
}
delete ts;
std::cout << Form("input run list was split into %d files. Total number of jobs %d. Total number of events %d",
nFiles,nTotalJobs,nEvts) << std::endl;
return nFiles;
}
//______________________________________________________________________________
Int_t AliMuonAccEffSubmitter::Submit(Bool_t dryRun)
{
/// Submit multiple production jobs with the format "submit jdl 000run#.xml 000run#".
///
/// Return the number of submitted (master) jobs
///
/// Example:
/// - outputDir = "/alice/cern.ch/user/p/ppillot/Sim/LHC10h/JPsiPbPb276/AlignRawVtxRaw/ESDs"
/// - runList must contains the list of run number
/// - trigger is the (fully qualified) trigger name used to compute the base number of events
/// - mult is the factor to apply to the number of trigger to get the number of events to be generated
/// (# generated events = # triggers x mult
if (!IsValid()) return 0;
AliDebug(1,"");
gGrid->Cd(RemoteDir());
if (!RemoteFileExists(RunJDLName()))
{
AliError(Form("file %s does not exist in %s", RunJDLName().Data(), RemoteDir().Data()));
return 0;
}
if ( !NofRuns() )
{
AliError("No run list set. Use SetRunList");
return 0;
}
const std::vector<int>& runs = RunList();
if (runs.empty())
{
AliError("No run to work with");
return 0;
}
// cout << "total number of selected MB events = " << totEvt << endl;
// cout << "required number of generated events = " << nGenEvents << endl;
// cout << "number of generated events per MB event = " << ratio << endl;
// cout << endl;
std::cout << "run\tfirstChunk\tlastChunk\teventsPerJob" << std::endl;
std::cout << "----------------------" << std::endl;
Int_t nJobs(0);
Int_t nEvts(0);
Bool_t failedRun(kFALSE);
AliAnalysisTriggerScalers* ts(0x0);
for (std::vector<int>::size_type i=0; i < runs.size(); ++i)
{
Int_t runNumber = runs[i];
Int_t nEvtRun(fFixedNofEvents);
if ( fRatio > 0 )
{
if (!ts)
{
AliInfo(Form("Creating AliAnalysisTriggerScalers from OCDB=%s",OCDBPath().Data()));
ts = new AliAnalysisTriggerScalers(runs,OCDBPath().Data());
}
AliAnalysisTriggerScalerItem* trigger = ts->GetTriggerScaler(runNumber, "L2A", ReferenceTrigger().Data());
if (!trigger)
{
AliError(Form("Could not get trigger %s for run %09d",ReferenceTrigger().Data(),runNumber));
continue;
}
nEvtRun = TMath::Nint(fRatio * trigger->Value());
}
Int_t nChunk = nEvtRun/MaxEventsPerChunk();
if ( nChunk == 0 ) nChunk++;
Int_t nEvtChunk = 0, delta = MaxEventsPerChunk();
for ( Int_t tmpnChunk=nChunk; tmpnChunk<=nChunk+1; tmpnChunk++ ) {
Int_t tmpnEventChunk = TMath::Min(nEvtRun/tmpnChunk,MaxEventsPerChunk());
Int_t tmpDelta = TMath::Abs(tmpnChunk*tmpnEventChunk-nEvtRun);
if ( tmpDelta < delta ) {
nChunk = tmpnChunk;
nEvtChunk = tmpnEventChunk;
delta = tmpDelta;
}
}
nJobs += nChunk;
nEvts += nChunk*nEvtChunk;
std::cout << runNumber << "\t1\t" << nChunk << "\t" << nEvtChunk << std::endl;
TString query(Form("submit %s %d 1 %d %d", RunJDLName().Data(), runNumber, nChunk, nEvtChunk));
std::cout << query.Data() << " ..." << std::flush;
TGridResult* res = 0x0;
if (!dryRun)
{
res = gGrid->Command(query);
}
Bool_t done = kFALSE;
if (res)
{
TString cjobId1 = res->GetKey(0,"jobId");
if (!cjobId1.Length())
{
std::cout << " FAILED" << std::endl << std::endl;
gGrid->Stdout();
gGrid->Stderr();
}
else
{
std::cout << "DONE" << std::endl;
std::cout << Form(" --> the job Id is: %s",cjobId1.Data()) << std::endl << std::endl;
done = kTRUE;
}
}
else
{
std::cout << " FAILED" << std::endl << std::endl;
}
if (!dryRun && !done)
{
gSystem->Exec(Form("echo %d >> __failed__", runNumber));
failedRun = kTRUE;
}
delete res;
}
std::cout << std::endl
<< "total number of jobs = " << nJobs << std::endl
<< "total number of generated events = " << nEvts << std::endl
<< std::endl;
if (failedRun)
{
AliInfo("\n--------------------\n");
AliInfo("list of failed runs:\n");
gSystem->Exec("cat __failed__");
gSystem->Exec("rm -f __failed__");
}
delete ts;
return nJobs;
}
//______________________________________________________________________________
void AliMuonAccEffSubmitter::UpdateLocalFileList(Bool_t clearSnapshots)
{
/// Update the list of local files
AliMuonGridSubmitter::UpdateLocalFileList();
if (!NofRuns()) return;
if ( clearSnapshots )
{
TIter next(LocalFileList());
TObjString* file;
while ( ( file = static_cast<TObjString*>(next())) )
{
if ( file->String().Contains("OCDB_") )
{
LocalFileList()->Remove(file);
}
}
LocalFileList()->Compress();
}
const char* type[] = { "sim","rec" };
const std::vector<int>& runs = RunList();
for ( std::vector<int>::size_type i = 0; i < runs.size(); ++i )
{
Int_t runNumber = runs[i];
for ( Int_t t = 0; t < 2; ++t )
{
TString snapshot(Form("%s/OCDB/%d/OCDB_%s.root",LocalSnapshotDir().Data(),runNumber,type[t]));
if ( !gSystem->AccessPathName(snapshot.Data()) )
{
AddToLocalFileList(snapshot);
}
}
}
}
/// Whether or not we should use OCDB snapshots
//______________________________________________________________________________
Bool_t AliMuonAccEffSubmitter::UseOCDBSnapshots() const
{
return GetVar("VAR_OCDB_SNAPSHOT")=="kTRUE";
}
//______________________________________________________________________________
void AliMuonAccEffSubmitter::UseOCDBSnapshots(Bool_t flag)
{
/// Whether or not to use OCDB snapshots
/// Using OCDB snapshots will speed-up both the sim and reco initialization
/// phases on each worker node, but takes time to produce...
/// So using them is not always a win-win...
if ( flag )
{
SetVar("VAR_OCDB_SNAPSHOT","kTRUE");
}
else
{
SetVar("VAR_OCDB_SNAPSHOT","kFALSE");
}
UpdateLocalFileList();
}
//______________________________________________________________________________
void AliMuonAccEffSubmitter::UseAODMerging(Bool_t flag)
{
/// whether or not we should generate JDL for merging AODs
fUseAODMerging = flag;
AddToTemplateFileList(MergeJDLName(kFALSE).Data());
AddToTemplateFileList(MergeJDLName(kTRUE).Data());
AddToTemplateFileList("AOD_merge.sh");
AddToTemplateFileList("validation_merge.sh");
}
/// Use an external config (or the default Config.C if externalConfigFullFilePath="")
//______________________________________________________________________________
void AliMuonAccEffSubmitter::UseExternalConfig(const char* externalConfigFullFilePath)
{
fExternalConfig = externalConfigFullFilePath;
if ( fExternalConfig.Length() > 0 )
{
AddToTemplateFileList(fExternalConfig);
}
else
{
AddToTemplateFileList("Config.C");
}
}
| 29.843632 | 314 | 0.655223 |
76e571f497eee37ee1d1c998d036ab36c27fb434 | 407 | cpp | C++ | atcoder.jp/abc176/abc176_c/Main.cpp | shikij1/AtCoder | 7ae2946efdceaea3cc8725e99a2b9c137598e2f8 | [
"MIT"
] | null | null | null | atcoder.jp/abc176/abc176_c/Main.cpp | shikij1/AtCoder | 7ae2946efdceaea3cc8725e99a2b9c137598e2f8 | [
"MIT"
] | null | null | null | atcoder.jp/abc176/abc176_c/Main.cpp | shikij1/AtCoder | 7ae2946efdceaea3cc8725e99a2b9c137598e2f8 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main()
{
long long n;
cin >> n;
vector<long long> a(n);
for (long long i = 0; i < n; i++)
{
cin >> a[i];
}
long long sum = 0;
for (long long i = 1; i < n; i++)
{
if (a[i - 1] - a[i] > 0)
{
sum += a[i - 1] - a[i];
a[i] = a[i - 1];
}
}
cout << sum << endl;
}
| 17.695652 | 37 | 0.36855 |
76e80425e6f570ee6e75f0f24157922dde924e0f | 14,289 | cc | C++ | tile/lang/gen_special.cc | redoclag/plaidml | 46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314 | [
"Apache-2.0"
] | 4,535 | 2017-10-20T05:03:57.000Z | 2022-03-30T15:42:33.000Z | tile/lang/gen_special.cc | HOZHENWAI/plaidml | 46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314 | [
"Apache-2.0"
] | 984 | 2017-10-20T17:16:09.000Z | 2022-03-30T05:43:18.000Z | tile/lang/gen_special.cc | HOZHENWAI/plaidml | 46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314 | [
"Apache-2.0"
] | 492 | 2017-10-20T18:22:32.000Z | 2022-03-30T09:00:05.000Z |
#include "tile/lang/gen_special.h"
#include <exception>
#include <map>
#include <memory>
#include <utility>
#include "base/util/logging.h"
#include "tile/lang/gid.h"
#include "tile/lang/ops.h"
#include "tile/lang/sembuilder.h"
#include "tile/lang/semprinter.h"
namespace vertexai {
namespace tile {
namespace lang {
static void GenGather(KernelList& r, const Op& op, const Bindings& bindings, // NOLINT(runtime/references)
const std::string& kname, const HardwareSettings& settings) {
using namespace vertexai::tile::sem::builder; // NOLINT
IVLOG(3, "Making a gather");
// Extract shapes to locals
const TensorShape out_shape = bindings.at(op.output).shape;
const TensorShape data_shape = bindings.at(op.inputs[0]).shape;
const TensorShape idx_shape = bindings.at(op.inputs[1]).shape;
// Make an empty function body
auto body = _Block({});
// Generate expressions for the GIDs.
std::vector<size_t> lidx_sizes;
for (const auto& d : idx_shape.dims) {
lidx_sizes.push_back(d.size);
}
for (const auto& d : data_shape.dims) {
lidx_sizes.push_back(d.size);
}
auto gids = gid::MakeMap(settings.goal_dimension_sizes, lidx_sizes);
std::vector<sem::ExprPtr> gid_vars;
gid_vars.reserve(gids.gid_sizes.size());
for (std::size_t idx = 0; idx < gids.gid_sizes.size(); ++idx) {
std::string var = "gidx" + std::to_string(idx);
body->append(_Declare({sem::Type::INDEX}, var, _Index(sem::IndexExpr::GLOBAL, idx)));
gid_vars.push_back(_(var));
}
// Generate expressions for the logical dimension indicies.
std::vector<sem::ExprPtr> lid_vars;
lid_vars.reserve(gids.dims.size());
for (std::size_t idx = 0; idx < gids.dims.size(); ++idx) {
std::string var = "lidx" + std::to_string(idx);
auto index = gid::LogicalIndex(gid_vars, gids.dims[idx]);
body->append(_Declare({sem::Type::INDEX}, var, index));
lid_vars.push_back(_(var));
}
// Generate the output offset
sem::ExprPtr out_offset = _Const(0);
for (size_t i = 0; i < out_shape.dims.size(); i++) {
if (i < idx_shape.dims.size()) {
out_offset = out_offset + lid_vars[i] * out_shape.dims[i].stride;
} else {
out_offset = out_offset + lid_vars[i + 1] * out_shape.dims[i].stride;
}
}
// Generate the index offset
sem::ExprPtr idx_offset = _Const(0);
for (size_t i = 0; i < idx_shape.dims.size(); i++) {
idx_offset = idx_offset + lid_vars[i] * idx_shape.dims[i].stride;
}
// Generate the data offset
sem::ExprPtr data_offset = _Clamp(_("idx")[idx_offset], _Const(0), _Const(data_shape.dims[0].size - 1));
data_offset = data_offset * data_shape.dims[0].stride;
for (size_t i = 1; i < data_shape.dims.size(); i++) {
data_offset = data_offset + lid_vars[idx_shape.dims.size() + i] * data_shape.dims[i].stride;
}
// Copy the data across
body->append(_("out")[out_offset] = _("data")[data_offset]);
// Build function params
sem::Function::params_t params;
params.push_back(std::make_pair(sem::Type(sem::Type::POINTER_MUT, out_shape.type, 1, 0, sem::Type::GLOBAL), "out"));
params.push_back(
std::make_pair(sem::Type(sem::Type::POINTER_CONST, data_shape.type, 1, 0, sem::Type::GLOBAL), "data"));
params.push_back(std::make_pair(sem::Type(sem::Type::POINTER_CONST, idx_shape.type, 1, 0, sem::Type::GLOBAL), "idx"));
// Set kernel info
KernelInfo ki;
ki.kname = kname;
ki.outputs.push_back(op.output);
ki.inputs.push_back(r.var_rewrites.Lookup(op.inputs[0]));
ki.inputs.push_back(r.var_rewrites.Lookup(op.inputs[1]));
ki.kfunc = std::make_shared<sem::Function>(kname, sem::Type(sem::Type::TVOID), params, body);
auto grids = gid::ComputeGrids(gids, settings.threads);
uint64_t out_size = out_shape.elem_size();
ki.gwork = grids.first;
ki.lwork = grids.second;
ki.tot_bytes = out_size * ((bit_width(out_shape.type) + 7) / 8);
ki.tot_flops = out_size;
auto pb = ki.info.mutable_special();
pb->set_fn(op.f.fn);
ki.info.set_flops(ki.tot_flops);
ki.info.set_bytes(ki.tot_bytes);
// Dump the code
sem::Print dump(*ki.kfunc);
IVLOG(4, "CODE:\n" << dump.str());
IVLOG(4, "gwork: " << ki.gwork << ", lwork: " << ki.lwork);
// Add to kernel list
r.kernels.push_back(ki);
}
static void GenScatter(KernelList& r, const Op& op, const Bindings& bindings, // NOLINT(runtime/references)
const std::string& kname, const HardwareSettings& settings) {
using namespace vertexai::tile::sem::builder; // NOLINT
IVLOG(3, "Making a scatter");
// Extract shapes to locals
const TensorShape out_shape = bindings.at(op.output).shape;
const TensorShape expn_shape = bindings.at(op.inputs[0]).shape;
const TensorShape idx_shape = bindings.at(op.inputs[1]).shape;
const TensorShape val_shape = bindings.at(op.inputs[2]).shape;
// Make an empty function body
auto body = _Block({});
// Generate expressions for the GIDs.
std::vector<size_t> lidx_sizes;
for (size_t i = idx_shape.dims.size(); i < expn_shape.dims.size(); ++i) {
lidx_sizes.push_back(expn_shape.dims[i].size);
}
auto gids = gid::MakeMap(settings.goal_dimension_sizes, lidx_sizes);
std::vector<sem::ExprPtr> gid_vars;
gid_vars.reserve(gids.gid_sizes.size());
for (std::size_t idx = 0; idx < gids.gid_sizes.size(); ++idx) {
std::string var = "gidx" + std::to_string(idx);
body->append(_Declare({sem::Type::INDEX}, var, _Index(sem::IndexExpr::GLOBAL, idx)));
gid_vars.push_back(_(var));
}
// Generate expressions for the logical dimension indicies.
std::vector<sem::ExprPtr> lid_vars;
lid_vars.reserve(gids.dims.size());
for (std::size_t idx = 0; idx < gids.dims.size(); ++idx) {
std::string var = "lidx" + std::to_string(idx);
auto index = gid::LogicalIndex(gid_vars, gids.dims[idx]);
body->append(_Declare({sem::Type::INDEX}, var, index));
lid_vars.push_back(_(var));
}
// inner is what will be inside the for loops over the index dimensions
auto inner = _Block({});
// Generate the expansion offset
sem::ExprPtr expn_offset = _Const(0);
for (size_t i = 0; i < expn_shape.dims.size(); i++) {
if (i < idx_shape.dims.size()) {
expn_offset = expn_offset + _("i_" + std::to_string(i)) * expn_shape.dims[i].stride;
} else {
expn_offset = expn_offset + lid_vars[i - idx_shape.dims.size()] * expn_shape.dims[i].stride;
}
}
inner->append(_Declare({sem::Type::INDEX}, "expn_offset", expn_offset));
// Generate the index offset
sem::ExprPtr idx_offset = _Const(0);
for (size_t i = 0; i < idx_shape.dims.size(); i++) {
idx_offset = idx_offset + _("i_" + std::to_string(i)) * idx_shape.dims[i].stride;
}
inner->append(_Declare({sem::Type::INDEX}, "idx_offset", idx_offset));
// Generate the output offset
sem::ExprPtr out_offset = _Clamp(_("idx")[_("idx_offset")], _Const(0), _Const(out_shape.dims[0].size - 1));
out_offset = out_offset * out_shape.dims[0].stride;
for (size_t i = 1; i < out_shape.dims.size(); i++) {
out_offset = out_offset + lid_vars[i - 1] * out_shape.dims[i].stride;
}
inner->append(_Declare({sem::Type::INDEX}, "out_offset", out_offset));
// Add in this entry
inner->append(_("out")[_("out_offset")] = _("out")[_("out_offset")] + _("expn")[_("expn_offset")]);
// Loop over the index dimensions
for (size_t i = 0; i < idx_shape.dims.size(); ++i) {
auto next = _Block({});
next->append(_For("i_" + std::to_string(i), idx_shape.dims[i].size, 1, inner));
inner = next;
}
body->append(inner);
// Build function params
sem::Function::params_t params;
params.push_back(std::make_pair(sem::Type(sem::Type::POINTER_MUT, out_shape.type, 1, 0, sem::Type::GLOBAL), "out"));
params.push_back(
std::make_pair(sem::Type(sem::Type::POINTER_CONST, expn_shape.type, 1, 0, sem::Type::GLOBAL), "expn"));
params.push_back(std::make_pair(sem::Type(sem::Type::POINTER_CONST, idx_shape.type, 1, 0, sem::Type::GLOBAL), "idx"));
// Set kernel info
KernelInfo ki;
ki.kname = kname;
ki.outputs.push_back(op.output);
ki.inputs.push_back(r.var_rewrites.Lookup(op.inputs[0]));
ki.inputs.push_back(r.var_rewrites.Lookup(op.inputs[1]));
ki.kfunc = std::make_shared<sem::Function>(kname, sem::Type(sem::Type::TVOID), params, body);
auto grids = gid::ComputeGrids(gids, settings.threads);
uint64_t out_size = out_shape.elem_size();
ki.gwork = grids.first;
ki.lwork = grids.second;
ki.tot_bytes = out_size * ((bit_width(out_shape.type) + 7) / 8);
ki.tot_flops = out_size;
auto pb = ki.info.mutable_special();
pb->set_fn(op.f.fn);
ki.info.set_flops(ki.tot_flops);
ki.info.set_bytes(ki.tot_bytes);
// Dump the code
sem::Print dump(*ki.kfunc);
IVLOG(4, "CODE:\n" << dump.str());
IVLOG(4, "gwork: " << ki.gwork << ", lwork: " << ki.lwork);
// Add to kernel list
r.kernels.push_back(ki);
}
static void GenShape(KernelList& r, const Op& op, const Bindings& bindings, // NOLINT(runtime/references)
const std::string& kname, const HardwareSettings& setting) {
using namespace vertexai::tile::sem::builder; // NOLINT
IVLOG(3, "Making a shape");
// Extract shapes to locals
const TensorShape out_shape = bindings.at(op.output).shape;
const TensorShape data_shape = bindings.at(op.inputs[0]).shape;
// Make an empty function body
auto body = _Block({});
for (int i = 0; i < data_shape.dims.size(); i++) {
sem::ExprPtr out_offset = _Const(i);
body->append(_("out")[out_offset] = data_shape.dims[i].size);
}
sem::Function::params_t params;
params.push_back(std::make_pair(sem::Type(sem::Type::POINTER_MUT, out_shape.type, 1, 0, sem::Type::GLOBAL), "out"));
KernelInfo ki;
ki.kname = kname;
ki.outputs.push_back(op.output);
ki.kfunc = std::make_shared<sem::Function>(kname, sem::Type(sem::Type::TVOID), params, body);
uint64_t out_size = out_shape.elem_size();
IVLOG(4, "OUT_SIZE:\n" << out_size);
ki.gwork = {{1, 1, 1}};
ki.lwork = {{1, 1, 1}};
ki.tot_bytes = out_size * ((bit_width(out_shape.type) + 7) / 8);
ki.tot_flops = out_size;
auto pb = ki.info.mutable_special();
pb->set_fn(op.f.fn);
ki.info.set_flops(ki.tot_flops);
ki.info.set_bytes(ki.tot_bytes);
// Dump the code
sem::Print dump(*ki.kfunc);
IVLOG(4, "CODE:\n" << dump.str());
// Add to kernel list
r.kernels.push_back(ki);
}
static void GenPRNG(KernelList& r, const Op& op, const Bindings& bindings, // NOLINT(runtime/references)
const std::string& kname, const HardwareSettings& setting) {
using namespace vertexai::tile::sem::builder; // NOLINT
IVLOG(3, "Making PRNG");
if (op.inputs.size() < 1) {
throw std::runtime_error("prng must have at least one parameter");
}
if (op.f.params.size() != 2) {
throw std::runtime_error("prng not properly part of triple");
}
std::string sout = op.f.params[0];
std::string vout = op.f.params[1];
// Extract shapes to locals
const TensorShape out_shape = bindings.at(vout).shape;
// Predeclare types for nice syntax
auto idx_type = sem::Type(sem::Type::INDEX);
auto uint32_type = sem::Type(sem::Type::VALUE, DataType::UINT32);
auto float_type = sem::Type(sem::Type::VALUE, DataType::FLOAT32);
// Make function body
auto body = _Block({});
body->append(_Declare(idx_type, "i", _Index(sem::IndexExpr::GLOBAL, 0)));
body->append(_Declare(uint32_type, "s1", _("state_in")[_("i") + 0 * k_rng_size]));
body->append(_Declare(uint32_type, "s2", _("state_in")[_("i") + 1 * k_rng_size]));
body->append(_Declare(uint32_type, "s3", _("state_in")[_("i") + 2 * k_rng_size]));
auto loop = _Block({});
loop->append(_("s1") = (((_("s1") & 4294967294) << 12) ^ (((sem::ExprPtr(_("s1")) << 13) ^ _("s1")) >> 19)));
loop->append(_("s2") = (((_("s2") & 4294967288) << 4) ^ (((sem::ExprPtr(_("s2")) << 2) ^ _("s2")) >> 25)));
loop->append(_("s3") = (((_("s3") & 4294967280) << 17) ^ (((sem::ExprPtr(_("s3")) << 3) ^ _("s3")) >> 11)));
loop->append(_("out")[_("i")] = _Cast(float_type, _("s1") ^ _("s2") ^ _("s3")) / _Const(4294967296.0));
loop->append(_("i") = _("i") + k_rng_size);
body->append(_While(_("i") < out_shape.elem_size(), loop));
body->append(_("i") = _Index(sem::IndexExpr::GLOBAL, 0));
body->append(_("state_out")[_("i") + 0 * k_rng_size] = _("s1"));
body->append(_("state_out")[_("i") + 1 * k_rng_size] = _("s2"));
body->append(_("state_out")[_("i") + 2 * k_rng_size] = _("s3"));
sem::Function::params_t params;
params.push_back(
std::make_pair(sem::Type(sem::Type::POINTER_MUT, DataType::FLOAT32, 1, 0, sem::Type::GLOBAL), "out"));
params.push_back(
std::make_pair(sem::Type(sem::Type::POINTER_MUT, DataType::UINT32, 1, 0, sem::Type::GLOBAL), "state_out"));
params.push_back(
std::make_pair(sem::Type(sem::Type::POINTER_CONST, DataType::UINT32, 1, 0, sem::Type::GLOBAL), "state_in"));
KernelInfo ki;
ki.kname = kname;
ki.outputs.push_back(vout);
ki.outputs.push_back(sout);
ki.inputs.push_back(r.var_rewrites.Lookup(op.inputs[0]));
ki.kfunc = std::make_shared<sem::Function>(kname, sem::Type(sem::Type::TVOID), params, body);
uint64_t out_size = out_shape.elem_size();
ki.gwork = {{k_rng_size, 1, 1}};
ki.lwork = {{size_t(setting.threads), 1, 1}};
ki.tot_bytes = out_size * ((bit_width(out_shape.type) + 7) / 8);
ki.tot_flops = out_size;
auto pb = ki.info.mutable_special();
pb->set_fn(op.f.fn);
ki.info.set_flops(ki.tot_flops);
ki.info.set_bytes(ki.tot_bytes);
// Dump the code
sem::Print dump(*ki.kfunc);
IVLOG(3, "CODE:\n" << dump.str());
// Add to kernel list
r.kernels.push_back(ki);
}
void GenSpecial(KernelList& r, const Op& op, const Bindings& bindings, // NOLINT(runtime/references)
const std::string& kname, const HardwareSettings& settings) {
IVLOG(3, "Making special kernel " << op.f.fn);
if (op.f.fn == "gather") {
GenGather(r, op, bindings, kname, settings);
} else if (op.f.fn == "scatter") {
GenScatter(r, op, bindings, kname, settings);
} else if (op.f.fn == "shape") {
GenShape(r, op, bindings, kname, settings);
} else if (op.f.fn == "prng_step") {
GenPRNG(r, op, bindings, kname, settings);
} else {
throw std::runtime_error("Unknown special function");
}
}
} // namespace lang
} // namespace tile
} // namespace vertexai
| 39.472376 | 120 | 0.654629 |
76e865181b8b8475f8930cbeb4ae1fcc7ea85a41 | 1,131 | cpp | C++ | StatisticsCollector/CollectStatistics.cpp | kozlov-andrey/anync-glbufferdata-bench | ca95752cd3857e9d6bc31162168c0a8658533831 | [
"Unlicense"
] | null | null | null | StatisticsCollector/CollectStatistics.cpp | kozlov-andrey/anync-glbufferdata-bench | ca95752cd3857e9d6bc31162168c0a8658533831 | [
"Unlicense"
] | null | null | null | StatisticsCollector/CollectStatistics.cpp | kozlov-andrey/anync-glbufferdata-bench | ca95752cd3857e9d6bc31162168c0a8658533831 | [
"Unlicense"
] | null | null | null | #include "CollectStatistics.h"
#include "Time.h"
#include "GLRenderer.h"
#include <iostream>
#include <fstream>
#include <map>
void collect_statistics(
std::function<void()> swap_func,
std::function<void()> create_context,
std::function<void()> destroy_context,
int width,
int height,
const char *output_path)
{
GLRenderer renderer(width, height, create_context, destroy_context);
std::vector<double> fps_statistics;
std::ofstream file(std::string(output_path) + "statistics.txt");
const auto policies = {
BufferUploadingPolicy::NoUploading,
BufferUploadingPolicy::WorkerThreadUploading,
BufferUploadingPolicy::MainThreadUploading
};
for (const auto policy : policies)
{
renderer.Setup(policy);
renderer.StartWorker();
const auto time_start = time_now();
const auto frame_count = 100;
for (int i = 0; i < frame_count; ++i)
{
renderer.Draw();
swap_func();
}
renderer.StopWorker();
const auto time_end = time_now();
fps_statistics.push_back(frame_count / ((time_end - time_start) / 1000000000.));
}
for (const auto fps : fps_statistics)
{
file << fps << std::endl;
}
}
| 20.196429 | 82 | 0.712644 |
76ec34d5e9013b663a976d1ec8b0e86c06081e50 | 650 | cpp | C++ | Sources/CryGame C++/Solution1/STLPORT/test/regression/lexcmp1.cpp | fromasmtodisasm/CryENGINE_MOD_SDK | 0b242ffcf615cdc0177f6c96b03b4d60a4338321 | [
"FSFAP"
] | 14 | 2016-05-09T01:14:03.000Z | 2021-10-12T21:41:02.000Z | src/STLport/test/regression/lexcmp1.cpp | aestesis/elektronika | 870f72ca7f64942f8316b3cd8f733f43c7d2d117 | [
"Apache-2.0"
] | null | null | null | src/STLport/test/regression/lexcmp1.cpp | aestesis/elektronika | 870f72ca7f64942f8316b3cd8f733f43c7d2d117 | [
"Apache-2.0"
] | 6 | 2015-08-19T01:28:54.000Z | 2020-10-25T05:17:08.000Z | // STLport regression testsuite component.
// To compile as a separate example, please #define MAIN.
#include <iostream>
#include <algorithm>
#ifdef MAIN
#define lexcmp1_test main
#endif
#if !defined (STLPORT) || defined(__STL_USE_NAMESPACES)
using namespace std;
#endif
int lexcmp1_test(int, char**)
{
cout<<"Results of lexcmp1_test:"<<endl;
const unsigned size = 6;
char n1[size] = "shoe";
char n2[size] = "shine";
bool before = lexicographical_compare(n1, n1 + size, n2, n2 + size);
if(before)
cout << n1 << " is before " << n2 << endl;
else
cout << n2 << " is before " << n1 << endl;
return 0;
}
| 23.214286 | 71 | 0.64 |
76f414310d4339aaf3d0b460446f0cf8c02a9f17 | 1,078 | cpp | C++ | Photon/photon/util/Transform.cpp | tatjam/Photon | a0c1584d10e1422cc2e468a6f94351a8310b7599 | [
"MIT"
] | 1 | 2017-05-28T12:10:30.000Z | 2017-05-28T12:10:30.000Z | Photon/photon/util/Transform.cpp | tatjam/Photon | a0c1584d10e1422cc2e468a6f94351a8310b7599 | [
"MIT"
] | null | null | null | Photon/photon/util/Transform.cpp | tatjam/Photon | a0c1584d10e1422cc2e468a6f94351a8310b7599 | [
"MIT"
] | null | null | null | #include "Transform.h"
namespace ph
{
glm::mat4 Transform::buildMatrix()
{
mat = glm::mat4();
mat = glm::translate(mat, pos);
glm::mat4 rotm = glm::mat4_cast(rot);
mat *= rotm;
mat = glm::scale(mat, scale);
return mat;
}
void Transform::rotEuler(glm::vec3 eu)
{
glm::quat qP = glm::angleAxis(glm::radians(eu.x), glm::vec3(1, 0, 0));
glm::quat qY = glm::angleAxis(glm::radians(eu.y), glm::vec3(0, 1, 0));
glm::quat qR = glm::angleAxis(glm::radians(eu.z), glm::vec3(0, 0, 1));
rot = qP * qY * qR;
}
glm::vec3 Transform::getEuler()
{
return glm::eulerAngles(rot);
}
void Transform::move(glm::vec3 o)
{
pos += o;
buildMatrix();
}
void Transform::rotate(glm::vec3 eu)
{
glm::vec3 curr = getEuler();
curr += eu;
glm::quat qP = glm::angleAxis(glm::radians(curr.x), glm::vec3(1, 0, 0));
glm::quat qY = glm::angleAxis(glm::radians(curr.y), glm::vec3(0, 1, 0));
glm::quat qR = glm::angleAxis(glm::radians(curr.z), glm::vec3(0, 0, 1));
rot = qP * qY * qR;
}
Transform::Transform()
{
}
Transform::~Transform()
{
}
}
| 17.966667 | 74 | 0.59462 |
76f529c822bc107727ad263e023f4c0149759b69 | 1,576 | hpp | C++ | redist/inc/imqdst.hpp | gmarcon83/mq-mqi-nodejs | 27d44772254d0d76438022c6305277f603ff6acb | [
"Apache-2.0"
] | null | null | null | redist/inc/imqdst.hpp | gmarcon83/mq-mqi-nodejs | 27d44772254d0d76438022c6305277f603ff6acb | [
"Apache-2.0"
] | null | null | null | redist/inc/imqdst.hpp | gmarcon83/mq-mqi-nodejs | 27d44772254d0d76438022c6305277f603ff6acb | [
"Apache-2.0"
] | null | null | null | /* @(#) MQMBID sn=p924-L211104 su=_OdbBaj17EeygWfM06SbNXw pn=include/imqdst.pre_hpp */
#ifndef _IMQDST_HPP_
#define _IMQDST_HPP_
// Library: IBM MQ
// Component: IMQI (IBM MQ C++ MQI)
// Part: IMQDST.HPP
//
// Description: "ImqDistributionList" class declaration
// <copyright
// notice="lm-source-program"
// pids=""
// years="1994,2016"
// crc="257479060" >
// Licensed Materials - Property of IBM
//
//
//
// (C) Copyright IBM Corp. 1994, 2016 All Rights Reserved.
//
// US Government Users Restricted Rights - Use, duplication or
// disclosure restricted by GSA ADP Schedule Contract with
// IBM Corp.
// </copyright>
#include <imqque.hpp> // ImqQueue
#define ImqDistributionList ImqDst
class IMQ_EXPORTCLASS ImqDistributionList : public ImqQueue {
ImqQueue * opfirstDistributedQueue;
protected :
friend class ImqQueue ;
// Overloaded "ImqObject" methods:
virtual void openInformationDisperse ( );
virtual ImqBoolean openInformationPrepare ( );
// Overloaded "ImqQueue" methods:
virtual void putInformationDisperse ( ImqPmo & );
virtual ImqBoolean putInformationPrepare ( const ImqMsg &, ImqPmo & );
// New methods:
void setFirstDistributedQueue ( ImqQueue * pqueue = 0 )
{ opfirstDistributedQueue = pqueue ; }
public :
// New methods:
ImqDistributionList ( );
ImqDistributionList ( const ImqDistributionList & );
virtual ~ ImqDistributionList ( );
void operator = ( const ImqDistributionList & );
ImqQueue * firstDistributedQueue ( ) const
{ return opfirstDistributedQueue ; }
} ;
#endif
| 28.142857 | 86 | 0.706853 |
76f885c2f0a786d1eecf066cc26c0cf3da44d3a2 | 230 | cpp | C++ | src/plane_traits.cpp | richard-vock/triplet_match | a0375e75e08357c71b8b3945cb508ffb519121f8 | [
"CC0-1.0"
] | 3 | 2019-02-14T16:55:33.000Z | 2022-02-07T13:08:47.000Z | src/plane_traits.cpp | richard-vock/triplet_match | a0375e75e08357c71b8b3945cb508ffb519121f8 | [
"CC0-1.0"
] | 1 | 2019-02-14T17:10:37.000Z | 2019-02-14T17:10:37.000Z | src/plane_traits.cpp | richard-vock/triplet_match | a0375e75e08357c71b8b3945cb508ffb519121f8 | [
"CC0-1.0"
] | null | null | null | #include <plane_traits>
#include <impl/plane_traits.hpp>
namespace triplet_match {
#define INSTANTIATE_PCL_POINT_TYPE(type) \
template struct plane_traits<type>;
#include "pcl_point_types.def"
} // namespace triplet_match
| 20.909091 | 42 | 0.782609 |
76fa0b5358e9073caaf294c15fc60955f02be592 | 3,010 | cpp | C++ | src/stms/curl.cpp | RotartsiORG/StoneMason | 0f6efefad68b29e7e82524e705ce47606ba53665 | [
"Apache-2.0"
] | 1 | 2021-10-02T19:31:14.000Z | 2021-10-02T19:31:14.000Z | src/stms/curl.cpp | RotartsiORG/StoneMason | 0f6efefad68b29e7e82524e705ce47606ba53665 | [
"Apache-2.0"
] | 1 | 2020-06-17T01:15:45.000Z | 2020-06-17T01:16:08.000Z | src/stms/curl.cpp | RotartsiORG/StoneMason | 0f6efefad68b29e7e82524e705ce47606ba53665 | [
"Apache-2.0"
] | 1 | 2020-10-17T23:57:27.000Z | 2020-10-17T23:57:27.000Z | //
// Created by grant on 6/2/20.
//
#include "stms/curl.hpp"
#include <mutex>
#include "stms/logging.hpp"
namespace stms {
void initCurl() {
curl_global_init(CURL_GLOBAL_SSL | CURL_GLOBAL_WIN32);
auto version = curl_version_info(CURLVERSION_NOW);
STMS_INFO("LibCURL {}: On host '{}' with libZ {} & SSL {}", version->version, version->host, version->libz_version, version->ssl_version);
}
void quitCurl() {
curl_global_cleanup();
}
static size_t curlWriteCb(void *buf, size_t size, size_t nmemb, void *userDat) {
auto dat = reinterpret_cast<CURLHandle *>(userDat);
std::lock_guard<std::mutex> lg(dat->resultMtx);
dat->result.append(reinterpret_cast<char *>(buf), size * nmemb);
return size * nmemb;
}
static int curlProgressCb(void *userDat, double dTotal, double dNow, double uTotal, double uNow) {
auto dat = reinterpret_cast<CURLHandle *>(userDat);
dat->downloadTotal = dTotal;
dat->downloadSoFar = dNow;
dat->uploadSoFar = uNow;
dat->uploadTotal = uTotal;
return 0;
}
CURLHandle::CURLHandle(PoolLike *inPool) : pool(inPool), handle(curl_easy_init()) {
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, curlWriteCb);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, this);
curl_easy_setopt(handle, CURLOPT_NOPROGRESS, 0);
curl_easy_setopt(handle, CURLOPT_PROGRESSFUNCTION, curlProgressCb);
curl_easy_setopt(handle, CURLOPT_PROGRESSDATA, this);
}
CURLHandle::~CURLHandle() {
curl_easy_cleanup(handle);
handle = nullptr;
}
std::future<CURLcode> CURLHandle::perform() {
result.clear(); // Should we require the client to explicitly request this?
std::shared_ptr<std::promise<CURLcode>> prom = std::make_shared<std::promise<CURLcode>>();
pool.load()->submitTask([=]() {
auto err = curl_easy_perform(handle); // This is typically an expensive call so we async it
if (err != CURLE_OK) {
STMS_ERROR("Failed to perform curl operation on url {}", url); // We can't throw an exception so :[
}
prom->set_value(err);
});
return prom->get_future();
}
CURLHandle &CURLHandle::operator=(CURLHandle &&rhs) noexcept {
if (&rhs == this || rhs.handle.load() == handle.load()) {
return *this;
}
std::lock_guard<std::mutex> rlg(rhs.resultMtx);
std::lock_guard<std::mutex> tlg(resultMtx);
result = std::move(rhs.result);
downloadSoFar = rhs.downloadTotal;
downloadTotal = rhs.downloadTotal;
uploadSoFar = rhs.uploadSoFar;
uploadTotal = rhs.uploadTotal;
pool = rhs.pool.load();
handle = rhs.handle.load();
url = std::move(rhs.url);
return *this;
}
CURLHandle::CURLHandle(CURLHandle &&rhs) noexcept : handle(nullptr) {
*this = std::move(rhs);
}
}
| 31.354167 | 146 | 0.619934 |
76fbe39e413419e717be088742184ad004bd0256 | 1,937 | cpp | C++ | Engine/src/renderer/material/TexturePNG.cpp | Owlinated/SkyHockey | 787a7fa6c4cd1773c5a5c7e15e014f675947a21e | [
"MIT"
] | null | null | null | Engine/src/renderer/material/TexturePNG.cpp | Owlinated/SkyHockey | 787a7fa6c4cd1773c5a5c7e15e014f675947a21e | [
"MIT"
] | null | null | null | Engine/src/renderer/material/TexturePNG.cpp | Owlinated/SkyHockey | 787a7fa6c4cd1773c5a5c7e15e014f675947a21e | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <png.h>
#include <src/support/Logger.h>
#include "TexturePNG.h"
/**
* Load texture from .png file
* @param image_path File of .png file.
* @param mipmap Whether to load/generate mipmaps.
*/
TexturePNG::TexturePNG(const std::string& image_path, bool mipmap) {
const auto fp = fopen(("res/" + image_path).c_str(), "rb");
const auto png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
const auto info = png_create_info_struct(png);
png_init_io(png, fp);
png_read_info(png, info);
// Add alpha channel if png is RGB
if (png_get_color_type(png, info) == PNG_COLOR_TYPE_RGB) {
png_set_add_alpha(png, 0xff, PNG_FILLER_AFTER);
png_read_update_info(png, info);
}
const auto width = png_get_image_width(png, info);
const auto height = png_get_image_height(png, info);
std::vector<unsigned char> data;
data.resize(png_get_rowbytes(png, info) * height);
const auto row_pointers = new png_bytep[height];
for (auto y = 0; y < height; y++)
{
row_pointers[height - 1 - y] = data.data() + y * png_get_rowbytes(png, info);
}
png_read_image(png, row_pointers);
delete[] row_pointers;
glGenTextures(1, &handle);
glBindTexture(GL_TEXTURE_2D, handle);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data.data());
if(mipmap) {
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
} else {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
}
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
this->width = static_cast<int>(width);
this->height = static_cast<int>(height);
}
| 33.396552 | 102 | 0.710893 |
76fcf2736b58a99b802d5f28f72253782ebdd52f | 2,947 | cpp | C++ | RobWork/src/rw/trajectory/TimedUtil.cpp | ZLW07/RobWork | e713881f809d866b9a0749eeb15f6763e64044b3 | [
"Apache-2.0"
] | 1 | 2021-12-29T14:16:27.000Z | 2021-12-29T14:16:27.000Z | RobWork/src/rw/trajectory/TimedUtil.cpp | ZLW07/RobWork | e713881f809d866b9a0749eeb15f6763e64044b3 | [
"Apache-2.0"
] | null | null | null | RobWork/src/rw/trajectory/TimedUtil.cpp | ZLW07/RobWork | e713881f809d866b9a0749eeb15f6763e64044b3 | [
"Apache-2.0"
] | null | null | null | /********************************************************************************
* Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute,
* Faculty of Engineering, University of Southern Denmark
*
* 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 "TimedUtil.hpp"
#include "TimeMetricUtil.hpp"
#include <rw/models/Device.hpp>
using namespace rw::trajectory;
using namespace rw::math;
using namespace rw::models;
using namespace rw::kinematics;
typedef Timed< State > TimedState;
typedef Timed< Q > TimedQ;
TimedQPath TimedUtil::makeTimedQPath (const Q& speed, const QPath& path, double offset)
{
TimedQPath result;
if (path.empty ())
return result;
typedef QPath::const_iterator I;
I next = path.begin ();
I cur = next;
double time = offset;
result.push_back (TimedQ (time, *next));
for (++next; next != path.end (); ++cur, ++next) {
time += TimeMetricUtil::timeDistance (*cur, *next, speed);
result.push_back (TimedQ (time, *next));
}
return result;
}
TimedQPath TimedUtil::makeTimedQPath (const Device& device, const QPath& path, double offset)
{
return makeTimedQPath (device.getVelocityLimits (), path, offset);
}
TimedStatePath TimedUtil::makeTimedStatePath (const WorkCell& speed, const StatePath& path,
double offset)
{
TimedStatePath result;
if (path.empty ())
return result;
typedef StatePath::const_iterator I;
I next = path.begin ();
I cur = next;
double time = offset;
result.push_back (TimedState (0, *next));
for (++next; next != path.end (); ++cur, ++next) {
time += TimeMetricUtil::timeDistance (*cur, *next, speed);
result.push_back (TimedState (time, *next));
}
return result;
}
TimedStatePath TimedUtil::makeTimedStatePath (const Device& device, const QPath& path,
const State& common_state, double offset)
{
State state = common_state;
const TimedQPath qts = makeTimedQPath (device.getVelocityLimits (), path, offset);
TimedStatePath result;
typedef Timed< Q > TimedQ;
for (const TimedQ& qt : qts) {
device.setQ (qt.getValue (), state);
result.push_back (makeTimed (qt.getTime (), state));
}
return result;
}
| 30.697917 | 93 | 0.624364 |
76fe86d469a3f2265d05dc3009f9981988a6a44a | 647 | cpp | C++ | src/kc/core/Clock.cpp | nekoffski/libkc | f72cc40d2780747a707eaf6b822ba98848d92237 | [
"MIT"
] | null | null | null | src/kc/core/Clock.cpp | nekoffski/libkc | f72cc40d2780747a707eaf6b822ba98848d92237 | [
"MIT"
] | null | null | null | src/kc/core/Clock.cpp | nekoffski/libkc | f72cc40d2780747a707eaf6b822ba98848d92237 | [
"MIT"
] | null | null | null | #include "Clock.h"
#include <ctime>
#include <iomanip>
namespace kc::core {
float toSeconds(const Clock::TimePoint& timePoint) {
using namespace std::chrono;
return duration_cast<microseconds>(timePoint.time_since_epoch()).count() / Clock::microsecondsInSecond;
}
std::string Clock::getTimeString(const std::string& format) const {
auto t = std::time(nullptr);
auto tm = *std::localtime(&t);
std::ostringstream oss;
oss << std::put_time(&tm, format.c_str());
return oss.str();
}
Clock::TimePoint Clock::now() const {
return m_clock.now();
}
float Clock::nowAsFloat() const {
return toSeconds(now());
}
} | 21.566667 | 107 | 0.678516 |
0a00f41bfb75f9575dd010edec32c552fcb78c42 | 4,845 | cc | C++ | packages/solid/Cylinder_3D.cc | brbass/ibex | 5a4cc5b4d6d46430d9667970f8a34f37177953d4 | [
"MIT"
] | 2 | 2020-04-13T20:06:41.000Z | 2021-02-12T17:55:54.000Z | packages/solid/Cylinder_3D.cc | brbass/ibex | 5a4cc5b4d6d46430d9667970f8a34f37177953d4 | [
"MIT"
] | 1 | 2018-10-22T21:03:35.000Z | 2018-10-22T21:03:35.000Z | packages/solid/Cylinder_3D.cc | brbass/ibex | 5a4cc5b4d6d46430d9667970f8a34f37177953d4 | [
"MIT"
] | 3 | 2019-04-03T02:15:37.000Z | 2022-01-04T05:50:23.000Z | #include "Cylinder_3D.hh"
#include "Vector_Functions_3D.hh"
#include <cmath>
using namespace std;
namespace vf3 = Vector_Functions_3D;
Cylinder_3D::
Cylinder_3D(int index,
Surface_Type surface_type,
double radius,
vector<double> const &origin,
vector<double> const &direction):
Cylinder(index,
3, // dimension
surface_type),
radius_(radius),
origin_(origin),
direction_(direction)
{
}
Cylinder_3D::Relation Cylinder_3D::
relation(vector<double> const &particle_position,
bool check_equality) const
{
// Cross product approach
// vector<double> const k0 = vf3::cross(direction_,
// vf3::subtract(particle_position,
// origin_));
// double const r = vf3::magnitude(k0);
// Dot product approach
vector<double> const k0 = vf3::subtract(particle_position,
origin_);
vector<double> const n = vf3::subtract(k0,
vf3::multiply(direction_,
vf3::dot(direction_,
k0)));
double const r = vf3::magnitude(n);
double const dr = r - radius_;
if (check_equality)
{
if (std::abs(dr) <= relation_tolerance_)
{
return Relation::EQUAL;
}
}
if (dr > 0)
{
return Relation::OUTSIDE;
}
else // if (dr > 0)
{
return Relation::INSIDE;
}
}
Cylinder_3D::Intersection Cylinder_3D::
intersection(vector<double> const &particle_position,
vector<double> const &particle_direction) const
{
Intersection intersection;
vector<double> const j0 = vf3::subtract(particle_position,
origin_);
vector<double> const k0 = vf3::subtract(j0,
vf3::multiply(direction_,
vf3::dot(direction_,
j0)));
vector<double> const k1 = vf3::subtract(particle_direction,
vf3::multiply(direction_,
vf3::dot(direction_,
particle_direction)));
double const l0 = vf3::magnitude_squared(k0) - radius_ * radius_;
double const l1 = vf3::dot(k0,
k1);
double const l2 = vf3::magnitude_squared(k1);
double const l3 = l1 * l1 - l0 * l2;
if (l3 < 0)
{
intersection.type = Intersection::Type::NONE;
return intersection;
}
else if (l2 <= intersection_tolerance_)
{
intersection.type = Intersection::Type::PARALLEL;
return intersection;
}
double const l4 = sqrt(l3);
double const s1 = (-l1 + l4) / l2;
double const s2 = (-l1 - l4) / l2;
if (s2 > 0)
{
intersection.distance = s2;
}
else if (s1 > 0)
{
intersection.distance = s1;
}
else
{
intersection.type = Intersection::Type::NEGATIVE;
return intersection;
}
intersection.position = vf3::add(particle_position,
vf3::multiply(particle_direction,
intersection.distance));
if (l3 <= intersection_tolerance_)
{
intersection.type = Intersection::Type::TANGEANT;
return intersection;
}
else
{
intersection.type = Intersection::Type::INTERSECTS;
return intersection;
}
}
Cylinder_3D::Normal Cylinder_3D::
normal_direction(vector<double> const &position,
bool check_normal) const
{
Normal normal;
vector<double> const k0 = vf3::subtract(position,
origin_);
vector<double> const n = vf3::subtract(k0,
vf3::multiply(direction_,
vf3::dot(direction_,
k0)));
if (check_normal)
{
if (std::abs(vf3::magnitude_squared(n) - radius_ * radius_) > normal_tolerance_ * radius_ * radius_)
{
normal.exists = false;
return normal;
}
}
normal.exists = true;
normal.direction = vf3::normalize(n);
return normal;
}
void Cylinder_3D::
check_class_invariants() const
{
Assert(origin_.size() == dimension_);
Assert(direction_.size() == dimension_);
}
| 29.011976 | 108 | 0.490815 |
0a028dcc0da795f0e336636cc08e39356c210a3f | 7,281 | cpp | C++ | src/core/Hub.cpp | gabrielklein/SensorNode | e92dbd56aa0a7d75ab95b9c484f27ba6d0be64df | [
"MIT"
] | 2 | 2018-01-21T11:43:36.000Z | 2019-07-15T20:08:31.000Z | src/core/Hub.cpp | gabrielklein/SensorNode | e92dbd56aa0a7d75ab95b9c484f27ba6d0be64df | [
"MIT"
] | null | null | null | src/core/Hub.cpp | gabrielklein/SensorNode | e92dbd56aa0a7d75ab95b9c484f27ba6d0be64df | [
"MIT"
] | null | null | null | #include "Hub.h"
#include "../Settings.h"
Hub::Hub() {
};
Hub::~Hub() {
delete(this->webServerSN);
delete(this->apStaClient);
delete(this->led);
delete(this->temp);
delete(this->relay);
delete(this->switc);
delete(this->geiger);
delete(this->mqtt);
delete(this->otaUpdate);
};
/**
* Called at setup time. Use this call to initialize some data.
*/
void Hub::setup() {
// Use serial
Serial.begin ( 115200 );
Serial.println ("\nStarting Hub");
this->fileServ.setup();
#ifdef WEB_SERVER_SN_ENABLE
this->webServerSN = new WebServerSN(&this->fileServ);
this->webServerSN->addServ(this->webServerSN);
this->webServerSN->setup();
#endif
#ifdef WS281X_STRIP_ENABLE
this->led = new Led(&this->fileServ);
this->led->setup();
this->led->rgb(0, 0, 0, 50);
if (this->webServerSN != NULL)
this->webServerSN->addServ(this->led);
#endif
#ifdef AP_SERVER_CLIENT_ENABLE
this->apStaClient = new APStaClient(&this->fileServ, this->led);
isClientMode = this->apStaClient->setup();
if (this->webServerSN != NULL) {
this->webServerSN->addServ(this->apStaClient);
if (!isClientMode) {
this->webServerSN->apModeOnly();
}
}
#endif
#ifdef OTA_ENABLE
this->otaUpdate = new OTAUpdate();
this->otaUpdate->setup();
#endif
if (isClientMode) {
#ifdef TIME_ENABLE
this->iTime = new ITime(&this->fileServ);
this->iTime->setup();
if (this->webServerSN != NULL)
this->webServerSN->addServ(this->iTime);
#endif
#ifdef MQTT_ENABLE
this->mqtt = new MQTT(&this->fileServ);
this->mqtt->setup();
if (this->webServerSN != NULL)
this->webServerSN->addServ(this->mqtt);
#endif
#ifdef TEMP_ENABLE
this->temp = new Temp();
this->temp->setup();
if (this->webServerSN != NULL)
this->webServerSN->addServ(this->temp);
if (this->mqtt != NULL)
this->mqtt->addServ(this->temp);
#endif
#ifdef RELAY_ENABLE
this->relay = new Relay();
this->relay->setup();
if (this->webServerSN != NULL)
this->webServerSN->addServ(this->relay);
if (this->mqtt != NULL)
this->mqtt->addServ(this->relay);
#endif
#ifdef SWITCH_ENABLE
this->switc = new Switch();
this->switc->setup();
if (this->webServerSN != NULL)
this->webServerSN->addServ(this->switc);
if (this->mqtt != NULL)
this->mqtt->addServ(this->switc);
#endif
#ifdef GEIGER_ENABLE
this->geiger = new Geiger(&this->fileServ);
this->geiger->setup();
if (this->webServerSN != NULL)
this->webServerSN->addServ(this->geiger);
if (this->mqtt != NULL)
this->mqtt->addServ(this->geiger);
#endif
}
};
/**
* Loop
*/
void Hub::loop() {
if (this->webServerSN!=NULL) {
unsigned long now = millis();
this->webServerSN->loop();
unsigned long duration = millis() - now;
if (duration > 100) {
Serial.print("Loop for WebServerSN is a bit long: ");
Serial.println(duration);
}
}
if (this->otaUpdate!=NULL) {
unsigned long now = millis();
this->otaUpdate->loop();
unsigned long duration = millis() - now;
if (duration > 100) {
Serial.print("Loop for otaUpdate is a bit long: ");
Serial.println(duration);
}
}
if (!isClientMode) {
return;
}
if (this->iTime!=NULL) {
unsigned long now = millis();
this->iTime->loop();
unsigned long duration = millis() - now;
if (duration > 100) {
Serial.print("Loop for iTime is a bit long: ");
Serial.println(duration);
}
}
if (this->led!=NULL) {
unsigned long now = millis();
this->led->loop();
unsigned long duration = millis() - now;
if (duration > 100) {
Serial.print("Loop for led is a bit long: ");
Serial.println(duration);
}
}
if (this->temp!=NULL) {
unsigned long now = millis();
this->temp->loop();
unsigned long duration = millis() - now;
if (duration > 100) {
Serial.print("Loop for temp is a bit long: ");
Serial.println(duration);
}
}
if (this->apStaClient!=NULL) {
unsigned long now = millis();
this->apStaClient->loop();
unsigned long duration = millis() - now;
if (duration > 100) {
Serial.print("Loop for apStaClient is a bit long: ");
Serial.println(duration);
}
}
if (this->relay!=NULL) {
unsigned long now = millis();
this->relay->loop();
unsigned long duration = millis() - now;
if (duration > 100) {
Serial.print("Loop for relay is a bit long: ");
Serial.println(duration);
}
}
if (this->switc!=NULL) {
unsigned long now = millis();
this->switc->loop();
unsigned long duration = millis() - now;
if (duration > 100) {
Serial.print("Loop for switc is a bit long: ");
Serial.println(duration);
}
}
if (this->geiger!=NULL) {
unsigned long now = millis();
this->geiger->loop();
unsigned long duration = millis() - now;
if (duration > 100) {
Serial.print("Loop for geiger is a bit long: ");
Serial.println(duration);
}
}
if (this->mqtt!=NULL) {
unsigned long now = millis();
this->mqtt->loop();
unsigned long duration = millis() - now;
if (duration > 100) {
Serial.print("Loop for mqtt is a bit long: ");
Serial.println(duration);
}
}
}
| 30.721519 | 77 | 0.439363 |
0a065fe2c8f15d4ad8f0c1d2ae1aae271b46cd46 | 2,916 | cpp | C++ | src/batterymonitor.cpp | spiiroin/btrfs-balancer | 5c1f0145db34dd6837bcbb38f00854f6d962bcc3 | [
"BSD-3-Clause"
] | null | null | null | src/batterymonitor.cpp | spiiroin/btrfs-balancer | 5c1f0145db34dd6837bcbb38f00854f6d962bcc3 | [
"BSD-3-Clause"
] | null | null | null | src/batterymonitor.cpp | spiiroin/btrfs-balancer | 5c1f0145db34dd6837bcbb38f00854f6d962bcc3 | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************************
**
** Copyright (C) 2015 Jolla Ltd.
** Contact: Martin Grimme <martin.grimme@gmail.com>
** All rights reserved.
**
** This file is part of the btrfs-balancer package.
**
** You may use this file under the terms of the GNU Lesser General
** Public License version 2.1 as published by the Free Software Foundation
** and appearing in the file license.lgpl included in the packaging
** of this file.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file license.lgpl included in the packaging
** of this file.
**
** 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.
**
****************************************************************************************/
#include "batterymonitor.h"
#include <contextproperty.h>
namespace
{
const QString BATTERY_CHARGE("Battery.ChargePercentage");
const QString BATTERY_STATE("Battery.State");
}
BatteryMonitor::BatteryMonitor(QObject *parent)
: QObject(parent)
, m_currentCharge(-1) // charge is -1 while pending and to be ignored
, m_currentStatus(PENDING)
{
ContextProperty *chargeProperty = new ContextProperty(BATTERY_CHARGE, this);
ContextProperty *stateProperty = new ContextProperty(BATTERY_STATE, this);
connect(chargeProperty, SIGNAL(valueChanged()),
this, SLOT(slotChargeChanged()));
connect(stateProperty, SIGNAL(valueChanged()),
this, SLOT(slotStateChanged()));
}
void BatteryMonitor::slotChargeChanged()
{
ContextProperty* prop = qobject_cast<ContextProperty*>(sender());
if (prop) {
m_currentCharge = prop->value(QVariant(0)).toInt();
if (m_currentStatus != PENDING) {
emit status(m_currentStatus, m_currentCharge);
}
}
}
void BatteryMonitor::slotStateChanged()
{
ContextProperty* prop = qobject_cast<ContextProperty*>(sender());
if (prop) {
const QString value = prop->value(QVariant("unknown")).toString();
if (value == "charging") {
m_currentStatus = CHARGING;
} else if (value == "discharging") {
m_currentStatus = DISCHARGING;
} else if (value == "full") {
m_currentStatus = DISCHARGING; // no difference for this use case
} else if (value == "low" || value == "empty") {
m_currentStatus = CRITICAL;
} else { // unknown
m_currentStatus = UNKNOWN;
}
if (m_currentCharge != -1) {
emit status(m_currentStatus, m_currentCharge);
}
}
}
| 33.517241 | 89 | 0.63546 |
0a096f8d0bea078fd113c110e2ccfa182e51f0ee | 156 | hpp | C++ | example/src/Utils/Config.hpp | matusnovak/doxydown | 187dc2991dabe65f808263845e608e2ba2a41082 | [
"MIT"
] | 131 | 2019-12-12T09:08:03.000Z | 2022-03-27T01:48:11.000Z | example/src/Utils/Config.hpp | matusnovak/doxydown | 187dc2991dabe65f808263845e608e2ba2a41082 | [
"MIT"
] | 69 | 2020-02-21T05:50:27.000Z | 2022-03-11T21:16:17.000Z | example/src/Utils/Config.hpp | matusnovak/doxydown | 187dc2991dabe65f808263845e608e2ba2a41082 | [
"MIT"
] | 27 | 2020-02-20T04:50:23.000Z | 2022-03-17T00:55:00.000Z | #pragma once
/*!
* @brief Autogenerated version string by CMake
* @ingroup Utils
*/
#define ENGINE_VERSION "v1.0.1"
#define ENGINE_ARCH "amd64"
| 17.333333 | 48 | 0.679487 |
0a0cf82fe63806cf84c2abc335fc5cb6eda5b4c6 | 563 | cpp | C++ | Section10/LetterPyramid/main.cpp | Yash-Singh1/cpp-programming | 696c1dcff18af8e798fae6126a3b13f6259af4b7 | [
"MIT"
] | null | null | null | Section10/LetterPyramid/main.cpp | Yash-Singh1/cpp-programming | 696c1dcff18af8e798fae6126a3b13f6259af4b7 | [
"MIT"
] | null | null | null | Section10/LetterPyramid/main.cpp | Yash-Singh1/cpp-programming | 696c1dcff18af8e798fae6126a3b13f6259af4b7 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Welcome to the Letter Pyramid Generator!" << endl;
string input;
cout << "Enter the input text: ";
getline(cin, input);
size_t padding{input.length() - 1};
for (size_t i{1}; i <= input.length(); ++i)
{
cout << string(padding, ' ') << input.substr(0, i);
if (i != 1)
{
for (size_t ri{i - 2}; ri > 0; --ri)
{
cout << input[ri];
}
cout << input[0];
}
cout << endl;
--padding;
}
cout << endl;
return 0;
}
| 17.060606 | 61 | 0.520426 |
0a0f0a5347be9d4d7b08b04467c4ed9c6c63ce96 | 14,129 | cpp | C++ | include/h3api/H3Dialogs/H3BaseDialog.cpp | Patrulek/H3API | 91f10de37c6b86f3160706c1fdf4792f927e9952 | [
"MIT"
] | 14 | 2020-09-07T21:49:26.000Z | 2021-11-29T18:09:41.000Z | include/h3api/H3Dialogs/H3BaseDialog.cpp | Day-of-Reckoning/H3API | a82d3069ec7d5127b13528608d5350d2b80d57be | [
"MIT"
] | 2 | 2021-02-12T15:52:31.000Z | 2021-02-12T16:21:24.000Z | include/h3api/H3Dialogs/H3BaseDialog.cpp | Day-of-Reckoning/H3API | a82d3069ec7d5127b13528608d5350d2b80d57be | [
"MIT"
] | 8 | 2021-02-12T15:52:41.000Z | 2022-01-31T15:28:10.000Z | //////////////////////////////////////////////////////////////////////
// //
// Created by RoseKavalier: //
// rosekavalierhc@gmail.com //
// Created or last updated on: 2021-01-25 //
// ***You may use or distribute these files freely //
// so long as this notice remains present.*** //
// //
//////////////////////////////////////////////////////////////////////
#include "h3api/H3Dialogs/H3BaseDialog.hpp"
#include "h3api/H3DialogControls.hpp"
#include "h3api/H3Dialogs/H3Message.hpp"
#include "h3api/H3Assets/H3Resource.hpp"
#include "h3api/H3Managers/H3WindowManager.hpp"
#include "h3api/H3Assets/H3LoadedDef.hpp"
#include "h3api/H3Assets/H3LoadedPcx.hpp"
namespace h3
{
_H3API_ H3BaseDlg::H3BaseDlg(INT x, INT y, INT w, INT h) :
zOrder(-1), nextDialog(), lastDialog(), flags(0x12), state(),
xDlg(x), yDlg(y), widthDlg(w), heightDlg(h), lastItem(), firstItem(),
focusedItemId(-1), pcx16(), deactivatesCount()
{
}
_H3API_ VOID H3BaseDlg::Redraw(INT32 x, INT32 y, INT32 dx, INT32 dy)
{
H3WindowManager::Get()->H3Redraw(xDlg + x, yDlg + y, dx, dy);
}
_H3API_ VOID H3BaseDlg::Redraw()
{
vRedraw(TRUE, -65535, 65535);
}
_H3API_ INT32 H3BaseDlg::DefaultProc(H3Msg* msg)
{
return DefaultProc(*msg);
}
_H3API_ INT32 H3BaseDlg::DefaultProc(H3Msg& msg)
{
return THISCALL_2(INT32, 0x41B120, this, &msg);
}
_H3API_ H3DlgItem* H3BaseDlg::getDlgItem(UINT16 id, h3func vtable) const
{
H3DlgItem* it = firstItem;
if (it == nullptr)
return it;
do
{
if ((it->GetID() == id) && (*reinterpret_cast<h3func*>(it) == vtable))
break;
} while (it = it->GetNextItem());
return it;
}
_H3API_ INT32 H3BaseDlg::GetWidth() const
{
return widthDlg;
}
_H3API_ INT32 H3BaseDlg::GetHeight() const
{
return heightDlg;
}
_H3API_ INT32 H3BaseDlg::GetX() const
{
return xDlg;
}
_H3API_ INT32 H3BaseDlg::GetY() const
{
return yDlg;
}
_H3API_ BOOL H3BaseDlg::IsTopDialog() const
{
return nextDialog == nullptr;
}
_H3API_ VOID H3BaseDlg::AddControlState(INT32 id, eControlState state)
{
THISCALL_3(VOID, 0x5FF490, this, id, state);
}
_H3API_ VOID H3BaseDlg::RemoveControlState(INT32 id, eControlState state)
{
THISCALL_3(VOID, 0x5FF520, this, id, state);
}
_H3API_ H3DlgItem* H3BaseDlg::AddItem(H3DlgItem* item, BOOL initiate /*= TRUE*/)
{
dlgItems += item;
if (initiate)
return THISCALL_3(H3DlgItem*, 0x5FF270, this, item, -1); // LoadItem
else
return item;
}
_H3API_ H3DlgDef* H3BaseDlg::GetDef(UINT16 id) const
{
return get<H3DlgDef>(id);
}
_H3API_ H3DlgPcx* H3BaseDlg::GetPcx(UINT16 id) const
{
return get<H3DlgPcx>(id);
}
_H3API_ H3DlgEdit* H3BaseDlg::GetEdit(UINT16 id) const
{
return get<H3DlgEdit>(id);
}
_H3API_ H3DlgText* H3BaseDlg::GetText(UINT16 id) const
{
return get<H3DlgText>(id);
}
_H3API_ H3DlgFrame* H3BaseDlg::GetFrame(UINT16 id) const
{
return get<H3DlgFrame>(id);
}
_H3API_ H3DlgPcx16* H3BaseDlg::GetPcx16(UINT16 id) const
{
return get<H3DlgPcx16>(id);
}
_H3API_ H3DlgTextPcx* H3BaseDlg::GetTextPcx(UINT16 id) const
{
return get<H3DlgTextPcx>(id);
}
_H3API_ H3DlgDefButton* H3BaseDlg::GetDefButton(UINT16 id) const
{
return get<H3DlgDefButton>(id);
}
_H3API_ H3DlgScrollbar* H3BaseDlg::GetScrollbar(UINT16 id) const
{
return get<H3DlgScrollbar>(id);
}
_H3API_ H3DlgTransparentItem* H3BaseDlg::GetTransparent(UINT16 id) const
{
return get<H3DlgTransparentItem>(id);
}
_H3API_ H3DlgCustomButton* H3BaseDlg::GetCustomButton(UINT16 id) const
{
return get<H3DlgCustomButton>(id);
}
_H3API_ H3DlgCaptionButton* H3BaseDlg::GetCaptionButton(UINT16 id) const
{
return get<H3DlgCaptionButton>(id);
}
_H3API_ H3DlgScrollableText* H3BaseDlg::GetScrollableText(UINT16 id) const
{
return get<H3DlgScrollableText>(id);
}
_H3API_ H3DlgTransparentItem* H3BaseDlg::CreateHidden(INT32 x, INT32 y, INT32 width, INT32 height, INT32 id)
{
H3DlgTransparentItem* it = H3DlgTransparentItem::Create(x, y, width, height, id);
if (it)
AddItem(it);
return it;
}
_H3API_ H3LoadedPcx16* H3BaseDlg::GetCurrentPcx()
{
return pcx16;
}
_H3API_ H3DlgItem* H3BaseDlg::ItemAtPosition(H3Msg* msg)
{
return ItemAtPosition(*msg);
}
_H3API_ H3DlgItem* H3BaseDlg::ItemAtPosition(H3Msg& msg)
{
return THISCALL_3(H3DlgItem*, 0x5FF9A0, this, msg.GetX(), msg.GetY());
}
_H3API_ H3Vector<H3DlgItem*>& H3BaseDlg::GetList()
{
return dlgItems;
}
_H3API_ H3DlgItem* H3BaseDlg::GetH3DlgItem(UINT16 id)
{
return THISCALL_2(H3DlgItem*, 0x5FF5B0, this, id);
}
_H3API_ VOID H3BaseDlg::RedrawItem(UINT16 itemID)
{
if (H3DlgItem* it = GetH3DlgItem(itemID))
it->Refresh();
}
_H3API_ VOID H3BaseDlg::EnableItem(UINT16 id, BOOL enable)
{
H3DlgItem* it = GetH3DlgItem(id);
if (it)
it->EnableItem(enable);
}
_H3API_ VOID H3BaseDlg::SendCommandToItem(INT32 command, UINT16 itemID, UINT32 parameter)
{
THISCALL_5(VOID, 0x5FF400, this, 0x200, command, itemID, parameter);
}
_H3API_ VOID H3BaseDlg::SendCommandToAllItems(INT32 command, INT32 itemID, INT32 parameter)
{
H3Msg msg;
msg.SetCommand(eMsgCommand::ITEM_COMMAND, eMsgSubtype(command), itemID, eMsgFlag::NONE, 0, 0, parameter, 0);
THISCALL_2(VOID, 0x5FF3A0, this, &msg);
}
_H3API_ VOID H3BaseDlg::AdjustToPlayerColor(INT8 player, UINT16 itemId)
{
if (H3DlgItem* it = GetH3DlgItem(itemId))
it->ColorToPlayer(player);
}
_H3API_ H3DlgFrame* H3BaseDlg::CreateFrame(INT32 x, INT32 y, INT32 width, INT32 height, INT32 id, RGB565 color)
{
H3DlgFrame* frame = H3DlgFrame::Create(x, y, width, height, id, color);
if (frame)
AddItem(frame);
return frame;
}
_H3API_ H3DlgFrame* H3BaseDlg::CreateFrame(INT32 x, INT32 y, INT32 width, INT32 height, RGB565 color)
{
H3DlgFrame* frame = H3DlgFrame::Create(x, y, width, height, 0, color);
if (frame)
AddItem(frame);
return frame;
}
_H3API_ H3DlgFrame* H3BaseDlg::CreateFrame(H3DlgItem* target, RGB565 color, INT id, BOOL around_edge)
{
H3DlgFrame* frame = H3DlgFrame::Create(target, color, id, around_edge);
if (frame)
AddItem(frame);
return frame;
}
_H3API_ H3DlgDef* H3BaseDlg::CreateDef(INT32 x, INT32 y, INT32 width, INT32 height, INT32 id, LPCSTR defName, INT32 frame, INT32 group, INT32 mirror, BOOL closeDialog)
{
H3DlgDef* def = H3DlgDef::Create(x, y, width, height, id, defName, frame, group, mirror, closeDialog);
if (def)
AddItem(def);
return def;
}
_H3API_ H3DlgDef* H3BaseDlg::CreateDef(INT32 x, INT32 y, INT32 id, LPCSTR defName, INT32 frame, INT32 group, INT32 mirror, BOOL closeDialog)
{
H3DlgDef* def = H3DlgDef::Create(x, y, id, defName, frame, group, mirror, closeDialog);
if (def)
AddItem(def);
return def;
}
_H3API_ H3DlgDefButton* H3BaseDlg::CreateButton(INT32 x, INT32 y, INT32 width, INT32 height, INT32 id, LPCSTR defName, INT32 frame, INT32 clickFrame, BOOL closeDialog, INT32 hotkey)
{
H3DlgDefButton* but = H3DlgDefButton::Create(x, y, width, height, id, defName, frame, clickFrame, closeDialog, hotkey);
if (but)
AddItem(but);
return but;
}
_H3API_ H3DlgDefButton* H3BaseDlg::CreateButton(INT32 x, INT32 y, INT32 id, LPCSTR defName, INT32 frame, INT32 clickFrame, BOOL closeDialog, INT32 hotkey)
{
H3DlgDefButton* but = CreateButton(x, y, 0, 0, id, defName, frame, clickFrame, closeDialog, hotkey);
if (but)
{
H3LoadedDef* def = but->GetDef();
if (def)
{
but->SetWidth(def->widthDEF);
but->SetHeight(def->heightDEF);
}
}
return but;
}
_H3API_ H3DlgDefButton* H3BaseDlg::CreateOKButton(INT32 x, INT32 y)
{
H3DlgDefButton* button = H3DlgDefButton::Create(x, y, int(eControlId::OK), NH3Dlg::Assets::OKAY_DEF, 0, 1, TRUE, NH3VKey::H3VK_ENTER);
if (button)
{
AddItem(H3DlgPcx::Create(x - 1, y - 1, NH3Dlg::Assets::BOX_64_30_PCX));
AddItem(button);
}
return button;
}
_H3API_ H3DlgDefButton* H3BaseDlg::CreateSaveButton(INT32 x, INT32 y, LPCSTR button_name)
{
H3DlgDefButton* button = H3DlgDefButton::Create(x, y, int(eControlId::SAVE), button_name, 0, 1, FALSE, NH3VKey::H3VK_S);
if (button)
{
AddItem(H3DlgFrame::Create(button, H3RGB565::Highlight(), 0, TRUE));
//AddItem(H3DlgPcx::Create(x - 1, y - 1, NH3Dlg::Assets::BOX_64_32_PCX));
AddItem(button);
}
return button;
}
_H3API_ H3DlgDefButton* H3BaseDlg::CreateOnOffCheckbox(INT32 x, INT32 y, INT32 id, INT32 frame, INT32 clickFrame)
{
if (clickFrame == -1)
clickFrame = 1 - frame;
H3DlgDefButton* button = H3DlgDefButton::Create(x, y, id, NH3Dlg::Assets::ON_OFF_CHECKBOX, frame, clickFrame, 0, 0);
if (button)
AddItem(button);
return button;
}
_H3API_ H3DlgDefButton* H3BaseDlg::CreateOKButton()
{
H3DlgDefButton* button = H3DlgDefButton::Create(25, heightDlg - 50, int(eControlId::OK), NH3Dlg::Assets::OKAY_DEF, 0, 1, TRUE, NH3VKey::H3VK_ENTER);
if (button)
{
AddItem(H3DlgPcx::Create(25 - 1, heightDlg - 50 - 1, NH3Dlg::Assets::BOX_64_30_PCX));
AddItem(button);
}
return button;
}
_H3API_ H3DlgDefButton* H3BaseDlg::CreateOK32Button(INT32 x, INT32 y)
{
H3DlgDefButton* button = H3DlgDefButton::Create(x, y, int(eControlId::OK), NH3Dlg::Assets::OKAY32_DEF, 0, 1, TRUE, NH3VKey::H3VK_ENTER);
if (button)
{
AddItem(H3DlgPcx::Create(x - 1, y - 1, NH3Dlg::Assets::BOX_66_32_PCX));
AddItem(button);
}
return button;
}
_H3API_ H3DlgDefButton* H3BaseDlg::CreateCancelButton()
{
return CreateCancelButton(widthDlg - 25 - 64, heightDlg - 50);
}
_H3API_ H3DlgDefButton* H3BaseDlg::CreateCancelButton(INT32 x, INT32 y)
{
H3DlgDefButton* button = H3DlgDefButton::Create(x, y, eControlId::CANCEL, NH3Dlg::Assets::CANCEL_DEF, 0, 1, TRUE, NH3VKey::H3VK_ESCAPE);
if (button)
{
AddItem(H3DlgPcx::Create(x - 1, y - 1, NH3Dlg::Assets::BOX_64_30_PCX));
AddItem(button);
}
return button;
}
_H3API_ H3DlgCaptionButton* H3BaseDlg::CreateCaptionButton(INT32 x, INT32 y, INT32 width, INT32 height, INT32 id, LPCSTR defName, LPCSTR text, LPCSTR font, INT32 frame, INT32 group, BOOL closeDialog, INT32 hotkey, INT32 color)
{
H3DlgCaptionButton* but = H3DlgCaptionButton::Create(x, y, width, height, id, defName, text, font, frame, group, closeDialog, hotkey, color);
if (but)
AddItem(but);
return but;
}
_H3API_ H3DlgCustomButton* H3BaseDlg::CreateCustomButton(INT32 x, INT32 y, INT32 width, INT32 height, INT32 id, LPCSTR defName, H3DlgButton_proc customProc, INT32 frame, INT32 clickFrame)
{
H3DlgCustomButton* but = H3DlgCustomButton::Create(x, y, width, height, id, defName, customProc, frame, clickFrame);
if (but)
AddItem(but);
return but;
}
_H3API_ H3DlgCustomButton* H3BaseDlg::CreateCustomButton(INT32 x, INT32 y, INT32 id, LPCSTR defName, H3DlgButton_proc customProc, INT32 frame, INT32 clickFrame)
{
H3DlgCustomButton* but = H3DlgCustomButton::Create(x, y, id, defName, customProc, frame, clickFrame);
if (but)
AddItem(but);
return but;
}
_H3API_ H3DlgCustomButton* H3BaseDlg::CreateCustomButton(INT32 x, INT32 y, LPCSTR defName, H3DlgButton_proc customProc, INT32 frame, INT32 clickFrame)
{
return CreateCustomButton(x, y, 0, defName, customProc, frame, clickFrame);
}
_H3API_ H3DlgPcx* H3BaseDlg::CreatePcx(INT32 x, INT32 y, INT32 width, INT32 height, INT32 id, LPCSTR pcxName)
{
H3DlgPcx* pcx = H3DlgPcx::Create(x, y, width, height, id, pcxName);
if (pcx)
AddItem(pcx);
return pcx;
}
_H3API_ H3DlgPcx* H3BaseDlg::CreatePcx(INT32 x, INT32 y, INT32 id, LPCSTR pcxName)
{
H3DlgPcx* pcx = CreatePcx(x, y, 0, 0, id, pcxName);
if (pcx && pcx->GetPcx())
{
H3LoadedPcx* p = pcx->GetPcx();
pcx->SetWidth(p->width);
pcx->SetHeight(p->height);
}
return pcx;
}
_H3API_ H3DlgPcx* H3BaseDlg::CreateLineSeparator(INT32 x, INT32 y, INT32 width)
{
return CreatePcx(x, y, width, 2, 0, NH3Dlg::HDassets::LINE_SEPARATOR);
}
_H3API_ H3DlgPcx16* H3BaseDlg::CreatePcx16(INT32 x, INT32 y, INT32 width, INT32 height, INT32 id, LPCSTR pcxName)
{
H3DlgPcx16* pcx = H3DlgPcx16::Create(x, y, width, height, id, pcxName);
if (pcx)
AddItem(pcx);
return pcx;
}
_H3API_ H3DlgEdit* H3BaseDlg::CreateEdit(INT32 x, INT32 y, INT32 width, INT32 height, INT32 maxLength, LPCSTR text, LPCSTR fontName, INT32 color, INT32 align, LPCSTR pcxName, INT32 id, INT32 hasBorder, INT32 borderX, INT32 borderY)
{
H3DlgEdit* ed = H3DlgEdit::Create(x, y, width, height, maxLength, text, fontName, color, align, pcxName, id, hasBorder, borderX, borderY);
if (ed)
AddItem(ed);
return ed;
}
_H3API_ H3DlgText* H3BaseDlg::CreateText(INT32 x, INT32 y, INT32 width, INT32 height, LPCSTR text, LPCSTR fontName, INT32 color, INT32 id, eTextAlignment align, INT32 bkColor)
{
H3DlgText* tx = H3DlgText::Create(x, y, width, height, text, fontName, color, id, align, bkColor);
if (tx)
AddItem(tx);
return tx;
}
_H3API_ H3DlgTextPcx* H3BaseDlg::CreateTextPcx(INT32 x, INT32 y, INT32 width, INT32 height, LPCSTR text, LPCSTR fontName, LPCSTR pcxName, INT32 color, INT32 id, INT32 align)
{
H3DlgTextPcx* tx = H3DlgTextPcx::Create(x, y, width, height, text, fontName, pcxName, color, id, align);
if (tx)
AddItem(tx);
return tx;
}
_H3API_ H3DlgScrollableText* H3BaseDlg::CreateScrollableText(LPCSTR text, INT32 x, INT32 y, INT32 width, INT32 height, LPCSTR font, INT32 color, INT32 isBlue)
{
H3DlgScrollableText* sc = H3DlgScrollableText::Create(text, x, y, width, height, font, color, isBlue);
if (sc)
AddItem(sc);
return sc;
}
_H3API_ H3DlgScrollbar* H3BaseDlg::CreateScrollbar(INT32 x, INT32 y, INT32 width, INT32 height, INT32 id, INT32 ticksCount, H3DlgScrollbar_proc scrollbarProc, BOOL isBlue, INT32 stepSize, BOOL arrowsEnabled)
{
H3DlgScrollbar* sc = H3DlgScrollbar::Create(x, y, width, height, id, ticksCount, scrollbarProc, isBlue, stepSize, arrowsEnabled);
if (sc)
AddItem(sc);
return sc;
}
_H3API_ H3ExtendedDlg::H3ExtendedDlg(INT x, INT y, INT w, INT h) :
H3BaseDlg(x, y, w, h)
{
}
} /* namespace h3 */
| 34.293689 | 232 | 0.69375 |
0a0f1f29e718edf02fe77504a3c521cca069adde | 5,283 | cpp | C++ | mgmtd/source/net/message/nodes/storagepools/ModifyStoragePoolMsgEx.cpp | TomatoYoung/beegfs | edf287940175ecded493183209719d2d90d45374 | [
"BSD-3-Clause"
] | null | null | null | mgmtd/source/net/message/nodes/storagepools/ModifyStoragePoolMsgEx.cpp | TomatoYoung/beegfs | edf287940175ecded493183209719d2d90d45374 | [
"BSD-3-Clause"
] | null | null | null | mgmtd/source/net/message/nodes/storagepools/ModifyStoragePoolMsgEx.cpp | TomatoYoung/beegfs | edf287940175ecded493183209719d2d90d45374 | [
"BSD-3-Clause"
] | null | null | null | #include "ModifyStoragePoolMsgEx.h"
#include <common/app/log/LogContext.h>
#include <common/net/message/nodes/storagepools/ModifyStoragePoolRespMsg.h>
#include <common/net/message/control/GenericResponseMsg.h>
#include <nodes/StoragePoolStoreEx.h>
#include <program/Program.h>
bool ModifyStoragePoolMsgEx::processIncoming(ResponseContext& ctx)
{
if (Program::getApp()->isShuttingDown())
{
ctx.sendResponse(GenericResponseMsg(GenericRespMsgCode_TRYAGAIN, "Mgmtd shutting down."));
return true;
}
StoragePoolStoreEx* storagePoolStore = Program::getApp()->getStoragePoolStore();
if (Program::getApp()->isShuttingDown())
{
ctx.sendResponse(GenericResponseMsg(GenericRespMsgCode_TRYAGAIN, "Mgmtd shutting down."));
return true;
}
FhgfsOpsErr result = FhgfsOpsErr_SUCCESS;
bool changesMade = false;
// check if pool exists
bool poolExists = storagePoolStore->poolExists(poolId);
if (!poolExists)
{
LOG(STORAGEPOOLS, WARNING, "Storage pool ID doesn't exist", poolId);
result = FhgfsOpsErr_INVAL;
goto send_response;
}
bool setDescriptionResp;
if (newDescription && !newDescription->empty()) // changeName
{
setDescriptionResp = storagePoolStore->setPoolDescription(poolId, *newDescription);
if (setDescriptionResp == FhgfsOpsErr_SUCCESS)
{
changesMade = true;
}
else
{
LOG(STORAGEPOOLS, WARNING, "Could not set new description for storage pool");
result = FhgfsOpsErr_INTERNAL;
}
}
else
{
setDescriptionResp = false; // needed later for notifications to metadata nodes
}
if (addTargets) // add targets to the pool
{ // -> this can only happen if targets are in the default pool
for (auto it = addTargets->begin(); it != addTargets->end(); it++)
{
FhgfsOpsErr moveTargetsResp =
storagePoolStore->moveTarget(StoragePoolStore::DEFAULT_POOL_ID, poolId, *it);
if (moveTargetsResp == FhgfsOpsErr_SUCCESS)
{
changesMade = true;
}
else
{
LOG(STORAGEPOOLS, WARNING,
"Could not add target to storage pool. "
"Probably the target doesn't exist or is not a member of the default storage pool.",
poolId, ("targetId",*it));
result = FhgfsOpsErr_INTERNAL;
// however, we still try to move the remaining targets
}
}
}
if (rmTargets) // remove targets from the pool (i.e. move them to the default pool)
{
for (auto it = rmTargets->begin(); it != rmTargets->end(); it++)
{
FhgfsOpsErr moveTargetsResp =
storagePoolStore->moveTarget(poolId, StoragePoolStore::DEFAULT_POOL_ID, *it);
if (moveTargetsResp == FhgfsOpsErr_SUCCESS)
{
changesMade = true;
}
else
{
LOG(STORAGEPOOLS, WARNING,
"Could not remove target from storage pool. "
"Probably the target doesn't exist or is not a member of the storage pool.",
poolId, ("targetId",*it));
result = FhgfsOpsErr_INTERNAL;
// however, we still try to move the remaining targets
}
}
}
if (addBuddyGroups) // add targets to the pool
{ // -> this can only happen if targets are in the default pool
for (auto it = addBuddyGroups->begin(); it != addBuddyGroups->end(); it++)
{
FhgfsOpsErr moveBuddyGroupsResp =
storagePoolStore->moveBuddyGroup(StoragePoolStore::DEFAULT_POOL_ID, poolId, *it);
if (moveBuddyGroupsResp == FhgfsOpsErr_SUCCESS)
{
changesMade = true;
}
else
{
LOG(STORAGEPOOLS, WARNING,
"Could not add buddy group to storage pool. "
"Probably the buddy group doesn't exist "
"or is not a member of the default storage pool.",
poolId, ("buddyGroupId",*it));
result = FhgfsOpsErr_INTERNAL;
// however, we still try to move the remaining buddy groups
}
}
}
if (rmBuddyGroups) // remove targets from the pool (i.e. move them to the default pool)
{
for (auto it = rmBuddyGroups->begin(); it != rmBuddyGroups->end(); it++)
{
FhgfsOpsErr moveBuddyGroupsResp =
storagePoolStore->moveBuddyGroup(poolId, StoragePoolStore::DEFAULT_POOL_ID, *it);
if (moveBuddyGroupsResp == FhgfsOpsErr_SUCCESS)
{
changesMade = true;
}
else
{
LOG(STORAGEPOOLS, WARNING,
"Could not remove buddy group from storage pool. "
"Probably the buddy group doesn't exist or is not a member of the storage pool.",
poolId, ("buddy group",*it));
result = FhgfsOpsErr_INTERNAL;
// however, we still try to move the remaining buddy groups
}
}
}
if (changesMade)
{ // changes were made
Program::getApp()->getHeartbeatMgr()->notifyAsyncRefreshStoragePools();
}
send_response:
ctx.sendResponse(ModifyStoragePoolRespMsg(result));
return true;
}
| 29.847458 | 99 | 0.607609 |
0a1013d51b3e1a8ab70f40d2abc05e2d462045d7 | 5,677 | cpp | C++ | mainwindow.cpp | diegofps/picker | a8e09c74e2d34a17a61ba6e1be08df135cbce60b | [
"Apache-2.0"
] | null | null | null | mainwindow.cpp | diegofps/picker | a8e09c74e2d34a17a61ba6e1be08df135cbce60b | [
"Apache-2.0"
] | null | null | null | mainwindow.cpp | diegofps/picker | a8e09c74e2d34a17a61ba6e1be08df135cbce60b | [
"Apache-2.0"
] | null | null | null | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QToolButton>
#include <QShortcut>
#include <QBitmap>
#include <QStyle>
#include <QFile>
#include <QFileInfo>
#include <QDir>
#include <QSet>
#include <QProcess>
using namespace wup;
MainWindow::MainWindow(Params & params, QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
iconSize = params.getInt("iconSize", 64);
ui->setupUi(this);
configureWindow(params);
configureCloseOnEscape();
configureActions(params);
// auto iconFilepath = "/usr/share/virt-manager/icons/hicolor/48x48/actions/vm_import_wizard.png";
// addButton("Button 1", iconFilepath, "q", 0, 0);
// addButton("Button 2", iconFilepath, "w", 0, 1);
// addButton("Button 3", iconFilepath, "e", 0, 2);
// addButton("Button 4", iconFilepath, "r", 1, 0);
// addButton("Button 5", iconFilepath, "t", 1, 1);
// addButton("Button 6", iconFilepath, "y", 1, 2);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::configureWindow(Params ¶ms)
{
if (params.has("fullscreen"))
{
setWindowFlags(Qt::Widget | Qt::FramelessWindowHint);
setParent(nullptr);
setAttribute(Qt::WA_NoSystemBackground, true);
setAttribute(Qt::WA_TranslucentBackground, true);
// setAttribute(Qt::WA_PaintOnScreen);
QMainWindow::showFullScreen();
if (params.len("fullscreen"))
{
auto color = params.getString("fullscreen");
this->setStyleSheet(QString("background-color: #") + color);
}
}
else
{
setWindowFlags(Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint | Qt::FramelessWindowHint);
setParent(nullptr);
setAttribute(Qt::WA_NoSystemBackground, true);
setAttribute(Qt::WA_TranslucentBackground, true);
}
}
void MainWindow::configureCloseOnEscape()
{
auto s = new QShortcut(QKeySequence("Escape"), this);
connect(s, &QShortcut::activated, [this]()
{
close();
});
}
void MainWindow::changeEvent(QEvent * event)
{
QWidget::changeEvent(event);
if (event->type() == QEvent::ActivationChange && !this->isActiveWindow())
close();
}
void MainWindow::configureActions(Params ¶ms)
{
QList<Action*> actions;
const QString actionsFilepath = params.getString("actions");
const int numCols = params.getInt("cols", 5);
loadActions(actionsFilepath, actions);
int i = 0;
int j = 0;
for (auto & a : actions)
{
addButton(a, i, j);
++j;
if (j == numCols)
{
++i;
j = 0;
}
}
}
void MainWindow::loadActions(const QString actionsFilepath, QList<MainWindow::Action *> &actions)
{
QString homeDir = QDir::homePath();
QFileInfo info(actionsFilepath);
QFile file(actionsFilepath);
QSet<QString> shortcuts;
QDir::setCurrent(info.path());
if (!file.open(QIODevice::ReadOnly))
error("Could not open actions file");
int i = 0;
while (!file.atEnd())
{
QByteArray line = file.readLine();
auto cells = line.split(';');
if (cells.size() != 4)
error("Wrong number of cells in actions file at line", i);
auto a = new Action();
a->name = cells[0];
a->iconFilepath = QString(cells[1]).replace("~", homeDir);
a->shortcut = cells[2];
a->cmd = QString(cells[3]).replace("~", homeDir);
if (shortcuts.contains(a->shortcut))
error("Shortcut mapped twice:", a->shortcut);
actions.push_back(a);
++i;
}
}
void MainWindow::addButton(const Action * a,
const int row,
const int col)
{
// Get the icon
QIcon * icon;
if (a->iconFilepath.endsWith("svg"))
{
icon = new QIcon(a->iconFilepath);
}
else
{
QPixmap pixmap(a->iconFilepath);
if (pixmap.width() != iconSize)
{
QPixmap scaled = pixmap.scaled( QSize(iconSize, iconSize), Qt::KeepAspectRatio, Qt::SmoothTransformation );
icon = new QIcon(scaled);
}
else
{
icon = new QIcon(pixmap);
}
}
// Configure the button
auto b = new QToolButton();
b->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
b->setIconSize(QSize(iconSize,iconSize));
b->setIcon(*icon);
b->setText(a->name + "\n(" + a->shortcut + ")");
b->setStyleSheet(
"QToolButton {"
"border: 0px;"
"border-radius: 6px;"
"background-color: #ff222222;"
"color: #fff;"
"padding-top: 7px;"
"padding-bottom: 6px;"
"padding-right: 20px;"
"padding-left: 20px;"
"}"
"QToolButton:hover {"
"background-color: #ff333333;"
"}");
// Callback to execute this action
auto callback = [a, this]()
{
// QProcess::execute(a->cmd);
QDir::setCurrent(QDir::homePath());
QProcess::startDetached(a->cmd);
close();
};
// Configure button click
connect(b, &QToolButton::clicked, callback);
// Configure shortcut
auto s = new QShortcut(QKeySequence(a->shortcut), this);
connect(s, &QShortcut::activated, callback);
// Add button to screen
ui->gridLayout->addWidget(b, row, col);
}
void MainWindow::on_actiona_triggered()
{
print("a");
}
void MainWindow::on_actionb_triggered()
{
print("b");
}
void MainWindow::on_shortcut()
{
print("action");
}
| 24.469828 | 119 | 0.574599 |
0a116c910ba20a7b92c886dcea15f9b4b3040368 | 24,529 | cpp | C++ | source/renderer/scene/adaptiveGrid/AdaptiveGrid.cpp | DaSutt/VolumetricParticles | 6ec9bac4bec4a8757343bb770b23110ef2364dfd | [
"Apache-2.0"
] | 6 | 2017-06-26T11:42:26.000Z | 2018-09-10T17:53:53.000Z | source/renderer/scene/adaptiveGrid/AdaptiveGrid.cpp | DaSutt/VolumetricParticles | 6ec9bac4bec4a8757343bb770b23110ef2364dfd | [
"Apache-2.0"
] | 8 | 2017-06-24T20:25:42.000Z | 2017-08-09T10:50:40.000Z | source/renderer/scene/adaptiveGrid/AdaptiveGrid.cpp | DaSutt/VolumetricParticles | 6ec9bac4bec4a8757343bb770b23110ef2364dfd | [
"Apache-2.0"
] | null | null | null | /*
MIT License
Copyright(c) 2017 Daniel Suttor
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 "AdaptiveGrid.h"
#include "..\..\passResources\ShaderBindingManager.h"
#include "..\..\passes\Passes.h"
#include "..\..\ShadowMap.h"
#include "..\..\resources\BufferManager.h"
#include "..\..\resources\ImageManager.h"
#include "..\..\passes\GuiPass.h"
#include "..\..\wrapper\Surface.h"
#include "..\..\wrapper\Barrier.h"
#include "..\..\wrapper\QueryPool.h"
#include "..\..\..\scene\Scene.h"
#include "..\..\..\utility\Status.h"
#include "AdaptiveGridConstants.h"
#include "debug\DebugData.h"
#include <glm\gtc\matrix_transform.hpp>
#define GLM_ENABLE_EXPERIMENTAL
#include <glm\gtx\component_wise.hpp>
#include <random>
#include <functional>
namespace Renderer
{
constexpr int debugScreenDivision_ = 1;
AdaptiveGrid::AdaptiveGrid(float worldCellSize) :
worldCellSize_{ worldCellSize },
imageAtlas_{GridConstants::imageResolution}
{
//min count for grid level data
gridLevelData_.resize(3);
}
void AdaptiveGrid::SetWorldExtent(const glm::vec3& min, const glm::vec3& max)
{
glm::vec3 scale;
const auto worldScale = max - min;
//grid resolution of root node is 1
std::vector<int> resolutions = { 1, GridConstants::nodeResolution, GridConstants::nodeResolution };
glm::vec3 maxScale = CalcMaxScale(resolutions, GridConstants::nodeResolution);
//add additional levels until the whole world is covered
/*while (glm::compMax(worldScale) > glm::compMax(maxScale))
{
resolutions.push_back(gridResolution_);
maxScale = CalcMaxScale(resolutions, imageResolution_);
}*/
scale = maxScale;
printf("Scene size %f %f %f\n", scale.x, scale.y, scale.z);
//Calculate world extent
const auto center = glm::vec3(0,0,0);
const auto halfScale = scale * 0.5f;
worldBoundingBox_.min = center - halfScale;
worldBoundingBox_.max = center + halfScale;
raymarchingData_.gridMinPosition = worldBoundingBox_.min;
radius_ = glm::distance(worldBoundingBox_.max, glm::vec3(0.0f));
int globalResolution = resolutions[0];
//Initialize all grid levels
for (size_t i = 0; i < resolutions.size(); ++i)
{
if (i > 0)
{
globalResolution *= resolutions[i];
}
gridLevels_.push_back({ resolutions[i] });
gridLevels_.back().SetWorldExtend(worldBoundingBox_.min, scale, static_cast<float>(globalResolution));
}
for (size_t i = 1; i < gridLevels_.size(); ++i)
{
gridLevels_[i].SetParentLevel(&gridLevels_[i - 1]);
}
gridLevels_.back().SetLeafLevel();
mostDetailedParentLevel_ = static_cast<int>(gridLevels_.size() - 2);
raymarchingData_.maxLevel = static_cast<int>(resolutions.size() - 1);
gridLevelData_.resize(resolutions.size());
for (size_t i = 0; i < resolutions.size(); ++i)
{
gridLevelData_[i].gridCellSize = gridLevels_[i].GetGridCellSize();
gridLevelData_[i].gridResolution = GridConstants::nodeResolution;
gridLevelData_[i].childCellSize = gridLevels_[i].GetGridCellSize() / GridConstants::nodeResolution;
}
groundFog_.SetSizes(gridLevels_[1].GetGridCellSize(), scale.x);
particleSystems_.SetGridOffset(worldBoundingBox_.min);
Status::UpdateGrid(scale, worldBoundingBox_.min);
Status::SetParticleSystems(&particleSystems_);
}
void AdaptiveGrid::ResizeConstantBuffers(BufferManager* bufferManager)
{
const auto levelBufferSize = sizeof(LevelData) * gridLevelData_.size();
bufferManager->Ref_RequestBufferResize(cbIndices_[CB_RAYMARCHING_LEVELS], levelBufferSize);
}
void AdaptiveGrid::RequestResources(ImageManager* imageManager, BufferManager* bufferManager, int frameCount)
{
BufferManager::BufferInfo bufferInfo;
bufferInfo.typeBits = BufferManager::BUFFER_CONSTANT_BIT | BufferManager::BUFFER_SCENE_BIT;
bufferInfo.pool = BufferManager::MEMORY_CONSTANT;
bufferInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
bufferInfo.bufferingCount = frameCount;
frameCount_ = frameCount;
auto cbIndex = CB_RAYMARCHING;
{
bufferInfo.data = &raymarchingData_;
bufferInfo.size = sizeof(RaymarchingData);
cbIndices_[cbIndex] = bufferManager->Ref_RequestBuffer(bufferInfo);
}
cbIndex = CB_RAYMARCHING_LEVELS;
{
bufferInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
bufferInfo.data = gridLevelData_.data();
cbIndices_[cbIndex] = bufferManager->Ref_RequestBuffer(bufferInfo);
}
{
BufferManager::BufferInfo gridBufferInfo;
gridBufferInfo.pool = BufferManager::MEMORY_GRID;
gridBufferInfo.size = sizeof(uint32_t);
gridBufferInfo.typeBits = BufferManager::BUFFER_GRID_BIT;
gridBufferInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
gridBufferInfo.bufferingCount = frameCount;
for (size_t i = GPU_BUFFER_NODE_INFOS; i < GPU_MAX; ++i)
{
gpuResources_[i] = { bufferManager->Ref_RequestBuffer(gridBufferInfo), 1 };
}
}
imageAtlas_.RequestResources(imageManager, bufferManager, ImageManager::MEMORY_POOL_GRID, frameCount);
const int atlasImageIndex = imageAtlas_.GetImageIndex();
const int atlasBufferIndex = imageAtlas_.GetBufferIndex();
debugFilling_.SetGpuResources(atlasImageIndex, atlasBufferIndex);
globalVolume_.RequestResources(bufferManager, frameCount, atlasImageIndex);
groundFog_.RequestResources(imageManager, bufferManager, frameCount, atlasImageIndex);
particleSystems_.RequestResources(bufferManager, frameCount, atlasImageIndex);
mipMapping_.RequestResources(imageManager, bufferManager, frameCount, atlasImageIndex);
neighborCells_.RequestResources(bufferManager, frameCount, atlasImageIndex);
for (size_t i = 0; i < gpuResources_.size(); ++i)
{
gpuResources_[i].maxSize = sizeof(int);
}
}
void AdaptiveGrid::SetImageIndices(int raymarching, int depth, int shadowMap, int noise)
{
raymarchingImageIndex_ = raymarching;
//TODO to test the image atlas
//raymarchingImageIndex_ = mipMapping_.GetImageAtlasIndex();
depthImageIndex_ = depth;
shadowMapIndex_ = shadowMap;
noiseImageIndex_ = noise;
debugTraversal_.SetImageIndices(
imageAtlas_.GetImageIndex(),
depthImageIndex_,
shadowMap,
noise
);
}
void AdaptiveGrid::OnLoadScene(const Scene* scene)
{
particleSystems_.OnLoadScene(scene);
}
void AdaptiveGrid::UpdateParticles(float dt)
{
particleSystems_.Update(dt);
}
int AdaptiveGrid::GetShaderBinding(ShaderBindingManager* bindingManager, Pass pass)
{
ShaderBindingManager::BindingInfo bindingInfo = {};
switch (pass)
{
case GRID_PASS_GLOBAL:
return globalVolume_.GetShaderBinding(bindingManager, frameCount_);
case GRID_PASS_GROUND_FOG:
return groundFog_.GetShaderBinding(bindingManager, frameCount_);
case GRID_PASS_PARTICLES:
return particleSystems_.GetShaderBinding(bindingManager, frameCount_);
case GRID_PASS_DEBUG_FILLING:
return debugFilling_.GetShaderBinding(bindingManager, frameCount_);
case GRID_PASS_MIPMAPPING:
return mipMapping_.GetShaderBinding(bindingManager, frameCount_, pass - GRID_PASS_MIPMAPPING);
case GRID_PASS_MIPMAPPING_MERGING:
return mipMapping_.GetShaderBinding(bindingManager, frameCount_, pass - GRID_PASS_MIPMAPPING);
case GRID_PASS_NEIGHBOR_UPDATE:
return neighborCells_.GetShaderBinding(bindingManager, frameCount_);
case GRID_PASS_RAYMARCHING:
{
bindingInfo.pass = SUBPASS_VOLUME_ADAPTIVE_RAYMARCHING;
bindingInfo.resourceIndex = {
raymarchingImageIndex_,
depthImageIndex_,
imageAtlas_.GetImageIndex(),
//mipMapping_.GetImageAtlasIndex(),
shadowMapIndex_,
noiseImageIndex_,
gpuResources_[GPU_BUFFER_NODE_INFOS].index,
gpuResources_[GPU_BUFFER_ACTIVE_BITS].index,
gpuResources_[GPU_BUFFER_BIT_COUNTS].index,
gpuResources_[GPU_BUFFER_CHILDS].index,
cbIndices_[CB_RAYMARCHING],
cbIndices_[CB_RAYMARCHING_LEVELS]
};
bindingInfo.stages = {
VK_SHADER_STAGE_COMPUTE_BIT,
VK_SHADER_STAGE_COMPUTE_BIT,
VK_SHADER_STAGE_COMPUTE_BIT,
VK_SHADER_STAGE_COMPUTE_BIT,
VK_SHADER_STAGE_COMPUTE_BIT,
VK_SHADER_STAGE_COMPUTE_BIT,
VK_SHADER_STAGE_COMPUTE_BIT,
VK_SHADER_STAGE_COMPUTE_BIT,
VK_SHADER_STAGE_COMPUTE_BIT,
VK_SHADER_STAGE_COMPUTE_BIT,
VK_SHADER_STAGE_COMPUTE_BIT };
bindingInfo.types = {
VK_DESCRIPTOR_TYPE_STORAGE_IMAGE,
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
VK_DESCRIPTOR_TYPE_STORAGE_BUFFER };
bindingInfo.refactoring_ = { false, false, true, true, true, true, true, true, true, true, true };
bindingInfo.setCount = frameCount_;
}break;
default:
printf("Get shader bindings from adaptive grid for invalid type\n");
break;
}
return bindingManager->RequestShaderBinding(bindingInfo);
}
void AdaptiveGrid::Update(BufferManager* bufferManager, ImageManager* imageManager, Scene* scene, Surface* surface, ShadowMap* shadowMap, int frameIndex)
{
UpdateCBData(scene, surface, shadowMap);
UpdateGrid(scene);
ResizeGpuResources(bufferManager, imageManager);
UpdateGpuResources(bufferManager, frameIndex);
if (GuiPass::GetDebugVisState().nodeRendering)
{
UpdateBoundingBoxes();
}
}
void AdaptiveGrid::Dispatch(QueueManager* queueManager, ImageManager* imageManager, BufferManager* bufferManager,
VkCommandBuffer commandBuffer, Pass pass, int frameIndex, int level)
{
switch (pass)
{
case GRID_PASS_GLOBAL:
{
globalVolume_.Dispatch(imageManager, commandBuffer, frameIndex);
}
break;
case GRID_PASS_GROUND_FOG:
{
groundFog_.Dispatch(queueManager, imageManager, bufferManager, commandBuffer, frameIndex);
} break;
case GRID_PASS_PARTICLES:
particleSystems_.Dispatch(imageManager, commandBuffer, frameIndex);
break;
case GRID_PASS_DEBUG_FILLING:
debugFilling_.Dispatch(imageManager, commandBuffer);
break;
case GRID_PASS_MIPMAPPING:
mipMappingStarted_ = true;
case GRID_PASS_MIPMAPPING_MERGING:
mipMapping_.Dispatch(imageManager, bufferManager, commandBuffer, frameIndex, level, pass - GRID_PASS_MIPMAPPING);
break;
case GRID_PASS_NEIGHBOR_UPDATE:
{
neighborCells_.Dispatch(commandBuffer, imageManager, level, mipMappingStarted_, frameIndex);
}
break;
case GRID_PASS_RAYMARCHING:
mipMappingStarted_ = false;
break;
default:
break;
}
}
namespace
{
uint32_t CalcDispatchSize(uint32_t number, uint32_t multiple)
{
if (number % multiple == 0)
{
return number / multiple;
}
else
{
return number / multiple + 1;
}
}
}
void AdaptiveGrid::Raymarch(ImageManager* imageManager, VkCommandBuffer commandBuffer, uint32_t width, uint32_t height, int frameIndex)
{
if (initialized_)
{
const uint32_t dispatchX = CalcDispatchSize(width / debugScreenDivision_, 16);
const uint32_t dispatchY = CalcDispatchSize(height / debugScreenDivision_, 16);
auto& queryPool = Wrapper::QueryPool::GetInstance();
queryPool.TimestampStart(commandBuffer, Wrapper::TIMESTAMP_GRID_RAYMARCHING, frameIndex);
vkCmdDispatch(commandBuffer, dispatchX, dispatchY, 1);
queryPool.TimestampEnd(commandBuffer, Wrapper::TIMESTAMP_GRID_RAYMARCHING, frameIndex);
ImageManager::BarrierInfo imageAtlasBarrier{};
imageAtlasBarrier.imageIndex = imageAtlas_.GetImageIndex();
imageAtlasBarrier.type = ImageManager::BARRIER_READ_WRITE;
ImageManager::BarrierInfo shadowMapBarrier{};
shadowMapBarrier.imageIndex = shadowMapIndex_;
shadowMapBarrier.type = ImageManager::BARRIER_READ_WRITE;
auto barriers = imageManager->Barrier({ imageAtlasBarrier, shadowMapBarrier });
Wrapper::PipelineBarrierInfo pipelineBarrierInfo{};
pipelineBarrierInfo.src = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
pipelineBarrierInfo.dst = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
pipelineBarrierInfo.AddImageBarriers(barriers);
Wrapper::AddPipelineBarrier(commandBuffer, pipelineBarrierInfo);
}
}
void AdaptiveGrid::UpdateDebugTraversal(QueueManager* queueManager, BufferManager* bufferManager, ImageManager* imageManager)
{
const auto& volumeState = GuiPass::GetVolumeState();
if (volumeState.debugTraversal && !previousFrameTraversal_)
{
previousFrameTraversal_ = true;
const glm::ivec2 position = static_cast<glm::ivec2>(volumeState.cursorPosition);
debugTraversal_.Traversal(queueManager, bufferManager, imageManager, position.x, position.y);
}
else
{
previousFrameTraversal_ = false;
}
}
void AdaptiveGrid::UpdateCBData(Scene* scene, Surface* surface, ShadowMap* shadowMap)
{
{
const auto& camera = scene->GetCamera();
raymarchingData_.viewPortToWorld = glm::inverse(camera.GetViewProj());
raymarchingData_.nearPlane = camera.nearZ_;
raymarchingData_.farPlane = camera.farZ_;
raymarchingData_.shadowCascades = shadowMap->GetShadowMatrices();
const auto& screenSize = surface->GetSurfaceSize();
raymarchingData_.screenSize = { screenSize.width, screenSize.height};
static bool printedScreenSize = false;
if (!printedScreenSize)
{
printf("Raymarching resolution %f %f\n", raymarchingData_.screenSize.x, raymarchingData_.screenSize.y);
printedScreenSize = true;
}
}
{
const auto& lightingState = GuiPass::GetLightingState();
const auto& lv = lightingState.lightVector;
const auto& li = lightingState.irradiance;
raymarchingData_.irradiance = glm::vec3(li[0], li[1], li[2]);
const auto lightDir = glm::vec4(lv.x, lv.y, lv.z, 0.0f);
raymarchingData_.lightDirection = lightDir;
const glm::vec4 shadowRayNormalPos = glm::vec4(0, 0, 0, 1)
+ radius_ * lightDir;
raymarchingData_.shadowRayPlaneNormal = lightDir;
raymarchingData_.shadowRayPlaneDistance = glm::dot(-lightDir, shadowRayNormalPos);
}
{
const auto& volumeState = GuiPass::GetVolumeState();
globalMediumData_.scattering = volumeState.globalValue.scattering;
globalMediumData_.extinction = volumeState.globalValue.absorption + volumeState.globalValue.scattering;
globalMediumData_.phaseG = volumeState.globalValue.phaseG;
raymarchingData_.lodScale_Reciprocal = 1.0f / volumeState.lodScale;
raymarchingData_.globalScattering = { globalMediumData_.scattering, globalMediumData_.extinction, globalMediumData_.phaseG, 0.0f };
raymarchingData_.maxDepth = volumeState.maxDepth;
raymarchingData_.jitteringScale = volumeState.jitteringScale;
raymarchingData_.maxSteps = volumeState.stepCount;
raymarchingData_.exponentialScale = log(volumeState.maxDepth);
//TODO check why these values are double
volumeMediaData_.scattering = volumeState.groundFogValue.scattering;
volumeMediaData_.extinction = volumeState.groundFogValue.absorption + volumeState.groundFogValue.scattering;
volumeMediaData_.phaseG = volumeState.groundFogValue.phaseG;
if (volumeState.debugTraversal)
{
DebugData::raymarchData_ = raymarchingData_;
DebugData::levelData_.data = gridLevelData_;
}
groundFog_.UpdateCBData(volumeState.groundFogHeight,
volumeState.groundFogValue.scattering,
volumeState.groundFogValue.absorption,
volumeState.groundFogValue.phaseG,
volumeState.groundFogNoiseScale);
globalVolume_.UpdateCB(&groundFog_);
for (auto& levelData : gridLevelData_)
{
//levelData.minStepSize = levelData.gridCellSize / volumeState.lodScale;
levelData.shadowRayStepSize = levelData.gridCellSize /
static_cast<float>(volumeState.shadowRayPerLevel);
levelData.texelScale = GridConstants::nodeResolution /
((GridConstants::nodeResolution + 2) * imageAtlas_.GetSideLength() *
levelData.gridCellSize);
}
}
{
static std::default_random_engine generator;
static std::uniform_real_distribution<float> distribution(0.0f, 1.0f);
static auto RandPos = std::bind(distribution, generator);
raymarchingData_.randomness = { RandPos(), RandPos(), RandPos() };
}
{
const float nodeResolutionWithBorder = static_cast<float>(GridConstants::nodeResolution + 2);
raymarchingData_.atlasSideLength_Reciprocal = 1.0f / raymarchingData_.atlasSideLength;
raymarchingData_.textureOffset = 1.0f / nodeResolutionWithBorder / raymarchingData_.atlasSideLength;
raymarchingData_.atlasTexelToNodeTexCoord = 1.0f / GridConstants::imageResolution /
static_cast<float>(raymarchingData_.atlasSideLength);
const float relTexelSize = 1.0f / GridConstants::imageResolution / static_cast<float>(raymarchingData_.atlasSideLength);
raymarchingData_.texelHalfSize = relTexelSize * 0.5f;
raymarchingData_.nodeTexelSize = raymarchingData_.atlasSideLength_Reciprocal - relTexelSize;
}
particleSystems_.UpdateCBData(&gridLevels_[2]);
}
void AdaptiveGrid::UpdateGrid(Scene* scene)
{
for (auto& gridLevel : gridLevels_)
{
gridLevel.Reset();
}
gridLevels_[0].AddNode({ 0,0,0 });
//gridLevels_[1].AddNode({ 256, 256, 256 });
//gridLevels_[2].AddNode({ 256, 258,256 });
//gridLevels_[2].AddNode({ 258, 256, 256 });
//gridLevels_[2].AddNode({ 256, 256, 258 });
//gridLevels_[2].AddNode({ 254, 256,256 });
groundFog_.UpdateGridCells(&gridLevels_[1]);
particleSystems_.GridInsertParticleNodes(raymarchingData_.gridMinPosition, &gridLevels_[2]);
int parentChildOffset = 0;
for (auto& level : gridLevels_)
{
parentChildOffset = level.Update(parentChildOffset);
}
imageAtlas_.UpdateSize(gridLevels_.back().GetImageOffset());
const int atlasSideLength = imageAtlas_.GetSideLength();
mipMapping_.UpdateAtlasProperties(atlasSideLength, imageAtlas_.GetResolution());
for (auto& level : gridLevels_)
{
level.UpdateImageIndices(atlasSideLength);
}
particleSystems_.UpdateGpuData(&gridLevels_[1], &gridLevels_[2], atlasSideLength);
const int maxParentLevel = static_cast<int>(gridLevels_.size() - 1);
for (size_t i = 0; i < maxParentLevel; ++i)
{
mipMapping_.UpdateMipMapNodes(&gridLevels_[i], &gridLevels_[i + 1]);
}
//neighborCells_.CalculateNeighbors(gridLevels_);
debugFilling_.SetImageCount(&gridLevels_[2]);
debugFilling_.AddDebugNodes(gridLevels_);
volumeMediaData_.atlasSideLength = atlasSideLength;
volumeMediaData_.imageResolutionOffset = GridConstants::imageResolution;
raymarchingData_.atlasSideLength = atlasSideLength;
//neighborCells_.UpdateAtlasProperties(atlasSideLength);
}
std::array<VkDeviceSize, AdaptiveGrid::GPU_MAX> AdaptiveGrid::GetGpuResourceSize()
{
std::array<VkDeviceSize, GPU_MAX> totalSizes{};
for (const auto& level : gridLevels_)
{
totalSizes[GPU_BUFFER_NODE_INFOS] += level.GetNodeInfoSize();
totalSizes[GPU_BUFFER_ACTIVE_BITS] += level.GetActiveBitSize();
totalSizes[GPU_BUFFER_BIT_COUNTS] += level.GetBitCountsSize();
totalSizes[GPU_BUFFER_CHILDS] += level.GetChildSize();
}
return totalSizes;
}
void AdaptiveGrid::ResizeGpuResources(BufferManager* bufferManager, ImageManager* imageManager)
{
bool resize = false;
std::vector<ResourceResize>resourceResizes;
const auto totalSizes = GetGpuResourceSize();
imageAtlas_.ResizeImage(imageManager);
for (int i = 0; i < GPU_MAX; ++i)
{
const auto totalSize = totalSizes[i];
auto& maxSize = gpuResources_[i].maxSize;
if (maxSize < totalSize)
{
resize = true;
maxSize = totalSize;
}
resourceResizes.push_back({ maxSize, gpuResources_[i].index });
}
resize = groundFog_.ResizeGPUResources(resourceResizes) ? true : resize;
resize = particleSystems_.ResizeGpuResources(resourceResizes) ? true : resize;
resize = mipMapping_.ResizeGpuResources(imageManager, resourceResizes) ? true : resize;
resize = neighborCells_.ResizeGpuResources(resourceResizes) ? true : resize;
if (!initialized_)
{
resize = true;
initialized_ = true;
}
if (resize)
{
bufferManager->Ref_ResizeBuffers(resourceResizes, BufferManager::MEMORY_GRID);
}
resizing_ = resize;
}
namespace
{
struct ResourceInfo
{
void* dataPtr;
int offset;
};
}
void* AdaptiveGrid::GetDebugBufferCopyDst(GridLevel::BufferType type, int size)
{
switch (type)
{
case GridLevel::BUFFER_NODE_INFOS:
DebugData::nodeInfos_.data.resize(size / sizeof(NodeInfo));
return DebugData::nodeInfos_.data.data();
case GridLevel::BUFFER_ACTIVE_BITS:
DebugData::activeBits_.data.resize(size / sizeof(uint32_t));
return DebugData::activeBits_.data.data();
case GridLevel::BUFFER_BIT_COUNTS:
DebugData::bitCounts_.data.resize(size / sizeof(int));
return DebugData::bitCounts_.data.data();
case GridLevel::BUFFER_CHILDS:
DebugData::childIndices_.indices.resize(size / sizeof(int));
return DebugData::childIndices_.indices.data();
default:
printf("Invalid buffer type to get copy dst\n");
break;
}
return nullptr;
}
void AdaptiveGrid::UpdateGpuResources(BufferManager* bufferManager, int frameIndex)
{
const auto& volumeState = GuiPass::GetVolumeState();
std::array<ResourceInfo, GPU_MAX> offsets{};
for (int i = 0; i < GPU_MAX; ++i)
{
offsets[i].dataPtr =
bufferManager->Ref_Map(gpuResources_[i].index, frameIndex, BufferManager::BUFFER_GRID_BIT);
}
for (size_t i = 0; i < gridLevels_.size(); ++i)
{
//TODO check if neccessary
gridLevelData_[i].nodeArrayOffset = offsets[GridLevel::BUFFER_NODE_INFOS].offset;
gridLevelData_[i].childArrayOffset = offsets[GridLevel::BUFFER_CHILDS].offset;
gridLevelData_[i].nodeOffset = gridLevelData_[i].nodeArrayOffset / sizeof(NodeInfo);
gridLevelData_[i].childOffset = gridLevelData_[i].childArrayOffset / sizeof(int);
for (int resourceIndex = 0; resourceIndex < GridLevel::BUFFER_MAX; ++resourceIndex)
{
const auto bufferType = static_cast<GridLevel::BufferType>(resourceIndex);
const int offset = offsets[resourceIndex].offset;
offsets[resourceIndex].offset = gridLevels_[i].CopyBufferData(offsets[resourceIndex].dataPtr,
static_cast<GridLevel::BufferType>(resourceIndex), offsets[resourceIndex].offset);
if (volumeState.debugTraversal)
{
gridLevels_[i].CopyBufferData(GetDebugBufferCopyDst(bufferType, offsets[resourceIndex].offset),
bufferType, offset);
}
}
}
for (int i = GPU_BUFFER_NODE_INFOS; i < GPU_MAX; ++i)
{
bufferManager->Ref_Unmap(gpuResources_[i].index, frameIndex, BufferManager::BUFFER_GRID_BIT);
}
groundFog_.UpdatePerNodeBuffer(bufferManager, &gridLevels_[1], frameIndex, imageAtlas_.GetSideLength());
particleSystems_.UpdateGpuResources(bufferManager, frameIndex);
mipMapping_.UpdateGpuResources(bufferManager, frameIndex);
neighborCells_.UpdateGpuResources(bufferManager, frameIndex);
}
void AdaptiveGrid::UpdateBoundingBoxes()
{
debugBoundingBoxes_.clear();
for (auto& level : gridLevels_)
{
level.UpdateBoundingBoxes();
const auto& nodeData = level.GetNodeData();
glm::vec4 color = glm::vec4(0, 1, 0, 1);
for (size_t i = 0; i < level.nodeBoundingBoxes_.size(); ++i)
{
debugBoundingBoxes_.push_back({
WorldMatrix(level.nodeBoundingBoxes_[i]), color
});
}
}
debugBoundingBoxes_.push_back({ WorldMatrix(worldBoundingBox_), glm::vec4(0,1,0,0) });
}
glm::vec3 AdaptiveGrid::CalcMaxScale(std::vector<int> levelResolutions, int textureResolution)
{
glm::vec3 scale = glm::vec3(worldCellSize_) * static_cast<float>(textureResolution);
for (const auto res : levelResolutions)
{
scale *= static_cast<float>(res);
}
return scale;
}
} | 34.941595 | 154 | 0.755229 |
0a11745da99a17acd76d39f6448e62662e77c7cd | 826 | hpp | C++ | iOS/G3MiOSSDK/Commons/Mesh/DirectMesh.hpp | RMMJR/g3m | 990467dc8e2bf584f8b512bdf06ecf4def625185 | [
"BSD-2-Clause"
] | 1 | 2016-08-23T10:29:44.000Z | 2016-08-23T10:29:44.000Z | iOS/G3MiOSSDK/Commons/Mesh/DirectMesh.hpp | RMMJR/g3m | 990467dc8e2bf584f8b512bdf06ecf4def625185 | [
"BSD-2-Clause"
] | null | null | null | iOS/G3MiOSSDK/Commons/Mesh/DirectMesh.hpp | RMMJR/g3m | 990467dc8e2bf584f8b512bdf06ecf4def625185 | [
"BSD-2-Clause"
] | null | null | null | //
// DirectMesh.hpp
// G3MiOSSDK
//
// Created by Diego Gomez Deck on 12/1/12.
//
//
#ifndef __G3MiOSSDK__DirectMesh__
#define __G3MiOSSDK__DirectMesh__
#include "AbstractMesh.hpp"
class DirectMesh : public AbstractMesh {
protected:
void rawRender(const G3MRenderContext* rc) const;
Mesh* createNormalsMesh() const;
public:
DirectMesh(const int primitive,
bool owner,
const Vector3D& center,
IFloatBuffer* vertices,
float lineWidth,
float pointSize,
const Color* flatColor = NULL,
IFloatBuffer* colors = NULL,
const float colorsIntensity = 0.0f,
bool depthTest = true,
IFloatBuffer* normals = NULL);
~DirectMesh() {
#ifdef JAVA_CODE
super.dispose();
#endif
}
};
#endif
| 19.209302 | 51 | 0.621065 |
0a11a41c4f6816516a80e4c0094caf5df7e4b4c3 | 137 | inl | C++ | TAO/orbsvcs/orbsvcs/Event/EC_Null_Scheduling.inl | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 36 | 2015-01-10T07:27:33.000Z | 2022-03-07T03:32:08.000Z | TAO/orbsvcs/orbsvcs/Event/EC_Null_Scheduling.inl | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 2 | 2018-08-13T07:30:51.000Z | 2019-02-25T03:04:31.000Z | TAO/orbsvcs/orbsvcs/Event/EC_Null_Scheduling.inl | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 38 | 2015-01-08T14:12:06.000Z | 2022-01-19T08:33:00.000Z | // $Id: EC_Null_Scheduling.inl 73791 2006-07-27 20:54:56Z wotte $
ACE_INLINE
TAO_EC_Null_Scheduling::TAO_EC_Null_Scheduling (void)
{
}
| 17.125 | 65 | 0.773723 |
0a12180042ae162df850e0e4289edbb1cfb7fd52 | 369 | hpp | C++ | include/texugo/message/MessageParser.hpp | leozz37/Texugo | 61d1d2e65fb383b1402bb5d61871d72563060494 | [
"MIT"
] | 20 | 2020-07-17T04:07:37.000Z | 2022-01-07T19:02:07.000Z | include/texugo/message/MessageParser.hpp | leozz37/Texugo | 61d1d2e65fb383b1402bb5d61871d72563060494 | [
"MIT"
] | 15 | 2020-08-29T03:30:34.000Z | 2022-02-27T10:12:27.000Z | include/texugo/message/MessageParser.hpp | leozz37/Texugo | 61d1d2e65fb383b1402bb5d61871d72563060494 | [
"MIT"
] | 5 | 2020-07-11T10:38:37.000Z | 2020-09-26T20:56:45.000Z | #pragma once
#include <nlohmann/json.hpp>
#include <string>
#include <vector>
class MessageParser
{
public:
explicit MessageParser(const std::string&);
const std::vector<std::string>& getDestination() const;
const std::string& getMessage() const;
private:
std::vector<std::string> m_destination;
std::string m_message;
}; | 23.0625 | 59 | 0.661247 |
0a14825b689f0c39af63ff61ae29ce1652980afa | 1,250 | cpp | C++ | src/game/piece/pawn.cpp | Aviraj55/Chess | 51dfdd4a33f18f6cbb9666b6b16ecd4d859ac3e1 | [
"MIT"
] | null | null | null | src/game/piece/pawn.cpp | Aviraj55/Chess | 51dfdd4a33f18f6cbb9666b6b16ecd4d859ac3e1 | [
"MIT"
] | null | null | null | src/game/piece/pawn.cpp | Aviraj55/Chess | 51dfdd4a33f18f6cbb9666b6b16ecd4d859ac3e1 | [
"MIT"
] | 1 | 2020-10-03T20:59:17.000Z | 2020-10-03T20:59:17.000Z | #include "pawn.h"
#include "../board.h"
std::vector<Coordinate> Pawn::get_candidate_moves() const {
std::vector<Coordinate> candidate_moves;
int dir = color_ == Color::WHITE ? 1 : -1;
// Pawns may always move one square forward
std::vector<int> forward_moves(1, 1);
if (move_history_.empty()) {
// If this is the first move that this pawn has made, then it may optionally
// move two squares forward
forward_moves.push_back(2);
}
for (int rank_offset : forward_moves) {
Coordinate dest(coordinate_.get_rank() + rank_offset * dir,
coordinate_.get_file());
// When moving forward, pawns may be blocked by pieces of either color (and
// may not capture)
if (board_->piece_at(dest) == nullptr) {
candidate_moves.push_back(dest);
}
}
// Pawns may move diagonally one square to capture an enemy piece
for (int file_offset : {-1, 1}) {
Coordinate dest(coordinate_.get_rank() + dir,
coordinate_.get_file() + file_offset);
Piece *dest_piece = board_->piece_at(dest);
if (dest_piece != nullptr && dest_piece->get_color() != color_) {
candidate_moves.push_back(dest);
}
}
// TODO: Implement en passant
return candidate_moves;
}
| 30.487805 | 80 | 0.656 |
0a16121a40d0ec98bee0874a48b135d8e44a5164 | 3,651 | cpp | C++ | src/robot_state_publisher-kinetic-devel/test/test_subclass.cpp | mowtian/Projektarbeit | 43d575f6cf06690e869da4f995ed271fe4088f69 | [
"MIT"
] | 37 | 2017-12-13T16:14:32.000Z | 2022-02-19T03:12:52.000Z | src/robot_state_publisher-kinetic-devel/test/test_subclass.cpp | mowtian/Projektarbeit | 43d575f6cf06690e869da4f995ed271fe4088f69 | [
"MIT"
] | 71 | 2018-01-17T20:17:03.000Z | 2022-03-23T19:48:45.000Z | src/robot_state_publisher-kinetic-devel/test/test_subclass.cpp | mowtian/Projektarbeit | 43d575f6cf06690e869da4f995ed271fe4088f69 | [
"MIT"
] | 32 | 2018-01-08T03:21:18.000Z | 2022-02-19T03:12:47.000Z | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2016, Open Source Robotics Foundation, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <gtest/gtest.h>
#include <urdf/model.h>
#include <kdl_parser/kdl_parser.hpp>
#include "robot_state_publisher/joint_state_listener.h"
#include "robot_state_publisher/robot_state_publisher.h"
namespace robot_state_publisher_test
{
class AccessibleJointStateListener : public robot_state_publisher::JointStateListener
{
public:
AccessibleJointStateListener(
const KDL::Tree& tree, const MimicMap& m, const urdf::Model& model) :
robot_state_publisher::JointStateListener(tree, m, model)
{
}
bool usingTfStatic() const {
return use_tf_static_;
}
};
class AccessibleRobotStatePublisher : public robot_state_publisher::RobotStatePublisher
{
public:
AccessibleRobotStatePublisher(const KDL::Tree& tree, const urdf::Model& model) :
robot_state_publisher::RobotStatePublisher(tree, model)
{
}
const urdf::Model & getModel() const {
return model_;
}
};
} // robot_state_publisher_test
TEST(TestRobotStatePubSubclass, robot_state_pub_subclass)
{
urdf::Model model;
model.initParam("robot_description");
KDL::Tree tree;
if (!kdl_parser::treeFromUrdfModel(model, tree)){
ROS_ERROR("Failed to extract kdl tree from xml robot description");
FAIL();
}
MimicMap mimic;
for(std::map< std::string, urdf::JointSharedPtr >::iterator i = model.joints_.begin(); i != model.joints_.end(); i++){
if(i->second->mimic){
mimic.insert(make_pair(i->first, i->second->mimic));
}
}
robot_state_publisher_test::AccessibleRobotStatePublisher state_pub(tree, model);
EXPECT_EQ(model.name_, state_pub.getModel().name_);
EXPECT_EQ(model.root_link_, state_pub.getModel().root_link_);
robot_state_publisher_test::AccessibleJointStateListener state_listener(tree, mimic, model);
EXPECT_TRUE(state_listener.usingTfStatic());
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "test_subclass");
testing::InitGoogleTest(&argc, argv);
int res = RUN_ALL_TESTS();
return res;
}
| 32.891892 | 120 | 0.743632 |
0a1afd47397ae3f5abf49c9eb0d6a9d1945edb4e | 3,666 | cpp | C++ | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/platformsupport/input/shared/qtouchoutputmapping.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/platformsupport/input/shared/qtouchoutputmapping.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/platformsupport/input/shared/qtouchoutputmapping.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the plugins module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qtouchoutputmapping_p.h"
#include <QFile>
#include <QVariantMap>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
QT_BEGIN_NAMESPACE
bool QTouchOutputMapping::load()
{
static QByteArray configFile = qgetenv("QT_QPA_EGLFS_KMS_CONFIG");
if (configFile.isEmpty())
return false;
QFile file(QString::fromUtf8(configFile));
if (!file.open(QFile::ReadOnly)) {
qWarning("touch input support: Failed to open %s", configFile.constData());
return false;
}
const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
if (!doc.isObject()) {
qWarning("touch input support: Failed to parse %s", configFile.constData());
return false;
}
// What we are interested is the virtualIndex and touchDevice properties for
// each element in the outputs array.
const QJsonArray outputs = doc.object().value(QLatin1String("outputs")).toArray();
for (int i = 0; i < outputs.size(); ++i) {
const QVariantMap output = outputs.at(i).toObject().toVariantMap();
if (!output.contains(QStringLiteral("touchDevice")))
continue;
if (!output.contains(QStringLiteral("name"))) {
qWarning("evdevtouch: Output %d specifies touchDevice but not name, this is wrong", i);
continue;
}
const QString &deviceNode = output.value(QStringLiteral("touchDevice")).toString();
const QString &screenName = output.value(QStringLiteral("name")).toString();
m_screenTable.insert(deviceNode, screenName);
}
return true;
}
QString QTouchOutputMapping::screenNameForDeviceNode(const QString &deviceNode)
{
return m_screenTable.value(deviceNode);
}
QT_END_NAMESPACE
| 39.847826 | 99 | 0.68958 |