hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
0f3156cdb70e2aad75e0fd77cf3e7abaa12fdd6f
5,290
cc
C++
JetMETCorrections/InterpolationTables/src/HistoAxis.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
JetMETCorrections/InterpolationTables/src/HistoAxis.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
JetMETCorrections/InterpolationTables/src/HistoAxis.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#include <cmath> #include <climits> #include <algorithm> #include "JetMETCorrections/InterpolationTables/interface/NpstatException.h" #include "Alignment/Geners/interface/binaryIO.hh" #include "Alignment/Geners/interface/IOException.hh" #include "JetMETCorrections/InterpolationTables/interface/closeWithinTolerance.h" #include "JetMETCorrections/InterpolationTables/interface/HistoAxis.h" namespace npstat { HistoAxis::HistoAxis(const unsigned nbins, const double min, const double max, const char* label) : min_(min), max_(max), label_(label ? label : ""), nBins_(nbins) { if (!(nBins_ && nBins_ < UINT_MAX/2U - 1U)) throw npstat::NpstatInvalidArgument("In npstat::HistoAxis constructor: " "number of bins is out of range"); if (min_ > max_) std::swap(min_, max_); bw_ = (max_ - min_)/nBins_; } HistoAxis HistoAxis::rebin(const unsigned nbins) const { return HistoAxis(nbins, min_, max_, label_.c_str()); } bool HistoAxis::isClose(const HistoAxis& r, const double tol) const { return closeWithinTolerance(min_, r.min_, tol) && closeWithinTolerance(max_, r.max_, tol) && label_ == r.label_ && nBins_ == r.nBins_; } bool HistoAxis::operator==(const HistoAxis& r) const { return min_ == r.min_ && max_ == r.max_ && label_ == r.label_ && nBins_ == r.nBins_; } bool HistoAxis::operator!=(const HistoAxis& r) const { return !(*this == r); } int HistoAxis::binNumber(const double x) const { if (bw_) { int binnum = static_cast<int>(floor((x - min_)/bw_)); if (x >= max_) { if (binnum < static_cast<int>(nBins_)) binnum = nBins_; } else { if (binnum >= static_cast<int>(nBins_)) binnum = nBins_ - 1U; } return binnum; } else { if (x < min_) return -1; else return nBins_; } } unsigned HistoAxis::closestValidBin(const double x) const { if (x <= min_) return 0U; else if (bw_ && x < max_) { const unsigned binnum = static_cast<unsigned>(floor((x-min_)/bw_)); if (binnum < nBins_) return binnum; } return nBins_ - 1U; } LinearMapper1d HistoAxis::binNumberMapper(const bool mapLeftEdgeTo0) const { if (!bw_) throw npstat::NpstatDomainError( "In npstat::HistoAxis::binNumberMapper: " "bin width is zero. Mapper can not be constructed."); const double base = mapLeftEdgeTo0 ? min_/bw_ : min_/bw_ + 0.5; return LinearMapper1d(1.0/bw_, -base); } CircularMapper1d HistoAxis::kernelScanMapper(const bool doubleRange) const { if (!bw_) throw npstat::NpstatDomainError( "In npstat::HistoAxis::kernelScanMapper: " "bin width is zero. Mapper can not be constructed."); double range = max_ - min_; if (doubleRange) range *= 2.0; return CircularMapper1d(bw_, 0.0, range); } unsigned HistoAxis::overflowIndexWeighted( const double x, unsigned* binNumber, double *weight) const { if (x < min_) return 0U; else if (x >= max_) return 2U; else { if (nBins_ <= 1U) throw npstat::NpstatInvalidArgument( "In npstat::HistoAxis::overflowIndexWeighted: " "must have more than one bin"); const double dbin = (x - min_)/bw_; if (dbin <= 0.5) { *binNumber = 0; *weight = 1.0; } else if (dbin >= nBins_ - 0.5) { *binNumber = nBins_ - 2; *weight = 0.0; } else { const unsigned bin = static_cast<unsigned>(dbin - 0.5); *binNumber = bin >= nBins_ - 1U ? nBins_ - 2U : bin; *weight = 1.0 - (dbin - 0.5 - *binNumber); } return 1U; } } bool HistoAxis::write(std::ostream& of) const { gs::write_pod(of, min_); gs::write_pod(of, max_); gs::write_pod(of, label_); gs::write_pod(of, nBins_); return !of.fail(); } HistoAxis* HistoAxis::read(const gs::ClassId& id, std::istream& in) { static const gs::ClassId current(gs::ClassId::makeId<HistoAxis>()); current.ensureSameId(id); double min = 0.0, max = 0.0; std::string label; unsigned nBins = 0; gs::read_pod(in, &min); gs::read_pod(in, &max); gs::read_pod(in, &label); gs::read_pod(in, &nBins); if (!in.fail()) return new HistoAxis(nBins, min, max, label.c_str()); else throw gs::IOReadFailure("In npstat::HistoAxis::read: " "input stream failure"); } }
30.578035
84
0.519471
nistefan
0f31a22df5f7e480bfeabf09840fb4a0026b9aeb
1,143
hpp
C++
src/mbgl/programs/hillshade_prepare_program.hpp
finnpetersen/mapbox-gl-native3
1a7ed9a822db3476ff4f6b5d4d4e3151046c7353
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
src/mbgl/programs/hillshade_prepare_program.hpp
finnpetersen/mapbox-gl-native3
1a7ed9a822db3476ff4f6b5d4d4e3151046c7353
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
src/mbgl/programs/hillshade_prepare_program.hpp
finnpetersen/mapbox-gl-native3
1a7ed9a822db3476ff4f6b5d4d4e3151046c7353
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
#pragma once #include <mbgl/programs/program.hpp> #include <mbgl/programs/attributes.hpp> #include <mbgl/programs/uniforms.hpp> #include <mbgl/shaders/hillshade_prepare.hpp> #include <mbgl/util/geometry.hpp> namespace mbgl { namespace uniforms { MBGL_DEFINE_UNIFORM_VECTOR(uint16_t, 2, u_dimension); } // namespace uniforms class HillshadePrepareProgram : public Program< shaders::hillshade_prepare, gl::Triangle, gl::Attributes< attributes::a_pos, attributes::a_texture_pos>, gl::Uniforms< uniforms::u_matrix, uniforms::u_dimension, uniforms::u_zoom, uniforms::u_image>, style::Properties<>> { public: using Program::Program; static LayoutVertex layoutVertex(Point<int16_t> p, Point<uint16_t> t) { return LayoutVertex { {{ p.x, p.y }}, {{ t.x, t.y }} }; } }; using HillshadePrepareLayoutVertex = HillshadePrepareProgram::LayoutVertex; using HillshadePrepareAttributes = HillshadePrepareProgram::Attributes; } // namespace mbgl
23.8125
75
0.634296
finnpetersen
0f331a25ed9df1a6f6f194ace75a99a81c28b660
22,458
cpp
C++
source/blender/compositor/intern/COM_NodeOperationBuilder.cpp
mmk-code/blender
c8fc23fdbe09c33f5342ed51735dab50fe4f071b
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
source/blender/compositor/intern/COM_NodeOperationBuilder.cpp
mmk-code/blender
c8fc23fdbe09c33f5342ed51735dab50fe4f071b
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
source/blender/compositor/intern/COM_NodeOperationBuilder.cpp
mmk-code/blender
c8fc23fdbe09c33f5342ed51735dab50fe4f071b
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * Copyright 2013, Blender Foundation. */ extern "C" { #include "BLI_utildefines.h" } #include "COM_NodeConverter.h" #include "COM_Converter.h" #include "COM_Debug.h" #include "COM_ExecutionSystem.h" #include "COM_Node.h" #include "COM_SocketProxyNode.h" #include "COM_NodeOperation.h" #include "COM_PreviewOperation.h" #include "COM_SetValueOperation.h" #include "COM_SetVectorOperation.h" #include "COM_SetColorOperation.h" #include "COM_SocketProxyOperation.h" #include "COM_ReadBufferOperation.h" #include "COM_WriteBufferOperation.h" #include "COM_ViewerOperation.h" #include "COM_NodeOperationBuilder.h" /* own include */ NodeOperationBuilder::NodeOperationBuilder(const CompositorContext *context, bNodeTree *b_nodetree) : m_context(context), m_current_node(NULL), m_active_viewer(NULL) { m_graph.from_bNodeTree(*context, b_nodetree); } NodeOperationBuilder::~NodeOperationBuilder() { } void NodeOperationBuilder::convertToOperations(ExecutionSystem *system) { /* interface handle for nodes */ NodeConverter converter(this); for (int index = 0; index < m_graph.nodes().size(); index++) { Node *node = (Node *)m_graph.nodes()[index]; m_current_node = node; DebugInfo::node_to_operations(node); node->convertToOperations(converter, *m_context); } m_current_node = NULL; /* The input map constructed by nodes maps operation inputs to node inputs. * Inverting yields a map of node inputs to all connected operation inputs, * so multiple operations can use the same node input. */ OpInputInverseMap inverse_input_map; for (InputSocketMap::const_iterator it = m_input_map.begin(); it != m_input_map.end(); ++it) inverse_input_map[it->second].push_back(it->first); for (NodeGraph::Links::const_iterator it = m_graph.links().begin(); it != m_graph.links().end(); ++it) { const NodeGraph::Link &link = *it; NodeOutput *from = link.getFromSocket(); NodeInput *to = link.getToSocket(); NodeOperationOutput *op_from = find_operation_output(m_output_map, from); const OpInputs &op_to_list = find_operation_inputs(inverse_input_map, to); if (!op_from || op_to_list.empty()) { /* XXX allow this? error/debug message? */ //BLI_assert(false); /* XXX note: this can happen with certain nodes (e.g. OutputFile) * which only generate operations in certain circumstances (rendering) * just let this pass silently for now ... */ continue; } for (OpInputs::const_iterator it = op_to_list.begin(); it != op_to_list.end(); ++it) { NodeOperationInput *op_to = *it; addLink(op_from, op_to); } } add_operation_input_constants(); resolve_proxies(); add_datatype_conversions(); determineResolutions(); /* surround complex ops with read/write buffer */ add_complex_operation_buffers(); /* links not available from here on */ /* XXX make m_links a local variable to avoid confusion! */ m_links.clear(); prune_operations(); /* ensure topological (link-based) order of nodes */ /*sort_operations();*/ /* not needed yet */ /* create execution groups */ group_operations(); /* transfer resulting operations to the system */ system->set_operations(m_operations, m_groups); } void NodeOperationBuilder::addOperation(NodeOperation *operation) { m_operations.push_back(operation); } void NodeOperationBuilder::mapInputSocket(NodeInput *node_socket, NodeOperationInput *operation_socket) { BLI_assert(m_current_node); BLI_assert(node_socket->getNode() == m_current_node); /* note: this maps operation sockets to node sockets. * for resolving links the map will be inverted first in convertToOperations, * to get a list of links for each node input socket. */ m_input_map[operation_socket] = node_socket; } void NodeOperationBuilder::mapOutputSocket(NodeOutput *node_socket, NodeOperationOutput *operation_socket) { BLI_assert(m_current_node); BLI_assert(node_socket->getNode() == m_current_node); m_output_map[node_socket] = operation_socket; } void NodeOperationBuilder::addLink(NodeOperationOutput *from, NodeOperationInput *to) { if (to->isConnected()) return; m_links.push_back(Link(from, to)); /* register with the input */ to->setLink(from); } void NodeOperationBuilder::removeInputLink(NodeOperationInput *to) { for (Links::iterator it = m_links.begin(); it != m_links.end(); ++it) { Link &link = *it; if (link.to() == to) { /* unregister with the input */ to->setLink(NULL); m_links.erase(it); return; } } } NodeInput *NodeOperationBuilder::find_node_input(const InputSocketMap &map, NodeOperationInput *op_input) { InputSocketMap::const_iterator it = map.find(op_input); return (it != map.end() ? it->second : NULL); } const NodeOperationBuilder::OpInputs &NodeOperationBuilder::find_operation_inputs( const OpInputInverseMap &map, NodeInput *node_input) { static const OpInputs empty_list; OpInputInverseMap::const_iterator it = map.find(node_input); return (it != map.end() ? it->second : empty_list); } NodeOperationOutput *NodeOperationBuilder::find_operation_output(const OutputSocketMap &map, NodeOutput *node_output) { OutputSocketMap::const_iterator it = map.find(node_output); return (it != map.end() ? it->second : NULL); } PreviewOperation *NodeOperationBuilder::make_preview_operation() const { BLI_assert(m_current_node); if (!(m_current_node->getbNode()->flag & NODE_PREVIEW)) return NULL; /* previews only in the active group */ if (!m_current_node->isInActiveGroup()) return NULL; /* do not calculate previews of hidden nodes */ if (m_current_node->getbNode()->flag & NODE_HIDDEN) return NULL; bNodeInstanceHash *previews = m_context->getPreviewHash(); if (previews) { PreviewOperation *operation = new PreviewOperation(m_context->getViewSettings(), m_context->getDisplaySettings()); operation->setbNodeTree(m_context->getbNodeTree()); operation->verifyPreview(previews, m_current_node->getInstanceKey()); return operation; } return NULL; } void NodeOperationBuilder::addPreview(NodeOperationOutput *output) { PreviewOperation *operation = make_preview_operation(); if (operation) { addOperation(operation); addLink(output, operation->getInputSocket(0)); } } void NodeOperationBuilder::addNodeInputPreview(NodeInput *input) { PreviewOperation *operation = make_preview_operation(); if (operation) { addOperation(operation); mapInputSocket(input, operation->getInputSocket(0)); } } void NodeOperationBuilder::registerViewer(ViewerOperation *viewer) { if (m_active_viewer) { if (m_current_node->isInActiveGroup()) { /* deactivate previous viewer */ m_active_viewer->setActive(false); m_active_viewer = viewer; viewer->setActive(true); } } else { if (m_current_node->getbNodeTree() == m_context->getbNodeTree()) { m_active_viewer = viewer; viewer->setActive(true); } } } /**************************** **** Optimization Steps **** ****************************/ void NodeOperationBuilder::add_datatype_conversions() { Links convert_links; for (Links::const_iterator it = m_links.begin(); it != m_links.end(); ++it) { const Link &link = *it; /* proxy operations can skip data type conversion */ NodeOperation *from_op = &link.from()->getOperation(); NodeOperation *to_op = &link.to()->getOperation(); if (!(from_op->useDatatypeConversion() || to_op->useDatatypeConversion())) continue; if (link.from()->getDataType() != link.to()->getDataType()) convert_links.push_back(link); } for (Links::const_iterator it = convert_links.begin(); it != convert_links.end(); ++it) { const Link &link = *it; NodeOperation *converter = Converter::convertDataType(link.from(), link.to()); if (converter) { addOperation(converter); removeInputLink(link.to()); addLink(link.from(), converter->getInputSocket(0)); addLink(converter->getOutputSocket(0), link.to()); } } } void NodeOperationBuilder::add_operation_input_constants() { /* Note: unconnected inputs cached first to avoid modifying * m_operations while iterating over it */ typedef std::vector<NodeOperationInput *> Inputs; Inputs pending_inputs; for (Operations::const_iterator it = m_operations.begin(); it != m_operations.end(); ++it) { NodeOperation *op = *it; for (int k = 0; k < op->getNumberOfInputSockets(); ++k) { NodeOperationInput *input = op->getInputSocket(k); if (!input->isConnected()) pending_inputs.push_back(input); } } for (Inputs::const_iterator it = pending_inputs.begin(); it != pending_inputs.end(); ++it) { NodeOperationInput *input = *it; add_input_constant_value(input, find_node_input(m_input_map, input)); } } void NodeOperationBuilder::add_input_constant_value(NodeOperationInput *input, NodeInput *node_input) { switch (input->getDataType()) { case COM_DT_VALUE: { float value; if (node_input && node_input->getbNodeSocket()) value = node_input->getEditorValueFloat(); else value = 0.0f; SetValueOperation *op = new SetValueOperation(); op->setValue(value); addOperation(op); addLink(op->getOutputSocket(), input); break; } case COM_DT_COLOR: { float value[4]; if (node_input && node_input->getbNodeSocket()) node_input->getEditorValueColor(value); else zero_v4(value); SetColorOperation *op = new SetColorOperation(); op->setChannels(value); addOperation(op); addLink(op->getOutputSocket(), input); break; } case COM_DT_VECTOR: { float value[3]; if (node_input && node_input->getbNodeSocket()) node_input->getEditorValueVector(value); else zero_v3(value); SetVectorOperation *op = new SetVectorOperation(); op->setVector(value); addOperation(op); addLink(op->getOutputSocket(), input); break; } } } void NodeOperationBuilder::resolve_proxies() { Links proxy_links; for (Links::const_iterator it = m_links.begin(); it != m_links.end(); ++it) { const Link &link = *it; /* don't replace links from proxy to proxy, since we may need them for replacing others! */ if (link.from()->getOperation().isProxyOperation() && !link.to()->getOperation().isProxyOperation()) { proxy_links.push_back(link); } } for (Links::const_iterator it = proxy_links.begin(); it != proxy_links.end(); ++it) { const Link &link = *it; NodeOperationInput *to = link.to(); NodeOperationOutput *from = link.from(); do { /* walk upstream bypassing the proxy operation */ from = from->getOperation().getInputSocket(0)->getLink(); } while (from && from->getOperation().isProxyOperation()); removeInputLink(to); /* we may not have a final proxy input link, * in that case it just gets dropped */ if (from) addLink(from, to); } } void NodeOperationBuilder::determineResolutions() { /* determine all resolutions of the operations (Width/Height) */ for (Operations::const_iterator it = m_operations.begin(); it != m_operations.end(); ++it) { NodeOperation *op = *it; if (op->isOutputOperation(m_context->isRendering()) && !op->isPreviewOperation()) { unsigned int resolution[2] = {0, 0}; unsigned int preferredResolution[2] = {0, 0}; op->determineResolution(resolution, preferredResolution); op->setResolution(resolution); } } for (Operations::const_iterator it = m_operations.begin(); it != m_operations.end(); ++it) { NodeOperation *op = *it; if (op->isOutputOperation(m_context->isRendering()) && op->isPreviewOperation()) { unsigned int resolution[2] = {0, 0}; unsigned int preferredResolution[2] = {0, 0}; op->determineResolution(resolution, preferredResolution); op->setResolution(resolution); } } /* add convert resolution operations when needed */ { Links convert_links; for (Links::const_iterator it = m_links.begin(); it != m_links.end(); ++it) { const Link &link = *it; if (link.to()->getResizeMode() != COM_SC_NO_RESIZE) { NodeOperation &from_op = link.from()->getOperation(); NodeOperation &to_op = link.to()->getOperation(); if (from_op.getWidth() != to_op.getWidth() || from_op.getHeight() != to_op.getHeight()) convert_links.push_back(link); } } for (Links::const_iterator it = convert_links.begin(); it != convert_links.end(); ++it) { const Link &link = *it; Converter::convertResolution(*this, link.from(), link.to()); } } } NodeOperationBuilder::OpInputs NodeOperationBuilder::cache_output_links( NodeOperationOutput *output) const { OpInputs inputs; for (Links::const_iterator it = m_links.begin(); it != m_links.end(); ++it) { const Link &link = *it; if (link.from() == output) inputs.push_back(link.to()); } return inputs; } WriteBufferOperation *NodeOperationBuilder::find_attached_write_buffer_operation( NodeOperationOutput *output) const { for (Links::const_iterator it = m_links.begin(); it != m_links.end(); ++it) { const Link &link = *it; if (link.from() == output) { NodeOperation &op = link.to()->getOperation(); if (op.isWriteBufferOperation()) return (WriteBufferOperation *)(&op); } } return NULL; } void NodeOperationBuilder::add_input_buffers(NodeOperation * /*operation*/, NodeOperationInput *input) { if (!input->isConnected()) return; NodeOperationOutput *output = input->getLink(); if (output->getOperation().isReadBufferOperation()) { /* input is already buffered, no need to add another */ return; } /* this link will be replaced below */ removeInputLink(input); /* check of other end already has write operation, otherwise add a new one */ WriteBufferOperation *writeoperation = find_attached_write_buffer_operation(output); if (!writeoperation) { writeoperation = new WriteBufferOperation(output->getDataType()); writeoperation->setbNodeTree(m_context->getbNodeTree()); addOperation(writeoperation); addLink(output, writeoperation->getInputSocket(0)); writeoperation->readResolutionFromInputSocket(); } /* add readbuffer op for the input */ ReadBufferOperation *readoperation = new ReadBufferOperation(output->getDataType()); readoperation->setMemoryProxy(writeoperation->getMemoryProxy()); this->addOperation(readoperation); addLink(readoperation->getOutputSocket(), input); readoperation->readResolutionFromWriteBuffer(); } void NodeOperationBuilder::add_output_buffers(NodeOperation *operation, NodeOperationOutput *output) { /* cache connected sockets, so we can safely remove links first before replacing them */ OpInputs targets = cache_output_links(output); if (targets.empty()) return; WriteBufferOperation *writeOperation = NULL; for (OpInputs::const_iterator it = targets.begin(); it != targets.end(); ++it) { NodeOperationInput *target = *it; /* try to find existing write buffer operation */ if (target->getOperation().isWriteBufferOperation()) { BLI_assert(writeOperation == NULL); /* there should only be one write op connected */ writeOperation = (WriteBufferOperation *)(&target->getOperation()); } else { /* remove all links to other nodes */ removeInputLink(target); } } /* if no write buffer operation exists yet, create a new one */ if (!writeOperation) { writeOperation = new WriteBufferOperation(operation->getOutputSocket()->getDataType()); writeOperation->setbNodeTree(m_context->getbNodeTree()); addOperation(writeOperation); addLink(output, writeOperation->getInputSocket(0)); } writeOperation->readResolutionFromInputSocket(); /* add readbuffer op for every former connected input */ for (OpInputs::const_iterator it = targets.begin(); it != targets.end(); ++it) { NodeOperationInput *target = *it; if (&target->getOperation() == writeOperation) continue; /* skip existing write op links */ ReadBufferOperation *readoperation = new ReadBufferOperation( operation->getOutputSocket()->getDataType()); readoperation->setMemoryProxy(writeOperation->getMemoryProxy()); addOperation(readoperation); addLink(readoperation->getOutputSocket(), target); readoperation->readResolutionFromWriteBuffer(); } } void NodeOperationBuilder::add_complex_operation_buffers() { /* note: complex ops and get cached here first, since adding operations * will invalidate iterators over the main m_operations */ Operations complex_ops; for (Operations::const_iterator it = m_operations.begin(); it != m_operations.end(); ++it) if ((*it)->isComplex()) complex_ops.push_back(*it); for (Operations::const_iterator it = complex_ops.begin(); it != complex_ops.end(); ++it) { NodeOperation *op = *it; DebugInfo::operation_read_write_buffer(op); for (int index = 0; index < op->getNumberOfInputSockets(); index++) add_input_buffers(op, op->getInputSocket(index)); for (int index = 0; index < op->getNumberOfOutputSockets(); index++) add_output_buffers(op, op->getOutputSocket(index)); } } typedef std::set<NodeOperation *> Tags; static void find_reachable_operations_recursive(Tags &reachable, NodeOperation *op) { if (reachable.find(op) != reachable.end()) return; reachable.insert(op); for (int i = 0; i < op->getNumberOfInputSockets(); ++i) { NodeOperationInput *input = op->getInputSocket(i); if (input->isConnected()) find_reachable_operations_recursive(reachable, &input->getLink()->getOperation()); } /* associated write-buffer operations are executed as well */ if (op->isReadBufferOperation()) { ReadBufferOperation *read_op = (ReadBufferOperation *)op; MemoryProxy *memproxy = read_op->getMemoryProxy(); find_reachable_operations_recursive(reachable, memproxy->getWriteBufferOperation()); } } void NodeOperationBuilder::prune_operations() { Tags reachable; for (Operations::const_iterator it = m_operations.begin(); it != m_operations.end(); ++it) { NodeOperation *op = *it; /* output operations are primary executed operations */ if (op->isOutputOperation(m_context->isRendering())) find_reachable_operations_recursive(reachable, op); } /* delete unreachable operations */ Operations reachable_ops; for (Operations::const_iterator it = m_operations.begin(); it != m_operations.end(); ++it) { NodeOperation *op = *it; if (reachable.find(op) != reachable.end()) reachable_ops.push_back(op); else delete op; } /* finally replace the operations list with the pruned list */ m_operations = reachable_ops; } /* topological (depth-first) sorting of operations */ static void sort_operations_recursive(NodeOperationBuilder::Operations &sorted, Tags &visited, NodeOperation *op) { if (visited.find(op) != visited.end()) return; visited.insert(op); for (int i = 0; i < op->getNumberOfInputSockets(); ++i) { NodeOperationInput *input = op->getInputSocket(i); if (input->isConnected()) sort_operations_recursive(sorted, visited, &input->getLink()->getOperation()); } sorted.push_back(op); } void NodeOperationBuilder::sort_operations() { Operations sorted; sorted.reserve(m_operations.size()); Tags visited; for (Operations::const_iterator it = m_operations.begin(); it != m_operations.end(); ++it) sort_operations_recursive(sorted, visited, *it); m_operations = sorted; } static void add_group_operations_recursive(Tags &visited, NodeOperation *op, ExecutionGroup *group) { if (visited.find(op) != visited.end()) return; visited.insert(op); if (!group->addOperation(op)) return; /* add all eligible input ops to the group */ for (int i = 0; i < op->getNumberOfInputSockets(); ++i) { NodeOperationInput *input = op->getInputSocket(i); if (input->isConnected()) add_group_operations_recursive(visited, &input->getLink()->getOperation(), group); } } ExecutionGroup *NodeOperationBuilder::make_group(NodeOperation *op) { ExecutionGroup *group = new ExecutionGroup(); m_groups.push_back(group); Tags visited; add_group_operations_recursive(visited, op, group); return group; } void NodeOperationBuilder::group_operations() { for (Operations::const_iterator it = m_operations.begin(); it != m_operations.end(); ++it) { NodeOperation *op = *it; if (op->isOutputOperation(m_context->isRendering())) { ExecutionGroup *group = make_group(op); group->setOutputExecutionGroup(true); } /* add new groups for associated memory proxies where needed */ if (op->isReadBufferOperation()) { ReadBufferOperation *read_op = (ReadBufferOperation *)op; MemoryProxy *memproxy = read_op->getMemoryProxy(); if (memproxy->getExecutor() == NULL) { ExecutionGroup *group = make_group(memproxy->getWriteBufferOperation()); memproxy->setExecutor(group); } } } }
31.900568
99
0.680737
mmk-code
0f33eff2849001dbb9c22a2d4a861efede0505f7
7,347
cpp
C++
examples/Meters/ExampleUIMeters.cpp
noisecode3/DPF
86a621bfd86922a49ce593fec2a618a1e0cc6ef3
[ "0BSD" ]
372
2015-02-09T15:05:16.000Z
2022-03-30T15:35:17.000Z
examples/Meters/ExampleUIMeters.cpp
noisecode3/DPF
86a621bfd86922a49ce593fec2a618a1e0cc6ef3
[ "0BSD" ]
324
2015-10-05T14:30:41.000Z
2022-03-30T07:06:04.000Z
examples/Meters/ExampleUIMeters.cpp
noisecode3/DPF
86a621bfd86922a49ce593fec2a618a1e0cc6ef3
[ "0BSD" ]
89
2015-02-20T11:26:50.000Z
2022-02-11T00:07:27.000Z
/* * DISTRHO Plugin Framework (DPF) * Copyright (C) 2012-2019 Filipe Coelho <falktx@falktx.com> * * Permission to use, copy, modify, and/or distribute this software for any purpose with * or without fee is hereby granted, provided that the above copyright notice and this * permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "DistrhoUI.hpp" START_NAMESPACE_DISTRHO /** We need the Color class from DGL. */ using DGL_NAMESPACE::Color; /** Smooth meters a bit. */ static const float kSmoothMultiplier = 3.0f; // ----------------------------------------------------------------------------------------------------------- class ExampleUIMeters : public UI { public: ExampleUIMeters() : UI(128, 512), // default color is green fColor(93, 231, 61), // which is value 0 fColorValue(0), // init meter values to 0 fOutLeft(0.0f), fOutRight(0.0f) { setGeometryConstraints(32, 128, false); } protected: /* -------------------------------------------------------------------------------------------------------- * DSP/Plugin Callbacks */ /** A parameter has changed on the plugin side. This is called by the host to inform the UI about parameter changes. */ void parameterChanged(uint32_t index, float value) override { switch (index) { case 0: // color updateColor(std::round(value)); break; case 1: // out-left value = (fOutLeft * kSmoothMultiplier + value) / (kSmoothMultiplier + 1.0f); /**/ if (value < 0.001f) value = 0.0f; else if (value > 0.999f) value = 1.0f; if (fOutLeft != value) { fOutLeft = value; repaint(); } break; case 2: // out-right value = (fOutRight * kSmoothMultiplier + value) / (kSmoothMultiplier + 1.0f); /**/ if (value < 0.001f) value = 0.0f; else if (value > 0.999f) value = 1.0f; if (fOutRight != value) { fOutRight = value; repaint(); } break; } } /** A state has changed on the plugin side. This is called by the host to inform the UI about state changes. */ void stateChanged(const char*, const char*) override { // nothing here } /* -------------------------------------------------------------------------------------------------------- * Widget Callbacks */ /** The NanoVG drawing function. */ void onNanoDisplay() override { static const Color kColorBlack(0, 0, 0); static const Color kColorRed(255, 0, 0); static const Color kColorYellow(255, 255, 0); // get meter values const float outLeft(fOutLeft); const float outRight(fOutRight); // tell DSP side to reset meter values setState("reset", ""); // useful vars const float halfWidth = static_cast<float>(getWidth())/2; const float redYellowHeight = static_cast<float>(getHeight())*0.2f; const float yellowBaseHeight = static_cast<float>(getHeight())*0.4f; const float baseBaseHeight = static_cast<float>(getHeight())*0.6f; // create gradients Paint fGradient1 = linearGradient(0.0f, 0.0f, 0.0f, redYellowHeight, kColorRed, kColorYellow); Paint fGradient2 = linearGradient(0.0f, redYellowHeight, 0.0f, yellowBaseHeight, kColorYellow, fColor); // paint left meter beginPath(); rect(0.0f, 0.0f, halfWidth-1.0f, redYellowHeight); fillPaint(fGradient1); fill(); closePath(); beginPath(); rect(0.0f, redYellowHeight-0.5f, halfWidth-1.0f, yellowBaseHeight); fillPaint(fGradient2); fill(); closePath(); beginPath(); rect(0.0f, redYellowHeight+yellowBaseHeight-1.5f, halfWidth-1.0f, baseBaseHeight); fillColor(fColor); fill(); closePath(); // paint left black matching output level beginPath(); rect(0.0f, 0.0f, halfWidth-1.0f, (1.0f-outLeft)*getHeight()); fillColor(kColorBlack); fill(); closePath(); // paint right meter beginPath(); rect(halfWidth+1.0f, 0.0f, halfWidth-2.0f, redYellowHeight); fillPaint(fGradient1); fill(); closePath(); beginPath(); rect(halfWidth+1.0f, redYellowHeight-0.5f, halfWidth-2.0f, yellowBaseHeight); fillPaint(fGradient2); fill(); closePath(); beginPath(); rect(halfWidth+1.0f, redYellowHeight+yellowBaseHeight-1.5f, halfWidth-2.0f, baseBaseHeight); fillColor(fColor); fill(); closePath(); // paint right black matching output level beginPath(); rect(halfWidth+1.0f, 0.0f, halfWidth-2.0f, (1.0f-outRight)*getHeight()); fillColor(kColorBlack); fill(); closePath(); } /** Mouse press event. This UI will change color when clicked. */ bool onMouse(const MouseEvent& ev) override { // Test for left-clicked + pressed first. if (ev.button != 1 || ! ev.press) return false; const int newColor(fColorValue == 0 ? 1 : 0); updateColor(newColor); setParameterValue(0, newColor); return true; } // ------------------------------------------------------------------------------------------------------- private: /** Color and its matching parameter value. */ Color fColor; int fColorValue; /** Meter values. These are the parameter outputs from the DSP side. */ float fOutLeft, fOutRight; /** Update color if needed. */ void updateColor(const int color) { if (fColorValue == color) return; fColorValue = color; switch (color) { case METER_COLOR_GREEN: fColor = Color(93, 231, 61); break; case METER_COLOR_BLUE: fColor = Color(82, 238, 248); break; } repaint(); } /** Set our UI class as non-copyable and add a leak detector just in case. */ DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(ExampleUIMeters) }; /* ------------------------------------------------------------------------------------------------------------ * UI entry point, called by DPF to create a new UI instance. */ UI* createUI() { return new ExampleUIMeters(); } // ----------------------------------------------------------------------------------------------------------- END_NAMESPACE_DISTRHO
28.699219
117
0.531782
noisecode3
0f38f548e204fdbca419c5fe7608d207710a24f6
1,110
cpp
C++
ijk/source/ijk-math/common/ijk-real/_cpp/ijkQuaternionSwizzle.cpp
dbuckstein/ijk
959f7292d6465e9d2c888ea94bc724c8ee03597e
[ "Apache-2.0" ]
1
2020-05-31T21:14:49.000Z
2020-05-31T21:14:49.000Z
ijk/source/ijk-math/common/ijk-real/_cpp/ijkQuaternionSwizzle.cpp
dbuckstein/ijk
959f7292d6465e9d2c888ea94bc724c8ee03597e
[ "Apache-2.0" ]
null
null
null
ijk/source/ijk-math/common/ijk-real/_cpp/ijkQuaternionSwizzle.cpp
dbuckstein/ijk
959f7292d6465e9d2c888ea94bc724c8ee03597e
[ "Apache-2.0" ]
null
null
null
/* Copyright 2020-2021 Daniel S. Buckstein 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. */ /* ijk: an open-source, cross-platform, light-weight, c-based rendering framework By Daniel S. Buckstein ijkQuaternionSwizzle.cpp C++ testing source definitions for quaternion types. */ #include "ijk/ijk-math/ijk-real/ijkQuaternion.h" //----------------------------------------------------------------------------- extern "C" { void ijkMathTestQuaternionSwizzle(); } void ijkMathTestQuaternionSwizzle() { typedef f32 base, * basev; typedef float type; typedef fquat tquat; typedef fdualquat tdualquat; }
26.428571
79
0.704505
dbuckstein
0f3b9b76e6959e5a3fd7b1f3ce52ba4689c68e08
6,196
cc
C++
examples/pxScene2d/external/libnode-v6.9.0/src/node_i18n.cc
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
5,964
2016-09-27T03:46:29.000Z
2022-03-31T16:25:27.000Z
examples/pxScene2d/external/libnode-v6.9.0/src/node_i18n.cc
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
1,432
2017-06-21T04:08:48.000Z
2020-08-25T16:21:15.000Z
examples/pxScene2d/external/libnode-v6.9.0/src/node_i18n.cc
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
1,006
2016-09-27T05:17:27.000Z
2022-03-30T02:46:51.000Z
/* * notes: by srl295 * - When in NODE_HAVE_SMALL_ICU mode, ICU is linked against "stub" (null) data * ( stubdata/libicudata.a ) containing nothing, no data, and it's also * linked against a "small" data file which the SMALL_ICUDATA_ENTRY_POINT * macro names. That's the "english+root" data. * * If icu_data_path is non-null, the user has provided a path and we assume * it goes somewhere useful. We set that path in ICU, and exit. * If icu_data_path is null, they haven't set a path and we want the * "english+root" data. We call * udata_setCommonData(SMALL_ICUDATA_ENTRY_POINT,...) * to load up the english+root data. * * - when NOT in NODE_HAVE_SMALL_ICU mode, ICU is linked directly with its full * data. All of the variables and command line options for changing data at * runtime are disabled, as they wouldn't fully override the internal data. * See: http://bugs.icu-project.org/trac/ticket/10924 */ #include "node_i18n.h" #if defined(NODE_HAVE_I18N_SUPPORT) #include "node.h" #include "env.h" #include "env-inl.h" #include "util.h" #include "util-inl.h" #include "v8.h" #include <unicode/putil.h> #include <unicode/udata.h> #include <unicode/uidna.h> #ifdef NODE_HAVE_SMALL_ICU /* if this is defined, we have a 'secondary' entry point. compare following to utypes.h defs for U_ICUDATA_ENTRY_POINT */ #define SMALL_ICUDATA_ENTRY_POINT \ SMALL_DEF2(U_ICU_VERSION_MAJOR_NUM, U_LIB_SUFFIX_C_NAME) #define SMALL_DEF2(major, suff) SMALL_DEF(major, suff) #ifndef U_LIB_SUFFIX_C_NAME #define SMALL_DEF(major, suff) icusmdt##major##_dat #else #define SMALL_DEF(major, suff) icusmdt##suff##major##_dat #endif extern "C" const char U_DATA_API SMALL_ICUDATA_ENTRY_POINT[]; #endif namespace node { using v8::Context; using v8::FunctionCallbackInfo; using v8::Local; using v8::Object; using v8::String; using v8::Value; bool flag_icu_data_dir = false; namespace i18n { bool InitializeICUDirectory(const char* icu_data_path) { if (icu_data_path != nullptr) { flag_icu_data_dir = true; u_setDataDirectory(icu_data_path); return true; // no error } else { UErrorCode status = U_ZERO_ERROR; #ifdef NODE_HAVE_SMALL_ICU // install the 'small' data. udata_setCommonData(&SMALL_ICUDATA_ENTRY_POINT, &status); #else // !NODE_HAVE_SMALL_ICU // no small data, so nothing to do. #endif // !NODE_HAVE_SMALL_ICU return (status == U_ZERO_ERROR); } } static int32_t ToUnicode(MaybeStackBuffer<char>* buf, const char* input, size_t length) { UErrorCode status = U_ZERO_ERROR; uint32_t options = UIDNA_DEFAULT; options |= UIDNA_NONTRANSITIONAL_TO_UNICODE; UIDNA* uidna = uidna_openUTS46(options, &status); if (U_FAILURE(status)) return -1; UIDNAInfo info = UIDNA_INFO_INITIALIZER; int32_t len = uidna_nameToUnicodeUTF8(uidna, input, length, **buf, buf->length(), &info, &status); if (status == U_BUFFER_OVERFLOW_ERROR) { status = U_ZERO_ERROR; buf->AllocateSufficientStorage(len); len = uidna_nameToUnicodeUTF8(uidna, input, length, **buf, buf->length(), &info, &status); } if (U_FAILURE(status)) len = -1; uidna_close(uidna); return len; } static int32_t ToASCII(MaybeStackBuffer<char>* buf, const char* input, size_t length) { UErrorCode status = U_ZERO_ERROR; uint32_t options = UIDNA_DEFAULT; options |= UIDNA_NONTRANSITIONAL_TO_ASCII; UIDNA* uidna = uidna_openUTS46(options, &status); if (U_FAILURE(status)) return -1; UIDNAInfo info = UIDNA_INFO_INITIALIZER; int32_t len = uidna_nameToASCII_UTF8(uidna, input, length, **buf, buf->length(), &info, &status); if (status == U_BUFFER_OVERFLOW_ERROR) { status = U_ZERO_ERROR; buf->AllocateSufficientStorage(len); len = uidna_nameToASCII_UTF8(uidna, input, length, **buf, buf->length(), &info, &status); } if (U_FAILURE(status)) len = -1; uidna_close(uidna); return len; } static void ToUnicode(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args); CHECK_GE(args.Length(), 1); CHECK(args[0]->IsString()); Utf8Value val(env->isolate(), args[0]); MaybeStackBuffer<char> buf; int32_t len = ToUnicode(&buf, *val, val.length()); if (len < 0) { return env->ThrowError("Cannot convert name to Unicode"); } args.GetReturnValue().Set( String::NewFromUtf8(env->isolate(), *buf, v8::NewStringType::kNormal, len).ToLocalChecked()); } static void ToASCII(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args); CHECK_GE(args.Length(), 1); CHECK(args[0]->IsString()); Utf8Value val(env->isolate(), args[0]); MaybeStackBuffer<char> buf; int32_t len = ToASCII(&buf, *val, val.length()); if (len < 0) { return env->ThrowError("Cannot convert name to ASCII"); } args.GetReturnValue().Set( String::NewFromUtf8(env->isolate(), *buf, v8::NewStringType::kNormal, len).ToLocalChecked()); } void Init(Local<Object> target, Local<Value> unused, Local<Context> context, void* priv) { Environment* env = Environment::GetCurrent(context); env->SetMethod(target, "toUnicode", ToUnicode); env->SetMethod(target, "toASCII", ToASCII); } } // namespace i18n } // namespace node NODE_MODULE_CONTEXT_AWARE_BUILTIN(icu, node::i18n::Init) #endif // NODE_HAVE_I18N_SUPPORT
30.522167
80
0.614429
madanagopaltcomcast
0f42124fd83b667916fff4bee0b94c45b97c0e12
2,735
cpp
C++
ConceptEngine/ConceptEngine/ConceptEngineRenderer/Rendering/Resources/Mesh.cpp
Ludaxord/ConceptEngine
16775bc9b518d4fd4c8bd32bb5f297223dfacbae
[ "MIT" ]
4
2021-01-10T00:46:21.000Z
2022-02-25T18:43:26.000Z
ConceptEngine/ConceptEngine/ConceptEngineRenderer/Rendering/Resources/Mesh.cpp
Ludaxord/ConceptEngine
16775bc9b518d4fd4c8bd32bb5f297223dfacbae
[ "MIT" ]
null
null
null
ConceptEngine/ConceptEngine/ConceptEngineRenderer/Rendering/Resources/Mesh.cpp
Ludaxord/ConceptEngine
16775bc9b518d4fd4c8bd32bb5f297223dfacbae
[ "MIT" ]
null
null
null
#include "Mesh.h" #include "../../RenderLayer/CommandList.h" #include "../../RenderLayer/RenderLayer.h" #include "Graphics/D3D12/Managers/CEDX12MeshManager.h" bool Mesh::Init(const MeshData& Data) { MainMeshData = Data; VertexCount = static_cast<uint32>(Data.Vertices.Size()); IndexCount = static_cast<uint32>(Data.Indices.Size()); const uint32 BufferFlags = IsRayTracingSupported() ? BufferFlag_SRV | BufferFlag_Default : BufferFlag_Default; ResourceData InitialData(Data.Vertices.Data(), Data.Vertices.SizeInBytes()); VertexBuffer = CreateVertexBuffer<Vertex>(VertexCount, BufferFlags, EResourceState::VertexAndConstantBuffer, &InitialData); if (!VertexBuffer) { return false; } else { VertexBuffer->SetName("VertexBuffer"); } const bool RTOn = IsRayTracingSupported(); InitialData = ResourceData(Data.Indices.Data(), Data.Indices.SizeInBytes()); IndexBuffer = CreateIndexBuffer(EIndexFormat::uint32, IndexCount, BufferFlags, EResourceState::IndexBuffer, &InitialData); if (!IndexBuffer) { return false; } else { IndexBuffer->SetName("IndexBuffer"); } if (RTOn) { RTGeometry = CreateRayTracingGeometry(RayTracingStructureBuildFlag_None, VertexBuffer.Get(), IndexBuffer.Get()); if (!RTGeometry) { return false; } else { RTGeometry->SetName("RayTracing Geometry"); } VertexBufferSRV = CreateShaderResourceView(VertexBuffer.Get(), 0, VertexCount); if (!VertexBufferSRV) { return false; } IndexBufferSRV = CreateShaderResourceView(IndexBuffer.Get(), 0, IndexCount); if (!IndexBufferSRV) { return false; } } CreateBoundingBox(Data); ID = CEUUID(); return true; } bool Mesh::BuildAccelerationStructure(CommandList& CmdList) { CmdList.BuildRayTracingGeometry(RTGeometry.Get(), VertexBuffer.Get(), IndexBuffer.Get(), true); return true; } TSharedPtr<Mesh> Mesh::Make(const MeshData& Data) { TSharedPtr<Mesh> Result = MakeShared<Mesh>(); if (Result->Init(Data)) { return Result; } else { return TSharedPtr<Mesh>(nullptr); } } void Mesh::CreateBoundingBox(const MeshData& Data) { constexpr float Inf = std::numeric_limits<float>::infinity(); XMFLOAT3 Min = XMFLOAT3(Inf, Inf, Inf); XMFLOAT3 Max = XMFLOAT3(-Inf, -Inf, -Inf); for (const Vertex& Vertex : Data.Vertices) { // X Min.x = Math::Min<float>(Min.x, Vertex.Position.x); Max.x = Math::Max<float>(Max.x, Vertex.Position.x); // Y Min.y = Math::Min<float>(Min.y, Vertex.Position.y); Max.y = Math::Max<float>(Max.y, Vertex.Position.y); // Z Min.z = Math::Min<float>(Min.z, Vertex.Position.z); Max.z = Math::Max<float>(Max.z, Vertex.Position.z); } BoundingBox.Top = Max; BoundingBox.Bottom = Min; }
27.908163
114
0.697623
Ludaxord
0f4221ff72c9047c31af1c3ad9015b1e9f075fd5
3,178
cpp
C++
source/agent/analytics/videoGstPipeline/GstInternalIn.cpp
andreasunterhuber/owt-server
128b83714361c0b543ec44fc841c9094f4267633
[ "Apache-2.0" ]
2
2021-02-05T04:57:58.000Z
2021-04-11T08:36:19.000Z
source/agent/analytics/videoGstPipeline/GstInternalIn.cpp
andreasunterhuber/owt-server
128b83714361c0b543ec44fc841c9094f4267633
[ "Apache-2.0" ]
3
2020-07-09T06:48:40.000Z
2020-09-17T03:04:30.000Z
source/agent/analytics/videoGstPipeline/GstInternalIn.cpp
andreasunterhuber/owt-server
128b83714361c0b543ec44fc841c9094f4267633
[ "Apache-2.0" ]
null
null
null
// Copyright (C) <2019> Intel Corporation // // SPDX-License-Identifier: Apache-2.0 #include "GstInternalIn.h" #include <gst/gst.h> #include <stdio.h> DEFINE_LOGGER(GstInternalIn, "GstInternalIn"); GstInternalIn::GstInternalIn(GstAppSrc *data, unsigned int minPort, unsigned int maxPort) { m_transport.reset(new owt_base::RawTransport<owt_base::TCP>(this)); if (minPort > 0 && minPort <= maxPort) { m_transport->listenTo(minPort, maxPort); } else { m_transport->listenTo(0); } appsrc = data; m_needKeyFrame = true; m_start = false; } GstInternalIn::~GstInternalIn() { m_transport->close(); } unsigned int GstInternalIn::getListeningPort() { return m_transport->getListeningPort(); } void GstInternalIn::setPushData(bool status){ m_start = status; } void GstInternalIn::onFeedback(const owt_base::FeedbackMsg& msg) { char sendBuffer[512]; sendBuffer[0] = owt_base::TDT_FEEDBACK_MSG; memcpy(&sendBuffer[1], reinterpret_cast<char*>(const_cast<owt_base::FeedbackMsg*>(&msg)), sizeof(owt_base::FeedbackMsg)); m_transport->sendData((char*)sendBuffer, sizeof(owt_base::FeedbackMsg) + 1); } void GstInternalIn::onTransportData(char* buf, int len) { if(!m_start) { ELOG_INFO("Not start yet, stop pushing data to appsrc\n"); pthread_t tid; tid = pthread_self(); return; } owt_base::Frame* frame = nullptr; switch (buf[0]) { case owt_base::TDT_MEDIA_FRAME:{ frame = reinterpret_cast<owt_base::Frame*>(buf + 1); if(frame->additionalInfo.video.width == 1) { ELOG_DEBUG("Not a valid video frame\n"); break; } frame->payload = reinterpret_cast<uint8_t*>(buf + 1 + sizeof(owt_base::Frame)); size_t payloadLength = frame->length; size_t headerLength = sizeof(frame); GstBuffer *buffer; GstFlowReturn ret; GstMapInfo map; if (m_needKeyFrame) { if (frame->additionalInfo.video.isKeyFrame) { m_needKeyFrame = false; } else { ELOG_DEBUG("Request key frame\n"); owt_base::FeedbackMsg msg {.type = owt_base::VIDEO_FEEDBACK, .cmd = owt_base::REQUEST_KEY_FRAME}; onFeedback(msg); return; } } /* Create a new empty buffer */ buffer = gst_buffer_new_and_alloc (payloadLength + headerLength); gst_buffer_map(buffer, &map, GST_MAP_WRITE); memcpy(map.data, frame, headerLength); memcpy(map.data + headerLength, frame->payload, payloadLength); gst_buffer_unmap(buffer, &map); g_signal_emit_by_name(appsrc, "push-buffer", buffer, &ret); gst_buffer_unref(buffer); if (ret != GST_FLOW_OK) { /* We got some error, stop sending data */ ELOG_DEBUG("Push buffer to appsrc got error\n"); m_start=false; } break; } default: break; } }
29.425926
125
0.58905
andreasunterhuber
0f42bc0e33dc6fa79792373d243d26e951ac609e
3,658
cc
C++
Mu2eUtilities/src/TriggerResultsNavigator.cc
AndrewEdmonds11/Offline
99d525aa55a477fb3f21826ac817224c25cda040
[ "Apache-2.0" ]
1
2021-06-25T00:00:12.000Z
2021-06-25T00:00:12.000Z
Mu2eUtilities/src/TriggerResultsNavigator.cc
shadowbehindthebread/Offline
57b5055641a4c626a695f3d83237c79758956b6a
[ "Apache-2.0" ]
null
null
null
Mu2eUtilities/src/TriggerResultsNavigator.cc
shadowbehindthebread/Offline
57b5055641a4c626a695f3d83237c79758956b6a
[ "Apache-2.0" ]
1
2020-05-27T22:33:52.000Z
2020-05-27T22:33:52.000Z
#include "fhiclcpp/ParameterSet.h" #include "fhiclcpp/ParameterSetRegistry.h" #include "Mu2eUtilities/inc/TriggerResultsNavigator.hh" #include <iostream> #include <iomanip> namespace mu2e { TriggerResultsNavigator::TriggerResultsNavigator(const art::TriggerResults* trigResults): _trigResults(trigResults){ auto const id = trigResults->parameterSetID(); auto const& pset = fhicl::ParameterSetRegistry::get(id); //set the vector<string> with the names of the tirgger_paths _trigPathsNames = pset.get<std::vector<std::string>>("trigger_paths"); //loop over trigResults to fill the map <string, unsigned int) for (unsigned int i=0; i< _trigPathsNames.size(); ++i){ _trigMap.insert(std::pair<std::string, unsigned int>(_trigPathsNames[i], i)); } } size_t TriggerResultsNavigator::findTrigPath(std::string const& name) const { return find(_trigMap, name); } size_t TriggerResultsNavigator::find(std::map<std::string, unsigned int> const& posmap, std::string const& name) const { auto const pos = posmap.find(name); if (pos == posmap.cend()) { return posmap.size(); } else { return pos->second; } } // Has ith path accepted the event? bool TriggerResultsNavigator::accepted(std::string const& name) const { size_t index = findTrigPath(name); return _trigResults->accept(index); } bool TriggerResultsNavigator::wasrun(std::string const& name) const { size_t index = findTrigPath(name); return _trigResults->wasrun(index); } std::vector<std::string> TriggerResultsNavigator::triggerModules(std::string const& name) const{ std::vector<std::string> modules; for ( auto const& i : fhicl::ParameterSetRegistry::get() ){ auto const id = i.first; if (i.second.has_key(name)){ auto const &pset = fhicl::ParameterSetRegistry::get(id); modules = pset.get<std::vector<std::string>>(name); break; } } return modules; } unsigned TriggerResultsNavigator::indexLastModule(std::string const& name) const{ size_t index = findTrigPath(name); return _trigResults->index(index); } std::string TriggerResultsNavigator::nameLastModule (std::string const& name) const{ unsigned indexLast = indexLastModule(name); std::vector<std::string> modulesVec = triggerModules(name); if ( modulesVec.size() == 0) { std::string nn = "PATH "+name+" NOT FOUND"; std::cout << "[TriggerResultsNavigator::nameLastModule] " << nn << std::endl; return nn; }else { return modulesVec[indexLast]; } } art::hlt::HLTState TriggerResultsNavigator::state(std::string const& name) const{ size_t index = findTrigPath(name); return _trigResults->state(index); } void TriggerResultsNavigator::print() const { std::cout << "TriggerResultsNaviogator Map" << std::endl; std::cout << "//------------------------------------------//" << std::endl; std::cout << "// trig_pathName id accepted //" << std::endl; std::cout << "//------------------------------------------//" << std::endl; for (unsigned int i=0; i< _trigPathsNames.size(); ++i){ std::string name = _trigPathsNames[i]; size_t index = findTrigPath(name); bool good = accepted(name); std::cout << std::right; std::cout <<"//"<<std::setw(24) << name << std::setw(2) << index << (good == true ? 1:0) << "//"<< std::endl; // %24s %2li %i //\n", name.c_str(), index, good == true ? 1:0); } } }
32.087719
115
0.613997
AndrewEdmonds11
0f44445cfe8bec2debd2c8cb15b96e15775a869e
1,044
hpp
C++
include/gct/fence.hpp
Fadis/gct
bde211f9336e945e4db21f5abb4ce01dcad78049
[ "MIT" ]
1
2022-03-03T09:27:09.000Z
2022-03-03T09:27:09.000Z
include/gct/fence.hpp
Fadis/gct
bde211f9336e945e4db21f5abb4ce01dcad78049
[ "MIT" ]
1
2021-12-02T03:45:45.000Z
2021-12-03T23:44:37.000Z
include/gct/fence.hpp
Fadis/gct
bde211f9336e945e4db21f5abb4ce01dcad78049
[ "MIT" ]
null
null
null
#ifndef GCT_FENCE_HPP #define GCT_FENCE_HPP #include <memory> #include <vulkan/vulkan.hpp> #include <gct/created_from.hpp> #include <gct/fence_create_info.hpp> namespace gct { struct device_t; class fence_t : public created_from< device_t >, public std::enable_shared_from_this< fence_t > { public: fence_t( const std::shared_ptr< device_t >&, const fence_create_info_t& ); fence_t( const fence_t& ) = delete; fence_t( fence_t&& ) = default; fence_t &operator=( const fence_t& ) = delete; fence_t &operator=( fence_t&& ) = default; const fence_create_info_t &get_props() const { return props; } vk::Fence &operator*() { return *handle; } const vk::Fence &operator*() const { return *handle; } vk::Fence *operator->() { return &handle.get(); } const vk::Fence *operator->() const { return &handle.get(); } private: fence_create_info_t props; vk::UniqueHandle< vk::Fence, VULKAN_HPP_DEFAULT_DISPATCHER_TYPE > handle; }; } #endif
25.463415
99
0.653257
Fadis
0f4464122c8fb96f11f5246107cf80e97a5b8aec
24,624
cpp
C++
clang-tools-extra/clangd/unittests/SelectionTests.cpp
hborla/llvm-project
6590b7ca0bb9c01e9a362bcbc5500d41d21bd6e7
[ "Apache-2.0" ]
null
null
null
clang-tools-extra/clangd/unittests/SelectionTests.cpp
hborla/llvm-project
6590b7ca0bb9c01e9a362bcbc5500d41d21bd6e7
[ "Apache-2.0" ]
null
null
null
clang-tools-extra/clangd/unittests/SelectionTests.cpp
hborla/llvm-project
6590b7ca0bb9c01e9a362bcbc5500d41d21bd6e7
[ "Apache-2.0" ]
null
null
null
//===-- SelectionTests.cpp - ----------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "Annotations.h" #include "Selection.h" #include "SourceCode.h" #include "TestTU.h" #include "support/TestTracer.h" #include "clang/AST/Decl.h" #include "llvm/Support/Casting.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace clang { namespace clangd { namespace { using ::testing::ElementsAreArray; using ::testing::UnorderedElementsAreArray; // Create a selection tree corresponding to a point or pair of points. // This uses the precisely-defined createRight semantics. The fuzzier // createEach is tested separately. SelectionTree makeSelectionTree(const StringRef MarkedCode, ParsedAST &AST) { Annotations Test(MarkedCode); switch (Test.points().size()) { case 1: { // Point selection. unsigned Offset = cantFail(positionToOffset(Test.code(), Test.point())); return SelectionTree::createRight(AST.getASTContext(), AST.getTokens(), Offset, Offset); } case 2: // Range selection. return SelectionTree::createRight( AST.getASTContext(), AST.getTokens(), cantFail(positionToOffset(Test.code(), Test.points()[0])), cantFail(positionToOffset(Test.code(), Test.points()[1]))); default: ADD_FAILURE() << "Expected 1-2 points for selection.\n" << MarkedCode; return SelectionTree::createRight(AST.getASTContext(), AST.getTokens(), 0u, 0u); } } Range nodeRange(const SelectionTree::Node *N, ParsedAST &AST) { if (!N) return Range{}; const SourceManager &SM = AST.getSourceManager(); const LangOptions &LangOpts = AST.getLangOpts(); StringRef Buffer = SM.getBufferData(SM.getMainFileID()); if (llvm::isa_and_nonnull<TranslationUnitDecl>(N->ASTNode.get<Decl>())) return Range{Position{}, offsetToPosition(Buffer, Buffer.size())}; auto FileRange = toHalfOpenFileRange(SM, LangOpts, N->ASTNode.getSourceRange()); assert(FileRange && "We should be able to get the File Range"); return Range{ offsetToPosition(Buffer, SM.getFileOffset(FileRange->getBegin())), offsetToPosition(Buffer, SM.getFileOffset(FileRange->getEnd()))}; } std::string nodeKind(const SelectionTree::Node *N) { return N ? N->kind() : "<null>"; } std::vector<const SelectionTree::Node *> allNodes(const SelectionTree &T) { std::vector<const SelectionTree::Node *> Result = {&T.root()}; for (unsigned I = 0; I < Result.size(); ++I) { const SelectionTree::Node *N = Result[I]; Result.insert(Result.end(), N->Children.begin(), N->Children.end()); } return Result; } // Returns true if Common is a descendent of Root. // Verifies nothing is selected above Common. bool verifyCommonAncestor(const SelectionTree::Node &Root, const SelectionTree::Node *Common, StringRef MarkedCode) { if (&Root == Common) return true; if (Root.Selected) ADD_FAILURE() << "Selected nodes outside common ancestor\n" << MarkedCode; bool Seen = false; for (const SelectionTree::Node *Child : Root.Children) if (verifyCommonAncestor(*Child, Common, MarkedCode)) { if (Seen) ADD_FAILURE() << "Saw common ancestor twice\n" << MarkedCode; Seen = true; } return Seen; } TEST(SelectionTest, CommonAncestor) { struct Case { // Selection is between ^marks^. // common ancestor marked with a [[range]]. const char *Code; const char *CommonAncestorKind; }; Case Cases[] = { { R"cpp( template <typename T> int x = [[T::^U::]]ccc(); )cpp", "NestedNameSpecifierLoc", }, { R"cpp( struct AAA { struct BBB { static int ccc(); };}; int x = AAA::[[B^B^B]]::ccc(); )cpp", "RecordTypeLoc", }, { R"cpp( struct AAA { struct BBB { static int ccc(); };}; int x = AAA::[[B^BB^]]::ccc(); )cpp", "RecordTypeLoc", }, { R"cpp( struct AAA { struct BBB { static int ccc(); };}; int x = [[AAA::BBB::c^c^c]](); )cpp", "DeclRefExpr", }, { R"cpp( struct AAA { struct BBB { static int ccc(); };}; int x = [[AAA::BBB::cc^c(^)]]; )cpp", "CallExpr", }, { R"cpp( void foo() { [[if (1^11) { return; } else {^ }]] } )cpp", "IfStmt", }, { R"cpp( int x(int); #define M(foo) x(foo) int a = 42; int b = M([[^a]]); )cpp", "DeclRefExpr", }, { R"cpp( void foo(); #define CALL_FUNCTION(X) X() void bar() { CALL_FUNCTION([[f^o^o]]); } )cpp", "DeclRefExpr", }, { R"cpp( void foo(); #define CALL_FUNCTION(X) X() void bar() { [[CALL_FUNC^TION(fo^o)]]; } )cpp", "CallExpr", }, { R"cpp( void foo(); #define CALL_FUNCTION(X) X() void bar() { [[C^ALL_FUNC^TION(foo)]]; } )cpp", "CallExpr", }, { R"cpp( void foo(); #^define CALL_FUNCTION(X) X(^) void bar() { CALL_FUNCTION(foo); } )cpp", nullptr, }, { R"cpp( void foo(); #define CALL_FUNCTION(X) X() void bar() { CALL_FUNCTION(foo^)^; } )cpp", nullptr, }, { R"cpp( namespace ns { #if 0 void fo^o() {} #endif } )cpp", nullptr, }, { R"cpp( struct S { S(const char*); }; [[S s ^= "foo"]]; )cpp", // The AST says a CXXConstructExpr covers the = sign in C++14. // But we consider CXXConstructExpr to only own brackets. // (It's not the interesting constructor anyway, just S(&&)). "VarDecl", }, { R"cpp( struct S { S(const char*); }; [[S ^s = "foo"]]; )cpp", "VarDecl", }, { R"cpp( [[^void]] (*S)(int) = nullptr; )cpp", "BuiltinTypeLoc", }, { R"cpp( [[void (*S)^(int)]] = nullptr; )cpp", "FunctionProtoTypeLoc", }, { R"cpp( [[void (^*S)(int)]] = nullptr; )cpp", "PointerTypeLoc", }, { R"cpp( [[void (*^S)(int) = nullptr]]; )cpp", "VarDecl", }, { R"cpp( [[void ^(*S)(int)]] = nullptr; )cpp", "ParenTypeLoc", }, { R"cpp( struct S { int foo() const; int bar() { return [[f^oo]](); } }; )cpp", "MemberExpr", // Not implicit CXXThisExpr, or its implicit cast! }, { R"cpp( auto lambda = [](const char*){ return 0; }; int x = lambda([["y^"]]); )cpp", "StringLiteral", // Not DeclRefExpr to operator()! }, { R"cpp( struct Foo {}; struct Bar : [[v^ir^tual private Foo]] {}; )cpp", "CXXBaseSpecifier", }, { R"cpp( struct Foo {}; struct Bar : private [[Fo^o]] {}; )cpp", "RecordTypeLoc", }, { R"cpp( struct Foo {}; struct Bar : [[Fo^o]] {}; )cpp", "RecordTypeLoc", }, // Point selections. {"void foo() { [[^foo]](); }", "DeclRefExpr"}, {"void foo() { [[f^oo]](); }", "DeclRefExpr"}, {"void foo() { [[fo^o]](); }", "DeclRefExpr"}, {"void foo() { [[foo^()]]; }", "CallExpr"}, {"void foo() { [[foo^]] (); }", "DeclRefExpr"}, {"int bar; void foo() [[{ foo (); }]]^", "CompoundStmt"}, {"int x = [[42]]^;", "IntegerLiteral"}, // Ignores whitespace, comments, and semicolons in the selection. {"void foo() { [[foo^()]]; /*comment*/^}", "CallExpr"}, // Tricky case: FunctionTypeLoc in FunctionDecl has a hole in it. {"[[^void]] foo();", "BuiltinTypeLoc"}, {"[[void foo^()]];", "FunctionProtoTypeLoc"}, {"[[^void foo^()]];", "FunctionDecl"}, {"[[void ^foo()]];", "FunctionDecl"}, // Tricky case: two VarDecls share a specifier. {"[[int ^a]], b;", "VarDecl"}, {"[[int a, ^b]];", "VarDecl"}, // Tricky case: CXXConstructExpr wants to claim the whole init range. { R"cpp( struct X { X(int); }; class Y { X x; Y() : [[^x(4)]] {} }; )cpp", "CXXCtorInitializer", // Not the CXXConstructExpr! }, // Tricky case: anonymous struct is a sibling of the VarDecl. {"[[st^ruct {int x;}]] y;", "CXXRecordDecl"}, {"[[struct {int x;} ^y]];", "VarDecl"}, {"struct {[[int ^x]];} y;", "FieldDecl"}, // Tricky case: nested ArrayTypeLocs have the same token range. {"const int x = 1, y = 2; int array[^[[x]]][10][y];", "DeclRefExpr"}, {"const int x = 1, y = 2; int array[x][10][^[[y]]];", "DeclRefExpr"}, {"const int x = 1, y = 2; int array[x][^[[10]]][y];", "IntegerLiteral"}, {"const int x = 1, y = 2; [[i^nt]] array[x][10][y];", "BuiltinTypeLoc"}, {"void func(int x) { int v_array[^[[x]]][10]; }", "DeclRefExpr"}, {"int (*getFunc([[do^uble]]))(int);", "BuiltinTypeLoc"}, // FIXME: the AST has no location info for qualifiers. {"const [[a^uto]] x = 42;", "AutoTypeLoc"}, {"[[co^nst auto x = 42]];", "VarDecl"}, {"^", nullptr}, {"void foo() { [[foo^^]] (); }", "DeclRefExpr"}, // FIXME: Ideally we'd get a declstmt or the VarDecl itself here. // This doesn't happen now; the RAV doesn't traverse a node containing ;. {"int x = 42;^", nullptr}, // Common ancestor is logically TUDecl, but we never return that. {"^int x; int y;^", nullptr}, // Node types that have caused problems in the past. {"template <typename T> void foo() { [[^T]] t; }", "TemplateTypeParmTypeLoc"}, // No crash { R"cpp( template <class T> struct Foo {}; template <[[template<class> class /*cursor here*/^U]]> struct Foo<U<int>*> {}; )cpp", "TemplateTemplateParmDecl"}, // Foreach has a weird AST, ensure we can select parts of the range init. // This used to fail, because the DeclStmt for C claimed the whole range. { R"cpp( struct Str { const char *begin(); const char *end(); }; Str makeStr(const char*); void loop() { for (const char C : [[mak^eStr("foo"^)]]) ; } )cpp", "CallExpr"}, // User-defined literals are tricky: is 12_i one token or two? // For now we treat it as one, and the UserDefinedLiteral as a leaf. { R"cpp( struct Foo{}; Foo operator""_ud(unsigned long long); Foo x = [[^12_ud]]; )cpp", "UserDefinedLiteral"}, { R"cpp( int a; decltype([[^a]] + a) b; )cpp", "DeclRefExpr"}, {"[[decltype^(1)]] b;", "DecltypeTypeLoc"}, // Not the VarDecl. // decltype(auto) is an AutoTypeLoc! {"[[de^cltype(a^uto)]] a = 1;", "AutoTypeLoc"}, // Objective-C nullability attributes. { R"cpp( @interface I{} @property(nullable) [[^I]] *x; @end )cpp", "ObjCInterfaceTypeLoc"}, { R"cpp( @interface I{} - (void)doSomething:(nonnull [[i^d]])argument; @end )cpp", "TypedefTypeLoc"}, // Objective-C OpaqueValueExpr/PseudoObjectExpr has weird ASTs. // Need to traverse the contents of the OpaqueValueExpr to the POE, // and ensure we traverse only the syntactic form of the PseudoObjectExpr. { R"cpp( @interface I{} @property(retain) I*x; @property(retain) I*y; @end void test(I *f) { [[^f]].x.y = 0; } )cpp", "DeclRefExpr"}, { R"cpp( @interface I{} @property(retain) I*x; @property(retain) I*y; @end void test(I *f) { [[f.^x]].y = 0; } )cpp", "ObjCPropertyRefExpr"}, // Examples with implicit properties. { R"cpp( @interface I{} -(int)foo; @end int test(I *f) { return 42 + [[^f]].foo; } )cpp", "DeclRefExpr"}, { R"cpp( @interface I{} -(int)foo; @end int test(I *f) { return 42 + [[f.^foo]]; } )cpp", "ObjCPropertyRefExpr"}, {"struct foo { [[int has^h<:32:>]]; };", "FieldDecl"}, {"struct foo { [[op^erator int()]]; };", "CXXConversionDecl"}, {"struct foo { [[^~foo()]]; };", "CXXDestructorDecl"}, // FIXME: The following to should be class itself instead. {"struct foo { [[fo^o(){}]] };", "CXXConstructorDecl"}, {R"cpp( struct S1 { void f(); }; struct S2 { S1 * operator->(); }; void test(S2 s2) { s2[[-^>]]f(); } )cpp", "DeclRefExpr"}, // DeclRefExpr to the "operator->" method. // Template template argument. {R"cpp( template <typename> class Vector {}; template <template <typename> class Container> class A {}; A<[[V^ector]]> a; )cpp", "TemplateArgumentLoc"}, // Attributes {R"cpp( void f(int * __attribute__(([[no^nnull]])) ); )cpp", "NonNullAttr"}, {R"cpp( // Digraph syntax for attributes to avoid accidental annotations. class <:[gsl::Owner([[in^t]])]:> X{}; )cpp", "BuiltinTypeLoc"}, // This case used to crash - AST has a null Attr {R"cpp( @interface I [[@property(retain, nonnull) <:[My^Object2]:> *x]]; // error-ok @end )cpp", "ObjCPropertyDecl"}, {R"cpp( typedef int Foo; enum Bar : [[Fo^o]] {}; )cpp", "TypedefTypeLoc"}, {R"cpp( typedef int Foo; enum Bar : [[Fo^o]]; )cpp", "TypedefTypeLoc"}, }; for (const Case &C : Cases) { trace::TestTracer Tracer; Annotations Test(C.Code); TestTU TU; TU.Code = std::string(Test.code()); TU.ExtraArgs.push_back("-xobjective-c++"); auto AST = TU.build(); auto T = makeSelectionTree(C.Code, AST); EXPECT_EQ("TranslationUnitDecl", nodeKind(&T.root())) << C.Code; if (Test.ranges().empty()) { // If no [[range]] is marked in the example, there should be no selection. EXPECT_FALSE(T.commonAncestor()) << C.Code << "\n" << T; EXPECT_THAT(Tracer.takeMetric("selection_recovery", "C++"), testing::IsEmpty()); } else { // If there is an expected selection, common ancestor should exist // with the appropriate node type. EXPECT_EQ(C.CommonAncestorKind, nodeKind(T.commonAncestor())) << C.Code << "\n" << T; // Convert the reported common ancestor to a range and verify it. EXPECT_EQ(nodeRange(T.commonAncestor(), AST), Test.range()) << C.Code << "\n" << T; // Check that common ancestor is reachable on exactly one path from root, // and no nodes outside it are selected. EXPECT_TRUE(verifyCommonAncestor(T.root(), T.commonAncestor(), C.Code)) << C.Code; EXPECT_THAT(Tracer.takeMetric("selection_recovery", "C++"), ElementsAreArray({0})); } } } // Regression test: this used to match the injected X, not the outer X. TEST(SelectionTest, InjectedClassName) { const char *Code = "struct ^X { int x; };"; auto AST = TestTU::withCode(Annotations(Code).code()).build(); auto T = makeSelectionTree(Code, AST); ASSERT_EQ("CXXRecordDecl", nodeKind(T.commonAncestor())) << T; auto *D = dyn_cast<CXXRecordDecl>(T.commonAncestor()->ASTNode.get<Decl>()); EXPECT_FALSE(D->isInjectedClassName()); } TEST(SelectionTree, Metrics) { const char *Code = R"cpp( // error-ok: testing behavior on recovery expression int foo(); int foo(int, int); int x = fo^o(42); )cpp"; auto AST = TestTU::withCode(Annotations(Code).code()).build(); trace::TestTracer Tracer; auto T = makeSelectionTree(Code, AST); EXPECT_THAT(Tracer.takeMetric("selection_recovery", "C++"), ElementsAreArray({1})); EXPECT_THAT(Tracer.takeMetric("selection_recovery_type", "C++"), ElementsAreArray({1})); } // FIXME: Doesn't select the binary operator node in // #define FOO(X) X + 1 // int a, b = [[FOO(a)]]; TEST(SelectionTest, Selected) { // Selection with ^marks^. // Partially selected nodes marked with a [[range]]. // Completely selected nodes marked with a $C[[range]]. const char *Cases[] = { R"cpp( int abc, xyz = [[^ab^c]]; )cpp", R"cpp( int abc, xyz = [[a^bc^]]; )cpp", R"cpp( int abc, xyz = $C[[^abc^]]; )cpp", R"cpp( void foo() { [[if ([[1^11]]) $C[[{ $C[[return]]; }]] else [[{^ }]]]] char z; } )cpp", R"cpp( template <class T> struct unique_ptr {}; void foo(^$C[[unique_ptr<$C[[unique_ptr<$C[[int]]>]]>]]^ a) {} )cpp", R"cpp(int a = [[5 >^> 1]];)cpp", R"cpp( #define ECHO(X) X ECHO(EC^HO($C[[int]]) EC^HO(a)); )cpp", R"cpp( $C[[^$C[[int]] a^]]; )cpp", R"cpp( $C[[^$C[[int]] a = $C[[5]]^]]; )cpp", }; for (const char *C : Cases) { Annotations Test(C); auto AST = TestTU::withCode(Test.code()).build(); auto T = makeSelectionTree(C, AST); std::vector<Range> Complete, Partial; for (const SelectionTree::Node *N : allNodes(T)) if (N->Selected == SelectionTree::Complete) Complete.push_back(nodeRange(N, AST)); else if (N->Selected == SelectionTree::Partial) Partial.push_back(nodeRange(N, AST)); EXPECT_THAT(Complete, UnorderedElementsAreArray(Test.ranges("C"))) << C; EXPECT_THAT(Partial, UnorderedElementsAreArray(Test.ranges())) << C; } } TEST(SelectionTest, PathologicalPreprocessor) { const char *Case = R"cpp( #define MACRO while(1) void test() { #include "Expand.inc" br^eak; } )cpp"; Annotations Test(Case); auto TU = TestTU::withCode(Test.code()); TU.AdditionalFiles["Expand.inc"] = "MACRO\n"; auto AST = TU.build(); EXPECT_THAT(*AST.getDiagnostics(), ::testing::IsEmpty()); auto T = makeSelectionTree(Case, AST); EXPECT_EQ("BreakStmt", T.commonAncestor()->kind()); EXPECT_EQ("WhileStmt", T.commonAncestor()->Parent->kind()); } TEST(SelectionTest, IncludedFile) { const char *Case = R"cpp( void test() { #include "Exp^and.inc" break; } )cpp"; Annotations Test(Case); auto TU = TestTU::withCode(Test.code()); TU.AdditionalFiles["Expand.inc"] = "while(1)\n"; auto AST = TU.build(); auto T = makeSelectionTree(Case, AST); EXPECT_EQ(nullptr, T.commonAncestor()); } TEST(SelectionTest, MacroArgExpansion) { // If a macro arg is expanded several times, we only consider the first one // selected. const char *Case = R"cpp( int mul(int, int); #define SQUARE(X) mul(X, X); int nine = SQUARE(^3); )cpp"; Annotations Test(Case); auto AST = TestTU::withCode(Test.code()).build(); auto T = makeSelectionTree(Case, AST); EXPECT_EQ("IntegerLiteral", T.commonAncestor()->kind()); EXPECT_TRUE(T.commonAncestor()->Selected); // Verify that the common assert() macro doesn't suffer from this. // (This is because we don't associate the stringified token with the arg). Case = R"cpp( void die(const char*); #define assert(x) (x ? (void)0 : die(#x)) void foo() { assert(^42); } )cpp"; Test = Annotations(Case); AST = TestTU::withCode(Test.code()).build(); T = makeSelectionTree(Case, AST); EXPECT_EQ("IntegerLiteral", T.commonAncestor()->kind()); } TEST(SelectionTest, Implicit) { const char *Test = R"cpp( struct S { S(const char*); }; int f(S); int x = f("^"); )cpp"; auto AST = TestTU::withCode(Annotations(Test).code()).build(); auto T = makeSelectionTree(Test, AST); const SelectionTree::Node *Str = T.commonAncestor(); EXPECT_EQ("StringLiteral", nodeKind(Str)) << "Implicit selected?"; EXPECT_EQ("ImplicitCastExpr", nodeKind(Str->Parent)); EXPECT_EQ("CXXConstructExpr", nodeKind(Str->Parent->Parent)); EXPECT_EQ(Str, &Str->Parent->Parent->ignoreImplicit()) << "Didn't unwrap " << nodeKind(&Str->Parent->Parent->ignoreImplicit()); EXPECT_EQ("CXXConstructExpr", nodeKind(&Str->outerImplicit())); } TEST(SelectionTest, CreateAll) { llvm::Annotations Test("int$unique^ a=1$ambiguous^+1; $empty^"); auto AST = TestTU::withCode(Test.code()).build(); unsigned Seen = 0; SelectionTree::createEach( AST.getASTContext(), AST.getTokens(), Test.point("ambiguous"), Test.point("ambiguous"), [&](SelectionTree T) { // Expect to see the right-biased tree first. if (Seen == 0) { EXPECT_EQ("BinaryOperator", nodeKind(T.commonAncestor())); } else if (Seen == 1) { EXPECT_EQ("IntegerLiteral", nodeKind(T.commonAncestor())); } ++Seen; return false; }); EXPECT_EQ(2u, Seen); Seen = 0; SelectionTree::createEach(AST.getASTContext(), AST.getTokens(), Test.point("ambiguous"), Test.point("ambiguous"), [&](SelectionTree T) { ++Seen; return true; }); EXPECT_EQ(1u, Seen) << "Return true --> stop iterating"; Seen = 0; SelectionTree::createEach(AST.getASTContext(), AST.getTokens(), Test.point("unique"), Test.point("unique"), [&](SelectionTree T) { ++Seen; return false; }); EXPECT_EQ(1u, Seen) << "no ambiguity --> only one tree"; Seen = 0; SelectionTree::createEach(AST.getASTContext(), AST.getTokens(), Test.point("empty"), Test.point("empty"), [&](SelectionTree T) { EXPECT_FALSE(T.commonAncestor()); ++Seen; return false; }); EXPECT_EQ(1u, Seen) << "empty tree still created"; Seen = 0; SelectionTree::createEach(AST.getASTContext(), AST.getTokens(), Test.point("unique"), Test.point("ambiguous"), [&](SelectionTree T) { ++Seen; return false; }); EXPECT_EQ(1u, Seen) << "one tree for nontrivial selection"; } TEST(SelectionTest, DeclContextIsLexical) { llvm::Annotations Test("namespace a { void $1^foo(); } void a::$2^foo();"); auto AST = TestTU::withCode(Test.code()).build(); { auto ST = SelectionTree::createRight(AST.getASTContext(), AST.getTokens(), Test.point("1"), Test.point("1")); EXPECT_FALSE(ST.commonAncestor()->getDeclContext().isTranslationUnit()); } { auto ST = SelectionTree::createRight(AST.getASTContext(), AST.getTokens(), Test.point("2"), Test.point("2")); EXPECT_TRUE(ST.commonAncestor()->getDeclContext().isTranslationUnit()); } } } // namespace } // namespace clangd } // namespace clang
31.731959
80
0.515513
hborla
0f454bfc8ec10cb942fabe7006a52f259e290b27
944
cpp
C++
coast/modules/Security/Base64WDRenderer.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
coast/modules/Security/Base64WDRenderer.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
coast/modules/Security/Base64WDRenderer.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ #include "Base64WDRenderer.h" #include "Tracer.h" #include "Base64.h" //---- Base64WDRenderer --------------------------------------------------------------- RegisterRenderer(Base64WDRenderer); Base64WDRenderer::Base64WDRenderer(const char *name) : Renderer(name) { } Base64WDRenderer::~Base64WDRenderer() { } void Base64WDRenderer::RenderAll(std::ostream &reply, Context &ctx, const ROAnything &config) { StartTrace(Base64WDRenderer.RenderAll); String clearText, b64EncodedText; Renderer::RenderOnString(clearText, ctx, config); Base64(fName).DoEncode(b64EncodedText, clearText); reply << b64EncodedText; }
32.551724
102
0.717161
zer0infinity
0f46ef60058b018543fd088fcdedae365ee2ad5c
1,951
hpp
C++
src/PlayerManager.hpp
josephl70/OpenFusion
c1200e94c5f933bffb5885b1a83b9dab5ceb1db1
[ "MIT" ]
1
2020-08-20T17:43:10.000Z
2020-08-20T17:43:10.000Z
src/PlayerManager.hpp
josephl70/OpenFusion_VS
c1200e94c5f933bffb5885b1a83b9dab5ceb1db1
[ "MIT" ]
null
null
null
src/PlayerManager.hpp
josephl70/OpenFusion_VS
c1200e94c5f933bffb5885b1a83b9dab5ceb1db1
[ "MIT" ]
null
null
null
#pragma once #include "Player.hpp" #include "CNProtocol.hpp" #include "CNStructs.hpp" #include "CNShardServer.hpp" #include <map> #include <list> struct WarpLocation; struct PlayerView { std::list<CNSocket*> viewable; std::list<int32_t> viewableNPCs; Player *plr; uint64_t lastHeartbeat; }; namespace PlayerManager { extern std::map<CNSocket*, PlayerView> players; void init(); void addPlayer(CNSocket* key, Player plr); void removePlayer(CNSocket* key); void updatePlayerPosition(CNSocket* sock, int X, int Y, int Z); std::list<CNSocket*> getNearbyPlayers(int X, int Y, int dist); void enterPlayer(CNSocket* sock, CNPacketData* data); void loadPlayer(CNSocket* sock, CNPacketData* data); void movePlayer(CNSocket* sock, CNPacketData* data); void stopPlayer(CNSocket* sock, CNPacketData* data); void jumpPlayer(CNSocket* sock, CNPacketData* data); void jumppadPlayer(CNSocket* sock, CNPacketData* data); void launchPlayer(CNSocket* sock, CNPacketData* data); void ziplinePlayer(CNSocket* sock, CNPacketData* data); void movePlatformPlayer(CNSocket* sock, CNPacketData* data); void moveSlopePlayer(CNSocket* sock, CNPacketData* data); void gotoPlayer(CNSocket* sock, CNPacketData* data); void setSpecialPlayer(CNSocket* sock, CNPacketData* data); void heartbeatPlayer(CNSocket* sock, CNPacketData* data); void revivePlayer(CNSocket* sock, CNPacketData* data); void exitGame(CNSocket* sock, CNPacketData* data); void setSpecialSwitchPlayer(CNSocket* sock, CNPacketData* data); void changePlayerGuide(CNSocket *sock, CNPacketData *data); void enterPlayerVehicle(CNSocket* sock, CNPacketData* data); void exitPlayerVehicle(CNSocket* sock, CNPacketData* data); Player *getPlayer(CNSocket* key); WarpLocation getRespawnPoint(Player *plr); bool isAccountInUse(int accountId); void exitDuplicate(int accountId); }
33.067797
68
0.732445
josephl70
0f4e164d4244acf11a280e7f8a2dff813b57c3f8
1,346
hpp
C++
src/external/boost/boost_1_68_0/libs/metaparse/example/meta_hs/example_in_haskell.hpp
Bpowers4/turicreate
73dad213cc1c4f74337b905baea2b3a1e5a0266c
[ "BSD-3-Clause" ]
11,356
2017-12-08T19:42:32.000Z
2022-03-31T16:55:25.000Z
src/external/boost/boost_1_68_0/libs/metaparse/example/meta_hs/example_in_haskell.hpp
Bpowers4/turicreate
73dad213cc1c4f74337b905baea2b3a1e5a0266c
[ "BSD-3-Clause" ]
2,402
2017-12-08T22:31:01.000Z
2022-03-28T19:25:52.000Z
src/external/boost/boost_1_68_0/libs/metaparse/example/meta_hs/example_in_haskell.hpp
Bpowers4/turicreate
73dad213cc1c4f74337b905baea2b3a1e5a0266c
[ "BSD-3-Clause" ]
1,343
2017-12-08T19:47:19.000Z
2022-03-26T11:31:36.000Z
#ifndef EXAMPLE_IN_HASKELL_HPP #define EXAMPLE_IN_HASKELL_HPP // Copyright Abel Sinkovics (abel@sinkovics.hu) 2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/config.hpp> #if BOOST_METAPARSE_STD < 2011 // We have to fall back on the handcrafted one #include <example_handcrafted.hpp> #else #define BOOST_MPL_LIMIT_STRING_SIZE 50 #define BOOST_METAPARSE_LIMIT_STRING_SIZE BOOST_MPL_LIMIT_STRING_SIZE #include <meta_hs.hpp> #include <double_number.hpp> #include <boost/metaparse/string.hpp> #include <boost/mpl/int.hpp> #ifdef _STR # error _STR already defined #endif #define _STR BOOST_METAPARSE_STRING typedef meta_hs ::import1<_STR("f"), double_number>::type ::import<_STR("val"), boost::mpl::int_<11> >::type ::define<_STR("fib n = if n<2 then 1 else fib(n-2) + fib(n-1)")>::type ::define<_STR("fact n = if n<1 then 1 else n * fact(n-1)")>::type ::define<_STR("times4 n = f (f n)")>::type ::define<_STR("times11 n = n * val")>::type metafunctions; typedef metafunctions::get<_STR("fib")> fib; typedef metafunctions::get<_STR("fact")> fact; typedef metafunctions::get<_STR("times4")> times4; typedef metafunctions::get<_STR("times11")> times11; #endif #endif
25.884615
74
0.716939
Bpowers4
0f50f1363313589315c0ea5ed4cc9c3899526682
3,024
hpp
C++
CaffeMex_V28/include/caffe/layers/batch_norm_layer.hpp
yyht/OSM_CAA_WeightedContrastiveLoss
a8911b9fc1c951a2caec26a16473a8f5bfb2005f
[ "BSD-3-Clause" ]
196
2018-07-07T14:22:37.000Z
2022-03-19T06:21:11.000Z
CaffeMex_V28/include/caffe/layers/batch_norm_layer.hpp
yyht/OSM_CAA_WeightedContrastiveLoss
a8911b9fc1c951a2caec26a16473a8f5bfb2005f
[ "BSD-3-Clause" ]
2
2018-07-09T09:19:09.000Z
2018-07-17T15:08:49.000Z
lib/caffe-action/include/caffe/layers/batch_norm_layer.hpp
ParrtZhang/Optical-Flow-Guided-Feature
07d4501a29002ee7821c38c1820e4a64c1acf6e8
[ "MIT" ]
48
2018-07-10T02:11:20.000Z
2022-02-04T14:26:30.000Z
#ifndef CAFFE_BATCHNORM_LAYER_HPP_ #define CAFFE_BATCHNORM_LAYER_HPP_ #include <vector> #include "caffe/blob.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" namespace caffe { /** * @brief Normalizes the input to have 0-mean and/or unit (1) variance across * the batch. * * This layer computes Batch Normalization as described in [1]. For each channel * in the data (i.e. axis 1), it subtracts the mean and divides by the variance, * where both statistics are computed across both spatial dimensions and across * the different examples in the batch. * * By default, during training time, the network is computing global * mean/variance statistics via a running average, which is then used at test * time to allow deterministic outputs for each input. You can manually toggle * whether the network is accumulating or using the statistics via the * use_global_stats option. For reference, these statistics are kept in the * layer's three blobs: (0) mean, (1) variance, and (2) moving average factor. * * Note that the original paper also included a per-channel learned bias and * scaling factor. To implement this in Caffe, define a `ScaleLayer` configured * with `bias_term: true` after each `BatchNormLayer` to handle both the bias * and scaling factor. * * [1] S. Ioffe and C. Szegedy, "Batch Normalization: Accelerating Deep Network * Training by Reducing Internal Covariate Shift." arXiv preprint * arXiv:1502.03167 (2015). * * TODO(dox): thorough documentation for Forward, Backward, and proto params. */ template <typename Dtype> class BatchNormLayer : public Layer<Dtype> { public: explicit BatchNormLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "BatchNorm"; } virtual inline int ExactNumBottomBlobs() const { return 1; } virtual inline int ExactNumTopBlobs() const { return 1; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); Blob<Dtype> mean_, variance_, temp_, x_norm_; bool use_global_stats_; Dtype moving_average_fraction_; int channels_; Dtype eps_; // extra temporarary variables is used to carry out sums/broadcasting // using BLAS Blob<Dtype> batch_sum_multiplier_; Blob<Dtype> num_by_chans_; Blob<Dtype> spatial_sum_multiplier_; }; } // namespace caffe #endif // CAFFE_BATCHNORM_LAYER_HPP_
38.769231
80
0.73578
yyht
0f52348b383924b272ae4ffbf011f04dd4cf2573
2,315
cpp
C++
Main/gshow.cpp
dice-group/gStore-1
3b4fe58f021e6285026f4c948d5b30170e0cf28b
[ "BSD-3-Clause" ]
null
null
null
Main/gshow.cpp
dice-group/gStore-1
3b4fe58f021e6285026f4c948d5b30170e0cf28b
[ "BSD-3-Clause" ]
null
null
null
Main/gshow.cpp
dice-group/gStore-1
3b4fe58f021e6285026f4c948d5b30170e0cf28b
[ "BSD-3-Clause" ]
null
null
null
/*============================================================================= # Filename: gshow.cpp # Author: suxunbin # Mail: suxunbin@pku.edu.cn # Last Modified: 2019-07-25 17:00 # Description: used to show all the databases that have already been built =============================================================================*/ #include "../Util/Util.h" #include "../Database/Database.h" using namespace std; struct DBInfo { public: string db_name; string creator; string built_time; DBInfo() { } DBInfo(string _db_name) { db_name = _db_name; } ~DBInfo() { } }; string Getstr(string s) { int len = s.length(); return s.substr(1, len - 2); } int main(int argc, char* argv[]) { Util util; Database system_db("system"); system_db.load(); string sparql = "select ?s where{?s <database_status> \"already_built\".}"; ResultSet _rs; FILE* ofp = stdout; int ret = system_db.query(sparql, _rs, ofp); DBInfo* databases = new DBInfo[_rs.ansNum + 1]; databases[0].db_name = "<system>"; for (int i = 0; i < _rs.ansNum; i++) { databases[i + 1].db_name = _rs.answer[i][0]; string sparql1 = "select ?p ?o where{" + _rs.answer[i][0] + " ?p ?o.}"; ResultSet _rs1; FILE* ofp1 = stdout; int ret1 = system_db.query(sparql1, _rs1, ofp1); for (int j = 0; j < _rs1.ansNum; j++) { string p = _rs1.answer[j][0]; string o = _rs1.answer[j][1]; if (p == "<built_by>") databases[i + 1].creator = o; else if (p == "<built_time>") databases[i + 1].built_time = o; } } string sparql1 = "select ?p ?o where{<system> ?p ?o.}"; ResultSet _rs1; FILE* ofp1 = stdout; int ret1 = system_db.query(sparql1, _rs1, ofp1); for (int j = 0; j < _rs1.ansNum; j++) { string p = _rs1.answer[j][0]; string o = _rs1.answer[j][1]; if (p == "<built_by>") databases[0].creator = o; else if (p == "<built_time>") databases[0].built_time = o; } cout << "\n========================================\n"; for (int i = 0; i < _rs.ansNum + 1; i++) { string output = "database: " + Getstr(databases[i].db_name) + "\ncreator: " + Getstr(databases[i].creator) + "\nbuilt_time: " + databases[i].built_time + "\n========================================\n"; cout << output; } return 0; }
27.891566
205
0.531317
dice-group
0f529415588d99b621fe95f27a306d22ec7c8f82
3,652
cc
C++
not_found_detector_test.cc
google/plusfish
a56ac07ca132613ecda7f252a69312ada66bbbca
[ "Apache-2.0" ]
14
2020-10-16T18:33:37.000Z
2022-03-27T18:29:00.000Z
not_found_detector_test.cc
qause/plusfish
a56ac07ca132613ecda7f252a69312ada66bbbca
[ "Apache-2.0" ]
2
2021-03-18T11:19:59.000Z
2021-04-26T12:27:33.000Z
not_found_detector_test.cc
qause/plusfish
a56ac07ca132613ecda7f252a69312ada66bbbca
[ "Apache-2.0" ]
5
2021-06-29T10:51:04.000Z
2022-01-09T05:18:16.000Z
// Copyright 2020 Google LLC. 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 "not_found_detector.h" #include "gmock/gmock.h" #include <gtest/gtest.h> #include "gtest/gtest.h" #include "absl/container/flat_hash_set.h" #include "absl/container/node_hash_set.h" #include "request.h" #include "response.h" #include "testing/http_client_mock.h" #include "testing/request_mock.h" #include "util/html_fingerprint.h" using testing::ContainsRegex; using testing::Return; using testing::ReturnNull; namespace plusfish { class NotFoundDetectorTest : public ::testing::Test { public: NotFoundDetectorTest() : target_url_("http://test/foo.html") {} void SetUp() override { detector_.reset(new NotFoundDetector()); fake_schedule_callback_count_ = 0; fake_schedule_callback_return_value_ = true; fake_store_fp_callback_count_ = 0; fake_schedule_callback_req_urls_.clear(); // Set the two callbacks. detector_->SetHttpClientScheduleCallback([this](const Request* req) { this->fake_schedule_callback_req_urls_.insert(req->url()); this->fake_schedule_callback_count_++; return fake_schedule_callback_return_value_; }); detector_->SetDatastoreFingerprintCallback( [this](const HtmlFingerprint* fp) { this->fake_store_fp_callback_count_++; }); } int fake_store_fp_callback_count_; int fake_schedule_callback_count_; bool fake_schedule_callback_return_value_; absl::node_hash_set<std::string> fake_schedule_callback_req_urls_; std::string target_url_; std::unique_ptr<NotFoundDetector> detector_; }; TEST_F(NotFoundDetectorTest, AddUrlScheduledCorrectRequests) { detector_->AddUrl(target_url_); EXPECT_EQ(9, fake_schedule_callback_count_); for (const auto& url : fake_schedule_callback_req_urls_) { EXPECT_THAT(url, ContainsRegex("http:\\/\\/test:80\\/[0-9]+\\.[a-z]+")); } } TEST_F(NotFoundDetectorTest, AddUrlScheduledCorrectRequestsAndAddsSlash) { detector_->AddUrl("http://test:80"); EXPECT_EQ(9, fake_schedule_callback_count_); for (const auto& url : fake_schedule_callback_req_urls_) { EXPECT_THAT(url, ContainsRegex("http:\\/\\/test:80\\/[0-9]+\\.[a-z]+")); } } TEST_F(NotFoundDetectorTest, AddUrlScheduleFailsCorrect) { fake_schedule_callback_return_value_ = false; detector_->AddUrl(target_url_); EXPECT_EQ(0, detector_->probed_urls().size()); } TEST_F(NotFoundDetectorTest, RequestCallbackNoResponse) { testing::MockRequest request("http://test:80/foo.html"); EXPECT_CALL(request, response()).WillOnce(ReturnNull()); EXPECT_EQ(0, detector_->RequestCallback(&request)); EXPECT_EQ(0, fake_store_fp_callback_count_); } TEST_F(NotFoundDetectorTest, RequestCallbackOk) { testing::MockRequest request("http://test:80/foo.html"); Response response; response.Parse( "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n" "<html><p>a la la</p></html>"); EXPECT_CALL(request, response()).Times(2).WillRepeatedly(Return(&response)); EXPECT_EQ(1, detector_->RequestCallback(&request)); EXPECT_EQ(1, fake_store_fp_callback_count_); } } // namespace plusfish
33.504587
78
0.745071
google
0f5302bcdb7dee65025f22800a6a8022d05efc29
14,309
cpp
C++
test/test_nrf24Radio.cpp
fgr1986/fused
2443cf92390914060b074d12e9226f5358e3899b
[ "Apache-2.0" ]
9
2020-04-25T13:37:31.000Z
2021-02-27T08:36:12.000Z
test/test_nrf24Radio.cpp
fgr1986/fused
2443cf92390914060b074d12e9226f5358e3899b
[ "Apache-2.0" ]
null
null
null
test/test_nrf24Radio.cpp
fgr1986/fused
2443cf92390914060b074d12e9226f5358e3899b
[ "Apache-2.0" ]
5
2021-01-20T23:08:23.000Z
2021-11-18T04:39:32.000Z
/* * Copyright (c) 2019-2020, University of Southampton and Contributors. * All rights reserved. * * SPDX-License-Identifier: Apache-2.0 */ #include <spdlog/spdlog.h> #include <tlm_utils/simple_initiator_socket.h> #include <systemc> #include <tlm> #include "mcu/RegisterFile.hpp" #include "mcu/SpiTransactionExtension.hpp" #include "ps/PowerModelChannel.hpp" #include "sd/Nrf24Radio.hpp" #include "utilities/Config.hpp" #include "utilities/Utilities.hpp" extern "C" { #include "mcu/msp430fr5xx/device_includes/msp430fr5994.h" } using namespace sc_core; using namespace Utility; SC_MODULE(dut) { public: // Signals sc_signal<bool> nReset{"nReset"}; // Active low sc_signal_resolved chipSelect{"chipSelect"}; // Active low sc_signal_resolved chipEnable{"chipEnable"}; // Active high sc_signal_resolved interruptRequest{"interruptRequest"}; // Active low // Sockets tlm_utils::simple_initiator_socket<dut> iSpiSocket{"iSpiSocket"}; PowerModelChannel powerModelChannel{"powerModelChannel", "/tmp", sc_time(1, SC_US)}; SC_CTOR(dut) { m_dut.nReset.bind(nReset); m_dut.chipSelect.bind(chipSelect); m_dut.chipEnable.bind(chipEnable); m_dut.interruptRequest.bind(interruptRequest); m_dut.tSocket.bind(iSpiSocket); m_dut.powerModelPort.bind(powerModelChannel); } Nrf24Radio m_dut{"Nrf24Radio"}; }; SC_MODULE(tester) { public: SC_CTOR(tester) { SC_THREAD(runtests); } void runtests() { wait(sc_time(1, SC_US)); // Initialise test.nReset.write(true); wait(sc_time(100, SC_MS)); test.chipSelect.write(sc_dt::sc_logic(true)); test.chipEnable.write(sc_dt::sc_logic(false)); test.interruptRequest.write(sc_dt::sc_logic('Z')); // Prepare payload object uint8_t data = 0xab; tlm::tlm_generic_payload trans; auto *spiExtension = new SpiTransactionExtension(); trans.set_extension(spiExtension); trans.set_address(0); // SPI doesn't use address trans.set_data_length(1); // Transfer size up to 1 byte spiExtension->clkPeriod = sc_core::sc_time(10, sc_core::SC_US); spiExtension->nDataBits = 8; spiExtension->phase = SpiTransactionExtension::SpiPhase::CAPTURE_FIRST_EDGE; spiExtension->polarity = SpiTransactionExtension::SpiPolarity::HIGH; spiExtension->bitOrder = SpiTransactionExtension::SpiBitOrder::MSB_FIRST; sc_time delay = spiExtension->transferTime(); trans.set_command(tlm::TLM_WRITE_COMMAND); trans.set_data_ptr(&data); trans.set_response_status(tlm::TLM_INCOMPLETE_RESPONSE); wait(sc_time(1, SC_US)); spdlog::info("{:s}: Testing Starts @{:s}", this->name(), sc_time_stamp().to_string()); // ------ TEST: Read Registers test.chipSelect.write(sc_dt::sc_logic(false)); wait(sc_time(1, SC_US)); data = R_REGISTER; // data = 0xa1; // This is an invalid command test.iSpiSocket->b_transport(trans, delay); wait(delay); // Check response status if (trans.is_response_error()) { SC_REPORT_FATAL(this->name(), "Response error"); } else { sc_assert(trans.get_response_status() == tlm::tlm_response_status::TLM_OK_RESPONSE); } // Returned payload should be contents of status register sc_assert(spiExtension->response == (RX_P_NO_2 | RX_P_NO_1 | RX_P_NO_0)); // Expecting data bits sc_assert(test.m_dut.m_payloadType == Nrf24Radio::PayloadType::DATA); // Read First Register (NRF_CONFIG: 0x00) test.iSpiSocket->b_transport(trans, delay); wait(delay); // Check response status if (trans.is_response_error()) { SC_REPORT_FATAL(this->name(), "Response error"); } else { sc_assert(trans.get_response_status() == tlm::tlm_response_status::TLM_OK_RESPONSE); } // Check return payload sc_assert(spiExtension->response == EN_CRC); // Still expecting data bits sc_assert(test.m_dut.m_payloadType == Nrf24Radio::PayloadType::DATA); // Read next register (EN_AA: 0x01) test.iSpiSocket->b_transport(trans, delay); wait(delay); sc_assert(spiExtension->response == 0b00111111); // Warning if read beyond 5 registers test.iSpiSocket->b_transport(trans, delay); wait(delay); test.iSpiSocket->b_transport(trans, delay); wait(delay); test.iSpiSocket->b_transport(trans, delay); wait(delay); test.iSpiSocket->b_transport(trans, delay); wait(delay); wait(sc_time(1, SC_US)); test.chipSelect.write(sc_dt::sc_logic(true)); wait(sc_time(1, SC_US)); // ------ TEST: Write to Registers, Read from Registers spdlog::info("------ TEST: Write to Registers, Read from Registers"); test.chipSelect.write(sc_dt::sc_logic(false)); wait(sc_time(1, SC_US)); sc_assert(test.m_dut.m_payloadType == Nrf24Radio::PayloadType::COMMAND); // Give write to NRF_CONFIG (0x00) command data = W_REGISTER | EN_AA; test.iSpiSocket->b_transport(trans, delay); wait(delay); sc_assert(spiExtension->response == (RX_P_NO_2 | RX_P_NO_1 | RX_P_NO_0)); // Expecting data sc_assert(test.m_dut.m_payloadType == Nrf24Radio::PayloadType::DATA); // Write data data = 0xab; test.iSpiSocket->b_transport(trans, delay); wait(delay); sc_assert(test.m_dut.m_payloadType == Nrf24Radio::PayloadType::DATA); wait(sc_time(1, SC_US)); test.chipSelect.write(sc_dt::sc_logic(true)); wait(sc_time(1, SC_US)); // Read back written data test.chipSelect.write(sc_dt::sc_logic(false)); wait(sc_time(1, SC_US)); sc_assert(test.m_dut.m_payloadType == Nrf24Radio::PayloadType::COMMAND); data = R_REGISTER | EN_AA; test.iSpiSocket->b_transport(trans, delay); wait(delay); sc_assert(test.m_dut.m_payloadType == Nrf24Radio::PayloadType::DATA); test.iSpiSocket->b_transport(trans, delay); wait(delay); // Check that is is the same as the written sc_assert(spiExtension->response == 0xab); wait(sc_time(1, SC_US)); test.chipSelect.write(sc_dt::sc_logic(true)); wait(sc_time(1, SC_US)); // ------ TEST: State Machine spdlog::info("------ TEST: State Machine"); test.nReset.write(false); wait(sc_time(1, SC_US)); sc_assert(test.m_dut.m_radio_state == Nrf24Radio::OpModes::UNDEFINED); test.nReset.write(true); wait(sc_time(1, SC_US)); sc_assert(test.m_dut.m_radio_state == Nrf24Radio::OpModes::POWER_ON_RESET); wait(sc_time(100, SC_MS)); sc_assert(test.m_dut.m_radio_state == Nrf24Radio::OpModes::POWER_DOWN); // Write PWR_UP = 1 // POWER_DOWN -> STANDBY1 test.chipSelect.write(sc_dt::sc_logic(false)); wait(sc_time(1, SC_US)); data = W_REGISTER | NRF_CONFIG; test.iSpiSocket->b_transport(trans, delay); wait(delay); data = PWR_UP; test.iSpiSocket->b_transport(trans, delay); wait(delay); test.chipSelect.write(sc_dt::sc_logic(true)); wait(sc_time(1, SC_US)); sc_assert(test.m_dut.m_radio_state == Nrf24Radio::OpModes::OSC_STARTUP); wait(sc_time(3, SC_MS)); sc_assert(test.m_dut.m_radio_state == Nrf24Radio::OpModes::STANDBY1); // CE _| , PRIM_RX = 1 // STANDBY1 -> RX_MODE test.chipSelect.write(sc_dt::sc_logic(false)); wait(sc_time(1, SC_US)); data = W_REGISTER | NRF_CONFIG; test.iSpiSocket->b_transport(trans, delay); wait(delay); data = PWR_UP | PRIM_RX; test.iSpiSocket->b_transport(trans, delay); wait(delay); test.chipSelect.write(sc_dt::sc_logic(true)); wait(sc_time(1, SC_US)); test.chipEnable.write(sc_dt::sc_logic(true)); wait(sc_time(1, SC_US)); sc_assert(test.m_dut.m_radio_state == Nrf24Radio::OpModes::RX_SETTLING); wait(sc_time(130, SC_US)); sc_assert(test.m_dut.m_radio_state == Nrf24Radio::OpModes::RX_MODE); wait(sc_time(1, SC_MS)); sc_assert(test.m_dut.m_radio_state == Nrf24Radio::OpModes::RX_MODE); // CE |_ // RX_MODE -> STANDBY1 test.chipEnable.write(sc_dt::sc_logic(false)); wait(sc_time(1, SC_US)); sc_assert(test.m_dut.m_radio_state == Nrf24Radio::OpModes::STANDBY1); // ------ TEST: Writing to TX Fifo spdlog::info("------ TEST: Writing to TX Fifo"); test.chipSelect.write(sc_dt::sc_logic(false)); wait(sc_time(1, SC_US)); data = W_TX_PAYLOAD; test.iSpiSocket->b_transport(trans, delay); wait(delay); data = 0xab; test.iSpiSocket->b_transport(trans, delay); wait(delay); sc_assert(!test.m_dut.m_txFifo.isEmpty()); test.chipSelect.write(sc_dt::sc_logic(true)); wait(sc_time(1, SC_US)); // ------ TEST: Popping from TX Fifo // then keeping CE high // since tx fifo empty, TX_MODE -> STANDBY2 spdlog::info("------ TEST: Popping from TX Fifo (single tx)"); test.chipSelect.write(sc_dt::sc_logic(false)); wait(sc_time(1, SC_US)); data = W_REGISTER | NRF_CONFIG; test.iSpiSocket->b_transport(trans, delay); wait(delay); data = PWR_UP; // clear PRIM_RX test.iSpiSocket->b_transport(trans, delay); wait(delay); test.chipSelect.write(sc_dt::sc_logic(true)); wait(sc_time(1, SC_US)); test.chipEnable.write(sc_dt::sc_logic(true)); wait(sc_time(1, SC_US)); sc_assert(test.m_dut.m_radio_state == Nrf24Radio::OpModes::TX_SETTLING); wait(sc_time(130, SC_US)); sc_assert(test.m_dut.m_radio_state == Nrf24Radio::OpModes::TX_MODE); wait(sc_time(28, SC_US)); sc_assert(test.m_dut.m_radio_state == Nrf24Radio::OpModes::STANDBY2); // Irq line active low sc_assert(test.interruptRequest.read().to_bool() == 0); wait(sc_time(1, SC_US)); // Clear the interrupt line test.chipSelect.write(sc_dt::sc_logic(false)); wait(sc_time(1, SC_US)); data = W_REGISTER | NRF_STATUS; test.iSpiSocket->b_transport(trans, delay); wait(delay); data = TX_DS | RX_P_NO_2 | RX_P_NO_1 | RX_P_NO_0; // clear TX_DS test.iSpiSocket->b_transport(trans, delay); wait(delay); test.chipSelect.write(sc_dt::sc_logic(true)); wait(sc_time(1, SC_US)); // Irq line active low wait(sc_time(1, SC_US)); sc_assert(test.interruptRequest.read().to_bool() == 1); // ------ TEST: Writing to TX Fifo when in STANDBY2 (CE held high) // auto tirggers transmit spdlog::info( "------ TEST: Writing to TX Fifo when in STANDBY2 (auto trigger)"); test.chipSelect.write(sc_dt::sc_logic(false)); wait(sc_time(1, SC_US)); data = W_TX_PAYLOAD; test.iSpiSocket->b_transport(trans, delay); wait(delay); data = 0xac; test.iSpiSocket->b_transport(trans, delay); wait(delay); test.chipSelect.write(sc_dt::sc_logic(true)); wait(sc_time(1, SC_US)); sc_assert(test.m_dut.m_radio_state == Nrf24Radio::OpModes::TX_SETTLING); wait(sc_time(130, SC_US)); sc_assert(test.m_dut.m_radio_state == Nrf24Radio::OpModes::TX_MODE); test.chipEnable.write( sc_dt::sc_logic(false)); // So that -> STANDBY1 instead of STANDBY2 wait(sc_time(28, SC_US)); sc_assert(test.m_dut.m_radio_state == Nrf24Radio::OpModes::STANDBY1); // ------ TEST: Sending multiple packets // STANDBY1 -> TX_MODE with 3 packets in Tx Fifo spdlog::info("------ TEST: Sending multiple packets"); test.chipSelect.write(sc_dt::sc_logic(false)); // Packet 1 wait(sc_time(1, SC_US)); data = W_TX_PAYLOAD; test.iSpiSocket->b_transport(trans, delay); wait(delay); data = 0xac; test.iSpiSocket->b_transport(trans, delay); wait(delay); test.chipSelect.write(sc_dt::sc_logic(true)); wait(sc_time(1, SC_US)); test.chipSelect.write(sc_dt::sc_logic(false)); // Packet 2 wait(sc_time(1, SC_US)); data = W_TX_PAYLOAD; test.iSpiSocket->b_transport(trans, delay); wait(delay); data = 0xad; test.iSpiSocket->b_transport(trans, delay); wait(delay); test.chipSelect.write(sc_dt::sc_logic(true)); wait(sc_time(1, SC_US)); test.chipSelect.write(sc_dt::sc_logic(false)); // Packet 3 wait(sc_time(1, SC_US)); data = W_TX_PAYLOAD; test.iSpiSocket->b_transport(trans, delay); wait(delay); data = 0xae; test.iSpiSocket->b_transport(trans, delay); wait(delay); data = 0xaf; test.iSpiSocket->b_transport(trans, delay); wait(delay); test.chipSelect.write(sc_dt::sc_logic(true)); wait(sc_time(1, SC_US)); sc_assert(test.m_dut.m_txFifo.isFull()); sc_assert(test.m_dut.m_radio_state == Nrf24Radio::OpModes::STANDBY1); test.chipSelect.write(sc_dt::sc_logic(false)); // Change Address Width wait(sc_time(1, SC_US)); data = W_REGISTER | SETUP_AW; test.iSpiSocket->b_transport(trans, delay); wait(delay); data = AW_0; test.iSpiSocket->b_transport(trans, delay); wait(delay); test.chipSelect.write(sc_dt::sc_logic(true)); wait(sc_time(1, SC_US)); test.chipSelect.write( sc_dt::sc_logic(false)); // Change transmit power & dataRate wait(sc_time(1, SC_US)); data = W_REGISTER | RF_SETUP; test.iSpiSocket->b_transport(trans, delay); wait(delay); data = RF_PWR_0; test.iSpiSocket->b_transport(trans, delay); wait(delay); test.chipSelect.write(sc_dt::sc_logic(true)); wait(sc_time(1, SC_US)); test.chipEnable.write(sc_dt::sc_logic(true)); // Start Transmit wait(sc_time(1, SC_US)); sc_assert(test.m_dut.m_radio_state == Nrf24Radio::OpModes::TX_SETTLING); wait(sc_time(130, SC_US)); sc_assert(test.m_dut.m_radio_state == Nrf24Radio::OpModes::TX_MODE); wait(sc_time(40, SC_US)); sc_assert(test.m_dut.m_radio_state == Nrf24Radio::OpModes::TX_MODE); wait(sc_time(40, SC_US)); sc_assert(test.m_dut.m_radio_state == Nrf24Radio::OpModes::TX_MODE); wait(sc_time(48, SC_US)); sc_assert(test.m_dut.m_radio_state == Nrf24Radio::OpModes::STANDBY2); spdlog::info("{:s}: Testing Done @{:s} ", this->name(), sc_time_stamp().to_string()); sc_stop(); } dut test{"dut"}; }; int sc_main([[maybe_unused]] int argc, [[maybe_unused]] char *argv[]) { // Set up paths // Parse CLI arguments & config file auto &config = Config::get(); config.parseFile(); tester t("tester"); sc_start(); return false; }
29.872651
80
0.668111
fgr1986
0f546baf0ef75979d68c16736c687bbf207055b7
4,819
cpp
C++
logos/lib/utility.cpp
LogosNetwork/logos-core
6b155539a734efefb8f649a761d044b5f267a51a
[ "BSD-2-Clause" ]
3
2020-01-17T18:05:19.000Z
2021-12-29T04:21:59.000Z
logos/lib/utility.cpp
LogosNetwork/logos-core
6b155539a734efefb8f649a761d044b5f267a51a
[ "BSD-2-Clause" ]
null
null
null
logos/lib/utility.cpp
LogosNetwork/logos-core
6b155539a734efefb8f649a761d044b5f267a51a
[ "BSD-2-Clause" ]
2
2020-12-22T05:51:53.000Z
2021-06-08T00:27:46.000Z
#include <logos/lib/utility.hpp> #include <sstream> #include <iomanip> std::string logos::unicode_to_hex(std::string const & input) { static const char* const lut = "0123456789abcdef"; size_t len = input.length(); std::string output; output.reserve(2 * len); for (size_t i = 0; i < len; ++i) { const unsigned char c = input[i]; output.push_back(lut[c >> 4]); output.push_back(lut[c & 15]); } return output; } std::string logos::hex_to_unicode(std::string const & input) { std::string output; assert((input.length() % 2) == 0); size_t cnt = input.length() / 2; output.reserve(cnt); for (size_t i = 0; cnt > i; ++i) { uint32_t s = 0; std::stringstream ss; ss << std::hex << input.substr(i * 2, 2); ss >> s; output.push_back(static_cast<unsigned char>(s)); } return output; } bool logos::read (logos::stream & stream_a, Rational & value) { Rational::int_type n; Rational::int_type d; auto do_read = [&stream_a](auto & val) { for(auto i = 0; i < (256 / 8); ++i) { uint8_t byte; if(read(stream_a, byte)) { return true; } Rational::int_type word = byte; word <<= 8 * i; val |= word; } return false; }; if(do_read(n)) { return true; } if(do_read(d)) { return true; } value.assign(n, d); return false; } uint64_t logos::write (logos::stream & stream_a, const Rational & value) { uint64_t bytes = 0; for(auto val : {value.numerator(), value.denominator()}) { for(auto i = 0; i < (256 / 8); ++i) { auto byte = static_cast<uint8_t> (val & static_cast<uint8_t> (0xff)); val >>= 8; bytes += write(stream_a, byte); } } return bytes; } template<typename U> static bool ReadUnion(logos::stream & stream_a, U & value) { auto amount_read (stream_a.sgetn (value.bytes.data(), value.bytes.size())); return amount_read != value.bytes.size(); } template<typename U> static uint64_t WriteUnion (logos::stream & stream_a, U const & value) { auto amount_written (stream_a.sputn (value.bytes.data(), value.bytes.size())); assert (amount_written == value.bytes.size()); return amount_written; } bool logos::read (logos::stream & stream_a, uint128_union & value) { return ReadUnion(stream_a, value); } uint64_t logos::write (logos::stream & stream_a, uint128_union const & value) { return WriteUnion(stream_a, value); } bool logos::read (logos::stream & stream_a, uint256_union & value) { return ReadUnion(stream_a, value); } uint64_t logos::write (logos::stream & stream_a, uint256_union const & value) { return WriteUnion(stream_a, value); } bool logos::read (logos::stream & stream_a, uint512_union & value) { return ReadUnion(stream_a, value); } uint64_t logos::write (logos::stream & stream_a, uint512_union const & value) { return WriteUnion(stream_a, value); } uint16_t bits_to_bytes_ceiling(uint16_t x) { return (x + 7) / 8; } bool logos::read (logos::stream & stream_a, std::vector<bool> & value) { uint16_t n_bits_le = 0; bool error = logos::read(stream_a, n_bits_le); if(error) { return error; } auto n_bits = le16toh(n_bits_le); auto to_read = bits_to_bytes_ceiling(n_bits); std::vector<uint8_t> bytes(to_read); auto amount_read (stream_a.sgetn (bytes.data(), bytes.size())); if(amount_read != to_read) { return true; } for( auto b : bytes) { //std::cout << (int)b << std::endl; for(int i = 0; i < 8; ++i) { if(n_bits-- == 0) return false; uint8_t mask = 1u<<i; if(mask & b) value.push_back(true); else value.push_back(false); } } return false; } uint64_t logos::write (logos::stream & stream_a, const std::vector<bool> & value) { uint16_t n_bits = value.size(); auto n_bits_le = htole16(n_bits); auto amount_written (stream_a.sputn ((uint8_t *)&n_bits_le, sizeof(uint16_t))); std::vector<uint8_t> buf; uint8_t one_byte = 0; int cmp = 0; for ( auto b : value) { one_byte = one_byte | ((b ? 1 : 0) << cmp++); if(cmp == 8) { //std::cout << (int)one_byte << std::endl; buf.push_back(one_byte); cmp = 0; one_byte = 0; } } if(cmp != 0) { //std::cout << (int)one_byte << std::endl; buf.push_back(one_byte); } amount_written += stream_a.sputn (buf.data(), buf.size()); return amount_written; }
22.624413
83
0.566715
LogosNetwork
0f5609bb787094514d896fc23fcd63072b621e64
654
cpp
C++
Chapter01/ch01_ex06.cpp
PacktPublishing/C-Templates-Up-and-Running
9098d4a538c6a089284900e790488279a06c3a4f
[ "MIT" ]
3
2020-12-27T17:04:19.000Z
2021-11-14T14:33:58.000Z
Chapter01/ch01_ex06.cpp
PacktPublishing/C-Templates-Up-and-Running
9098d4a538c6a089284900e790488279a06c3a4f
[ "MIT" ]
null
null
null
Chapter01/ch01_ex06.cpp
PacktPublishing/C-Templates-Up-and-Running
9098d4a538c6a089284900e790488279a06c3a4f
[ "MIT" ]
null
null
null
// function template + invoke with ints & floats & longs #include <iostream> template<typename T> T get_smaller(T a, T b) { return a < b ? a : b; } int main() { int a{320}; int b{18}; std::cout << "The smaller of " << a << " & " << b << " is " << get_smaller(a, b) << '\n'; float c{8.1}; float d{8.8}; std::cout << "The smaller of " << c << " & " << d << " is " << get_smaller(c, d) << '\n'; long e{INT_MAX - 1}; long f{INT_MAX - 2}; std::cout << "The smaller of " << e << " & " << f << " is " << get_smaller(e, f) << '\n'; }
23.357143
56
0.415902
PacktPublishing
0f594b11e41d1ff1b4a9b416f1e042039c0aae0f
43,232
cc
C++
simplejson_test/srilm-1.7.2/lm/src/WordMesh.cc
rahman-mahmudur/PyART
36591cd10b2b7a560bbcb47a6cf744b72466f92a
[ "Apache-2.0" ]
1
2021-03-08T14:54:00.000Z
2021-03-08T14:54:00.000Z
PyART/srilm-1.7.2/lm/src/WordMesh.cc
PYART0/PyART-demo
9a889662fb2610b7be2687a8304620855e7c76de
[ "Apache-2.0" ]
null
null
null
PyART/srilm-1.7.2/lm/src/WordMesh.cc
PYART0/PyART-demo
9a889662fb2610b7be2687a8304620855e7c76de
[ "Apache-2.0" ]
null
null
null
/* * WordMesh.cc -- * Word Meshes (aka Confusion Networks aka Sausages) */ #ifndef lint static char Copyright[] = "Copyright (c) 1995-2012 SRI International, 2012-2016 Microsoft Corp. All Rights Reserved."; static char RcsId[] = "@(#)$Header: /home/srilm/CVS/srilm/lm/src/WordMesh.cc,v 1.56 2016/04/09 06:53:01 stolcke Exp $"; #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "WordMesh.h" #include "WordAlign.h" #include "TLSWrapper.h" #include "Array.cc" #include "LHash.cc" #include "SArray.cc" // Instantiate template types for external programs linking to the lib INSTANTIATE_LHASH(VocabIndex,NBestWordInfo); typedef struct { double cost; // minimal cost of partial alignment WordAlignType error; // best predecessor } ChartEntryDouble; typedef struct { unsigned cost; // minimal cost of partial alignment WordAlignType error; // best predecessor } ChartEntryUnsigned; /* * Special token used to represent an empty position in an alignment column */ const VocabString deleteWord = "*DELETE*"; template <class CT> void freeChart(CT **chart, unsigned maxRefLength) { for (unsigned i = 0; i <= maxRefLength; i ++) { delete [] chart[i]; } delete [] chart; } WordMesh::WordMesh(Vocab &vocab, const char *myname, VocabDistance *distance) : MultiAlign(vocab, myname), totalPosterior(0.0), numAligns(0), distance(distance) { deleteIndex = vocab.addWord(deleteWord); } WordMesh::~WordMesh() { if (name != 0) { free(name); } for (unsigned i = 0; i < numAligns; i ++) { delete aligns[i]; LHashIter<VocabIndex,NBestWordInfo> infoIter(*wordInfo[i]); NBestWordInfo *winfo; VocabIndex word; while ((winfo = infoIter.next(word))) { winfo->~NBestWordInfo(); } delete wordInfo[i]; LHashIter<VocabIndex,Array<HypID> > mapIter(*hypMap[i]); Array<HypID> *hyps; while ((hyps = mapIter.next(word))) { hyps->~Array(); } delete hypMap[i]; } } Boolean WordMesh::isEmpty() { return numAligns == 0; } /* * alignment set to sort by posterior (parameter to comparePosteriors) */ static TLSW(void*, compareAlignTLS); static int comparePosteriors(VocabIndex w1, VocabIndex w2) { LHash<VocabIndex, Prob>* compareAlign = (LHash<VocabIndex, Prob>*)TLSW_GET(compareAlignTLS); Prob* p1 = compareAlign->find(w1); Prob* p2 = compareAlign->find(w2); if (!p1 || !p2) { // Unexpected error case with no meaningful return value return 0; } Prob diff = *p1 - *p2; if (diff < 0.0) { return 1; } else if (diff > 0.0) { return -1; } else { return 0; } } Boolean WordMesh::write(File &file) { void* &compareAlign = TLSW_GET(compareAlignTLS); if (name != 0) { file.fprintf("name %s\n", name); } file.fprintf("numaligns %u\n", numAligns); file.fprintf("posterior %.*lg\n", Prob_Precision, (double)totalPosterior); for (unsigned i = 0; i < numAligns; i ++) { file.fprintf("align %u", i); compareAlign = aligns[sortedAligns[i]]; LHashIter<VocabIndex,Prob> alignIter(*((LHash<VocabIndex, Prob> *)compareAlign), comparePosteriors); Prob *prob; VocabIndex word; VocabIndex refWord = Vocab_None; while ((prob = alignIter.next(word))) { file.fprintf(" %s %.*lg", vocab.getWord(word), Prob_Precision, *prob); /* * See if this word is the reference one */ Array<HypID> *hypList = hypMap[sortedAligns[i]]->find(word); if (hypList) { for (unsigned j = 0; j < hypList->size(); j++) { if ((*hypList)[j] == refID) { refWord = word; break; } } } } file.fprintf("\n"); /* * Print column and transition posterior sums, * if different from total Posterior */ Prob myPosterior = columnPosteriors[sortedAligns[i]]; if (myPosterior != totalPosterior) { file.fprintf("posterior %u %.*lg\n", i, Prob_Precision, myPosterior); } Prob transPosterior = transPosteriors[sortedAligns[i]]; if (transPosterior != totalPosterior) { file.fprintf("transposterior %u %.*lg\n", i, Prob_Precision, transPosterior); } /* * Print reference word (if known) */ if (refWord != Vocab_None) { file.fprintf("reference %u %s\n", i, vocab.getWord(refWord)); } /* * Dump hyp IDs if known */ LHashIter<VocabIndex,Array<HypID> > mapIter(*hypMap[sortedAligns[i]], comparePosteriors); Array<HypID> *hypList; while ((hypList = mapIter.next(word))) { /* * Only output hyp IDs if they are different from the refID * (to avoid redundancy with "reference" line) */ if (hypList->size() > (unsigned) (word == refWord)) { file.fprintf("hyps %u %s", i, vocab.getWord(word)); for (unsigned j = 0; j < hypList->size(); j++) { if ((*hypList)[j] != refID) { file.fprintf(" %d", (int)(*hypList)[j]); } } file.fprintf("\n"); } } /* * Dump word backtrace info if known */ LHashIter<VocabIndex,NBestWordInfo> infoIter(*wordInfo[sortedAligns[i]], comparePosteriors); NBestWordInfo *winfo; while ((winfo = infoIter.next(word))) { file.fprintf("info %u %s ", i, vocab.getWord(word)); winfo->write(file); file.fprintf("\n"); } } return true; } Boolean WordMesh::read(File &file) { for (unsigned i = 0; i < numAligns; i ++) { delete aligns[i]; } char *line; totalPosterior = 1.0; while ((line = file.getline())) { char arg1[100]; double arg2; int parsed; unsigned index; if (sscanf(line, "numaligns %u", &index) == 1) { if (numAligns > 0) { file.position() << "repeated numaligns specification\n"; return false; } numAligns = index; // @kw false positive: SV.TAINTED.LOOP_BOUND (this->numAligns) for (unsigned i = 0; i < numAligns; i ++) { sortedAligns[i] = i; aligns[i] = new LHash<VocabIndex,Prob>; assert(aligns[i] != 0); wordInfo[i] = new LHash<VocabIndex,NBestWordInfo>; assert(wordInfo[i] != 0); hypMap[i] = new LHash<VocabIndex,Array<HypID> >; assert(hypMap[i] != 0); columnPosteriors[i] = transPosteriors[i] = totalPosterior; } } else if (sscanf(line, "name %100s", arg1) == 1) { if (name != 0) { free(name); } name = strdup(arg1); assert(name != 0); } else if (sscanf(line, "posterior %100s %lg", arg1, &arg2) == 2 && // scan node index with %s so we fail if only one numerical // arg is given (which case handled below) sscanf(arg1, "%u", &index) == 1) { if (index >= numAligns) { file.position() << "position index exceeds numaligns\n"; return false; } columnPosteriors[index] = arg2; } else if (sscanf(line, "transposterior %u %lg", &index, &arg2) == 2) { if (index >= numAligns) { file.position() << "position index exceeds numaligns\n"; return false; } transPosteriors[index] = arg2; } else if (sscanf(line, "posterior %lg", &arg2) == 1) { totalPosterior = arg2; for (unsigned j = 0; j < numAligns; j ++) { columnPosteriors[j] = transPosteriors[j] = arg2; } } else if (sscanf(line, "align %u%n", &index, &parsed) == 1) { if (index >= numAligns) { file.position() << "position index exceeds numaligns\n"; return false; } // @kw false positive: SV.TAINTED.INDEX_ACCESS (parsed) char *cp = line + parsed; while (sscanf(cp, "%100s %lg%n", arg1, &arg2, &parsed) == 2) { VocabIndex word = vocab.addWord(arg1); *aligns[index]->insert(word) = arg2; cp += parsed; } } else if (sscanf(line, "reference %u %100s", &index, arg1) == 2) { if (index >= numAligns) { file.position() << "position index exceeds numaligns\n"; return false; } VocabIndex refWord = vocab.addWord(arg1); /* * Records word as part of the reference string */ Array<HypID> *hypList = hypMap[index]->insert(refWord); (*hypList)[hypList->size()] = refID; } else if (sscanf(line, "hyps %u %100s%n", &index, arg1, &parsed) == 2){ if (index >= numAligns) { file.position() << "position index exceeds numaligns\n"; return false; } VocabIndex word = vocab.addWord(arg1); Array<HypID> *hypList = hypMap[index]->insert(word); /* * Parse and record hyp IDs */ char *cp = line + parsed; unsigned hypID; while (sscanf(cp, "%u%n", &hypID, &parsed) == 1) { (*hypList)[hypList->size()] = hypID; *allHyps.insert(hypID) = hypID; cp += parsed; } } else if (sscanf(line, "info %u %100s%n", &index, arg1, &parsed) == 2){ if (index >= numAligns) { file.position() << "position index exceeds numaligns\n"; return false; } VocabIndex word = vocab.addWord(arg1); NBestWordInfo *winfo = wordInfo[index]->insert(word); winfo->word = word; if (!winfo->parse(line + parsed)) { file.position() << "invalid word info\n"; return false; } } else { file.position() << "unknown keyword\n"; return false; } } return true; } /* * Compute expected error from aligning a word to an alignment column * if column == 0 : compute insertion cost * if word == deleteIndex : compute deletion cost */ double WordMesh::alignError(const LHash<VocabIndex,Prob>* column, Prob columnPosterior, VocabIndex word) { if (column == 0) { /* * Compute insertion cost for word */ if (word == deleteIndex) { return 0.0; } else { if (distance) { return columnPosterior * distance->penalty(word); } else { return columnPosterior; } } } else { if (word == deleteIndex) { /* * Compute deletion cost for alignment column */ if (distance) { double deletePenalty = 0.0; LHashIter<VocabIndex,Prob> iter(*column); Prob *prob; VocabIndex alignWord; while ((prob = iter.next(alignWord))) { if (alignWord != deleteIndex) { deletePenalty += *prob * distance->penalty(alignWord); } } return deletePenalty; } else { Prob *deleteProb = column->find(deleteIndex); return columnPosterior - (deleteProb ? *deleteProb : 0.0); } } else { /* * Compute "substitution" cost of word in column */ if (distance) { /* * Compute distance to existing alignment as a weighted * combination of distances */ double totalDistance = 0.0; LHashIter<VocabIndex,Prob> iter(*column); Prob *prob; VocabIndex alignWord; while ((prob = iter.next(alignWord))) { if (alignWord == deleteIndex) { totalDistance += *prob * distance->penalty(word); } else { totalDistance += *prob * distance->distance(alignWord, word); } } return totalDistance; } else { Prob *wordProb = column->find(word); return columnPosterior - (wordProb ? *wordProb : 0.0); } } } } /* * Compute expected error from aligning two alignment columns * if column1 == 0 : compute insertion cost * if column2 == 0 : compute deletion cost */ double WordMesh::alignError(const LHash<VocabIndex,Prob>* column1, Prob columnPosterior, const LHash<VocabIndex,Prob>* column2, Prob columnPosterior2) { if (column2 == 0) { return alignError(column1, columnPosterior, deleteIndex); } else { /* * compute weighted sum of aligning each of the column2 entries, * using column2 posteriors as weights */ double totalDistance = 0.0; LHashIter<VocabIndex,Prob> iter(*column2); Prob *prob; VocabIndex word2; while ((prob = iter.next(word2))) { double error = alignError(column1, columnPosterior, word2); /* * Handle case where one of the entries has posterior 1, but * others have small nonzero posteriors, too. The small ones * can be ignored in the sum total, and this shortcut makes the * numerical computation symmetric with respect to the case * where posterior 1 occurs in column1 (as well as speeding things * up). */ if (*prob == columnPosterior2) { return *prob * error; } else { totalDistance += *prob * error; } } return totalDistance; } } /* * Align new words to existing alignment columns, expanding them as required * (derived from WordAlign()) * If hypID != 0, then *hypID will record a sentence hyp ID for the * aligned words. */ void WordMesh::alignWords(const VocabIndex *words, Prob score, Prob *wordScores, const HypID *hypID) { unsigned numWords = Vocab::length(words); NBestWordInfo *winfo = new NBestWordInfo[numWords + 1]; assert(winfo != 0); /* * Fill word info array with word IDs and dummy info * Note: loop below also handles the final Vocab_None. */ for (unsigned i = 0; i <= numWords; i ++) { winfo[i].word = words[i]; winfo[i].wordPosterior = 0.0; winfo[i].transPosterior = 0.0; } alignWords(winfo, score, wordScores, hypID); delete [] winfo; } /* * This is the generalized version of alignWords(): * - merges NBestWordInfo into the existing alignment * - aligns word string between any two existing alignment positions * - optionally returns the alignment positions assigned to aligned words * - optionally returns the posterior probabilities of aligned words * Alignment positions are integers corresponding to word equivalence classes. * They are assigned in increasing order; hence numerical order does not * correspond to topological (temporal) order. * * - 'from' specifies the alignment position just BEFORE the first word. * A value of numAligns means the first word should start the alignment. * - 'to' specifies the alignment position just AFTER the last word. * A value of numAligns means the last word should end the alignment. * * Returns false if the 'from' position does not strictly precede the 'to'. */ static TLSW(unsigned, alignWordsMaxHypLengthTLS); static TLSW(unsigned, alignWordsMaxRefLengthTLS); static TLSW(ChartEntryDouble**, alignWordsChartTLS); Boolean WordMesh::alignWords(const NBestWordInfo *winfo, Prob score, Prob *wordScores, const HypID *hypID, unsigned from, unsigned to, unsigned *wordAlignment) { /* * Compute word string length */ unsigned hypLength = 0; for (unsigned i = 0; winfo[i].word != Vocab_None; i ++) hypLength ++; /* * Locate start and end positions to align to */ unsigned fromPos = 0; unsigned refLength = 0; if (numAligns > 0) { unsigned toPos = numAligns - 1; for (unsigned p = 0; p < numAligns; p ++) { if (sortedAligns[p] == from) fromPos = p + 1; if (sortedAligns[p] == to) toPos = p - 1; } refLength = toPos - fromPos + 1; if (toPos + 1 < fromPos) { return false; } } Boolean fullAlignment = (refLength == numAligns); /* * Allocate chart statically, enlarging on demand */ unsigned &maxHypLength = TLSW_GET(alignWordsMaxHypLengthTLS); unsigned &maxRefLength = TLSW_GET(alignWordsMaxRefLengthTLS); ChartEntryDouble** &chart = TLSW_GET(alignWordsChartTLS); if (chart == 0 || hypLength > maxHypLength || refLength > maxRefLength) { /* * Free old chart */ if (chart !=0) freeChart<ChartEntryDouble>(chart, maxRefLength); /* * Allocate new chart */ maxHypLength = hypLength; maxRefLength = refLength; chart = new ChartEntryDouble*[maxRefLength + 1]; assert(chart != 0); for (unsigned i = 0; i <= maxRefLength; i ++) { chart[i] = new ChartEntryDouble[maxHypLength + 1]; assert(chart[i] != 0); } } /* * Initialize the 0'th row */ chart[0][0].cost = 0.0; chart[0][0].error = CORR_ALIGN; for (unsigned j = 1; j <= hypLength; j ++) { chart[0][j].cost = chart[0][j-1].cost + alignError(0, totalPosterior, winfo[j-1].word); chart[0][j].error = INS_ALIGN; } /* * Fill in the rest of the chart, row by row. */ for (unsigned i = 1; i <= refLength; i ++) { double deletePenalty = alignError(aligns[sortedAligns[fromPos+i-1]], columnPosteriors[sortedAligns[fromPos+i-1]], deleteIndex); chart[i][0].cost = chart[i-1][0].cost + deletePenalty; chart[i][0].error = DEL_ALIGN; for (unsigned j = 1; j <= hypLength; j ++) { double minCost = chart[i-1][j-1].cost + alignError(aligns[sortedAligns[fromPos+i-1]], columnPosteriors[sortedAligns[fromPos+i-1]], winfo[j-1].word); WordAlignType minError = SUB_ALIGN; double delCost = chart[i-1][j].cost + deletePenalty; if (delCost + Prob_Epsilon < minCost) { minCost = delCost; minError = DEL_ALIGN; } double insCost = chart[i][j-1].cost + alignError(0, transPosteriors[sortedAligns[fromPos+i-1]], winfo[j-1].word); if (insCost + Prob_Epsilon < minCost) { minCost = insCost; minError = INS_ALIGN; } chart[i][j].cost = minCost; chart[i][j].error = minError; } } /* * Backtrace and add new words to alignment columns. * Store word posteriors if requested. */ { unsigned i = refLength; unsigned j = hypLength; while (i > 0 || j > 0) { Prob wordPosterior = score; Prob transPosterior = score; /* * Use word- and transition-specific posteriors if supplied. * Note: the transition posterior INTO the first word is * given on the Vocab_None item at winfo[hypLength]. */ if (j > 0 && winfo[j-1].wordPosterior != 0.0) { wordPosterior = winfo[j-1].wordPosterior; } if (j > 0 && winfo[j-1].transPosterior != 0.0) { transPosterior = winfo[j-1].transPosterior; } else if (j == 0 && winfo[hypLength].transPosterior != 0.0) { transPosterior = winfo[hypLength].transPosterior; } switch (chart[i][j].error) { case END_ALIGN: assert(0); break; case CORR_ALIGN: case SUB_ALIGN: *aligns[sortedAligns[fromPos+i-1]]->insert(winfo[j-1].word) += wordPosterior; columnPosteriors[sortedAligns[fromPos+i-1]] += wordPosterior; transPosteriors[sortedAligns[fromPos+i-1]] += transPosterior; /* * Check for preexisting word info and merge if necesssary */ if (winfo[j-1].valid()) { Boolean foundP; NBestWordInfo *oldInfo = wordInfo[sortedAligns[fromPos+i-1]]-> insert(winfo[j-1].word, foundP); if (foundP) { oldInfo->merge(winfo[j-1], wordPosterior); } else { *oldInfo = winfo[j-1]; } } if (hypID) { /* * Add hyp ID to the hyp list for this word */ Array<HypID> &hypList = *hypMap[sortedAligns[fromPos+i-1]]->insert(winfo[j-1].word); hypList[hypList.size()] = *hypID; } if (wordAlignment) { wordAlignment[j-1] = sortedAligns[fromPos+i-1]; } if (wordScores) { Prob* p = aligns[sortedAligns[fromPos+i-1]]->find(winfo[j-1].word); // For unexpected NULL error case, use LogP_Zero wordScores[j-1] = p?*p:LogP_Zero; } i --; j --; break; case DEL_ALIGN: *aligns[sortedAligns[fromPos+i-1]]->insert(deleteIndex) += transPosterior; columnPosteriors[sortedAligns[fromPos+i-1]] += transPosterior; transPosteriors[sortedAligns[fromPos+i-1]] += transPosterior; if (hypID) { /* * Add hyp ID to the hyp list for this word */ Array<HypID> &hypList = *hypMap[sortedAligns[fromPos+i-1]]->insert(deleteIndex); hypList[hypList.size()] = *hypID; } i --; break; case INS_ALIGN: /* * Make room for new alignment column in sortedAligns * and position new column */ for (unsigned k = numAligns; k > fromPos + i; k --) { // use an intermediate variable to avoid bug in MVC. unsigned a = sortedAligns[k-1]; sortedAligns[k] = a; } sortedAligns[fromPos + i] = numAligns; aligns[numAligns] = new LHash<VocabIndex,Prob>; assert(aligns[numAligns] != 0); wordInfo[numAligns] = new LHash<VocabIndex,NBestWordInfo>; assert(wordInfo[numAligns] != 0); hypMap[numAligns] = new LHash<VocabIndex,Array<HypID> >; assert(hypMap[numAligns] != 0); /* * The transition posterior from the preceding to the following * position becomes the posterior for *delete* at the new * position (that's why we need transition posteriors!). */ Prob nullPosterior = totalPosterior; if (fromPos+i > 0) { nullPosterior = transPosteriors[sortedAligns[fromPos+i-1]]; } if (nullPosterior != 0.0) { *aligns[numAligns]->insert(deleteIndex) = nullPosterior; } *aligns[numAligns]->insert(winfo[j-1].word) = wordPosterior; columnPosteriors[numAligns] = nullPosterior + wordPosterior; transPosteriors[numAligns] = nullPosterior + transPosterior; /* * Record word info if given */ if (winfo[j-1].valid()) { *wordInfo[numAligns]->insert(winfo[j-1].word) = winfo[j-1]; } /* * Add all hypIDs previously recorded to the *DELETE* * hypothesis at the newly created position. */ { Array<HypID> *hypList = 0; SArrayIter<HypID,HypID> myIter(allHyps); HypID id; while (myIter.next(id)) { /* * Avoid inserting *DELETE* in hypMap unless needed */ if (hypList == 0) { hypList = hypMap[numAligns]->insert(deleteIndex); } (*hypList)[hypList->size()] = id; } } if (hypID) { /* * Add hyp ID to the hyp list for this word */ Array<HypID> &hypList = *hypMap[numAligns]->insert(winfo[j-1].word); hypList[hypList.size()] = *hypID; } if (wordAlignment) { wordAlignment[j-1] = numAligns; } if (wordScores) { wordScores[j-1] = wordPosterior; } numAligns ++; j --; break; } } /* * Add the transition posterior INTO the FIRST hyp word to * to the transition posterior into the first alignment position * This only applies when doing a partial alignment that doesn't * start at the 0th position. */ if (fromPos+i > 0) { Prob transPosterior = score; if (winfo[hypLength].transPosterior != 0.0) { transPosterior = winfo[hypLength].transPosterior; } transPosteriors[sortedAligns[fromPos+i-1]] += transPosterior; } } /* * Add hyp to global list of IDs */ if (hypID) { *allHyps.insert(*hypID) = *hypID; } /* * Only change total posterior if the alignment spanned the whole mesh. * This ensure totalPosterior reflects the initia/final node posterior * in a lattice. */ if (fullAlignment) { totalPosterior += score; } return true; } NBestWordInfo* WordMesh::wordInfoFromUnsortedColumn(unsigned unsortedColumnIndex, VocabIndex word) { if (unsortedColumnIndex >= numAligns) { return NULL; } else { LHash<VocabIndex,NBestWordInfo>* vocabToInfo = wordInfo[unsortedColumnIndex]; return vocabToInfo->find(word); } } Prob WordMesh::wordProbFromUnsortedColumn(unsigned unsortedColumnIndex, VocabIndex word) { if (unsortedColumnIndex < numAligns) { LHash<VocabIndex,Prob>* vocabToProb = aligns[unsortedColumnIndex]; Prob* probability = vocabToProb->find(word); if (probability == NULL) { return 0; } else { return *probability; } } else { return 0; } } static TLSW(unsigned, alignAlignmentMaxHypLengthTLS); static TLSW(unsigned, alignAlignmentMaxRefLengthTLS); static TLSW(ChartEntryDouble**, alignAlignmentChartTLS); void WordMesh::alignAlignment(MultiAlign &alignment, Prob score, Prob *alignScores) { WordMesh &other = (WordMesh &)alignment; unsigned refLength = numAligns; unsigned hypLength = other.numAligns; /* * Allocate chart statically, enlarging on demand */ unsigned &maxHypLength = TLSW_GET(alignAlignmentMaxHypLengthTLS); unsigned &maxRefLength = TLSW_GET(alignAlignmentMaxRefLengthTLS); ChartEntryDouble** &chart = TLSW_GET(alignAlignmentChartTLS); if (chart == 0 || hypLength > maxHypLength || refLength > maxRefLength) { /* * Free old chart */ if (chart !=0) freeChart<ChartEntryDouble>(chart, maxRefLength); /* * Allocate new chart */ maxHypLength = hypLength; maxRefLength = refLength; chart = new ChartEntryDouble*[maxRefLength + 1]; assert(chart != 0); for (unsigned i = 0; i <= maxRefLength; i ++) { chart[i] = new ChartEntryDouble[maxHypLength + 1]; assert(chart[i] != 0); } } /* * Initialize the 0'th row */ chart[0][0].cost = 0.0; chart[0][0].error = CORR_ALIGN; for (unsigned j = 1; j <= hypLength; j ++) { unsigned pos = other.sortedAligns[j-1]; chart[0][j].cost = chart[0][j-1].cost + alignError(0, totalPosterior, other.aligns[other.sortedAligns[j-1]], other.columnPosteriors[other.sortedAligns[j-1]]); chart[0][j].error = INS_ALIGN; } /* * Fill in the rest of the chart, row by row. */ for (unsigned i = 1; i <= refLength; i ++) { double deletePenalty = alignError(aligns[sortedAligns[i-1]], columnPosteriors[sortedAligns[i-1]], deleteIndex); chart[i][0].cost = chart[i-1][0].cost + deletePenalty; chart[i][0].error = DEL_ALIGN; for (unsigned j = 1; j <= hypLength; j ++) { double minCost = chart[i-1][j-1].cost + alignError(aligns[sortedAligns[i-1]], columnPosteriors[sortedAligns[i-1]], other.aligns[other.sortedAligns[j-1]], other.columnPosteriors[other.sortedAligns[j-1]]); WordAlignType minError = SUB_ALIGN; double delCost = chart[i-1][j].cost + deletePenalty; if (delCost + Prob_Epsilon < minCost) { minCost = delCost; minError = DEL_ALIGN; } double insCost = chart[i][j-1].cost + alignError(0, transPosteriors[sortedAligns[i-1]], other.aligns[other.sortedAligns[j-1]], other.columnPosteriors[other.sortedAligns[j-1]]); if (insCost + Prob_Epsilon < minCost) { minCost = insCost; minError = INS_ALIGN; } chart[i][j].cost = minCost; chart[i][j].error = minError; } } /* * Backtrace and add new words to alignment columns. * Store word posteriors if requested. */ { unsigned i = refLength; unsigned j = hypLength; while (i > 0 || j > 0) { switch (chart[i][j].error) { case END_ALIGN: assert(0); break; case CORR_ALIGN: case SUB_ALIGN: /* * merge all words in "other" alignment column into our own */ { double totalScore = 0.0; LHashIter<VocabIndex,Prob> iter(*other.aligns[other.sortedAligns[j-1]]); Prob *otherProb; VocabIndex otherWord; while ((otherProb = iter.next(otherWord))) { totalScore += (*aligns[sortedAligns[i-1]]->insert(otherWord) += score * *otherProb); /* * Check for preexisting word info and merge if * necesssary */ NBestWordInfo *otherInfo = other.wordInfo[other.sortedAligns[j-1]]-> find(otherWord); if (otherInfo) { Boolean foundP; NBestWordInfo *oldInfo = wordInfo[sortedAligns[i-1]]-> insert(otherWord, foundP); if (foundP) { oldInfo->merge(*otherInfo); } else { *oldInfo = *otherInfo; } } Array<HypID> *otherHypList = other.hypMap[other.sortedAligns[j-1]]-> find(otherWord); if (otherHypList) { /* * Add hyp IDs to the hyp list for this word * XXX: hyp IDs should be disjoint but there is no * checking of this! */ Array<HypID> &hypList = *hypMap[sortedAligns[i-1]]-> insert(otherWord); for (unsigned h = 0; h < otherHypList->size(); h ++) { hypList[hypList.size()] = (*otherHypList)[h]; } } } if (alignScores) { alignScores[j-1] = totalScore; } } columnPosteriors[sortedAligns[i-1]] += score * other.columnPosteriors[other.sortedAligns[j-1]]; transPosteriors[sortedAligns[i-1]] += score * other.transPosteriors[other.sortedAligns[j-1]]; i --; j --; break; case DEL_ALIGN: *aligns[sortedAligns[i-1]]->insert(deleteIndex) += score * other.totalPosterior; columnPosteriors[sortedAligns[i-1]] += score * other.totalPosterior; transPosteriors[sortedAligns[i-1]] += score * other.totalPosterior; /* * Add all hyp IDs from "other" alignment to our delete hyp */ if (other.allHyps.numEntries() > 0) { Array<HypID> &hypList = *hypMap[sortedAligns[i-1]]->insert(deleteIndex); SArrayIter<HypID,HypID> otherHypsIter(other.allHyps); HypID id; while (otherHypsIter.next(id)) { hypList[hypList.size()] = id; } } i --; break; case INS_ALIGN: /* * Make room for new alignment column in sortedAligns * and position new column */ for (unsigned k = numAligns; k > i; k --) { // use an intermediate variable to avoid bug in MVC. unsigned a = sortedAligns[k-1]; sortedAligns[k] = a; } sortedAligns[i] = numAligns; aligns[numAligns] = new LHash<VocabIndex,Prob>; assert(aligns[numAligns] != 0); wordInfo[numAligns] = new LHash<VocabIndex,NBestWordInfo>; assert(wordInfo[numAligns] != 0); hypMap[numAligns] = new LHash<VocabIndex,Array<HypID> >; assert(hypMap[numAligns] != 0); /* * The transition posterior from the preceding to the following * position becomes the posterior for *delete* at the new * position (that's why we need transition posteriors!). */ Prob nullPosterior = totalPosterior; if (i > 0) { nullPosterior = transPosteriors[sortedAligns[i-1]]; } if (nullPosterior != 0.0) { *aligns[numAligns]->insert(deleteIndex) = nullPosterior; } columnPosteriors[numAligns] = nullPosterior; transPosteriors[numAligns] = nullPosterior; /* * Add all hypIDs previously recorded to the *DELETE* * hypothesis at the newly created position. */ { Array<HypID> *hypList = 0; SArrayIter<HypID,HypID> myIter(allHyps); HypID id; while (myIter.next(id)) { /* * Avoid inserting *DELETE* in hypMap unless needed */ if (hypList == 0) { hypList = hypMap[numAligns]->insert(deleteIndex); } (*hypList)[hypList->size()] = id; } } /* * insert all words in "other" alignment at current position */ { LHashIter<VocabIndex,Prob> iter(*other.aligns[other.sortedAligns[j-1]]); Prob *otherProb; VocabIndex otherWord; while ((otherProb = iter.next(otherWord))) { *aligns[numAligns]->insert(otherWord) += score * *otherProb; /* * Record word info if given */ NBestWordInfo *otherInfo = other.wordInfo[other.sortedAligns[j-1]]-> find(otherWord); if (otherInfo) { *wordInfo[numAligns]->insert(otherWord) = *otherInfo; } Array<HypID> *otherHypList = other.hypMap[other.sortedAligns[j-1]]-> find(otherWord); if (otherHypList) { /* * Add hyp IDs to the hyp list for this word */ Array<HypID> &hypList = *hypMap[numAligns]->insert(otherWord); for (unsigned h = 0; h < otherHypList->size(); h ++) { hypList[hypList.size()] = (*otherHypList)[h]; } } } if (alignScores) { alignScores[j-1] = score; } } columnPosteriors[numAligns] += score * other.columnPosteriors[other.sortedAligns[j-1]]; transPosteriors[numAligns] += score * other.transPosteriors[other.sortedAligns[j-1]]; numAligns ++; j --; break; } } } /* * Add hyps from "other" alignment to global list of our IDs */ SArrayIter<HypID,HypID> otherHypsIter(other.allHyps); HypID id; while (otherHypsIter.next(id)) { *allHyps.insert(id) = id; } totalPosterior += score * other.totalPosterior; } /* * Incremental partial alignments using alignWords() can leave the * posteriors of null entries defective (because not all transition posteriors * were added to the alignment). * This function normalized the null posteriors so that the total column * posteriors sum to the totalPosterior. */ void WordMesh::normalizeDeletes() { for (unsigned i = 0; i < numAligns; i ++) { LHashIter<VocabIndex,Prob> alignIter(*aligns[i]); Prob wordPosteriorSum = 0.0; Prob *prob; VocabIndex word; while ((prob = alignIter.next(word))) { if (word != deleteIndex) { wordPosteriorSum += *prob; } } Prob deletePosterior; if (wordPosteriorSum - totalPosterior > Prob_Epsilon) { cerr << "WordMesh::normalizeDeletes: word posteriors exceed total: " << wordPosteriorSum << endl; deletePosterior = 0.0; } else { deletePosterior = totalPosterior - wordPosteriorSum; } /* * Delete null tokens with zero posterior. * Insert nulls that should be there based on missing posterior mass. * Avoid deleting nulls with small positive posterior that were * already present in the alignment. */ if (deletePosterior <= 0.0) { aligns[i]->remove(deleteIndex); } else if (deletePosterior > Prob_Epsilon) { *aligns[i]->insert(deleteIndex) = deletePosterior; } columnPosteriors[i] = totalPosterior; transPosteriors[i] = totalPosterior; } } /* * Compute minimal word error with respect to existing alignment columns * (derived from WordAlign()) */ static TLSW(unsigned, wordErrorMaxHypLengthTLS); static TLSW(unsigned, wordErrorMaxRefLengthTLS); static TLSW(ChartEntryUnsigned **, wordErrorChartTLS); unsigned WordMesh::wordError(const VocabIndex *words, unsigned &sub, unsigned &ins, unsigned &del) { unsigned hypLength = Vocab::length(words); unsigned refLength = numAligns; /* * Allocate chart statically, enlarging on demand */ unsigned &maxHypLength = TLSW_GET(wordErrorMaxHypLengthTLS); unsigned &maxRefLength = TLSW_GET(wordErrorMaxRefLengthTLS); ChartEntryUnsigned** &chart = TLSW_GET(wordErrorChartTLS); if (chart == 0 || hypLength > maxHypLength || refLength > maxRefLength) { /* * Free old chart */ if (chart != 0) freeChart<ChartEntryUnsigned>(chart, maxRefLength); /* * Allocate new chart */ maxHypLength = hypLength; maxRefLength = refLength; chart = new ChartEntryUnsigned*[maxRefLength + 1]; assert(chart != 0); for (unsigned i = 0; i <= maxRefLength; i ++) { chart[i] = new ChartEntryUnsigned[maxHypLength + 1]; assert(chart[i] != 0); } /* * Initialize the 0'th row, which never changes */ chart[0][0].cost = 0; chart[0][0].error = CORR_ALIGN; for (unsigned j = 1; j <= maxHypLength; j ++) { chart[0][j].cost = chart[0][j-1].cost + INS_COST; chart[0][j].error = INS_ALIGN; } } /* * Fill in the rest of the chart, row by row. */ for (unsigned i = 1; i <= refLength; i ++) { /* * deletion error only if alignment column doesn't have *DELETE* */ Prob *delProb = aligns[sortedAligns[i-1]]->find(deleteIndex); unsigned THIS_DEL_COST = delProb && *delProb > 0.0 ? 0 : DEL_COST; chart[i][0].cost = chart[i-1][0].cost + THIS_DEL_COST; chart[i][0].error = DEL_ALIGN; for (unsigned j = 1; j <= hypLength; j ++) { unsigned minCost; WordAlignType minError; if (aligns[sortedAligns[i-1]]->find(words[j-1])) { minCost = chart[i-1][j-1].cost; minError = CORR_ALIGN; } else { minCost = chart[i-1][j-1].cost + SUB_COST; minError = SUB_ALIGN; } unsigned delCost = chart[i-1][j].cost + THIS_DEL_COST; if (delCost < minCost) { minCost = delCost; minError = DEL_ALIGN; } unsigned insCost = chart[i][j-1].cost + INS_COST; if (insCost < minCost) { minCost = insCost; minError = INS_ALIGN; } chart[i][j].cost = minCost; chart[i][j].error = minError; } } /* * Backtrace and add new words to alignment columns */ { unsigned i = refLength; unsigned j = hypLength; sub = ins = del = 0; while (i > 0 || j > 0) { switch (chart[i][j].error) { case END_ALIGN: assert(0); break; case CORR_ALIGN: i --; j--; break; case SUB_ALIGN: sub ++; i --; j --; break; case DEL_ALIGN: /* * deletion error only if alignment column doesn't * have *DELETE* */ { Prob *delProb = aligns[sortedAligns[i-1]]->find(deleteIndex); if (!delProb || *delProb == 0.0) { del ++; } } i --; break; case INS_ALIGN: ins ++; j --; break; } } } return sub + ins + del; } double WordMesh::minimizeWordError(VocabIndex *words, unsigned length, double &sub, double &ins, double &del, unsigned flags, double delBias) { NBestWordInfo *winfo = new NBestWordInfo[length]; assert(winfo != 0); double result = minimizeWordError(winfo, length, sub, ins, del, flags, delBias); for (unsigned i = 0; i < length; i ++) { words[i] = winfo[i].word; if (words[i] == Vocab_None) break; } delete [] winfo; return result; } double WordMesh::minimizeWordError(NBestWordInfo *winfo, unsigned length, double &sub, double &ins, double &del, unsigned flags, double delBias) { unsigned numWords = 0; sub = ins = del = 0.0; for (unsigned i = 0; i < numAligns; i ++) { LHashIter<VocabIndex,Prob> alignIter(*aligns[sortedAligns[i]]); Prob deleteProb = 0.0; Prob bestProb = 0.0; VocabIndex bestWord = Vocab_None; Prob *prob; VocabIndex word; while ((prob = alignIter.next(word))) { Prob effectiveProb = *prob; // prob adjusted for deletion bias if (word == deleteIndex) { effectiveProb *= delBias; deleteProb = effectiveProb; } if (bestWord == Vocab_None || effectiveProb > bestProb) { bestWord = word; bestProb = effectiveProb; } } if (bestWord != deleteIndex) { if (numWords < length) { NBestWordInfo *thisInfo = wordInfo[sortedAligns[i]]->find(bestWord); if (thisInfo) { winfo[numWords] = *thisInfo; } else { winfo[numWords].word = bestWord; winfo[numWords].invalidate(); } /* * Always return the word posterior into the NBestWordInfo */ winfo[numWords].wordPosterior = bestProb; winfo[numWords].transPosterior = bestProb; numWords += 1; } ins += deleteProb; sub += totalPosterior - deleteProb - bestProb; } else { del += totalPosterior - deleteProb; } } if (numWords < length) { winfo[numWords].word = Vocab_None;; winfo[numWords].invalidate(); } return sub + ins + del; } /* * Return confusion set for a given position */ LHash<VocabIndex,Prob> * WordMesh::wordColumn(unsigned columnNumber) { if (columnNumber < numAligns) { return aligns[sortedAligns[columnNumber]]; } else { return 0; } } /* * Return word info set for a given position */ LHash<VocabIndex,NBestWordInfo> * WordMesh::wordinfoColumn(unsigned columnNumber) { if (columnNumber < numAligns) { return wordInfo[sortedAligns[columnNumber]]; } else { return 0; } } void WordMesh::freeThread() { ChartEntryDouble** &chart1 = TLSW_GET(alignWordsChartTLS); ChartEntryDouble** &chart2 = TLSW_GET(alignAlignmentChartTLS); ChartEntryUnsigned** &chart3 = TLSW_GET(wordErrorChartTLS); unsigned &len1 = TLSW_GET(alignWordsMaxRefLengthTLS); unsigned &len2 = TLSW_GET(alignAlignmentMaxRefLengthTLS); unsigned &len3 = TLSW_GET(wordErrorMaxRefLengthTLS); if (chart1 != 0) freeChart<ChartEntryDouble>(chart1, len1); if (chart2 != 0) freeChart<ChartEntryDouble>(chart2, len2); if (chart3 != 0) freeChart<ChartEntryUnsigned>(chart3, len3); TLSW_FREE(compareAlignTLS); TLSW_FREE(alignWordsMaxHypLengthTLS); TLSW_FREE(alignWordsMaxRefLengthTLS); TLSW_FREE(alignWordsChartTLS); TLSW_FREE(alignAlignmentMaxHypLengthTLS); TLSW_FREE(alignAlignmentMaxRefLengthTLS); TLSW_FREE(alignAlignmentChartTLS); TLSW_FREE(wordErrorMaxHypLengthTLS); TLSW_FREE(wordErrorMaxRefLengthTLS); TLSW_FREE(wordErrorChartTLS); } void WordMesh::alignAlignment(MultiAlign &other_alignment, vector<int>& src2other_col_map) { WordMesh &other = (WordMesh &)other_alignment; unsigned refLength = this->numAligns; unsigned hypLength = other.numAligns; typedef struct { double cost; // minimal cost of partial alignment WordAlignType error; // best predecessor } ChartEntry; /* * Allocate chart statically, enlarging on demand */ static unsigned maxHypLength = 0; static unsigned maxRefLength = 0; static ChartEntry **chart = 0; if (chart == 0 || hypLength > maxHypLength || refLength > maxRefLength) { /* * Free old chart */ if (chart != 0) { for (unsigned i = 0; i <= maxRefLength; i ++) { delete [] chart[i]; } delete [] chart; } /* * Allocate new chart */ maxHypLength = hypLength; maxRefLength = refLength; chart = new ChartEntry*[maxRefLength + 1]; assert(chart != 0); for (unsigned i = 0; i <= maxRefLength; i ++) { chart[i] = new ChartEntry[maxHypLength + 1]; assert(chart[i] != 0); } } /* * Initialize the 0'th row */ chart[0][0].cost = 0.0; chart[0][0].error = CORR_ALIGN; for (unsigned j = 1; j <= hypLength; j ++) { unsigned pos = other.sortedAligns[j-1]; chart[0][j].cost = chart[0][j-1].cost + this->alignError(0, this->totalPosterior, other.aligns[pos], other.columnPosteriors[pos]); chart[0][j].error = INS_ALIGN; } /* * Fill in the rest of the chart, row by row. */ for (unsigned i = 1; i <= refLength; i ++) { unsigned main_pos = this->sortedAligns[i-1]; double deletePenalty = this->alignError(this->aligns[main_pos], this->columnPosteriors[main_pos], this->deleteIndex); chart[i][0].cost = chart[i-1][0].cost + deletePenalty; chart[i][0].error = DEL_ALIGN; for (unsigned j = 1; j <= hypLength; j ++) { unsigned other_pos = other.sortedAligns[j-1]; // TODO: save local errors (substitution error) double minCost = chart[i-1][j-1].cost + this->alignError(this->aligns[main_pos], this->columnPosteriors[main_pos], other.aligns[other_pos], other.columnPosteriors[other_pos]); WordAlignType minError = SUB_ALIGN; double delCost = chart[i-1][j].cost + deletePenalty; if (delCost < minCost) { minCost = delCost; minError = DEL_ALIGN; } double insCost = chart[i][j-1].cost + this->alignError(0, this->transPosteriors[main_pos], other.aligns[other_pos], other.columnPosteriors[other_pos]); if (insCost < minCost) { minCost = insCost; minError = INS_ALIGN; } chart[i][j].cost = minCost; chart[i][j].error = minError; } } /* * Backtrace and add new words to alignment columns. * Store word posteriors if requested. */ { unsigned i = refLength; unsigned j = hypLength; src2other_col_map.resize(i, -1); while (i > 0 || j > 0) { switch (chart[i][j].error) { case END_ALIGN: assert(0); break; case CORR_ALIGN: case SUB_ALIGN: /* * merge all words in "other" alignment column into our own */ { // x.sortedAligns[] maps to the actual col in the sausage src2other_col_map[i-1] = j-1; i --; j --; } break; case DEL_ALIGN: i --; break; case INS_ALIGN: j --; break; } } } }
25.581065
119
0.630413
rahman-mahmudur
0f5a027569fc7b1c7542d632313e827cdccdebae
1,230
cpp
C++
src/BaseApplication.cpp
DavidAzouz29/AIENetworking
0ea9eb45cc56f5dc0e4f07bc09a75ef677a4563e
[ "MIT" ]
null
null
null
src/BaseApplication.cpp
DavidAzouz29/AIENetworking
0ea9eb45cc56f5dc0e4f07bc09a75ef677a4563e
[ "MIT" ]
null
null
null
src/BaseApplication.cpp
DavidAzouz29/AIENetworking
0ea9eb45cc56f5dc0e4f07bc09a75ef677a4563e
[ "MIT" ]
null
null
null
#include "BaseApplication.h" //#include "gl_core_4_4.h" #include <iostream> #include <GLFW/glfw3.h> #include <glm/glm.hpp> bool BaseApplication::createWindow(const char* title, int width, int height) { if (glfwInit() == GL_FALSE) return false; m_window = glfwCreateWindow(width, height, title, nullptr, nullptr); if (m_window == nullptr) { glfwTerminate(); return false; } glfwMakeContextCurrent(m_window); if (ogl_LoadFunctions() == ogl_LOAD_FAILED) { glfwDestroyWindow(m_window); glfwTerminate(); return false; } glfwSetWindowSizeCallback(m_window, [](GLFWwindow*, int w, int h){ glViewport(0, 0, w, h); }); auto major = ogl_GetMajorVersion(); auto minor = ogl_GetMinorVersion(); std::cout << "GL: " << major << "." << minor << std::endl; glClearColor(0.25f, 0.25f, 0.25f, 1); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); return true; } GLvoid BaseApplication::destroyWindow() { glfwDestroyWindow(m_window); glfwTerminate(); } GLvoid BaseApplication::run() { double prevTime = glfwGetTime(); double currTime = 0; while (currTime = glfwGetTime(), update((float)(currTime - prevTime))) { glfwPollEvents(); draw(); glfwSwapBuffers(m_window); prevTime = currTime; } }
20.5
95
0.695935
DavidAzouz29
0f5af1202f29c98b17f23e9bb3ea911767f7f38c
699
cpp
C++
solution/day2/part2.cpp
Desheen/AdventOfCode-2018
4d633f51ba5f906c365bb8ef2512465dea941d24
[ "BSD-3-Clause" ]
1
2018-12-02T20:17:59.000Z
2018-12-02T20:17:59.000Z
solution/day2/part2.cpp
Desheen/AdventOfCode-2018
4d633f51ba5f906c365bb8ef2512465dea941d24
[ "BSD-3-Clause" ]
null
null
null
solution/day2/part2.cpp
Desheen/AdventOfCode-2018
4d633f51ba5f906c365bb8ef2512465dea941d24
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <fstream> #include <algorithm> #include <map> #include <vector> #include <unordered_map> std::vector<short> match( std::string& s1 , std::string& s2) { std::vector<short> v; for( int i = 0 ; i < s1.size() ; ++i) { if( s1[i] != s2[i] ) { v.push_back(i); } } return v; } int main( int argc , char**argv ) { std::ifstream file; file.open("input",std::ifstream::in); std::string line; std::vector<std::string> data; while(std::getline(file,line)) { data.push_back(line); } for( auto itr1 : data ) { for( auto itr2 : data) { auto c = match(itr1,itr2); if( c.size() == 1 ) { std::cout << itr1 << std::endl; } } } return 0; }
15.533333
62
0.579399
Desheen
0f5bbc6f005e19c3f346f7ff5efbb10b1b0a8a6b
3,401
cc
C++
mindspore/lite/test/ut/src/runtime/kernel/arm/fp32/space_to_depth_fp32_tests.cc
HappyKL/mindspore
479cb89e8b5c9d859130891567038bb849a30bce
[ "Apache-2.0" ]
1
2020-10-18T12:27:45.000Z
2020-10-18T12:27:45.000Z
mindspore/lite/test/ut/src/runtime/kernel/arm/fp32/space_to_depth_fp32_tests.cc
ReIadnSan/mindspore
c3d1f54c7f6d6f514e5748430d24b16a4f9ee9e5
[ "Apache-2.0" ]
null
null
null
mindspore/lite/test/ut/src/runtime/kernel/arm/fp32/space_to_depth_fp32_tests.cc
ReIadnSan/mindspore
c3d1f54c7f6d6f514e5748430d24b16a4f9ee9e5
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <vector> #include <iostream> #include <memory> #include "src/common/log_adapter.h" #include "common/common_test.h" #include "mindspore/lite/nnacl/fp32/space_to_depth.h" #include "mindspore/lite/src/kernel_registry.h" #include "mindspore/lite/src/lite_kernel.h" namespace mindspore { class SpaceToDepthTestFp32 : public mindspore::CommonTest { public: SpaceToDepthTestFp32() {} }; TEST_F(SpaceToDepthTestFp32, SpaceToDepthTest1) { float input[16] = {1, 2, 5, 6, 10, 20, 3, 8, 18, 10, 3, 4, 11, 55, 15, 25}; const int out_size = 16; float expect_out[16] = {1, 2, 10, 20, 5, 6, 3, 8, 18, 10, 11, 55, 3, 4, 15, 25}; float output[16]; int in_shape[4] = {1, 4, 4, 1}; int out_shape[4] = {1, 2, 2, 4}; int h_start = 0; int h_end = 2; SpaceToDepthForNHWC((const float *)input, output, in_shape, out_shape, 4, 2, h_start, h_end); for (int i = 0; i < out_size; ++i) { std::cout << output[i] << " "; } std::cout << "\n"; CompareOutputData(output, expect_out, out_size, 0.000001); } TEST_F(SpaceToDepthTestFp32, SpaceToDepthTest2) { std::vector<float> input = {1, 2, 5, 6, 10, 20, 3, 8, 18, 10, 3, 4, 11, 55, 15, 25}; std::vector<int> in_shape = {1, 4, 4, 1}; lite::Tensor input_tensor; input_tensor.SetData(input.data()); input_tensor.set_shape(in_shape); input_tensor.SetFormat(schema::Format_NHWC); input_tensor.set_data_type(kNumberTypeFloat32); std::vector<lite::Tensor *> inputs_tensor; inputs_tensor.push_back(&input_tensor); const int out_size = 16; float expect_out[16] = {1, 2, 10, 20, 5, 6, 3, 8, 18, 10, 11, 55, 3, 4, 15, 25}; std::vector<float> output(16); std::vector<int> out_shape = {1, 2, 2, 4}; lite::Tensor output_tensor; output_tensor.SetData(output.data()); output_tensor.set_shape(out_shape); output_tensor.SetFormat(schema::Format_NHWC); output_tensor.set_data_type(kNumberTypeFloat32); std::vector<lite::Tensor *> outputs_tensor; outputs_tensor.push_back(&output_tensor); SpaceToDepthParameter op_param; op_param.op_parameter_.type_ = schema::PrimitiveType_SpaceToDepth; op_param.block_size_ = 2; lite::InnerContext ctx; ctx.thread_num_ = 3; ASSERT_EQ(lite::RET_OK, ctx.Init()); kernel::KernelKey desc = {kernel::KERNEL_ARCH::kCPU, kNumberTypeFloat32, schema::PrimitiveType_SpaceToDepth}; auto creator = lite::KernelRegistry::GetInstance()->GetCreator(desc); ASSERT_NE(creator, nullptr); kernel::LiteKernel *kernel = creator(inputs_tensor, outputs_tensor, reinterpret_cast<OpParameter *>(&op_param), &ctx, desc, nullptr); ASSERT_NE(kernel, nullptr); kernel->Run(); for (int i = 0; i < out_size; ++i) { std::cout << output[i] << " "; } std::cout << "\n"; CompareOutputData(output.data(), expect_out, out_size, 0.000001); } } // namespace mindspore
35.427083
111
0.6995
HappyKL
0f5caf09f8419ea3775cab5bf8351199d9dde597
218
cpp
C++
src/luogu/CF697A/11845974_ua_undefined_15ms_0k_noO2.cpp
lnkkerst/oj-codes
d778489182d644370b2a690aa92c3df6542cc306
[ "MIT" ]
null
null
null
src/luogu/CF697A/11845974_ua_undefined_15ms_0k_noO2.cpp
lnkkerst/oj-codes
d778489182d644370b2a690aa92c3df6542cc306
[ "MIT" ]
null
null
null
src/luogu/CF697A/11845974_ua_undefined_15ms_0k_noO2.cpp
lnkkerst/oj-codes
d778489182d644370b2a690aa92c3df6542cc306
[ "MIT" ]
null
null
null
#include <cstdio> int main() { int t, s, x; scanf("%d%d%d", &t, &s, &x); while(1) { if(t == x || t + 1 == x) { printf("YES"); return 0; } t += s; if (t > x) break; } printf ("NO"); return 0; }
12.823529
29
0.422018
lnkkerst
0f5dd9d7e3504cf34006c04dd41e55bd4660698e
9,291
cpp
C++
game/debug/log.cpp
edwinkepler/chessman
f9ffb902ce91c15726b8716665707d178ac734e1
[ "MIT" ]
null
null
null
game/debug/log.cpp
edwinkepler/chessman
f9ffb902ce91c15726b8716665707d178ac734e1
[ "MIT" ]
14
2017-08-28T15:37:20.000Z
2017-09-20T09:15:43.000Z
game/debug/log.cpp
edwinkepler/chessman
f9ffb902ce91c15726b8716665707d178ac734e1
[ "MIT" ]
null
null
null
#include "log.hpp" namespace Debug { Log& Log::info(string _s) { if(f_verbose_stdout) { cout << _s; } if(f_verbose_file) { ofstream file_log; file_log.open( s_file_name, ios::binary | ios_base::app | ios_base::out); file_log << _s; file_log.close(); } return *this; } Log& Log::info(int _i) { if(f_verbose_stdout) { cout << _i; } if(f_verbose_file) { ofstream file_log; file_log.open( s_file_name, ios::binary | ios_base::app | ios_base::out); file_log << _i; file_log.close(); } return *this; } Log& Log::n() { if(f_verbose_stdout) { cout << endl; } if(f_verbose_file) { ofstream file_log; file_log.open( s_file_name, ios::binary | ios_base::app | ios_base::out); file_log << "\n"; file_log.close(); } return *this; } Log& Log::t() { if(f_verbose_stdout) { cout << "\t"; } if(f_verbose_file) { ofstream file_log; file_log.open( s_file_name, ios::binary | ios_base::app | ios_base::out); file_log << "\t"; file_log.close(); } return *this; } Log& Log::t2() { if(f_verbose_stdout) { cout << "\t\t"; } if(f_verbose_file) { ofstream file_log; file_log.open( s_file_name, ios::binary | ios_base::app | ios_base::out); file_log << "\t\t"; file_log.close(); } return *this; } Log& Log::l(int _l) { if(f_verbose_stdout) { cout << "[" << _l << "] "; } if(f_verbose_file) { ofstream file_log; file_log.open( s_file_name, ios::binary | ios_base::app | ios_base::out); file_log << "[" << _l << "] "; file_log.close(); } return *this; } Log& Log::func_head(string _f) { if(f_verbose_stdout) { cout << "[" << _f << "][START]\n"; } if(f_verbose_file) { ofstream file_log; file_log.open( s_file_name, ios::binary | ios_base::app | ios_base::out); file_log << "[" << _f << "][START]\n"; file_log.close(); } return *this; } Log& Log::func_foot(string _f) { if(f_verbose_stdout) { cout << "[" << _f << "][DONE]\n"; } if(f_verbose_file) { ofstream file_log; file_log.open( s_file_name, ios::binary | ios_base::app | ios_base::out); file_log << "[" << _f << "][DONE]\n"; file_log.close(); } return *this; } Log& Log::func_foot(string _f, int _n) { if(f_verbose_stdout) { cout << "[" << _f << "][DONE in " << _n << "ms]\n"; } if(f_verbose_file) { ofstream file_log; file_log.open( s_file_name, ios::binary | ios_base::app | ios_base::out); file_log << "[" << _f << "][DONE in " << _n << "ms]\n"; file_log.close(); } return *this; } Log& Log::piece_func_head(string _f, int _t, int _o, const pair<int, int>& _c) { if(f_verbose_stdout) { cout << "\t\t[" << _f << "][type: " << _t << ", owner: " << _o << ", at: (" << _c.first << ", " << _c.second << ")]\n"; } if(f_verbose_file) { ofstream file_log; file_log.open( s_file_name, ios::binary | ios_base::app | ios_base::out); file_log << "\t\t[" << _f << "][type: " << _t << ", owner: " << _o << ", at: (" << _c.first << ", " << _c.second << ")]\n"; file_log.close(); } return *this; } Log& Log::board_func_head(string _f, const pair<int, int>& _c) { if(f_verbose_stdout) { cout << "\t\t[" << _f << "][coords: (" << _c.first << ", " << _c.second << ")]\n"; } if(f_verbose_file) { ofstream file_log; file_log.open( s_file_name, ios::binary | ios_base::app | ios_base::out); file_log << "\t\t[" << _f << "][coords: (" << _c.first << ", " << _c.second << ")]\n"; file_log.close(); } return *this; } Log& Log::board_func_head(string _f, const pair<int, int>& _c1, const pair<int, int>& _c2) { if(f_verbose_stdout) { cout << "\t\t[" << _f << "][from: (" << _c1.first << ", " << _c1.second << "), to: (" << _c2.first << ", " << _c2.second << ")]\n"; } if(f_verbose_file) { ofstream file_log; file_log.open( s_file_name, ios::binary | ios_base::app | ios_base::out); file_log << "\t\t[" << _f << "][from: (" << _c1.first << ", " << _c1.second << "), to: (" << _c2.first << ", " << _c2.second << ")]\n"; file_log.close(); } return *this; } void Log::test_func_head(const string _t) { if(f_verbose_stdout) { cout << "<--------- " << _t << " BEGIN ----------\n"; } if(f_verbose_file) { ofstream file_log; file_log.open( s_file_name, ios::binary | ios_base::app | ios_base::out); file_log << "<--------- " << _t << " BEGIN ----------\n"; file_log.close(); } } void Log::test_func_foot(const string _t) { if(f_verbose_stdout) { cout << "---------- " << _t << " END ----------->\n\n"; } if(f_verbose_file) { ofstream file_log; file_log.open( s_file_name, ios::binary | ios_base::app | ios_base::out); file_log << "---------- " << _t << " END ----------->\n\n"; file_log.close(); } } Log& Log::datetime_stamp() { if(f_verbose_stdout) { auto t = time(nullptr); auto tm = *localtime(&t); cout << "[" << put_time(&tm, "%d-%m-%Y %H:%M:%S") << "]"; } if(f_verbose_file) { auto t = time(nullptr); auto tm = *localtime(&t); ofstream file_log; file_log.open( s_file_name, ios::binary | ios_base::app | ios_base::out); file_log << "[" << put_time(&tm, "%d-%m-%Y %H:%M:%S") << "]"; file_log.close(); } return *this; } Log& Log::coords(const pair<int, int>& _c) { if(f_verbose_stdout) { cout << "coords: (" << _c.first << ", " << _c.second << ")"; } if(f_verbose_file) { ofstream file_log; file_log.open( s_file_name, ios::binary | ios_base::app | ios_base::out); file_log << "coords: (" << _c.first << ", " << _c.second << ")"; file_log.close(); } return *this; } Log& Log::coords(const pair<int, int>& _c1, const pair<int, int>& _c2) { if(f_verbose_stdout) { cout << "coords: (" << _c1.first << ", " << _c1.second << "), (" << _c2.first << ", " << _c2.second << ")"; } if(f_verbose_file) { ofstream file_log; file_log.open( s_file_name, ios::binary | ios_base::app | ios_base::out); file_log << "coords: (" << _c1.first << ", " << _c1.second << "), (" << _c2.first << ", " << _c2.second << ")"; file_log.close(); } return *this; } Log& Log::operator<<(string s) { info(s); return *this; } Log& Log::operator<<(int i) { info(i); return *this; } void Log::verbose_stdout(bool _f) { f_verbose_stdout = _f; } void Log::verbose_file(bool _f) { f_verbose_file = _f; } }
28.069486
84
0.380691
edwinkepler
0f5df5702f12e11af32a42059a08eeb7c17422c3
178
cpp
C++
5e/C++11/098.cpp
mallius/CppPrimer
0285fabe5934492dfed0a9cf67ba5650982a5f76
[ "MIT" ]
null
null
null
5e/C++11/098.cpp
mallius/CppPrimer
0285fabe5934492dfed0a9cf67ba5650982a5f76
[ "MIT" ]
null
null
null
5e/C++11/098.cpp
mallius/CppPrimer
0285fabe5934492dfed0a9cf67ba5650982a5f76
[ "MIT" ]
1
2022-01-25T15:51:34.000Z
2022-01-25T15:51:34.000Z
#include <iostream> #include <vector> using namespace std; int main(void) { vector<int> v; const vector<int> cv; auto it = v.cbegin(); auto it2 = cv.cbegin(); return 0; }
13.692308
24
0.657303
mallius
0f630b337452435d718cd2626aa782ff86420858
2,892
cpp
C++
sources/Engine/Modules/Graphics/GUI/GUIProgressBar.cpp
n-paukov/swengine
ca7441f238e8834efff5d2b61b079627824bf3e4
[ "MIT" ]
22
2017-07-26T17:42:56.000Z
2022-03-21T22:12:52.000Z
sources/Engine/Modules/Graphics/GUI/GUIProgressBar.cpp
n-paukov/swengine
ca7441f238e8834efff5d2b61b079627824bf3e4
[ "MIT" ]
50
2017-08-02T19:37:48.000Z
2020-07-24T21:10:38.000Z
sources/Engine/Modules/Graphics/GUI/GUIProgressBar.cpp
n-paukov/swengine
ca7441f238e8834efff5d2b61b079627824bf3e4
[ "MIT" ]
4
2018-08-20T08:12:48.000Z
2020-07-19T14:10:05.000Z
#include "precompiled.h" #pragma hdrstop #include "GUIProgressBar.h" #include "GUISystem.h" GUIProgressBar::GUIProgressBar() : GUIWidgetRect("progress_bar"), m_scaleBox(std::make_unique<GUIWidgetRect>("scale")) { } void GUIProgressBar::applyStylesheetRule(const GUIWidgetStylesheetRule& stylesheetRule) { GUIWidgetRect::applyStylesheetRule(stylesheetRule); stylesheetRule.visit([this](auto propertyName, auto property, GUIWidgetVisualState visualState) { if (propertyName == "border-padding") { SW_ASSERT(std::holds_alternative<glm::ivec2>(property.getValue())); SW_ASSERT(visualState == GUIWidgetVisualState::Default && "Border padding is supported only for default state"); this->setBorderPadding(std::get<glm::ivec2>(property.getValue())); } else if (propertyName == "max-value") { SW_ASSERT(std::holds_alternative<int>(property.getValue())); SW_ASSERT(visualState == GUIWidgetVisualState::Default && "Max value is supported only for default state"); this->setMaxValue(std::get<int>(property.getValue())); } else if (propertyName == "value") { SW_ASSERT(std::holds_alternative<int>(property.getValue())); SW_ASSERT(visualState == GUIWidgetVisualState::Default && "Value is supported only for default state"); this->setValue(std::get<int>(property.getValue())); } else if (propertyName == "background") { // Do nothing as property should be already processed by GUILayout } else { SW_ASSERT(false); } }); } void GUIProgressBar::applyStylesheetRuleToChildren( const GUIWidgetStylesheetRule& stylesheetRule, const std::vector<GUIWidgetStylesheetSelectorPart>& currentPath) { GUIWidget::applyStylesheetRuleToChildren(stylesheetRule, currentPath); m_scaleBox->applyStylesheetRuleWithSelector(stylesheetRule, currentPath); } void GUIProgressBar::setMaxValue(int value) { m_maxValue = value; updateScaleSize(); } int GUIProgressBar::getMaxValue() const { return m_maxValue; } void GUIProgressBar::setValue(int value) { m_currentValue = value; updateScaleSize(); } int GUIProgressBar::getValue() const { return m_currentValue; } void GUIProgressBar::setBorderPadding(const glm::ivec2& padding) { m_borderPadding = padding; updateScaleSize(); } const glm::ivec2& GUIProgressBar::getBorderPadding() const { return m_borderPadding; } void GUIProgressBar::updateScaleSize() { if (m_scaleBox->getParent() == nullptr) { addChildWidget(m_scaleBox); } m_scaleBox->setOrigin(m_borderPadding); float scaleWidthFactor = static_cast<float>(m_currentValue) / static_cast<float>(m_maxValue); int scaleWidth = static_cast<int>(static_cast<float>(getSize().x - m_borderPadding.x * 2) * scaleWidthFactor); int scaleHeight = getSize().y - m_borderPadding.y * 2; m_scaleBox->setSize({ scaleWidth, scaleHeight }); }
28.07767
112
0.728562
n-paukov
0f638a0f04e30041fd5fe200bbd888be11aa0a43
12,219
cpp
C++
Main/src/Audio/AudioPlayback.cpp
redline2466/unnamed-sdvx-clone
8f75329bb07439683fc2ea438e1fdac6831c897f
[ "MIT" ]
null
null
null
Main/src/Audio/AudioPlayback.cpp
redline2466/unnamed-sdvx-clone
8f75329bb07439683fc2ea438e1fdac6831c897f
[ "MIT" ]
null
null
null
Main/src/Audio/AudioPlayback.cpp
redline2466/unnamed-sdvx-clone
8f75329bb07439683fc2ea438e1fdac6831c897f
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "AudioPlayback.hpp" #include <Beatmap/BeatmapPlayback.hpp> #include <Beatmap/Beatmap.hpp> #include <Audio/Audio.hpp> #include <Audio/DSP.hpp> AudioPlayback::AudioPlayback() { } AudioPlayback::~AudioPlayback() { m_CleanupDSP(m_buttonDSPs[0]); m_CleanupDSP(m_buttonDSPs[1]); m_CleanupDSP(m_laserDSP); } bool AudioPlayback::Init(class BeatmapPlayback& playback, const String& mapRootPath) { // Cleanup exising DSP's m_currentHoldEffects[0] = nullptr; m_currentHoldEffects[1] = nullptr; m_CleanupDSP(m_buttonDSPs[0]); m_CleanupDSP(m_buttonDSPs[1]); m_CleanupDSP(m_laserDSP); m_playback = &playback; m_beatmap = &playback.GetBeatmap(); m_beatmapRootPath = mapRootPath; assert(m_beatmap != nullptr); // Set default effect type SetLaserEffect(EffectType::PeakingFilter); const BeatmapSettings& mapSettings = m_beatmap->GetMapSettings(); String audioPath = Path::Normalize(m_beatmapRootPath + Path::sep + mapSettings.audioNoFX); audioPath.TrimBack(' '); if(!Path::FileExists(audioPath)) { Logf("Audio file for beatmap does not exists at: \"%s\"", Logger::Severity::Error, audioPath); return false; } m_music = g_audio->CreateStream(audioPath, true); if(!m_music) { Logf("Failed to load any audio for beatmap \"%s\"", Logger::Severity::Error, audioPath); return false; } m_musicVolume = mapSettings.musicVolume; m_music->SetVolume(m_musicVolume); // Load FX track audioPath = Path::Normalize(m_beatmapRootPath + Path::sep + mapSettings.audioFX); audioPath.TrimBack(' '); if(!audioPath.empty()) { if(!Path::FileExists(audioPath) || Path::IsDirectory(audioPath)) { Logf("FX audio for for beatmap does not exists at: \"%s\" Using real-time effects instead.", Logger::Severity::Warning, audioPath); } else { m_fxtrack = g_audio->CreateStream(audioPath, true); if(m_fxtrack) { // Initially mute normal track if fx is enabled m_music->SetVolume(0.0f); } } } if (m_fxtrack) { // Prevent loading switchables if fx track is in use. return true; } auto switchablePaths = m_beatmap->GetSwitchablePaths(); // Load switchable audio tracks for (auto it = switchablePaths.begin(); it != switchablePaths.end(); ++it) { audioPath = Path::Normalize(m_beatmapRootPath + Path::sep + *it); audioPath.TrimBack(' '); SwitchableAudio switchable; switchable.m_enabled = false; if (!audioPath.empty()) { if (!Path::FileExists(audioPath)) { Logf("Audio for a SwitchAudio effect does not exists at: \"%s\"", Logger::Severity::Warning, audioPath); } else { switchable.m_audio = g_audio->CreateStream(audioPath, true); if (switchable.m_audio) { // Mute all switchable audio by default switchable.m_audio->SetVolume(0.0f); } } } m_switchables.Add(switchable); } return true; } void AudioPlayback::Tick(float deltaTime) { } void AudioPlayback::Play() { m_music->Play(); if(m_fxtrack) m_fxtrack->Play(); for (auto it = m_switchables.begin(); it != m_switchables.end(); ++it) if (it->m_audio) it->m_audio->Play(); m_paused = false; } void AudioPlayback::Advance(MapTime ms) { SetPosition(GetPosition() + ms); } MapTime AudioPlayback::GetPosition() const { return m_music->GetPosition(); } void AudioPlayback::SetPosition(MapTime time) { m_music->SetPosition(time); if(m_fxtrack) m_fxtrack->SetPosition(time); for (auto it = m_switchables.begin(); it != m_switchables.end(); ++it) if (it->m_audio) it->m_audio->SetPosition(time); } void AudioPlayback::TogglePause() { if(m_paused) Play(); else Pause(); } void AudioPlayback::Pause() { if (m_paused) return; m_music->Pause(); if (m_fxtrack) m_fxtrack->Pause(); for (auto it = m_switchables.begin(); it != m_switchables.end(); ++it) if (it->m_audio) it->m_audio->Pause(); m_paused = true; } bool AudioPlayback::HasEnded() const { return m_music->HasEnded(); } void AudioPlayback::SetEffect(uint32 index, HoldObjectState* object, class BeatmapPlayback& playback) { // Don't use effects when using an FX track if(m_fxtrack) return; assert(index <= 1); m_CleanupDSP(m_buttonDSPs[index]); m_currentHoldEffects[index] = object; // For Time based effects const TimingPoint* timingPoint = playback.GetTimingPointAt(object->time); // Duration of a single bar double barDelay = timingPoint->numerator * timingPoint->beatDuration; DSP*& dsp = m_buttonDSPs[index]; m_buttonEffects[index] = m_beatmap->GetEffect(object->effectType); // Do not create DSP for SwitchAudio effect if (m_buttonEffects[index].type == EffectType::SwitchAudio) return; dsp = m_buttonEffects[index].CreateDSP(m_GetDSPTrack().get(), *this); Logf("Set effect: %s", Logger::Severity::Debug, dsp->GetName()); if(dsp) { m_buttonEffects[index].SetParams(dsp, *this, object); // Initialize mix value to previous value dsp->mix = m_effectMix[index]; dsp->startTime = object->time; dsp->chartOffset = playback.GetBeatmap().GetMapSettings().offset; dsp->lastTimingPoint = playback.GetCurrentTimingPoint().time; } } void AudioPlayback::SetEffectEnabled(uint32 index, bool enabled) { assert(index <= 1); m_effectMix[index] = enabled ? 1.0f : 0.0f; if (m_buttonEffects[index].type == EffectType::SwitchAudio) { SetSwitchableTrackEnabled(m_buttonEffects[index].switchaudio.index.Sample(), enabled); return; } if(m_buttonDSPs[index]) { m_buttonDSPs[index]->mix = m_effectMix[index]; } } void AudioPlayback::ClearEffect(uint32 index, HoldObjectState* object) { assert(index <= 1); if(m_currentHoldEffects[index] == object) { m_CleanupDSP(m_buttonDSPs[index]); m_currentHoldEffects[index] = nullptr; } } void AudioPlayback::SetLaserEffect(EffectType type) { if(type != m_laserEffectType) { m_CleanupDSP(m_laserDSP); m_laserEffectType = type; m_laserEffect = m_beatmap->GetFilter(type); } } void AudioPlayback::SetLaserFilterInput(float input, bool active) { if(m_laserEffect.type != EffectType::None && (active || (input != 0.0f))) { if (m_laserEffect.type == EffectType::SwitchAudio) { m_laserSwitchable = m_laserEffect.switchaudio.index.Sample(); SetSwitchableTrackEnabled(m_laserSwitchable, true); return; } // SwitchAudio transition into other filters if (m_laserSwitchable > 0) { SetSwitchableTrackEnabled(m_laserSwitchable, false); m_laserSwitchable = -1; } // Create DSP if(!m_laserDSP) { // Don't use Bitcrush effects over FX track if(m_fxtrack && m_laserEffectType == EffectType::Bitcrush) return; m_laserDSP = m_laserEffect.CreateDSP(m_GetDSPTrack().get(), *this); if(!m_laserDSP) { Logf("Failed to create laser DSP with type %d", Logger::Severity::Warning, m_laserEffect.type); return; } } // Set params m_SetLaserEffectParameter(input); m_laserInput = input; } else { if (m_laserSwitchable > 0) SetSwitchableTrackEnabled(m_laserSwitchable, true); m_laserSwitchable = -1; m_CleanupDSP(m_laserDSP); m_laserInput = 0.0f; } } float AudioPlayback::GetLaserFilterInput() const { return m_laserInput; } void AudioPlayback::SetLaserEffectMix(float mix) { m_laserEffectMix = mix; } float AudioPlayback::GetLaserEffectMix() const { return m_laserEffectMix; } Ref<AudioStream> AudioPlayback::m_GetDSPTrack() { if(m_fxtrack) return m_fxtrack; return m_music; } void AudioPlayback::SetFXTrackEnabled(bool enabled) { if(!m_fxtrack) return; if(m_fxtrackEnabled != enabled) { if(enabled) { m_fxtrack->SetVolume(m_musicVolume); m_music->SetVolume(0.0f); } else { m_fxtrack->SetVolume(0.0f); m_music->SetVolume(m_musicVolume); } } m_fxtrackEnabled = enabled; } void AudioPlayback::SetSwitchableTrackEnabled(size_t index, bool enabled) { if (m_fxtrack) return; assert(index < m_switchables.size()); int32 disableTrack = -1; int32 enableTrack = -1; if (!enabled) { disableTrack = index; m_enabledSwitchables.Remove(index); enableTrack = m_enabledSwitchables.size() ? m_enabledSwitchables.back() : -2; } else { disableTrack = m_enabledSwitchables.size() ? m_enabledSwitchables.back() : -2; m_enabledSwitchables.AddUnique(index); enableTrack = m_enabledSwitchables.size() ? m_enabledSwitchables.back() : -2; } if (disableTrack != -1) { if (disableTrack == -2) m_music->SetVolume(0.0f); else if (m_switchables[disableTrack].m_audio) m_switchables[disableTrack].m_audio->SetVolume(0.0f); } if (enableTrack != -1) { if (enableTrack == -2) m_music->SetVolume(m_musicVolume); else if (m_switchables[enableTrack].m_audio) m_switchables[enableTrack].m_audio->SetVolume(m_musicVolume); } } void AudioPlayback::ResetSwitchableTracks() { for (size_t i = 0; i < m_switchables.size(); ++i) { if (m_switchables[i].m_audio) m_switchables[i].m_audio->SetVolume(0.0f); } m_music->SetVolume(m_musicVolume); } BeatmapPlayback& AudioPlayback::GetBeatmapPlayback() { return *m_playback; } const Beatmap& AudioPlayback::GetBeatmap() const { return *m_beatmap; } const String& AudioPlayback::GetBeatmapRootPath() const { return m_beatmapRootPath; } void AudioPlayback::SetPlaybackSpeed(float speed) { m_music->PlaybackSpeed = speed; if (m_fxtrack) m_fxtrack->PlaybackSpeed = speed; for (auto it = m_switchables.begin(); it != m_switchables.end(); ++it) if (it->m_audio) it->m_audio->PlaybackSpeed = speed; } float AudioPlayback::GetPlaybackSpeed() const { return m_music->PlaybackSpeed; } void AudioPlayback::SetVolume(float volume) { m_music->SetVolume(volume); if (m_fxtrack) m_fxtrack->SetVolume(volume); for (auto it = m_switchables.begin(); it != m_switchables.end(); ++it) if (it->m_audio) it->m_audio->SetVolume(volume); } void AudioPlayback::m_CleanupDSP(DSP*& ptr) { if(ptr) { m_GetDSPTrack()->RemoveDSP(ptr); delete ptr; ptr = nullptr; } } void AudioPlayback::m_SetLaserEffectParameter(float input) { if(!m_laserDSP) return; assert(input >= 0.0f && input <= 1.0f); // Mix float biquad filters, these are applied manualy by changing the filter parameters (gain,q,freq,etc.) float mix = m_laserEffectMix; double noteDuration = m_playback->GetCurrentTimingPoint().GetWholeNoteLength(); uint32 actualLength = m_laserEffect.duration.Sample(input).Absolute(noteDuration); if(input < 0.1f) mix *= input / 0.1f; switch (m_laserEffect.type) { case EffectType::Bitcrush: { m_laserDSP->mix = m_laserEffect.mix.Sample(input); BitCrusherDSP* bcDSP = (BitCrusherDSP*)m_laserDSP; bcDSP->SetPeriod((float)m_laserEffect.bitcrusher.reduction.Sample(input)); break; } case EffectType::Echo: { m_laserDSP->mix = m_laserEffect.mix.Sample(input); EchoDSP* echoDSP = (EchoDSP*)m_laserDSP; echoDSP->feedback = m_laserEffect.echo.feedback.Sample(input); break; } case EffectType::PeakingFilter: { m_laserDSP->mix = m_laserEffectMix; if (input > 0.8f) mix *= 1.0f - (input - 0.8f) / 0.2f; BQFDSP* bqfDSP = (BQFDSP*)m_laserDSP; bqfDSP->SetPeaking(m_laserEffect.peaking.q.Sample(input), m_laserEffect.peaking.freq.Sample(input), m_laserEffect.peaking.gain.Sample(input) * mix); break; } case EffectType::LowPassFilter: { m_laserDSP->mix = m_laserEffectMix; BQFDSP* bqfDSP = (BQFDSP*)m_laserDSP; bqfDSP->SetLowPass(m_laserEffect.lpf.q.Sample(input) * mix + 0.1f, m_laserEffect.lpf.freq.Sample(input)); break; } case EffectType::HighPassFilter: { m_laserDSP->mix = m_laserEffectMix; BQFDSP* bqfDSP = (BQFDSP*)m_laserDSP; bqfDSP->SetHighPass(m_laserEffect.hpf.q.Sample(input) * mix + 0.1f, m_laserEffect.hpf.freq.Sample(input)); break; } case EffectType::PitchShift: { m_laserDSP->mix = m_laserEffect.mix.Sample(input); PitchShiftDSP* ps = (PitchShiftDSP*)m_laserDSP; ps->amount = m_laserEffect.pitchshift.amount.Sample(input); break; } case EffectType::Gate: { m_laserDSP->mix = m_laserEffect.mix.Sample(input); GateDSP * gd = (GateDSP*)m_laserDSP; // gd->SetLength(actualLength); break; } case EffectType::Retrigger: { m_laserDSP->mix = m_laserEffect.mix.Sample(input); RetriggerDSP * rt = (RetriggerDSP*)m_laserDSP; rt->SetLength(actualLength); break; } default: break; } } GameAudioEffect::GameAudioEffect(const AudioEffect& other) { *((AudioEffect*)this) = other; }
25.350622
150
0.717407
redline2466
0f63b2342d8a2d1d8564a5400d8d931e62e908ae
1,230
cc
C++
bindings/java/src/main/native/worker.cc
RankoM/ucx
d8269f0141f97764c21d03235c0783f04a9864b7
[ "BSD-3-Clause" ]
5
2019-05-31T01:47:34.000Z
2022-01-10T11:59:53.000Z
bindings/java/src/main/native/worker.cc
frontwing/ucx
e1eed19d973844198445ba822239f0b8a5be19a7
[ "BSD-3-Clause" ]
1
2020-01-28T08:42:44.000Z
2020-01-28T08:42:44.000Z
bindings/java/src/main/native/worker.cc
frontwing/ucx
e1eed19d973844198445ba822239f0b8a5be19a7
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) Mellanox Technologies Ltd. 2001-2017. ALL RIGHTS RESERVED. * See file LICENSE for terms. */ #include "worker.h" #include <new> // bad_alloc exception worker::worker(context* ctx, uint32_t cap, ucp_worker_params_t params) : jucx_context(ctx), ucp_worker(nullptr), queue_size(cap), event_queue(nullptr) { ucs_status_t status = jucx_context->ref_context(); if (status != UCS_OK) { throw std::bad_alloc{}; } status = ucp_worker_create(jucx_context->get_ucp_context(), &params, &ucp_worker); if (status != UCS_OK) { jucx_context->deref_context(); throw std::bad_alloc{}; } event_queue = new char[queue_size]; } worker::~worker() { delete[] event_queue; ucp_worker_destroy(ucp_worker); jucx_context->deref_context(); } ucs_status_t worker::extract_worker_address(ucp_address_t** worker_address, size_t& address_length) { return ucp_worker_get_address(ucp_worker, worker_address, &address_length); } void worker::release_worker_address(ucp_address_t* worker_address) { ucp_worker_release_address(ucp_worker, worker_address); }
30.75
79
0.657724
RankoM
0f69f2a44ad7e3a2d8ef555342593f34218ee841
804
cpp
C++
solutions/218.the-skyline-problem.378841603.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
78
2020-10-22T11:31:53.000Z
2022-02-22T13:27:49.000Z
solutions/218.the-skyline-problem.378841603.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
null
null
null
solutions/218.the-skyline-problem.378841603.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
26
2020-10-23T15:10:44.000Z
2021-11-07T16:13:50.000Z
class Solution { public: vector<vector<int>> getSkyline(vector<vector<int>> &buildings) { int n = buildings.size(); vector<vector<int>> arr; vector<vector<int>> ans; if (!n) return ans; for (auto b : buildings) { arr.push_back({b[0], b[2], 1}); arr.push_back({b[1], b[2], -1}); } sort(arr.begin(), arr.end()); multiset<int> set; set.insert(0); for (int i = 0; i < 2 * n; i++) { int x = arr[i][0]; int h = arr[i][1]; int op = arr[i][2]; if (op == 1) set.insert(h); else set.erase(set.find(h)); if (i != 2 * n - 1 && arr[i + 1][0] == x) continue; if (ans.empty() || *set.rbegin() != ans.back()[1]) ans.push_back({x, *set.rbegin()}); } return ans; } };
19.142857
66
0.472637
satu0king
0f6aa7ef32bc85f9b9a66990cf07613e435e86d0
242
cpp
C++
Modules/Assimp/RNAssimpInit.cpp
uberpixel/Rayne
94f601561aedfc3200e67ff9522f64fbc5ca4d8c
[ "MIT" ]
13
2020-08-08T11:57:05.000Z
2022-03-10T17:29:19.000Z
Modules/Assimp/RNAssimpInit.cpp
uberpixel/Rayne
94f601561aedfc3200e67ff9522f64fbc5ca4d8c
[ "MIT" ]
1
2022-03-10T17:35:28.000Z
2022-03-10T18:21:57.000Z
Modules/Assimp/RNAssimpInit.cpp
uberpixel/Rayne
94f601561aedfc3200e67ff9522f64fbc5ca4d8c
[ "MIT" ]
3
2020-08-08T14:22:34.000Z
2021-05-15T21:12:17.000Z
// // init.cpp // Rayne-Assimp // // Copyright 2015 by Überpixel. All rights reserved. // Unauthorized use is punishable by torture, mutilation, and vivisection. // #include <Rayne.h> RNModule(RayneAssimp, "net.uberpixel.rayne.assimp")
20.166667
75
0.719008
uberpixel
0f7206bcf5ca36bc7659f68efd712639a06a541a
6,336
cpp
C++
rocAL/rocAL/source/video_file_source_reader.cpp
Indumathi31/MIVisionX
e58c8b63d51e3f857d5f1c8750433d1ec887d7f0
[ "MIT" ]
null
null
null
rocAL/rocAL/source/video_file_source_reader.cpp
Indumathi31/MIVisionX
e58c8b63d51e3f857d5f1c8750433d1ec887d7f0
[ "MIT" ]
8
2021-12-10T14:07:28.000Z
2022-03-04T02:53:11.000Z
rocAL/rocAL/source/video_file_source_reader.cpp
Indumathi31/MIVisionX
e58c8b63d51e3f857d5f1c8750433d1ec887d7f0
[ "MIT" ]
2
2021-06-01T09:42:51.000Z
2021-11-09T14:35:36.000Z
/* Copyright (c) 2019 - 2022 Advanced Micro Devices, Inc. All rights reserved. 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 <cassert> #include <algorithm> #include <commons.h> #include "video_file_source_reader.h" #include <boost/filesystem.hpp> namespace filesys = boost::filesystem; #ifdef RALI_VIDEO VideoFileSourceReader::VideoFileSourceReader() : _shuffle_time("shuffle_time", DBG_TIMING) { _curr_sequence_idx = 0; _loop = false; _sequence_id = 0; _shuffle = false; _sequence_count_all_shards = 0; } unsigned VideoFileSourceReader::count_items() { if (_loop) return _total_sequences_count; int ret = (int)(_total_sequences_count - _read_counter); return ((ret <= 0) ? 0 : ret); } VideoReader::Status VideoFileSourceReader::initialize(VideoReaderConfig desc) { auto ret = VideoReader::Status::OK; _sequence_id = 0; _folder_path = desc.path(); _shard_id = desc.get_shard_id(); _shard_count = desc.get_shard_count(); _shuffle = desc.shuffle(); _loop = desc.loop(); _video_prop = desc.get_video_properties(); _video_count = _video_prop.videos_count; _video_file_names.resize(_video_count); _start_end_frame.resize(_video_count); _video_file_names = _video_prop.video_file_names; _sequence_length = desc.get_sequence_length(); _step = desc.get_frame_step(); _stride = desc.get_frame_stride(); _video_frame_count = _video_prop.frames_count; _start_end_frame = _video_prop.start_end_frame_num; _batch_count = desc.get_batch_size(); _total_sequences_count = 0; ret = create_sequence_info(); // the following code is required to make every shard the same size:: required for multi-gpu training if (_shard_count > 1 && _batch_count > 1) { int _num_batches = _sequences.size()/_batch_count; int max_batches_per_shard = (_sequence_count_all_shards + _shard_count-1)/_shard_count; max_batches_per_shard = (max_batches_per_shard + _batch_count-1)/_batch_count; if (_num_batches < max_batches_per_shard) { replicate_last_batch_to_pad_partial_shard(); } } //shuffle dataset if set _shuffle_time.start(); if (ret == VideoReader::Status::OK && _shuffle) std::random_shuffle(_sequences.begin(), _sequences.end()); _shuffle_time.end(); return ret; } void VideoFileSourceReader::incremenet_read_ptr() { _read_counter ++; _curr_sequence_idx = (_curr_sequence_idx + 1) % _sequences.size(); } SequenceInfo VideoFileSourceReader::get_sequence_info() { auto current_sequence = _sequences[_curr_sequence_idx]; auto file_path = current_sequence.video_file_name; _last_id = file_path; incremenet_read_ptr(); return current_sequence; } VideoFileSourceReader::~VideoFileSourceReader() { } void VideoFileSourceReader::reset() { if (_shuffle) std::random_shuffle(_sequences.begin(), _sequences.end()); _read_counter = 0; _curr_sequence_idx = 0; } VideoReader::Status VideoFileSourceReader::create_sequence_info() { VideoReader::Status status = VideoReader::Status::OK; for (size_t i = 0; i < _video_count; i++) { unsigned start = std::get<0>(_start_end_frame[i]); size_t max_sequence_frames = (_sequence_length - 1) * _stride; for(size_t sequence_start = start; (sequence_start + max_sequence_frames) < (start + _video_frame_count[i]); sequence_start += _step) { if(get_sequence_shard_id() != _shard_id) { _sequence_count_all_shards++; incremenet_sequence_id(); continue; } _in_batch_read_count++; _in_batch_read_count = (_in_batch_read_count % _batch_count == 0) ? 0 : _in_batch_read_count; _sequences.push_back({sequence_start, _video_file_names[i]}); _last_sequence = _sequences.back(); _total_sequences_count ++; _sequence_count_all_shards++; incremenet_sequence_id(); } } if(_in_batch_read_count > 0 && _in_batch_read_count < _batch_count) { replicate_last_sequence_to_fill_last_shard(); LOG("VideoFileSourceReader ShardID [" + TOSTR(_shard_id) + "] Replicated the last sequence " + TOSTR((_batch_count - _in_batch_read_count) ) + " times to fill the last batch") } if(_sequences.empty()) WRN("VideoFileSourceReader ShardID ["+ TOSTR(_shard_id)+ "] Did not load any sequences from " + _folder_path) return status; } void VideoFileSourceReader::replicate_last_sequence_to_fill_last_shard() { for (size_t i = _in_batch_read_count; i < _batch_count; i++) { _sequences.push_back(_last_sequence); _total_sequences_count ++; } } void VideoFileSourceReader::replicate_last_batch_to_pad_partial_shard() { if (_sequences.size() >= _batch_count) { for (size_t i = 0; i < _batch_count; i++) { _sequences.push_back(_sequences[i - _batch_count]); _total_sequences_count ++; } } } size_t VideoFileSourceReader::get_sequence_shard_id() { if (_batch_count == 0 || _shard_count == 0) THROW("Shard (Batch) size cannot be set to 0") //return (_sequence_id / (_batch_count)) % _shard_count; return _sequence_id % _shard_count; } #endif
35.396648
183
0.705335
Indumathi31
0f7219755fee8b12023492c0e3e75b62a3581580
3,945
cpp
C++
test/bwe/RateControllerTest.cpp
TheJuanAndOnly99/SymphonyMediaBridge
9a04c2ece444575e78297b89dc9bcc13b303bc53
[ "Apache-2.0" ]
null
null
null
test/bwe/RateControllerTest.cpp
TheJuanAndOnly99/SymphonyMediaBridge
9a04c2ece444575e78297b89dc9bcc13b303bc53
[ "Apache-2.0" ]
null
null
null
test/bwe/RateControllerTest.cpp
TheJuanAndOnly99/SymphonyMediaBridge
9a04c2ece444575e78297b89dc9bcc13b303bc53
[ "Apache-2.0" ]
null
null
null
#include "bwe/RateController.h" #include "config/Config.h" #include "memory/PacketPoolAllocator.h" #include "rtp/RtcpHeader.h" #include "rtp/RtpHeader.h" #include "test/bwe/FakeAudioSource.h" #include "test/bwe/FakeVideoSource.h" #include "test/bwe/RcCall.h" #include "test/transport/FakeNetwork.h" #include "transport/RtpReceiveState.h" #include "transport/RtpSenderState.h" #include "transport/ice/IceSession.h" #include "transport/sctp/SctpConfig.h" #include <gtest/gtest.h> #include <vector> class RateControllerTestBase : public ::testing::TestWithParam<uint32_t> { public: RateControllerTestBase() : _allocator(4096 * 32, "ratemain") {} memory::PacketPoolAllocator _allocator; config::Config _config; }; class RateControllerTestLongRtt : public RateControllerTestBase { }; TEST_P(RateControllerTestLongRtt, longRtt) { uint32_t capacityKbps = GetParam(); bwe::RateControllerConfig rcConfig; bwe::RateController rateControl(1, rcConfig); auto* uplink = new fakenet::NetworkLink(capacityKbps, 75000, 1480); uplink->setStaticDelay(90); auto* downLink = new fakenet::NetworkLink(6500, 75000, 1480); downLink->setStaticDelay(70); fakenet::RcCall call(_allocator, _config, rateControl, uplink, downLink, true, 24 * utils::Time::sec); fakenet::FakeVideoSource* video = nullptr; if (capacityKbps > 300) { auto video = new fakenet::FakeVideoSource(_allocator, 0, 10); call.addChannel(video, 90000); video->setBandwidth(100); } call.run(utils::Time::sec * 9, capacityKbps * 1.05); EXPECT_GE(rateControl.getTargetRate(), std::min(1000.0, capacityKbps * 0.60)); if (video) { video->setBandwidth((rateControl.getTargetRate() - 100) * 0.8); } double timeLine = 0; while (call.run(utils::Time::sec * 2, capacityKbps * 1.05)) { timeLine += 2; if (video) { video->setBandwidth(std::min(1800.0, (rateControl.getTargetRate() - 100) * 0.8)); } EXPECT_GE(rateControl.getTargetRate(), std::min(1000 + (timeLine * 200), capacityKbps * 0.90)); EXPECT_LT(rateControl.getTargetRate(), capacityKbps * 1.05); } } INSTANTIATE_TEST_SUITE_P(RateControllerLongRtt, RateControllerTestLongRtt, testing::Values(300, 500, 700, 1000, 1200, 3000, 4000, 5000)); class RateControllerTestShortRtt : public RateControllerTestBase { }; TEST_P(RateControllerTestShortRtt, shortRtt) { uint32_t capacityKbps = GetParam(); bwe::RateControllerConfig rcConfig; bwe::RateController rateControl(1, rcConfig); auto* uplink = new fakenet::NetworkLink(capacityKbps, 75000, 1480); uplink->setStaticDelay(0); auto* downLink = new fakenet::NetworkLink(6500, 75000, 1480); downLink->setStaticDelay(0); fakenet::RcCall call(_allocator, _config, rateControl, uplink, downLink, true, 24 * utils::Time::sec); fakenet::FakeVideoSource* video = nullptr; if (capacityKbps > 300) { auto video = new fakenet::FakeVideoSource(_allocator, 0, 10); call.addChannel(video, 90000); video->setBandwidth(100); } call.run(utils::Time::sec * 10, capacityKbps * 1.05); double timeLine = 0; EXPECT_GE(rateControl.getTargetRate(), std::min(1000.0, capacityKbps * 0.60)); if (video) { video->setBandwidth((rateControl.getTargetRate() - 100) * 0.8); } while (call.run(utils::Time::sec * 2, capacityKbps * 1.05)) { timeLine += 2; if (video) { video->setBandwidth(std::min(1800.0, (rateControl.getTargetRate() - 100) * 0.8)); } EXPECT_GE(rateControl.getTargetRate(), std::min(1000 + (timeLine * 150), capacityKbps * 0.90)); EXPECT_LT(rateControl.getTargetRate(), capacityKbps * 1.05); } } INSTANTIATE_TEST_SUITE_P(RateControllerShortRtt, RateControllerTestShortRtt, testing::Values(300, 500, 700, 1000, 1200, 3000, 4000, 5000));
32.875
106
0.678327
TheJuanAndOnly99
0f7260b548a23114931b730ef6da9b8d818b145f
2,399
cpp
C++
src/UserInteraction/SdkModel/UserInteractionController.cpp
usamakhan049/assignment
40eb153e8fd74f73ba52ce29417d8220ab744b5d
[ "BSD-2-Clause" ]
69
2017-06-07T10:47:03.000Z
2022-03-24T08:33:33.000Z
src/UserInteraction/SdkModel/UserInteractionController.cpp
usamakhan049/assignment
40eb153e8fd74f73ba52ce29417d8220ab744b5d
[ "BSD-2-Clause" ]
23
2017-06-07T10:47:00.000Z
2020-07-09T10:31:17.000Z
src/UserInteraction/SdkModel/UserInteractionController.cpp
usamakhan049/assignment
40eb153e8fd74f73ba52ce29417d8220ab744b5d
[ "BSD-2-Clause" ]
31
2017-08-12T13:19:32.000Z
2022-01-04T20:33:40.000Z
// Copyright eeGeo Ltd (2012-2015), All Rights Reserved #include "UserInteractionController.h" // App includes #include "IAppCameraController.h" #include "ICameraTransitionController.h" #include "InteriorExplorerUserInteractionModel.h" #include "UserInteractionModel.h" namespace ExampleApp { namespace UserInteraction { namespace SdkModel { UserInteractionController::UserInteractionController(UserInteractionModel& userInteractionModel, AppCamera::SdkModel::IAppCameraController& appCameraController, InteriorsExplorer::SdkModel::InteriorExplorerUserInteractionModel& interiorExplorerUserInteractionModel, CameraTransitions::SdkModel::ICameraTransitionController& cameraTransitionController) : m_userInteractionModel(userInteractionModel) , m_appCameraController(appCameraController) , m_cameraTransitionController(cameraTransitionController) , m_interiorExplorerUserInteractionModel(interiorExplorerUserInteractionModel) , m_handler(this, &UserInteractionController::OnObservedChanged) { m_cameraTransitionController.InsertTransitioningChangedCallback(m_handler); m_appCameraController.InsertTransitioInFlightChangedCallback(m_handler); m_interiorExplorerUserInteractionModel.InsertEnabledChangedCallback(m_handler); } UserInteractionController::~UserInteractionController() { m_cameraTransitionController.RemoveTransitioningChangedCallback(m_handler); m_appCameraController.RemoveTransitioInFlightChangedCallback(m_handler); m_interiorExplorerUserInteractionModel.RemoveEnabledChangedCallback(m_handler); } void UserInteractionController::OnObservedChanged() { m_userInteractionModel.SetEnabled(!m_cameraTransitionController.IsTransitioning() && !m_appCameraController.IsTransitionInFlight() && m_interiorExplorerUserInteractionModel.IsEnabled()); } } } }
51.042553
169
0.64777
usamakhan049
0f72b5a4586d789930a47936f53311a7b3822c77
566
cpp
C++
searchlib/src/vespa/searchlib/fef/fieldinfo.cpp
amahussein/vespa
29d266ae1e5c95e25002b97822953fdd02b1451e
[ "Apache-2.0" ]
1
2018-12-30T05:42:18.000Z
2018-12-30T05:42:18.000Z
searchlib/src/vespa/searchlib/fef/fieldinfo.cpp
amahussein/vespa
29d266ae1e5c95e25002b97822953fdd02b1451e
[ "Apache-2.0" ]
1
2021-03-31T22:27:25.000Z
2021-03-31T22:27:25.000Z
searchlib/src/vespa/searchlib/fef/fieldinfo.cpp
amahussein/vespa
29d266ae1e5c95e25002b97822953fdd02b1451e
[ "Apache-2.0" ]
1
2020-02-01T07:21:28.000Z
2020-02-01T07:21:28.000Z
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "fieldinfo.h" namespace search { namespace fef { FieldInfo::FieldInfo(FieldType type_in, CollectionType collection_in, const string &name_in, uint32_t id_in) : _type(type_in), _data_type(DataType::DOUBLE), _collection(collection_in), _name(name_in), _id(id_in), _isFilter(false), _hasAttribute(type_in == FieldType::ATTRIBUTE) { } } // namespace fef } // namespace search
24.608696
118
0.685512
amahussein
0f73c4df97f79d6bd4a28161cee331ccbc6094e0
3,222
cpp
C++
codeBase/CodeJam/2008/2008_Q_B/2008_Q_B.cpp
suren3141/codeBase
10ed9a56aca33631dc8c419cd83859c19dd6ff09
[ "Apache-2.0" ]
3
2020-03-16T14:59:08.000Z
2021-07-28T20:51:53.000Z
codeBase/CodeJam/2008/2008_Q_B/2008_Q_B.cpp
suren3141/codeBase
10ed9a56aca33631dc8c419cd83859c19dd6ff09
[ "Apache-2.0" ]
2
2016-04-16T05:39:20.000Z
2016-06-06T12:24:56.000Z
codeBase/CodeJam/2008/2008_Q_B/2008_Q_B.cpp
killerilaksha/codeBase
91cbd950fc90066903e58311000784aeba4ffc02
[ "Apache-2.0" ]
18
2020-02-17T23:17:37.000Z
2021-07-28T20:52:13.000Z
#include<bits/stdc++.h> using namespace std; #define NIL 0 #define INF INT_MAX typedef long int li; typedef pair<int,int> pr; class BipGraph { int m, n; vector<vector<int> > adj; vector<int> pairU, pairV, dist; public: BipGraph(int, int); void addEdge(int, int); bool bfs(); bool dfs(int); int hopcroftKarp(); }; int BipGraph::hopcroftKarp() { for (int u = 0; u < m; u++) pairU[u] = NIL; for (int v = 0; v < n; v++) pairV[v] = NIL; int result = 0; while (bfs()) { for (int u = 1; u <= m; u++) if (pairU[u] == NIL && dfs(u)) { result++; } } return result; } bool BipGraph::bfs() { queue<int> Q; for (int u = 1; u <= m; u++) { if (pairU[u] == NIL) { dist[u] = 0; Q.push(u); } else dist[u] = INF; } dist[NIL] = INF; while (!Q.empty()) { int u = Q.front(); Q.pop(); if (dist[u] < dist[NIL]) { for (int i = 0; i < adj[u].size(); ++i) { int v = adj[u][i]; if (dist[pairV[v]] == INF) { dist[pairV[v]] = dist[u] + 1; Q.push(pairV[v]); } } } } return (dist[NIL] != INF); } bool BipGraph::dfs(int u) { if (u != NIL) { for (int i = 0; i < adj[u].size(); ++i) { int v = adj[u][i]; if (dist[pairV[v]] == dist[u] + 1) { if (dfs(pairV[v]) == true) { pairV[v] = u; pairU[u] = v; return true; } } } dist[u] = INF; return false; } return true; } BipGraph::BipGraph(int m, int n) { this->m = m; this->n = n; adj.resize(m + 1); pairU.resize(m + 1); pairV.resize(n + 1); dist.resize(m + 1); } void BipGraph::addEdge(int u, int v) { adj[u].push_back(v); } int main() { int tt; cin>>tt; for(int t=0;t<tt;t++){ int T,A,B; cin>>T>>A>>B; vector<pr> AT(A); vector<pr> BT(B); for(int i=0;i<A;i++){ int a,b,c,d; scanf("%d:%d %d:%d\n",&a,&b,&c,&d); //cout<<a<<" "<<b<<" "<<c<<" "<<d<<endl; AT[i]=make_pair(a*60+b,c*60+d); } for(int i=0;i<B;i++){ int a,b,c,d; scanf("%d:%d %d:%d\n",&a,&b,&c,&d); //cout<<a<<" "<<b<<" "<<c<<" "<<d<<endl; BT[i]=make_pair(a*60+b,c*60+d); } BipGraph g1(A,B); for(int i=0;i<A;i++){ for(int j=0;j<B;j++){ int e=BT[j].second; int s=AT[i].first; if(s-e>=T) g1.addEdge(i+1,j+1); } } printf("Case #%d: ",t+1); cout<<A-g1.hopcroftKarp()<<" "; BipGraph g2(B,A); for(int i=0;i<B;i++){ for(int j=0;j<A;j++){ int e=AT[j].second; int s=BT[i].first; if(s-e>=T) g2.addEdge(i+1,j+1); } } cout<<B-g2.hopcroftKarp()<<endl; } return 0; }
22.690141
53
0.379268
suren3141
0f74226fb051456497cb058c209e436a6f333b75
2,804
hpp
C++
Dependencies/xerces-c-src_2_8_0/include/xercesc/internal/XProtoType.hpp
neonkingfr/wildogcad
6d9798daa672d3ab293579439f38bb279fa376c7
[ "BSD-3-Clause" ]
11
2016-02-26T23:00:34.000Z
2020-11-12T03:09:45.000Z
proj/vendors/xerces/include/xercesc/internal/XProtoType.hpp
DSRCorporation/asdcplib-as02
018002ccc5d62716514921a14782446e8edc4f3a
[ "OpenSSL" ]
null
null
null
proj/vendors/xerces/include/xercesc/internal/XProtoType.hpp
DSRCorporation/asdcplib-as02
018002ccc5d62716514921a14782446e8edc4f3a
[ "OpenSSL" ]
1
2018-07-10T19:24:28.000Z
2018-07-10T19:24:28.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: XProtoType.hpp 568078 2007-08-21 11:43:25Z amassari $ */ #if !defined(XPROTOTYPE_HPP) #define XPROTOTYPE_HPP #include <xercesc/util/PlatformUtils.hpp> XERCES_CPP_NAMESPACE_BEGIN class XSerializeEngine; class XSerializable; class XMLUTIL_EXPORT XProtoType { public: void store(XSerializeEngine& serEng) const; static void load(XSerializeEngine& serEng , XMLByte* const name , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); // ------------------------------------------------------------------------------- // data // // fClassName: // name of the XSerializable derivatives // // fCreateObject: // pointer to the factory method (createObject()) // of the XSerializable derivatives // // ------------------------------------------------------------------------------- XMLByte* fClassName; XSerializable* (*fCreateObject)(MemoryManager*); }; #define DECL_XPROTOTYPE(class_name) \ static XProtoType class##class_name; \ static XSerializable* createObject(MemoryManager* manager); /*** * For non-abstract class ***/ #define IMPL_XPROTOTYPE_TOCREATE(class_name) \ IMPL_XPROTOTYPE_INSTANCE(class_name) \ XSerializable* class_name::createObject(MemoryManager* manager) \ {return new (manager) class_name(manager);} /*** * For abstract class ***/ #define IMPL_XPROTOTYPE_NOCREATE(class_name) \ IMPL_XPROTOTYPE_INSTANCE(class_name) \ XSerializable* class_name::createObject(MemoryManager*) \ {return 0;} /*** * Helper Macro ***/ #define XPROTOTYPE_CLASS(class_name) ((XProtoType*)(&class_name::class##class_name)) #define IMPL_XPROTOTYPE_INSTANCE(class_name) \ XProtoType class_name::class##class_name = \ {(XMLByte*) #class_name, class_name::createObject }; XERCES_CPP_NAMESPACE_END #endif
29.515789
92
0.646933
neonkingfr
0f76dc536e7bc0613e9b45102b2c6237262d07a8
1,354
cpp
C++
external_codes/mpi_wrapper/mpi3/test/shm_multi_array.cpp
bwvdg/qmcpack
cd09fc54b36de2579c9802f5e64b7ec15506f3c3
[ "NCSA" ]
null
null
null
external_codes/mpi_wrapper/mpi3/test/shm_multi_array.cpp
bwvdg/qmcpack
cd09fc54b36de2579c9802f5e64b7ec15506f3c3
[ "NCSA" ]
null
null
null
external_codes/mpi_wrapper/mpi3/test/shm_multi_array.cpp
bwvdg/qmcpack
cd09fc54b36de2579c9802f5e64b7ec15506f3c3
[ "NCSA" ]
null
null
null
#if COMPILATION_INSTRUCTIONS mpic++ -O3 -std=c++14 `#-Wall` `#-Wfatal-errors` -I$HOME/prj $0 -o $0x.x -lboost_serialization && time mpirun -np 4 $0x.x $@ && rm -f $0x.x; exit #endif // (C) Copyright 2018 Alfredo A. Correa #define OMPI_SKIP_MPICXX 1 // https://github.com/open-mpi/ompi/issues/5157 #include "alf/boost/mpi3/main.hpp" #include "alf/boost/mpi3/communicator.hpp" #include "alf/boost/mpi3/process.hpp" #include "alf/boost/mpi3/shm/allocator.hpp" #include "alf/boost/mpi3/mutex.hpp" #include<random> #include<thread> //sleep_for #include<mutex> //lock_guard #include "alf/boost/multi/array.hpp" namespace mpi3 = boost::mpi3; namespace multi = boost::multi; using std::cout; int mpi3::main(int argc, char* argv[], mpi3::communicator world){ mpi3::shared_communicator node = world.split_shared(); multi::array<double, 2, mpi3::shm::allocator<double>> A({4, 5}, node); multi::array<double, 2, mpi3::shm::allocator<double>> B({1, 1}, node); multi::array<double, 2, mpi3::shm::allocator<double>> C({0, 0}, node); { multi::array<double, 2, mpi3::shm::allocator<double>> D({4, 5}, node); D.clear(); // multi::array<double, 2, mpi3::shm::allocator<double>> D(std::move(A)); std::clog << "hola" << std::endl; } { multi::array<double, 2> a({4, 5}); a.clear(); } // multi::array<double, 2> d(std::move(a)); return 0; }
28.808511
145
0.666913
bwvdg
0f79ba02d5a1e1288510a2e12629e6540e50c1c5
137
hxx
C++
src/Providers/UNIXProviders/IPsecTransportAction/UNIX_IPsecTransportAction_DARWIN.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
1
2020-10-12T09:00:09.000Z
2020-10-12T09:00:09.000Z
src/Providers/UNIXProviders/IPsecTransportAction/UNIX_IPsecTransportAction_DARWIN.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
src/Providers/UNIXProviders/IPsecTransportAction/UNIX_IPsecTransportAction_DARWIN.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
#ifdef PEGASUS_OS_DARWIN #ifndef __UNIX_IPSECTRANSPORTACTION_PRIVATE_H #define __UNIX_IPSECTRANSPORTACTION_PRIVATE_H #endif #endif
11.416667
45
0.861314
brunolauze
0f7d4b72ee6311de74e95ca6a08a59572495b787
8,364
hpp
C++
compiler/Engines/multithread-engine/specific/include/Job.hpp
toandv/IFinder
7d7c48c87034fb1f66ceb5473f516dd833f49450
[ "CECILL-B" ]
null
null
null
compiler/Engines/multithread-engine/specific/include/Job.hpp
toandv/IFinder
7d7c48c87034fb1f66ceb5473f516dd833f49450
[ "CECILL-B" ]
null
null
null
compiler/Engines/multithread-engine/specific/include/Job.hpp
toandv/IFinder
7d7c48c87034fb1f66ceb5473f516dd833f49450
[ "CECILL-B" ]
null
null
null
/** * Copyright Verimag laboratory. * * contributors: * Jacques Combaz (jacques.combaz@univ-grenoble-alpes.fr) * * This software is a computer program whose purpose is to generate * executable code from BIP models. * * This software is governed by the CeCILL-B license under French law and * abiding by the rules of distribution of free software. You can use, * modify and/ or redistribute the software under the terms of the CeCILL-B * license as circulated by CEA, CNRS and INRIA at the following URL * "http://www.cecill.info". * * As a counterpart to the access to the source code and rights to copy, * modify and redistribute granted by the license, users are provided only * with a limited warranty and the software's author, the holder of the * economic rights, and the successive licensors have only limited * liability. * * In this respect, the user's attention is drawn to the risks associated * with loading, using, modifying and/or developing or reproducing the * software by the user in light of its specific status of free software, * that may mean that it is complicated to manipulate, and that also * therefore means that it is reserved for developers and experienced * professionals having in-depth computer knowledge. Users are therefore * encouraged to load and test the software's suitability as regards their * requirements in conditions enabling the security of their systems and/or * data to be ensured and, more generally, to use and operate it in the * same conditions as regards security. * * The fact that you are presently reading this means that you have had * knowledge of the CeCILL-B license and that you accept its terms. */ #ifndef _BIP_Engine_Job_HPP_ #define _BIP_Engine_Job_HPP_ #include "BipError.hpp" #include "FastMutex.hpp" #include "ReadyQueue.hpp" #include <TimeValue.hpp> #include <Interval.hpp> #include <ModelClock.hpp> #include <NotifiableClock.hpp> #include <RealTimeClock.hpp> #include <SimulationClock.hpp> #include <Resource.hpp> class ResetableItf; class Thread; class Job { public: class Joiner; // constructors Job(ReadyQueue<Job> &readyQueue, bool highPriority = false); // destructor virtual ~Job(); // getters bool isRestarted() const { return mIsRestarted.load(); } // operations void dependsOn(ResetableItf &resetable); void execute(); void restart(); void restart(const TimeValue &time); void preventEnqueuing() { mPreventEnqueuing.fetch_add(1); } void unpreventEnqueuing(); // FIXME: ReadyQueue<Job> &readyQueue() { return mReadyQueue; } const vector<Thread *> &threads() const { return mReadyQueue.threads(); } const ModelClock &modelClock() const { return mModelClock; } const NotifiableClock &platformClock() const; static Resource &simulationClockResource() { return mSimulationClockResource; } bool isRealTime() const { return mIsRealTime; } void setIsRealTime(bool isRealTime); bool profiling() const { return mProfiling; } void setProfiling(bool profiling) { mProfiling = profiling; } unsigned int totalNbOfExecution() const { return mTotalNbOfExecutions; } const TimeValue &totalExecutionTime() const { return mTotalExecutionTime; } const TimeValue &totalPrologueTime() const { return mTotalPrologueTime; } const TimeValue &totalEpilogueTime() const { return mTotalEpilogueTime; } const TimeValue &totalWaitingTime() const { return mTotalWaitingTime; } // join mechanisms class Joiner { public: // constructors / destructors Joiner() : mNbOfJobsToJoin(0) { } virtual ~Joiner() { } void addJobToJoin(Job &job); void join(); protected: virtual void epilogue() { } const vector<Job *> &jobsToJoin() const { return mJobsToJoin; } private: vector<Job *> mJobsToJoin; atomic<unsigned int> mNbOfJobsToJoin; }; protected: // protected operations virtual void realJob() { // dummy job by default } virtual void prologue() { } virtual void epilogue() { } void enqueue(); void commonRestart(); // real-time mechanisms ModelClock &modelClock() { return mModelClock; } NotifiableClock &platformClock(); bool waitForWakeUpTime(); // real-time scheduling void setWakeUpTime(const TimeValue &wakeUpTime); const TimeValue &wakeUpTime() const { return mWakeUpTime; } void clearWakeUpTime(); bool hasWokenUpAtWakeUpTime() const { return mHasWokenUpAtWakeUpTime; } // joining mechanisms void setJoiner(Joiner &joiner) { mJoiner = &joiner; } void clearJoiner() { mJoiner = NULL; } bool hasJoiner() const { return mJoiner != NULL; } Joiner &joiner() { return *mJoiner; } // attributes ReadyQueue<Job> &mReadyQueue; bool mHighPriority; atomic<bool> mIsRestarted; atomic<bool> mIsEnqueued; atomic<unsigned int> mPreventEnqueuing; // joining mechanisms Joiner *mJoiner; // (b)locking mechanisms FastMutex mExecuting; // real-time mechanisms bool mIsRealTime; ModelClock mModelClock; RealTimeClock mRealTimeClock; SimulationClock mSimulationClock; static Resource mSimulationClockResource; // wake-up mechanisms atomic<bool> mHasWakeUpTime; bool mHasWokenUpAtWakeUpTime; TimeValue mWakeUpTime; // profiling bool mProfiling; unsigned int mTotalNbOfExecutions; TimeValue mTotalExecutionTime; TimeValue mTotalPrologueTime; TimeValue mTotalEpilogueTime; TimeValue mTotalWaitingTime; }; inline void Job::restart() { // immediate restart clearWakeUpTime(); commonRestart(); } inline void Job::restart(const TimeValue &time) { // delayed restart setWakeUpTime(time); commonRestart(); } inline void Job::commonRestart() { if (!mIsRestarted.exchange(true)) { // restarted jobs require enqueuing at some point #ifdef NDEBUG mIsEnqueued.store(false); #else bool oldIsEnqueued = mIsEnqueued.exchange(false); #endif assert(oldIsEnqueued == true); // enqueue if no before job has been restarted if (mPreventEnqueuing.load() == 0) { enqueue(); } } } inline void Job::unpreventEnqueuing() { unsigned int oldPreventEnqueuing = mPreventEnqueuing.fetch_sub(1); assert(oldPreventEnqueuing > 0); if (oldPreventEnqueuing - 1 == 0) { enqueue(); } } inline const NotifiableClock &Job::platformClock() const { if (isRealTime()) { return mRealTimeClock; } else { return mSimulationClock; } } inline NotifiableClock &Job::platformClock() { if (isRealTime()) { return mRealTimeClock; } else { return mSimulationClock; } } inline bool Job::waitForWakeUpTime() { bool ret = false; if (mHasWakeUpTime.exchange(false)) { bool hasNotifications = platformClock().wait(wakeUpTime()); ret = !hasNotifications; assert(platformClock().time() >= wakeUpTime() || !mHasWokenUpAtWakeUpTime); mWakeUpTime = TimeValue::MIN; } return ret; } inline void Job::setWakeUpTime(const TimeValue &wakeUpTime) { mWakeUpTime = wakeUpTime; mHasWokenUpAtWakeUpTime = false; #ifndef NDEBUG bool oldHasWakeUpTime = #endif mHasWakeUpTime.exchange(true); assert(!oldHasWakeUpTime); } inline void Job::clearWakeUpTime() { if (mHasWakeUpTime.exchange(false)) { mWakeUpTime = TimeValue::MIN; } platformClock().notify(); } inline void Job::Joiner::addJobToJoin(Job &job) { mJobsToJoin.push_back(&job); mNbOfJobsToJoin.fetch_add(1); assert(!job.hasJoiner()); job.setJoiner(*this); } inline void Job::Joiner::join() { unsigned int oldNbOfJobsToJoin = mNbOfJobsToJoin.fetch_sub(1); assert(oldNbOfJobsToJoin > 0); if (oldNbOfJobsToJoin - 1 == 0) { // joiner-specific epilogue epilogue(); bool empty = mJobsToJoin.empty(); assert(!empty); while (!empty) { vector<Job *>::iterator jobIt = mJobsToJoin.end() - 1; Job &job = **jobIt; // remove job from the jobs to join mJobsToJoin.erase(jobIt); // WARNING: order is critical! // it should be placed before job.epilogue()! empty = mJobsToJoin.empty(); assert(find(mJobsToJoin.begin(), mJobsToJoin.end(), &job) == mJobsToJoin.end()); // remove job's joiner job.clearJoiner(); assert(mNbOfJobsToJoin.load() == 0); // terminate job's execution job.epilogue(); } } } #endif // _BIP_Engine_Job_HPP_
25.735385
81
0.707437
toandv
0f7f6049f6ea9aeb01c13779744acd28f4ad17e4
4,895
hpp
C++
drape/batcher.hpp
kudlav/organicmaps
390236365749e0525b9229684132c2888d11369d
[ "Apache-2.0" ]
4,879
2015-09-30T10:56:36.000Z
2022-03-31T18:43:03.000Z
drape/batcher.hpp
mbrukman/omim
d22fe2b6e0beee697f096e931df97a64f9db9dc1
[ "Apache-2.0" ]
7,549
2015-09-30T10:52:53.000Z
2022-03-31T22:04:22.000Z
drape/batcher.hpp
mbrukman/omim
d22fe2b6e0beee697f096e931df97a64f9db9dc1
[ "Apache-2.0" ]
1,493
2015-09-30T10:43:06.000Z
2022-03-21T09:16:49.000Z
#pragma once #include "drape/attribute_provider.hpp" #include "drape/graphics_context.hpp" #include "drape/overlay_handle.hpp" #include "drape/pointers.hpp" #include "drape/render_bucket.hpp" #include "drape/render_state.hpp" #include "drape/vertex_array_buffer.hpp" #include "base/macros.hpp" #include <functional> #include <map> #include <vector> namespace dp { class RenderBucket; class AttributeProvider; class OverlayHandle; class Batcher { public: static uint32_t const IndexPerTriangle = 3; static uint32_t const IndexPerQuad = 6; static uint32_t const VertexPerQuad = 4; Batcher(uint32_t indexBufferSize, uint32_t vertexBufferSize); ~Batcher(); void InsertTriangleList(ref_ptr<GraphicsContext> context, RenderState const & state, ref_ptr<AttributeProvider> params); IndicesRange InsertTriangleList(ref_ptr<GraphicsContext> context, RenderState const & state, ref_ptr<AttributeProvider> params, drape_ptr<OverlayHandle> && handle); void InsertTriangleStrip(ref_ptr<GraphicsContext> context, RenderState const & state, ref_ptr<AttributeProvider> params); IndicesRange InsertTriangleStrip(ref_ptr<GraphicsContext> context, RenderState const & state, ref_ptr<AttributeProvider> params, drape_ptr<OverlayHandle> && handle); void InsertTriangleFan(ref_ptr<GraphicsContext> context, RenderState const & state, ref_ptr<AttributeProvider> params); IndicesRange InsertTriangleFan(ref_ptr<GraphicsContext> context, RenderState const & state, ref_ptr<AttributeProvider> params, drape_ptr<OverlayHandle> && handle); void InsertListOfStrip(ref_ptr<GraphicsContext> context, RenderState const & state, ref_ptr<AttributeProvider> params, uint8_t vertexStride); IndicesRange InsertListOfStrip(ref_ptr<GraphicsContext> context, RenderState const & state, ref_ptr<AttributeProvider> params, drape_ptr<OverlayHandle> && handle, uint8_t vertexStride); void InsertLineStrip(ref_ptr<GraphicsContext> context, RenderState const & state, ref_ptr<AttributeProvider> params); IndicesRange InsertLineStrip(ref_ptr<GraphicsContext> context, RenderState const & state, ref_ptr<AttributeProvider> params, drape_ptr<OverlayHandle> && handle); void InsertLineRaw(ref_ptr<GraphicsContext> context, RenderState const & state, ref_ptr<AttributeProvider> params, std::vector<int> const & indices); IndicesRange InsertLineRaw(ref_ptr<GraphicsContext> context, RenderState const & state, ref_ptr<AttributeProvider> params, std::vector<int> const & indices, drape_ptr<OverlayHandle> && handle); using TFlushFn = std::function<void (RenderState const &, drape_ptr<RenderBucket> &&)>; void StartSession(TFlushFn const & flusher); void EndSession(ref_ptr<GraphicsContext> context); void ResetSession(); void SetBatcherHash(uint64_t batcherHash); void SetFeatureMinZoom(int minZoom); private: template <typename TBatcher, typename... TArgs> IndicesRange InsertPrimitives(ref_ptr<GraphicsContext> context, RenderState const & state, ref_ptr<AttributeProvider> params, drape_ptr<OverlayHandle> && transferHandle, uint8_t vertexStride, TArgs... batcherArgs); class CallbacksWrapper; void ChangeBuffer(ref_ptr<GraphicsContext> context, ref_ptr<CallbacksWrapper> wrapper); ref_ptr<RenderBucket> GetBucket(RenderState const & state); void FinalizeBucket(ref_ptr<GraphicsContext> context, RenderState const & state); void Flush(ref_ptr<GraphicsContext> context); uint32_t const m_indexBufferSize; uint32_t const m_vertexBufferSize; uint64_t m_batcherHash = 0; TFlushFn m_flushInterface; using TBuckets = std::map<RenderState, drape_ptr<RenderBucket>>; TBuckets m_buckets; int m_featureMinZoom = 0; }; class BatcherFactory { public: BatcherFactory(uint32_t indexBufferSize, uint32_t vertexBufferSize) : m_indexBufferSize(indexBufferSize) , m_vertexBufferSize(vertexBufferSize) {} Batcher * GetNew() const; private: uint32_t const m_indexBufferSize; uint32_t const m_vertexBufferSize; }; class SessionGuard { public: SessionGuard(ref_ptr<GraphicsContext> context, Batcher & batcher, Batcher::TFlushFn const & flusher); ~SessionGuard(); private: ref_ptr<GraphicsContext> m_context; Batcher & m_batcher; DISALLOW_COPY_AND_MOVE(SessionGuard); }; } // namespace dp
36.804511
97
0.690909
kudlav
0f80b62fa4cef88c932d8280a5697722d5a21b7a
2,090
cpp
C++
chatra_emb/EmbeddedLibraries.cpp
chatra-lang/chatra
fdae457fcbd066ac8c0d44d6b763d4a18bf524f7
[ "Apache-2.0" ]
3
2019-10-14T12:25:23.000Z
2021-01-06T17:53:17.000Z
chatra_emb/EmbeddedLibraries.cpp
chatra-lang/chatra
fdae457fcbd066ac8c0d44d6b763d4a18bf524f7
[ "Apache-2.0" ]
3
2019-10-15T14:40:34.000Z
2020-08-29T14:25:06.000Z
chatra_emb/EmbeddedLibraries.cpp
chatra-lang/chatra
fdae457fcbd066ac8c0d44d6b763d4a18bf524f7
[ "Apache-2.0" ]
null
null
null
/* * Programming language 'Chatra' reference implementation * * Copyright(C) 2019-2020 Chatra Project Team * * 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. * * author: Satoshi Hosokawa (chatra.hosokawa@gmail.com) */ #include "chatra.h" #include <unordered_map> #include <atomic> #include <mutex> namespace chatra { namespace emb { namespace sys { cha::PackageInfo packageInfo(); } namespace format { cha::PackageInfo packageInfo(); } namespace regex { cha::PackageInfo packageInfo(); } namespace containers { cha::PackageInfo packageInfo(); } namespace io { cha::PackageInfo packageInfo(); } namespace random { cha::PackageInfo packageInfo(); } namespace math { cha::PackageInfo packageInfo(); } } // namespace emb static std::atomic<bool> initialized = {false}; static std::mutex mtInitialize; static std::unordered_map<std::string, cha::PackageInfo> packages; static void initialize() { std::lock_guard<std::mutex> lock(mtInitialize); if (initialized) return; std::vector<cha::PackageInfo> packageList = { emb::sys::packageInfo(), emb::format::packageInfo(), emb::regex::packageInfo(), emb::containers::packageInfo(), emb::io::packageInfo(), emb::random::packageInfo(), emb::math::packageInfo(), }; for (auto& pi : packageList) packages.emplace(pi.scripts[0].name, pi); initialized = true; } PackageInfo queryEmbeddedPackage(const std::string& packageName) { if (!initialized) initialize(); auto it = packages.find(packageName); return it != packages.cend() ? it->second : PackageInfo{{}, {}, nullptr}; } } // namespace chatra
29.43662
75
0.721053
chatra-lang
0f81fe9ca9a3c4961f7b8a02133497ae2c9fe1e1
8,733
cxx
C++
sw/3rd_party/VTK-7.1.0/Common/Color/Testing/Cxx/TestColorSeries.cxx
esean/stl_voro_fill
c569a4019ff80afbf85482c7193711ea85a7cafb
[ "MIT" ]
4
2019-05-30T01:52:12.000Z
2021-09-29T21:12:13.000Z
sw/3rd_party/VTK-7.1.0/Common/Color/Testing/Cxx/TestColorSeries.cxx
esean/stl_voro_fill
c569a4019ff80afbf85482c7193711ea85a7cafb
[ "MIT" ]
null
null
null
sw/3rd_party/VTK-7.1.0/Common/Color/Testing/Cxx/TestColorSeries.cxx
esean/stl_voro_fill
c569a4019ff80afbf85482c7193711ea85a7cafb
[ "MIT" ]
2
2019-08-30T23:36:13.000Z
2019-11-08T16:52:01.000Z
/*========================================================================= Program: Visualization Toolkit Module: TestColorSeries.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkTestErrorObserver.h" #include "vtkLookupTable.h" #include "vtkColorSeries.h" #include "vtkColor.h" #include "vtkDoubleArray.h" #include "vtkImageData.h" #include "vtkPNGWriter.h" #include "vtkPointData.h" #include "vtkSmartPointer.h" #include "vtkTesting.h" #include "vtkTestUtilities.h" #include "vtkTrivialProducer.h" #include "vtkUnsignedCharArray.h" #include <cstdio> // For EXIT_SUCCESS #define VTK_CREATE(type, name) \ vtkSmartPointer<type> name = vtkSmartPointer<type>::New() int TestColorSeries( int argc, char* argv[] ) { int valResult = vtkTesting::PASSED; vtkTesting* t = vtkTesting::New(); for ( int cc = 1; cc < argc; ++ cc ) { t->AddArgument(argv[cc]); } VTK_CREATE(vtkColorSeries,palettes); vtkColor3ub color; vtkColor3ub black( 0, 0, 0 ); // Create a new, custom palette: int pid = palettes->SetColorSchemeByName( "Foo" ); // Should return black as there are no colors: color = palettes->GetColor( 0 ); if ( ! black.Compare( color, 1 ) ) { vtkGenericWarningMacro( "Failure: GetColor on empty palette" ); valResult = vtkTesting::FAILED; } // Should return black as there are no colors: color = palettes->GetColorRepeating( 0 ); if ( ! black.Compare( color, 1 ) ) { vtkGenericWarningMacro( "Failure: GetColorRepeating on empty palette" ); valResult = vtkTesting::FAILED; } // Test appending colors: color = vtkColor3ub( 255, 255, 255 ); palettes->AddColor( color ); color = vtkColor3ub( 0, 255, 0 ); palettes->AddColor( color ); color = vtkColor3ub( 0, 0, 255 ); palettes->AddColor( color ); // Test insertion (as opposed to append): color = vtkColor3ub( 255, 0, 0 ); palettes->InsertColor( 1, color ); // Test removing a color palettes->RemoveColor( 0 ); // Iterate over all the palettes, testing GetColorRepeating // (w/ a non-empty palette) and the palette iteration API int np = palettes->GetNumberOfColorSchemes(); VTK_CREATE(vtkImageData,img); VTK_CREATE(vtkTrivialProducer,exec); VTK_CREATE(vtkUnsignedCharArray,pix); exec->SetOutput( img ); pix->SetNumberOfComponents(3); // First, find the largest number of colors in any palette: int mps = 0; // maximum palette size for ( int p = 0; p < np; ++ p ) { palettes->SetColorScheme( p ); int nc = palettes->GetNumberOfColors(); // in the current scheme if ( nc > mps ) mps = nc; } // Now size the test image properly and generate swatches pix->SetNumberOfTuples( np * 5 * mps * 5 ); pix->FillComponent( 0, 255 ); pix->FillComponent( 1, 255 ); pix->FillComponent( 2, 255 ); img->SetExtent( 0, mps * 5 - 1, 0, np * 5 - 1, 0, 0 ); img->GetPointData()->SetScalars( pix.GetPointer() ); for ( int p = 0; p < np; ++ p ) { palettes->SetColorScheme( p ); int nc = palettes->GetNumberOfColors(); // in the current scheme /* cout << " " << palettes->GetColorSchemeName() << ", " << palettes->GetNumberOfColors() << " colors\n"; */ int yoff = ( np - p - 1 ) * 5; // Put palette 0 at the top of the image for ( int c = 0; c < nc; ++ c ) { color = palettes->GetColorRepeating( c ); for ( int i = 1; i < 4; ++ i ) { for ( int j = 1; j < 4; ++ j ) { vtkIdType coord = ( ( ( yoff + i ) * mps + c ) * 5 + j ) * 3; /* cout << "i " << i << " j " << j << " c " << c << " p " << p << " off " << coord << " poff " << coord/3 << "\n"; */ pix->SetValue( coord ++, color.GetRed() ); pix->SetValue( coord ++, color.GetGreen() ); pix->SetValue( coord ++, color.GetBlue() ); } } } } /* Uncomment to save an updated test image. VTK_CREATE(vtkPNGWriter,wri); wri->SetFileName( "/tmp/TestColorSeries.png" ); wri->SetInputConnection( exec->GetOutputPort() ); wri->Write(); */ int imgResult = t->RegressionTest( exec.GetPointer(), 0.); palettes->SetColorScheme( vtkColorSeries::BREWER_SEQUENTIAL_BLUE_GREEN_9 ); // Adding a color now should create a copy of the palette. Verify the name changed. color = vtkColor3ub( 255, 255, 255 ); palettes->AddColor( color ); vtkStdString palName = palettes->GetColorSchemeName(); vtkStdString expected( "Brewer Sequential Blue-Green (9) copy" ); if ( palName != expected ) { vtkGenericWarningMacro( << "Failure: Palette copy-on-write: name should have been " << "\"" << expected.c_str() << "\" but was " << "\"" << palName.c_str() << "\" instead." ); valResult = vtkTesting::FAILED; } if ( palettes->GetNumberOfColors() != 10 ) { vtkGenericWarningMacro( << "Modified palette should have had 10 entries but had " << palettes->GetNumberOfColors() << " instead." ); valResult = vtkTesting::FAILED; } palettes->SetColorSchemeName(""); // Test bad name... should have no effect. palName = palettes->GetColorSchemeName(); if ( palName != expected ) { vtkGenericWarningMacro( << "Failure: Setting empty palette name should have no effect." ); valResult = vtkTesting::FAILED; } // Check setting a custom palette name and non-copy-on-write // behavior for custom palettes: palettes->SetColorSchemeName("Unoriginal Blue-Green"); palettes->SetColorSchemeByName("Unoriginal Blue-Green"); if ( np != palettes->GetColorScheme() ) { vtkGenericWarningMacro( << "Modified palette had ID " << palettes->GetColorScheme() << " not expected ID " << np ); valResult = vtkTesting::FAILED; } palettes->SetNumberOfColors( 8 ); if ( palettes->GetNumberOfColors() != 8 ) { vtkGenericWarningMacro( << "Resized palette should have had 8 entries but had " << palettes->GetNumberOfColors() << " instead." ); valResult = vtkTesting::FAILED; } palettes->ClearColors(); if ( palettes->GetNumberOfColors() != 0 ) { vtkGenericWarningMacro( << "Cleared palette should have had 0 entries but had " << palettes->GetNumberOfColors() << " instead." ); valResult = vtkTesting::FAILED; } // Make sure our custom scheme is still around palettes->SetColorScheme( pid ); // Now test GetColor on a non-empty palette color = palettes->GetColor( 2 ); // Should return blue vtkColor3ub blue( 0, 0, 255 ); if ( ! blue.Compare( color, 1 ) ) { vtkGenericWarningMacro( "Failure: GetColor on small test palette" ); valResult = vtkTesting::FAILED; } // Test DeepCopy VTK_CREATE(vtkColorSeries,other); other->DeepCopy(palettes); if ( other->GetColorScheme() != palettes->GetColorScheme() ) { vtkGenericWarningMacro( "Failure: DeepCopy did not preserve current scheme" ); valResult = vtkTesting::FAILED; } other->DeepCopy(NULL); // Test SetColor other->SetColorScheme( pid ); other->SetColor( 0, blue ); color = other->GetColor( 0 ); if ( ! blue.Compare( color, 1 ) ) { vtkGenericWarningMacro( "Failure: SetColor on test palette" ); valResult = vtkTesting::FAILED; } // Build a lookup table vtkLookupTable* lut = palettes->CreateLookupTable(); lut->Print(std::cout); lut->Delete(); // Test scheme out of range warning VTK_CREATE(vtkTest::ErrorObserver, warningObserver); palettes->AddObserver(vtkCommand::WarningEvent, warningObserver); palettes->SetColorScheme(1000); if (warningObserver->GetWarning()) { std::cout << "Caught expected warning: " << warningObserver->GetWarningMessage() << std::endl; } else { vtkGenericWarningMacro( "Failure: SetColorScheme(1000) did not produce expected warning" ); valResult = vtkTesting::FAILED; } vtkIndent indent; palettes->PrintSelf(std::cout, indent); t->Delete(); return ( imgResult == vtkTesting::PASSED && valResult == vtkTesting::PASSED ) ? EXIT_SUCCESS : EXIT_FAILURE; }
33.079545
96
0.611359
esean
0f82767dba14d864176d6d612e74d02352ebf845
969
cpp
C++
exercise_part_1/exercise3/white_space_file_reader.cpp
jamesjallorina/cpp_exercises
0e18511aad163510143dc66523a8111057694bff
[ "MIT" ]
1
2019-07-08T14:35:57.000Z
2019-07-08T14:35:57.000Z
exercise_part_1/exercise3/white_space_file_reader.cpp
jamesjallorina/cpp_exercises
0e18511aad163510143dc66523a8111057694bff
[ "MIT" ]
null
null
null
exercise_part_1/exercise3/white_space_file_reader.cpp
jamesjallorina/cpp_exercises
0e18511aad163510143dc66523a8111057694bff
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <ctype.h> int white_space_counter(std::ifstream &fs) { std::string buffer = ""; std::string::const_iterator itr; int number_of_white_space = 0; while( std::getline( fs, buffer )) { for(itr = buffer.begin(); itr != buffer.end(); ++itr) { if( iswspace( *itr ) ) number_of_white_space++; } } return number_of_white_space; } int main(int argc, char **argv) { if(argc < 2) { std::cout << "./white_space_file_reader [filename] \n"; return -1; } std::cout << "filename [" << argv[1] << "]\n"; std::ifstream filestream(argv[1], std::ifstream::in); if(filestream.good()) { std::cout << "file is good \n"; if(!filestream.is_open()) { std::cout << "file is not okay to open \n"; return -1; } std::cout << "file is okay to open \n"; } std::cout << "total number of white space inside the file: " << white_space_counter(filestream) << "\n"; filestream.close(); return 0; }
20.1875
105
0.619195
jamesjallorina
0f82db5b1c766f6b5711e40a438d42a38c62990b
2,847
hpp
C++
src/cpu/cpu_memory_storage.hpp
igor-byel/mkl-dnn
b03ea18e2c3a7576052c52e6c9aca7baa66d44af
[ "Apache-2.0" ]
null
null
null
src/cpu/cpu_memory_storage.hpp
igor-byel/mkl-dnn
b03ea18e2c3a7576052c52e6c9aca7baa66d44af
[ "Apache-2.0" ]
null
null
null
src/cpu/cpu_memory_storage.hpp
igor-byel/mkl-dnn
b03ea18e2c3a7576052c52e6c9aca7baa66d44af
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef CPU_MEMORY_STORAGE_HPP #define CPU_MEMORY_STORAGE_HPP #include <memory> #include "common/c_types_map.hpp" #include "common/memory.hpp" #include "common/memory_storage.hpp" #include "common/utils.hpp" namespace dnnl { namespace impl { namespace cpu { class cpu_memory_storage_t : public memory_storage_t { public: cpu_memory_storage_t(engine_t *engine) : memory_storage_t(engine), data_(nullptr, release) {} status_t init(unsigned flags, size_t size, void *handle) { // Do not allocate memory if one of these is true: // 1) size is 0 // 2) handle is nullptr and 'alloc' flag is not set if (size == 0 || (!handle && !(flags & memory_flags_t::alloc))) return status::success; if (flags & memory_flags_t::alloc) { void *data_ptr = malloc(size, 64); if (data_ptr == nullptr) return status::out_of_memory; data_ = decltype(data_)(data_ptr, destroy); } else if (flags & memory_flags_t::use_runtime_ptr) { data_ = decltype(data_)(handle, release); } return status::success; } virtual status_t get_data_handle(void **handle) const override { *handle = data_.get(); return status::success; } virtual status_t set_data_handle(void *handle) override { data_ = decltype(data_)(handle, release); return status::success; } virtual std::unique_ptr<memory_storage_t> get_sub_storage( size_t offset, size_t size) const override { void *sub_ptr = reinterpret_cast<uint8_t *>(data_.get()) + offset; auto sub_storage = new cpu_memory_storage_t(this->engine()); sub_storage->init(memory_flags_t::use_runtime_ptr, size, sub_ptr); return std::unique_ptr<memory_storage_t>(sub_storage); } private: std::unique_ptr<void, void (*)(void *)> data_; DNNL_DISALLOW_COPY_AND_ASSIGN(cpu_memory_storage_t); static void release(void *ptr) {} static void destroy(void *ptr) { free(ptr); } }; } // namespace cpu } // namespace impl } // namespace dnnl #endif
33.892857
80
0.642079
igor-byel
abeeee9ee1e0a47af59465360973f959e0a96d19
3,373
cc
C++
mindspore/lite/src/runtime/kernel/arm/fp32_grad/unsorted_segment_sum.cc
LottieWang/mindspore
1331c7e432fb691d1cfa625ab7cc7451dcfc7ce0
[ "Apache-2.0" ]
1
2021-07-03T06:52:20.000Z
2021-07-03T06:52:20.000Z
mindspore/lite/src/runtime/kernel/arm/fp32_grad/unsorted_segment_sum.cc
Ming-blue/mindspore
9ec8bc233c76c9903a2f7be5dfc134992e4bf757
[ "Apache-2.0" ]
null
null
null
mindspore/lite/src/runtime/kernel/arm/fp32_grad/unsorted_segment_sum.cc
Ming-blue/mindspore
9ec8bc233c76c9903a2f7be5dfc134992e4bf757
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2021 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/runtime/kernel/arm/fp32_grad/unsorted_segment_sum.h" #include <vector> #include <algorithm> #include "schema/model_generated.h" #include "src/kernel_registry.h" #include "nnacl/base/unsorted_segment_sum_base.h" #include "include/errorcode.h" using mindspore::kernel::KERNEL_ARCH; using mindspore::lite::KernelRegistrar; using mindspore::lite::RET_ERROR; using mindspore::lite::RET_OK; using mindspore::schema::PrimitiveType_UnsortedSegmentSum; namespace mindspore::kernel { int UnsortedSegmentSumCPUKernel::Init() { if (!InferShapeDone()) { return RET_OK; } auto input_shape = in_tensors_.at(0)->shape(); auto segment_ids_shape = in_tensors_.at(1)->shape(); auto output_shape = out_tensors_.at(0)->shape(); unit_num_ = 1; input_dim1_ = 1; for (size_t i = 0; i < input_shape.size(); ++i) { unit_num_ *= input_shape[i]; if (i >= segment_ids_shape.size()) { input_dim1_ *= input_shape[i]; } } output_dim0_ = output_shape[0]; output_dim1_ = 1; for (size_t j = 1; j < output_shape.size(); j++) { output_dim1_ *= output_shape[j]; } return RET_OK; } int UnsortedSegmentSumCPUKernel::ReSize() { return RET_OK; } int UnsortedSegmentSumRun(void *cdata, int task_id, float lhs_scale, float rhs_scale) { MS_ASSERT(cdata != nullptr); auto kernel = reinterpret_cast<UnsortedSegmentSumCPUKernel *>(cdata); auto error_code = kernel->Execute(task_id); if (error_code != RET_OK) { MS_LOG(ERROR) << "UnsortedSegmentSum Run error task_id[" << task_id << "] error_code[" << error_code << "]"; return RET_ERROR; } return RET_OK; } int UnsortedSegmentSumCPUKernel::Run() { int error_code = ParallelLaunch(this->ms_context_, UnsortedSegmentSumRun, this, 1); if (error_code != RET_OK) { MS_LOG(ERROR) << "Strided slice error error_code[" << error_code << "]"; return RET_ERROR; } return RET_OK; } int UnsortedSegmentSumCPUKernel::Execute(int task_id) { int ret; auto input_tensor = in_tensors_.at(0); auto indices_tensor = in_tensors_.at(1); auto output_tensor = out_tensors_.at(0); float *input = reinterpret_cast<float *>(input_tensor->data_c()); int *indices = reinterpret_cast<int *>(indices_tensor->data_c()); float *output = reinterpret_cast<float *>(output_tensor->MutableData()); std::fill(output, output + output_tensor->ElementsNum(), 0.f); ret = UnsortedSegmentSum(float, int, input, unit_num_, input_dim1_, indices, output, output_dim0_, output_dim1_); if (ret != RET_OK) { MS_LOG(ERROR) << "StridedSliceGrad error error_code[" << ret << "]"; return RET_ERROR; } return RET_OK; } REG_KERNEL(kCPU, kNumberTypeFloat32, PrimitiveType_UnsortedSegmentSum, LiteKernelCreator<UnsortedSegmentSumCPUKernel>) } // namespace mindspore::kernel
35.135417
118
0.722502
LottieWang
abf08a48fb387ff01feb50583eaa24bfc1992168
787
cpp
C++
src/allegro_flare/circle.cpp
MarkOates/allegro_flare
b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7
[ "MIT" ]
25
2015-03-30T02:02:43.000Z
2019-03-04T22:29:12.000Z
src/allegro_flare/circle.cpp
MarkOates/allegro_flare
b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7
[ "MIT" ]
122
2015-04-01T08:15:26.000Z
2019-10-16T20:31:22.000Z
src/allegro_flare/circle.cpp
MarkOates/allegro_flare
b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7
[ "MIT" ]
4
2016-09-02T12:14:09.000Z
2018-11-23T20:38:49.000Z
#include <allegro_flare/circle.h> #include <AllegroFlare/Color.hpp> #include <AllegroFlare/Useful.hpp> // for distance namespace allegro_flare { UISurfaceAreaCircle::UISurfaceAreaCircle(float x, float y, float r) : UISurfaceAreaBase(x, y, r*2, r*2) {} bool UISurfaceAreaCircle::collides(float x, float y) { placement.transform_coordinates(&x, &y); return AllegroFlare::distance(placement.size.x/2, placement.size.y/2, x, y) <= placement.size.x/2; } void UISurfaceAreaCircle::draw_bounding_area() { placement.start_transform(); al_draw_circle(placement.size.x/2, placement.size.y/2, placement.size.x/2, AllegroFlare::color::color(AllegroFlare::color::aliceblue, 0.2), 3.0); placement.restore_transform(); } }
19.675
151
0.691233
MarkOates
abf2ae9e45d883a785c4ebadedc56dde87cd53cd
4,622
cxx
C++
modules/ITK/examples/itkBuildShapeModel.cxx
skn123/statismo-1
a380f33cf070d1c4ba624db8b0c6d946d2aecabf
[ "BSD-3-Clause" ]
14
2020-04-28T17:24:01.000Z
2021-07-20T11:54:59.000Z
modules/ITK/examples/itkBuildShapeModel.cxx
latimagine/statismo
a380f33cf070d1c4ba624db8b0c6d946d2aecabf
[ "BSD-3-Clause" ]
8
2020-01-22T09:05:00.000Z
2021-06-29T10:10:24.000Z
modules/ITK/examples/itkBuildShapeModel.cxx
latimagine/statismo
a380f33cf070d1c4ba624db8b0c6d946d2aecabf
[ "BSD-3-Clause" ]
6
2020-03-11T19:41:06.000Z
2021-09-07T12:57:20.000Z
/* * This file is part of the statismo library. * * Author: Marcel Luethi (marcel.luethi@unibas.ch) * * Copyright (c) 2011 University of Basel * 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 the project's author nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "statismo/core/LoggerMultiHandlersThreaded.h" #include "statismo/ITK/itkDataManager.h" #include "statismo/ITK/itkPCAModelBuilder.h" #include "statismo/ITK/itkStandardMeshRepresenter.h" #include "statismo/ITK/itkIO.h" #include "statismo/ITK/itkStatisticalModel.h" #include "statismo/ITK/itkUtils.h" #include "statismo/ITK/itkStatismoOutputWindow.h" #include <itkMesh.h> #include <itkMeshFileWriter.h> #include <itkMeshFileReader.h> #include <iostream> /* * This example shows the ITK Wrapping of statismo can be used to build a shape model. */ namespace { constexpr unsigned gk_dimensions = 3; using MeshType = itk::Mesh<float, gk_dimensions>; using RepresenterType = itk::StandardMeshRepresenter<float, gk_dimensions>; void DoRunExample(const char * referenceFilename, const char * dir, const char * modelname) { using ModelBuilderType = itk::PCAModelBuilder<MeshType>; using DataManagerType = itk::DataManager<MeshType>; using MeshReaderType = itk::MeshFileReader<MeshType>; // Background logger statismo::LoggerMultiHandlersThreaded logger{ std::make_unique<statismo::BasicLogHandler>( statismo::StdOutLogWriter(), statismo::DefaultFormatter()), statismo::LogLevel::LOG_DEBUG, true }; logger.Start(); // Redirect ITK log to Statismo logger auto itkToStatismoLogger = itk::StatismoOutputWindow::New(); itkToStatismoLogger->SetLogger(&logger); itk::StatismoOutputWindow::SetInstance(itkToStatismoLogger); auto representer = RepresenterType::New(); representer->SetLogger(&logger); auto refReader = MeshReaderType::New(); refReader->SetFileName(referenceFilename); refReader->Update(); representer->SetReference(refReader->GetOutput()); auto filenames = statismo::itk::GetDirFiles(dir, ".vtk"); auto dataManager = DataManagerType::New(); dataManager->SetRepresenter(representer); for (const auto & file : filenames) { auto fullpath = std::string(dir) + "/" + file; auto reader = MeshReaderType::New(); reader->SetFileName(fullpath.c_str()); reader->Update(); MeshType::Pointer mesh = reader->GetOutput(); dataManager->AddDataset(mesh, fullpath.c_str()); } auto pcaModelBuilder = ModelBuilderType::New(); pcaModelBuilder->SetLogger(&logger); auto model = pcaModelBuilder->BuildNewModel(dataManager->GetData(), 0); itk::StatismoIO<MeshType>::SaveStatisticalModel(model, modelname); } } // namespace int main(int argc, char * argv[]) { if (argc < 4) { std::cerr << "usage " << argv[0] << " referenceShape shapeDir modelname" << std::endl; return 1; } const char * reference = argv[1]; const char * dir = argv[2]; const char * modelname = argv[3]; DoRunExample(reference, dir, modelname); std::cout << "Model building is completed successfully." << std::endl; return 0; }
34.75188
109
0.722198
skn123
abf3888dd90afc21d9d659bb4465accdd8a2cab0
1,983
cc
C++
src/Foundational/data_source/tlarge.cc
michaelweiss092/LillyMol
a2b7d1d8a07ef338c754a0a2e3b2624aac694cc9
[ "Apache-2.0" ]
53
2018-06-01T13:16:15.000Z
2022-02-23T21:04:28.000Z
src/Foundational/data_source/tlarge.cc
IanAWatson/LillyMol-4.0-Bazel
f38f23a919c622c31280222f8a90e6ab7d871b93
[ "Apache-2.0" ]
19
2018-08-14T13:43:18.000Z
2021-09-24T12:53:11.000Z
src/Foundational/data_source/tlarge.cc
IanAWatson/LillyMol-4.0-Bazel
f38f23a919c622c31280222f8a90e6ab7d871b93
[ "Apache-2.0" ]
19
2018-10-23T19:41:01.000Z
2022-02-17T08:14:00.000Z
#include <stdlib.h> #include <unistd.h> /* Tester for large file source */ #include "cmdline.h" #include "Large_File.h" static int verbose = 0; static void usage (int rc) { cerr << "Tester for large file reader\n"; cerr << " -e echo input file\n"; cerr << " -v verbose output\n"; exit (rc); } static int do_test_echo (IW_Large_File & input, int output) { IWString buffer; char newline = '\n'; while (input.next_record (buffer)) { (void) write (output, buffer.rawchars (), buffer.length ()); write (output, &newline, sizeof (newline)); } return 1; } static int do_test_echo (const char * fname, int output) { IW_Large_File input (fname); if (! input.ok ()) { cerr << "Cannot open '" << fname << "'\n"; return 0; } return do_test_echo (input, output); } static int tlarge (IW_Large_File & input) { IWString buffer; while (input.next_record (buffer)) { } cerr << "Read " << input.records_read () << " records\n"; return 1; } static int tlarge (const char * fname) { IW_Large_File input; if (! input.open (fname)) { cerr << "Cannot open via open () '" << fname << "'\n"; return 0; } return tlarge (input); } static int tlarge (int argc, char ** argv) { Command_Line cl (argc, argv, "ve"); if (cl.unrecognised_options_encountered ()) { cerr << "unrecognised options encountered\n"; usage (3); } verbose = cl.option_count ('v'); if (0 == cl.number_elements ()) { cerr << "Insufficient arguments\n"; usage (3); } int test_echo = 0; if (cl.option_present ('e')) { test_echo = 1; } int rc; for (int i = 0; i < cl.number_elements (); i++) { if (test_echo) rc = do_test_echo (cl[i], 1); else rc = tlarge (cl[i]); if (0 == rc) { rc = i + 1; break; } } return rc; } int main (int argc, char ** argv) { int rc = tlarge (argc, argv); return rc; }
14.909774
64
0.569339
michaelweiss092
abf465685e459616242659562e0044675609eb29
7,435
hxx
C++
BeastHttp/include/http/base/impl/cb.hxx
Lyoko-Jeremie/BeastHttp
6121cba601a115a638c7c56cd2eb87e5e4eec14b
[ "BSD-2-Clause" ]
2
2022-03-18T10:02:17.000Z
2022-03-18T14:05:35.000Z
BeastHttp/include/http/base/impl/cb.hxx
Lyoko-Jeremie/BeastHttp
6121cba601a115a638c7c56cd2eb87e5e4eec14b
[ "BSD-2-Clause" ]
null
null
null
BeastHttp/include/http/base/impl/cb.hxx
Lyoko-Jeremie/BeastHttp
6121cba601a115a638c7c56cd2eb87e5e4eec14b
[ "BSD-2-Clause" ]
2
2022-03-18T10:02:22.000Z
2022-03-27T01:09:44.000Z
#ifndef BEASTHTTP_BASE_IMPL_CB_HXX #define BEASTHTTP_BASE_IMPL_CB_HXX #include <http/base/config.hxx> #include <functional> namespace _0xdead4ead { namespace http { namespace base { namespace cb { namespace detail { #ifndef BEASTHTTP_CXX17_IF_CONSTEXPR template<std::size_t value> using size_type = std::integral_constant<std::size_t, value>; template <class Begin, class End, typename S, class... Elements> struct for_each_impl { void operator()(const std::tuple<Elements...>& tpl, const Begin& begin, const End& end) { const auto& value = std::get<S::value>(tpl); begin(value); for_each_impl<Begin, End, size_type<S() + 1>, Elements...>{}(tpl, begin, end); } }; // struct for_each_impl template <class Begin, class End, class... Elements> struct for_each_impl<Begin, End, size_type<std::tuple_size<std::tuple<Elements...>>::value - 1>, Elements...> { void operator()(const std::tuple<Elements...>& tpl, const Begin& begin, const End& end) { const auto& value = std::get<size_type<std::tuple_size< std::tuple<Elements...>>::value - 1>::value>(tpl); end(value); (void)begin; } }; // struct for_each_impl template<std::size_t Index, class Begin, class End, class... Elements> void for_each(const std::tuple<Elements...>& tpl, const Begin& begin, const End& end) { for_each_impl<Begin, End, size_type<Index>, Elements...>{}(tpl, begin, end); } #else template<std::size_t Index, class Begin, class End, class... Elements> void for_each(const std::tuple<Elements...>& tpl, const Begin& begin, const End& end) { const auto& value = std::get<Index>(tpl); if constexpr (Index + 1 == std::tuple_size<std::tuple<Elements...>>::value) end(value); else { begin(value); for_each<Index + 1, Begin, End, Elements...>(tpl, begin, end); } } #endif // BEASTHTTP_CXX17_IF_CONSTEXPR #ifndef BEASTHTTP_CXX14_GENERIC_LAMBDAS template<class Container> struct cb_push_cxx11 { using container_type = Container; using value_type = typename container_type::value_type; Container& l_; cb_push_cxx11(Container& l) : l_{l} { } template<class F> void operator()(const F& value) const { l_.push_back( value_type( std::bind<void>( value, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3))); } }; // struct cb_push_cxx11 template<class Container> struct cb_push_fin_cxx11 { using container_type = Container; using value_type = typename container_type::value_type; Container& l_; cb_push_fin_cxx11(Container& l) : l_{l} { } template<class F> void operator()(const F& value) const { l_.push_back( value_type( std::bind<void>( value, std::placeholders::_1, std::placeholders::_2))); } }; // struct cb_push_fin_cxx11 #endif // BEASTHTTP_CXX14_GENERIC_LAMBDAS } // namespace detail template<class Request, class SessionFlesh, class Storage> void executor::execute(Request& request, SessionFlesh& session_flesh, Storage& storage) { storage.begin_exec(request, session_flesh)(); } BEASTHTTP_DECLARE_STORAGE_TEMPLATE const_iterator<Session, Entry, Container>::const_iterator( const container_type& container, request_type& request, session_flesh& flesh) : pos_{0}, cont_begin_iter_{container.begin()}, cont_end_iter_{container.end()}, request_{request}, session_flesh_{flesh}, current_target_{request_.target().to_string()} { if (container.size() > 1) skip_target(); } BEASTHTTP_DECLARE_STORAGE_TEMPLATE typename const_iterator<Session, Entry, Container>::self_type& const_iterator<Session, Entry, Container>::operator++() { cont_begin_iter_++; pos_++; if (cont_begin_iter_ == cont_end_iter_) { cont_begin_iter_--; pos_--; } skip_target(); return *this; } BEASTHTTP_DECLARE_STORAGE_TEMPLATE typename const_iterator<Session, Entry, Container>::self_type const_iterator<Session, Entry, Container>::operator++(int) { self_type _tmp{*this}; ++(*this); return _tmp; } BEASTHTTP_DECLARE_STORAGE_TEMPLATE void const_iterator<Session, Entry, Container>::operator()() const { session_context _ctx{session_flesh_}; (*cont_begin_iter_) (request_, std::move(_ctx), *this); } BEASTHTTP_DECLARE_STORAGE_TEMPLATE void const_iterator<Session, Entry, Container>::skip_target() { std::size_t pos = current_target_.find('/', 1); if (pos != std::string::npos) { auto next_target = current_target_.substr(0, pos); current_target_ = current_target_.substr(pos); request_.target(next_target); } else request_.target(current_target_); } BEASTHTTP_DECLARE_STORAGE_TEMPLATE typename const_iterator<Session, Entry, Container>::size_type const_iterator<Session, Entry, Container>::pos() const { return pos_; } BEASTHTTP_DECLARE_STORAGE_TEMPLATE template<class F, class... Fn, typename> storage<Session, Entry, Container>::storage(F&& f, Fn&&... fn) : container_{prepare(std::forward<F>(f), std::forward<Fn>(fn)...)} { } BEASTHTTP_DECLARE_STORAGE_TEMPLATE template<class... OnRequest> typename storage<Session, Entry, Container>::container_type storage<Session, Entry, Container>::prepare(OnRequest&&... on_request) { container_type _l; const auto& tuple_cb = std::make_tuple( std::forward<OnRequest>(on_request)...); static_assert(std::tuple_size<typename std::decay< decltype (tuple_cb) >::type>::value != 0, "Oops...! tuple is empty."); #ifndef BEASTHTTP_CXX14_GENERIC_LAMBDAS detail::for_each<0>(tuple_cb, detail::cb_push_cxx11<container_type>{_l}, detail::cb_push_fin_cxx11<container_type>{_l}); #else detail::for_each<0>(tuple_cb, [&_l](const auto& value){ _l.push_back( entry_type( std::bind<void>( value, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)));}, [&_l](const auto & value){ _l.push_back( entry_type( std::bind<void>( value, std::placeholders::_1, std::placeholders::_2)));}); #endif // BEASTHTTP_CXX14_GENERIC_LAMBDAS return _l; } BEASTHTTP_DECLARE_STORAGE_TEMPLATE typename storage<Session, Entry, Container>::iterator_type storage<Session, Entry, Container>::begin_exec( request_type& request, session_flesh& flesh) { return iterator_type(container_, request, flesh); } } // namespace cb } // namespace base } // namespace http } // namespace _0xdead4ead #endif // not defined BEASTHTTP_BASE_IMPL_CB_HXX
26.938406
80
0.609953
Lyoko-Jeremie
abf5c375d92ad65a76155a67f06e53c1f32664bd
5,529
cc
C++
Geometry/TrackerGeometryBuilder/test/GeoHierarchyTest.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
Geometry/TrackerGeometryBuilder/test/GeoHierarchyTest.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
Geometry/TrackerGeometryBuilder/test/GeoHierarchyTest.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
// -*- C++ -*- // /* Description: <one line class summary> Implementation: <Notes on implementation> */ // // Original Author: Riccardo Ranieri // Created: Wed May 3 10:30:00 CEST 2006 // // // system include files #include <memory> // user include files #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "Geometry/CommonDetUnit/interface/TrackingGeometry.h" #include "Geometry/Records/interface/TrackerDigiGeometryRecord.h" #include "Geometry/TrackerNumberingBuilder/interface/GeometricDet.h" #include "Geometry/CommonDetUnit/interface/GeomDet.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h" #include "Geometry/TrackerGeometryBuilder/interface/trackerHierarchy.h" #include "DataFormats/Common/interface/Trie.h" #include "DataFormats/TrackerCommon/interface/TrackerTopology.h" #include <string> #include <iostream> template <typename Det> struct Print { // typedef edm::TrieNode<Det> const node; void operator()(Det det, std::string const& label) const { if (!det) return; for (char i : label) std::cout << int(i) << '/'; std::cout << " " << det->geographicalId().rawId() << std::endl; } }; class GeoHierarchy : public edm::one::EDAnalyzer<> { public: explicit GeoHierarchy(const edm::ParameterSet&); ~GeoHierarchy() override; void beginJob() override {} void analyze(edm::Event const& iEvent, edm::EventSetup const&) override; void endJob() override {} private: // ----------member data --------------------------- bool fromDDD_; bool printDDD_; }; GeoHierarchy::GeoHierarchy(const edm::ParameterSet& ps) { fromDDD_ = ps.getParameter<bool>("fromDDD"); printDDD_ = ps.getUntrackedParameter<bool>("printDDD", true); } GeoHierarchy::~GeoHierarchy() {} template <typename Iter> void constructAndDumpTrie(const TrackerTopology* tTopo, Iter b, Iter e) { typedef typename std::iterator_traits<Iter>::value_type Det; edm::Trie<Det> trie(nullptr); typedef edm::TrieNode<Det> Node; typedef Node const* node_pointer; // sigh.... typedef edm::TrieNodeIter<Det> node_iterator; std::cout << "In Tracker Geom there are " << e - b << " modules" << std::endl; Iter last = b; try { for (; b != e; ++b) { last = b; unsigned int rawid = (*b)->geographicalId().rawId(); trie.insert(trackerHierarchy(tTopo, rawid), *b); } } catch (edm::Exception const& ex) { std::cout << "in filling " << ex.what() << std::endl; unsigned int rawid = (*last)->geographicalId().rawId(); int subdetid = (*last)->geographicalId().subdetId(); std::cout << rawid << " " << subdetid << std::endl; } try { Print<Det> pr; edm::walkTrie(pr, *trie.initialNode()); std::cout << std::endl; unsigned int layerId[] = {1, 3, 5, 21, 22, 41, 42, 61, 62}; int layerSize[9]; for (int i = 0; i < 9; i++) { std::string s; if (layerId[i] > 9) s += char(layerId[i] / 10); s += char(layerId[i] % 10); node_iterator eit; node_iterator p(trie.node(s)); layerSize[i] = std::distance(p, eit); } edm::LogInfo("TkDetLayers") << "------ Geometry constructed with: ------" << "\n" << "n pxlBarLayers: " << layerSize[0] << "\n" << "n tibLayers: " << layerSize[1] << "\n" << "n tobLayers: " << layerSize[2] << "\n" << "n negPxlFwdLayers: " << layerSize[3] << "\n" << "n posPxlFwdLayers: " << layerSize[4] << "\n" << "n negTidLayers: " << layerSize[5] << "\n" << "n posTidLayers: " << layerSize[6] << "\n" << "n negTecLayers: " << layerSize[7] << "\n" << "n posTecLayers: " << layerSize[8] << "\n"; // << "n barreLayers: " << this->barrelLayers().size() << "\n" //<< "n negforwardLayers: " << this->negForwardLayers().size() << "\n" //<< "n posForwardLayers: " << this->posForwardLayers().size() ; } catch (edm::Exception const& ex) { std::cout << "in walking " << ex.what() << std::endl; } } // ------------ method called to produce the data ------------ void GeoHierarchy::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { edm::LogInfo("GeoHierarchy") << "begins"; //first instance tracking geometry edm::ESHandle<TrackerGeometry> pDD; iSetup.get<TrackerDigiGeometryRecord>().get(pDD); edm::ESHandle<TrackerTopology> tTopo_handle; iSetup.get<TrackerTopologyRcd>().get(tTopo_handle); const TrackerTopology* tTopo = tTopo_handle.product(); // GeometricDet const* rDD = pDD->trackerDet(); std::vector<const GeometricDet*> modules; (*rDD).deepComponents(modules); std::cout << "\nGeometricDet Hierarchy\n" << std::endl; constructAndDumpTrie(tTopo, modules.begin(), modules.end()); std::cout << "\nGDet Hierarchy\n" << std::endl; constructAndDumpTrie(tTopo, pDD->dets().begin(), pDD->dets().end()); } //define this as a plug-in DEFINE_FWK_MODULE(GeoHierarchy);
33.307229
85
0.612226
ckamtsikis
abf64bc5c06a1773c952e6c7e32a5c44d0c5f2cb
549
cpp
C++
spec/cpp/tests/timing/ClockTests.cpp
NeoResearch/libbft
6608f7f3cc90d976c06d54d42b72ec9eb5df5a25
[ "MIT" ]
21
2019-07-24T22:06:33.000Z
2021-11-29T08:36:58.000Z
spec/cpp/tests/timing/ClockTests.cpp
NeoResearch/libbft
6608f7f3cc90d976c06d54d42b72ec9eb5df5a25
[ "MIT" ]
35
2019-09-30T21:18:56.000Z
2020-03-03T01:50:48.000Z
spec/cpp/tests/timing/ClockTests.cpp
NeoResearch/libbft
6608f7f3cc90d976c06d54d42b72ec9eb5df5a25
[ "MIT" ]
3
2019-12-26T02:53:43.000Z
2021-03-19T03:55:11.000Z
#include <thread> #include <gtest/gtest.h> #include "timing/Clock.hpp" using namespace std; using namespace libbft; TEST(TimingClock, ToString) { unique_ptr<Clock> clock(new Clock("T")); EXPECT_EQ("Clock {name='T'}", clock->toString()); } TEST(TimingClock, GetTime) { unique_ptr<Clock> clock(new Clock("T")); auto actualTime = clock->getTime(); EXPECT_LT(0, actualTime); this_thread::sleep_for(chrono::milliseconds(200)); EXPECT_LT(0.19, clock->getTime() - actualTime); EXPECT_GT(0.8, clock->getTime() - actualTime); }
22.875
53
0.688525
NeoResearch
abf73340941f3a6115e777ae5e7173933db9d853
1,062
cpp
C++
problemsets/Codejam/2017/ROUND1B/A/a.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/Codejam/2017/ROUND1B/A/a.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/Codejam/2017/ROUND1B/A/a.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
/** * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * */ #define _USE_MATH_DEFINES #include <bits/stdc++.h> using namespace std; #define pb push_back #define mp make_pair #define mt make_tuple #define fi first #define se second #define sz(v) ((int) (v).size()) #define all(v) (v).begin(), (v).end() #define sqr(x) ((x)*(x)) typedef pair<int, int> pii; typedef long long ll; typedef vector<int> vi; typedef vector<double> vd; typedef vector<char> vc; typedef vector<string> ent; const double EPS = 1E-10; inline int cmp(double x, double y = 0, double tol = EPS) { return (x <= y + tol) ? (x + tol < y) ? -1 : 0 : 1; } int main() { // setbuf(stdout, NULL); // ios::sync_with_stdio(0); int TT; cin >> TT; for (int tt = 1; tt <= TT; tt++) { cout << "Case #" << tt << ": "; int D, N; cin >> D >> N; double tm = 0; for (int i = 0; i < N; i++) { int k, s; cin >> k >> s; double t = (D-k)/(double)s; if (cmp(tm,t) < 0) tm = t; } cout << fixed << setprecision(6) << D/tm << endl; } return 0; }
18.964286
58
0.577213
juarezpaulino
abfa449d8085c5bbc3a2784041e546a194a16308
3,207
hpp
C++
gecode/iter/ranges-rangelist.hpp
LeslieW/gecode-clone
ab3ab207c98981abfe4c52f01b248ec7bc4e8e8c
[ "MIT-feh" ]
null
null
null
gecode/iter/ranges-rangelist.hpp
LeslieW/gecode-clone
ab3ab207c98981abfe4c52f01b248ec7bc4e8e8c
[ "MIT-feh" ]
null
null
null
gecode/iter/ranges-rangelist.hpp
LeslieW/gecode-clone
ab3ab207c98981abfe4c52f01b248ec7bc4e8e8c
[ "MIT-feh" ]
null
null
null
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Guido Tack <tack@gecode.org> * * Copyright: * Guido Tack, 2011 * * Last modified: * $Date$ by $Author$ * $Revision$ * * This file is part of Gecode, the generic constraint * development environment: * http://www.gecode.org * * 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. * */ namespace Gecode { namespace Iter { namespace Ranges { /** * \brief %Range iterator for range lists * * Allows to iterate the ranges of a RangeList where the * ranges must be increasing and non-overlapping. * * \ingroup FuncIterRanges */ class RangeList { protected: /// Current range const Gecode::RangeList* c; public: /// \name Constructors and initialization //@{ /// Default constructor RangeList(void); /// Initialize with BndSet \a s RangeList(const Gecode::RangeList* s); /// Initialize with BndSet \a s void init(const Gecode::RangeList* s); //@} /// \name Iteration control //@{ /// Test whether iterator is still at a range or done bool operator ()(void) const; /// Move iterator to next range (if possible) void operator ++(void); //@} /// \name Range access //@{ /// Return smallest value of range int min(void) const; /// Return largest value of range int max(void) const; /// Return width of range (distance between minimum and maximum) unsigned int width(void) const; //@} }; forceinline RangeList::RangeList(void) {} forceinline RangeList::RangeList(const Gecode::RangeList* s) : c(s) {} forceinline void RangeList::init(const Gecode::RangeList* s) { c = s; } forceinline bool RangeList::operator ()(void) const { return c != NULL; } forceinline void RangeList::operator ++(void) { c = c->next(); } forceinline int RangeList::min(void) const { return c->min(); } forceinline int RangeList::max(void) const { return c->max(); } forceinline unsigned int RangeList::width(void) const { return c->width(); } }}} // STATISTICS: iter-any
27.646552
74
0.664172
LeslieW
abfcc2cdffcf23f0d8427cb5d2994f80ff70ef75
5,329
cc
C++
test/string_view_test.cc
WilliamTambellini/cpu_features
20fa92a02ae724f4532b7e12691633a43dec7772
[ "Apache-2.0" ]
5
2020-12-19T06:56:06.000Z
2022-01-09T01:28:42.000Z
test/string_view_test.cc
WilliamTambellini/cpu_features
20fa92a02ae724f4532b7e12691633a43dec7772
[ "Apache-2.0" ]
1
2021-09-27T06:00:40.000Z
2021-09-27T06:00:40.000Z
test/string_view_test.cc
WilliamTambellini/cpu_features
20fa92a02ae724f4532b7e12691633a43dec7772
[ "Apache-2.0" ]
3
2020-12-19T06:56:27.000Z
2021-09-26T18:50:44.000Z
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "internal/string_view.h" #include "gtest/gtest.h" namespace cpu_features { bool operator==(const StringView& a, const StringView& b) { return CpuFeatures_StringView_IsEquals(a, b); } namespace { TEST(StringViewTest, Empty) { EXPECT_EQ(kEmptyStringView.ptr, nullptr); EXPECT_EQ(kEmptyStringView.size, 0); } TEST(StringViewTest, Build) { const auto view = str("test"); EXPECT_EQ(view.ptr[0], 't'); EXPECT_EQ(view.size, 4); } TEST(StringViewTest, CpuFeatures_StringView_IndexOfChar) { // Found. EXPECT_EQ(CpuFeatures_StringView_IndexOfChar(str("test"), 'e'), 1); // Not found. EXPECT_EQ(CpuFeatures_StringView_IndexOfChar(str("test"), 'z'), -1); // Empty. EXPECT_EQ(CpuFeatures_StringView_IndexOfChar(kEmptyStringView, 'z'), -1); } TEST(StringViewTest, CpuFeatures_StringView_IndexOf) { // Found. EXPECT_EQ(CpuFeatures_StringView_IndexOf(str("test"), str("es")), 1); // Not found. EXPECT_EQ(CpuFeatures_StringView_IndexOf(str("test"), str("aa")), -1); // Empty. EXPECT_EQ(CpuFeatures_StringView_IndexOf(kEmptyStringView, str("aa")), -1); EXPECT_EQ(CpuFeatures_StringView_IndexOf(str("aa"), kEmptyStringView), -1); } TEST(StringViewTest, CpuFeatures_StringView_StartsWith) { EXPECT_TRUE(CpuFeatures_StringView_StartsWith(str("test"), str("te"))); EXPECT_FALSE(CpuFeatures_StringView_StartsWith(str("test"), str(""))); EXPECT_FALSE( CpuFeatures_StringView_StartsWith(str("test"), kEmptyStringView)); EXPECT_FALSE( CpuFeatures_StringView_StartsWith(kEmptyStringView, str("test"))); } TEST(StringViewTest, CpuFeatures_StringView_IsEquals) { EXPECT_TRUE( CpuFeatures_StringView_IsEquals(kEmptyStringView, kEmptyStringView)); EXPECT_TRUE(CpuFeatures_StringView_IsEquals(kEmptyStringView, str(""))); EXPECT_TRUE(CpuFeatures_StringView_IsEquals(str(""), kEmptyStringView)); EXPECT_TRUE(CpuFeatures_StringView_IsEquals(str("a"), str("a"))); EXPECT_FALSE(CpuFeatures_StringView_IsEquals(str("a"), str("b"))); EXPECT_FALSE(CpuFeatures_StringView_IsEquals(str("a"), kEmptyStringView)); EXPECT_FALSE(CpuFeatures_StringView_IsEquals(kEmptyStringView, str("a"))); } TEST(StringViewTest, CpuFeatures_StringView_PopFront) { EXPECT_EQ(CpuFeatures_StringView_PopFront(str("test"), 2), str("st")); EXPECT_EQ(CpuFeatures_StringView_PopFront(str("test"), 0), str("test")); EXPECT_EQ(CpuFeatures_StringView_PopFront(str("test"), 4), str("")); EXPECT_EQ(CpuFeatures_StringView_PopFront(str("test"), 100), str("")); } TEST(StringViewTest, CpuFeatures_StringView_ParsePositiveNumber) { EXPECT_EQ(CpuFeatures_StringView_ParsePositiveNumber(str("42")), 42); EXPECT_EQ(CpuFeatures_StringView_ParsePositiveNumber(str("0x2a")), 42); EXPECT_EQ(CpuFeatures_StringView_ParsePositiveNumber(str("0x2A")), 42); EXPECT_EQ(CpuFeatures_StringView_ParsePositiveNumber(str("-0x2A")), -1); EXPECT_EQ(CpuFeatures_StringView_ParsePositiveNumber(str("abc")), -1); EXPECT_EQ(CpuFeatures_StringView_ParsePositiveNumber(str("")), -1); } TEST(StringViewTest, CpuFeatures_StringView_CopyString) { char buf[4]; buf[0] = 'X'; // Empty CpuFeatures_StringView_CopyString(str(""), buf, sizeof(buf)); EXPECT_STREQ(buf, ""); // Less CpuFeatures_StringView_CopyString(str("a"), buf, sizeof(buf)); EXPECT_STREQ(buf, "a"); // exact CpuFeatures_StringView_CopyString(str("abc"), buf, sizeof(buf)); EXPECT_STREQ(buf, "abc"); // More CpuFeatures_StringView_CopyString(str("abcd"), buf, sizeof(buf)); EXPECT_STREQ(buf, "abc"); } TEST(StringViewTest, CpuFeatures_StringView_HasWord) { // Find flags at beginning, middle and end. EXPECT_TRUE( CpuFeatures_StringView_HasWord(str("first middle last"), "first")); EXPECT_TRUE( CpuFeatures_StringView_HasWord(str("first middle last"), "middle")); EXPECT_TRUE(CpuFeatures_StringView_HasWord(str("first middle last"), "last")); // Do not match partial flags EXPECT_FALSE( CpuFeatures_StringView_HasWord(str("first middle last"), "irst")); EXPECT_FALSE(CpuFeatures_StringView_HasWord(str("first middle last"), "mid")); EXPECT_FALSE(CpuFeatures_StringView_HasWord(str("first middle last"), "las")); } TEST(StringViewTest, CpuFeatures_StringView_GetAttributeKeyValue) { const StringView line = str(" key : first middle last "); StringView key, value; EXPECT_TRUE(CpuFeatures_StringView_GetAttributeKeyValue(line, &key, &value)); EXPECT_EQ(key, str("key")); EXPECT_EQ(value, str("first middle last")); } TEST(StringViewTest, FailingGetAttributeKeyValue) { const StringView line = str("key first middle last"); StringView key, value; EXPECT_FALSE(CpuFeatures_StringView_GetAttributeKeyValue(line, &key, &value)); } } // namespace } // namespace cpu_features
36.751724
80
0.750422
WilliamTambellini
28004a673c9dcf40e10372183a58c071e8dffe64
2,625
cpp
C++
export/windows/obj/src/resources/__res_27.cpp
seanbashaw/frozenlight
47c540d30d63e946ea2dc787b4bb602cc9347d21
[ "MIT" ]
null
null
null
export/windows/obj/src/resources/__res_27.cpp
seanbashaw/frozenlight
47c540d30d63e946ea2dc787b4bb602cc9347d21
[ "MIT" ]
null
null
null
export/windows/obj/src/resources/__res_27.cpp
seanbashaw/frozenlight
47c540d30d63e946ea2dc787b4bb602cc9347d21
[ "MIT" ]
null
null
null
// Generated by Haxe 3.4.7 namespace hx { unsigned char __res_27[] = { 0xff, 0xff, 0xff, 0xff, 137,80,78,71,13,10,26,10,0,0, 0,13,73,72,68,82,0,0,0,24, 0,0,0,32,8,6,0,0,0,8, 94,184,56,0,0,0,25,116,69,88, 116,83,111,102,116,119,97,114,101,0, 65,100,111,98,101,32,73,109,97,103, 101,82,101,97,100,121,113,201,101,60, 0,0,2,100,73,68,65,84,120,218, 180,150,207,107,19,65,20,199,191,59, 217,132,160,38,84,210,74,37,169,86, 250,195,34,168,69,80,130,160,248,39, 136,34,10,158,20,79,226,77,16,188, 164,180,23,143,34,244,226,15,66,162, 101,211,36,133,180,57,85,4,49,55, 65,68,137,57,91,165,173,144,162,82, 108,105,195,166,201,250,102,77,150,221, 52,27,179,233,228,193,219,153,157,89, 190,159,125,51,195,123,35,5,66,193, 8,128,41,116,201,92,251,252,254,119, 212,106,228,185,110,0,228,90,59,201, 31,15,39,167,91,70,242,104,226,158, 99,0,227,15,77,211,116,8,9,68, 68,71,32,209,30,104,149,74,21,140, 73,144,36,137,143,77,216,69,114,255, 246,101,91,161,222,129,144,125,4,186, 105,82,189,39,52,18,3,112,229,234, 117,140,14,143,8,135,24,128,3,62, 63,158,60,158,198,177,193,65,161,16, 102,126,217,40,85,48,159,74,227,232, 192,17,97,16,11,96,187,164,66,99, 30,44,164,211,8,5,131,66,32,172, 113,96,105,185,168,139,103,102,147,56, 220,223,191,103,200,46,192,159,205,45, 252,94,223,208,247,130,67,14,245,245, 25,16,58,138,145,61,3,184,125,93, 41,234,237,240,208,16,50,201,36,2, 129,64,199,144,166,128,226,207,117,108, 110,149,244,254,241,145,81,61,146,131, 61,61,29,65,152,221,196,82,45,10, 110,39,198,198,48,167,40,240,251,124, 142,33,182,128,213,226,47,168,229,29, 227,253,244,201,83,4,73,56,134,216, 2,120,126,250,190,186,102,25,59,51, 62,14,37,30,135,215,235,109,27,194, 90,77,126,251,177,134,74,181,106,25, 11,159,61,135,212,171,153,182,33,45, 1,170,186,163,47,85,163,157,15,135, 49,19,141,194,227,118,195,84,79,34, 142,1,141,155,109,182,75,23,46,34, 254,252,197,127,33,114,43,241,89,37, 134,124,254,19,109,236,126,18,106,254, 41,95,42,181,92,54,67,96,174,241, 182,128,84,226,37,22,230,211,255,62, 146,93,96,46,214,238,209,183,64,154, 2,178,36,156,201,36,193,11,156,44, 203,144,152,228,52,67,24,144,93,128, 215,139,89,36,104,105,24,99,144,221, 46,62,244,150,252,65,135,201,212,99, 1,228,114,111,16,139,62,53,47,201, 34,47,118,84,163,183,59,173,201,6, 224,227,135,247,40,20,242,112,19,179, 86,252,179,228,215,72,92,21,82,112, 190,20,62,211,95,27,55,139,57,17, 226,70,4,46,235,9,225,226,55,155, 137,219,45,131,147,84,161,144,223,16, 241,231,150,139,87,173,31,35,191,195, 243,156,200,155,93,61,130,103,228,183, 68,139,215,111,215,189,212,222,237,214, 245,253,175,0,3,0,153,80,196,12, 205,10,29,203,0,0,0,0,73,69, 78,68,174,66,96,130,0x00 }; }
34.090909
39
0.690667
seanbashaw
28016ac39eb6d7ad8b2e6392582ef415f731b57a
741
cpp
C++
src/MapNPCCharacter.cpp
nathanmentley/EssexEngineLibIsoMap
59fe0db6d139647eb9675365c269c8d166d631a7
[ "BSD-2-Clause" ]
null
null
null
src/MapNPCCharacter.cpp
nathanmentley/EssexEngineLibIsoMap
59fe0db6d139647eb9675365c269c8d166d631a7
[ "BSD-2-Clause" ]
null
null
null
src/MapNPCCharacter.cpp
nathanmentley/EssexEngineLibIsoMap
59fe0db6d139647eb9675365c269c8d166d631a7
[ "BSD-2-Clause" ]
null
null
null
/* * Essex Engine * * Copyright (C) 2018 Nathan Mentley - All Rights Reserved * You may use, distribute and modify this code under the * terms of the BSD license. * * You should have received a copy of the BSD license with * this file. If not, please visit: https://github.com/nathanmentley/EssexEngine */ #include <EssexEngineLibIsoMap/MapNPCCharacter.h> EssexEngine::Libs::IsoMap::MapNPCCharacter::MapNPCCharacter(WeakPointer<Context> gameContext, WeakPointer<Daemons::Window::IRenderContext> target, std::string bodyTexture, std::string headTexture, std::string weaponTexture) :MapCharacter(gameContext, target, bodyTexture, headTexture, weaponTexture) { } EssexEngine::Libs::IsoMap::MapNPCCharacter::~MapNPCCharacter() { }
37.05
223
0.769231
nathanmentley
2803255a0606af4c55f6cde0a96135703c232acd
10,824
cc
C++
src/scheduling/simple/simple_scheduler.cc
Container-Projects/firmament
d0de5258f0805f8d17b45d70c0a8e6d6a67617c0
[ "Apache-2.0", "OpenSSL" ]
287
2016-05-13T17:45:48.000Z
2022-01-23T00:26:20.000Z
src/scheduling/simple/simple_scheduler.cc
Container-Projects/firmament
d0de5258f0805f8d17b45d70c0a8e6d6a67617c0
[ "Apache-2.0", "OpenSSL" ]
33
2016-05-13T11:40:21.000Z
2020-11-16T17:57:17.000Z
src/scheduling/simple/simple_scheduler.cc
Container-Projects/firmament
d0de5258f0805f8d17b45d70c0a8e6d6a67617c0
[ "Apache-2.0", "OpenSSL" ]
64
2016-05-26T06:35:39.000Z
2021-09-27T12:02:44.000Z
/* * Firmament * Copyright (c) The Firmament Authors. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT * LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR * A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing * permissions and limitations under the License. */ // Naive implementation of a simple-minded queue-based scheduler. #include "scheduling/simple/simple_scheduler.h" #include <boost/timer/timer.hpp> #include <deque> #include <map> #include <string> #include <utility> #include <vector> #include "base/units.h" #include "misc/map-util.h" #include "misc/utils.h" #include "storage/object_store_interface.h" DEFINE_bool(randomly_place_tasks, false, "Place tasks randomly"); namespace firmament { namespace scheduler { using store::ObjectStoreInterface; SimpleScheduler::SimpleScheduler( shared_ptr<JobMap_t> job_map, shared_ptr<ResourceMap_t> resource_map, ResourceTopologyNodeDescriptor* resource_topology, shared_ptr<ObjectStoreInterface> object_store, shared_ptr<TaskMap_t> task_map, shared_ptr<KnowledgeBase> knowledge_base, shared_ptr<TopologyManager> topo_mgr, MessagingAdapterInterface<BaseMessage>* m_adapter, SchedulingEventNotifierInterface* event_notifier, ResourceID_t coordinator_res_id, const string& coordinator_uri, TimeInterface* time_manager, TraceGenerator* trace_generator) : EventDrivenScheduler(job_map, resource_map, resource_topology, object_store, task_map, knowledge_base, topo_mgr, m_adapter, event_notifier, coordinator_res_id, coordinator_uri, time_manager, trace_generator) { VLOG(1) << "SimpleScheduler initiated."; } SimpleScheduler::~SimpleScheduler() { } bool SimpleScheduler::FindResourceForTask(const TaskDescriptor& task_desc, ResourceID_t* best_resource) { // TODO(malte): This is an extremely simple-minded approach to resource // selection (i.e. the essence of scheduling). We will simply traverse the // resource map in some order, and grab the first resource available. VLOG(2) << "Trying to place task " << task_desc.uid() << "..."; // Find the first idle resource in the resource map for (ResourceMap_t::iterator res_iter = resource_map_->begin(); res_iter != resource_map_->end(); ++res_iter) { VLOG(3) << "Considering resource " << res_iter->first << ", which is in state " << res_iter->second->descriptor().state(); if (res_iter->second->descriptor().state() == ResourceDescriptor::RESOURCE_IDLE) { *best_resource = res_iter->first; return true; } } // We have not found any idle resources in our local resource map. At this // point, we should start looking beyond the machine boundary and towards // remote resources. return false; } bool SimpleScheduler::FindRandomResourceForTask(const TaskDescriptor& task_desc, ResourceID_t* best_resource) { // TODO(malte): This is an extremely simple-minded approach to resource // selection (i.e. the essence of scheduling). We will simply traverse the // resource map in some order, and grab the first resource available. VLOG(2) << "Trying to place task " << task_desc.uid() << "..."; vector<ResourceStatus*> resources; // Find the first idle resource in the resource map for (ResourceMap_t::iterator res_iter = resource_map_->begin(); res_iter != resource_map_->end(); ++res_iter) { resources.push_back(res_iter->second); } for (uint64_t max_attempts = 2000; max_attempts > 0; max_attempts--) { uint32_t resource_index = static_cast<uint32_t>(rand_r(&rand_seed_)) % resources.size(); if (resources[resource_index]->descriptor().state() == ResourceDescriptor::RESOURCE_IDLE) { *best_resource = ResourceIDFromString( resources[resource_index]->descriptor().uuid()); return true; } } // We have not found any idle resources in our local resource map. At this // point, we should start looking beyond the machine boundary and towards // remote resources. return false; } void SimpleScheduler::HandleTaskCompletion(TaskDescriptor* td_ptr, TaskFinalReport* report) { ResourceID_t res_id = ResourceIDFromString(td_ptr->scheduled_to_resource()); ResourceStatus* rs = FindPtrOrNull(*resource_map_, res_id); CHECK_NOTNULL(rs); ResourceDescriptor* rd_ptr = rs->mutable_descriptor(); // TODO(ionel): This assumes no PU sharing. rd_ptr->clear_current_running_tasks(); EventDrivenScheduler::HandleTaskCompletion(td_ptr, report); } void SimpleScheduler::HandleTaskEviction(TaskDescriptor* td_ptr, ResourceDescriptor* rd_ptr) { // TODO(ionel): This assumes no PU sharing. rd_ptr->clear_current_running_tasks(); EventDrivenScheduler::HandleTaskEviction(td_ptr, rd_ptr); } void SimpleScheduler::HandleTaskFailure(TaskDescriptor* td_ptr) { ResourceID_t res_id = ResourceIDFromString(td_ptr->scheduled_to_resource()); ResourceStatus* rs = FindPtrOrNull(*resource_map_, res_id); CHECK_NOTNULL(rs); ResourceDescriptor* rd_ptr = rs->mutable_descriptor(); // TODO(ionel): This assumes no PU sharing. rd_ptr->clear_current_running_tasks(); EventDrivenScheduler::HandleTaskFailure(td_ptr); } void SimpleScheduler::KillRunningTask( TaskID_t task_id, TaskKillMessage::TaskKillReason reason) { // TODO(ionel): Make sure the task is removed from current_running_tasks // when it is killed. } void SimpleScheduler::HandleTaskFinalReport(const TaskFinalReport& report, TaskDescriptor* td_ptr) { boost::lock_guard<boost::recursive_mutex> lock(scheduling_lock_); EventDrivenScheduler::HandleTaskFinalReport(report, td_ptr); TaskID_t task_id = td_ptr->uid(); vector<EquivClass_t> equiv_classes; // We create two equivalence class IDs: // 1) an equivalence class ID per task_id // 2) an equivalence class ID per program // We create these equivalence class IDs in order to make the EC // statistics view on the web UI work. EquivClass_t task_agg = static_cast<EquivClass_t>(HashCommandLine(*td_ptr)); equiv_classes.push_back(task_agg); equiv_classes.push_back(task_id); knowledge_base_->ProcessTaskFinalReport(equiv_classes, report); } void SimpleScheduler::PopulateSchedulerResourceUI( ResourceID_t res_id, TemplateDictionary* dict) const { // At the moment to we do not show any resource-specific information // for the simple scheduler. } void SimpleScheduler::PopulateSchedulerTaskUI(TaskID_t task_id, TemplateDictionary* dict) const { // At the moment to we do not show any task-specific information // for the simple scheduler. } uint64_t SimpleScheduler::ScheduleAllJobs(SchedulerStats* scheduler_stats) { return ScheduleAllJobs(scheduler_stats, NULL); } uint64_t SimpleScheduler::ScheduleAllJobs(SchedulerStats* scheduler_stats, vector<SchedulingDelta>* deltas) { boost::lock_guard<boost::recursive_mutex> lock(scheduling_lock_); vector<JobDescriptor*> jobs; for (auto& job_id_jd : jobs_to_schedule_) { jobs.push_back(job_id_jd.second); } uint64_t num_scheduled_tasks = ScheduleJobs(jobs, scheduler_stats, deltas); return num_scheduled_tasks; } uint64_t SimpleScheduler::ScheduleJob(JobDescriptor* jd_ptr, SchedulerStats* scheduler_stats) { uint64_t num_scheduled_tasks = 0; VLOG(2) << "Preparing to schedule job " << jd_ptr->uuid(); boost::lock_guard<boost::recursive_mutex> lock(scheduling_lock_); LOG(INFO) << "START SCHEDULING " << jd_ptr->uuid(); boost::timer::cpu_timer scheduler_timer; // Get the set of runnable tasks for this job unordered_set<TaskID_t> runnable_tasks = ComputeRunnableTasksForJob(jd_ptr); VLOG(2) << "Scheduling job " << jd_ptr->uuid() << ", which has " << runnable_tasks.size() << " runnable tasks."; JobID_t job_id = JobIDFromString(jd_ptr->uuid()); for (unordered_set<TaskID_t>::const_iterator task_iter = runnable_tasks.begin(); task_iter != runnable_tasks.end(); ++task_iter) { TaskDescriptor* td = FindPtrOrNull(*task_map_, *task_iter); CHECK(td); trace_generator_->TaskSubmitted(td); VLOG(2) << "Considering task " << td->uid() << ":\n" << td->DebugString(); ResourceID_t best_resource; bool success = false; if (FLAGS_randomly_place_tasks) { success = FindRandomResourceForTask(*td, &best_resource); } else { success = FindResourceForTask(*td, &best_resource); } if (!success) { VLOG(2) << "No suitable resource found, will need to try again."; } else { ResourceStatus* rp = FindPtrOrNull(*resource_map_, best_resource); CHECK(rp); VLOG(1) << "Scheduling task " << td->uid() << " on resource " << rp->descriptor().uuid(); // Remove the task from the runnable set. runnable_tasks_[job_id].erase(td->uid()); HandleTaskPlacement(td, rp->mutable_descriptor()); num_scheduled_tasks++; } } if (num_scheduled_tasks > 0) jd_ptr->set_state(JobDescriptor::RUNNING); if (scheduler_stats != NULL) { scheduler_stats->scheduler_runtime_ = scheduler_timer.elapsed().wall / NANOSECONDS_IN_MICROSECOND; } LOG(INFO) << "STOP SCHEDULING " << jd_ptr->uuid(); return num_scheduled_tasks; } uint64_t SimpleScheduler::ScheduleJobs(const vector<JobDescriptor*>& jds_ptr, SchedulerStats* scheduler_stats, vector<SchedulingDelta>* deltas) { boost::lock_guard<boost::recursive_mutex> lock(scheduling_lock_); uint64_t num_scheduled_tasks = 0; boost::timer::cpu_timer scheduler_timer; // TODO(ionel): Populate scheduling deltas! for (auto& jd_ptr : jds_ptr) { num_scheduled_tasks += ScheduleJob(jd_ptr, scheduler_stats); } if (scheduler_stats != NULL) { scheduler_stats->scheduler_runtime_ = static_cast<uint64_t>(scheduler_timer.elapsed().wall) / NANOSECONDS_IN_MICROSECOND; } return num_scheduled_tasks; } } // namespace scheduler } // namespace firmament
39.217391
80
0.699187
Container-Projects
28038deb08ecca4ac7c17a4b8fa1206392ac153c
2,541
cpp
C++
src/engineDX7/caption.cpp
FreeAllegiance/Allegiance-AZ
1d8678ddff9e2efc79ed449de6d47544989bc091
[ "MIT" ]
1
2017-09-11T22:18:19.000Z
2017-09-11T22:18:19.000Z
src/engineDX7/caption.cpp
FreeAllegiance/Allegiance-AZ
1d8678ddff9e2efc79ed449de6d47544989bc091
[ "MIT" ]
2
2017-09-12T18:28:33.000Z
2017-09-13T06:15:36.000Z
src/engineDX7/caption.cpp
FreeAllegiance/Allegiance-AZ
1d8678ddff9e2efc79ed449de6d47544989bc091
[ "MIT" ]
null
null
null
#include "pch.h" ////////////////////////////////////////////////////////////////////////////// // // // ////////////////////////////////////////////////////////////////////////////// class CaptionImpl : public ICaption, public EventTargetContainer<CaptionImpl> { private: TRef<ButtonPane> m_pbuttonClose; TRef<ButtonPane> m_pbuttonRestore; TRef<ButtonPane> m_pbuttonMinimize; TRef<Pane> m_ppane; TRef<ICaptionSite> m_psite; void DoCreateButton( Modeler* pmodeler, TRef<ButtonPane>& pbuttonPane, const ZString& str, const WinPoint& offset, Pane* ppane ) { TRef<ButtonFacePane> pface = CreateButtonFacePane( pmodeler->LoadSurface(str, false), ButtonFaceUp | ButtonFaceDown ); pbuttonPane = CreateButton(pface); pbuttonPane->SetOffset(offset); ppane->InsertAtTop(pbuttonPane); } public: CaptionImpl(Modeler* pmodeler, Pane* ppane, ICaptionSite* psite) : m_ppane(ppane), m_psite(psite) { DoCreateButton(pmodeler, m_pbuttonClose, "btnclosebmp", WinPoint(780, 5), ppane); DoCreateButton(pmodeler, m_pbuttonRestore, "btnrestorebmp", WinPoint(761, 5), ppane); DoCreateButton(pmodeler, m_pbuttonMinimize, "btnminimizebmp", WinPoint(744, 5), ppane); // mdvalley: Three pointers and class names AddEventTarget(&CaptionImpl::OnClose, m_pbuttonClose->GetEventSource()); AddEventTarget(&CaptionImpl::OnRestore, m_pbuttonRestore->GetEventSource()); AddEventTarget(&CaptionImpl::OnMinimize, m_pbuttonMinimize->GetEventSource()); } bool OnClose() { m_psite->OnCaptionClose(); return true; } bool OnMinimize() { m_psite->OnCaptionMinimize(); return true; } bool OnRestore() { m_psite->OnCaptionRestore(); return true; } void SetFullscreen(bool bFullscreen) { m_pbuttonClose->SetHidden(!bFullscreen); m_pbuttonRestore->SetHidden(!bFullscreen); m_pbuttonMinimize->SetHidden(!bFullscreen); } }; ////////////////////////////////////////////////////////////////////////////// // // // ////////////////////////////////////////////////////////////////////////////// TRef<ICaption> CreateCaption(Modeler* pmodeler, Pane* ppane, ICaptionSite* psite) { return new CaptionImpl(pmodeler, ppane, psite); }
28.550562
95
0.541913
FreeAllegiance
2805ad8a83ec54c69cd93b852397396041a7e2ef
7,637
cpp
C++
lib/small_range.cpp
LinerSu/crab
8f3516f4b4765f4a093bb3c3a94ac2daa174130c
[ "Apache-2.0" ]
null
null
null
lib/small_range.cpp
LinerSu/crab
8f3516f4b4765f4a093bb3c3a94ac2daa174130c
[ "Apache-2.0" ]
null
null
null
lib/small_range.cpp
LinerSu/crab
8f3516f4b4765f4a093bb3c3a94ac2daa174130c
[ "Apache-2.0" ]
null
null
null
#include <crab/domains/small_range.hpp> #include <crab/support/debug.hpp> #include <assert.h> namespace crab { namespace domains { small_range::small_range(kind_t v) : m_value(v){}; /* [0,0] | [0,0] = [0,0] [0,0] | [1,1] = [0,1] [0,0] | [0,1] = [0,1] [0,0] | [0,+oo] = [0,+oo] [0,0] | [1,+oo] = [0,+oo] */ small_range small_range::join_zero_with(const small_range &other) const { if (other.m_value == ExactlyZero) { return other; } else if (other.m_value == ExactlyOne) { return small_range(ZeroOrOne); } else if (other.m_value == ZeroOrOne) { return other; } else { return small_range(ZeroOrMore); } } /* [1,1] | [0,0] = [0,1] [1,1] | [1,1] = [1,+oo] [1,1] | [0,1] = [0,+oo] [1,1] | [0,+oo] = [0,+oo] [1,1] | [1,+oo] = [1,+oo] */ small_range small_range::join_one_with(const small_range &other) const { if (other.m_value == ExactlyZero) { return small_range(ZeroOrOne); } else if (other.m_value == ExactlyOne) { return small_range(OneOrMore); } else if (other.m_value == OneOrMore) { return other; } else { return small_range(ZeroOrMore); } } /* [0,1] | [0,0] = [0,1] [0,1] | [1,1] = [0,+oo] [0,1] | [0,1] = [0,+oo] [0,1] | [0,+oo] = [0,+oo] [0,1] | [1,+oo] = [0,+oo] */ small_range small_range::join_zero_or_one_with(const small_range &other) const { if (other.m_value == ExactlyZero) { return small_range(ZeroOrOne); } else { return small_range(ZeroOrMore); } } /* [1,+oo] | [0,0] = [0,+oo] [1,+oo] | [1,1] = [1,+oo] [1,+oo] | [0,1] = [0,+oo] [1,+oo] | [0,+oo] = [0,+oo] [1,+oo] | [1,+oo] = [1,+oo] */ small_range small_range::join_one_or_more_with(const small_range &other) const { if (other.m_value == ExactlyOne || other.m_value == OneOrMore) { return small_range(OneOrMore); } else { return small_range(ZeroOrMore); } } /* [0,0] & [0,0] = [0,0] [0,0] & [1,1] = _|_ [0,0] & [0,1] = [0,0] [0,0] & [0,+oo] = [0,0] [0,0] & [1,+oo] = _|_ */ small_range small_range::meet_zero_with(const small_range &other) const { assert(is_zero()); if (other.m_value == ExactlyOne || other.m_value == OneOrMore) { return small_range::bottom(); } else { return *this; } } /* [1,1] & [0,0] = _|_ [1,1] & [1,1] = [1,1] [1,1] & [0,1] = [1,1] [1,1] & [0,+oo] = [1,1] [1,1] & [1,+oo] = [1,1] */ small_range small_range::meet_one_with(const small_range &other) const { assert(is_one()); if (other.m_value == ExactlyZero) { return small_range::bottom(); } else { return *this; } } /* [0,1] & [0,0] = [0,0] [0,1] & [1,1] = [1,1] [0,1] & [0,1] = [0,1] [0,1] & [0,+oo] = [0,1] [0,1] & [1,+oo] = [1,1] */ small_range small_range::meet_zero_or_one_with(const small_range &other) const { assert(m_value == ZeroOrOne); if (other.is_zero() || other.is_one()) { return other; } else if (other.m_value == OneOrMore) { return one(); } else { return *this; } } /* [1,+oo] & [0,0] = _|_ [1,+oo] & [1,1] = [1,1] [1,+oo] & [0,1] = [1,1] [1,+oo] & [0,+oo] = [1,+oo] [1,+oo] & [1,+oo] = [1,+oo] */ small_range small_range::meet_one_or_more_with(const small_range &other) const { if (other.is_zero()) { return small_range::bottom(); } else if (other.is_one()) { return other; } else if (other.m_value == ZeroOrOne) { return one(); } else { assert(other.is_top() || other.m_value == OneOrMore); return *this; } } small_range::small_range() : m_value(ZeroOrMore) {} small_range small_range::bottom() { return small_range(Bottom); } small_range small_range::top() { return small_range(ZeroOrMore); } small_range small_range::zero() { return small_range(ExactlyZero); } small_range small_range::one() { return small_range(ExactlyOne); } small_range small_range::oneOrMore() { return small_range(OneOrMore); } bool small_range::is_bottom() const { return (m_value == Bottom); } bool small_range::is_top() const { return (m_value == ZeroOrMore); } bool small_range::is_zero() const { return (m_value == ExactlyZero); } bool small_range::is_one() const { return (m_value == ExactlyOne); } /* [0,+oo] | \ | \ [0,1] [1,+oo] / \ / 0 1 */ bool small_range::operator<=(small_range other) const { if (m_value == other.m_value) { return true; } else if (m_value == Bottom || other.m_value == ZeroOrMore) { return true; } else if (m_value == ExactlyZero) { return other.m_value != ExactlyOne && other.m_value != OneOrMore; } else if (m_value == ExactlyOne) { return other.m_value != ExactlyZero; } else if (m_value == ZeroOrOne || m_value == OneOrMore) { return other.m_value == ZeroOrMore; } else if (m_value == ZeroOrMore) { assert(other.m_value != ZeroOrMore); return false; } // should be unreachable return false; } bool small_range::operator==(small_range other) const { return m_value == other.m_value; } small_range small_range::operator|(small_range other) const { if (is_bottom()) { return other; } else if (other.is_bottom()) { return *this; } else if (is_zero()) { return join_zero_with(other); } else if (other.is_zero()) { return join_zero_with(*this); } else if (is_one()) { return join_one_with(other); } else if (other.is_one()) { return join_one_with(*this); } else if (m_value == ZeroOrOne) { return join_zero_or_one_with(other); } else if (other.m_value == ZeroOrOne) { return join_zero_or_one_with(*this); } else if (m_value == OneOrMore) { return join_one_or_more_with(other); } else if (other.m_value == OneOrMore) { return join_one_or_more_with(*this); } else { return small_range(ZeroOrMore); } } small_range small_range::operator||(small_range other) const { return *this | other; } small_range small_range::operator&(small_range other) const { if (is_bottom() || other.is_top()) { return *this; } else if (other.is_bottom() || is_top()) { return other; } if (is_zero()) { return meet_zero_with(other); } else if (other.is_zero()) { return other.meet_zero_with(*this); } else if (is_one()) { return meet_one_with(other); } else if (other.is_one()) { return other.meet_one_with(*this); } else if (m_value == ZeroOrOne) { return meet_zero_or_one_with(other); } else if (other.m_value == ZeroOrOne) { return other.meet_zero_or_one_with(*this); } else if (m_value == OneOrMore) { return meet_one_or_more_with(other); } else if (other.m_value == OneOrMore) { return other.meet_one_or_more_with(*this); } else { // unreachable because top cases handled above CRAB_ERROR("unexpected small_range::meet operands"); } } small_range small_range::operator&&(small_range other) const { return *this & other; } small_range small_range::increment(void) { if (!is_bottom()) { if (m_value == ExactlyZero) { m_value = ExactlyOne; } else if (m_value == ExactlyOne || m_value == ZeroOrMore || m_value == ZeroOrOne || m_value == OneOrMore) { m_value = OneOrMore; } else { CRAB_ERROR("small_range::increment unreachable"); } } return *this; } void small_range::write(crab_os &o) const { switch (m_value) { case Bottom: o << "_|_"; break; case ExactlyZero: o << "[0,0]"; break; case ExactlyOne: o << "[1,1]"; break; case ZeroOrOne: o << "[0,1]"; break; case ZeroOrMore: o << "[0,+oo]"; break; case OneOrMore: o << "[1,+oo]"; break; default: CRAB_ERROR("unexpected small_range value"); } } } // end namespace domains } // end namespace crab
26.243986
90
0.603116
LinerSu
28071e2199a013b840686fcace33fc8b113b0b63
5,531
cpp
C++
people_tracking_filter/src/tracker_particle.cpp
jdddog/people
8a8254a071e966db90d1d077a051f2d2926aa9af
[ "BSD-3-Clause" ]
2
2018-06-10T19:17:41.000Z
2021-11-09T10:17:23.000Z
people/people_tracking_filter/src/tracker_particle.cpp
procopiostein/leader
c2daa37e1c7071a3536c53c0cc4544f289923170
[ "BSD-3-Clause" ]
1
2018-05-05T02:48:42.000Z
2018-05-05T02:48:42.000Z
people_tracking_filter/src/tracker_particle.cpp
jdddog/people
8a8254a071e966db90d1d077a051f2d2926aa9af
[ "BSD-3-Clause" ]
null
null
null
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2008, Willow Garage, 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 the Willow Garage 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. *********************************************************************/ /* Author: Wim Meeussen */ #include "people_tracking_filter/tracker_particle.h" #include "people_tracking_filter/gaussian_pos_vel.h" using namespace MatrixWrapper; using namespace BFL; using namespace tf; using namespace std; using namespace ros; namespace estimation { // constructor TrackerParticle::TrackerParticle(const string& name, unsigned int num_particles, const StatePosVel& sysnoise): Tracker(name), prior_(num_particles), filter_(NULL), sys_model_(sysnoise), meas_model_(tf::Vector3(0.1,0.1,0.1)), tracker_initialized_(false), num_particles_(num_particles) {}; // destructor TrackerParticle::~TrackerParticle(){ if (filter_) delete filter_; }; // initialize prior density of filter void TrackerParticle::initialize(const StatePosVel& mu, const StatePosVel& sigma, const double time) { cout << "Initializing tracker with " << num_particles_ << " particles, with covariance " << sigma << " around " << mu << endl; GaussianPosVel gauss_pos_vel(mu, sigma); vector<Sample<StatePosVel> > prior_samples(num_particles_); gauss_pos_vel.SampleFrom(prior_samples, num_particles_, CHOLESKY, NULL); prior_.ListOfSamplesSet(prior_samples); filter_ = new BootstrapFilter<StatePosVel, tf::Vector3>(&prior_, &prior_, 0, num_particles_/4.0); // tracker initialized tracker_initialized_ = true; quality_ = 1; filter_time_ = time; init_time_ = time; } // update filter prediction bool TrackerParticle::updatePrediction(const double time) { bool res = true; if (time > filter_time_){ // set dt in sys model sys_model_.SetDt(time - filter_time_); filter_time_ = time; // update filter res = filter_->Update(&sys_model_); if (!res) quality_ = 0; } return res; }; // update filter correction bool TrackerParticle::updateCorrection(const tf::Vector3& meas, const MatrixWrapper::SymmetricMatrix& cov) { assert(cov.columns() == 3); // set covariance ((MeasPdfPos*)(meas_model_.MeasurementPdfGet()))->CovarianceSet(cov); // update filter bool res = filter_->Update(&meas_model_, meas); if (!res) quality_ = 0; return res; }; // get evenly spaced particle cloud void TrackerParticle::getParticleCloud(const tf::Vector3& step, double threshold, sensor_msgs::PointCloud& cloud) const { ((MCPdfPosVel*)(filter_->PostGet()))->getParticleCloud(step, threshold, cloud); }; // get most recent filter posterior void TrackerParticle::getEstimate(StatePosVel& est) const { est = ((MCPdfPosVel*)(filter_->PostGet()))->ExpectedValueGet(); }; void TrackerParticle::getEstimate(people_msgs::PositionMeasurement& est) const { StatePosVel tmp = filter_->PostGet()->ExpectedValueGet(); est.pos.x = tmp.pos_[0]; est.pos.y = tmp.pos_[1]; est.pos.z = tmp.pos_[2]; est.header.stamp.fromSec( filter_time_ ); est.object_id = getName(); } /// Get histogram from certain area Matrix TrackerParticle::getHistogramPos(const tf::Vector3& min, const tf::Vector3& max, const tf::Vector3& step) const { return ((MCPdfPosVel*)(filter_->PostGet()))->getHistogramPos(min, max, step); }; Matrix TrackerParticle::getHistogramVel(const tf::Vector3& min, const tf::Vector3& max, const tf::Vector3& step) const { return ((MCPdfPosVel*)(filter_->PostGet()))->getHistogramVel(min, max, step); }; double TrackerParticle::getLifetime() const { if (tracker_initialized_) return filter_time_ - init_time_; else return 0; } double TrackerParticle::getTime() const { if (tracker_initialized_) return filter_time_; else return 0; } }; // namespace
29.110526
121
0.690472
jdddog
28090551b66ae9420e16ec1ef61fd2e67de9381a
1,310
hpp
C++
module-apps/application-onboarding/windows/EULALicenseWindow.hpp
SP2FET/MuditaOS-1
2906bb8a2fb3cdd39b167e600f6cc6d9ce1327bd
[ "BSL-1.0" ]
1
2021-11-11T22:56:43.000Z
2021-11-11T22:56:43.000Z
module-apps/application-onboarding/windows/EULALicenseWindow.hpp
SP2FET/MuditaOS-1
2906bb8a2fb3cdd39b167e600f6cc6d9ce1327bd
[ "BSL-1.0" ]
null
null
null
module-apps/application-onboarding/windows/EULALicenseWindow.hpp
SP2FET/MuditaOS-1
2906bb8a2fb3cdd39b167e600f6cc6d9ce1327bd
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #pragma once #include "AppWindow.hpp" #include <module-apps/application-onboarding/presenter/EULALicenseWindowPresenter.hpp> #include <module-gui/gui/widgets/Label.hpp> #include <module-gui/gui/widgets/text/Text.hpp> #include <module-gui/gui/input/InputEvent.hpp> namespace app::onBoarding { class EULALicenseWindow : public gui::AppWindow, public EULALicenseWindowContract::View { public: explicit EULALicenseWindow(app::ApplicationCommon *app, std::unique_ptr<EULALicenseWindowContract::Presenter> &&windowPresenter); ~EULALicenseWindow() noexcept override; gui::status_bar::Configuration configureStatusBar(gui::status_bar::Configuration appConfiguration) override; void onBeforeShow(gui::ShowMode mode, gui::SwitchData *data) override; bool onInput(const gui::InputEvent &inputEvent) override; void rebuild() override; void buildInterface() override; void destroyInterface() override; private: std::unique_ptr<EULALicenseWindowContract::Presenter> presenter; gui::Text *eulaText = nullptr; }; } // namespace app::onBoarding
36.388889
116
0.712977
SP2FET
28094a5b58ef4275742f10f06786e19964f3bc12
936
hpp
C++
world/tiles/include/DigChances.hpp
sidav/shadow-of-the-wyrm
747afdeebed885b1a4f7ab42f04f9f756afd3e52
[ "MIT" ]
60
2019-08-21T04:08:41.000Z
2022-03-10T13:48:04.000Z
world/tiles/include/DigChances.hpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
3
2021-03-18T15:11:14.000Z
2021-10-20T12:13:07.000Z
world/tiles/include/DigChances.hpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
8
2019-11-16T06:29:05.000Z
2022-01-23T17:33:43.000Z
#pragma once #include "ISerializable.hpp" #include <string> #include <vector> class DigChances : public ISerializable { public: DigChances(); DigChances(const int new_pct_chance_undead, const int new_pct_chance_item, const std::vector<std::string>& new_item_ids); bool operator==(const DigChances& dc) const; void set_pct_chance_undead(const int new_pct_chance_undead); int get_pct_chance_undead() const; void set_pct_chance_item(const int new_pct_chance_item); int get_pct_chance_item() const; void set_item_ids(const std::vector<std::string>& new_item_ids); std::vector<std::string> get_item_ids() const; bool serialize(std::ostream& stream) const override; bool deserialize(std::istream& stream); protected: int pct_chance_undead; int pct_chance_item; std::vector<std::string> item_ids; private: ClassIdentifier internal_class_identifier() const override; };
26.742857
125
0.74359
sidav
280a5199d107c4755551501dec08f770a2e05e2d
6,855
cpp
C++
Vendor/assimp/test/unit/utFindDegenerates.cpp
mallonoce/BaseOpenGLProject
597a2ee2619cfa666856f32ee95f7943c6ae5223
[ "MIT" ]
1
2021-01-07T14:33:22.000Z
2021-01-07T14:33:22.000Z
Vendor/assimp/test/unit/utFindDegenerates.cpp
mallonoce/BaseOpenGLProject
597a2ee2619cfa666856f32ee95f7943c6ae5223
[ "MIT" ]
1
2022-03-26T07:18:59.000Z
2022-03-26T07:18:59.000Z
Vendor/assimp/test/unit/utFindDegenerates.cpp
mallonoce/BaseOpenGLProject
597a2ee2619cfa666856f32ee95f7943c6ae5223
[ "MIT" ]
null
null
null
/* --------------------------------------------------------------------------- Open Asset Import Library (assimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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 "UnitTestPCH.h" #include "../../include/assimp/scene.h" #include "PostProcessing/FindDegenerates.h" #include <memory> using namespace std; using namespace Assimp; class FindDegeneratesProcessTest : public ::testing::Test { public: FindDegeneratesProcessTest() : Test(), mMesh(nullptr), mProcess(nullptr) { // empty } protected: virtual void SetUp(); virtual void TearDown(); protected: aiMesh *mMesh; FindDegeneratesProcess *mProcess; }; void FindDegeneratesProcessTest::SetUp() { mMesh = new aiMesh(); mProcess = new FindDegeneratesProcess(); mMesh->mNumFaces = 1000; mMesh->mFaces = new aiFace[1000]; mMesh->mNumVertices = 5000 * 2; mMesh->mVertices = new aiVector3D[5000 * 2]; for (unsigned int i = 0; i < 5000; ++i) { mMesh->mVertices[i] = mMesh->mVertices[i + 5000] = aiVector3D((float)i); } mMesh->mPrimitiveTypes = aiPrimitiveType_LINE | aiPrimitiveType_POINT | aiPrimitiveType_POLYGON | aiPrimitiveType_TRIANGLE; unsigned int numOut = 0, numFaces = 0; for (unsigned int i = 0; i < 1000; ++i) { aiFace &f = mMesh->mFaces[i]; f.mNumIndices = (i % 5) + 1; // between 1 and 5 f.mIndices = new unsigned int[f.mNumIndices]; bool had = false; for (unsigned int n = 0; n < f.mNumIndices; ++n) { // FIXME #if 0 // some duplicate indices if ( n && n == (i / 200)+1) { f.mIndices[n] = f.mIndices[n-1]; had = true; } // and some duplicate vertices #endif if (n && i % 2 && 0 == n % 2) { f.mIndices[n] = f.mIndices[n - 1] + 5000; had = true; } else { f.mIndices[n] = numOut++; } } if (!had) ++numFaces; } mMesh->mNumUVComponents[0] = numOut; mMesh->mNumUVComponents[1] = numFaces; } void FindDegeneratesProcessTest::TearDown() { delete mMesh; delete mProcess; } TEST_F(FindDegeneratesProcessTest, testDegeneratesDetection) { mProcess->EnableInstantRemoval(false); mProcess->ExecuteOnMesh(mMesh); unsigned int out = 0; for (unsigned int i = 0; i < 1000; ++i) { aiFace &f = mMesh->mFaces[i]; out += f.mNumIndices; } EXPECT_EQ(1000U, mMesh->mNumFaces); EXPECT_EQ(10000U, mMesh->mNumVertices); EXPECT_EQ(out, mMesh->mNumUVComponents[0]); EXPECT_EQ(static_cast<unsigned int>( aiPrimitiveType_LINE | aiPrimitiveType_POINT | aiPrimitiveType_POLYGON | aiPrimitiveType_TRIANGLE), mMesh->mPrimitiveTypes); } TEST_F(FindDegeneratesProcessTest, testDegeneratesRemoval) { mProcess->EnableAreaCheck(false); mProcess->EnableInstantRemoval(true); mProcess->ExecuteOnMesh(mMesh); EXPECT_EQ(mMesh->mNumUVComponents[1], mMesh->mNumFaces); } TEST_F(FindDegeneratesProcessTest, testDegeneratesRemovalWithAreaCheck) { mProcess->EnableAreaCheck(true); mProcess->EnableInstantRemoval(true); mProcess->ExecuteOnMesh(mMesh); EXPECT_EQ(mMesh->mNumUVComponents[1] - 100, mMesh->mNumFaces); } namespace { std::unique_ptr<aiMesh> getDegenerateMesh() { std::unique_ptr<aiMesh> mesh(new aiMesh); mesh->mNumVertices = 2; mesh->mVertices = new aiVector3D[2]; mesh->mVertices[0] = aiVector3D{ 0.0f, 0.0f, 0.0f }; mesh->mVertices[1] = aiVector3D{ 1.0f, 0.0f, 0.0f }; mesh->mNumFaces = 1; mesh->mFaces = new aiFace[1]; mesh->mFaces[0].mNumIndices = 3; mesh->mFaces[0].mIndices = new unsigned int[3]; mesh->mFaces[0].mIndices[0] = 0; mesh->mFaces[0].mIndices[1] = 1; mesh->mFaces[0].mIndices[2] = 0; return mesh; } } TEST_F(FindDegeneratesProcessTest, meshRemoval) { mProcess->EnableAreaCheck(true); mProcess->EnableInstantRemoval(true); mProcess->ExecuteOnMesh(mMesh); std::unique_ptr<aiScene> scene(new aiScene); scene->mNumMeshes = 5; scene->mMeshes = new aiMesh*[5]; /// Use the mesh which doesn't get completely stripped of faces from the main test. aiMesh* meshWhichSurvives = mMesh; mMesh = nullptr; scene->mMeshes[0] = getDegenerateMesh().release(); scene->mMeshes[1] = getDegenerateMesh().release(); scene->mMeshes[2] = meshWhichSurvives; scene->mMeshes[3] = getDegenerateMesh().release(); scene->mMeshes[4] = getDegenerateMesh().release(); scene->mRootNode = new aiNode; scene->mRootNode->mNumMeshes = 5; scene->mRootNode->mMeshes = new unsigned int[5]; scene->mRootNode->mMeshes[0] = 0; scene->mRootNode->mMeshes[1] = 1; scene->mRootNode->mMeshes[2] = 2; scene->mRootNode->mMeshes[3] = 3; scene->mRootNode->mMeshes[4] = 4; mProcess->Execute(scene.get()); EXPECT_EQ(scene->mNumMeshes, 1); EXPECT_EQ(scene->mMeshes[0], meshWhichSurvives); EXPECT_EQ(scene->mRootNode->mNumMeshes, 1); EXPECT_EQ(scene->mRootNode->mMeshes[0], 0); }
32.799043
87
0.643764
mallonoce
280ae91e3dfe1e892725860e0be47b680d2db10a
2,898
hpp
C++
implementations/masa/masa-serial/masa-serial-1.0.1.1024/libs/masa-core/src/libmasa/aligners/AbstractAlignerSafe.hpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/masa/masa-serial/masa-serial-1.0.1.1024/libs/masa-core/src/libmasa/aligners/AbstractAlignerSafe.hpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/masa/masa-serial/masa-serial-1.0.1.1024/libs/masa-core/src/libmasa/aligners/AbstractAlignerSafe.hpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
/******************************************************************************* * * Copyright (c) 2010-2015 Edans Sandes * * This file is part of MASA-Core. * * MASA-Core is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MASA-Core is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MASA-Core. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************/ #ifndef ABSTRACTALIGNERSAFE_HPP_ #define ABSTRACTALIGNERSAFE_HPP_ #include "AbstractAligner.hpp" #include <pthread.h> #include <queue> using namespace std; struct dispatch_job_t { enum dispatch_type_e {JOB_SCORE} type; union dispatch_params_t { struct params_score_t { score_t score; int bx; int by; } params_score; } dispatch_params; }; /** @brief A thread-safe AbstractAligner extension. * * The current MASA implementation is not thread-safe. So, if an Aligner * executes simultaneous threads, the dispatch methods may generate an * inconsistent state leading to segmentation faults. To avoid this behavior, * the Aligner must extend the AbstractAlignerSafe class in order to * serialize the dispatch calls. * * There are two serialization strategies. * * <ul> * <li>Serialize by Mutex: the class uses mutex to lock simultaneous threads. * The threads are locked until no other thread is dispatching. * <li>Serialize by Queue: the class enqueue all dispatch executions and a * consumer thread dispatches the requisitions to the MASA engine. The * threads are only locked during the enqueue process. By now, only the * dispatchScore function is queued. To enable this feature, use * the createDispatcherQueue and destroyDispatcherQueue in the * alignPartition method. * </ul> */ class AbstractAlignerSafe : public AbstractAligner { public: AbstractAlignerSafe(); virtual ~AbstractAlignerSafe(); virtual void dispatchColumn(int j, const cell_t* buffer, int len); virtual void dispatchRow(int i, const cell_t* buffer, int len); virtual void dispatchScore(score_t score, int bx=-1, int by=-1); protected: void createDispatcherQueue(); void destroyDispatcherQueue(); private: pthread_t thread; pthread_mutex_t mutex; pthread_cond_t condition; bool dispatcherQueueActive; queue<dispatch_job_t> dispatcherQueue; static void *staticFunctionThread(void *arg); void executeLoop(); }; #endif /* ABSTRACTALIGNERSAFE_HPP_ */
32.931818
80
0.70842
r-barnes
280b50c57ea2ec3ac0fb87e562d1a581af7fabd0
3,407
cpp
C++
src/test/rwcollection_tests.cpp
danhper/bitcoin-abc
d2b4bfc4d42d054cfebb5d951d23bbe96115f262
[ "MIT" ]
1
2021-09-08T14:26:46.000Z
2021-09-08T14:26:46.000Z
src/test/rwcollection_tests.cpp
danhper/bitcoin-abc
d2b4bfc4d42d054cfebb5d951d23bbe96115f262
[ "MIT" ]
1
2020-02-19T10:28:45.000Z
2020-02-19T10:28:45.000Z
src/test/rwcollection_tests.cpp
danhper/bitcoin-abc
d2b4bfc4d42d054cfebb5d951d23bbe96115f262
[ "MIT" ]
1
2017-06-30T20:58:07.000Z
2017-06-30T20:58:07.000Z
// Copyright (c) 2018-2019 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <rwcollection.h> #include <reverse_iterator.h> #include <test/test_bitcoin.h> #include <boost/test/unit_test.hpp> #include <set> #include <vector> BOOST_AUTO_TEST_SUITE(rwcollection_tests) BOOST_AUTO_TEST_CASE(vector) { RWCollection<std::vector<int>> rwvector; { auto w = rwvector.getWriteView(); for (int i = 0; i < 100; i++) { w->push_back(i + 10); BOOST_CHECK_EQUAL(w[i], i + 10); BOOST_CHECK_EQUAL(w->back(), i + 10); BOOST_CHECK_EQUAL(w->size(), i + 1); w[i] = i; BOOST_CHECK_EQUAL(w[i], i); } int e = 0; for (int &i : w) { BOOST_CHECK_EQUAL(i, e++); i *= 2; } e = 0; for (int &i : reverse_iterate(w)) { BOOST_CHECK_EQUAL(i, 198 - 2 * e); i = e++; } } { auto r = rwvector.getReadView(); for (int i = 0; i < 100; i++) { BOOST_CHECK_EQUAL(r[i], 99 - i); } int e = 0; for (const int &i : r) { BOOST_CHECK_EQUAL(i, 99 - (e++)); } e = 0; for (const int &i : reverse_iterate(r)) { BOOST_CHECK_EQUAL(i, e++); } } } BOOST_AUTO_TEST_CASE(set) { RWCollection<std::set<int>> rwset; { auto w = rwset.getWriteView(); for (int i = 0; i < 100; i++) { w->insert(i); BOOST_CHECK_EQUAL(w->count(i), 1); BOOST_CHECK_EQUAL(*(w->find(i)), i); BOOST_CHECK_EQUAL(w->size(), i + 1); } for (int i = 0; i < 100; i += 2) { BOOST_CHECK_EQUAL(w->erase(i), 1); BOOST_CHECK_EQUAL(w->count(i), 0); BOOST_CHECK(w->find(i) == std::end(w)); } int e = 0; for (const int &i : w) { BOOST_CHECK_EQUAL(i / 2, e++); } } { auto r = rwset.getReadView(); for (int i = 0; i < 100; i += 2) { BOOST_CHECK_EQUAL(r->count(i), 0); BOOST_CHECK(r->find(i) == std::end(r)); } for (int i = 1; i < 100; i += 2) { BOOST_CHECK_EQUAL(r->count(i), 1); BOOST_CHECK_EQUAL(*(r->find(i)), i); } int e = 0; for (const int &i : r) { BOOST_CHECK_EQUAL(i / 2, e++); } } } BOOST_AUTO_TEST_CASE(map) { RWCollection<std::map<std::string, std::string>> rwmap; { auto w = rwmap.getWriteView(); w["1"] = "one"; w["2"] = "two"; w["3"] = "three"; BOOST_CHECK_EQUAL(w["1"], "one"); BOOST_CHECK_EQUAL(w["2"], "two"); BOOST_CHECK_EQUAL(w["3"], "three"); for (const std::pair<const std::string, std::string> &p : w) { BOOST_CHECK_EQUAL(w[p.first], p.second); } } { auto r = rwmap.getReadView(); BOOST_CHECK_EQUAL(r->count("1"), 1); BOOST_CHECK_EQUAL(r->find("1")->first, "1"); BOOST_CHECK_EQUAL(r->find("1")->second, "one"); for (const std::pair<const std::string, std::string> &p : r) { BOOST_CHECK_EQUAL(r->at(p.first), p.second); } } } BOOST_AUTO_TEST_SUITE_END();
24.868613
70
0.487819
danhper
280fdaa99ee62f1bf810aa6c189a4ef2c977d822
1,926
cxx
C++
Modules/Nonunit/IntegratedTest/test/itkMaximumDecisionRuleTest.cxx
ferdymercury/ITK
b0a86ded2edd698a6f4a3e58a9db23523a7eb871
[ "Apache-2.0" ]
2
2021-02-01T17:24:16.000Z
2021-02-02T02:18:46.000Z
Modules/Nonunit/IntegratedTest/test/itkMaximumDecisionRuleTest.cxx
ferdymercury/ITK
b0a86ded2edd698a6f4a3e58a9db23523a7eb871
[ "Apache-2.0" ]
4
2019-02-08T21:13:11.000Z
2019-02-18T20:57:34.000Z
Modules/Nonunit/IntegratedTest/test/itkMaximumDecisionRuleTest.cxx
ferdymercury/ITK
b0a86ded2edd698a6f4a3e58a9db23523a7eb871
[ "Apache-2.0" ]
4
2015-02-07T05:09:14.000Z
2019-10-08T09:17:30.000Z
/*========================================================================= * * Copyright NumFOCUS * * 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.txt * * 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 "itkMaximumDecisionRule.h" #include "itkObjectFactory.h" int itkMaximumDecisionRuleTest(int, char *[]) { using MaximumDecisionRuleType = itk::Statistics::MaximumDecisionRule; using MembershipVectorType = MaximumDecisionRuleType::MembershipVectorType; auto decisionRule = MaximumDecisionRuleType::New(); std::cout << decisionRule->GetNameOfClass() << std::endl; std::cout << decisionRule->MaximumDecisionRuleType::Superclass::GetNameOfClass() << std::endl; decisionRule->Print(std::cout); MembershipVectorType membershipScoreVector; double membershipScore1; membershipScore1 = 0.1; membershipScoreVector.push_back(membershipScore1); double membershipScore2; membershipScore2 = 0.5; membershipScoreVector.push_back(membershipScore2); double membershipScore3; membershipScore3 = 1.9; membershipScoreVector.push_back(membershipScore3); // the maximum score is the third component. The decision rule should // return index ( 2) if (decisionRule->Evaluate(membershipScoreVector) != 2) { std::cerr << "Decision rule computation is incorrect!" << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
32.1
96
0.688993
ferdymercury
28102ee57483a3ce6077ae6b09cc355c93d8b09d
918
cpp
C++
CoreTests/Script/Test_Eval.cpp
azhirnov/GraphicsGenFramework-modular
348be601f1991f102defa0c99250529f5e44c4d3
[ "BSD-2-Clause" ]
12
2017-12-23T14:24:57.000Z
2020-10-02T19:52:12.000Z
CoreTests/Script/Test_Eval.cpp
azhirnov/ModularGraphicsFramework
348be601f1991f102defa0c99250529f5e44c4d3
[ "BSD-2-Clause" ]
null
null
null
CoreTests/Script/Test_Eval.cpp
azhirnov/ModularGraphicsFramework
348be601f1991f102defa0c99250529f5e44c4d3
[ "BSD-2-Clause" ]
null
null
null
// Copyright (c) Zhirnov Andrey. For more information see 'LICENSE.txt' #include "CoreTests/Script/Common.h" class Script { public: static ScriptEngine * engine; int Run (int value) { const char script[] = R"#( int main (int x) { return 10 + x; } )#"; ScriptModulePtr mod = New<ScriptModule>( engine ); mod->Create( "def1" ); int res = 0; mod->Run( script, "main", OUT res, value ); return res; } }; ScriptEngine * Script::engine = null; static void Test_ScriptInScript (ScriptEngine &se) { const char script[] = R"#( int main () { Script sc; return sc.Run( 1 ); } )#"; Script::engine = &se; ClassBinder<Script> binder{ &se, "Script" }; binder.CreateClassValue(); binder.AddMethod( &Script::Run, "Run" ); int res = 0; se.Run( script, "main", OUT res ); TEST( res == 11 ); } extern void Test_Eval () { ScriptEngine se; Test_ScriptInScript( se ); }
14.806452
72
0.618736
azhirnov
281424d9e9815d152705477a00350131197243c6
8,786
cc
C++
missive/dbus/upload_client_test.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
missive/dbus/upload_client_test.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
missive/dbus/upload_client_test.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2021 The Chromium OS 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 "missive/dbus/upload_client.h" #include <string> #include <utility> #include <base/bind.h> #include <base/memory/scoped_refptr.h> #include <base/sequenced_task_runner.h> #include <base/task/thread_pool.h> #include <base/test/task_environment.h> #include <chromeos/dbus/service_constants.h> #include <dbus/bus.h> #include <dbus/message.h> #include <dbus/mock_bus.h> #include <dbus/mock_object_proxy.h> #include <dbus/object_path.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "missive/proto/interface.pb.h" #include "missive/proto/record.pb.h" #include "missive/util/test_support_callbacks.h" using ::testing::_; using ::testing::Eq; using ::testing::Invoke; using ::testing::NiceMock; using ::testing::Return; using ::testing::StrEq; using ::testing::WithArgs; namespace reporting { namespace { class UploadClientProducer : public UploadClient { public: static scoped_refptr<UploadClient> CreateForTests( scoped_refptr<dbus::Bus> bus, dbus::ObjectProxy* chrome_proxy) { return UploadClient::Create(bus, chrome_proxy); } }; class UploadClientTest : public ::testing::Test { protected: void SetUp() override { dbus_task_runner_ = base::ThreadPool::CreateSequencedTaskRunner( {base::TaskPriority::BEST_EFFORT, base::MayBlock()}); test::TestEvent<scoped_refptr<NiceMock<dbus::MockBus>>> dbus_waiter; dbus_task_runner_->PostTask( FROM_HERE, base::BindOnce(&UploadClientTest::CreateMockDBus, dbus_waiter.cb())); mock_bus_ = dbus_waiter.result(); EXPECT_CALL(*mock_bus_, GetDBusTaskRunner()) .WillRepeatedly(Return(dbus_task_runner_.get())); EXPECT_CALL(*mock_bus_, GetOriginTaskRunner()) .WillRepeatedly(Return(dbus_task_runner_.get())); // We actually want AssertOnOriginThread and AssertOnDBusThread to work // properly (actually assert they are on dbus_thread_). If the unit tests // end up creating calls on the wrong thread, the unit test will just hang // anyways, and it's easier to debug if we make the program crash at that // point. Since these are ON_CALLs, VerifyAndClearMockExpectations doesn't // clear them. ON_CALL(*mock_bus_, AssertOnOriginThread()) .WillByDefault(Invoke(this, &UploadClientTest::AssertOnDBusThread)); ON_CALL(*mock_bus_, AssertOnDBusThread()) .WillByDefault(Invoke(this, &UploadClientTest::AssertOnDBusThread)); mock_chrome_proxy_ = base::WrapRefCounted(new NiceMock<dbus::MockObjectProxy>( mock_bus_.get(), chromeos::kChromeReportingServiceName, dbus::ObjectPath(chromeos::kChromeReportingServicePath))); upload_client_ = UploadClientProducer::CreateForTests( mock_bus_, mock_chrome_proxy_.get()); upload_client_->SetAvailabilityForTest(/*is_available=*/true); } void TearDown() override { // Let everything ongoing to finish. task_environment_.RunUntilIdle(); } static void CreateMockDBus( base::OnceCallback<void(scoped_refptr<NiceMock<dbus::MockBus>>)> ready_cb) { dbus::Bus::Options options; options.bus_type = dbus::Bus::SYSTEM; std::move(ready_cb).Run(base::WrapRefCounted<NiceMock<dbus::MockBus>>( new NiceMock<dbus::MockBus>(options))); } void AssertOnDBusThread() { ASSERT_TRUE(dbus_task_runner_->RunsTasksInCurrentSequence()); } base::test::TaskEnvironment task_environment_; scoped_refptr<base::SequencedTaskRunner> dbus_task_runner_; scoped_refptr<NiceMock<dbus::MockBus>> mock_bus_; scoped_refptr<NiceMock<dbus::MockObjectProxy>> mock_chrome_proxy_; scoped_refptr<UploadClient> upload_client_; }; TEST_F(UploadClientTest, SuccessfulCall) { test::TestCallbackWaiter waiter; waiter.Attach(); auto response_callback = base::BindOnce( [](test::TestCallbackWaiter* waiter, StatusOr<UploadEncryptedRecordResponse> response) { ASSERT_OK(response) << response.status().ToString(); UploadEncryptedRecordResponse upload_response = std::move(response.ValueOrDie()); EXPECT_EQ(upload_response.status().code(), error::OK); waiter->Signal(); }, &waiter); constexpr char kTestData[] = "TEST_DATA"; EncryptedRecord encrypted_record; encrypted_record.set_encrypted_wrapped_record(kTestData); const int64_t kSequenceId = 42; const int64_t kGenerationId = 1701; const Priority kPriority = Priority::SLOW_BATCH; SequenceInformation* sequence_information = encrypted_record.mutable_sequence_information(); sequence_information->set_sequencing_id(kSequenceId); sequence_information->set_generation_id(kGenerationId); sequence_information->set_priority(kPriority); // We have to own the response here so that it lives throughout the rest of // the test. std::unique_ptr<dbus::Response> dbus_response = dbus::Response::CreateEmpty(); EXPECT_CALL(*mock_chrome_proxy_, DoCallMethod(_, _, _)) .WillOnce(WithArgs<0, 2>(Invoke([&encrypted_record, &dbus_response]( dbus::MethodCall* call, base::OnceCallback<void( // clang-format off dbus::Response* response)>* // clang-format on response_cb) { ASSERT_NE(call, nullptr); ASSERT_THAT(call->GetInterface(), Eq(chromeos::kChromeReportingServiceInterface)); ASSERT_THAT( call->GetMember(), Eq(chromeos::kChromeReportingServiceUploadEncryptedRecordMethod)); // Read the request. dbus::MessageReader reader(call); UploadEncryptedRecordRequest request; ASSERT_TRUE(reader.PopArrayOfBytesAsProto(&request)); // We only expect the one record, so access it directly. std::string requested_serialized; request.encrypted_record(0).SerializeToString(&requested_serialized); std::string expected_serialized; encrypted_record.SerializeToString(&expected_serialized); EXPECT_THAT(requested_serialized, StrEq(expected_serialized)); UploadEncryptedRecordResponse upload_response; upload_response.mutable_status()->set_code(error::OK); ASSERT_TRUE(dbus::MessageWriter(dbus_response.get()) .AppendProtoAsArrayOfBytes(upload_response)); std::move(*response_cb).Run(dbus_response.get()); }))); std::unique_ptr<std::vector<EncryptedRecord>> records = std::make_unique<std::vector<EncryptedRecord>>(); records->push_back(encrypted_record); upload_client_->SendEncryptedRecords(std::move(records), /*need_encryption_keys=*/false, std::move(response_callback)); waiter.Wait(); } TEST_F(UploadClientTest, CallUnavailable) { upload_client_->SetAvailabilityForTest(/*is_available=*/false); test::TestCallbackWaiter waiter; waiter.Attach(); auto response_callback = base::BindOnce( [](test::TestCallbackWaiter* waiter, StatusOr<UploadEncryptedRecordResponse> response) { ASSERT_FALSE(response.ok()); ASSERT_THAT(response.status().code(), Eq(error::UNAVAILABLE)) << response.status().ToString(); waiter->Signal(); }, &waiter); constexpr char kTestData[] = "TEST_DATA"; EncryptedRecord encrypted_record; encrypted_record.set_encrypted_wrapped_record(kTestData); const int64_t kSequenceId = 42; const int64_t kGenerationId = 1701; const Priority kPriority = Priority::SLOW_BATCH; SequenceInformation* sequence_information = encrypted_record.mutable_sequence_information(); sequence_information->set_sequencing_id(kSequenceId); sequence_information->set_generation_id(kGenerationId); sequence_information->set_priority(kPriority); // We have to own the response here so that it lives throughout the rest of // the test. std::unique_ptr<dbus::Response> dbus_response = dbus::Response::CreateEmpty(); EXPECT_CALL(*mock_chrome_proxy_, DoCallMethod(_, _, _)).Times(0); std::unique_ptr<std::vector<EncryptedRecord>> records = std::make_unique<std::vector<EncryptedRecord>>(); records->push_back(encrypted_record); upload_client_->SendEncryptedRecords(std::move(records), /*need_encryption_keys=*/false, std::move(response_callback)); waiter.Wait(); } } // namespace } // namespace reporting
37.708155
80
0.693034
Toromino
28148bc581c3c1e250b850ea9be7124d0d30e647
3,188
cpp
C++
compat/hkbParticleSystemEventPayload_0.cpp
BlazesRus/hkxcmd
e00a554225234e40e111e808b095156ac1d4b1fe
[ "Intel" ]
38
2015-03-24T00:41:59.000Z
2022-03-23T09:18:29.000Z
compat/hkbParticleSystemEventPayload_0.cpp
BlazesRus/hkxcmd
e00a554225234e40e111e808b095156ac1d4b1fe
[ "Intel" ]
2
2015-10-14T07:41:48.000Z
2015-12-14T02:19:05.000Z
compat/hkbParticleSystemEventPayload_0.cpp
BlazesRus/hkxcmd
e00a554225234e40e111e808b095156ac1d4b1fe
[ "Intel" ]
24
2015-08-03T20:41:07.000Z
2022-03-27T03:58:37.000Z
#include "StdAfx.h" #include "hkbParticleSystemEventPayload_0.h" #include <Common/Serialize/hkSerialize.h> #include <Common/Serialize/Util/hkSerializeUtil.h> #include <Common/Serialize/Version/hkVersionPatchManager.h> #include <Common/Serialize/Data/Dict/hkDataObjectDict.h> #include <Common/Serialize/Data/Native/hkDataObjectNative.h> #include <Common/Serialize/Data/Util/hkDataObjectUtil.h> #include <Common/Base/Reflection/Registry/hkDynamicClassNameRegistry.h> #include <Common/Base/Reflection/Registry/hkVtableClassRegistry.h> #include <Common/Base/Reflection/hkClass.h> #include <Common/Base/Reflection/hkInternalClassMember.h> #include <Common/Serialize/Util/hkSerializationCheckingUtils.h> #include <Common/Serialize/Util/hkVersionCheckingUtils.h> static const hkInternalClassEnumItem SystemTypeEnumItems[] = { {0, "DEBRIS"}, {1, "DUST"}, {2, "EXPLOSION"}, {3, "SMOKE"}, {4, "SPARKS"}, }; static const hkInternalClassEnum hkbParticleSystemEventPayloadClass_Enums[] = { {"SystemType", SystemTypeEnumItems, _countof(SystemTypeEnumItems), HK_NULL, 0 }, }; const hkClassEnum* SystemTypeEnum = reinterpret_cast<const hkClassEnum*>(&hkbParticleSystemEventPayloadClass_Enums[0]); static const hkInternalClassMember hkbParticleSystemEventPayloadClass_Members[] = { { "type",HK_NULL,SystemTypeEnum,hkClassMember::TYPE_ENUM,hkClassMember::TYPE_UINT8,0,hkClassMember::FLAGS_NONE,HK_OFFSET_OF(hkbParticleSystemEventPayload,m_type) /*8*/,HK_NULL}, { "emitBoneIndex",HK_NULL,HK_NULL,hkClassMember::TYPE_INT16,hkClassMember::TYPE_VOID,0,hkClassMember::FLAGS_NONE,HK_OFFSET_OF(hkbParticleSystemEventPayload,m_emitBoneIndex) /*10*/,HK_NULL}, { "offset",HK_NULL,HK_NULL,hkClassMember::TYPE_VECTOR4,hkClassMember::TYPE_VOID,0,hkClassMember::FLAGS_NONE,HK_OFFSET_OF(hkbParticleSystemEventPayload,m_offset) /*16*/,HK_NULL}, { "direction",HK_NULL,HK_NULL,hkClassMember::TYPE_VECTOR4,hkClassMember::TYPE_VOID,0,hkClassMember::FLAGS_NONE,HK_OFFSET_OF(hkbParticleSystemEventPayload,m_direction) /*32*/,HK_NULL}, { "numParticles",HK_NULL,HK_NULL,hkClassMember::TYPE_INT32,hkClassMember::TYPE_VOID,0,hkClassMember::FLAGS_NONE,HK_OFFSET_OF(hkbParticleSystemEventPayload,m_numParticles) /*48*/,HK_NULL}, { "speed",HK_NULL,HK_NULL,hkClassMember::TYPE_REAL,hkClassMember::TYPE_VOID,0,hkClassMember::FLAGS_NONE,HK_OFFSET_OF(hkbParticleSystemEventPayload,m_speed) /*52*/,HK_NULL}, }; // Signature: 9df46cd6 extern const hkClass hkbEventPayloadClass; extern const hkClass hkbParticleSystemEventPayloadClass; const hkClass hkbParticleSystemEventPayloadClass( "hkbParticleSystemEventPayload", &hkbEventPayloadClass, // parent sizeof(hkbParticleSystemEventPayload), HK_NULL, 0, // interfaces reinterpret_cast<const hkClassEnum*>(hkbParticleSystemEventPayloadClass_Enums), HK_COUNT_OF(hkbParticleSystemEventPayloadClass_Enums), reinterpret_cast<const hkClassMember*>(hkbParticleSystemEventPayloadClass_Members), HK_COUNT_OF(hkbParticleSystemEventPayloadClass_Members), HK_NULL, // defaults HK_NULL, // attributes 0, // flags 0 // version ); HK_REFLECTION_DEFINE_VIRTUAL(hkbParticleSystemEventPayload, hkbParticleSystemEventPayload);
54.033898
192
0.813363
BlazesRus
2815d744bc1be7abdc029823f1e835c90446b7b7
15,932
cpp
C++
test/beast/http/read.cpp
bebuch/beast
2454d671653844d8435f4f066946a7751a758db7
[ "BSL-1.0" ]
null
null
null
test/beast/http/read.cpp
bebuch/beast
2454d671653844d8435f4f066946a7751a758db7
[ "BSL-1.0" ]
null
null
null
test/beast/http/read.cpp
bebuch/beast
2454d671653844d8435f4f066946a7751a758db7
[ "BSL-1.0" ]
null
null
null
// // Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/boostorg/beast // // Test that header file is self-contained. #include <boost/beast/http/read.hpp> #include "test_parser.hpp" #include <boost/beast/core/ostream.hpp> #include <boost/beast/core/flat_static_buffer.hpp> #include <boost/beast/http/fields.hpp> #include <boost/beast/http/dynamic_body.hpp> #include <boost/beast/http/parser.hpp> #include <boost/beast/http/string_body.hpp> #include <boost/beast/_experimental/test/stream.hpp> #include <boost/beast/_experimental/unit_test/suite.hpp> #include <boost/beast/test/yield_to.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/strand.hpp> #include <boost/asio/ip/tcp.hpp> #include <atomic> namespace boost { namespace beast { namespace http { class read_test : public beast::unit_test::suite , public test::enable_yield_to { public: template<bool isRequest> void failMatrix(char const* s, yield_context do_yield) { static std::size_t constexpr limit = 100; std::size_t n; auto const len = strlen(s); for(n = 0; n < limit; ++n) { multi_buffer b; b.commit(net::buffer_copy( b.prepare(len), net::buffer(s, len))); test::fail_count fc(n); test::stream ts{ioc_, fc}; test_parser<isRequest> p(fc); error_code ec = test::error::test_failure; ts.close_remote(); read(ts, b, p, ec); if(! ec) break; } BEAST_EXPECT(n < limit); for(n = 0; n < limit; ++n) { static std::size_t constexpr pre = 10; multi_buffer b; b.commit(net::buffer_copy( b.prepare(pre), net::buffer(s, pre))); test::fail_count fc(n); test::stream ts{ioc_, fc, std::string(s + pre, len - pre)}; test_parser<isRequest> p(fc); error_code ec = test::error::test_failure; ts.close_remote(); read(ts, b, p, ec); if(! ec) break; } BEAST_EXPECT(n < limit); for(n = 0; n < limit; ++n) { multi_buffer b; b.commit(net::buffer_copy( b.prepare(len), net::buffer(s, len))); test::fail_count fc(n); test::stream ts{ioc_, fc}; test_parser<isRequest> p(fc); error_code ec = test::error::test_failure; ts.close_remote(); async_read(ts, b, p, do_yield[ec]); if(! ec) break; } BEAST_EXPECT(n < limit); for(n = 0; n < limit; ++n) { multi_buffer b; b.commit(net::buffer_copy( b.prepare(len), net::buffer(s, len))); test::fail_count fc(n); test::stream ts{ioc_, fc}; test_parser<isRequest> p(fc); error_code ec = test::error::test_failure; ts.close_remote(); async_read_header(ts, b, p, do_yield[ec]); if(! ec) break; } BEAST_EXPECT(n < limit); for(n = 0; n < limit; ++n) { static std::size_t constexpr pre = 10; multi_buffer b; b.commit(net::buffer_copy( b.prepare(pre), net::buffer(s, pre))); test::fail_count fc(n); test::stream ts(ioc_, fc, std::string{s + pre, len - pre}); test_parser<isRequest> p(fc); error_code ec = test::error::test_failure; ts.close_remote(); async_read(ts, b, p, do_yield[ec]); if(! ec) break; } BEAST_EXPECT(n < limit); } void testThrow() { try { multi_buffer b; test::stream c{ioc_, "GET / X"}; c.close_remote(); request_parser<dynamic_body> p; read(c, b, p); fail(); } catch(std::exception const&) { pass(); } } void testBufferOverflow() { { test::stream c{ioc_}; ostream(c.buffer()) << "GET / HTTP/1.1\r\n" "Host: localhost\r\n" "User-Agent: test\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" "10\r\n" "****************\r\n" "0\r\n\r\n"; flat_static_buffer<1024> b; request<string_body> req; try { read(c, b, req); pass(); } catch(std::exception const& e) { fail(e.what(), __FILE__, __LINE__); } } { test::stream c{ioc_}; ostream(c.buffer()) << "GET / HTTP/1.1\r\n" "Host: localhost\r\n" "User-Agent: test\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" "10\r\n" "****************\r\n" "0\r\n\r\n"; error_code ec = test::error::test_failure; flat_static_buffer<10> b; request<string_body> req; read(c, b, req, ec); BEAST_EXPECTS(ec == error::buffer_overflow, ec.message()); } } void testFailures(yield_context do_yield) { char const* req[] = { "GET / HTTP/1.0\r\n" "Host: localhost\r\n" "User-Agent: test\r\n" "Empty:\r\n" "\r\n" , "GET / HTTP/1.1\r\n" "Host: localhost\r\n" "User-Agent: test\r\n" "Content-Length: 2\r\n" "\r\n" "**" , "GET / HTTP/1.1\r\n" "Host: localhost\r\n" "User-Agent: test\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" "10\r\n" "****************\r\n" "0\r\n\r\n" , nullptr }; char const* res[] = { "HTTP/1.0 200 OK\r\n" "Server: test\r\n" "\r\n" , "HTTP/1.0 200 OK\r\n" "Server: test\r\n" "\r\n" "***" , "HTTP/1.1 200 OK\r\n" "Server: test\r\n" "Content-Length: 3\r\n" "\r\n" "***" , "HTTP/1.1 200 OK\r\n" "Server: test\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" "10\r\n" "****************\r\n" "0\r\n\r\n" , nullptr }; for(std::size_t i = 0; req[i]; ++i) failMatrix<true>(req[i], do_yield); for(std::size_t i = 0; res[i]; ++i) failMatrix<false>(res[i], do_yield); } void testRead(yield_context do_yield) { static std::size_t constexpr limit = 100; std::size_t n; for(n = 0; n < limit; ++n) { test::fail_count fc{n}; test::stream c{ioc_, fc, "GET / HTTP/1.1\r\n" "Host: localhost\r\n" "User-Agent: test\r\n" "Content-Length: 0\r\n" "\r\n" }; request<dynamic_body> m; try { multi_buffer b; read(c, b, m); break; } catch(std::exception const&) { } } BEAST_EXPECT(n < limit); for(n = 0; n < limit; ++n) { test::fail_count fc{n}; test::stream ts{ioc_, fc, "GET / HTTP/1.1\r\n" "Host: localhost\r\n" "User-Agent: test\r\n" "Content-Length: 0\r\n" "\r\n" }; request<dynamic_body> m; error_code ec = test::error::test_failure; multi_buffer b; read(ts, b, m, ec); if(! ec) break; } BEAST_EXPECT(n < limit); for(n = 0; n < limit; ++n) { test::fail_count fc{n}; test::stream c{ioc_, fc, "GET / HTTP/1.1\r\n" "Host: localhost\r\n" "User-Agent: test\r\n" "Content-Length: 0\r\n" "\r\n" }; request<dynamic_body> m; error_code ec = test::error::test_failure; multi_buffer b; async_read(c, b, m, do_yield[ec]); if(! ec) break; } BEAST_EXPECT(n < limit); for(n = 0; n < limit; ++n) { test::fail_count fc{n}; test::stream c{ioc_, fc, "GET / HTTP/1.1\r\n" "Host: localhost\r\n" "User-Agent: test\r\n" "Content-Length: 0\r\n" "\r\n" }; request_parser<dynamic_body> m; error_code ec = test::error::test_failure; multi_buffer b; async_read_some(c, b, m, do_yield[ec]); if(! ec) break; } BEAST_EXPECT(n < limit); } void testEof(yield_context do_yield) { { multi_buffer b; test::stream ts{ioc_}; request_parser<dynamic_body> p; error_code ec; ts.close_remote(); read(ts, b, p, ec); BEAST_EXPECT(ec == http::error::end_of_stream); } { multi_buffer b; test::stream ts{ioc_}; request_parser<dynamic_body> p; error_code ec; ts.close_remote(); async_read(ts, b, p, do_yield[ec]); BEAST_EXPECT(ec == http::error::end_of_stream); } } // Ensure completion handlers are not leaked struct handler { static std::atomic<std::size_t>& count() { static std::atomic<std::size_t> n; return n; } handler() { ++count(); } ~handler() { --count(); } handler(handler const&) { ++count(); } void operator()(error_code const&, std::size_t) const {} }; void testIoService() { { // Make sure handlers are not destroyed // after calling io_context::stop net::io_context ioc; test::stream ts{ioc, "GET / HTTP/1.1\r\n\r\n"}; BEAST_EXPECT(handler::count() == 0); multi_buffer b; request<dynamic_body> m; async_read(ts, b, m, handler{}); BEAST_EXPECT(handler::count() > 0); ioc.stop(); BEAST_EXPECT(handler::count() > 0); ioc.restart(); BEAST_EXPECT(handler::count() > 0); ioc.run_one(); BEAST_EXPECT(handler::count() == 0); } { // Make sure uninvoked handlers are // destroyed when calling ~io_context { net::io_context ioc; test::stream ts{ioc, "GET / HTTP/1.1\r\n\r\n"}; BEAST_EXPECT(handler::count() == 0); multi_buffer b; request<dynamic_body> m; async_read(ts, b, m, handler{}); BEAST_EXPECT(handler::count() > 0); } BEAST_EXPECT(handler::count() == 0); } } // https://github.com/boostorg/beast/issues/430 void testRegression430() { test::stream ts{ioc_}; ts.read_size(1); ostream(ts.buffer()) << "HTTP/1.1 200 OK\r\n" "Transfer-Encoding: chunked\r\n" "Content-Type: application/octet-stream\r\n" "\r\n" "4\r\nabcd\r\n" "0\r\n\r\n"; error_code ec; flat_buffer fb; response_parser<dynamic_body> p; read(ts, fb, p, ec); BEAST_EXPECTS(! ec, ec.message()); } //-------------------------------------------------------------------------- template<class Parser, class Pred> void readgrind(string_view s, Pred&& pred) { for(std::size_t n = 1; n < s.size() - 1; ++n) { Parser p; error_code ec = test::error::test_failure; flat_buffer b; test::stream ts{ioc_}; ostream(ts.buffer()) << s; ts.read_size(n); read(ts, b, p, ec); if(! BEAST_EXPECTS(! ec, ec.message())) continue; pred(p); } } void testReadGrind() { readgrind<test_parser<false>>( "HTTP/1.1 200 OK\r\n" "Transfer-Encoding: chunked\r\n" "Content-Type: application/octet-stream\r\n" "\r\n" "4\r\nabcd\r\n" "0\r\n\r\n" ,[&](test_parser<false> const& p) { BEAST_EXPECT(p.body == "abcd"); }); readgrind<test_parser<false>>( "HTTP/1.1 200 OK\r\n" "Server: test\r\n" "Expect: Expires, MD5-Fingerprint\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" "5\r\n" "*****\r\n" "2;a;b=1;c=\"2\"\r\n" "--\r\n" "0;d;e=3;f=\"4\"\r\n" "Expires: never\r\n" "MD5-Fingerprint: -\r\n" "\r\n" ,[&](test_parser<false> const& p) { BEAST_EXPECT(p.body == "*****--"); }); } struct copyable_handler { template<class... Args> void operator()(Args&&...) const { } }; void testAsioHandlerInvoke() { using strand = net::strand< net::io_context::executor_type>; // make sure things compile, also can set a // breakpoint in asio_handler_invoke to make sure // it is instantiated. { net::io_context ioc; strand s{ioc.get_executor()}; test::stream ts{ioc}; flat_buffer b; request_parser<dynamic_body> p; async_read_some(ts, b, p, net::bind_executor( s, copyable_handler{})); } { net::io_context ioc; strand s{ioc.get_executor()}; test::stream ts{ioc}; flat_buffer b; request_parser<dynamic_body> p; async_read(ts, b, p, net::bind_executor( s, copyable_handler{})); } { net::io_context ioc; strand s{ioc.get_executor()}; test::stream ts{ioc}; flat_buffer b; request<dynamic_body> m; async_read(ts, b, m, net::bind_executor( s, copyable_handler{})); } } void run() override { testThrow(); testBufferOverflow(); yield_to([&](yield_context yield) { testFailures(yield); }); yield_to([&](yield_context yield) { testRead(yield); }); yield_to([&](yield_context yield) { testEof(yield); }); testIoService(); testRegression430(); testReadGrind(); testAsioHandlerInvoke(); } }; BEAST_DEFINE_TESTSUITE(beast,http,read); } // http } // beast } // boost
28.298401
80
0.442631
bebuch
28163ca0fc1be168bcf7718b9a08388996a625ca
5,916
cpp
C++
XmlLib/Src/SaxContentElement.cpp
shortydude/DDOBuilder-learning
e71162c10b81bb4afd0365e61088437353cc4607
[ "MIT" ]
null
null
null
XmlLib/Src/SaxContentElement.cpp
shortydude/DDOBuilder-learning
e71162c10b81bb4afd0365e61088437353cc4607
[ "MIT" ]
null
null
null
XmlLib/Src/SaxContentElement.cpp
shortydude/DDOBuilder-learning
e71162c10b81bb4afd0365e61088437353cc4607
[ "MIT" ]
null
null
null
// SaxContentElement.cpp // #include "stdafx.h" #include "XmlLib\SaxContentElement.h" using XmlLib::SaxString; using XmlLib::SaxAttributes; #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // SaxContentElementInterface using XmlLib::SaxContentElementInterface; SaxContentElementInterface::SaxContentElementInterface() : m_readErrorHandler(NULL) { } SaxContentElementInterface::~SaxContentElementInterface() { } SaxContentElementInterface * SaxContentElementInterface::StartElement( const SaxString & name, const SaxAttributes & attributes) { return NULL; } void SaxContentElementInterface::Characters(const SaxString & chars) { } void SaxContentElementInterface::EndElement() { } SaxContentElementInterface * SaxContentElementInterface::SaxReadErrorHandler() const { return m_readErrorHandler; } void SaxContentElementInterface::SetSaxReadErrorHandler(SaxContentElementInterface * handler) { m_readErrorHandler = handler; } void SaxContentElementInterface::ClearSaxReadErrorHandler() { m_readErrorHandler = NULL; } void SaxContentElementInterface::ReportSaxReadError(const std::string & errorDescription) { // propagate or die if (m_readErrorHandler != NULL) { m_readErrorHandler->ReportSaxReadError(errorDescription); } else { throw errorDescription; } } ////////////////////////////////////////////////////////////////////// // SaxSimpleElement<std::string> XmlLib::SaxSimpleElement<std::string> XmlLib::SaxSimpleElement<std::string>::s_singleton; XmlLib::SaxSimpleElement<std::string> * XmlLib::SaxSimpleElement<std::string>::Handle(std::string * t) { t->erase(); s_singleton.m_t = t; return &s_singleton; } void XmlLib::SaxSimpleElement<std::string>::Characters(const SaxString & chars) { // ensure the capacity grows faster than adding it bit by bit as that // takes a loooooooong time for big strings if (m_t->capacity() < m_t->size() + chars.size() + 1) { m_t->reserve(m_t->capacity() * 2 + chars.size() + 1); } *m_t += chars; } ////////////////////////////////////////////////////////////////////// // SaxSimpleElement<std::wstring> XmlLib::SaxSimpleElement<std::wstring> XmlLib::SaxSimpleElement<std::wstring>::s_singleton; XmlLib::SaxSimpleElement<std::wstring> * XmlLib::SaxSimpleElement<std::wstring>::Handle(std::wstring * t) { t->erase(); s_singleton.m_t = t; return &s_singleton; } void XmlLib::SaxSimpleElement<std::wstring>::Characters(const SaxString & chars) { *m_t += chars; } ////////////////////////////////////////////////////////////////////// // SaxContentElement using XmlLib::SaxContentElement; const XmlLib::SaxString f_saxVersionAttributeName = L"version"; SaxContentElement::SaxContentElement(const SaxString & elementName) : m_elementName(elementName), m_elementVersion(0), m_elementHandlingVersion(0), m_readErrorMode(REM_terminate) { } SaxContentElement::SaxContentElement(const SaxString & elementName, unsigned version) : m_elementName(elementName), m_elementVersion(version), m_elementHandlingVersion(0), m_readErrorMode(REM_terminate) { } const XmlLib::SaxString & SaxContentElement::ElementName() const { return m_elementName; } bool SaxContentElement::SaxElementIsSelf( const SaxString & name, const SaxAttributes & attributes) { bool self = (name == m_elementName); if (self) { SaxSetAttributes(attributes); } return self; } void SaxContentElement::SaxSetAttributes(const SaxAttributes & attributes) { // store the id attribute (if there is one) if (attributes.HasAttribute(f_saxVersionAttributeName)) { std::wstringstream wssSax(attributes[f_saxVersionAttributeName]); wssSax >> m_elementHandlingVersion; if (wssSax.fail()) { std::stringstream ss; ss << "XML element " << m_elementName << " found with invalid version attribute"; ReportSaxReadError(ss.str()); } } } unsigned SaxContentElement::ElementHandlingVersion() const { return m_elementHandlingVersion; } SaxAttributes SaxContentElement::VersionAttributes() const { SaxAttributes attributes; if (m_elementVersion > 0) { std::wstringstream wssSax; wssSax << m_elementVersion; attributes[f_saxVersionAttributeName] = SaxString(wssSax.str()); } return attributes; } void SaxContentElement::ReportSaxReadError(const std::string & errorDescription) { if (m_readErrorMode == REM_accumulate) { // SAX read errors are collected and the owner must check for read errors m_saxReadErrors.push_back(errorDescription); } else { SaxContentElementInterface::ReportSaxReadError(errorDescription); } } void SaxContentElement::SetReadErrorMode(SaxContentElement::ReadErrorMode mode) { m_readErrorMode = mode; m_saxReadErrors.clear(); } SaxContentElement::ReadErrorMode SaxContentElement::GetReadErrorMode() const { return m_readErrorMode; } bool SaxContentElement::HasReadErrors() const { return !m_saxReadErrors.empty(); } const std::vector<std::string> & SaxContentElement::ReadErrors() const { return m_saxReadErrors; } const SaxContentElement & SaxContentElement::operator=(const SaxContentElement & copy) { // only copy element name if we don't already have one if (m_elementName.size() == 0) { m_elementName = copy.m_elementName; m_elementVersion = copy.m_elementVersion; } m_elementHandlingVersion = copy.m_elementHandlingVersion; m_readErrorMode = copy.m_readErrorMode; m_saxReadErrors = copy.m_saxReadErrors; return *this; } //////////////////////////////////////////////////////////////////////
25.174468
105
0.677654
shortydude
2817ed4ba0a6f3a90a6d283794581e941a2d2a78
57,078
cc
C++
src/selectParser.cc
nporsche/fastbit
91d06c68b9f4a0a0cc39da737d1c880ab21fe947
[ "BSD-3-Clause-LBNL" ]
null
null
null
src/selectParser.cc
nporsche/fastbit
91d06c68b9f4a0a0cc39da737d1c880ab21fe947
[ "BSD-3-Clause-LBNL" ]
null
null
null
src/selectParser.cc
nporsche/fastbit
91d06c68b9f4a0a0cc39da737d1c880ab21fe947
[ "BSD-3-Clause-LBNL" ]
null
null
null
/* A Bison parser, made by GNU Bison 2.7.12-4996. */ /* Skeleton implementation for Bison LALR(1) parsers in C++ Copyright (C) 2002-2013 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* "%code top" blocks. */ /* Line 276 of lalr1.cc */ #line 6 "selectParser.yy" /** \file Defines the parser for the select clause accepted by FastBit IBIS. The definitions are processed through bison. */ #include <iostream> /* Line 276 of lalr1.cc */ #line 44 "selectParser.cc" // Take the name prefix into account. #define yylex ibislex /* First part of user declarations. */ /* Line 283 of lalr1.cc */ #line 52 "selectParser.cc" #include "selectParser.hh" /* User implementation prologue. */ /* Line 289 of lalr1.cc */ #line 70 "selectParser.yy" #include "selectLexer.h" #undef yylex #define yylex driver.lexer->lex /* Line 289 of lalr1.cc */ #line 67 "selectParser.cc" # ifndef YY_NULL # if defined __cplusplus && 201103L <= __cplusplus # define YY_NULL nullptr # else # define YY_NULL 0 # endif # endif #ifndef YY_ # if defined YYENABLE_NLS && YYENABLE_NLS # if ENABLE_NLS # include <libintl.h> /* FIXME: INFRINGES ON USER NAME SPACE */ # define YY_(msgid) dgettext ("bison-runtime", msgid) # endif # endif # ifndef YY_ # define YY_(msgid) msgid # endif #endif #define YYRHSLOC(Rhs, K) ((Rhs)[K]) /* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N]. If N is 0, then set CURRENT to the empty location which ends the previous symbol: RHS[0] (always defined). */ # ifndef YYLLOC_DEFAULT # define YYLLOC_DEFAULT(Current, Rhs, N) \ do \ if (N) \ { \ (Current).begin = YYRHSLOC (Rhs, 1).begin; \ (Current).end = YYRHSLOC (Rhs, N).end; \ } \ else \ { \ (Current).begin = (Current).end = YYRHSLOC (Rhs, 0).end; \ } \ while (/*CONSTCOND*/ false) # endif /* Suppress unused-variable warnings by "using" E. */ #define YYUSE(e) ((void) (e)) /* Enable debugging if requested. */ #if YYDEBUG /* A pseudo ostream that takes yydebug_ into account. */ # define YYCDEBUG if (yydebug_) (*yycdebug_) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug_) \ { \ *yycdebug_ << Title << ' '; \ yy_symbol_print_ ((Type), (Value), (Location)); \ *yycdebug_ << std::endl; \ } \ } while (false) # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug_) \ yy_reduce_print_ (Rule); \ } while (false) # define YY_STACK_PRINT() \ do { \ if (yydebug_) \ yystack_print_ (); \ } while (false) #else /* !YYDEBUG */ # define YYCDEBUG if (false) std::cerr # define YY_SYMBOL_PRINT(Title, Type, Value, Location) YYUSE(Type) # define YY_REDUCE_PRINT(Rule) static_cast<void>(0) # define YY_STACK_PRINT() static_cast<void>(0) #endif /* !YYDEBUG */ #define yyerrok (yyerrstatus_ = 0) #define yyclearin (yychar = yyempty_) #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab #define YYRECOVERING() (!!yyerrstatus_) namespace ibis { /* Line 357 of lalr1.cc */ #line 162 "selectParser.cc" /* Return YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. */ std::string selectParser::yytnamerr_ (const char *yystr) { if (*yystr == '"') { std::string yyr = ""; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; /* Fall through. */ default: yyr += *yyp; break; case '"': return yyr; } do_not_strip_quotes: ; } return yystr; } /// Build a parser object. selectParser::selectParser (class ibis::selectClause& driver_yyarg) : #if YYDEBUG yydebug_ (false), yycdebug_ (&std::cerr), #endif driver (driver_yyarg) { } selectParser::~selectParser () { } #if YYDEBUG /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ inline void selectParser::yy_symbol_value_print_ (int yytype, const semantic_type* yyvaluep, const location_type* yylocationp) { YYUSE (yylocationp); YYUSE (yyvaluep); std::ostream& yyo = debug_stream (); std::ostream& yyoutput = yyo; YYUSE (yyoutput); YYUSE (yytype); } void selectParser::yy_symbol_print_ (int yytype, const semantic_type* yyvaluep, const location_type* yylocationp) { *yycdebug_ << (yytype < yyntokens_ ? "token" : "nterm") << ' ' << yytname_[yytype] << " (" << *yylocationp << ": "; yy_symbol_value_print_ (yytype, yyvaluep, yylocationp); *yycdebug_ << ')'; } #endif void selectParser::yydestruct_ (const char* yymsg, int yytype, semantic_type* yyvaluep, location_type* yylocationp) { YYUSE (yylocationp); YYUSE (yymsg); YYUSE (yyvaluep); if (yymsg) YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); switch (yytype) { case 13: /* "name" */ /* Line 452 of lalr1.cc */ #line 67 "selectParser.yy" { delete ((*yyvaluep).stringVal); }; /* Line 452 of lalr1.cc */ #line 265 "selectParser.cc" break; case 14: /* "string literal" */ /* Line 452 of lalr1.cc */ #line 66 "selectParser.yy" { delete ((*yyvaluep).stringVal); }; /* Line 452 of lalr1.cc */ #line 272 "selectParser.cc" break; case 23: /* mathExpr */ /* Line 452 of lalr1.cc */ #line 68 "selectParser.yy" { delete ((*yyvaluep).selectNode); }; /* Line 452 of lalr1.cc */ #line 279 "selectParser.cc" break; default: break; } } void selectParser::yypop_ (unsigned int n) { yystate_stack_.pop (n); yysemantic_stack_.pop (n); yylocation_stack_.pop (n); } #if YYDEBUG std::ostream& selectParser::debug_stream () const { return *yycdebug_; } void selectParser::set_debug_stream (std::ostream& o) { yycdebug_ = &o; } selectParser::debug_level_type selectParser::debug_level () const { return yydebug_; } void selectParser::set_debug_level (debug_level_type l) { yydebug_ = l; } #endif inline bool selectParser::yy_pact_value_is_default_ (int yyvalue) { return yyvalue == yypact_ninf_; } inline bool selectParser::yy_table_value_is_error_ (int yyvalue) { return yyvalue == yytable_ninf_; } int selectParser::parse () { /// Lookahead and lookahead in internal form. int yychar = yyempty_; int yytoken = 0; // State. int yyn; int yylen = 0; int yystate = 0; // Error handling. int yynerrs_ = 0; int yyerrstatus_ = 0; /// Semantic value of the lookahead. static semantic_type yyval_default; semantic_type yylval = yyval_default; /// Location of the lookahead. location_type yylloc; /// The locations where the error started and ended. location_type yyerror_range[3]; /// $$. semantic_type yyval; /// @$. location_type yyloc; int yyresult; // FIXME: This shoud be completely indented. It is not yet to // avoid gratuitous conflicts when merging into the master branch. try { YYCDEBUG << "Starting parse" << std::endl; /* User initialization code. */ /* Line 539 of lalr1.cc */ #line 28 "selectParser.yy" { // initialize location object yylloc.begin.filename = yylloc.end.filename = &(driver.clause_); } /* Line 539 of lalr1.cc */ #line 379 "selectParser.cc" /* Initialize the stacks. The initial state will be pushed in yynewstate, since the latter expects the semantical and the location values to have been already stored, initialize these stacks with a primary value. */ yystate_stack_.clear (); yysemantic_stack_.clear (); yylocation_stack_.clear (); yysemantic_stack_.push (yylval); yylocation_stack_.push (yylloc); /* New state. */ yynewstate: yystate_stack_.push (yystate); YYCDEBUG << "Entering state " << yystate << std::endl; /* Accept? */ if (yystate == yyfinal_) goto yyacceptlab; goto yybackup; /* Backup. */ yybackup: /* Try to take a decision without lookahead. */ yyn = yypact_[yystate]; if (yy_pact_value_is_default_ (yyn)) goto yydefault; /* Read a lookahead token. */ if (yychar == yyempty_) { YYCDEBUG << "Reading a token: "; yychar = yylex (&yylval, &yylloc); } /* Convert token to internal form. */ if (yychar <= yyeof_) { yychar = yytoken = yyeof_; YYCDEBUG << "Now at end of input." << std::endl; } else { yytoken = yytranslate_ (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || yylast_ < yyn || yycheck_[yyn] != yytoken) goto yydefault; /* Reduce or error. */ yyn = yytable_[yyn]; if (yyn <= 0) { if (yy_table_value_is_error_ (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the token being shifted. */ yychar = yyempty_; yysemantic_stack_.push (yylval); yylocation_stack_.push (yylloc); /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus_) --yyerrstatus_; yystate = yyn; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact_[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: yylen = yyr2_[yyn]; /* If YYLEN is nonzero, implement the default value of the action: `$$ = $1'. Otherwise, use the top of the stack. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. */ if (yylen) yyval = yysemantic_stack_[yylen - 1]; else yyval = yysemantic_stack_[0]; // Compute the default @$. { slice<location_type, location_stack_type> slice (yylocation_stack_, yylen); YYLLOC_DEFAULT (yyloc, slice, yylen); } // Perform the reduction. YY_REDUCE_PRINT (yyn); switch (yyn) { case 4: /* Line 664 of lalr1.cc */ #line 79 "selectParser.yy" { driver.addTerm((yysemantic_stack_[(2) - (1)].selectNode), 0); } break; case 5: /* Line 664 of lalr1.cc */ #line 82 "selectParser.yy" { driver.addTerm((yysemantic_stack_[(2) - (1)].selectNode), 0); } break; case 6: /* Line 664 of lalr1.cc */ #line 85 "selectParser.yy" { driver.addTerm((yysemantic_stack_[(3) - (1)].selectNode), (yysemantic_stack_[(3) - (2)].stringVal)); delete (yysemantic_stack_[(3) - (2)].stringVal); } break; case 7: /* Line 664 of lalr1.cc */ #line 89 "selectParser.yy" { driver.addTerm((yysemantic_stack_[(3) - (1)].selectNode), (yysemantic_stack_[(3) - (2)].stringVal)); delete (yysemantic_stack_[(3) - (2)].stringVal); } break; case 8: /* Line 664 of lalr1.cc */ #line 93 "selectParser.yy" { driver.addTerm((yysemantic_stack_[(4) - (1)].selectNode), (yysemantic_stack_[(4) - (3)].stringVal)); delete (yysemantic_stack_[(4) - (3)].stringVal); } break; case 9: /* Line 664 of lalr1.cc */ #line 97 "selectParser.yy" { driver.addTerm((yysemantic_stack_[(4) - (1)].selectNode), (yysemantic_stack_[(4) - (3)].stringVal)); delete (yysemantic_stack_[(4) - (3)].stringVal); } break; case 10: /* Line 664 of lalr1.cc */ #line 104 "selectParser.yy" { #if defined(DEBUG) && DEBUG + 0 > 1 LOGGER(ibis::gVerbose >= 0) << __FILE__ << ":" << __LINE__ << " parsing -- " << *(yysemantic_stack_[(3) - (1)].selectNode) << " + " << *(yysemantic_stack_[(3) - (3)].selectNode); #endif ibis::math::bediener *opr = new ibis::math::bediener(ibis::math::PLUS); opr->setRight((yysemantic_stack_[(3) - (3)].selectNode)); opr->setLeft((yysemantic_stack_[(3) - (1)].selectNode)); (yyval.selectNode) = opr; } break; case 11: /* Line 664 of lalr1.cc */ #line 116 "selectParser.yy" { #if defined(DEBUG) && DEBUG + 0 > 1 LOGGER(ibis::gVerbose >= 0) << __FILE__ << ":" << __LINE__ << " parsing -- " << *(yysemantic_stack_[(3) - (1)].selectNode) << " - " << *(yysemantic_stack_[(3) - (3)].selectNode); #endif ibis::math::bediener *opr = new ibis::math::bediener(ibis::math::MINUS); opr->setRight((yysemantic_stack_[(3) - (3)].selectNode)); opr->setLeft((yysemantic_stack_[(3) - (1)].selectNode)); (yyval.selectNode) = opr; } break; case 12: /* Line 664 of lalr1.cc */ #line 128 "selectParser.yy" { #if defined(DEBUG) && DEBUG + 0 > 1 LOGGER(ibis::gVerbose >= 0) << __FILE__ << ":" << __LINE__ << " parsing -- " << *(yysemantic_stack_[(3) - (1)].selectNode) << " * " << *(yysemantic_stack_[(3) - (3)].selectNode); #endif ibis::math::bediener *opr = new ibis::math::bediener(ibis::math::MULTIPLY); opr->setRight((yysemantic_stack_[(3) - (3)].selectNode)); opr->setLeft((yysemantic_stack_[(3) - (1)].selectNode)); (yyval.selectNode) = opr; } break; case 13: /* Line 664 of lalr1.cc */ #line 140 "selectParser.yy" { #if defined(DEBUG) && DEBUG + 0 > 1 LOGGER(ibis::gVerbose >= 0) << __FILE__ << ":" << __LINE__ << " parsing -- " << *(yysemantic_stack_[(3) - (1)].selectNode) << " / " << *(yysemantic_stack_[(3) - (3)].selectNode); #endif ibis::math::bediener *opr = new ibis::math::bediener(ibis::math::DIVIDE); opr->setRight((yysemantic_stack_[(3) - (3)].selectNode)); opr->setLeft((yysemantic_stack_[(3) - (1)].selectNode)); (yyval.selectNode) = opr; } break; case 14: /* Line 664 of lalr1.cc */ #line 152 "selectParser.yy" { #if defined(DEBUG) && DEBUG + 0 > 1 LOGGER(ibis::gVerbose >= 0) << __FILE__ << ":" << __LINE__ << " parsing -- " << *(yysemantic_stack_[(3) - (1)].selectNode) << " % " << *(yysemantic_stack_[(3) - (3)].selectNode); #endif ibis::math::bediener *opr = new ibis::math::bediener(ibis::math::REMAINDER); opr->setRight((yysemantic_stack_[(3) - (3)].selectNode)); opr->setLeft((yysemantic_stack_[(3) - (1)].selectNode)); (yyval.selectNode) = opr; } break; case 15: /* Line 664 of lalr1.cc */ #line 164 "selectParser.yy" { #if defined(DEBUG) && DEBUG + 0 > 1 LOGGER(ibis::gVerbose >= 0) << __FILE__ << ":" << __LINE__ << " parsing -- " << *(yysemantic_stack_[(3) - (1)].selectNode) << " ^ " << *(yysemantic_stack_[(3) - (3)].selectNode); #endif ibis::math::bediener *opr = new ibis::math::bediener(ibis::math::POWER); opr->setRight((yysemantic_stack_[(3) - (3)].selectNode)); opr->setLeft((yysemantic_stack_[(3) - (1)].selectNode)); (yyval.selectNode) = opr; } break; case 16: /* Line 664 of lalr1.cc */ #line 176 "selectParser.yy" { #if defined(DEBUG) && DEBUG + 0 > 1 LOGGER(ibis::gVerbose >= 0) << __FILE__ << ":" << __LINE__ << " parsing -- " << *(yysemantic_stack_[(3) - (1)].selectNode) << " & " << *(yysemantic_stack_[(3) - (3)].selectNode); #endif ibis::math::bediener *opr = new ibis::math::bediener(ibis::math::BITAND); opr->setRight((yysemantic_stack_[(3) - (3)].selectNode)); opr->setLeft((yysemantic_stack_[(3) - (1)].selectNode)); (yyval.selectNode) = opr; } break; case 17: /* Line 664 of lalr1.cc */ #line 188 "selectParser.yy" { #if defined(DEBUG) && DEBUG + 0 > 1 LOGGER(ibis::gVerbose >= 0) << __FILE__ << ":" << __LINE__ << " parsing -- " << *(yysemantic_stack_[(3) - (1)].selectNode) << " | " << *(yysemantic_stack_[(3) - (3)].selectNode); #endif ibis::math::bediener *opr = new ibis::math::bediener(ibis::math::BITOR); opr->setRight((yysemantic_stack_[(3) - (3)].selectNode)); opr->setLeft((yysemantic_stack_[(3) - (1)].selectNode)); (yyval.selectNode) = opr; } break; case 18: /* Line 664 of lalr1.cc */ #line 200 "selectParser.yy" { #if defined(DEBUG) && DEBUG + 0 > 1 LOGGER(ibis::gVerbose >= 0) << __FILE__ << ":" << __LINE__ << " parsing -- " << *(yysemantic_stack_[(4) - (1)].stringVal) << "(*)"; #endif ibis::math::term *fun = 0; if (stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "count") == 0) { // aggregation count ibis::math::variable *var = new ibis::math::variable("*"); fun = driver.addAgregado(ibis::selectClause::CNT, var); } else { LOGGER(ibis::gVerbose >= 0) << "Warning -- only operator COUNT supports * as the argument, " "but received " << *(yysemantic_stack_[(4) - (1)].stringVal); throw "invalid use of (*)"; } delete (yysemantic_stack_[(4) - (1)].stringVal); (yyval.selectNode) = fun; } break; case 19: /* Line 664 of lalr1.cc */ #line 219 "selectParser.yy" { #if defined(DEBUG) && DEBUG + 0 > 1 LOGGER(ibis::gVerbose >= 0) << __FILE__ << ":" << __LINE__ << " parsing -- " << *(yysemantic_stack_[(4) - (1)].stringVal) << "(" << *(yysemantic_stack_[(4) - (3)].selectNode) << ")"; #endif ibis::math::term *fun = 0; if (stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "count") == 0) { // aggregation count delete (yysemantic_stack_[(4) - (3)].selectNode); // drop the expression, replace it with "*" ibis::math::variable *var = new ibis::math::variable("*"); fun = driver.addAgregado(ibis::selectClause::CNT, var); } else if (stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "max") == 0) { // aggregation max fun = driver.addAgregado(ibis::selectClause::MAX, (yysemantic_stack_[(4) - (3)].selectNode)); } else if (stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "min") == 0) { // aggregation min fun = driver.addAgregado(ibis::selectClause::MIN, (yysemantic_stack_[(4) - (3)].selectNode)); } else if (stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "sum") == 0) { // aggregation sum fun = driver.addAgregado(ibis::selectClause::SUM, (yysemantic_stack_[(4) - (3)].selectNode)); } else if (stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "median") == 0) { // aggregation median fun = driver.addAgregado(ibis::selectClause::MEDIAN, (yysemantic_stack_[(4) - (3)].selectNode)); } else if (stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "countd") == 0 || stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "countdistinct") == 0) { // count distinct values fun = driver.addAgregado(ibis::selectClause::DISTINCT, (yysemantic_stack_[(4) - (3)].selectNode)); } else if (stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "concat") == 0 || stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "group_concat") == 0) { // concatenate all values as ASCII strings fun = driver.addAgregado(ibis::selectClause::CONCAT, (yysemantic_stack_[(4) - (3)].selectNode)); } else if (stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "avg") == 0) { // aggregation avg ibis::math::term *numer = driver.addAgregado(ibis::selectClause::SUM, (yysemantic_stack_[(4) - (3)].selectNode)); ibis::math::variable *var = new ibis::math::variable("*"); ibis::math::term *denom = driver.addAgregado(ibis::selectClause::CNT, var); ibis::math::bediener *opr = new ibis::math::bediener(ibis::math::DIVIDE); opr->setRight(denom); opr->setLeft(numer); fun = opr; } else if (stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "varp") == 0 || stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "varpop") == 0) { // population variance is computed as // fabs(sum (x^2) / count(*) - (sum (x) / count(*))^2) ibis::math::term *x = (yysemantic_stack_[(4) - (3)].selectNode); ibis::math::number *two = new ibis::math::number(2.0); ibis::math::variable *star = new ibis::math::variable("*"); ibis::math::term *t11 = new ibis::math::bediener(ibis::math::POWER); t11->setLeft(x); t11->setRight(two); t11 = driver.addAgregado(ibis::selectClause::SUM, t11); ibis::math::term *t12 = driver.addAgregado(ibis::selectClause::CNT, star); ibis::math::term *t13 = new ibis::math::bediener(ibis::math::DIVIDE); t13->setLeft(t11); t13->setRight(t12); ibis::math::term *t21 = driver.addAgregado(ibis::selectClause::SUM, x->dup()); ibis::math::term *t23 = new ibis::math::bediener(ibis::math::DIVIDE); t23->setLeft(t21); t23->setRight(t12->dup()); ibis::math::term *t24 = new ibis::math::bediener(ibis::math::POWER); t24->setLeft(t23); t24->setRight(two->dup()); ibis::math::term *t0 = new ibis::math::bediener(ibis::math::MINUS); t0->setLeft(t13); t0->setRight(t24); fun = new ibis::math::stdFunction1("fabs"); fun->setLeft(t0); //fun = driver.addAgregado(ibis::selectClause::VARPOP, $3); } else if (stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "var") == 0 || stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "varsamp") == 0 || stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "variance") == 0) { // sample variance is computed as // fabs((sum (x^2) / count(*) - (sum (x) / count(*))^2) * (count(*) / (count(*)-1))) ibis::math::term *x = (yysemantic_stack_[(4) - (3)].selectNode); ibis::math::number *two = new ibis::math::number(2.0); ibis::math::variable *star = new ibis::math::variable("*"); ibis::math::term *t11 = new ibis::math::bediener(ibis::math::POWER); t11->setLeft(x); t11->setRight(two); t11 = driver.addAgregado(ibis::selectClause::SUM, t11); ibis::math::term *t12 = driver.addAgregado(ibis::selectClause::CNT, star); ibis::math::term *t13 = new ibis::math::bediener(ibis::math::DIVIDE); t13->setLeft(t11); t13->setRight(t12); ibis::math::term *t21 = driver.addAgregado(ibis::selectClause::SUM, x->dup()); ibis::math::term *t23 = new ibis::math::bediener(ibis::math::DIVIDE); t23->setLeft(t21); t23->setRight(t12->dup()); ibis::math::term *t24 = new ibis::math::bediener(ibis::math::POWER); t24->setLeft(t23); t24->setRight(two->dup()); ibis::math::term *t31 = new ibis::math::bediener(ibis::math::MINUS); t31->setLeft(t13); t31->setRight(t24); ibis::math::term *t32 = new ibis::math::bediener(ibis::math::MINUS); ibis::math::number *one = new ibis::math::number(1.0); t32->setLeft(t12->dup()); t32->setRight(one); ibis::math::term *t33 = new ibis::math::bediener(ibis::math::DIVIDE); t33->setLeft(t12->dup()); t33->setRight(t32); ibis::math::term *t0 = new ibis::math::bediener(ibis::math::MULTIPLY); t0->setLeft(t31); t0->setRight(t33); fun = new ibis::math::stdFunction1("fabs"); fun->setLeft(t0); //fun = driver.addAgregado(ibis::selectClause::VARSAMP, $3); } else if (stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "stdevp") == 0 || stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "stdpop") == 0) { // population standard deviation is computed as // sqrt(fabs(sum (x^2) / count(*) - (sum (x) / count(*))^2)) ibis::math::term *x = (yysemantic_stack_[(4) - (3)].selectNode); ibis::math::number *two = new ibis::math::number(2.0); ibis::math::variable *star = new ibis::math::variable("*"); ibis::math::term *t11 = new ibis::math::bediener(ibis::math::POWER); t11->setLeft(x); t11->setRight(two); t11 = driver.addAgregado(ibis::selectClause::SUM, t11); ibis::math::term *t12 = driver.addAgregado(ibis::selectClause::CNT, star); ibis::math::term *t13 = new ibis::math::bediener(ibis::math::DIVIDE); t13->setLeft(t11); t13->setRight(t12); ibis::math::term *t21 = driver.addAgregado(ibis::selectClause::SUM, x->dup()); ibis::math::term *t23 = new ibis::math::bediener(ibis::math::DIVIDE); t23->setLeft(t21); t23->setRight(t12->dup()); ibis::math::term *t24 = new ibis::math::bediener(ibis::math::POWER); t24->setLeft(t23); t24->setRight(two->dup()); ibis::math::term *t31 = new ibis::math::bediener(ibis::math::MINUS); t31->setLeft(t13); t31->setRight(t24); ibis::math::term *t0 = new ibis::math::stdFunction1("fabs"); t0->setLeft(t31); fun = new ibis::math::stdFunction1("sqrt"); fun->setLeft(t0); //fun = driver.addAgregado(ibis::selectClause::STDPOP, $3); } else if (stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "std") == 0 || stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "stdev") == 0 || stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "stddev") == 0 || stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "stdsamp") == 0) { // sample standard deviation is computed as // sqrt(fabs(sum (x^2) / count(*) - (sum (x) / count(*))^2) * (count(*) / (count(*)-1)))) ibis::math::term *x = (yysemantic_stack_[(4) - (3)].selectNode); ibis::math::number *two = new ibis::math::number(2.0); ibis::math::variable *star = new ibis::math::variable("*"); ibis::math::term *t11 = new ibis::math::bediener(ibis::math::POWER); t11->setLeft(x); t11->setRight(two); t11 = driver.addAgregado(ibis::selectClause::SUM, t11); ibis::math::term *t12 = driver.addAgregado(ibis::selectClause::CNT, star); ibis::math::term *t13 = new ibis::math::bediener(ibis::math::DIVIDE); t13->setLeft(t11); t13->setRight(t12); ibis::math::term *t21 = driver.addAgregado(ibis::selectClause::SUM, x->dup()); ibis::math::term *t23 = new ibis::math::bediener(ibis::math::DIVIDE); t23->setLeft(t21); t23->setRight(t12->dup()); ibis::math::term *t24 = new ibis::math::bediener(ibis::math::POWER); t24->setLeft(t23); t24->setRight(two->dup()); ibis::math::term *t31 = new ibis::math::bediener(ibis::math::MINUS); t31->setLeft(t13); t31->setRight(t24); ibis::math::term *t32 = new ibis::math::bediener(ibis::math::MINUS); ibis::math::number *one = new ibis::math::number(1.0); t32->setLeft(t12->dup()); t32->setRight(one); ibis::math::term *t33 = new ibis::math::bediener(ibis::math::DIVIDE); t33->setLeft(t12->dup()); t33->setRight(t32); ibis::math::term *t34 = new ibis::math::bediener(ibis::math::MULTIPLY); t34->setLeft(t31); t34->setRight(t33); ibis::math::term *t0 = new ibis::math::stdFunction1("fabs"); t0->setLeft(t34); fun = new ibis::math::stdFunction1("sqrt"); fun->setLeft(t0); // fun = driver.addAgregado(ibis::selectClause::STDSAMP, $3); } else { // assume it is a standard math function fun = new ibis::math::stdFunction1((yysemantic_stack_[(4) - (1)].stringVal)->c_str()); fun->setLeft((yysemantic_stack_[(4) - (3)].selectNode)); } delete (yysemantic_stack_[(4) - (1)].stringVal); (yyval.selectNode) = fun; } break; case 20: /* Line 664 of lalr1.cc */ #line 423 "selectParser.yy" { #if defined(DEBUG) && DEBUG + 0 > 1 LOGGER(ibis::gVerbose >= 0) << __FILE__ << ":" << __LINE__ << " parsing -- FORMAT_UNIXTIME_GMT(" << *(yysemantic_stack_[(6) - (3)].selectNode) << ", " << *(yysemantic_stack_[(6) - (5)].stringVal) << ")"; #endif ibis::math::formatUnixTime fut((yysemantic_stack_[(6) - (5)].stringVal)->c_str(), "GMT"); ibis::math::stringFunction1 *fun = new ibis::math::stringFunction1(fut); fun->setLeft((yysemantic_stack_[(6) - (3)].selectNode)); (yyval.selectNode) = fun; delete (yysemantic_stack_[(6) - (5)].stringVal); } break; case 21: /* Line 664 of lalr1.cc */ #line 435 "selectParser.yy" { #if defined(DEBUG) && DEBUG + 0 > 1 LOGGER(ibis::gVerbose >= 0) << __FILE__ << ":" << __LINE__ << " parsing -- FORMAT_UNIXTIME_GMT(" << *(yysemantic_stack_[(6) - (3)].selectNode) << ", " << *(yysemantic_stack_[(6) - (5)].stringVal) << ")"; #endif ibis::math::formatUnixTime fut((yysemantic_stack_[(6) - (5)].stringVal)->c_str(), "GMT"); ibis::math::stringFunction1 *fun = new ibis::math::stringFunction1(fut); fun->setLeft((yysemantic_stack_[(6) - (3)].selectNode)); (yyval.selectNode) = fun; delete (yysemantic_stack_[(6) - (5)].stringVal); } break; case 22: /* Line 664 of lalr1.cc */ #line 447 "selectParser.yy" { #if defined(DEBUG) && DEBUG + 0 > 1 LOGGER(ibis::gVerbose >= 0) << __FILE__ << ":" << __LINE__ << " parsing -- FORMAT_UNIXTIME_LOCAL(" << *(yysemantic_stack_[(6) - (3)].selectNode) << ", " << *(yysemantic_stack_[(6) - (5)].stringVal) << ")"; #endif ibis::math::formatUnixTime fut((yysemantic_stack_[(6) - (5)].stringVal)->c_str()); ibis::math::stringFunction1 *fun = new ibis::math::stringFunction1(fut); fun->setLeft((yysemantic_stack_[(6) - (3)].selectNode)); (yyval.selectNode) = fun; delete (yysemantic_stack_[(6) - (5)].stringVal); } break; case 23: /* Line 664 of lalr1.cc */ #line 459 "selectParser.yy" { #if defined(DEBUG) && DEBUG + 0 > 1 LOGGER(ibis::gVerbose >= 0) << __FILE__ << ":" << __LINE__ << " parsing -- FORMAT_UNIXTIME_LOCAL(" << *(yysemantic_stack_[(6) - (3)].selectNode) << ", " << *(yysemantic_stack_[(6) - (5)].stringVal) << ")"; #endif ibis::math::formatUnixTime fut((yysemantic_stack_[(6) - (5)].stringVal)->c_str()); ibis::math::stringFunction1 *fun = new ibis::math::stringFunction1(fut); fun->setLeft((yysemantic_stack_[(6) - (3)].selectNode)); (yyval.selectNode) = fun; delete (yysemantic_stack_[(6) - (5)].stringVal); } break; case 24: /* Line 664 of lalr1.cc */ #line 471 "selectParser.yy" { /* two-arugment math functions */ #if defined(DEBUG) && DEBUG + 0 > 1 LOGGER(ibis::gVerbose >= 0) << __FILE__ << ":" << __LINE__ << " parsing -- " << *(yysemantic_stack_[(6) - (1)].stringVal) << "(" << *(yysemantic_stack_[(6) - (3)].selectNode) << ", " << *(yysemantic_stack_[(6) - (5)].selectNode) << ")"; #endif ibis::math::stdFunction2 *fun = new ibis::math::stdFunction2((yysemantic_stack_[(6) - (1)].stringVal)->c_str()); fun->setRight((yysemantic_stack_[(6) - (5)].selectNode)); fun->setLeft((yysemantic_stack_[(6) - (3)].selectNode)); (yyval.selectNode) = fun; delete (yysemantic_stack_[(6) - (1)].stringVal); } break; case 25: /* Line 664 of lalr1.cc */ #line 485 "selectParser.yy" { #if defined(DEBUG) && DEBUG + 0 > 1 LOGGER(ibis::gVerbose >= 0) << __FILE__ << ":" << __LINE__ << " parsing -- - " << *(yysemantic_stack_[(2) - (2)].selectNode); #endif ibis::math::bediener *opr = new ibis::math::bediener(ibis::math::NEGATE); opr->setRight((yysemantic_stack_[(2) - (2)].selectNode)); (yyval.selectNode) = opr; } break; case 26: /* Line 664 of lalr1.cc */ #line 495 "selectParser.yy" { (yyval.selectNode) = (yysemantic_stack_[(2) - (2)].selectNode); } break; case 27: /* Line 664 of lalr1.cc */ #line 498 "selectParser.yy" { (yyval.selectNode) = (yysemantic_stack_[(3) - (2)].selectNode); } break; case 28: /* Line 664 of lalr1.cc */ #line 501 "selectParser.yy" { #if defined(DEBUG) && DEBUG + 0 > 1 LOGGER(ibis::gVerbose >= 0) << __FILE__ << ":" << __LINE__ << " got a variable name " << *(yysemantic_stack_[(1) - (1)].stringVal); #endif (yyval.selectNode) = new ibis::math::variable((yysemantic_stack_[(1) - (1)].stringVal)->c_str()); delete (yysemantic_stack_[(1) - (1)].stringVal); } break; case 29: /* Line 664 of lalr1.cc */ #line 509 "selectParser.yy" { #if defined(DEBUG) && DEBUG + 0 > 1 LOGGER(ibis::gVerbose >= 0) << __FILE__ << ":" << __LINE__ << " got a string literal " << *(yysemantic_stack_[(1) - (1)].stringVal); #endif (yyval.selectNode) = new ibis::math::literal((yysemantic_stack_[(1) - (1)].stringVal)->c_str()); delete (yysemantic_stack_[(1) - (1)].stringVal); } break; case 30: /* Line 664 of lalr1.cc */ #line 517 "selectParser.yy" { #if defined(DEBUG) && DEBUG + 0 > 1 LOGGER(ibis::gVerbose >= 0) << __FILE__ << ":" << __LINE__ << " got a number " << (yysemantic_stack_[(1) - (1)].doubleVal); #endif (yyval.selectNode) = new ibis::math::number((yysemantic_stack_[(1) - (1)].doubleVal)); } break; /* Line 664 of lalr1.cc */ #line 1076 "selectParser.cc" default: break; } /* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. */ YY_SYMBOL_PRINT ("-> $$ =", yyr1_[yyn], &yyval, &yyloc); yypop_ (yylen); yylen = 0; YY_STACK_PRINT (); yysemantic_stack_.push (yyval); yylocation_stack_.push (yyloc); /* Shift the result of the reduction. */ yyn = yyr1_[yyn]; yystate = yypgoto_[yyn - yyntokens_] + yystate_stack_[0]; if (0 <= yystate && yystate <= yylast_ && yycheck_[yystate] == yystate_stack_[0]) yystate = yytable_[yystate]; else yystate = yydefgoto_[yyn - yyntokens_]; goto yynewstate; /*------------------------------------. | yyerrlab -- here on detecting error | `------------------------------------*/ yyerrlab: /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yytranslate_ (yychar); /* If not already recovering from an error, report this error. */ if (!yyerrstatus_) { ++yynerrs_; if (yychar == yyempty_) yytoken = yyempty_; error (yylloc, yysyntax_error_ (yystate, yytoken)); } yyerror_range[1] = yylloc; if (yyerrstatus_ == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= yyeof_) { /* Return failure if at end of input. */ if (yychar == yyeof_) YYABORT; } else { yydestruct_ ("Error: discarding", yytoken, &yylval, &yylloc); yychar = yyempty_; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (false) goto yyerrorlab; yyerror_range[1] = yylocation_stack_[yylen - 1]; /* Do not reclaim the symbols of the rule which action triggered this YYERROR. */ yypop_ (yylen); yylen = 0; yystate = yystate_stack_[0]; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus_ = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact_[yystate]; if (!yy_pact_value_is_default_ (yyn)) { yyn += yyterror_; if (0 <= yyn && yyn <= yylast_ && yycheck_[yyn] == yyterror_) { yyn = yytable_[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yystate_stack_.height () == 1) YYABORT; yyerror_range[1] = yylocation_stack_[0]; yydestruct_ ("Error: popping", yystos_[yystate], &yysemantic_stack_[0], &yylocation_stack_[0]); yypop_ (); yystate = yystate_stack_[0]; YY_STACK_PRINT (); } yyerror_range[2] = yylloc; // Using YYLLOC is tempting, but would change the location of // the lookahead. YYLOC is available though. YYLLOC_DEFAULT (yyloc, yyerror_range, 2); yysemantic_stack_.push (yylval); yylocation_stack_.push (yyloc); /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos_[yyn], &yysemantic_stack_[0], &yylocation_stack_[0]); yystate = yyn; goto yynewstate; /* Accept. */ yyacceptlab: yyresult = 0; goto yyreturn; /* Abort. */ yyabortlab: yyresult = 1; goto yyreturn; yyreturn: if (yychar != yyempty_) { /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yytranslate_ (yychar); yydestruct_ ("Cleanup: discarding lookahead", yytoken, &yylval, &yylloc); } /* Do not reclaim the symbols of the rule which action triggered this YYABORT or YYACCEPT. */ yypop_ (yylen); while (1 < yystate_stack_.height ()) { yydestruct_ ("Cleanup: popping", yystos_[yystate_stack_[0]], &yysemantic_stack_[0], &yylocation_stack_[0]); yypop_ (); } return yyresult; } catch (...) { YYCDEBUG << "Exception caught: cleaning lookahead and stack" << std::endl; // Do not try to display the values of the reclaimed symbols, // as their printer might throw an exception. if (yychar != yyempty_) { /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yytranslate_ (yychar); yydestruct_ (YY_NULL, yytoken, &yylval, &yylloc); } while (1 < yystate_stack_.height ()) { yydestruct_ (YY_NULL, yystos_[yystate_stack_[0]], &yysemantic_stack_[0], &yylocation_stack_[0]); yypop_ (); } throw; } } // Generate an error message. std::string selectParser::yysyntax_error_ (int yystate, int yytoken) { std::string yyres; // Number of reported tokens (one for the "unexpected", one per // "expected"). size_t yycount = 0; // Its maximum. enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; // Arguments of yyformat. char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; /* There are many possibilities here to consider: - If this state is a consistent state with a default action, then the only way this function was invoked is if the default action is an error action. In that case, don't check for expected tokens because there are none. - The only way there can be no lookahead present (in yytoken) is if this state is a consistent state with a default action. Thus, detecting the absence of a lookahead is sufficient to determine that there is no unexpected or expected token to report. In that case, just report a simple "syntax error". - Don't assume there isn't a lookahead just because this state is a consistent state with a default action. There might have been a previous inconsistent state, consistent state with a non-default action, or user semantic action that manipulated yychar. - Of course, the expected token list depends on states to have correct lookahead information, and it depends on the parser not to perform extra reductions after fetching a lookahead from the scanner and before detecting a syntax error. Thus, state merging (from LALR or IELR) and default reductions corrupt the expected token list. However, the list is correct for canonical LR with one exception: it will still contain any token that will not be accepted due to an error action in a later state. */ if (yytoken != yyempty_) { yyarg[yycount++] = yytname_[yytoken]; int yyn = yypact_[yystate]; if (!yy_pact_value_is_default_ (yyn)) { /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. In other words, skip the first -YYN actions for this state because they are default actions. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = yylast_ - yyn + 1; int yyxend = yychecklim < yyntokens_ ? yychecklim : yyntokens_; for (int yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck_[yyx + yyn] == yyx && yyx != yyterror_ && !yy_table_value_is_error_ (yytable_[yyx + yyn])) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; break; } else yyarg[yycount++] = yytname_[yyx]; } } } char const* yyformat = YY_NULL; switch (yycount) { #define YYCASE_(N, S) \ case N: \ yyformat = S; \ break YYCASE_(0, YY_("syntax error")); YYCASE_(1, YY_("syntax error, unexpected %s")); YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s")); YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s")); YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s")); YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s")); #undef YYCASE_ } // Argument number. size_t yyi = 0; for (char const* yyp = yyformat; *yyp; ++yyp) if (yyp[0] == '%' && yyp[1] == 's' && yyi < yycount) { yyres += yytnamerr_ (yyarg[yyi++]); ++yyp; } else yyres += *yyp; return yyres; } /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ const signed char selectParser::yypact_ninf_ = -13; const signed char selectParser::yypact_[] = { 126, 126, 126, -13, -12, -13, -6, -2, 126, 30, 126, 29, 20, 20, 113, 126, 126, 61, -13, -13, -13, 28, 126, 126, 126, 126, 126, 126, 126, 126, 2, -13, 24, 45, 93, 107, -13, 3, 68, 83, 0, 0, 20, 20, 20, 20, -13, -13, -13, 126, -13, -9, 4, -13, -13, 77, 25, 26, 38, 39, -13, -13, -13, -13, -13 }; /* YYDEFACT[S] -- default reduction number in state S. Performed when YYTABLE doesn't specify something else to do. Zero means the default is an error. */ const unsigned char selectParser::yydefact_[] = { 0, 0, 0, 30, 28, 29, 0, 0, 0, 0, 2, 0, 26, 25, 0, 0, 0, 0, 1, 3, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 27, 0, 17, 16, 10, 11, 12, 13, 14, 15, 7, 6, 18, 0, 19, 0, 0, 9, 8, 0, 0, 0, 0, 0, 24, 20, 21, 22, 23 }; /* YYPGOTO[NTERM-NUM]. */ const signed char selectParser::yypgoto_[] = { -13, 37, -13, -1 }; /* YYDEFGOTO[NTERM-NUM]. */ const signed char selectParser::yydefgoto_[] = { -1, 9, 10, 11 }; /* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule which number is the opposite. If YYTABLE_NINF_, syntax error. */ const signed char selectParser::yytable_ninf_ = -1; const unsigned char selectParser::yytable_[] = { 12, 13, 46, 53, 56, 57, 14, 17, 26, 27, 28, 29, 15, 33, 34, 35, 16, 58, 59, 47, 54, 38, 39, 40, 41, 42, 43, 44, 45, 20, 18, 29, 21, 22, 23, 24, 25, 26, 27, 28, 29, 37, 30, 48, 61, 62, 31, 19, 55, 22, 23, 24, 25, 26, 27, 28, 29, 63, 64, 0, 0, 0, 49, 0, 50, 22, 23, 24, 25, 26, 27, 28, 29, 23, 24, 25, 26, 27, 28, 29, 36, 22, 23, 24, 25, 26, 27, 28, 29, 24, 25, 26, 27, 28, 29, 0, 60, 22, 23, 24, 25, 26, 27, 28, 29, 0, 0, 0, 0, 0, 51, 22, 23, 24, 25, 26, 27, 28, 29, 1, 2, 32, 0, 0, 52, 3, 4, 5, 6, 7, 0, 8, 1, 2, 0, 0, 0, 0, 3, 4, 5, 6, 7, 0, 8 }; /* YYCHECK. */ const signed char selectParser::yycheck_[] = { 1, 2, 0, 0, 13, 14, 18, 8, 8, 9, 10, 11, 18, 14, 15, 16, 18, 13, 14, 17, 17, 22, 23, 24, 25, 26, 27, 28, 29, 0, 0, 11, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 13, 19, 19, 19, 17, 10, 49, 4, 5, 6, 7, 8, 9, 10, 11, 19, 19, -1, -1, -1, 17, -1, 19, 4, 5, 6, 7, 8, 9, 10, 11, 5, 6, 7, 8, 9, 10, 11, 19, 4, 5, 6, 7, 8, 9, 10, 11, 6, 7, 8, 9, 10, 11, -1, 19, 4, 5, 6, 7, 8, 9, 10, 11, -1, -1, -1, -1, -1, 17, 4, 5, 6, 7, 8, 9, 10, 11, 6, 7, 8, -1, -1, 17, 12, 13, 14, 15, 16, -1, 18, 6, 7, -1, -1, -1, -1, 12, 13, 14, 15, 16, -1, 18 }; /* STOS_[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ const unsigned char selectParser::yystos_[] = { 0, 6, 7, 12, 13, 14, 15, 16, 18, 21, 22, 23, 23, 23, 18, 18, 18, 23, 0, 21, 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 17, 8, 23, 23, 23, 19, 13, 23, 23, 23, 23, 23, 23, 23, 23, 0, 17, 19, 17, 19, 17, 17, 0, 17, 23, 13, 14, 13, 14, 19, 19, 19, 19, 19 }; #if YYDEBUG /* TOKEN_NUMBER_[YYLEX-NUM] -- Internal symbol number corresponding to YYLEX-NUM. */ const unsigned short int selectParser::yytoken_number_[] = { 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 44, 40, 41 }; #endif /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ const unsigned char selectParser::yyr1_[] = { 0, 20, 21, 21, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23 }; /* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */ const unsigned char selectParser::yyr2_[] = { 0, 2, 1, 2, 2, 2, 3, 3, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 6, 6, 6, 6, 6, 2, 2, 3, 1, 1, 1 }; /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at \a yyntokens_, nonterminals. */ const char* const selectParser::yytname_[] = { "\"end of input\"", "error", "$undefined", "\"as\"", "\"|\"", "\"&\"", "\"+\"", "\"-\"", "\"*\"", "\"/\"", "\"%\"", "\"**\"", "\"numerical value\"", "\"name\"", "\"string literal\"", "\"FORMAT_UNIXTIME_GMT\"", "\"FORMAT_UNIXTIME_LOCAL\"", "','", "'('", "')'", "$accept", "slist", "sterm", "mathExpr", YY_NULL }; #if YYDEBUG /* YYRHS -- A `-1'-separated list of the rules' RHS. */ const selectParser::rhs_number_type selectParser::yyrhs_[] = { 21, 0, -1, 22, -1, 22, 21, -1, 23, 17, -1, 23, 0, -1, 23, 13, 17, -1, 23, 13, 0, -1, 23, 3, 13, 17, -1, 23, 3, 13, 0, -1, 23, 6, 23, -1, 23, 7, 23, -1, 23, 8, 23, -1, 23, 9, 23, -1, 23, 10, 23, -1, 23, 11, 23, -1, 23, 5, 23, -1, 23, 4, 23, -1, 13, 18, 8, 19, -1, 13, 18, 23, 19, -1, 15, 18, 23, 17, 13, 19, -1, 15, 18, 23, 17, 14, 19, -1, 16, 18, 23, 17, 13, 19, -1, 16, 18, 23, 17, 14, 19, -1, 13, 18, 23, 17, 23, 19, -1, 7, 23, -1, 6, 23, -1, 18, 23, 19, -1, 13, -1, 14, -1, 12, -1 }; /* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in YYRHS. */ const unsigned char selectParser::yyprhs_[] = { 0, 0, 3, 5, 8, 11, 14, 18, 22, 27, 32, 36, 40, 44, 48, 52, 56, 60, 64, 69, 74, 81, 88, 95, 102, 109, 112, 115, 119, 121, 123 }; /* YYRLINE[YYN] -- Source line where rule number YYN was defined. */ const unsigned short int selectParser::yyrline_[] = { 0, 78, 78, 78, 79, 82, 85, 89, 93, 97, 104, 116, 128, 140, 152, 164, 176, 188, 200, 219, 423, 435, 447, 459, 471, 485, 495, 498, 501, 509, 517 }; // Print the state stack on the debug stream. void selectParser::yystack_print_ () { *yycdebug_ << "Stack now"; for (state_stack_type::const_iterator i = yystate_stack_.begin (); i != yystate_stack_.end (); ++i) *yycdebug_ << ' ' << *i; *yycdebug_ << std::endl; } // Report on the debug stream that the rule \a yyrule is going to be reduced. void selectParser::yy_reduce_print_ (int yyrule) { unsigned int yylno = yyrline_[yyrule]; int yynrhs = yyr2_[yyrule]; /* Print the symbols being reduced, and their result. */ *yycdebug_ << "Reducing stack by rule " << yyrule - 1 << " (line " << yylno << "):" << std::endl; /* The symbols being reduced. */ for (int yyi = 0; yyi < yynrhs; yyi++) YY_SYMBOL_PRINT (" $" << yyi + 1 << " =", yyrhs_[yyprhs_[yyrule] + yyi], &(yysemantic_stack_[(yynrhs) - (yyi + 1)]), &(yylocation_stack_[(yynrhs) - (yyi + 1)])); } #endif // YYDEBUG /* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */ selectParser::token_number_type selectParser::yytranslate_ (int t) { static const token_number_type translate_table[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 18, 19, 2, 2, 17, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; if ((unsigned int) t <= yyuser_token_number_max_) return translate_table[t]; else return yyundef_token_; } const int selectParser::yyeof_ = 0; const int selectParser::yylast_ = 144; const int selectParser::yynnts_ = 4; const int selectParser::yyempty_ = -2; const int selectParser::yyfinal_ = 18; const int selectParser::yyterror_ = 1; const int selectParser::yyerrcode_ = 256; const int selectParser::yyntokens_ = 20; const unsigned int selectParser::yyuser_token_number_max_ = 271; const selectParser::token_number_type selectParser::yyundef_token_ = 2; } // ibis /* Line 1135 of lalr1.cc */ #line 1649 "selectParser.cc" /* Line 1136 of lalr1.cc */ #line 526 "selectParser.yy" void ibis::selectParser::error(const ibis::selectParser::location_type& l, const std::string& m) { LOGGER(ibis::gVerbose >= 0) << "Warning -- ibis::selectParser encountered " << m << " at location " << l; }
34.425814
111
0.547987
nporsche
281874f0f50215f6ddae0de843f105fd9460a5dc
906
hpp
C++
src/unit/cavalry/knight.hpp
JoiNNewtany/LETI-Game
51d31a2b0b212f8bbd11c1562af4ef23d34437b6
[ "Unlicense" ]
2
2021-11-15T19:27:32.000Z
2021-12-10T20:51:37.000Z
src/unit/cavalry/knight.hpp
JoiNNewtany/LETI-Game
51d31a2b0b212f8bbd11c1562af4ef23d34437b6
[ "Unlicense" ]
null
null
null
src/unit/cavalry/knight.hpp
JoiNNewtany/LETI-Game
51d31a2b0b212f8bbd11c1562af4ef23d34437b6
[ "Unlicense" ]
null
null
null
#pragma once #include "unit/unit.hpp" class Knight : public Unit { public: Knight(int hp = 80, int dmg = 15, int df = 5) { health = hp; maxHealth = hp; damage = dmg; defense = df; graphics = 'k'; } ~Knight() {} virtual bool attack(Unit&) override; virtual Knight* duplicate() override; virtual void setHealth(int h) override { health = h; } virtual int getHealth() override { return health; } virtual void setDefense(int d) override { defense = d; } virtual int getDefense() override { return defense; } virtual void setDamage(int d) override { damage = d; } virtual int getDamage() override { return damage; } virtual void setGraphics(char g) override { graphics = g; } virtual char getGraphics() override { return graphics; } };
29.225806
67
0.572848
JoiNNewtany
2819887ad608e023490df95aa9871e8f846b53bd
151
cpp
C++
Src/Kranos/Layer.cpp
KDahir247/KranosLoader
5e55a0f1a697170020c2601c9b0d04b0da27da93
[ "MIT" ]
null
null
null
Src/Kranos/Layer.cpp
KDahir247/KranosLoader
5e55a0f1a697170020c2601c9b0d04b0da27da93
[ "MIT" ]
null
null
null
Src/Kranos/Layer.cpp
KDahir247/KranosLoader
5e55a0f1a697170020c2601c9b0d04b0da27da93
[ "MIT" ]
null
null
null
// // Created by kdahi on 2020-09-29. // #include "Layer.h" Layer::Layer(std::string name) : m_DebugName(std::move(name)) { } Layer::~Layer() { }
10.785714
63
0.609272
KDahir247
281a91c72bf7f47480b2a52e92ab2773f3aac8da
3,011
cpp
C++
simple-dx11-renderer/Systems/DataSystem.cpp
ike-0/simple-dx11-renderer
e6597e30d9675a56be84c8c26f78697cc16a7e25
[ "MIT" ]
null
null
null
simple-dx11-renderer/Systems/DataSystem.cpp
ike-0/simple-dx11-renderer
e6597e30d9675a56be84c8c26f78697cc16a7e25
[ "MIT" ]
null
null
null
simple-dx11-renderer/Systems/DataSystem.cpp
ike-0/simple-dx11-renderer
e6597e30d9675a56be84c8c26f78697cc16a7e25
[ "MIT" ]
null
null
null
#include "DataSystem.h" DataSystem* DataSystem::Instance = nullptr; DataSystem::DataSystem() { Instance = this; } DataSystem::~DataSystem() { Instance = nullptr; RemoveShaders(); } void DataSystem::LoadShaders() { try { std::filesystem::path shaderpath = Path::Relative("shaders\\"); for (auto& dir : std::filesystem::recursive_directory_iterator(shaderpath)) { if (dir.is_directory()) continue; if (dir.path().extension() == ".hlsl") { AddShaderFromPath(dir.path()); } } } catch (const std::filesystem::filesystem_error& e) { WARN("Could not load shaders" + e.what()); } catch (const std::exception& e) { WARN("Error" + e.what()); } } void DataSystem::LoadModels() { std::filesystem::path shaderpath = Path::Relative("meshes\\"); for (auto& dir : std::filesystem::recursive_directory_iterator(shaderpath)) { if (dir.is_directory()) continue; if (dir.path().extension() == ".dae" || dir.path().extension() == ".gltf" || dir.path().extension() == ".fbx") { AddModel(dir.path(), dir.path().parent_path()); } } } //void DataSystem::ReloadShaders() //{ // OnShadersReloadedEvent.Invoke(); // RemoveShaders(); // LoadShaders(); // ShadersReloadedEvent.Invoke(); //} void DataSystem::AddShaderFromPath(const std::filesystem::path& filepath) { Microsoft::WRL::ComPtr<ID3DBlob> blob = HLSLCompiler::LoadFromFile(filepath); std::filesystem::path filename = filepath.filename(); std::string ext = filename.replace_extension().extension().string(); filename.replace_extension(); ext.erase(0, 1); AddShader(filename.string(), ext, blob); } void DataSystem::AddModel(const std::filesystem::path& filepath, const std::filesystem::path& dir) { std::shared_ptr<Model> model; std::shared_ptr<AnimModel> animmodel; ModelLoader::LoadFromFile(filepath,dir, &model, &animmodel); if (model) { Models[model->name] = model; } } void DataSystem::AddShader(const std::string& name, const std::string& ext, const Microsoft::WRL::ComPtr<ID3DBlob>& blob) { if (ext == "vs") { VertexShader vs = VertexShader(name, blob); vs.Compile(); VertexShaders[name] = vs; } else if (ext == "hs") { HullShader hs = HullShader(name, blob); hs.Compile(); HullShaders[name] = hs; } else if (ext == "ds") { DomainShader ds = DomainShader(name, blob); ds.Compile(); DomainShaders[name] = ds; } else if (ext == "gs") { GeometryShader gs = GeometryShader(name, blob); gs.Compile(); GeometryShaders[name] = gs; } else if (ext == "ps") { PixelShader ps = PixelShader(name, blob); ps.Compile(); PixelShaders[name] = ps; } else if (ext == "cs") { ComputeShader cs = ComputeShader(name, blob); cs.Compile(); ComputeShaders[name] = cs; } else { WARN("Unrecognized shader extension \"" + ext + "\" for shader \"" + name + "\""); } } void DataSystem::RemoveShaders() { VertexShaders.clear(); HullShaders.clear(); DomainShaders.clear(); GeometryShaders.clear(); PixelShaders.clear(); ComputeShaders.clear(); }
20.909722
121
0.663235
ike-0
281c3004a31fa9001737787f07cd19fc22402ae9
4,920
cpp
C++
Other OJs/SPOJ/MSUBSTR.cpp
lxdlam/ACM
cde519ef9732ff9e4e9e3f53c00fb30d07bdb306
[ "MIT" ]
1
2019-11-12T15:08:16.000Z
2019-11-12T15:08:16.000Z
Other OJs/SPOJ/MSUBSTR.cpp
lxdlam/ACM
cde519ef9732ff9e4e9e3f53c00fb30d07bdb306
[ "MIT" ]
null
null
null
Other OJs/SPOJ/MSUBSTR.cpp
lxdlam/ACM
cde519ef9732ff9e4e9e3f53c00fb30d07bdb306
[ "MIT" ]
1
2021-05-05T01:16:28.000Z
2021-05-05T01:16:28.000Z
#include <bits/stdc++.h> using namespace std; #define TemplateVersion "3.4.1" // Useful Marcos //====================START===================== // Compile use C++11 and above #ifdef LOCAL #define debug(args...) \ { \ string _s = #args; \ replace(_s.begin(), _s.end(), ',', ' '); \ stringstream _ss(_s); \ istream_iterator<string> _it(_ss); \ err(_it, args); \ } void err(istream_iterator<string> it) {} template <typename T, typename... Args> void err(istream_iterator<string> it, T a, Args... args) { cerr << *it << " = " << a << endl; err(++it, args...); } #define MSG cout << "Finished" << endl #else #define debug(args...) #define MSG #endif #if __cplusplus >= 201703L template <typename... Args> void readln(Args&... args) { ((cin >> args), ...); } template <typename... Args> void writeln(Args... args) { ((cout << args << " "), ...); cout << endl; } #elif __cplusplus >= 201103L void readln() {} template <typename T, typename... Args> void readln(T& a, Args&... args) { cin >> a; readln(args...); } void writeln() { cout << endl; } template <typename T, typename... Args> void writeln(T a, Args... args) { cout << a << " "; writeln(args...); } #endif #if __cplusplus >= 201103L #define FOR(_i, _begin, _end) for (auto _i = _begin; _i < _end; _i++) #define FORR(_i, _begin, _end) for (auto _i = _begin; _i > _end; _i--) #else #define FOR(_i, _begin, _end) for (int _i = (int)_begin; _i < (int)_end; _i++) #define FORR(_i, _begin, _end) for (int _i = (int)_begin; _i > (int)_end; _i--) #define nullptr NULL #endif #if __cplusplus >= 201103L #define VIS(_kind, _name, _size) \ vector<_kind> _name(_size); \ for (auto& i : _name) cin >> i; #else #define VIS(_kind, _name, _size) \ vector<_kind> _name; \ _name.resize(_size); \ for (int i = 0; i < _size; i++) cin >> _name[i]; #endif // alias #define mp make_pair #define pb push_back #define eb emplace_back #define all(x) (x).begin(), (x).end() #define tcase() \ int T; \ cin >> T; \ FOR(kase, 1, T + 1) // Swap max/min template <typename T> bool smax(T& a, const T& b) { if (a > b) return false; a = b; return true; } template <typename T> bool smin(T& a, const T& b) { if (a < b) return false; a = b; return true; } // ceil divide template <typename T> T cd(T a, T b) { return (a + b - 1) / b; } // min exchange template <typename T> bool se(T& a, T& b) { if (a < b) return false; swap(a, b); return true; } // A better MAX choice const int INF = 0x3f3f3f3f; const long long INFLL = 0x3f3f3f3f3f3f3f3fLL; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pii; typedef vector<int> vi; typedef vector<ll> vll; typedef set<int> si; typedef vector<string> cb; //====================END===================== // Constants here const int CHAR_SIZE = 26; const char CHAR_START = 'a'; const int SIZE = 1e5 + 10; // String size map<int, int, greater<int>> m; struct PAM { int node[SIZE][CHAR_SIZE]; int fail[SIZE]; int cnt[SIZE]; // distinct palindromes at node i int num[SIZE]; // the number of palindroms which end with the end of longest // palindrome at node i int len[SIZE]; // length of the palindrome at node i int s[SIZE]; int last; // the longest palindrome's node int n; // count of character int p; // count of nodes int new_node(int le) { for (int i = 0; i < CHAR_SIZE; i++) node[p][i] = 0; cnt[p] = 0; num[p] = 0; len[p] = le; return p++; } void init() { p = 0; new_node(0); new_node(-1); last = n = 0; s[0] = -1; fail[0] = 1; } int get_fail(int x) { while (s[n - len[x] - 1] != s[n]) x = fail[x]; return x; } void add(char ch) { int c = ch - CHAR_START; s[++n] = c; int cur = get_fail(last); if (!node[cur][c]) { int now = new_node(len[cur] + 2); fail[now] = node[get_fail(fail[cur])][c]; node[cur][c] = now; num[now] = num[fail[now]] + 1; } last = node[cur][c]; cnt[last]++; } void get_cnt() { for (int i = p - 1; i >= 0; i--) { cnt[fail[i]] += cnt[i]; m[len[i]] += cnt[i]; } } int get_num() { return num[n]; } } pam; // Pre-Build Function inline void build() {} // Actual Solver inline void solve() { tcase() { pam.init(); m.clear(); string s; cin >> s; for (auto i : s) pam.add(i); pam.get_cnt(); writeln(m.begin()->first, m.begin()->second); } } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); #ifdef LOCAL clock_t _begin = clock(); #endif build(); solve(); #ifdef LOCAL cerr << "Time elapsed: " << (double)(clock() - _begin) * 1000 / CLOCKS_PER_SEC << "ms." << endl; #endif return 0; }
22.568807
98
0.552439
lxdlam
281c5f3d12b95787c73b64e42ee2bd5cf0a020d3
1,376
cc
C++
src/ft_ee_ua_size_op.cc
Incont/n-ftdi
fb9ec653b731c9e55d50a668be539b4774950c8b
[ "MIT" ]
2
2019-09-30T09:22:06.000Z
2019-09-30T14:40:11.000Z
src/ft_ee_ua_size_op.cc
Incont/n-ftdi
fb9ec653b731c9e55d50a668be539b4774950c8b
[ "MIT" ]
8
2019-09-05T05:18:45.000Z
2021-07-11T11:45:30.000Z
src/ft_ee_ua_size_op.cc
Incont/n-ftdi
fb9ec653b731c9e55d50a668be539b4774950c8b
[ "MIT" ]
3
2020-05-25T09:49:25.000Z
2020-06-29T18:34:47.000Z
#include "ft_ee_ua_size_op.h" Napi::Object FtEeUaSize::Init(Napi::Env env, Napi::Object exports) { exports.Set("eeUaSizeSync", Napi::Function::New(env, FtEeUaSize::InvokeSync)); exports.Set("eeUaSize", Napi::Function::New(env, FtEeUaSize::Invoke)); return exports; } Napi::Object FtEeUaSize::InvokeSync(const Napi::CallbackInfo &info) { FT_HANDLE ftHandle = (FT_HANDLE)info[0].As<Napi::External<void>>().Data(); DWORD uaSize; FT_STATUS ftStatus = FT_EE_UASize(ftHandle, &uaSize); return CreateResult(info.Env(), ftStatus, uaSize); } Napi::Promise FtEeUaSize::Invoke(const Napi::CallbackInfo &info) { FT_HANDLE ftHandle = (FT_HANDLE)info[0].As<Napi::External<void>>().Data(); auto *operation = new FtEeUaSize(info.Env(), ftHandle); operation->Queue(); return operation->Promise(); } FtEeUaSize::FtEeUaSize(Napi::Env env, FT_HANDLE ftHandle) : FtBaseOp(env), ftHandle(ftHandle) { } void FtEeUaSize::Execute() { ftStatus = FT_EE_UASize(ftHandle, &uaSize); } void FtEeUaSize::OnOK() { Napi::HandleScope scope(Env()); deferred.Resolve(CreateResult(Env(), ftStatus, uaSize)); } Napi::Object FtEeUaSize::CreateResult(Napi::Env env, FT_STATUS ftStatus, DWORD uaSize) { Napi::Object result = Napi::Object::New(env); result.Set("ftStatus", ftStatus); result.Set("uaSize", uaSize); return result; }
28.081633
86
0.695494
Incont
281cef6cd6f9e35263ab4bd3be968217ab81112d
5,880
cpp
C++
ScriptHookDotNet/ScriptThread.cpp
HazardX/gta4_scripthookdotnet
927b2830952664b63415234541a6c83592e53679
[ "MIT" ]
3
2021-11-14T20:59:58.000Z
2021-12-16T16:41:31.000Z
ScriptHookDotNet/ScriptThread.cpp
HazardX/gta4_scripthookdotnet
927b2830952664b63415234541a6c83592e53679
[ "MIT" ]
2
2021-11-29T14:41:23.000Z
2021-11-30T13:13:51.000Z
ScriptHookDotNet/ScriptThread.cpp
HazardX/gta4_scripthookdotnet
927b2830952664b63415234541a6c83592e53679
[ "MIT" ]
3
2021-11-21T12:41:55.000Z
2021-12-22T16:17:52.000Z
/* * Copyright (c) 2009-2011 Hazard (hazard_x@gmx.net / twitter.com/HazardX) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "stdafx.h" #include "NetThread.h" #include "ScriptThread.h" #include "RemoteScriptDomain.h" #include "Script.h" namespace GTA { #ifdef USE_NETTHREAD ScriptThread::ScriptThread(RemoteScriptDomain^ domain, String^ scriptFile, System::Type^ scriptType) { #else ScriptThread::ScriptThread(RemoteScriptDomain^ domain, String^ scriptFile, System::Type^ scriptType) :IngameThread(true) { #endif //SetName("CustomFiberThread"); //GTA::NetHook::LoadScripts(); this->domain = domain; this->scriptFile = scriptFile; this->scriptType = scriptType; } //ScriptThread::~ScriptThread() { // this->!ScriptThread(); //} //ScriptThread::!ScriptThread() { // if isNotNULL(scriptType) { // LogFin(scriptType->ToString()); // //delete scriptType; // scriptType = nullptr; // } // if isNotNULL(script) { // //delete script; // script = nullptr; // } //} [System::Runtime::ExceptionServices::HandleProcessCorruptedStateExceptions] bool ScriptThread::LoadScriptNow() { //if (!Game::isModdingAllowed) { // GTA::NetHook::Log(String::Concat( "Rejected start of script '", scriptType->FullName, "' in this multiplayer gamemode!" )); // //GTA::NetHook::DisplayText(String::Concat( "DO NOT USE MODS/SCRIPTS IN RANKED MULTIPLAYER GAMES!" ), 10000 ); // //Abort(); // return false ; //} currentlyLoading = this; if (VERBOSE) GTA::NetHook::Log(String::Concat( "Constructing script '", scriptType->FullName, "'..." )); try { if isNULL(scriptType) return false; // IMPORTANT: Constructor runs here already System::Object^ o = System::Activator::CreateInstance(scriptType); if isNULL(o) return false; script = static_cast<GTA::Script^>(o); //domain->LoadScript(scriptType); if isNotNULL(script) { script->Initialize(this); //if (VERBOSE) GTA::NetHook::Log(String::Concat( " ...successfully constructed script '", script->Name, "'!" )); return true; } else { //bError = true; return false; } } catch (System::InvalidOperationException^) { //Object::ReferenceEquals(ex,nullptr); // just a dummy to get rid of the warning //bError = true; return false; } catch (System::Reflection::TargetInvocationException^ ex) { try { if ( isNULL(ex) || isNULL(ex->InnerException) ) { throw gcnew Exception(); return false; } throw ex->InnerException; //} catch (System::MissingMethodException^ ex) { // if (ex->ToString()->Contains("GTA.value.ScriptSettings GTA.Script.get_Settings()")) continue; } catchErrors ("Error in constructor of script '"+scriptType->FullName+"'", ) return false; } catchErrors ("Error during construction of script '"+scriptType->FullName+"'", ) //bError = true; return false; } [System::Runtime::ExceptionServices::HandleProcessCorruptedStateExceptions] void ScriptThread::OnStartup() { bool bError = false; //lock(syncroot) { bError = !LoadScriptNow(); //bError = isNULL(script); if (!bError) { //if (!GTA::NetHook::RunScript(script)) bError = true; try { //if (VERBOSE) GTA::NetHook::Log(String::Concat( " ...starting script '", script->Name, "'..." )); domain->SetCurrentScript(script); // we have to set it here again, because script was still Nothing at startup script->DoStartup(); domain->AddRunningScript(script); GTA::NetHook::Log(String::Concat( " ...successfully started script '", script->Name, "'!" )); } catchScriptErrors (script, "Startup", bError = true; ) } if (bError) { GTA::NetHook::DisplayText( String::Concat("Error in script '", scriptType->FullName, "'!"), 5000 ); if isNotNULL(script) script->myThread = nullptr; Abort(); } //} unlock(syncroot); //script = GTA::NetHook::RunScript(scriptType); //if(script != nullptr) { // script->myThread = this; //} else { // Abort(); //} } [System::Runtime::ExceptionServices::HandleProcessCorruptedStateExceptions] void ScriptThread::OnTick() { //lock(syncroot) { if ( isNULL(script) || (!script->isRunning) ) { //Abort(); return; } try { script->DoTick(); } catch (System::Threading::ThreadAbortException^ taex) { throw taex; } catchScriptErrors (script, "Tick", if isNotNULL(script) script->Abort(); ) //} unlock(syncroot); } void ScriptThread::OnThreadContinue() { domain->SetCurrentScript(script); } void ScriptThread::OnThreadHalt() { //RemoteScriptDomain::Instance->RaiseEventInLocalScriptDomain("ThreadHalt",nullptr); domain->SetCurrentScript(nullptr); } void ScriptThread::OnEnd() { if isNotNULL(script) { if (VERBOSE) NetHook::Log("Script ended: " + script->Name); domain->RemoveRunningScript(script); } } }
31.44385
129
0.680442
HazardX
281fc5b4ad418631e464c9fb6bb424d4a7a74785
3,589
cpp
C++
doc/6.0.1/MPG/example-search-tracer.cpp
zayenz/gecode.github.io
e759c2c1940d9a018373bcc6c316d9cb04efa5a0
[ "MIT-feh" ]
1
2020-10-28T06:11:30.000Z
2020-10-28T06:11:30.000Z
doc/6.0.1/MPG/example-search-tracer.cpp
zayenz/gecode.github.io
e759c2c1940d9a018373bcc6c316d9cb04efa5a0
[ "MIT-feh" ]
1
2019-05-05T11:10:31.000Z
2019-05-05T11:10:31.000Z
doc/6.0.1/MPG/example-search-tracer.cpp
zayenz/gecode.github.io
e759c2c1940d9a018373bcc6c316d9cb04efa5a0
[ "MIT-feh" ]
4
2019-05-03T18:43:19.000Z
2020-12-17T04:06:59.000Z
/* * Authors: * Christian Schulte <schulte@gecode.org> * * Copyright: * Christian Schulte, 2008-2018 * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this 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 <gecode/search.hh> using namespace Gecode; class SimpleSearchTracer : public SearchTracer { protected: static const char* t2s(EngineType et) { switch (et) { case EngineType::DFS: return "DFS"; case EngineType::BAB: return "BAB"; case EngineType::LDS: return "LDS"; case EngineType::RBS: return "RBS"; case EngineType::PBS: return "PBS"; case EngineType::AOE: return "AOE"; } } public: SimpleSearchTracer(void) {} // init virtual void init(void) { std::cout << "trace<Search>::init()" << std::endl; for (unsigned int e=0U; e<engines(); e++) { std::cout << "\t" << e << ": " << t2s(engine(e).type()); if (engine(e).meta()) { // init for meta engines std::cout << ", engines: {"; for (unsigned int i=engine(e).efst(); i<engine(e).elst(); i++) { std::cout << i; if (i+1 < engine(e).elst()) std::cout << ","; } } else { // init for engines std::cout << ", workers: {"; for (unsigned int i=engine(e).wfst(); i<engine(e).wlst(); i++) { std::cout << i; if (i+1 < engine(e).wlst()) std::cout << ","; } } std::cout << "}" << std::endl; } } // node virtual void node(const EdgeInfo& ei, const NodeInfo& ni) { std::cout << "trace<Search>::node("; switch (ni.type()) { case NodeType::FAILED: std::cout << "FAILED"; break; case NodeType::SOLVED: std::cout << "SOLVED"; break; case NodeType::BRANCH: std::cout << "BRANCH(" << ni.choice().alternatives() << ")"; break; } std::cout << ',' << "w:" << ni.wid() << ',' << "n:" << ni.nid() << ')'; if (ei) { if (ei.wid() != ni.wid()) std::cout << " [stolen from w:" << ei.wid() << "]"; std::cout << std::endl << '\t' << ei.string() << std::endl; } else { std::cout << std::endl; } } // round virtual void round(unsigned int eid) { std::cout << "trace<Search>::round(e:" << eid << ")" << std::endl; } // skip virtual void skip(const EdgeInfo& ei) { std::cout << "trace<Search>Search::skip(w:" << ei.wid() << ",n:" << ei.nid() << ",a:" << ei.alternative() << ")" << std::endl; } // done virtual void done(void) { std::cout << "trace<Search>::done()" << std::endl; } virtual ~SimpleSearchTracer(void) {} };
33.231481
77
0.574255
zayenz
28257fdbab3a888d0240cdd2ddad2ef460f5574a
8,838
cpp
C++
binding-cpp/runtime/src/test/transport/EtchMessagizerTest.cpp
apache/etch
5a875755019a7f342a07c8c368a50e3efb6ae68c
[ "ECL-2.0", "Apache-2.0" ]
9
2015-02-14T15:09:54.000Z
2021-11-10T15:09:45.000Z
binding-cpp/runtime/src/test/transport/EtchMessagizerTest.cpp
apache/etch
5a875755019a7f342a07c8c368a50e3efb6ae68c
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
binding-cpp/runtime/src/test/transport/EtchMessagizerTest.cpp
apache/etch
5a875755019a7f342a07c8c368a50e3efb6ae68c
[ "ECL-2.0", "Apache-2.0" ]
14
2015-04-20T10:35:00.000Z
2021-11-10T15:09:35.000Z
/* $Id$ * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you under the Apache License, Version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <gtest/gtest.h> #include <gmock/gmock.h> #include "serialization/EtchDefaultValueFactory.h" #include "serialization/EtchBinaryTaggedData.h" #include "serialization/EtchBinaryTaggedDataInput.h" #include "serialization/EtchValidatorShort.h" #include "transport/EtchMessagizer.h" #include "transport/EtchTcpConnection.h" #include "transport/EtchPacketizer.h" #include "transport/EtchSessionListener.h" #include "transport/EtchTcpListener.h" class MockListener11 : public virtual EtchSessionListener<EtchSocket> { public: MockListener11(EtchTransport<EtchSessionListener<EtchSocket> >* transport) : mTransport(transport) { if(mTransport != NULL) { mTransport->setSession(this); } } virtual ~MockListener11() { if(mTransport != NULL) { delete mTransport; } } //This method is called status_t sessionAccepted(EtchSocket* connection) { delete connection; return ETCH_OK; } MOCK_METHOD2(sessionQuery, status_t(capu::SmartPointer<EtchObject> query, capu::SmartPointer<EtchObject> &result)); MOCK_METHOD2(sessionControl, status_t(capu::SmartPointer<EtchObject> control, capu::SmartPointer<EtchObject> value)); status_t sessionNotify(capu::SmartPointer<EtchObject> event) { return ETCH_OK; } private: EtchTransport<EtchSessionListener<EtchSocket> >* mTransport; }; class MockMailboxManager : public EtchSessionMessage { public: status_t sessionMessage(capu::SmartPointer<EtchWho> receipent, capu::SmartPointer<EtchMessage> buf) { EXPECT_TRUE(buf->count() == 1); buf->clear(); return ETCH_OK; } MOCK_METHOD2(sessionQuery, status_t(capu::SmartPointer<EtchObject> query, capu::SmartPointer<EtchObject> &result)); MOCK_METHOD2(sessionControl, status_t(capu::SmartPointer<EtchObject> control, capu::SmartPointer<EtchObject> value)); status_t sessionNotify(capu::SmartPointer<EtchObject> event) { return ETCH_OK; } }; class EtchMessagizerTest : public ::testing::Test { protected: virtual void SetUp() { mRuntime = new EtchRuntime(); mRuntime->start(); } virtual void TearDown() { mRuntime->shutdown(); delete mRuntime; mRuntime = NULL; } EtchRuntime* mRuntime; }; TEST_F(EtchMessagizerTest, constructorTest) { EtchTypeMap types; EtchClass2TypeMap class2type; EtchDefaultValueFactory * factory; EtchDefaultValueFactory::Init(mRuntime, &types, &class2type); EtchString uri("tcp://127.0.0.1:4001"); factory = new EtchDefaultValueFactory(uri, &types, &class2type); //created value factory EtchURL u("tcp://127.0.0.1:4001"); EtchResources r; EtchObject *out; r.put(EtchTransport<EtchSessionMessage>::VALUE_FACTORY(), factory, out); EtchTransportData* conn = new EtchTcpConnection(mRuntime, NULL, &u); EtchTransportPacket* pac = new EtchPacketizer(mRuntime, conn, &u); EtchSessionPacket* mes = new EtchMessagizer(mRuntime, pac, &u, &r); //Delete created stack delete conn; delete mes; delete pac; delete factory; types.clear(); } TEST_F(EtchMessagizerTest, TransportControlTest) { EtchTypeMap types; EtchClass2TypeMap class2type; EtchDefaultValueFactory * factory; MockMailboxManager manager; EtchDefaultValueFactory::Init(mRuntime, &types, &class2type); EtchString uri("tcp://127.0.0.1:4001"); factory = new EtchDefaultValueFactory(uri, &types, &class2type); //created value factory EtchURL u("tcp://127.0.0.1:4001"); EtchResources r; EtchObject *out; r.put(EtchTransport<EtchSessionMessage>::VALUE_FACTORY(), factory, out); EtchTransportData* conn = new EtchTcpConnection(mRuntime, NULL, &u); EtchPacketizer* pac = new EtchPacketizer(mRuntime, conn, &u); EtchMessagizer* mess = new EtchMessagizer(mRuntime, pac, &u, &r); mess->setSession(&manager); EtchTcpListener* transport = new EtchTcpListener(mRuntime, &u); EtchSessionListener<EtchSocket>* mSessionListener = new MockListener11(transport); transport->transportControl(new EtchString(EtchTcpListener::START_AND_WAIT_UP()), new EtchInt32(1000)); mess->transportControl(new EtchString(EtchPacketizer::START_AND_WAIT_UP()), new EtchInt32(1000)); //test transport commands mess->transportControl(new EtchString(EtchPacketizer::STOP_AND_WAIT_DOWN()), new EtchInt32(1000)); transport->transportControl(new EtchString(EtchTcpListener::STOP_AND_WAIT_DOWN()), new EtchInt32(1000)); delete conn; delete mSessionListener; delete pac; delete mess; delete factory; types.clear(); } TEST_F(EtchMessagizerTest, TransportMessageTest) { EtchTypeMap types; EtchClass2TypeMap class2type; EtchDefaultValueFactory * factory; MockMailboxManager manager; EtchDefaultValueFactory::Init(mRuntime, &types, &class2type); EtchString uri("tcp://127.0.0.1:4001"); factory = new EtchDefaultValueFactory(uri, &types, &class2type); //default value factory EtchURL u("tcp://127.0.0.1:4001"); EtchResources r; EtchObject *out; //add to the resource r.put(EtchTransport<EtchSessionMessage>::VALUE_FACTORY(), factory, out); EtchTransportData* conn = new EtchTcpConnection(mRuntime, NULL, &u); EtchPacketizer* pac = new EtchPacketizer(mRuntime, conn, &u); EtchMessagizer* mess = new EtchMessagizer(mRuntime, pac, &u, &r); mess->setSession(&manager); //creation of example message which will be serialized EtchType *mt_foo = NULL; EtchField mf_x("x"); EtchString str("foo"); factory->getType(str, mt_foo); capu::SmartPointer<EtchValidator> v; EtchValidatorShort::Get(mRuntime, 0, v); mt_foo->putValidator(mf_x, v); capu::SmartPointer<EtchShort> data = new EtchShort(10000); capu::SmartPointer<EtchMessage> msg = new EtchMessage(mt_foo, factory); msg->put(mf_x, data); EXPECT_TRUE(mess->transportMessage(NULL, msg) == ETCH_ERROR); delete conn; delete mess; delete pac; delete factory; types.clear(); } TEST_F(EtchMessagizerTest, SessionDataTest) { //creation of an example message to compare the deserialized messageMyValueFactory vf("tcp:"); EtchTypeMap types; EtchClass2TypeMap class2type; EtchString name1("a"); EtchString name2("b"); EtchType *mt_foo = new EtchType(1, name1); EtchField mf_x(2, name2); capu::SmartPointer<EtchValidator> v; EtchValidatorShort::Get(mRuntime, 0, v); mt_foo->putValidator(mf_x, v); types.add(mt_foo); capu::SmartPointer<EtchShort> data = new EtchShort(10000); //default value factory EtchDefaultValueFactory * factory; EtchDefaultValueFactory::Init(mRuntime, &types, &class2type); EtchString uri("tcp://127.0.0.1:4001"); factory = new EtchDefaultValueFactory(uri, &types, &class2type); capu::SmartPointer<EtchMessage> msg = new EtchMessage(mt_foo, factory); msg->put(mf_x, data); EtchURL u(uri); EtchResources r; EtchObject *out; //add the value factory to the resources r.put(EtchTransport<EtchSessionMessage>::VALUE_FACTORY(), factory, out); //create stack EtchTransportData* conn = new EtchTcpConnection(mRuntime, NULL, &u); EtchPacketizer* pac = new EtchPacketizer(mRuntime, conn, &u); EtchMessagizer* mess = new EtchMessagizer(mRuntime, pac, &u, &r); capu::SmartPointer<EtchFlexBuffer> buffer = new EtchFlexBuffer(); //A packet is created capu::int8_t byte_pos[] = {3, 1, 1, 2, -123, 39, 16, -127}; buffer->setByteRepresentation(ETCH_BIG_ENDIAN); buffer->put((capu::int8_t *)"_header_", pac->getHeaderSize()); buffer->put((capu::int8_t *)byte_pos, 8); buffer->setIndex(0); capu::int32_t pktsize = buffer->getLength() - pac->getHeaderSize(); buffer->put((capu::int8_t *) & pac->SIG, sizeof (capu::int32_t)); buffer->put((capu::int8_t *) & pktsize, sizeof (capu::int32_t)); buffer->setIndex(pac->getHeaderSize()); EXPECT_TRUE(buffer->getLength() == 16); //Simulate call with fake package EtchSessionMessage* mMailboxManager = new MockMailboxManager(); mess->setSession(mMailboxManager); EXPECT_TRUE(mess->sessionPacket(NULL, buffer) == ETCH_OK); mess->setSession(NULL); types.clear(); delete conn; delete mMailboxManager; delete pac; delete mess; delete factory; }
34.123552
119
0.739194
apache
2828538a14b2a0bbd6583b6dadb46893cfd40c07
2,177
cc
C++
components/spellcheck/renderer/platform_spelling_engine.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
components/spellcheck/renderer/platform_spelling_engine.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
components/spellcheck/renderer/platform_spelling_engine.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.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 "components/spellcheck/renderer/platform_spelling_engine.h" #include "content/public/renderer/render_thread.h" #include "services/service_manager/public/cpp/local_interface_provider.h" using content::RenderThread; SpellingEngine* CreateNativeSpellingEngine( service_manager::LocalInterfaceProvider* embedder_provider) { DCHECK(embedder_provider); return new PlatformSpellingEngine(embedder_provider); } PlatformSpellingEngine::PlatformSpellingEngine( service_manager::LocalInterfaceProvider* embedder_provider) : embedder_provider_(embedder_provider) {} PlatformSpellingEngine::~PlatformSpellingEngine() = default; spellcheck::mojom::SpellCheckHost& PlatformSpellingEngine::GetOrBindSpellCheckHost() { if (spell_check_host_) return *spell_check_host_; embedder_provider_->GetInterface(&spell_check_host_); return *spell_check_host_; } void PlatformSpellingEngine::Init(base::File bdict_file) { DCHECK(!bdict_file.IsValid()); } bool PlatformSpellingEngine::InitializeIfNeeded() { return false; } bool PlatformSpellingEngine::IsEnabled() { return true; } // Synchronously query against the platform's spellchecker. // TODO(groby): We might want async support here, too. Ideally, // all engines share a similar path for async requests. bool PlatformSpellingEngine::CheckSpelling(const base::string16& word_to_check, int tag) { bool word_correct = false; GetOrBindSpellCheckHost().CheckSpelling(word_to_check, tag, &word_correct); return word_correct; } // Synchronously query against the platform's spellchecker. // TODO(groby): We might want async support here, too. Ideally, // all engines share a similar path for async requests. void PlatformSpellingEngine::FillSuggestionList( const base::string16& wrong_word, std::vector<base::string16>* optional_suggestions) { GetOrBindSpellCheckHost().FillSuggestionList(wrong_word, optional_suggestions); }
34.015625
79
0.762058
zipated
28286fc38f45510bdb7d3e72f057aa401cd1e532
8,781
cpp
C++
wrap/csllbc/native/src/comm/_Service.cpp
shakeumm/llbc
5aaf6f83eedafde87d52adf44b7548e85ad4a9d1
[ "MIT" ]
5
2021-10-31T17:12:45.000Z
2022-01-10T11:10:27.000Z
wrap/csllbc/native/src/comm/_Service.cpp
shakeumm/llbc
5aaf6f83eedafde87d52adf44b7548e85ad4a9d1
[ "MIT" ]
1
2019-09-04T12:23:37.000Z
2019-09-04T12:23:37.000Z
wrap/csllbc/native/src/comm/_Service.cpp
ericyonng/llbc
a7fd1193db03b8ad34879441b09914adec8a62e6
[ "MIT" ]
null
null
null
// The MIT License (MIT) // Copyright (c) 2013 lailongwei<lailongwei@126.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. #include "csllbc/common/Export.h" #include "csllbc/comm/csCoder.h" #include "csllbc/comm/csFacade.h" #include "csllbc/comm/csService.h" #include "csllbc/comm/_Service.h" LLBC_BEGIN_C_DECL csllbc_Service *csllbc_Service_Create(int svcType, const char *svcName, bool fullStack, csllbc_Delegates::Deleg_Service_EncodePacket encodeDeleg, csllbc_Delegates::Deleg_Service_DecodePacket decodeDeleg, csllbc_Delegates::Deleg_Service_PacketHandler handlerDeleg, csllbc_Delegates::Deleg_Service_PacketPreHandler preHandlerDeleg, csllbc_Delegates::Deleg_Service_PacketUnifyPreHandler unifyPreHandlerDeleg, csllbc_Delegates::Deleg_Service_NativeCouldNotFoundDecoderReport notFoundDecoderDeleg) { if (svcType != static_cast<int>(LLBC_IService::Raw) && svcType != static_cast<int>(LLBC_IService::Normal)) { LLBC_SetLastError(LLBC_ERROR_ARG); return NULL; } return LLBC_New9(csllbc_Service, static_cast<csllbc_Service::Type>(svcType), svcName, fullStack != 0, encodeDeleg, decodeDeleg, handlerDeleg, preHandlerDeleg, unifyPreHandlerDeleg, notFoundDecoderDeleg); } void csllbc_Service_Delete(csllbc_Service *svc) { LLBC_XDelete(svc); } int csllbc_Service_GetType(csllbc_Service *svc) { return static_cast<int>(svc->GetType()); } int csllbc_Service_GetId(csllbc_Service *svc) { return svc->GetId(); } int csllbc_Service_IsFullStack(csllbc_Service *svc) { return svc->IsFullStack() ? 1 : 0; } int csllbc_Service_GetDriveMode(csllbc_Service *svc) { return static_cast<int>(svc->GetDriveMode()); } int csllbc_Service_SetDriveMode(csllbc_Service *svc, int driveMode) { return svc->SetDriveMode(static_cast<LLBC_IService::DriveMode>(driveMode)); } int csllbc_Service_Start(csllbc_Service *svc, int pollerCount) { return svc->Start(pollerCount); } void csllbc_Service_Stop(csllbc_Service *svc) { svc->Stop(); } int csllbc_Service_IsStarted(csllbc_Service *svc) { return svc->IsStarted() ? 1 : 0; } int csllbc_Service_GetFPS(csllbc_Service *svc) { return svc->GetFPS(); } int csllbc_Service_SetFPS(csllbc_Service *svc, int fps) { return svc->SetFPS(fps); } int csllbc_Service_GetFrameInterval(csllbc_Service *svc) { return svc->GetFrameInterval(); } int csllbc_Service_Listen(csllbc_Service *svc, const char *ip, int port) { return svc->Listen(ip, port); } int csllbc_Service_Connect(csllbc_Service *svc, const char *ip, int port) { return svc->Connect(ip, port); } int csllbc_Service_AsyncConn(csllbc_Service *svc, const char *ip, int port) { return svc->AsyncConn(ip, port); } int csllbc_Service_RemoveSession(csllbc_Service *svc, int sessionId, const char *reason, int reasonLength) { char *nativeReason; if (reasonLength == 0) { nativeReason = NULL; } else { nativeReason = LLBC_Malloc(char, reasonLength + 1); memcpy(nativeReason, reason, reasonLength); nativeReason[reasonLength] = '\0'; } const int ret = svc->RemoveSession(sessionId, nativeReason); LLBC_XFree(nativeReason); return ret; } int csllbc_Service_IsSessionValidate(csllbc_Service *svc, int sessionId) { return svc->IsSessionValidate(sessionId) ? 1 : 0; } int csllbc_Service_SendBytes(csllbc_Service *svc, int sessionId, int opcode, const void *data, int dataLen, int status) { return svc->Send(sessionId, opcode, data, static_cast<size_t>(dataLen), status); } int csllbc_Service_SendPacket(csllbc_Service *svc, int sessionId, int opcode, sint64 packetId, int status) { csllbc_Coder *coder = LLBC_New(csllbc_Coder); coder->SetEncodeInfo(packetId, svc->GetEncodePacketDeleg()); if (svc->Send(sessionId, opcode, coder, status) != LLBC_OK) { LLBC_Delete(coder); return LLBC_FAILED; } return LLBC_OK; } int csllbc_Service_Multicast(csllbc_Service *svc, int *sessionIds, int sessionIdCount, int opcode, const void *data, int dataLen, int status) { LLBC_SessionIdList sessionIdList(sessionIdCount); for (int idx = 0; idx < sessionIdCount; ++idx) sessionIdList.push_back(sessionIds[idx]); LLBC_XFree(sessionIds); return svc->Multicast(sessionIdList, opcode, data, static_cast<size_t>(dataLen), status); } int csllbc_Service_Broadcast(csllbc_Service *svc, int opcode, const void *data, int dataLen, int status) { return svc->Broadcast(opcode, data, static_cast<size_t>(dataLen), status); } int csllbc_Service_RegisterFacade(csllbc_Service *svc, csllbc_Delegates::Deleg_Facade_OnInit initDeleg, csllbc_Delegates::Deleg_Facade_OnDestroy destroyDeleg, csllbc_Delegates::Deleg_Facade_OnStart startDeleg, csllbc_Delegates::Deleg_Facade_OnStop stopDeleg, csllbc_Delegates::Deleg_Facade_OnUpdate updateDeleg, csllbc_Delegates::Deleg_Facade_OnIdle idleDeleg, csllbc_Delegates::Deleg_Facade_OnSessionCreate sessionCreateDeleg, csllbc_Delegates::Deleg_Facade_OnSessionDestroy sessionDestroyDeleg, csllbc_Delegates::Deleg_Facade_OnAsyncConnResult asyncConnResultDeleg, csllbc_Delegates::Deleg_Facade_OnProtoReport protoReportDeleg, csllbc_Delegates::Deleg_Facade_OnUnHandledPacket unHandledPacketDeleg) { csllbc_Facade *facade = new csllbc_Facade(initDeleg, destroyDeleg, startDeleg, stopDeleg, updateDeleg, idleDeleg, sessionCreateDeleg, sessionDestroyDeleg, asyncConnResultDeleg, protoReportDeleg, unHandledPacketDeleg); if (svc->RegisterFacade(facade) != LLBC_OK) { LLBC_Delete(facade); return LLBC_FAILED; } return LLBC_OK; } int csllbc_Service_RegisterCoder(csllbc_Service *svc, int opcode) { return svc->RegisterCoder(opcode); } int csllbc_Service_Subscribe(csllbc_Service *svc, int opcode) { return svc->Subscribe(opcode); } int csllbc_Service_PreSubscribe(csllbc_Service *svc, int opcode) { return svc->PreSubscribe(opcode); } int csllbc_Service_UnifyPreSubscribe(csllbc_Service *svc) { return svc->UnifyPreSubscribe(); } void csllbc_Service_OnSvc(csllbc_Service *svc, bool fullFrame) { svc->OnSvc(fullFrame); } LLBC_END_C_DECL
32.643123
124
0.623961
shakeumm
282c19a79fdd2e73cbab17a4ac5b4a42ea2f5aaf
1,511
cpp
C++
ABC197/e.cpp
KoukiNAGATA/c-
ae51bacb9facb936a151dd777beb6688383a2dcd
[ "MIT" ]
null
null
null
ABC197/e.cpp
KoukiNAGATA/c-
ae51bacb9facb936a151dd777beb6688383a2dcd
[ "MIT" ]
3
2021-03-31T01:39:25.000Z
2021-05-04T10:02:35.000Z
ABC197/e.cpp
KoukiNAGATA/c-
ae51bacb9facb936a151dd777beb6688383a2dcd
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define REP(i, n) for (int i = 0; i < n; i++) #define REPR(i, n) for (int i = n - 1; i >= 0; i--) #define FOR(i, m, n) for (int i = m; i <= n; i++) #define FORR(i, m, n) for (int i = m; i >= n; i--) #define SORT(v, n) sort(v, v + n) #define MAX 100000 #define inf 1000000007 using namespace std; using ll = long long; using vll = vector<ll>; using vvll = vector<vector<ll>>; using P = pair<ll, ll>; using Graph = vector<vector<int>>; int main() { // cin高速化 cin.tie(0); ios::sync_with_stdio(false); int n; cin >> n; vector<vector<int>> ball(n + 1); // 色名の管理 set<int> ctyp; int x, c; REP(i, n) { cin >> x >> c; ball[c].push_back(x); ctyp.insert(c); } // 色iまで回収し終えたあとに左・右端にいるスコアの最小値 // 左端にいる場合のスコア、右端にいる場合のスコア ll lscore = 0, rscore = 0; // 0色回収後の色 int lnew = 0, rnew = 0; for (auto c : ctyp) { sort(ball[c].begin(), ball[c].end()); // 次の色の左端、右端の座標 int l = ball[c][0], r = ball[c][ball[c].size() - 1]; // lnew or rnewからrに移動して、rからlへ回収 ll lmi = min(lscore + abs(r - lnew), rscore + abs(r - rnew)) + abs(r - l); // lnew or rnewからlに移動して、lからrへ回収 ll rmi = min(lscore + abs(l - lnew), rscore + abs(l - rnew)) + abs(r - l); // 更新後のスコア lscore = lmi; rscore = rmi; // 操作後の座標 lnew = l; rnew = r; } // 原点へ戻る cout << min(lscore + abs(lnew), rscore + abs(rnew)) << "\n"; return 0; }
26.051724
82
0.512244
KoukiNAGATA
282c401068b45c3be3e3878068c02abbf2ac662e
5,002
hpp
C++
Zaimoni.STL/iterator_array_size.hpp
zaimoni/Iskandria
b056d2ba359b814db02aab42eba8d5f7f5ca7a1a
[ "BSL-1.0" ]
2
2019-11-23T12:35:49.000Z
2022-02-10T08:27:54.000Z
Zaimoni.STL/iterator_array_size.hpp
zaimoni/Iskandria
b056d2ba359b814db02aab42eba8d5f7f5ca7a1a
[ "BSL-1.0" ]
8
2019-11-15T08:13:48.000Z
2020-04-29T00:35:42.000Z
Zaimoni.STL/iterator_array_size.hpp
zaimoni/Iskandria
b056d2ba359b814db02aab42eba8d5f7f5ca7a1a
[ "BSL-1.0" ]
null
null
null
// iterator_array_size.hpp #ifndef ITERATOR_ARRAY_SIZE_HPP #define ITERATOR_ARRAY_SIZE_HPP 1 #include "Logging.h" #include "iterator.on.hpp" #include <iterator> namespace zaimoni { template<class T> class iterator_array_size { public: typedef typename T::difference_type difference_type; // these five aligned with container typedef typename T::size_type size_type; typedef typename T::value_type value_type; typedef typename T::reference reference; typedef typename T::pointer pointer; typedef std::random_access_iterator_tag iterator_category; private: T* _src; size_type _i; bool can_dereference() const {return _src && _i < _src->size();} public: bool is_valid() const {return _src && _i <= _src->size();} // for post-condition testing iterator_array_size(T* src = 0, size_type offset = 0) : _src(src),_i(offset) {}; ZAIMONI_DEFAULT_COPY_DESTROY_ASSIGN(iterator_array_size); bool operator==(const iterator_array_size& rhs) const {return _src==rhs._src && _i==rhs._i;} reference operator*() const { assert(can_dereference()); return (*_src)[_i]; }; iterator_array_size& operator++() { // prefix if (_src->size() > _i) _i++; return *this; }; iterator_array_size operator++(int) { // postfix iterator_array_size ret(*this); if (_src->size() > _i) _i++; return ret; }; // bidirectional iterator_array_size& operator--() { // prefix if (0 < _i) _i--; return *this; }; iterator_array_size operator--(int) { // postfix iterator_array_size ret(*this); if (0 < _i) _i--; return ret; }; // random access iterator_array_size& operator+=(difference_type n) { if (0<n) { assert(_src.size()-_i >= n); _i += n; } else if (0>n) { assert(_i >= -n); _i += n; } return *this; }; iterator_array_size& operator-=(difference_type n) { if (0<n) { assert(_i >= -n); _i -= n; } else if (0>n) { assert(_src.size()-_i >= n); _i -= n; } return *this; }; difference_type operator-(const iterator_array_size& rhs) { assert(_src==rhs._src); return _i-rhs._i; } reference operator[](size_type n) const { assert(_src->size()-_i >= n); return _src[_i+n]; } bool operator<(const iterator_array_size& rhs) const { assert(_src==rhs._src); return _i < rhs._i; } ZAIMONI_ITER_DECLARE(iterator_array_size) }; template<class T> class const_iterator_array_size { public: typedef typename T::difference_type difference_type; // these five aligned with container typedef typename T::size_type size_type; typedef const typename T::value_type value_type; typedef const typename T::reference reference; typedef const typename T::pointer pointer; typedef std::random_access_iterator_tag iterator_category; private: const T* _src; size_type _i; bool can_dereference() const {return _src && _i < _src->size();} public: bool is_valid() const {return _src && _i <= _src->size();} // for post-condition testing const_iterator_array_size(const T* src = 0, size_type offset = 0) : _src(src),_i(offset) {}; ZAIMONI_DEFAULT_COPY_DESTROY_ASSIGN(const_iterator_array_size); bool operator==(const const_iterator_array_size& rhs) const {return _src==rhs._src && _i==rhs._i;} reference operator*() const { assert(can_dereference()); return (*_src)[_i]; }; const_iterator_array_size& operator++() { // prefix if (_src->size() > _i) _i++; assert(is_valid()); return *this; }; const_iterator_array_size operator++(int) { // postfix const_iterator_array_size ret(*this); if (_src->size() > _i) _i++; assert(is_valid()); return ret; }; // bidirectional const_iterator_array_size& operator--() { // prefix if (0 < _i) _i--; assert(is_valid()); return *this; }; const_iterator_array_size operator--(int) { // postfix const_iterator_array_size ret(*this); if (0 < _i) _i--; assert(is_valid()); return ret; }; const_iterator_array_size& operator+=(difference_type n) { // postfix if (0<n) { assert(_src.size()-_i >= n); _i += n; } else if (0>n) { assert(_i >= -n); _i += n; } assert(is_valid()); return *this; }; const_iterator_array_size& operator-=(difference_type n) { if (0<n) { assert(_i >= -n); _i -= n; } else if (0>n) { assert(_src.size()-_i >= n); _i -= n; } assert(is_valid()); return *this; }; difference_type operator-(const const_iterator_array_size& rhs) const { assert(_src==rhs._src); return _i-rhs._i; } reference operator[](size_type n) const { // random access assert(_src->size()-_i >= n); return _src[_i+n]; } bool operator<(const const_iterator_array_size& rhs) const { assert(_src==rhs._src); return _i < rhs._i; } ZAIMONI_ITER_DECLARE(const_iterator_array_size) }; } // namespace zaimoni #undef ZAIMONI_ITER_DECLARE #endif
24.885572
100
0.647341
zaimoni
282d1de720e5f1e4780992e97cf6ce995786aa92
62
cpp
C++
Src/Evora/Engine/game_state.cpp
medovina/Evora
95e41e7b2d5c408d515a01a5649ddfaa211e9349
[ "Apache-2.0" ]
1
2020-11-25T20:53:36.000Z
2020-11-25T20:53:36.000Z
Src/Evora/Engine/game_state.cpp
medovina/Evora
95e41e7b2d5c408d515a01a5649ddfaa211e9349
[ "Apache-2.0" ]
16
2020-03-06T09:11:55.000Z
2020-07-24T10:57:41.000Z
Src/Evora/Engine/game_state.cpp
medovina/Evora
95e41e7b2d5c408d515a01a5649ddfaa211e9349
[ "Apache-2.0" ]
1
2020-01-18T13:11:38.000Z
2020-01-18T13:11:38.000Z
#include "game_state.h" game_state::~game_state() = default;
15.5
36
0.725806
medovina
28306a60542b3d1077c9f2f0a2c231c56e530088
443
cpp
C++
boost/join.cpp
ysoftman/test_code
4c71cc7c6a17d73cc84298e3a44051d3ab9d40f8
[ "MIT" ]
3
2017-12-07T04:29:36.000Z
2022-01-11T10:58:14.000Z
boost/join.cpp
ysoftman/test_code
4c71cc7c6a17d73cc84298e3a44051d3ab9d40f8
[ "MIT" ]
14
2018-07-17T05:16:42.000Z
2022-03-22T00:43:47.000Z
boost/join.cpp
ysoftman/test_code
4c71cc7c6a17d73cc84298e3a44051d3ab9d40f8
[ "MIT" ]
null
null
null
// ysoftman // boost join 사용하기 #include <iostream> #include <vector> #include <string> #include <boost/algorithm/string/join.hpp> using namespace std; int main() { cout << "boost join test" << endl; vector<string> strVec; strVec.push_back("Yoon"); strVec.push_back("Byoung"); strVec.push_back("Hoon"); string joined_string = boost::algorithm::join(strVec, ",\n"); cout << joined_string << endl; return 0; }
19.26087
65
0.654628
ysoftman
283206c28f3ee30b3afe64271cb1a35d04d539d4
1,525
cpp
C++
src/read_fasta.cpp
danielsundfeld/cuda_sankoff
dd765a2707b14aef24852a7e1d4d6e5df565d38d
[ "MIT" ]
null
null
null
src/read_fasta.cpp
danielsundfeld/cuda_sankoff
dd765a2707b14aef24852a7e1d4d6e5df565d38d
[ "MIT" ]
null
null
null
src/read_fasta.cpp
danielsundfeld/cuda_sankoff
dd765a2707b14aef24852a7e1d4d6e5df565d38d
[ "MIT" ]
null
null
null
/*! * \author Daniel Sundfeld * \copyright MIT License */ #include "read_fasta.h" #include <fstream> #include <iostream> #include <string> #include "Sequences.h" int read_fasta_file_core(const std::string &name) { std::ifstream file(name.c_str()); Sequences *sequences = Sequences::get_instance(); if (!file.is_open()) { std::cout << "Can't open file " << name << std::endl; return -1; } while (!file.eof()) { std::string seq; while (!file.eof()) { std::string buf; getline(file, buf); if ((buf.length() <= 0) || (buf.at(0) == '>')) break; seq.append(buf); } if (!seq.empty()) sequences->set_seq(seq); } return 0; } /*! * Read the \a name fasta file, loading it to the Sequences singleton. * Fail if the number of sequences is non-null and not equal to \a limit */ int read_fasta_file(const std::string &name, const int &check) { try { int ret = read_fasta_file_core(name); if (ret == 0 && check != 0 && Sequences::get_nseq() != check) { std::cerr << "Invalid fasta file: must have " << check << " sequences.\n"; return -1; } return ret; } catch (std::exception &e) { std::cerr << "Reading file fatal error: " << e.what() << std::endl; } catch (...) { std::cerr << "Unknown fatal error while reading file!\n"; } return -1; }
22.761194
86
0.523934
danielsundfeld
283245e594d24b971e8c22fbe2604a2550742e54
22,479
cc
C++
third_party/blink/renderer/modules/indexeddb/idb_database.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
third_party/blink/renderer/modules/indexeddb/idb_database.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
third_party/blink/renderer/modules/indexeddb/idb_database.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
/* * Copyright (C) 2010 Google 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: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS 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 APPLE OR ITS 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 "third_party/blink/renderer/modules/indexeddb/idb_database.h" #include <limits> #include <memory> #include <utility> #include "base/atomic_sequence_num.h" #include "base/optional.h" #include "third_party/blink/public/common/browser_interface_broker_proxy.h" #include "third_party/blink/public/common/indexeddb/web_idb_types.h" #include "third_party/blink/public/mojom/indexeddb/indexeddb.mojom-blink.h" #include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules.h" #include "third_party/blink/renderer/core/dom/events/event_queue.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/modules/indexed_db_names.h" #include "third_party/blink/renderer/modules/indexeddb/idb_any.h" #include "third_party/blink/renderer/modules/indexeddb/idb_event_dispatcher.h" #include "third_party/blink/renderer/modules/indexeddb/idb_index.h" #include "third_party/blink/renderer/modules/indexeddb/idb_key_path.h" #include "third_party/blink/renderer/modules/indexeddb/idb_tracing.h" #include "third_party/blink/renderer/modules/indexeddb/idb_version_change_event.h" #include "third_party/blink/renderer/modules/indexeddb/web_idb_database_callbacks.h" #include "third_party/blink/renderer/modules/indexeddb/web_idb_database_callbacks_impl.h" #include "third_party/blink/renderer/modules/indexeddb/web_idb_transaction_impl.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/heap/heap.h" #include "third_party/blink/renderer/platform/wtf/assertions.h" #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" namespace blink { const char IDBDatabase::kIndexDeletedErrorMessage[] = "The index or its object store has been deleted."; const char IDBDatabase::kIndexNameTakenErrorMessage[] = "An index with the specified name already exists."; const char IDBDatabase::kIsKeyCursorErrorMessage[] = "The cursor is a key cursor."; const char IDBDatabase::kNoKeyOrKeyRangeErrorMessage[] = "No key or key range specified."; const char IDBDatabase::kNoSuchIndexErrorMessage[] = "The specified index was not found."; const char IDBDatabase::kNoSuchObjectStoreErrorMessage[] = "The specified object store was not found."; const char IDBDatabase::kNoValueErrorMessage[] = "The cursor is being iterated or has iterated past its end."; const char IDBDatabase::kNotValidKeyErrorMessage[] = "The parameter is not a valid key."; const char IDBDatabase::kNotVersionChangeTransactionErrorMessage[] = "The database is not running a version change transaction."; const char IDBDatabase::kObjectStoreDeletedErrorMessage[] = "The object store has been deleted."; const char IDBDatabase::kObjectStoreNameTakenErrorMessage[] = "An object store with the specified name already exists."; const char IDBDatabase::kRequestNotFinishedErrorMessage[] = "The request has not finished."; const char IDBDatabase::kSourceDeletedErrorMessage[] = "The cursor's source or effective object store has been deleted."; const char IDBDatabase::kTransactionInactiveErrorMessage[] = "The transaction is not active."; const char IDBDatabase::kTransactionFinishedErrorMessage[] = "The transaction has finished."; const char IDBDatabase::kTransactionReadOnlyErrorMessage[] = "The transaction is read-only."; const char IDBDatabase::kDatabaseClosedErrorMessage[] = "The database connection is closed."; IDBDatabase::IDBDatabase( ExecutionContext* context, std::unique_ptr<WebIDBDatabase> backend, IDBDatabaseCallbacks* callbacks, mojo::PendingRemote<mojom::blink::ObservedFeature> connection_lifetime) : ExecutionContextLifecycleObserver(context), backend_(std::move(backend)), connection_lifetime_(std::move(connection_lifetime)), event_queue_( MakeGarbageCollected<EventQueue>(context, TaskType::kDatabaseAccess)), database_callbacks_(callbacks), feature_handle_for_scheduler_( context ? context->GetScheduler()->RegisterFeature( SchedulingPolicy::Feature::kIndexedDBConnection, {SchedulingPolicy::DisableBackForwardCache()}) : FrameOrWorkerScheduler::SchedulingAffectingFeatureHandle()) { database_callbacks_->Connect(this); } IDBDatabase::~IDBDatabase() { if (!close_pending_ && backend_) backend_->Close(); } void IDBDatabase::Trace(Visitor* visitor) const { visitor->Trace(version_change_transaction_); visitor->Trace(transactions_); visitor->Trace(event_queue_); visitor->Trace(database_callbacks_); EventTargetWithInlineData::Trace(visitor); ExecutionContextLifecycleObserver::Trace(visitor); } int64_t IDBDatabase::NextTransactionId() { // Starts at 1, unlike AtomicSequenceNumber. // Only keep a 32-bit counter to allow ports to use the other 32 // bits of the id. static base::AtomicSequenceNumber current_transaction_id; return current_transaction_id.GetNext() + 1; } void IDBDatabase::SetMetadata(const IDBDatabaseMetadata& metadata) { metadata_ = metadata; } void IDBDatabase::SetDatabaseMetadata(const IDBDatabaseMetadata& metadata) { metadata_.CopyFrom(metadata); } void IDBDatabase::TransactionCreated(IDBTransaction* transaction) { DCHECK(transaction); DCHECK(!transactions_.Contains(transaction->Id())); transactions_.insert(transaction->Id(), transaction); if (transaction->IsVersionChange()) { DCHECK(!version_change_transaction_); version_change_transaction_ = transaction; } } void IDBDatabase::TransactionFinished(const IDBTransaction* transaction) { DCHECK(transaction); DCHECK(transactions_.Contains(transaction->Id())); DCHECK_EQ(transactions_.at(transaction->Id()), transaction); transactions_.erase(transaction->Id()); if (transaction->IsVersionChange()) { DCHECK_EQ(version_change_transaction_, transaction); version_change_transaction_ = nullptr; } if (close_pending_ && transactions_.IsEmpty()) CloseConnection(); } void IDBDatabase::OnAbort(int64_t transaction_id, DOMException* error) { DCHECK(transactions_.Contains(transaction_id)); transactions_.at(transaction_id)->OnAbort(error); } void IDBDatabase::OnComplete(int64_t transaction_id) { DCHECK(transactions_.Contains(transaction_id)); transactions_.at(transaction_id)->OnComplete(); } DOMStringList* IDBDatabase::objectStoreNames() const { auto* object_store_names = MakeGarbageCollected<DOMStringList>(); for (const auto& it : metadata_.object_stores) object_store_names->Append(it.value->name); object_store_names->Sort(); return object_store_names; } const String& IDBDatabase::GetObjectStoreName(int64_t object_store_id) const { const auto& it = metadata_.object_stores.find(object_store_id); DCHECK(it != metadata_.object_stores.end()); return it->value->name; } IDBObjectStore* IDBDatabase::createObjectStore( const String& name, const IDBKeyPath& key_path, bool auto_increment, ExceptionState& exception_state) { IDB_TRACE("IDBDatabase::createObjectStore"); if (!version_change_transaction_) { exception_state.ThrowDOMException( DOMExceptionCode::kInvalidStateError, IDBDatabase::kNotVersionChangeTransactionErrorMessage); return nullptr; } if (!version_change_transaction_->IsActive()) { exception_state.ThrowDOMException( DOMExceptionCode::kTransactionInactiveError, version_change_transaction_->InactiveErrorMessage()); return nullptr; } if (!key_path.IsNull() && !key_path.IsValid()) { exception_state.ThrowDOMException( DOMExceptionCode::kSyntaxError, "The keyPath option is not a valid key path."); return nullptr; } if (ContainsObjectStore(name)) { exception_state.ThrowDOMException( DOMExceptionCode::kConstraintError, IDBDatabase::kObjectStoreNameTakenErrorMessage); return nullptr; } if (auto_increment && ((key_path.GetType() == mojom::IDBKeyPathType::String && key_path.GetString().IsEmpty()) || key_path.GetType() == mojom::IDBKeyPathType::Array)) { exception_state.ThrowDOMException( DOMExceptionCode::kInvalidAccessError, "The autoIncrement option was set but the " "keyPath option was empty or an array."); return nullptr; } if (!backend_) { exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError, IDBDatabase::kDatabaseClosedErrorMessage); return nullptr; } int64_t object_store_id = metadata_.max_object_store_id + 1; DCHECK_NE(object_store_id, IDBObjectStoreMetadata::kInvalidId); version_change_transaction_->transaction_backend()->CreateObjectStore( object_store_id, name, key_path, auto_increment); scoped_refptr<IDBObjectStoreMetadata> store_metadata = base::AdoptRef(new IDBObjectStoreMetadata( name, object_store_id, key_path, auto_increment, WebIDBDatabase::kMinimumIndexId)); auto* object_store = MakeGarbageCollected<IDBObjectStore>( store_metadata, version_change_transaction_.Get()); version_change_transaction_->ObjectStoreCreated(name, object_store); metadata_.object_stores.Set(object_store_id, std::move(store_metadata)); ++metadata_.max_object_store_id; return object_store; } void IDBDatabase::deleteObjectStore(const String& name, ExceptionState& exception_state) { IDB_TRACE("IDBDatabase::deleteObjectStore"); if (!version_change_transaction_) { exception_state.ThrowDOMException( DOMExceptionCode::kInvalidStateError, IDBDatabase::kNotVersionChangeTransactionErrorMessage); return; } if (!version_change_transaction_->IsActive()) { exception_state.ThrowDOMException( DOMExceptionCode::kTransactionInactiveError, version_change_transaction_->InactiveErrorMessage()); return; } int64_t object_store_id = FindObjectStoreId(name); if (object_store_id == IDBObjectStoreMetadata::kInvalidId) { exception_state.ThrowDOMException( DOMExceptionCode::kNotFoundError, "The specified object store was not found."); return; } if (!backend_) { exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError, IDBDatabase::kDatabaseClosedErrorMessage); return; } version_change_transaction_->transaction_backend()->DeleteObjectStore( object_store_id); version_change_transaction_->ObjectStoreDeleted(object_store_id, name); metadata_.object_stores.erase(object_store_id); } IDBTransaction* IDBDatabase::transaction( ScriptState* script_state, const StringOrStringSequence& store_names, const String& mode, ExceptionState& exception_state) { return transaction(script_state, store_names, mode, nullptr, exception_state); } IDBTransaction* IDBDatabase::transaction( ScriptState* script_state, const StringOrStringSequence& store_names, const String& mode_string, const IDBTransactionOptions* options, ExceptionState& exception_state) { IDB_TRACE("IDBDatabase::transaction"); HashSet<String> scope; if (store_names.IsString()) { scope.insert(store_names.GetAsString()); } else if (store_names.IsStringSequence()) { for (const String& name : store_names.GetAsStringSequence()) scope.insert(name); } else { NOTREACHED(); } if (version_change_transaction_) { exception_state.ThrowDOMException( DOMExceptionCode::kInvalidStateError, "A version change transaction is running."); return nullptr; } if (close_pending_) { exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError, "The database connection is closing."); return nullptr; } if (!backend_) { exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError, IDBDatabase::kDatabaseClosedErrorMessage); return nullptr; } if (scope.IsEmpty()) { exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError, "The storeNames parameter was empty."); return nullptr; } Vector<int64_t> object_store_ids; for (const String& name : scope) { int64_t object_store_id = FindObjectStoreId(name); if (object_store_id == IDBObjectStoreMetadata::kInvalidId) { exception_state.ThrowDOMException( DOMExceptionCode::kNotFoundError, "One of the specified object stores was not found."); return nullptr; } object_store_ids.push_back(object_store_id); } mojom::IDBTransactionMode mode = IDBTransaction::StringToMode(mode_string); if (mode != mojom::IDBTransactionMode::ReadOnly && mode != mojom::IDBTransactionMode::ReadWrite) { exception_state.ThrowTypeError( "The mode provided ('" + mode_string + "') is not one of 'readonly' or 'readwrite'."); return nullptr; } // TODO(cmp): Delete |transaction_id| once all users are removed. int64_t transaction_id = NextTransactionId(); auto transaction_backend = std::make_unique<WebIDBTransactionImpl>( ExecutionContext::From(script_state) ->GetTaskRunner(TaskType::kDatabaseAccess), transaction_id); mojom::IDBTransactionDurability durability = mojom::IDBTransactionDurability::Default; if (options) { DCHECK(RuntimeEnabledFeatures::IDBRelaxedDurabilityEnabled()); if (options->durability() == indexed_db_names::kRelaxed) { durability = mojom::IDBTransactionDurability::Relaxed; } else if (options->durability() == indexed_db_names::kStrict) { durability = mojom::IDBTransactionDurability::Strict; } } backend_->CreateTransaction(transaction_backend->CreateReceiver(), transaction_id, object_store_ids, mode, durability); return IDBTransaction::CreateNonVersionChange( script_state, std::move(transaction_backend), transaction_id, scope, mode, durability, this); } void IDBDatabase::ForceClose() { for (const auto& it : transactions_) it.value->abort(IGNORE_EXCEPTION_FOR_TESTING); this->close(); EnqueueEvent(Event::Create(event_type_names::kClose)); } void IDBDatabase::close() { IDB_TRACE("IDBDatabase::close"); if (close_pending_) return; connection_lifetime_.reset(); close_pending_ = true; feature_handle_for_scheduler_.reset(); if (transactions_.IsEmpty()) CloseConnection(); } void IDBDatabase::CloseConnection() { DCHECK(close_pending_); DCHECK(transactions_.IsEmpty()); if (backend_) { backend_->Close(); backend_.reset(); } if (database_callbacks_) database_callbacks_->DetachWebCallbacks(); if (!GetExecutionContext()) return; // Remove any pending versionchange events scheduled to fire on this // connection. They would have been scheduled by the backend when another // connection attempted an upgrade, but the frontend connection is being // closed before they could fire. event_queue_->CancelAllEvents(); } void IDBDatabase::OnVersionChange(int64_t old_version, int64_t new_version) { IDB_TRACE("IDBDatabase::onVersionChange"); if (!GetExecutionContext()) return; if (close_pending_) { // If we're pending, that means there's a busy transaction. We won't // fire 'versionchange' but since we're not closing immediately the // back-end should still send out 'blocked'. backend_->VersionChangeIgnored(); return; } base::Optional<uint64_t> new_version_nullable; if (new_version != IDBDatabaseMetadata::kNoVersion) { new_version_nullable = new_version; } EnqueueEvent(MakeGarbageCollected<IDBVersionChangeEvent>( event_type_names::kVersionchange, old_version, new_version_nullable)); } void IDBDatabase::EnqueueEvent(Event* event) { DCHECK(GetExecutionContext()); event->SetTarget(this); event_queue_->EnqueueEvent(FROM_HERE, *event); } DispatchEventResult IDBDatabase::DispatchEventInternal(Event& event) { IDB_TRACE("IDBDatabase::dispatchEvent"); event.SetTarget(this); // If this event originated from script, it should have no side effects. if (!event.isTrusted()) return EventTarget::DispatchEventInternal(event); DCHECK(event.type() == event_type_names::kVersionchange || event.type() == event_type_names::kClose); if (!GetExecutionContext()) return DispatchEventResult::kCanceledBeforeDispatch; DispatchEventResult dispatch_result = EventTarget::DispatchEventInternal(event); if (event.type() == event_type_names::kVersionchange && !close_pending_ && backend_) backend_->VersionChangeIgnored(); return dispatch_result; } int64_t IDBDatabase::FindObjectStoreId(const String& name) const { for (const auto& it : metadata_.object_stores) { if (it.value->name == name) { DCHECK_NE(it.key, IDBObjectStoreMetadata::kInvalidId); return it.key; } } return IDBObjectStoreMetadata::kInvalidId; } void IDBDatabase::RenameObjectStore(int64_t object_store_id, const String& new_name) { DCHECK(version_change_transaction_) << "Object store renamed on database without a versionchange transaction"; DCHECK(version_change_transaction_->IsActive()) << "Object store renamed when versionchange transaction is not active"; DCHECK(backend_) << "Object store renamed after database connection closed"; DCHECK(metadata_.object_stores.Contains(object_store_id)); backend_->RenameObjectStore(version_change_transaction_->Id(), object_store_id, new_name); IDBObjectStoreMetadata* object_store_metadata = metadata_.object_stores.at(object_store_id); version_change_transaction_->ObjectStoreRenamed(object_store_metadata->name, new_name); object_store_metadata->name = new_name; } void IDBDatabase::RevertObjectStoreCreation(int64_t object_store_id) { DCHECK(version_change_transaction_) << "Object store metadata reverted on " "database without a versionchange " "transaction"; DCHECK(!version_change_transaction_->IsActive()) << "Object store metadata reverted when versionchange transaction is " "still active"; DCHECK(metadata_.object_stores.Contains(object_store_id)); metadata_.object_stores.erase(object_store_id); } void IDBDatabase::RevertObjectStoreMetadata( scoped_refptr<IDBObjectStoreMetadata> old_metadata) { DCHECK(version_change_transaction_) << "Object store metadata reverted on " "database without a versionchange " "transaction"; DCHECK(!version_change_transaction_->IsActive()) << "Object store metadata reverted when versionchange transaction is " "still active"; DCHECK(old_metadata.get()); metadata_.object_stores.Set(old_metadata->id, std::move(old_metadata)); } bool IDBDatabase::HasPendingActivity() const { // The script wrapper must not be collected before the object is closed or // we can't fire a "versionchange" event to let script manually close the // connection. return !close_pending_ && GetExecutionContext() && HasEventListeners(); } void IDBDatabase::ContextDestroyed() { // Immediately close the connection to the back end. Don't attempt a // normal close() since that may wait on transactions which require a // round trip to the back-end to abort. if (backend_) { backend_->Close(); backend_.reset(); } connection_lifetime_.reset(); if (database_callbacks_) database_callbacks_->DetachWebCallbacks(); } const AtomicString& IDBDatabase::InterfaceName() const { return event_target_names::kIDBDatabase; } ExecutionContext* IDBDatabase::GetExecutionContext() const { return ExecutionContextLifecycleObserver::GetExecutionContext(); } STATIC_ASSERT_ENUM(mojom::blink::IDBException::kNoError, DOMExceptionCode::kNoError); STATIC_ASSERT_ENUM(mojom::blink::IDBException::kUnknownError, DOMExceptionCode::kUnknownError); STATIC_ASSERT_ENUM(mojom::blink::IDBException::kConstraintError, DOMExceptionCode::kConstraintError); STATIC_ASSERT_ENUM(mojom::blink::IDBException::kDataError, DOMExceptionCode::kDataError); STATIC_ASSERT_ENUM(mojom::blink::IDBException::kVersionError, DOMExceptionCode::kVersionError); STATIC_ASSERT_ENUM(mojom::blink::IDBException::kAbortError, DOMExceptionCode::kAbortError); STATIC_ASSERT_ENUM(mojom::blink::IDBException::kQuotaError, DOMExceptionCode::kQuotaExceededError); STATIC_ASSERT_ENUM(mojom::blink::IDBException::kTimeoutError, DOMExceptionCode::kTimeoutError); } // namespace blink
38.294719
94
0.735531
Ron423c
28331d1fad394a87a4e92012de0e9b6b0598c39f
26,831
cpp
C++
shared/source/device_binary_format/patchtokens_decoder.cpp
maleadt/compute-runtime
5d90e2ab1defd413dc9633fe237a44c2a1298185
[ "Intel", "MIT" ]
null
null
null
shared/source/device_binary_format/patchtokens_decoder.cpp
maleadt/compute-runtime
5d90e2ab1defd413dc9633fe237a44c2a1298185
[ "Intel", "MIT" ]
null
null
null
shared/source/device_binary_format/patchtokens_decoder.cpp
maleadt/compute-runtime
5d90e2ab1defd413dc9633fe237a44c2a1298185
[ "Intel", "MIT" ]
null
null
null
/* * Copyright (C) 2019-2022 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "patchtokens_decoder.h" #include "shared/source/debug_settings/debug_settings_manager.h" #include "shared/source/helpers/debug_helpers.h" #include "shared/source/helpers/hash.h" #include "shared/source/helpers/ptr_math.h" #include <algorithm> namespace NEO { namespace PatchTokenBinary { struct PatchTokensStreamReader { const ArrayRef<const uint8_t> data; PatchTokensStreamReader(ArrayRef<const uint8_t> data) : data(data) {} template <typename DecodePosT> bool notEnoughDataLeft(DecodePosT *decodePos, size_t requestedSize) { return getDataSizeLeft(decodePos) < requestedSize; } template <typename T, typename DecodePosT> constexpr bool notEnoughDataLeft(DecodePosT *decodePos) { return notEnoughDataLeft(decodePos, sizeof(T)); } template <typename... ArgsT> bool enoughDataLeft(ArgsT &&...args) { return false == notEnoughDataLeft(std::forward<ArgsT>(args)...); } template <typename T, typename... ArgsT> bool enoughDataLeft(ArgsT &&...args) { return false == notEnoughDataLeft<T>(std::forward<ArgsT>(args)...); } template <typename DecodePosT> size_t getDataSizeLeft(DecodePosT *decodePos) { auto dataConsumed = ptrDiff(decodePos, data.begin()); UNRECOVERABLE_IF(dataConsumed > data.size()); return data.size() - dataConsumed; } }; template <typename T> inline void assignToken(const T *&dst, const SPatchItemHeader *src) { dst = reinterpret_cast<const T *>(src); } inline KernelArgFromPatchtokens &getKernelArg(KernelFromPatchtokens &kernel, size_t argNum, ArgObjectType type = ArgObjectType::None, ArgObjectTypeSpecialized typeSpecialized = ArgObjectTypeSpecialized::None) { if (kernel.tokens.kernelArgs.size() < argNum + 1) { kernel.tokens.kernelArgs.resize(argNum + 1); } auto &arg = kernel.tokens.kernelArgs[argNum]; if (arg.objectType == ArgObjectType::None) { arg.objectType = type; } else if ((arg.objectType != type) && (type != ArgObjectType::None)) { kernel.decodeStatus = DecodeError::InvalidBinary; DBG_LOG(LogPatchTokens, "\n Mismatched metadata for kernel arg :", argNum); DEBUG_BREAK_IF(true); } if (arg.objectTypeSpecialized == ArgObjectTypeSpecialized::None) { arg.objectTypeSpecialized = typeSpecialized; } else if (typeSpecialized != ArgObjectTypeSpecialized::None) { UNRECOVERABLE_IF(arg.objectTypeSpecialized != typeSpecialized); } return arg; } inline void assignArgInfo(KernelFromPatchtokens &kernel, const SPatchItemHeader *src) { auto argInfoToken = reinterpret_cast<const SPatchKernelArgumentInfo *>(src); getKernelArg(kernel, argInfoToken->ArgumentNumber, ArgObjectType::None).argInfo = argInfoToken; } template <typename T> inline uint32_t getArgNum(const SPatchItemHeader *argToken) { return reinterpret_cast<const T *>(argToken)->ArgumentNumber; } inline void assignArg(KernelFromPatchtokens &kernel, const SPatchItemHeader *src) { uint32_t argNum = 0; ArgObjectType type = ArgObjectType::Buffer; switch (src->Token) { default: UNRECOVERABLE_IF(src->Token != PATCH_TOKEN_SAMPLER_KERNEL_ARGUMENT); argNum = getArgNum<SPatchSamplerKernelArgument>(src); type = ArgObjectType::Sampler; break; case PATCH_TOKEN_IMAGE_MEMORY_OBJECT_KERNEL_ARGUMENT: argNum = getArgNum<SPatchImageMemoryObjectKernelArgument>(src); type = ArgObjectType::Image; break; case PATCH_TOKEN_GLOBAL_MEMORY_OBJECT_KERNEL_ARGUMENT: argNum = getArgNum<SPatchGlobalMemoryObjectKernelArgument>(src); break; case PATCH_TOKEN_STATELESS_GLOBAL_MEMORY_OBJECT_KERNEL_ARGUMENT: argNum = getArgNum<SPatchStatelessGlobalMemoryObjectKernelArgument>(src); break; case PATCH_TOKEN_STATELESS_CONSTANT_MEMORY_OBJECT_KERNEL_ARGUMENT: argNum = getArgNum<SPatchStatelessConstantMemoryObjectKernelArgument>(src); break; case PATCH_TOKEN_STATELESS_DEVICE_QUEUE_KERNEL_ARGUMENT: argNum = getArgNum<SPatchStatelessDeviceQueueKernelArgument>(src); break; } getKernelArg(kernel, argNum, type).objectArg = src; } inline void assignToken(StackVecStrings &stringVec, const SPatchItemHeader *src) { auto stringToken = reinterpret_cast<const SPatchString *>(src); if (stringVec.size() < stringToken->Index + 1) { stringVec.resize(stringToken->Index + 1); } stringVec[stringToken->Index] = stringToken; } template <size_t S> inline void assignTokenInArray(const SPatchDataParameterBuffer *(&tokensArray)[S], const SPatchDataParameterBuffer *src, StackVecUnhandledTokens &unhandledTokens) { auto sourceIndex = src->SourceOffset >> 2; if (sourceIndex >= S) { DBG_LOG(LogPatchTokens, "\n .Type", "Unhandled sourceIndex ", sourceIndex); DEBUG_BREAK_IF(true); unhandledTokens.push_back(src); return; } assignToken(tokensArray[sourceIndex], src); } template <typename PatchT, size_t NumInlineEl> inline void addTok(StackVec<const PatchT *, NumInlineEl> &tokensVec, const SPatchItemHeader *src) { tokensVec.push_back(reinterpret_cast<const PatchT *>(src)); } inline void decodeKernelDataParameterToken(const SPatchDataParameterBuffer *token, KernelFromPatchtokens &out) { auto &crossthread = out.tokens.crossThreadPayloadArgs; auto sourceIndex = token->SourceOffset >> 2; auto argNum = token->ArgumentNumber; switch (token->Type) { default: DBG_LOG(LogPatchTokens, "\n .Type", "Unhandled SPatchDataParameterBuffer ", token->Type); DEBUG_BREAK_IF(true); out.unhandledTokens.push_back(token); break; case DATA_PARAMETER_KERNEL_ARGUMENT: getKernelArg(out, argNum, ArgObjectType::None).byValMap.push_back(token); break; case DATA_PARAMETER_LOCAL_WORK_SIZE: { if (sourceIndex >= 3) { DBG_LOG(LogPatchTokens, "\n .Type", "Unhandled sourceIndex ", sourceIndex); DEBUG_BREAK_IF(true); out.unhandledTokens.push_back(token); return; } auto localWorkSizeArray = (crossthread.localWorkSize[sourceIndex] == nullptr) ? crossthread.localWorkSize : crossthread.localWorkSize2; localWorkSizeArray[sourceIndex] = token; break; } case DATA_PARAMETER_GLOBAL_WORK_OFFSET: assignTokenInArray(crossthread.globalWorkOffset, token, out.unhandledTokens); break; case DATA_PARAMETER_ENQUEUED_LOCAL_WORK_SIZE: assignTokenInArray(crossthread.enqueuedLocalWorkSize, token, out.unhandledTokens); break; case DATA_PARAMETER_GLOBAL_WORK_SIZE: assignTokenInArray(crossthread.globalWorkSize, token, out.unhandledTokens); break; case DATA_PARAMETER_NUM_WORK_GROUPS: assignTokenInArray(crossthread.numWorkGroups, token, out.unhandledTokens); break; case DATA_PARAMETER_MAX_WORKGROUP_SIZE: crossthread.maxWorkGroupSize = token; break; case DATA_PARAMETER_WORK_DIMENSIONS: crossthread.workDimensions = token; break; case DATA_PARAMETER_SIMD_SIZE: crossthread.simdSize = token; break; case DATA_PARAMETER_PRIVATE_MEMORY_STATELESS_SIZE: crossthread.privateMemoryStatelessSize = token; break; case DATA_PARAMETER_LOCAL_MEMORY_STATELESS_WINDOW_SIZE: crossthread.localMemoryStatelessWindowSize = token; break; case DATA_PARAMETER_LOCAL_MEMORY_STATELESS_WINDOW_START_ADDRESS: crossthread.localMemoryStatelessWindowStartAddress = token; break; case DATA_PARAMETER_OBJECT_ID: getKernelArg(out, argNum, ArgObjectType::None).objectId = token; break; case DATA_PARAMETER_SUM_OF_LOCAL_MEMORY_OBJECT_ARGUMENT_SIZES: { auto &kernelArg = getKernelArg(out, argNum, ArgObjectType::Slm); kernelArg.byValMap.push_back(token); kernelArg.metadata.slm.token = token; } break; case DATA_PARAMETER_BUFFER_OFFSET: getKernelArg(out, argNum, ArgObjectType::Buffer).metadata.buffer.bufferOffset = token; break; case DATA_PARAMETER_BUFFER_STATEFUL: getKernelArg(out, argNum, ArgObjectType::Buffer).metadata.buffer.pureStateful = token; break; case DATA_PARAMETER_IMAGE_WIDTH: getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.width = token; break; case DATA_PARAMETER_IMAGE_HEIGHT: getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.height = token; break; case DATA_PARAMETER_IMAGE_DEPTH: getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.depth = token; break; case DATA_PARAMETER_IMAGE_CHANNEL_DATA_TYPE: getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.channelDataType = token; break; case DATA_PARAMETER_IMAGE_CHANNEL_ORDER: getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.channelOrder = token; break; case DATA_PARAMETER_IMAGE_ARRAY_SIZE: getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.arraySize = token; break; case DATA_PARAMETER_IMAGE_NUM_SAMPLES: getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.numSamples = token; break; case DATA_PARAMETER_IMAGE_NUM_MIP_LEVELS: getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.numMipLevels = token; break; case DATA_PARAMETER_FLAT_IMAGE_BASEOFFSET: getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.flatBaseOffset = token; break; case DATA_PARAMETER_FLAT_IMAGE_WIDTH: getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.flatWidth = token; break; case DATA_PARAMETER_FLAT_IMAGE_HEIGHT: getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.flatHeight = token; break; case DATA_PARAMETER_FLAT_IMAGE_PITCH: getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.flatPitch = token; break; case DATA_PARAMETER_SAMPLER_COORDINATE_SNAP_WA_REQUIRED: getKernelArg(out, argNum, ArgObjectType::Sampler).metadata.sampler.coordinateSnapWaRequired = token; break; case DATA_PARAMETER_SAMPLER_ADDRESS_MODE: getKernelArg(out, argNum, ArgObjectType::Sampler).metadata.sampler.addressMode = token; break; case DATA_PARAMETER_SAMPLER_NORMALIZED_COORDS: getKernelArg(out, argNum, ArgObjectType::Sampler).metadata.sampler.normalizedCoords = token; break; case DATA_PARAMETER_VME_MB_BLOCK_TYPE: getKernelArg(out, argNum, ArgObjectType::None, ArgObjectTypeSpecialized::Vme).metadataSpecialized.vme.mbBlockType = token; break; case DATA_PARAMETER_VME_SUBPIXEL_MODE: getKernelArg(out, argNum, ArgObjectType::None, ArgObjectTypeSpecialized::Vme).metadataSpecialized.vme.subpixelMode = token; break; case DATA_PARAMETER_VME_SAD_ADJUST_MODE: getKernelArg(out, argNum, ArgObjectType::None, ArgObjectTypeSpecialized::Vme).metadataSpecialized.vme.sadAdjustMode = token; break; case DATA_PARAMETER_VME_SEARCH_PATH_TYPE: getKernelArg(out, argNum, ArgObjectType::None, ArgObjectTypeSpecialized::Vme).metadataSpecialized.vme.searchPathType = token; break; case DATA_PARAMETER_PARENT_EVENT: crossthread.parentEvent = token; break; case DATA_PARAMETER_PREFERRED_WORKGROUP_MULTIPLE: crossthread.preferredWorkgroupMultiple = token; break; case DATA_PARAMETER_IMPL_ARG_BUFFER: out.tokens.crossThreadPayloadArgs.implicitArgsBufferOffset = token; break; case DATA_PARAMETER_NUM_HARDWARE_THREADS: case DATA_PARAMETER_PRINTF_SURFACE_SIZE: case DATA_PARAMETER_IMAGE_SRGB_CHANNEL_ORDER: case DATA_PARAMETER_STAGE_IN_GRID_ORIGIN: case DATA_PARAMETER_STAGE_IN_GRID_SIZE: case DATA_PARAMETER_LOCAL_ID: case DATA_PARAMETER_EXECUTION_MASK: case DATA_PARAMETER_VME_IMAGE_TYPE: case DATA_PARAMETER_VME_MB_SKIP_BLOCK_TYPE: case DATA_PARAMETER_CHILD_BLOCK_SIMD_SIZE: // ignored intentionally break; } } inline bool decodeToken(const SPatchItemHeader *token, KernelFromPatchtokens &out) { switch (token->Token) { default: { PRINT_DEBUG_STRING(DebugManager.flags.PrintDebugMessages.get(), stderr, "Unknown kernel-scope Patch Token: %d\n", token->Token); DEBUG_BREAK_IF(true); out.unhandledTokens.push_back(token); break; } case PATCH_TOKEN_INTERFACE_DESCRIPTOR_DATA: PRINT_DEBUG_STRING(DebugManager.flags.PrintDebugMessages.get(), stderr, "Ignored kernel-scope Patch Token: %d\n", token->Token); break; case PATCH_TOKEN_SAMPLER_STATE_ARRAY: assignToken(out.tokens.samplerStateArray, token); break; case PATCH_TOKEN_BINDING_TABLE_STATE: assignToken(out.tokens.bindingTableState, token); break; case PATCH_TOKEN_ALLOCATE_LOCAL_SURFACE: assignToken(out.tokens.allocateLocalSurface, token); break; case PATCH_TOKEN_MEDIA_VFE_STATE: assignToken(out.tokens.mediaVfeState[0], token); break; case PATCH_TOKEN_MEDIA_VFE_STATE_SLOT1: assignToken(out.tokens.mediaVfeState[1], token); break; case PATCH_TOKEN_MEDIA_INTERFACE_DESCRIPTOR_LOAD: assignToken(out.tokens.mediaInterfaceDescriptorLoad, token); break; case PATCH_TOKEN_THREAD_PAYLOAD: assignToken(out.tokens.threadPayload, token); break; case PATCH_TOKEN_EXECUTION_ENVIRONMENT: assignToken(out.tokens.executionEnvironment, token); break; case PATCH_TOKEN_KERNEL_ATTRIBUTES_INFO: assignToken(out.tokens.kernelAttributesInfo, token); break; case PATCH_TOKEN_ALLOCATE_STATELESS_PRIVATE_MEMORY: assignToken(out.tokens.allocateStatelessPrivateSurface, token); break; case PATCH_TOKEN_ALLOCATE_STATELESS_CONSTANT_MEMORY_SURFACE_WITH_INITIALIZATION: assignToken(out.tokens.allocateStatelessConstantMemorySurfaceWithInitialization, token); break; case PATCH_TOKEN_ALLOCATE_STATELESS_GLOBAL_MEMORY_SURFACE_WITH_INITIALIZATION: assignToken(out.tokens.allocateStatelessGlobalMemorySurfaceWithInitialization, token); break; case PATCH_TOKEN_ALLOCATE_STATELESS_PRINTF_SURFACE: assignToken(out.tokens.allocateStatelessPrintfSurface, token); break; case PATCH_TOKEN_ALLOCATE_STATELESS_EVENT_POOL_SURFACE: assignToken(out.tokens.allocateStatelessEventPoolSurface, token); break; case PATCH_TOKEN_ALLOCATE_STATELESS_DEFAULT_DEVICE_QUEUE_SURFACE: assignToken(out.tokens.allocateStatelessDefaultDeviceQueueSurface, token); break; case PATCH_TOKEN_STRING: assignToken(out.tokens.strings, token); break; case PATCH_TOKEN_INLINE_VME_SAMPLER_INFO: assignToken(out.tokens.inlineVmeSamplerInfo, token); break; case PATCH_TOKEN_GTPIN_FREE_GRF_INFO: assignToken(out.tokens.gtpinFreeGrfInfo, token); break; case PATCH_TOKEN_GTPIN_INFO: assignToken(out.tokens.gtpinInfo, token); break; case PATCH_TOKEN_STATE_SIP: assignToken(out.tokens.stateSip, token); break; case PATCH_TOKEN_ALLOCATE_SIP_SURFACE: assignToken(out.tokens.allocateSystemThreadSurface, token); break; case PATCH_TOKEN_PROGRAM_SYMBOL_TABLE: assignToken(out.tokens.programSymbolTable, token); break; case PATCH_TOKEN_PROGRAM_RELOCATION_TABLE: assignToken(out.tokens.programRelocationTable, token); break; case PATCH_TOKEN_KERNEL_ARGUMENT_INFO: assignArgInfo(out, token); break; case PATCH_TOKEN_SAMPLER_KERNEL_ARGUMENT: case PATCH_TOKEN_IMAGE_MEMORY_OBJECT_KERNEL_ARGUMENT: case PATCH_TOKEN_GLOBAL_MEMORY_OBJECT_KERNEL_ARGUMENT: case PATCH_TOKEN_STATELESS_GLOBAL_MEMORY_OBJECT_KERNEL_ARGUMENT: case PATCH_TOKEN_STATELESS_CONSTANT_MEMORY_OBJECT_KERNEL_ARGUMENT: case PATCH_TOKEN_STATELESS_DEVICE_QUEUE_KERNEL_ARGUMENT: assignArg(out, token); break; case PATCH_TOKEN_DATA_PARAMETER_STREAM: assignToken(out.tokens.dataParameterStream, token); break; case PATCH_TOKEN_DATA_PARAMETER_BUFFER: { auto tokDataP = reinterpret_cast<const SPatchDataParameterBuffer *>(token); decodeKernelDataParameterToken(tokDataP, out); } break; case PATCH_TOKEN_ALLOCATE_SYNC_BUFFER: { assignToken(out.tokens.allocateSyncBuffer, token); } break; } return out.decodeStatus != DecodeError::InvalidBinary; } inline bool decodeToken(const SPatchItemHeader *token, ProgramFromPatchtokens &out) { auto &progTok = out.programScopeTokens; switch (token->Token) { default: { PRINT_DEBUG_STRING(DebugManager.flags.PrintDebugMessages.get(), stderr, "Unknown program-scope Patch Token: %d\n", token->Token); DEBUG_BREAK_IF(true); out.unhandledTokens.push_back(token); break; } case PATCH_TOKEN_ALLOCATE_CONSTANT_MEMORY_SURFACE_PROGRAM_BINARY_INFO: addTok(progTok.allocateConstantMemorySurface, token); break; case PATCH_TOKEN_ALLOCATE_GLOBAL_MEMORY_SURFACE_PROGRAM_BINARY_INFO: addTok(progTok.allocateGlobalMemorySurface, token); break; case PATCH_TOKEN_GLOBAL_POINTER_PROGRAM_BINARY_INFO: addTok(progTok.globalPointer, token); break; case PATCH_TOKEN_CONSTANT_POINTER_PROGRAM_BINARY_INFO: addTok(progTok.constantPointer, token); break; case PATCH_TOKEN_PROGRAM_SYMBOL_TABLE: assignToken(progTok.symbolTable, token); break; case _PATCH_TOKEN_GLOBAL_HOST_ACCESS_TABLE: assignToken(progTok.hostAccessTable, token); break; } return true; } template <typename DecodeContext> inline size_t getPatchTokenTotalSize(PatchTokensStreamReader stream, const SPatchItemHeader *token); template <> inline size_t getPatchTokenTotalSize<KernelFromPatchtokens>(PatchTokensStreamReader stream, const SPatchItemHeader *token) { return token->Size; } template <> inline size_t getPatchTokenTotalSize<ProgramFromPatchtokens>(PatchTokensStreamReader stream, const SPatchItemHeader *token) { size_t tokSize = token->Size; switch (token->Token) { default: return tokSize; case PATCH_TOKEN_ALLOCATE_CONSTANT_MEMORY_SURFACE_PROGRAM_BINARY_INFO: return stream.enoughDataLeft<SPatchAllocateConstantMemorySurfaceProgramBinaryInfo>(token) ? tokSize + reinterpret_cast<const SPatchAllocateConstantMemorySurfaceProgramBinaryInfo *>(token)->InlineDataSize : std::numeric_limits<size_t>::max(); case PATCH_TOKEN_ALLOCATE_GLOBAL_MEMORY_SURFACE_PROGRAM_BINARY_INFO: return stream.enoughDataLeft<SPatchAllocateGlobalMemorySurfaceProgramBinaryInfo>(token) ? tokSize + reinterpret_cast<const SPatchAllocateGlobalMemorySurfaceProgramBinaryInfo *>(token)->InlineDataSize : std::numeric_limits<size_t>::max(); } } template <typename OutT> inline bool decodePatchList(PatchTokensStreamReader patchListStream, OutT &out) { auto decodePos = patchListStream.data.begin(); auto decodeEnd = patchListStream.data.end(); bool decodeSuccess = true; while ((ptrDiff(decodeEnd, decodePos) > sizeof(SPatchItemHeader)) && decodeSuccess) { auto token = reinterpret_cast<const SPatchItemHeader *>(decodePos); size_t tokenTotalSize = getPatchTokenTotalSize<OutT>(patchListStream, token); decodeSuccess = patchListStream.enoughDataLeft(decodePos, tokenTotalSize); decodeSuccess = decodeSuccess && (tokenTotalSize > 0U); decodeSuccess = decodeSuccess && decodeToken(token, out); decodePos = ptrOffset(decodePos, tokenTotalSize); } return decodeSuccess; } bool decodeKernelFromPatchtokensBlob(ArrayRef<const uint8_t> kernelBlob, KernelFromPatchtokens &out) { PatchTokensStreamReader stream{kernelBlob}; auto decodePos = stream.data.begin(); out.decodeStatus = DecodeError::Undefined; if (stream.notEnoughDataLeft<SKernelBinaryHeaderCommon>(decodePos)) { out.decodeStatus = DecodeError::InvalidBinary; return false; } out.header = reinterpret_cast<const SKernelBinaryHeaderCommon *>(decodePos); auto kernelInfoBlobSize = sizeof(SKernelBinaryHeaderCommon) + out.header->KernelNameSize + out.header->KernelHeapSize + out.header->GeneralStateHeapSize + out.header->DynamicStateHeapSize + out.header->SurfaceStateHeapSize + out.header->PatchListSize; if (stream.notEnoughDataLeft(decodePos, kernelInfoBlobSize)) { out.decodeStatus = DecodeError::InvalidBinary; return false; } out.blobs.kernelInfo = ArrayRef<const uint8_t>(stream.data.begin(), kernelInfoBlobSize); decodePos = ptrOffset(decodePos, sizeof(SKernelBinaryHeaderCommon)); auto kernelName = reinterpret_cast<const char *>(decodePos); out.name = ArrayRef<const char>(kernelName, out.header->KernelNameSize); decodePos = ptrOffset(decodePos, out.name.size()); out.isa = ArrayRef<const uint8_t>(decodePos, out.header->KernelHeapSize); decodePos = ptrOffset(decodePos, out.isa.size()); out.heaps.generalState = ArrayRef<const uint8_t>(decodePos, out.header->GeneralStateHeapSize); decodePos = ptrOffset(decodePos, out.heaps.generalState.size()); out.heaps.dynamicState = ArrayRef<const uint8_t>(decodePos, out.header->DynamicStateHeapSize); decodePos = ptrOffset(decodePos, out.heaps.dynamicState.size()); out.heaps.surfaceState = ArrayRef<const uint8_t>(decodePos, out.header->SurfaceStateHeapSize); decodePos = ptrOffset(decodePos, out.heaps.surfaceState.size()); out.blobs.patchList = ArrayRef<const uint8_t>(decodePos, out.header->PatchListSize); if (false == decodePatchList(out.blobs.patchList, out)) { out.decodeStatus = DecodeError::InvalidBinary; return false; } out.decodeStatus = DecodeError::Success; return true; } inline bool decodeProgramHeader(ProgramFromPatchtokens &decodedProgram) { auto decodePos = decodedProgram.blobs.programInfo.begin(); PatchTokensStreamReader stream{decodedProgram.blobs.programInfo}; if (stream.notEnoughDataLeft<SProgramBinaryHeader>(decodePos)) { return false; } decodedProgram.header = reinterpret_cast<const SProgramBinaryHeader *>(decodePos); if (decodedProgram.header->Magic != MAGIC_CL) { return false; } decodePos = ptrOffset(decodePos, sizeof(SProgramBinaryHeader)); if (stream.notEnoughDataLeft(decodePos, decodedProgram.header->PatchListSize)) { return false; } decodedProgram.blobs.patchList = ArrayRef<const uint8_t>(decodePos, decodedProgram.header->PatchListSize); decodePos = ptrOffset(decodePos, decodedProgram.blobs.patchList.size()); decodedProgram.blobs.kernelsInfo = ArrayRef<const uint8_t>(decodePos, stream.getDataSizeLeft(decodePos)); return true; } inline bool decodeKernels(ProgramFromPatchtokens &decodedProgram) { auto numKernels = decodedProgram.header->NumberOfKernels; decodedProgram.kernels.reserve(decodedProgram.header->NumberOfKernels); const uint8_t *decodePos = decodedProgram.blobs.kernelsInfo.begin(); bool decodeSuccess = true; PatchTokensStreamReader stream{decodedProgram.blobs.kernelsInfo}; for (uint32_t i = 0; (i < numKernels) && decodeSuccess; i++) { decodedProgram.kernels.resize(decodedProgram.kernels.size() + 1); auto &currKernelInfo = *decodedProgram.kernels.rbegin(); auto kernelDataLeft = ArrayRef<const uint8_t>(decodePos, stream.getDataSizeLeft(decodePos)); decodeSuccess = decodeKernelFromPatchtokensBlob(kernelDataLeft, currKernelInfo); decodePos = ptrOffset(decodePos, currKernelInfo.blobs.kernelInfo.size()); } return decodeSuccess; } bool decodeProgramFromPatchtokensBlob(ArrayRef<const uint8_t> programBlob, ProgramFromPatchtokens &out) { out.blobs.programInfo = programBlob; bool decodeSuccess = decodeProgramHeader(out); decodeSuccess = decodeSuccess && decodeKernels(out); decodeSuccess = decodeSuccess && decodePatchList(out.blobs.patchList, out); out.decodeStatus = decodeSuccess ? DecodeError::Success : DecodeError::InvalidBinary; return decodeSuccess; } uint32_t calcKernelChecksum(const ArrayRef<const uint8_t> kernelBlob) { UNRECOVERABLE_IF(kernelBlob.size() <= sizeof(SKernelBinaryHeaderCommon)); auto dataToHash = ArrayRef<const uint8_t>(ptrOffset(kernelBlob.begin(), sizeof(SKernelBinaryHeaderCommon)), kernelBlob.end()); uint64_t hashValue = Hash::hash(reinterpret_cast<const char *>(dataToHash.begin()), dataToHash.size()); uint32_t checksum = hashValue & 0xFFFFFFFF; return checksum; } bool hasInvalidChecksum(const KernelFromPatchtokens &decodedKernel) { uint32_t decodedChecksum = decodedKernel.header->CheckSum; uint32_t calculatedChecksum = NEO::PatchTokenBinary::calcKernelChecksum(decodedKernel.blobs.kernelInfo); return decodedChecksum != calculatedChecksum; } const KernelArgAttributesFromPatchtokens getInlineData(const SPatchKernelArgumentInfo *ptr) { KernelArgAttributesFromPatchtokens ret = {}; UNRECOVERABLE_IF(ptr == nullptr); auto decodePos = reinterpret_cast<const char *>(ptr + 1); auto bounds = reinterpret_cast<const char *>(ptr) + ptr->Size; ret.addressQualifier = ArrayRef<const char>(decodePos, std::min(decodePos + ptr->AddressQualifierSize, bounds)); decodePos += ret.addressQualifier.size(); ret.accessQualifier = ArrayRef<const char>(decodePos, std::min(decodePos + ptr->AccessQualifierSize, bounds)); decodePos += ret.accessQualifier.size(); ret.argName = ArrayRef<const char>(decodePos, std::min(decodePos + ptr->ArgumentNameSize, bounds)); decodePos += ret.argName.size(); ret.typeName = ArrayRef<const char>(decodePos, std::min(decodePos + ptr->TypeNameSize, bounds)); decodePos += ret.typeName.size(); ret.typeQualifiers = ArrayRef<const char>(decodePos, std::min(decodePos + ptr->TypeQualifierSize, bounds)); return ret; } const iOpenCL::SProgramBinaryHeader *decodeProgramHeader(const ArrayRef<const uint8_t> programBlob) { ProgramFromPatchtokens program; program.blobs.programInfo = programBlob; if (false == decodeProgramHeader(program)) { return nullptr; } return program.header; } } // namespace PatchTokenBinary } // namespace NEO
42.120879
255
0.735232
maleadt
283383cbfb967feccae62aef0f0c14b3dd3a6c3b
2,502
cc
C++
libcef/common/service_manifests/builtin_service_manifests.cc
aslistener/cef
d2bfa62d2df23cec85b6fea236aafb8ceb6f2423
[ "BSD-3-Clause" ]
null
null
null
libcef/common/service_manifests/builtin_service_manifests.cc
aslistener/cef
d2bfa62d2df23cec85b6fea236aafb8ceb6f2423
[ "BSD-3-Clause" ]
null
null
null
libcef/common/service_manifests/builtin_service_manifests.cc
aslistener/cef
d2bfa62d2df23cec85b6fea236aafb8ceb6f2423
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "libcef/common/service_manifests/builtin_service_manifests.h" #include "base/no_destructor.h" #include "build/build_config.h" #include "chrome/common/buildflags.h" #include "chrome/common/constants.mojom.h" #include "chrome/services/printing/public/cpp/manifest.h" #include "components/services/pdf_compositor/public/cpp/manifest.h" // nogncheck #include "components/spellcheck/common/spellcheck.mojom.h" #include "components/startup_metric_utils/common/startup_metric.mojom.h" #include "extensions/buildflags/buildflags.h" #include "printing/buildflags/buildflags.h" #include "services/proxy_resolver/public/mojom/proxy_resolver.mojom.h" #include "services/service_manager/public/cpp/manifest_builder.h" #if defined(OS_MACOSX) #include "components/spellcheck/common/spellcheck_panel.mojom.h" #endif namespace { const service_manager::Manifest& GetCefManifest() { static base::NoDestructor<service_manager::Manifest> manifest { service_manager::ManifestBuilder() .WithServiceName(chrome::mojom::kServiceName) .WithDisplayName("CEF") .WithOptions( service_manager::ManifestOptionsBuilder() .WithExecutionMode( service_manager::Manifest::ExecutionMode::kInProcessBuiltin) .WithInstanceSharingPolicy( service_manager::Manifest::InstanceSharingPolicy:: kSharedAcrossGroups) .CanConnectToInstancesWithAnyId(true) .CanRegisterOtherServiceInstances(true) .Build()) .ExposeCapability("renderer", service_manager::Manifest::InterfaceList< #if defined(OS_MACOSX) spellcheck::mojom::SpellCheckPanelHost, #endif spellcheck::mojom::SpellCheckHost, startup_metric_utils::mojom::StartupMetricHost>()) .RequireCapability(chrome::mojom::kRendererServiceName, "browser") .Build() }; return *manifest; } } // namespace const std::vector<service_manager::Manifest>& GetBuiltinServiceManifests() { static base::NoDestructor<std::vector<service_manager::Manifest>> manifests{{ GetCefManifest(), printing::GetPdfCompositorManifest(), GetChromePrintingManifest(), }}; return *manifests; }
39.09375
81
0.698641
aslistener
283494667f8cc67ec616bfd5cbb8447c4cc7275e
4,735
cpp
C++
src/ctrl/form/User.cpp
minyor/PocoBlog
9556c5e70618dd64abd36913cc34c5c373b5673f
[ "BSD-2-Clause" ]
5
2016-01-19T02:12:40.000Z
2018-01-12T09:20:53.000Z
src/ctrl/form/User.cpp
minyor/PocoBlog
9556c5e70618dd64abd36913cc34c5c373b5673f
[ "BSD-2-Clause" ]
null
null
null
src/ctrl/form/User.cpp
minyor/PocoBlog
9556c5e70618dd64abd36913cc34c5c373b5673f
[ "BSD-2-Clause" ]
null
null
null
#include "Poco/CountingStream.h" #include "Poco/NullStream.h" #include "Poco/StreamCopier.h" #include <ctrl/form/User.h> using namespace ctrl::form; static const std::string birthdayFormat = "%Y-%n-%e"; std::string birthdayFromDate(const Poco::DateTime &date) { return Poco::DateTimeFormatter::format(date, birthdayFormat); } Poco::DateTime birthdayToDate(const std::string &bday) { Poco::DateTime date; int timeZoneDifferential; if(Poco::DateTimeParser::tryParse(birthdayFormat, bday, date, timeZoneDifferential)) return date; return Poco::DateTime(Poco::Timestamp(0)); } User::User() { userTable.hideEmptyCollumns(true); userGroups.prompt = "Set Group"; userGroups.add("Admin", "0"); userGroups.add("User", "2"); userGroups.add("Subscriber", "3"); addEvent(updateUser); addEvent(removeUser); addEvent(selectUser); addEvent(updateGroup); addEvent(paginate); } User::~User() { } std::string User::format(const std::string &in) { return core::util::Html::format(in); } User::Mode User::mode() { if(users) return MODE_USERS; else return MODE_SETTINGS; } std::string User::param() { std::string ret; switch(mode()) { case MODE_USERS: ret += "m=users&"; break; case MODE_SETTINGS: ret += ""; break; } ret += "p=" + std::to_string(paginator.page()) + "&"; ret += "s=" + std::to_string(userTable.sort()) + "&"; return ret; } void User::onEnter() { val["status"] = ""; /// Fill settings val["firstName"] = user().firstName(); val["lastName"] = user().lastName(); val["phoneNumber"] = user().phoneNumber(); val["country"] = user().country(); val["state"] = user().state(); val["birthday"] = birthdayFromDate(user().birthday()); } void User::onLoad() { users = NULL; /// Parameters auto &mode = val["m"]; std::int64_t sort = 0; std::istringstream(val["s"]) >> sort; std::int32_t page = INTMAX(32); std::istringstream(val["p"]) >> page; userTable.sort(sort); if(page != INTMAX(32)) paginator.page(page); /// Mode switch(0) { default: /// Prepare User table bool modeUsers = mode == "users" && user().group() == user().ADMIN; if(modeUsers) { paginator.doPaging(ctrl().service().getUsersCount()); users = ctrl().service().getUsers(-1, userTable.sort(), paginator.limit(), paginator.offset()); userTable.set(users); break; } userTable.clear(); } /// Reset parameters val["m"] = val["s"] = val["p"] = ""; } void User::updateUser(std::istream *stream) { if(!user()) return; /// Parameters auto firstName = val["firstName"]; auto lastName = val["lastName"]; auto phoneNumber = val["phoneNumber"]; auto country = val["country"]; auto state = val["state"]; auto birthday = birthdayToDate(val["birthday"]); val["status"] = ""; /// Validation if(!birthday.timestamp().raw()) val["status"] = "*Incorrect birthday format!"; if(lastName.empty()) val["status"] = "*Please enter Last Name!"; if(firstName.empty()) val["status"] = "*Please enter First Name!"; if(!val["status"].empty()) return; model::User user = this->user(); user.firstName(firstName); user.lastName(lastName); user.phoneNumber(phoneNumber); user.country(country); user.state(state); user.birthday(birthday); ctrl().service().updateUser(user); ctrl().update(); val["status"] = "Updated successfully!"; } void User::removeUser(std::istream *stream) { if(user().group() != user().ADMIN) return; for(std::uint32_t i=0; i<users->size(); ++i) { if(!userTable.rows()[i]->checked) continue; ctrl().service().deleteUser(users()[i]->id()); } userTable.clear(); } void User::selectUser(std::istream *stream) { if(user().group() != user().ADMIN) return; /// Parameters core::DataID rowAll = 0; std::istringstream(val["a"]) >> rowAll; core::DataID rowInd = core::DataID(-1); std::istringstream(val["r"]) >> rowInd; val["a"] = val["r"] = ""; if(rowAll) { userTable.toggleAll(); return; } userTable.toggle(rowInd); } void User::updateGroup(std::istream *stream) { if(user().group() != user().ADMIN) return; /// Parameters std::int32_t group = -1; std::istringstream(val["g"]) >> group; val["g"] = ""; if(group < 0) return; for(std::uint32_t i=0; i<users->size(); ++i) { if(!userTable.rows()[i]->checked) continue; users()[i]->group((model::User::Group)group); ctrl().service().updateUser(*users()[i]); } userTable.clear(); } void User::paginate(std::istream *stream) { /// Parameters std::int32_t sort = INTMAX(32); std::istringstream(val["s"]) >> sort; std::int32_t page = INTMAX(32); std::istringstream(val["p"]) >> page; val["s"] = val["p"] = ""; if(sort != INTMAX(32)) userTable.sort(sort); else if(page != INTMAX(32)) paginator.page(page); else paginator.extend(); ctrl().redirect(path() + "?" + param()); }
22.023256
98
0.646251
minyor
28359254006702bcfe15cb754c96fba7efaae5fb
397
hpp
C++
include/mk2/math/sin.hpp
SachiSakurane/libmk2
e8acf044ee5de160ad8a6f0a3c955beddea8d8c2
[ "BSL-1.0" ]
null
null
null
include/mk2/math/sin.hpp
SachiSakurane/libmk2
e8acf044ee5de160ad8a6f0a3c955beddea8d8c2
[ "BSL-1.0" ]
null
null
null
include/mk2/math/sin.hpp
SachiSakurane/libmk2
e8acf044ee5de160ad8a6f0a3c955beddea8d8c2
[ "BSL-1.0" ]
null
null
null
// // sin.hpp // // // Created by Himatya on 2015/12/18. // Copyright (c) 2015 Himatya. All rights reserved. // #pragma once #include <type_traits> #include <mk2/math/cos.hpp> namespace mk2{ namespace math{ template<class T, typename = typename std::enable_if<std::is_floating_point<T>::value>::type> inline constexpr T sin(T x){ return cos(x - math::half_pi<T>); } } }
17.26087
97
0.649874
SachiSakurane
2836bc8a211175328048c71d425b69e73c5cceb8
1,015
cpp
C++
src/chatterbox_1.1.0/lib/Manual/Pots.cpp
danja/chatterbox
59ebf9d65bac38854a6162bc0f6f4b9f6d43d330
[ "MIT" ]
2
2021-02-19T22:30:59.000Z
2021-03-19T19:07:36.000Z
src/chatterbox_1.1.0/lib/Manual/Pots.cpp
danja/chatterbox
59ebf9d65bac38854a6162bc0f6f4b9f6d43d330
[ "MIT" ]
null
null
null
src/chatterbox_1.1.0/lib/Manual/Pots.cpp
danja/chatterbox
59ebf9d65bac38854a6162bc0f6f4b9f6d43d330
[ "MIT" ]
null
null
null
#include <Arduino.h> #include <Wavetable.h> #include <Pots.h> #include <Pot.h> Pots::Pots() { } void Pots::init() { // float tablesize = (float)TABLESIZE; // move potArray[POT_P0] = Pot("f1f", 36); potArray[POT_P1] = Pot("f2f", 39); potArray[POT_P2] = Pot("f3f", 32); potArray[POT_P3] = Pot("f3q", 33); potArray[POT_P4] = Pot("larynx", 34); potArray[POT_P5] = Pot("pitch", 35); for (int i = 0; i < N_POTS_ACTUAL; i++) { adcAttachPin(potArray[i].channel()); } potArray[POT_P0].range(ADC_TOP, F1F_LOW, F1F_HIGH); potArray[POT_P1].range(ADC_TOP, F2F_LOW, F2F_HIGH); potArray[POT_P2].range(ADC_TOP, F3F_LOW, F3F_HIGH); potArray[POT_P3].range(ADC_TOP, F3Q_MIN, F3Q_MAX); potArray[POT_P4].range(ADC_TOP, tablesize * LARYNX_MIN / 100.0f, tablesize * LARYNX_MAX / 100.0f); potArray[POT_P5].range(ADC_TOP, PITCH_MIN, PITCH_MAX); potArray[POT_GROWL].range(ADC_TOP, GROWL_MAX, GROWL_MIN); } Pot &Pots::getPot(int n) { return potArray[n]; }
25.375
102
0.64532
danja
2836e0aee839529b28bec1912dfa074e4306a4fa
34
cpp
C++
2D_Processing/src/LineStrip.cpp
Epono/5A-3DJV-2D_Processing
de64ef4c851775abd87a00db526c98ec41124dc2
[ "MIT" ]
null
null
null
2D_Processing/src/LineStrip.cpp
Epono/5A-3DJV-2D_Processing
de64ef4c851775abd87a00db526c98ec41124dc2
[ "MIT" ]
null
null
null
2D_Processing/src/LineStrip.cpp
Epono/5A-3DJV-2D_Processing
de64ef4c851775abd87a00db526c98ec41124dc2
[ "MIT" ]
null
null
null
#include "../headers/LineStrip.h"
17
33
0.705882
Epono
2837ca8e718fbb7d3c28209ed54b6039e3f1c823
17,969
hxx
C++
Modules/Segmentation/Conversion/include/otbLabelImageRegionMergingFilter.hxx
heralex/OTB
c52b504b64dc89c8fe9cac8af39b8067ca2c3a57
[ "Apache-2.0" ]
317
2015-01-19T08:40:58.000Z
2022-03-17T11:55:48.000Z
Modules/Segmentation/Conversion/include/otbLabelImageRegionMergingFilter.hxx
guandd/OTB
707ce4c6bb4c7186e3b102b2b00493a5050872cb
[ "Apache-2.0" ]
18
2015-07-29T14:13:45.000Z
2021-03-29T12:36:24.000Z
Modules/Segmentation/Conversion/include/otbLabelImageRegionMergingFilter.hxx
guandd/OTB
707ce4c6bb4c7186e3b102b2b00493a5050872cb
[ "Apache-2.0" ]
132
2015-02-21T23:57:25.000Z
2022-03-25T16:03:16.000Z
/* * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef otbLabelImageRegionMergingFilter_hxx #define otbLabelImageRegionMergingFilter_hxx #include "otbLabelImageRegionMergingFilter.h" #include "itkImageRegionConstIteratorWithIndex.h" #include "itkImageRegionIterator.h" #include "itkProgressReporter.h" namespace otb { template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage> LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::LabelImageRegionMergingFilter() { m_RangeBandwidth = 1.0; m_NumberOfComponentsPerPixel = 0; this->SetNumberOfRequiredInputs(2); this->SetNumberOfRequiredOutputs(2); this->SetNthOutput(0, OutputLabelImageType::New()); this->SetNthOutput(1, OutputClusteredImageType::New()); } template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage> void LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::SetInputLabelImage( const TInputLabelImage* labelImage) { // Process object is not const-correct so the const casting is required. this->SetNthInput(0, const_cast<TInputLabelImage*>(labelImage)); } template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage> void LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::SetInputSpectralImage( const TInputSpectralImage* spectralImage) { // Process object is not const-correct so the const casting is required. this->SetNthInput(1, const_cast<TInputSpectralImage*>(spectralImage)); } template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage> TInputLabelImage* LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::GetInputLabelImage() { return dynamic_cast<TInputLabelImage*>(itk::ProcessObject::GetInput(0)); } template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage> TInputSpectralImage* LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::GetInputSpectralImage() { return dynamic_cast<TInputSpectralImage*>(itk::ProcessObject::GetInput(1)); } template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage> LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::~LabelImageRegionMergingFilter() { } template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage> TOutputLabelImage* LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::GetLabelOutput() { if (this->GetNumberOfOutputs() < 1) { return nullptr; } return static_cast<OutputLabelImageType*>(this->itk::ProcessObject::GetOutput(0)); } template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage> const TOutputLabelImage* LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::GetLabelOutput() const { if (this->GetNumberOfOutputs() < 1) { return 0; } return static_cast<OutputLabelImageType*>(this->itk::ProcessObject::GetOutput(0)); } template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage> typename LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::OutputClusteredImageType* LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::GetClusteredOutput() { if (this->GetNumberOfOutputs() < 2) { return nullptr; } return static_cast<OutputClusteredImageType*>(this->itk::ProcessObject::GetOutput(1)); } template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage> const typename LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::OutputClusteredImageType* LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::GetClusteredOutput() const { if (this->GetNumberOfOutputs() < 2) { return 0; } return static_cast<OutputClusteredImageType*>(this->itk::ProcessObject::GetOutput(1)); } template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage> void LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::GenerateOutputInformation() { Superclass::GenerateOutputInformation(); unsigned int numberOfComponentsPerPixel = this->GetInputSpectralImage()->GetNumberOfComponentsPerPixel(); if (this->GetClusteredOutput()) { this->GetClusteredOutput()->SetNumberOfComponentsPerPixel(numberOfComponentsPerPixel); } } template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage> void LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::EnlargeOutputRequestedRegion( itk::DataObject* itkNotUsed(output)) { // This filter requires all of the output images in the buffer. for (unsigned int j = 0; j < this->GetNumberOfOutputs(); j++) { if (this->itk::ProcessObject::GetOutput(j)) { this->itk::ProcessObject::GetOutput(j)->SetRequestedRegionToLargestPossibleRegion(); } } } template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage> void LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::GenerateData() { typename InputSpectralImageType::Pointer spectralImage = this->GetInputSpectralImage(); typename InputLabelImageType::Pointer inputLabelImage = this->GetInputLabelImage(); typename OutputLabelImageType::Pointer outputLabelImage = this->GetLabelOutput(); typename OutputClusteredImageType::Pointer outputClusteredImage = this->GetClusteredOutput(); // Allocate output outputLabelImage->SetBufferedRegion(outputLabelImage->GetRequestedRegion()); outputLabelImage->Allocate(); outputClusteredImage->SetBufferedRegion(outputClusteredImage->GetRequestedRegion()); outputClusteredImage->Allocate(); m_NumberOfComponentsPerPixel = spectralImage->GetNumberOfComponentsPerPixel(); // std::cout << "Copy input label image to output label image" << std::endl; // Copy input label image to output label image typename itk::ImageRegionConstIterator<InputLabelImageType> inputIt(inputLabelImage, outputLabelImage->GetRequestedRegion()); typename itk::ImageRegionIterator<OutputLabelImageType> outputIt(outputLabelImage, outputLabelImage->GetRequestedRegion()); inputIt.GoToBegin(); outputIt.GoToBegin(); while (!inputIt.IsAtEnd()) { outputIt.Set(inputIt.Get()); ++inputIt; ++outputIt; } RegionAdjacencyMapType regionAdjacencyMap = LabelImageToRegionAdjacencyMap(outputLabelImage); unsigned int regionCount = regionAdjacencyMap.size() - 1; // Initialize arrays for mode information m_CanonicalLabels.clear(); m_CanonicalLabels.resize(regionCount + 1); m_Modes.clear(); m_Modes.reserve(regionCount + 1); for (unsigned int i = 0; i < regionCount + 1; ++i) { m_Modes.push_back(SpectralPixelType(m_NumberOfComponentsPerPixel)); } m_PointCounts.clear(); m_PointCounts.resize(regionCount + 1); // = std::vector<unsigned int>(regionCount+1); // Associate each label to a spectral value, a canonical label and a point count typename itk::ImageRegionConstIterator<InputLabelImageType> inputItWithIndex(inputLabelImage, outputLabelImage->GetRequestedRegion()); inputItWithIndex.GoToBegin(); while (!inputItWithIndex.IsAtEnd()) { LabelType label = inputItWithIndex.Get(); // if label has not been initialized yet .. if (m_PointCounts[label] == 0) { // m_CanonicalLabels[label] = label; m_Modes[label] = spectralImage->GetPixel(inputItWithIndex.GetIndex()); } m_PointCounts[label]++; ++inputItWithIndex; } // Region Merging bool finishedMerging = false; unsigned int mergeIterations = 0; // std::cout << "Start merging" << std::endl; // Iterate until no more merge to do // while(!finishedMerging) // { while (!finishedMerging) { // Initialize Canonical Labels for (LabelType curLabel = 1; curLabel <= regionCount; ++curLabel) m_CanonicalLabels[curLabel] = curLabel; // Iterate over all regions for (LabelType curLabel = 1; curLabel <= regionCount; ++curLabel) { if (m_PointCounts[curLabel] == 0) { // do not process empty regions continue; } // std::cout<<" point in label "<<curLabel<<" "<<m_PointCounts[curLabel]<<std::endl; const SpectralPixelType& curSpectral = m_Modes[curLabel]; // Iterate over all adjacent regions and check for merge typename AdjacentLabelsContainerType::const_iterator adjIt = regionAdjacencyMap[curLabel].begin(); while (adjIt != regionAdjacencyMap[curLabel].end()) { LabelType adjLabel = *adjIt; assert(adjLabel <= regionCount); const SpectralPixelType& adjSpectral = m_Modes[adjLabel]; // Check condition to merge regions bool isSimilar = true; RealType norm2 = 0; for (unsigned int comp = 0; comp < m_NumberOfComponentsPerPixel; ++comp) { RealType e; e = (curSpectral[comp] - adjSpectral[comp]) / m_RangeBandwidth; norm2 += e * e; } isSimilar = norm2 < 0.25; if (isSimilar) { // Find canonical label for current region LabelType curCanLabel = curLabel; // m_CanonicalLabels[curLabel]; while (m_CanonicalLabels[curCanLabel] != curCanLabel) { curCanLabel = m_CanonicalLabels[curCanLabel]; } // Find canonical label for adjacent region LabelType adjCanLabel = adjLabel; // m_CanonicalLabels[curLabel]; while (m_CanonicalLabels[adjCanLabel] != adjCanLabel) { adjCanLabel = m_CanonicalLabels[adjCanLabel]; } // Assign same canonical label to both regions if (curCanLabel < adjCanLabel) { m_CanonicalLabels[adjCanLabel] = curCanLabel; } else { m_CanonicalLabels[m_CanonicalLabels[curCanLabel]] = adjCanLabel; m_CanonicalLabels[curCanLabel] = adjCanLabel; } } ++adjIt; } // end of loop over adjacent labels } // end of loop over labels // std::cout << "Simplify the table of canonical labels" << std::endl; /* Simplify the table of canonical labels */ for (LabelType i = 1; i < regionCount + 1; ++i) { LabelType can = i; while (m_CanonicalLabels[can] != can) { can = m_CanonicalLabels[can]; } m_CanonicalLabels[i] = can; } // std::cout << "merge regions with same canonical label" << std::endl; /* Merge regions with same canonical label */ /* - update modes and point counts */ std::vector<SpectralPixelType> newModes; newModes.reserve(regionCount + 1); //(regionCount+1, SpectralPixelType(m_NumberOfComponentsPerPixel)); for (unsigned int i = 0; i < regionCount + 1; ++i) { newModes.push_back(SpectralPixelType(m_NumberOfComponentsPerPixel)); } std::vector<unsigned int> newPointCounts(regionCount + 1); for (unsigned int i = 1; i < regionCount + 1; ++i) { newModes[i].Fill(0); newPointCounts[i] = 0; } for (unsigned int i = 1; i < regionCount + 1; ++i) { LabelType canLabel = m_CanonicalLabels[i]; unsigned int nPoints = m_PointCounts[i]; for (unsigned int comp = 0; comp < m_NumberOfComponentsPerPixel; ++comp) { newModes[canLabel][comp] += nPoints * m_Modes[i][comp]; } newPointCounts[canLabel] += nPoints; } // std::cout << "re-labeling" << std::endl; /* re-labeling */ std::vector<LabelType> newLabels(regionCount + 1); std::vector<bool> newLabelSet(regionCount + 1); for (unsigned int i = 1; i < regionCount + 1; ++i) { newLabelSet[i] = false; } LabelType label = 0; for (unsigned int i = 1; i < regionCount + 1; ++i) { LabelType canLabel = m_CanonicalLabels[i]; if (newLabelSet[canLabel] == false) { newLabelSet[canLabel] = true; label++; newLabels[canLabel] = label; unsigned int nPoints = newPointCounts[canLabel]; for (unsigned int comp = 0; comp < m_NumberOfComponentsPerPixel; ++comp) { m_Modes[label][comp] = newModes[canLabel][comp] / nPoints; } m_PointCounts[label] = newPointCounts[canLabel]; } } unsigned int oldRegionCount = regionCount; regionCount = label; /* reassign labels in label image */ outputIt.GoToBegin(); while (!outputIt.IsAtEnd()) { LabelType l = outputIt.Get(); LabelType canLabel; assert(m_CanonicalLabels[l] <= oldRegionCount); canLabel = newLabels[m_CanonicalLabels[l]]; outputIt.Set(canLabel); ++outputIt; } finishedMerging = oldRegionCount == regionCount || mergeIterations >= 10 || regionCount == 1; // only one iteration for now if (!finishedMerging) { /* Update adjacency table */ regionAdjacencyMap = LabelImageToRegionAdjacencyMap(outputLabelImage); } mergeIterations++; } // end of main iteration loop // std::cout << "merge iterations: " << mergeIterations << std::endl; // std::cout << "number of label objects: " << regionCount << std::endl; // Generate clustered output itk::ImageRegionIterator<OutputClusteredImageType> outputClusteredIt(outputClusteredImage, outputClusteredImage->GetRequestedRegion()); outputClusteredIt.GoToBegin(); outputIt.GoToBegin(); while (!outputClusteredIt.IsAtEnd()) { LabelType label = outputIt.Get(); const SpectralPixelType& p = m_Modes[label]; outputClusteredIt.Set(p); ++outputClusteredIt; ++outputIt; } } template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage> void LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::PrintSelf(std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Range bandwidth: " << m_RangeBandwidth << std::endl; } template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage> typename LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::RegionAdjacencyMapType LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::LabelImageToRegionAdjacencyMap( typename OutputLabelImageType::Pointer labelImage) { // declare the output map RegionAdjacencyMapType ram; // Find the maximum label value itk::ImageRegionConstIterator<OutputLabelImageType> it(labelImage, labelImage->GetRequestedRegion()); it.GoToBegin(); LabelType maxLabel = 0; while (!it.IsAtEnd()) { LabelType label = it.Get(); maxLabel = std::max(maxLabel, label); ++it; } // Set the size of the adjacency map ram.resize(maxLabel + 1); // set the image region without bottom and right borders so that bottom and // right neighbors always exist RegionType regionWithoutBottomRightBorders = labelImage->GetRequestedRegion(); SizeType size = regionWithoutBottomRightBorders.GetSize(); for (unsigned int d = 0; d < ImageDimension; ++d) size[d] -= 1; regionWithoutBottomRightBorders.SetSize(size); itk::ImageRegionConstIteratorWithIndex<OutputLabelImageType> inputIt(labelImage, regionWithoutBottomRightBorders); inputIt.GoToBegin(); while (!inputIt.IsAtEnd()) { const InputIndexType& index = inputIt.GetIndex(); LabelType label = inputIt.Get(); // check neighbors for (unsigned int d = 0; d < ImageDimension; ++d) { InputIndexType neighborIndex = index; neighborIndex[d]++; LabelType neighborLabel = labelImage->GetPixel(neighborIndex); // add adjacency if different labels if (neighborLabel != label) { ram[label].insert(neighborLabel); ram[neighborLabel].insert(label); } } ++inputIt; } return ram; } } // end namespace otb #endif
38.069915
159
0.718181
heralex
28387227adf8dd2d42870d9474af4f96725dc1d4
2,120
cpp
C++
solved-codeforces/the_redback/contest/749/c/23155481.cpp
Maruf-Tuhin/Online_Judge
cf9b2a522e8b1a9623d3996a632caad7fd67f751
[ "MIT" ]
1
2019-03-31T05:47:30.000Z
2019-03-31T05:47:30.000Z
solved-codeforces/the_redback/contest/749/c/23155481.cpp
the-redback/competitive-programming
cf9b2a522e8b1a9623d3996a632caad7fd67f751
[ "MIT" ]
null
null
null
solved-codeforces/the_redback/contest/749/c/23155481.cpp
the-redback/competitive-programming
cf9b2a522e8b1a9623d3996a632caad7fd67f751
[ "MIT" ]
null
null
null
/** * @author : Maruf Tuhin * @College : CUET CSE 11 * @Topcoder : the_redback * @CodeForces : the_redback * @UVA : the_redback * @link : http://www.fb.com/maruf.2hin */ #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long llu; #define ft first #define sd second #define mp make_pair #define pb(x) push_back(x) #define all(x) x.begin(),x.end() #define allr(x) x.rbegin(),x.rend() #define mem(a,b) memset(a,b,sizeof(a)) #define sf(a) scanf("%lld",&a) #define ssf(a) scanf("%s",&a) #define sf2(a,b) scanf("%lld %lld",&a,&b) #define sf3(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define inf 1e9 #define eps 1e-9 #define mod 1000000007 #define NN 100010 #ifdef redback #define bug printf("line=%d\n",__LINE__); #define debug(args...) {cout<<":: "; dbg,args; cerr<<endl;} struct debugger{template<typename T>debugger& operator ,(const T& v){cerr<<v<<" ";return *this;}}dbg; #else #define bug #define debug(args...) #endif //debugging macros struct node { int w; node(){} node(int b) {w = b;} bool operator < ( const node& p ) const { return w > p.w; } }; priority_queue<node>R,D; char a[200010]; ll b[200010]; int main() { #ifdef redback freopen("C:\\Users\\Maruf\\Desktop\\in.txt","r",stdin); #endif ll t=1,tc; //sf(tc); ll l,m,n; while(~sf(n)) { ll i,j,k; R=priority_queue<node>(); D=priority_queue<node>(); mem(b,-1); ssf(a); for(i=0;i<n;i++) { if(a[i]=='D') D.push(node(i)); if(a[i]=='R') R.push(node(i)); } while(!R.empty() && !D.empty()) { node rr=R.top(); node dd=D.top(); R.pop(); D.pop(); if(rr.w<dd.w) { R.push(node(rr.w+n)); } else D.push(node(dd.w+n)); } if(!R.empty()) puts("R"); else puts("D"); } return 0; }
22.083333
102
0.49434
Maruf-Tuhin
2838a15aef565c77fc2e1f02155ebe31e09a2244
12,215
cpp
C++
applications/plugins/image/imagetoolbox/depth/depthimagetoolboxaction.cpp
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
applications/plugins/image/imagetoolbox/depth/depthimagetoolboxaction.cpp
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
applications/plugins/image/imagetoolbox/depth/depthimagetoolboxaction.cpp
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
#include "depthimagetoolbox.h" #include "depthimagetoolboxaction.h" #include <QString> #include <QLabel> namespace sofa { namespace gui { namespace qt { int DepthRowImageToolBoxAction::numindex=0; DepthImageToolBoxAction::DepthImageToolBoxAction(sofa::component::engine::LabelImageToolBox* lba,QObject *parent): LabelImageToolBoxAction(lba,parent) { /* QGroupBox *gb = new QGroupBox(); gb->setTitle("Main Commands"); QHBoxLayout *hb = new QHBoxLayout(); //button selection point select = new QPushButton("Select Point"); hb->addWidget(select); //this->addWidget(select); select->setCheckable(true); connect(select,SIGNAL(toggled(bool)),this,SLOT(selectionPointButtonClick(bool))); QPushButton* section = new QPushButton("Go to"); hb->addWidget(section); //this->addWidget(section); connect(section,SIGNAL(clicked()),this,SLOT(sectionButtonClick())); gb->setLayout(hb); this->addWidget(gb);*/ createMainCommands(); //createInfoWidget(); //createBoxCommands(); //createGridCommands(); //createNormalCommands(); createListLayers(); //executeButtonClick(); } void DepthImageToolBoxAction::createMainCommands() { QGroupBox *gb = new QGroupBox("Main Commands"); QHBoxLayout *hb = new QHBoxLayout(); // QPushButton *reloadButton = new QPushButton("Reload"); //QPushButton *executeButton = new QPushButton("Execute"); // hb->addWidget(reloadButton); //hb->addWidget(executeButton); QHBoxLayout *hb2 = new QHBoxLayout(); QPushButton *saveParamButton = new QPushButton("Save params"); QPushButton *loadParamButton = new QPushButton("Load params"); QPushButton *saveSceneButton = new QPushButton("Save SCN"); connect(saveParamButton,SIGNAL(clicked()),this,SLOT(saveButtonClick())); connect(loadParamButton,SIGNAL(clicked()),this,SLOT(loadButtonClick())); connect(saveSceneButton,SIGNAL(clicked()),this,SLOT(saveSceneButtonClick())); hb2->addWidget(saveParamButton); hb2->addWidget(loadParamButton); QHBoxLayout *hb3 = new QHBoxLayout(); hb3->addWidget(saveSceneButton); QVBoxLayout *vb =new QVBoxLayout(); vb->addLayout(hb); vb->addLayout(hb2); vb->addLayout(hb3); gb->setLayout(vb); this->addWidget(gb); } void DepthImageToolBoxAction::createListLayers() { std::cout<<"nnn "<<std::endl; sofa::component::engine::DepthImageToolBox *l = DITB(); unsigned int numberGrid = l->labelsOfGrid.size(); QGroupBox * gp = new QGroupBox("List of Layers"); QFormLayout *form = new QFormLayout(); form->addRow("numbers of Grids:",new QLabel(QString::number(numberGrid))); listLayers = new QTableWidget(); listLayers->insertColumn(0); listLayers->insertColumn(1); listLayers->insertColumn(2); listLayers->insertColumn(3); QStringList header; header << "name" << "geometry" << "grid1" << "grid2"; listLayers->setHorizontalHeaderLabels(header); QPushButton *listLayersAdd = new QPushButton("Add"); connect(listLayersAdd,SIGNAL(clicked()),this,SLOT(createNewRow())); QPushButton *listLayersRem = new QPushButton("remove"); QPushButton *listLayersGenerate = new QPushButton("generate"); connect(listLayersGenerate,SIGNAL(clicked()),this,SLOT(executeButtonClick())); QHBoxLayout * hb = new QHBoxLayout(); hb->addWidget(listLayersAdd); hb->addWidget(listLayersRem); QVBoxLayout *vb = new QVBoxLayout(); vb->addLayout(form); vb->addWidget(listLayers); vb->addLayout(hb); vb->addWidget(listLayersGenerate); gp->setLayout(vb); if(numberGrid==0) { listLayersAdd->setEnabled(false); listLayersRem->setEnabled(false); //listLayers->setEnabled(false); } this->addWidget(gp); } void DepthImageToolBoxAction::createNewRow(int layer) { sofa::component::engine::DepthImageToolBox *d = DITB(); sofa::component::engine::DepthImageToolBox::Layer &l = d->layers[layer]; this->createNewRow(); DepthRowImageToolBoxAction *row = listRows.back(); QString offset1;offsetToText(offset1,l.offset1,l.typeOffset1); QString offset2;offsetToText(offset2,l.offset2,l.typeOffset2); row->setValue(QString::fromStdString(l.name), l.layer1, offset1, l.layer2, offset2, l.base,l.nbSlice); } void DepthImageToolBoxAction::createNewRow() { //std::cout << "createNewRow"<<std::endl; sofa::component::engine::DepthImageToolBox *l = DITB(); DepthRowImageToolBoxAction *row = new DepthRowImageToolBoxAction(listRows.size()); row->setParameters(l->labelsOfGrid); row->toTableWidgetRow(listLayers); listLayers->update(); l->createLayer(); //std::cout << l->layers.size()<<std::endl; this->connect(row,SIGNAL(valueChanged(int,QString,int,QString,int,QString,int,int)),this,SLOT(changeRow(int,QString,int,QString,int,QString,int,int))); row->change(); listRows.push_back(row); } void DepthImageToolBoxAction::offsetToText(QString &out, double outValue, int type) { switch(type) { case DepthImageToolBox::Layer::Distance: out = QString::number(outValue); break; case DepthImageToolBox::Layer::Percent: out = QString::number(outValue*100) +"%"; break; } return; } void DepthImageToolBoxAction::textToOffset(QString text, double &outValue, int &type) { bool ok; outValue = text.toDouble(&ok); if(ok) { type = sofa::component::engine::DepthImageToolBox::Layer::Distance; return; } if(text.contains("%")) { text.replace("%",""); outValue = text.toDouble(&ok); outValue *= 0.01; if(ok) { type = sofa::component::engine::DepthImageToolBox::Layer::Percent; return; } } outValue = 0; type = sofa::component::engine::DepthImageToolBox::Layer::Distance; return; } void DepthImageToolBoxAction::changeRow(int index,QString name,int layer1,QString offset1,int layer2,QString offset2,int base,int nbSlice) { //std::cout << "DepthImageToolBoxAction::changeRow " << index << " "<< name.toStdString() << " "<<layer1<<" "<<offset1.toStdString()<<" "<<layer2<<" "<<offset2.toStdString()<<std::endl; sofa::component::engine::DepthImageToolBox *l = DITB(); if(l->layers.size()<=(unsigned int)index)return; sofa::component::engine::DepthImageToolBox::Layer &layer = l->layers[index]; layer.name = name.toStdString(); layer.layer1 = layer1; layer.layer2 = layer2; layer.base = base; layer.nbSlice = nbSlice; textToOffset(offset1,layer.offset1,layer.typeOffset1); textToOffset(offset2,layer.offset2,layer.typeOffset2); //std::cout << layer.name << " " << layer.offset1 << " " << layer.typeOffset1 <<layer.offset2 << " " << layer.typeOffset2 <<std::endl; } DepthImageToolBoxAction::~DepthImageToolBoxAction() { //delete select; } sofa::component::engine::DepthImageToolBox* DepthImageToolBoxAction::DITB() { return dynamic_cast<sofa::component::engine::DepthImageToolBox*>(this->p_label); } void DepthImageToolBoxAction::executeButtonClick() { sofa::component::engine::DepthImageToolBox *l = DITB(); l->executeAction(); //updateGraphs(); //std::cout << "exitButton"<<std::endl; } void DepthImageToolBoxAction::saveButtonClick() { //std::cout << "saveButtonClick"<<std::endl; sofa::component::engine::DepthImageToolBox *l = DITB(); l->saveFile(); //updateGraphs(); //std::cout << "exitButton"<<std::endl; } void DepthImageToolBoxAction::loaduttonClick() { sofa::component::engine::DepthImageToolBox *l = DITB(); l->loadFile(); updateGraphs(); //std::cout << "exitButton"<<std::endl; } void DepthImageToolBoxAction::saveSceneButtonClick() { sofa::component::engine::DepthImageToolBox *l = DITB(); l->saveSCN(); } void DepthImageToolBoxAction::selectionPointEvent(int /*mouseevent*/, const unsigned int /*axis*/,const sofa::defaulttype::Vec3d& /*imageposition*/,const sofa::defaulttype::Vec3d& /*position3D*/,const QString& /*value*/) { /* select->setChecked(false); disconnect(this,SIGNAL(clickImage(int,unsigned int,sofa::defaulttype::Vec3d,sofa::defaulttype::Vec3d,QString)),this,SLOT(selectionPointEvent(int,unsigned int,sofa::defaulttype::Vec3d,sofa::defaulttype::Vec3d,QString))); sofa::component::engine::DepthImageToolBox* lp = LGITB(); lp->d_ip.setValue(imageposition); lp->d_p.setValue(position3D); lp->d_axis.setValue(axis); lp->d_value.setValue(value.toStdString()); updateGraphs();*/ } /* void DepthImageToolBoxAction::selectionPointButtonClick(bool b) { if(b) { //select->setChecked(true); connect(this,SIGNAL(clickImage(int,unsigned int,sofa::defaulttype::Vec3d,sofa::defaulttype::Vec3d,QString)),this,SLOT(selectionPointEvent(int,unsigned int,sofa::defaulttype::Vec3d,sofa::defaulttype::Vec3d,QString))); } else { //select->setChecked(false); disconnect(this,SIGNAL(clickImage(int,unsigned int,sofa::defaulttype::Vec3d,sofa::defaulttype::Vec3d,QString)),this,SLOT(selectionPointEvent(int,unsigned int,sofa::defaulttype::Vec3d,sofa::defaulttype::Vec3d,QString))); } }*/ void DepthImageToolBoxAction::addOnGraphs() { // std::cout << "addOnGraph"<<std::endl; path[0] = GraphXY->addPath(QPainterPath()); path[1] = GraphXZ->addPath(QPainterPath()); path[2] = GraphZY->addPath(QPainterPath()); for(int i=0;i<3;i++) { path[i]->setVisible(true); } updateColor(); } void DepthImageToolBoxAction::moveTo(const unsigned int axis,const sofa::defaulttype::Vec3d& imageposition) { QPainterPath poly; int ximage,yimage; switch(axis) { case 0: ximage = 0; yimage = 1; break; case 1: ximage = 0; yimage = 2; break; case 2: ximage = 2; yimage = 1; break; default: return; } poly = path[axis]->path(); poly.moveTo(imageposition[ximage],imageposition[yimage]); path[axis]->setPath(poly); } void DepthImageToolBoxAction::lineTo(const unsigned int axis,const sofa::defaulttype::Vec3d& imageposition) { QPainterPath poly; int ximage,yimage; switch(axis) { case 0: ximage = 0; yimage = 1; break; case 1: ximage = 0; yimage = 2; break; case 2: ximage =2; yimage = 1; break; default: return; } poly = path[axis]->path(); poly.lineTo(imageposition[ximage],imageposition[yimage]); path[axis]->setPath(poly); } void DepthImageToolBoxAction::updateGraphs() { sofa::component::engine::DepthImageToolBox *l = DITB(); listLayers->clear(); listRows.clear(); for(unsigned int i=0;i<l->layers.size();i++) { this->createNewRow(i); } //int axis = l->d_axis.getValue(); //this->setAxis(axis); /*helper::vector<sofa::defaulttype::Vec3d>& pos = *(l->d_outImagePosition.beginEdit()); sofa::component::engine::DepthImageToolBox::Edges& edges = *(l->d_outEdges.beginEdit()); path[0]->setPath(QPainterPath()); path[1]->setPath(QPainterPath()); path[2]->setPath(QPainterPath()); for(unsigned int i=0;i<edges.size();i++) { sofa::defaulttype::Vec3d p1 = pos[edges[i][0]]; sofa::defaulttype::Vec3d p2 = pos[edges[i][1]]; moveTo(0,p1); moveTo(1,p1); moveTo(2,p1); lineTo(0,p2); lineTo(1,p2); lineTo(2,p2); }*/ } void DepthImageToolBoxAction::updateColor() { for(int i=0;i<3;i++) { path[i]->setPen(QPen(this->color())); } } /* void DepthImageToolBoxAction::sectionButtonClick() { // std::cout << "DepthImageToolBoxAction::sectionButtonClick()"<<std::endl; sofa::defaulttype::Vec3d pos = LGITB()->d_ip.getValue(); sofa::defaulttype::Vec3i pos2(round(pos.x()),round(pos.y()),round(pos.z())); emit sectionChanged(pos2); }*/ SOFA_DECL_CLASS(DepthImageToolBoxAction) } } }
26.439394
227
0.654032
sofa-framework
283a534e855eb822e3a85e59fcc8f8cf13f9b13d
2,116
cc
C++
shell/common/asar/scoped_temporary_file.cc
TarunavBA/electron
a41898bb9b889486fb93c11b7107b9412818133a
[ "MIT" ]
88,283
2016-04-04T19:29:13.000Z
2022-03-31T23:33:33.000Z
shell/common/asar/scoped_temporary_file.cc
TarunavBA/electron
a41898bb9b889486fb93c11b7107b9412818133a
[ "MIT" ]
27,327
2016-04-04T19:38:58.000Z
2022-03-31T22:34:10.000Z
shell/common/asar/scoped_temporary_file.cc
TarunavBA/electron
a41898bb9b889486fb93c11b7107b9412818133a
[ "MIT" ]
15,972
2016-04-04T19:32:06.000Z
2022-03-31T08:54:00.000Z
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/common/asar/scoped_temporary_file.h" #include <vector> #include "base/files/file_util.h" #include "base/logging.h" #include "base/threading/thread_restrictions.h" #include "shell/common/asar/asar_util.h" namespace asar { ScopedTemporaryFile::ScopedTemporaryFile() = default; ScopedTemporaryFile::~ScopedTemporaryFile() { if (!path_.empty()) { base::ThreadRestrictions::ScopedAllowIO allow_io; // On Windows it is very likely the file is already in use (because it is // mostly used for Node native modules), so deleting it now will halt the // program. #if defined(OS_WIN) base::DeleteFileAfterReboot(path_); #else base::DeleteFile(path_); #endif } } bool ScopedTemporaryFile::Init(const base::FilePath::StringType& ext) { if (!path_.empty()) return true; base::ThreadRestrictions::ScopedAllowIO allow_io; if (!base::CreateTemporaryFile(&path_)) return false; #if defined(OS_WIN) // Keep the original extension. if (!ext.empty()) { base::FilePath new_path = path_.AddExtension(ext); if (!base::Move(path_, new_path)) return false; path_ = new_path; } #endif return true; } bool ScopedTemporaryFile::InitFromFile( base::File* src, const base::FilePath::StringType& ext, uint64_t offset, uint64_t size, const absl::optional<IntegrityPayload>& integrity) { if (!src->IsValid()) return false; if (!Init(ext)) return false; base::ThreadRestrictions::ScopedAllowIO allow_io; std::vector<char> buf(size); int len = src->Read(offset, buf.data(), buf.size()); if (len != static_cast<int>(size)) return false; if (integrity.has_value()) { ValidateIntegrityOrDie(buf.data(), buf.size(), integrity.value()); } base::File dest(path_, base::File::FLAG_OPEN | base::File::FLAG_WRITE); if (!dest.IsValid()) return false; return dest.WriteAtCurrentPos(buf.data(), buf.size()) == static_cast<int>(size); } } // namespace asar
25.190476
77
0.690926
TarunavBA