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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c9af57acaf292d9e5dded59e15a94507fd51e092 | 3,568 | hpp | C++ | include/cass/iterator.hpp | API92/cassaforte | 27eb8fdd822c0fc5d7b078228b698cb2e0804e01 | [
"BSD-2-Clause"
] | null | null | null | include/cass/iterator.hpp | API92/cassaforte | 27eb8fdd822c0fc5d7b078228b698cb2e0804e01 | [
"BSD-2-Clause"
] | null | null | null | include/cass/iterator.hpp | API92/cassaforte | 27eb8fdd822c0fc5d7b078228b698cb2e0804e01 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (C) Andrey Pikas
*/
#pragma once
#include "delete_defaults.hpp"
#include "forward.hpp"
#include "impexp.hpp"
typedef struct CassIterator_ CassIterator;
namespace cass {
class CASSA_IMPEXP iterator : delete_defaults {
public:
static iterator * ptr(::CassIterator *p);
::CassIterator * backend();
::CassIterator const * backend() const;
void free();
static iterator_ptr from_result(cass::result const *result);
static iterator_ptr from_row(cass::row const *row);
static iterator_ptr from_collection(cass::value const *value);
static iterator_ptr from_map(cass::value const *value);
static iterator_ptr from_tuple(cass::value const *value);
static iterator_ptr fields_from_user_type(
cass::value const *value);
static iterator_ptr keyspaces_from_schema_meta(
cass::schema_meta const *schema_meta);
static iterator_ptr tables_from_keyspace_meta(
cass::keyspace_meta const *keyspace_meta);
static iterator_ptr materialized_views_from_keyspace_meta(
cass::keyspace_meta const *keyspace_meta);
static iterator_ptr user_types_from_keyspace_meta(
cass::keyspace_meta const *keyspace_meta);
static iterator_ptr functions_from_keyspace_meta(
cass::keyspace_meta const *keyspace_meta);
static iterator_ptr aggregates_from_keyspace_meta(
cass::keyspace_meta const *keyspace_meta);
static iterator_ptr fields_from_keyspace_meta(
cass::keyspace_meta const *keyspace_meta);
static iterator_ptr columns_from_table_meta(
cass::table_meta const *table_meta);
static iterator_ptr indexes_from_table_meta(
cass::table_meta const *table_meta);
static iterator_ptr materialized_views_from_table_meta(
cass::table_meta const *table_meta);
static iterator_ptr fields_from_table_meta(
cass::table_meta const *table_meta);
static iterator_ptr columns_from_materialized_view_meta(
materialized_view_meta const *view_meta);
static iterator_ptr fields_from_materialized_view_meta(
materialized_view_meta const *view_meta);
static iterator_ptr fields_from_column_meta(
cass::column_meta const *column_meta);
static iterator_ptr fields_from_index_meta(
cass::index_meta const *index_meta);
static iterator_ptr fields_from_function_meta(
cass::function_meta const *function_meta);
static iterator_ptr fields_from_aggregate_meta(
cass::aggregate_meta const *aggregate_meta);
iterator_type type();
bool next();
row const * get_row() const;
value const * get_column() const;
value const * get_value() const;
value const * get_map_key() const;
value const * get_map_value() const;
error get_user_type_field_name(char const **name,
size_t *name_length);
value const * get_user_type_field_value();
keyspace_meta const * get_keyspace_meta() const;
table_meta const * get_table_meta() const;
materialized_view_meta const * get_materialized_view_meta()
const;
data_type const * get_user_type() const;
function_meta const * get_function_meta() const;
aggregate_meta const * get_aggregate_meta() const;
column_meta const * get_column_meta() const;
index_meta const * get_index_meta() const;
error get_meta_field_name(char const **name, size_t *name_length);
value const * get_meta_field_value() const;
};
} // namespace cass
| 27.446154 | 70 | 0.716928 | API92 |
c9b002ebb15e6cceb3fd782e4180efc6daaa7c44 | 1,524 | cc | C++ | RAVL2/Core/System/testSTL.cc | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/Core/System/testSTL.cc | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/Core/System/testSTL.cc | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | // This file is part of RAVL, Recognition And Vision Library
// Copyright (C) 2001, University of Surrey
// This code may be redistributed under the terms of the GNU Lesser
// General Public License (LGPL). See the lgpl.licence file for details or
// see http://www.gnu.org/copyleft/lesser.html
// file-header-ends-here
//////////////////////////////////////////////////////////////
//! rcsid="$Id: testSTL.cc 6723 2008-04-17 14:18:15Z craftit $"
//! lib=RavlCore
//! file="Ravl/Core/System/testSTL.cc"
//! docentry="Ravl.API.Core.Misc"
//! author="Robert Crida"
#include "Ravl/STL.hh"
#include "Ravl/UnitTest.hh"
using namespace RavlN;
int testVectorIntIO();
int testVectorStringIO();
int main()
{
int err;
if((err = testVectorIntIO()) != 0) {
cerr << "Test failed line :" << err <<"\n";
return 1;
}
if((err = testVectorStringIO()) != 0) {
cerr << "Test failed line :" << err <<"\n";
return 1;
}
cerr << "STL test passed. \n";
return 0;
}
int testVectorIntIO() {
vector<int> intVec;
intVec.push_back(0);
intVec.push_back(1);
intVec.push_back(2);
vector<int> loadedVec;
if (!TestBinStreamIO(intVec, loadedVec)) return __LINE__;
if (intVec != loadedVec) return __LINE__;
return 0;
}
int testVectorStringIO() {
vector<string> strVec;
strVec.push_back("first");
strVec.push_back("second");
strVec.push_back("third");
vector<string> loadedVec;
if (!TestBinStreamIO(strVec, loadedVec)) return __LINE__;
if (strVec != loadedVec) return __LINE__;
return 0;
}
| 24.580645 | 74 | 0.646325 | isuhao |
c9b7684f537f975682598e17fb8da142a6258f88 | 3,553 | hpp | C++ | SPD/Schrage/Alternatywna implementacja kopca/kopiec.hpp | AzethMeron/SPD | d24f68b01101ed0589071fbc7dc030fb1c4d7efb | [
"Unlicense"
] | null | null | null | SPD/Schrage/Alternatywna implementacja kopca/kopiec.hpp | AzethMeron/SPD | d24f68b01101ed0589071fbc7dc030fb1c4d7efb | [
"Unlicense"
] | null | null | null | SPD/Schrage/Alternatywna implementacja kopca/kopiec.hpp | AzethMeron/SPD | d24f68b01101ed0589071fbc7dc030fb1c4d7efb | [
"Unlicense"
] | null | null | null | #ifndef KOPIEC_HPP
#define KOPIEC_HPP
#include <vector>
#include <algorithm>
#include <functional>
#include "Stack.hpp"
using namespace std;
// You need to pass function in constructor that will be used to compare values
// bool Comp(const TYPE& l, const TYPE& r)
// Return TRUE if LEFT is bigger than RIGHT to get asceding order
// Useful methods:
// 'push(const TYPE&)' to properly add new element to Heap
// 'front()' to get element on top of Heap
// 'pop()' to remove element on top
// 'size()' to get size of Heap
// 'remove(const int&)' to remove element from given index in internal container
// operator [] allows to GET, but not SET value in internal container. Useful for searching
// 'find(const TYPE& elem, bool FUNCTION(const TYPE&, const TYPE&))' get index of elem in internal container. Return -1 if not found
// for some reason, function named 'equal' didnt work, and 'func' and 'arc' worked fine
// Oh i get it now, it took std::equal or smt. So be careful to not overlap
template<typename TYPE>
class Heap
{
private:
void UpdateNode(const int& node);
inline int Parent(const int& node) const { return ((node-1)/2); }
inline int LChild(const int& node) const { int wyjscie = -1; if(((node+1)*2-1) < (int)size()) wyjscie = ((node+1)*2-1); return wyjscie; }
inline int RChild(const int& node) const { int wyjscie = -1; if(((node+1)*2) < (int)size()) wyjscie = ((node+1)*2); return wyjscie; }
protected:
vector<TYPE> data;
std::function<bool(const TYPE&, const TYPE&)> Comp;
public:
// Consts
inline unsigned int size(void) const { return data.size(); }
inline const TYPE& front(void) const { return data.front(); }
inline const TYPE& operator [] (const int& ind) const { return data[ind]; }
int find(const TYPE& elem, std::function<bool(const TYPE&, const TYPE&)> ifequal) const;
// Modifiers
inline void push(const TYPE& inp) { data.push_back(inp); UpdateNode(size()-1); }
inline void pop(void) { swap(data.front(),data.back()); data.pop_back(); UpdateNode(0); }
inline void remove(const int& ind) { swap(data[ind],data.back()); data.pop_back(); UpdateNode(ind); }
// Constructors
Heap(std::function<bool(const TYPE&, const TYPE&)> comp, const vector<TYPE>& newdata) { Comp = comp; for(unsigned int i = 0; i < newdata.size(); ++i) { push(newdata[i]); } }
Heap(std::function<bool(const TYPE&, const TYPE&)> comp) { Comp = comp; }
};
template<typename TYPE>
void Heap<TYPE>::UpdateNode(const int& fnode)
{
Stack<int> nodes;
nodes.push(fnode);
while(nodes.size())
{
int node = nodes.front();
nodes.pop();
int parent = Parent(node);
int lchild = LChild(node); // -1 if non-existant
int rchild = RChild(node); // -1 if non-existant
bool not_changed = true;
// Parent
if(node > 0 && not_changed)
{
if( Comp(data[parent],data[node]) )
{
swap(data[node],data[parent]); nodes.push(node); nodes.push(parent); not_changed = false;
}
}
// Childs
if( lchild > 0 && not_changed)
{
if( Comp(data[node],data[lchild]) )
{
swap(data[node],data[lchild]); nodes.push(node); nodes.push(lchild); not_changed = false;
}
}
if( rchild > 0 && not_changed)
{
if( Comp(data[node],data[rchild]) )
{
swap(data[node],data[rchild]); nodes.push(node); nodes.push(rchild); not_changed = false;
}
}
}
}
template<typename TYPE>
int Heap<TYPE>::find(const TYPE& elem, std::function<bool(const TYPE&, const TYPE&)> ifequal) const
{
for(int i = 0; i < (int)size(); ++i)
{
if(ifequal(elem,data[i]))
return i;
}
return -1;
}
#endif
| 33.205607 | 175 | 0.663665 | AzethMeron |
c9b88fe70f45e6dc9b57308f7b5af86e859cda19 | 1,669 | cpp | C++ | libs/geometry/doc/src/examples/algorithms/assign_2d_point.cpp | Ron2014/boost_1_48_0 | 19673f69677ffcba7c7bd6e08ec07ee3962f161c | [
"BSL-1.0"
] | null | null | null | libs/geometry/doc/src/examples/algorithms/assign_2d_point.cpp | Ron2014/boost_1_48_0 | 19673f69677ffcba7c7bd6e08ec07ee3962f161c | [
"BSL-1.0"
] | null | null | null | libs/geometry/doc/src/examples/algorithms/assign_2d_point.cpp | Ron2014/boost_1_48_0 | 19673f69677ffcba7c7bd6e08ec07ee3962f161c | [
"BSL-1.0"
] | null | null | null | // Boost.Geometry (aka GGL, Generic Geometry Library)
// QuickBook Example
// Copyright (c) 2011 Barend Gehrels, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to 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)
//[assign_2d_point
//` Shows the usage of assign to set point coordinates, and, besides that, shows how you can initialize ttmath points with high precision
#include <iostream>
#include <iomanip>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#if defined(HAVE_TTMATH)
# include <boost/geometry/extensions/contrib/ttmath_stub.hpp>
#endif
int main()
{
using boost::geometry::assign_values;
boost::geometry::model::d2::point_xy<double> p1;
assign_values(p1, 1.2345, 2.3456);
#if defined(HAVE_TTMATH)
boost::geometry::model::d2::point_xy<ttmath::Big<1,4> > p2;
assign_values(p2, "1.2345", "2.3456"); /*< It is possible to assign coordinates with other types than the coordinate type.
For ttmath, you can e.g. conveniently use strings. The advantage is that it then has higher precision, because
if doubles are used for assignments the double-precision is used.
>*/
#endif
std::cout
<< std::setprecision(20)
<< boost::geometry::dsv(p1) << std::endl
#if defined(HAVE_TTMATH)
<< boost::geometry::dsv(p2) << std::endl
#endif
;
return 0;
}
//]
//[assign_2d_point_output
/*`
Output:
[pre
(1.2344999999999999, 2.3456000000000001)
(1.2345, 2.3456)
]
*/
//]
| 26.492063 | 138 | 0.672259 | Ron2014 |
c9ba4f04b02308970fd6d08c048c104fbcd54faa | 5,627 | hxx | C++ | main/svtools/source/uno/wizard/wizardshell.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/svtools/source/uno/wizard/wizardshell.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/svtools/source/uno/wizard/wizardshell.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef SVT_UNO_WIZARD_SHELL
#define SVT_UNO_WIZARD_SHELL
/** === begin UNO includes === **/
#include <com/sun/star/ui/dialogs/XWizardController.hpp>
#include <com/sun/star/ui/dialogs/XWizard.hpp>
/** === end UNO includes === **/
#include <svtools/roadmapwizard.hxx>
#include <boost/shared_ptr.hpp>
#include <map>
//......................................................................................................................
namespace svt { namespace uno
{
//......................................................................................................................
class WizardPageController;
typedef ::boost::shared_ptr< WizardPageController > PWizardPageController;
//==================================================================================================================
//= WizardShell
//==================================================================================================================
typedef ::svt::RoadmapWizard WizardShell_Base;
class WizardShell : public WizardShell_Base
{
public:
WizardShell(
Window* _pParent,
const ::com::sun::star::uno::Reference< ::com::sun::star::ui::dialogs::XWizardController >& i_rController,
const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< sal_Int16 > >& i_rPaths
);
virtual ~WizardShell();
// Dialog overridables
virtual short Execute();
// OWizardMachine overridables
virtual TabPage* createPage( WizardState i_nState );
virtual void enterState( WizardState i_nState );
virtual sal_Bool leaveState( WizardState i_nState );
virtual String getStateDisplayName( WizardState i_nState ) const;
virtual bool canAdvance() const;
virtual sal_Bool onFinish();
virtual IWizardPageController*
getPageController( TabPage* _pCurrentPage ) const;
static sal_Int16 convertCommitReasonToTravelType( const CommitPageReason i_eReason );
// operations
sal_Bool advanceTo( const sal_Int16 i_nPageId )
{
return skipUntil( impl_pageIdToState( i_nPageId ) );
}
sal_Bool goBackTo( const sal_Int16 i_nPageId )
{
return skipBackwardUntil( impl_pageIdToState( i_nPageId ) );
}
sal_Bool travelNext() { return WizardShell_Base::travelNext(); }
sal_Bool travelPrevious() { return WizardShell_Base::travelPrevious(); }
void activatePath( const sal_Int16 i_nPathID, const sal_Bool i_bFinal )
{
WizardShell_Base::activatePath( PathId( i_nPathID ), i_bFinal );
}
::com::sun::star::uno::Reference< ::com::sun::star::ui::dialogs::XWizardPage >
getCurrentWizardPage() const;
sal_Int16 getCurrentPage() const
{
return impl_stateToPageId( getCurrentState() );
}
void enablePage( const sal_Int16 i_PageID, const sal_Bool i_Enable );
bool knowsPage( const sal_Int16 i_nPageID ) const
{
return knowsState( impl_pageIdToState( i_nPageID ) );
}
private:
sal_Int16 impl_stateToPageId( const WizardTypes::WizardState i_nState ) const
{
return static_cast< sal_Int16 >( i_nState + m_nFirstPageID );
}
WizardState impl_pageIdToState( const sal_Int16 i_nPageId ) const
{
return static_cast< WizardState >( i_nPageId - m_nFirstPageID );
}
PWizardPageController impl_getController( TabPage* i_pPage ) const;
// prevent outside access to some base class members
using WizardShell_Base::skip;
using WizardShell_Base::skipUntil;
using WizardShell_Base::skipBackwardUntil;
using WizardShell_Base::getCurrentState;
using WizardShell_Base::activatePath;
private:
typedef ::std::map< TabPage*, PWizardPageController > Page2ControllerMap;
const ::com::sun::star::uno::Reference< ::com::sun::star::ui::dialogs::XWizardController > m_xController;
const sal_Int16 m_nFirstPageID;
Page2ControllerMap m_aPageControllers;
};
//......................................................................................................................
} } // namespace svt::uno
//......................................................................................................................
#endif // SVT_UNO_WIZARD_SHELL
| 40.482014 | 120 | 0.54896 | Grosskopf |
c9bac0dfcabc1430d6ca3e5a4f613c339bdb21de | 4,402 | hpp | C++ | include/IteratorRecognition/Exchange/JSONTransfer.hpp | robcasloz/IteratorRecognition | fa1a1e67c36cde3639ac40528228ae85e54e3b13 | [
"MIT"
] | null | null | null | include/IteratorRecognition/Exchange/JSONTransfer.hpp | robcasloz/IteratorRecognition | fa1a1e67c36cde3639ac40528228ae85e54e3b13 | [
"MIT"
] | 6 | 2019-05-29T21:11:03.000Z | 2021-07-01T10:47:02.000Z | include/IteratorRecognition/Exchange/JSONTransfer.hpp | robcasloz/IteratorRecognition | fa1a1e67c36cde3639ac40528228ae85e54e3b13 | [
"MIT"
] | 1 | 2019-05-13T11:55:39.000Z | 2019-05-13T11:55:39.000Z | //
//
//
#pragma once
#include "IteratorRecognition/Config.hpp"
#include "IteratorRecognition/Support/Utils/Extras.hpp"
#include "IteratorRecognition/Support/Utils/DebugInfo.hpp"
#include "IteratorRecognition/Support/CondensationGraph.hpp"
#include "IteratorRecognition/Analysis/GraphUpdater.hpp"
#include "IteratorRecognition/Analysis/IteratorRecognition.hpp"
#include "IteratorRecognition/Analysis/Passes/PayloadDependenceGraphPass.hpp"
#include "llvm/Support/JSON.h"
// using json::Value
// using json::Object
// using json::Array
#include "llvm/ADT/StringRef.h"
// using llvm::StringRef
#include <llvm/ADT/GraphTraits.h>
// using llvm::GraphTraits
#include "llvm/Support/raw_ostream.h"
// using llvm::raw_string_ostream
#include "boost/iterator/indirect_iterator.hpp"
// using boost::make_indirect_iterator
#include "boost/range/adaptors.hpp"
// using boost::adaptors::filtered
#include "boost/range/algorithm.hpp"
// using boost::range::transform
#include <string>
// using std::string
#include <algorithm>
// using std::transform
#include <iterator>
// using std::back_inserter
// using std::make_move_iterator
#include <utility>
// using std::move
#include <type_traits>
// using std::enable_if
// namespace aliases
namespace ba = boost::adaptors;
namespace br = boost::range;
//
namespace llvm {
class Instruction;
class Loop;
} // namespace llvm
namespace iteratorrecognition {
namespace json {
template <typename GraphT, typename GT = llvm::GraphTraits<GraphT *>>
std::enable_if_t<has_unit_t<typename GT::NodeRef>::value, llvm::json::Value>
toJSON(const CondensationGraphNode<GraphT *> &CGN) {
llvm::json::Object root;
llvm::json::Object mapping;
std::string outs;
llvm::raw_string_ostream ss(outs);
llvm::json::Array condensationsArray;
br::transform(CGN | ba::filtered(is_not_null_unit),
std::back_inserter(condensationsArray), [&](const auto &e) {
outs.clear();
ss << *e->unit();
return ss.str();
});
mapping["condensation"] = std::move(condensationsArray);
root = std::move(mapping);
return std::move(root);
}
template <typename GraphT, typename GT = llvm::GraphTraits<GraphT *>>
std::enable_if_t<!has_unit_t<typename GT::NodeRef>::value, llvm::json::Value>
toJSON(const CondensationGraphNode<GraphT *> &CGN) {
llvm::json::Object root;
llvm::json::Object mapping;
std::string outs;
llvm::raw_string_ostream ss(outs);
llvm::json::Array condensationsArray;
br::transform(CGN, std::back_inserter(condensationsArray),
[&](const auto &e) { return toJSON(*e); });
mapping["condensation"] = std::move(condensationsArray);
root = std::move(mapping);
return std::move(root);
}
template <typename GraphT>
llvm::json::Value toJSON(const CondensationGraph<GraphT *> &G) {
llvm::json::Object root;
llvm::json::Array condensations;
for (const auto &cn : G) {
condensations.push_back(toJSON(*cn));
}
root["condensations"] = std::move(condensations);
return std::move(root);
}
llvm::json::Value toJSON(const llvm::Instruction &Instruction);
llvm::json::Value toJSON(const llvm::Loop &CurLoop);
llvm::json::Value toJSON(const dbg::LoopDebugInfoT &Info);
llvm::json::Value
toJSON(const IteratorRecognitionInfo::CondensationToLoopsMapT &Map);
llvm::json::Value toJSON(const UpdateAction &UA);
llvm::json::Value toJSON(const StaticCommutativityProperty &SCP);
llvm::json::Value toJSON(const StaticCommutativityResult &SCR);
} // namespace json
} // namespace iteratorrecognition
namespace iteratorrecognition {
template <typename PreambleT, typename IteratorT>
llvm::json::Value
ConvertToJSON(llvm::StringRef PreambleText, llvm::StringRef SequenceText,
const PreambleT &Preamble, IteratorT Begin, IteratorT End) {
llvm::json::Object mapping;
llvm::json::Array updates;
mapping[PreambleText] = json::toJSON(Preamble);
// TODO maybe detect if the pointee is a pointer itself with SFINAE in order
// to decide on the use of indirect_iterator or not
std::transform(boost::make_indirect_iterator(Begin),
boost::make_indirect_iterator(End),
std::back_inserter(updates),
[](const auto &e) { return json::toJSON(e); });
mapping[SequenceText] = std::move(updates);
return std::move(mapping);
}
} // namespace iteratorrecognition
| 25.593023 | 78 | 0.714448 | robcasloz |
c9bdd965321b0549b6b969d1466940b5a5fc7718 | 10,516 | cpp | C++ | WOF2/src/WOF/match/Match_Script.cpp | jadnohra/World-Of-Football | fc4c9dd23e0b2d8381ae8f62b1c387af7f28fcfc | [
"MIT"
] | 3 | 2018-12-02T14:09:22.000Z | 2021-11-22T07:14:05.000Z | WOF2/src/WOF/match/Match_Script.cpp | jadnohra/World-Of-Football | fc4c9dd23e0b2d8381ae8f62b1c387af7f28fcfc | [
"MIT"
] | 1 | 2018-12-03T22:54:38.000Z | 2018-12-03T22:54:38.000Z | WOF2/src/WOF/match/Match_Script.cpp | jadnohra/World-Of-Football | fc4c9dd23e0b2d8381ae8f62b1c387af7f28fcfc | [
"MIT"
] | 2 | 2020-09-22T21:04:14.000Z | 2021-05-24T09:43:28.000Z | #include "Match.h"
#include "inc/Entities.h"
DECLARE_INSTANCE_TYPE_NAME(WOF::match::Match, CMatch);
namespace WOF { namespace match {
const TCHAR* Match::ScriptClassName = L"CMatch";
void Match::declareInVM(SquirrelVM& target) {
SqPlus::SQClassDef<Match>(ScriptClassName).
enumInt(Scene_Up, L"Scene_Up").
enumInt(Scene_Right, L"Scene_Right").
enumInt(Scene_Forward, L"Scene_Fwd").
enumInt(Scene2D_Right, L"Scene2D_Right").
enumInt(Scene2D_Forward, L"Scene2D_Fwd").
func(&Match::script_getGame, L"getGame").
func(&Match::script_getScriptMatch, L"getScriptMatch").
func(&Match::script_resolveScriptRelativePath, L"resolveScriptRelativePath").
func(&Match::script_executePlugin, L"executePlugin").
func(&Match::script_SceneAxis, L"SceneAxis").
func(&Match::script_SceneUpAxis, L"SceneUpAxis").
func(&Match::script_SceneRightAxis, L"SceneRightAxis").
func(&Match::script_SceneFwdAxis, L"SceneFwdAxis").
func(&Match::script_SceneDownAxis, L"SceneDownAxis").
func(&Match::script_SceneLeftAxis, L"SceneLeftAxis").
func(&Match::script_SceneBackAxis, L"SceneBackAxis").
func(&Match::script_getCoordSys, L"getCoordSys").
func(&Match::script_conv, L"conv").
func(&Match::script_invConv, L"invConv").
func(&Match::script_toScene2D, L"toScene2D").
func(&Match::script_toScene3D, L"toScene3D").
func(&Match::script_getTweakEnableAI, L"getTweakEnableAI").
func(&Match::script_setMagicRequestingBallFootballer, L"setMagicRequestingBallFootballer").
func(&Match::script_getPitchWidth, L"getPitchWidth").
func(&Match::script_getPitchHalfWidth, L"getPitchHalfWidth").
func(&Match::script_getPitchLength, L"getPitchLength").
func(&Match::script_getPitchHalfLength, L"getPitchHalfLength").
func(&Match::script_setAutoSwitch, L"setAutoSwitch").
func(&Match::script_setSwitchVeryDynamic, L"setSwitchVeryDynamic").
func(&Match::script_showScanner, L"showScanner").
func(&Match::script_getTime, L"getTime").
func(&Match::script_getFrameInterval, L"getFrameInterval").
func(&Match::script_getFrameTickLength, L"getFrameTickLength").
func(&Match::script_getBall, L"getBall").
func(&Match::script_getTeam, L"getTeam").
func(&Match::script_getFootballer, L"getFootballer").
func(&Match::scrit_genBallCommandID, L"genBallCommandID").
func(&Match::script_setLight, L"setLight").
func(&Match::script_setAmbient, L"setAmbient").
func(&Match::script_setShadowing, L"setShadowing").
func(&Match::script_setShadowDir, L"setShadowDir").
func(&Match::script_getViewTransform, L"getViewTransform").
func(&Match::script_freeCam, L"freeCam").
func(&Match::script_manipulateCam, L"manipulateCam").
func(&Match::script_queueRenderSphere, L"queueRenderSphere").
func(&Match::script_getBallShotEstimator, L"getBallShotEstimator").
func(&Match::script_isEnabledShadowing, L"isEnabledShadowing").
func(&Match::script_renderSpatialManager, L"renderSpatialManager").
func(&Match::script_renderBallShotEstimator, L"renderBallShotEstimator").
func(&Match::script_estimateBallStateAtAAPlane, L"estimateBallStateAtAAPlane").
func(&Match::script_estimateBallStateAtPlane, L"estimateBallStateAtPlane").
func(&Match::script_isApproximateBallState, L"isApproximateBallState").
func(&Match::script_tuneApproximatedBallEstimate, L"tuneApproximatedBallEstimate").
func(&Match::script_getSpatialBallState, L"getSpatialBallState").
func(&Match::script_getSpatialPitchModel, L"getSpatialPitchModel").
func(&Match::script_findFootballerFreeSpace, L"findFootballerFreeSpace").
func(&Match::script_iterNextRegionFootballer, L"iterNextRegionFootballer");
}
ScriptObject Match::script_getScriptMatch() {
return mScriptMatch;
}
const TCHAR* Match::script_resolveScriptRelativePath(const TCHAR* path) {
static BufferString scriptPathHolder;
scriptPathHolder.assign(getScriptPath());
PathResolver::appendPath(scriptPathHolder, path, true);
return scriptPathHolder.c_tstr();
}
int Match::script_executePlugin(const TCHAR* plugin, const TCHAR* workingDir, const TCHAR* arg) {
BufferString pluginDirPath(getPluginPath());
BufferString pluginPath(pluginDirPath);
PathResolver::appendPath(pluginPath, plugin, true);
mLog->log(LOG_INFO, true, true, L"executing: %s", pluginPath.c_tstr());
if (workingDir)
mLog->log(LOG_INFO, true, true, L"workingDir: %s", workingDir);
int exitCode = -1;
if (!Win::executeProcess(pluginPath.c_tstr(), workingDir, arg, exitCode)) {
mLog->log(LOG_ERROR, true, true, L"Execution Failed");
return exitCode;
}
return exitCode;
}
bool Match::createScriptMatch() {
{
ScriptFunctionCall<ScriptObject> fct(mScriptEngine, L"createMatch", mStartScript.c_tstr());
mScriptMatch = (fct)(mScriptEngine->toScriptArg(), scriptArg(this));
if (!mScriptMatch.IsInstance()) {
mLoadErrorFlag = true;
mLog->log(LOG_ERROR, true, true, L"Failed to Create Script-Side Match");
return false;
}
}
return true;
}
bool Match::scriptedLoad() {
ScriptFunctionCall<bool> fct(mScriptEngine, mScriptMatch, L"load");
return (fct)();
}
void Match::scriptedPreFrameMove(const Time& t, const Time& dt) {
ScriptFunctionCall<void> fct(mScriptEngine, mScriptMatch, L"preFrameMove");
(fct)(t, dt);
}
void Match::scriptedPostFrameMove(const Time& t, const Time& dt) {
ScriptFunctionCall<void> fct(mScriptEngine, mScriptMatch, L"postFrameMove");
(fct)(t, dt);
}
void Match::scriptedPreRender() {
ScriptFunctionCall<void> fct(mScriptEngine, mScriptMatch, L"preRender");
(fct)();
}
void Match::scriptedPostRender() {
ScriptFunctionCall<void> fct(mScriptEngine, mScriptMatch, L"postRender");
(fct)();
}
ScriptObject Match::script_getFootballer(int teamIndex, int number) {
if (teamIndex < 0 || teamIndex >= 2)
return ScriptObject();
Team& team = getTeam((TeamEnum) teamIndex);
SoftPtr<Footballer> footballer;
if (team.getFootballer((FootballerNumber) number, footballer.ptrRef())) {
return (footballer->getScriptObject());
}
return ScriptObject();
}
void Match::script_setLight(RenderLight* pLight, int index) {
setLight(pLight, index);
}
void Match::script_setAmbient(RenderColor* pColor) {
setAmbient(pColor);
}
void Match::script_setShadowing(bool enable, RenderColor* pColor, bool alphaBlend, bool stencilTest) {
setShadowing(enable, pColor, alphaBlend, stencilTest);
}
void Match::script_setShadowDir(CtVector3& dir) {
Plane plane;
plane.init(Point(0.0f, 1.0f, 0.0f), Vector(0.0f, 1.0f, 0.0f), true);
mRenderer->setupShadowingPlanar(Vector3(dir.x, dir.y, dir.z), plane);
}
SceneTransform* Match::script_getViewTransform() {
return &(getActiveCamera().mTransformWorld);
}
void Match::script_manipulateCam(bool enable) {
mTweakEnableManipulateCam = enable;
}
void Match::script_freeCam(bool enable) {
if (enable) {
SceneCamera& cam = getActiveCamera();
cam.cancelTrack();
} else {
SceneCamera& cam = getActiveCamera();
float z = 0.0f;
cam.track(&(mEntityManager.getBall()), &z);
}
}
bool Match::script_estimateBallStateAtAAPlane(CtVector3& planePos, CtVector3& planeNormal, BallSimulation::TrajSample& result, bool allowPartialSimul) {
SoftPtr<BallSimulation> simul;
if (allowPartialSimul) {
simul = &getFootballerBallInterceptManager().getSimul();
if (simul->getSimulState() == BallSimulation::Simul_None)
simul.destroy();
} else {
simul = getFootballerBallInterceptManager().getValidSimul();
}
if (simul.isValid()) {
AAPlane plane;
plane.init(planePos, planeNormal, true);
if (simul->estimateStateAtPlane(plane, true, result, false, NULL, false)) {
return true;
} else {
return false;
}
}
return false;
}
bool Match::script_estimateBallStateAtPlane(CtVector3& planePos, CtVector3& planeNormal, BallSimulation::TrajSample& result, bool allowPartialSimul, bool allowApproximateSimul, bool fallbackCtBallVel, ScriptBool& isFallback) {
SoftPtr<BallSimulation> simul;
isFallback.value() = false;
if (allowPartialSimul) {
simul = &getFootballerBallInterceptManager().getSimul();
if (simul->getSimulState() == BallSimulation::Simul_None)
simul.destroy();
} else {
simul = getFootballerBallInterceptManager().getValidSimul();
}
if (!allowApproximateSimul && simul.isValid()) {
if (simul->isSimulApproximate())
simul.destroy();
}
if (simul.isValid()) {
Plane plane;
plane.init(planePos, planeNormal, true);
if (simul->estimateStateAtPlane(plane, true, result, false, NULL, false)) {
return true;
} else {
return false;
}
} else {
if (fallbackCtBallVel) {
isFallback.value() = true;
Ball& ball = getBall();
const Vector3& ballPos = ball.getPos();
Vector3 ballVel = (ball.getVel() != NULL) ? dref(ball.getVel()) : Vector3::kZero;
if (ball.isOnPitch())
ballVel.el[Scene_Up] = 0.0f;
if (ballVel.isZero()) {
return false;
} else {
float u;
if (intersectPlane(planePos, planeNormal, ballPos, ballVel, u, &result.pos)) {
result.vel = ballVel;
result.time = sqrtf(distanceSq(ballPos, result.pos) / ballVel.magSquared());
result.time += getClock().getTime();
result.isOnPitch = false;
return true;
} else {
return false;
}
}
}
}
return false;
}
bool Match::script_isApproximateBallState() {
return getFootballerBallInterceptManager().getSimul().isSimulApproximate();
}
bool Match::script_tuneApproximatedBallEstimate(BallSimulation::TrajSample& sample, BallSimulation::TrajSample& tunedSample) {
tunedSample = sample;
return getFootballerBallInterceptManager().getSimul().tuneApproximatedEstimate(getBall(), tunedSample);
}
ScriptedFootballer* Match::script_iterNextRegionFootballer(PitchRegionShape* pRegion, int teamFilter, ScriptInt& startIndex) {
FootballerIndex inOut = startIndex.value();
Footballer* pRet = mSpatialMatchState.iterNextRegionFootballer(pRegion, (TeamEnum) teamFilter, inOut);
startIndex.value() = inOut;
return scriptArg((ScriptedFootballer*) pRet);
}
void Match::script_queueRenderSphere(CtVector3& pos, float radius, RenderColor* pColor) {
Sphere sphere(pos, radius);
mRenderer->queueVol(VolumeRef(sphere), NULL, pColor);
}
} } | 28.042667 | 227 | 0.715766 | jadnohra |
c9bdf38f640c35fba71055c1b023061cfc1190b5 | 2,117 | cc | C++ | nipXray/src/NXHit.cc | maxwell-herrmann/geant4-simple-examples | 0052d40fdc05baef05b4a6873c03d0d54885ad40 | [
"BSD-2-Clause"
] | 9 | 2015-04-27T11:54:19.000Z | 2022-01-30T23:42:00.000Z | nipXray/src/NXHit.cc | maxwell-herrmann/geant4-simple-examples | 0052d40fdc05baef05b4a6873c03d0d54885ad40 | [
"BSD-2-Clause"
] | null | null | null | nipXray/src/NXHit.cc | maxwell-herrmann/geant4-simple-examples | 0052d40fdc05baef05b4a6873c03d0d54885ad40 | [
"BSD-2-Clause"
] | 3 | 2019-12-18T21:11:57.000Z | 2020-05-28T17:30:03.000Z | //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
#include "NXHit.hh"
#include "G4UnitsTable.hh"
#include "G4VVisManager.hh"
#include "G4Circle.hh"
#include "G4Colour.hh"
#include "G4VisAttributes.hh"
G4Allocator<NXHit> NXHitAllocator;
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
NXHit::NXHit() {}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
NXHit::~NXHit() {}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
NXHit::NXHit(const NXHit& right) :
G4VHit()
{
trackID = right.trackID;
chamberNb = right.chamberNb;
edep = right.edep;
pos = right.pos;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
const NXHit& NXHit::operator=(const NXHit& right)
{
trackID = right.trackID;
chamberNb = right.chamberNb;
edep = right.edep;
pos = right.pos;
return *this;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
G4int NXHit::operator==(const NXHit& right) const
{
return (this==&right) ? 1 : 0;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void NXHit::Draw()
{
G4VVisManager* pVVisManager = G4VVisManager::GetConcreteInstance();
if(pVVisManager)
{
G4Circle circle(pos);
circle.SetScreenSize(2.);
circle.SetFillStyle(G4Circle::filled);
G4Colour colour(1.,0.,0.);
G4VisAttributes attribs(colour);
circle.SetVisAttributes(attribs);
pVVisManager->Draw(circle);
}
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void NXHit::Print()
{
G4cout << " trackID: " << trackID << " chamberNb: " << chamberNb
<< " energy deposit: " << G4BestUnit(edep,"Energy")
<< " position: " << G4BestUnit(pos,"Length") << G4endl;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
| 27.141026 | 80 | 0.58479 | maxwell-herrmann |
c9bdf5d0a28d21aa4c108a76ad77f4635673acb2 | 52,974 | cc | C++ | src/meshes/hermite_element_quad_mesh.template.cc | pkeuchel/oomph-lib | 37c1c61425d6b9ea1c2ddceef63a68a228af6fa4 | [
"RSA-MD"
] | 4 | 2020-11-16T12:25:09.000Z | 2021-06-29T08:53:25.000Z | src/meshes/hermite_element_quad_mesh.template.cc | pkeuchel/oomph-lib | 37c1c61425d6b9ea1c2ddceef63a68a228af6fa4 | [
"RSA-MD"
] | 2 | 2020-05-05T22:41:37.000Z | 2020-05-10T14:14:17.000Z | src/meshes/hermite_element_quad_mesh.template.cc | pkeuchel/oomph-lib | 37c1c61425d6b9ea1c2ddceef63a68a228af6fa4 | [
"RSA-MD"
] | 3 | 2021-01-31T14:09:20.000Z | 2021-06-07T07:20:51.000Z | // LIC// ====================================================================
// LIC// This file forms part of oomph-lib, the object-oriented,
// LIC// multi-physics finite-element library, available
// LIC// at http://www.oomph-lib.org.
// LIC//
// LIC// Copyright (C) 2006-2021 Matthias Heil and Andrew Hazel
// LIC//
// LIC// This library is free software; you can redistribute it and/or
// LIC// modify it under the terms of the GNU Lesser General Public
// LIC// License as published by the Free Software Foundation; either
// LIC// version 2.1 of the License, or (at your option) any later version.
// LIC//
// LIC// This library is distributed in the hope that it will be useful,
// LIC// but WITHOUT ANY WARRANTY; without even the implied warranty of
// LIC// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// LIC// Lesser General Public License for more details.
// LIC//
// LIC// You should have received a copy of the GNU Lesser General Public
// LIC// License along with this library; if not, write to the Free Software
// LIC// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
// LIC// 02110-1301 USA.
// LIC//
// LIC// The authors may be contacted at oomph-lib@maths.man.ac.uk.
// LIC//
// LIC//====================================================================
// the mesh assembly functions for the hermite element quad mesh
#ifndef OOMPH_HERMITE_QUAD_MESH_TEMPLATE_CC
#define OOMPH_HERMITE_QUAD_MESH_TEMPLATE_CC
// Config header generated by autoconfig
#ifdef HAVE_CONFIG_H
#include <oomph-lib-config.h>
#endif
// oomph-lib includes
#include "hermite_element_quad_mesh.template.h"
namespace oomph
{
//=============================================================================
/// sets the generalised position of the node (i.e. - x_i, dx_i/ds_0,
/// dx_i/ds_1 & d2x_i/ds_0ds_1 for i = 1,2). Takes the x,y coordinates of the
/// node from which its position can be determined.
//=============================================================================
template<class ELEMENT>
void HermiteQuadMesh<ELEMENT>::set_position_of_node(
const unsigned& node_num_x, const unsigned& node_num_y, Node* node_pt)
{
// get the generalised macro element position of the node
DenseMatrix<double> m_gen(4, 2);
generalised_macro_element_position_of_node(node_num_x, node_num_y, m_gen);
// copy the macro element coordinates
Vector<double> node_macro_position(2);
node_macro_position[0] = m_gen(0, 0);
node_macro_position[1] = m_gen(0, 1);
// get the global position of the nodes
Vector<double> x_node(2);
Domain_pt->macro_element_pt(0)->macro_map(node_macro_position, x_node);
// get the jacobian of the mapping from macro to eulerian coordinates
DenseMatrix<double> jacobian_MX(2, 2);
Domain_pt->macro_element_pt(0)->assemble_macro_to_eulerian_jacobian(
node_macro_position, jacobian_MX);
// get the jacobian2 of the mapping from macro to eulerian coordinates
DenseMatrix<double> jacobian2_MX(3, 2);
Domain_pt->macro_element_pt(0)->assemble_macro_to_eulerian_jacobian2(
node_macro_position, jacobian2_MX);
// set x_0
node_pt->x_gen(0, 0) = x_node[0];
// set x_1
node_pt->x_gen(0, 1) = x_node[1];
// set dxi/dsj for i = 0,1 and j = 0,1
// computation : dxi/dsj = dm0/dsj*dxi/dm0 + dm1/dsj*dxi/dm1
for (unsigned i = 0; i < 2; i++)
{
for (unsigned j = 0; j < 2; j++)
{
node_pt->x_gen(j + 1, i) = m_gen(j + 1, 0) * jacobian_MX(0, i) +
m_gen(j + 1, 1) * jacobian_MX(1, i);
}
}
// set d2xi/ds0ds1 for i = 0,1
// d2xi/ds0ds1 = d2m0/ds0ds1*dxi/dm0
// + d2m1/ds0ds1*dxi/dm1
// + (dm0/ds1*d2xi/dm0^2 + dm1/ds1*d2xi/dm0dm1)*dm0/ds0
// + (dm0/ds1*d2xi/dm0dm1 + dm1/ds1*d2xi/dm1^2)*dm1/ds0
for (unsigned i = 0; i < 2; i++)
{
node_pt->x_gen(3, i) =
m_gen(3, 0) * jacobian_MX(0, i) + m_gen(3, 1) * jacobian_MX(1, i) +
m_gen(1, 0) * (m_gen(2, 0) * jacobian2_MX(0, i) +
m_gen(2, 1) * jacobian2_MX(2, i)) +
m_gen(1, 1) *
(m_gen(2, 0) * jacobian2_MX(2, i) + m_gen(2, 1) * jacobian2_MX(1, i));
}
}
//=============================================================================
/// sets the generalised position of the node (i.e. - x_i, dx_i/ds_0,
/// dx_i/ds_1 & d2x_i/ds_0ds_1 for i = 1,2). Takes the x,y coordinates of the
/// node from which its position can be determined. Also sets coordinates
/// on boundary vector for the node to be the generalised position of the node
/// in macro element coordinates
//=============================================================================
template<class ELEMENT>
void HermiteQuadMesh<ELEMENT>::set_position_of_boundary_node(
const unsigned& node_num_x,
const unsigned& node_num_y,
BoundaryNode<Node>* node_pt)
{
// get the generalised macro element position of the node
DenseMatrix<double> m_gen(4, 2, 0.0);
generalised_macro_element_position_of_node(node_num_x, node_num_y, m_gen);
// copy the macro element coordinates
Vector<double> node_macro_position(2);
node_macro_position[0] = m_gen(0, 0);
node_macro_position[1] = m_gen(0, 1);
// get the global position of the nodes
Vector<double> x_node(2);
Domain_pt->macro_element_pt(0)->macro_map(node_macro_position, x_node);
// get the jacobian of the mapping from macro to eulerian coordinates
DenseMatrix<double> jacobian_MX(2, 2);
Domain_pt->macro_element_pt(0)->assemble_macro_to_eulerian_jacobian(
node_macro_position, jacobian_MX);
// get the jacobian2 of the mapping from macro to eulerian coordinates
DenseMatrix<double> jacobian2_MX(3, 2);
Domain_pt->macro_element_pt(0)->assemble_macro_to_eulerian_jacobian2(
node_macro_position, jacobian2_MX);
// set x_0
node_pt->x_gen(0, 0) = x_node[0];
// set x_1
node_pt->x_gen(0, 1) = x_node[1];
// set dxi/dsj for i = 0,1 and j = 0,1
// computation : dxi/dsj = dm0/dsj*dxi/dm0 + dm1/dsj*dxi/dm1
for (unsigned i = 0; i < 2; i++)
{
for (unsigned j = 0; j < 2; j++)
{
node_pt->x_gen(j + 1, i) = m_gen(j + 1, 0) * jacobian_MX(0, i) +
m_gen(j + 1, 1) * jacobian_MX(1, i);
}
}
// set d2xi/ds0ds1 for i = 0,1
// d2xi/ds0ds1 = d2m0/ds0ds1*dxi/dm0
// + d2m1/ds0ds1*dxi/dm1
// + (dm0/ds1*d2xi/dm0^2 + dm1/ds1*d2xi/dm0dm1)*dm0/ds0
// + (dm0/ds1*d2xi/dm0dm1 + dm1/ds1*d2xi/dm1^2)*dm1/ds0
for (unsigned i = 0; i < 2; i++)
{
node_pt->x_gen(3, i) =
m_gen(3, 0) * jacobian_MX(0, i) + m_gen(3, 1) * jacobian_MX(1, i) +
m_gen(1, 0) * (m_gen(2, 0) * jacobian2_MX(0, i) +
m_gen(2, 1) * jacobian2_MX(2, i)) +
m_gen(1, 1) *
(m_gen(2, 0) * jacobian2_MX(2, i) + m_gen(2, 1) * jacobian2_MX(1, i));
}
// pass generalised macro element position to vector to pass to boundary
// node
for (unsigned b = 0; b < 4; b++)
{
if (node_pt->is_on_boundary(b))
{
Vector<double> boundary_macro_position(2, 0);
boundary_macro_position[0] = m_gen(0, b % 2);
boundary_macro_position[1] = m_gen(1 + b % 2, b % 2);
node_pt->set_coordinates_on_boundary(b, boundary_macro_position);
}
}
}
//=============================================================================
/// computes the generalised position of the node at position
/// (node_num_x, node_num_y) in the macro element coordinate scheme.
/// index 0 of m_gen : 0 - m_i
/// 1 - dm_i/ds_0
/// 2 - dm_i/ds_1
/// 3 - d2m_i/ds_0ds_1 (where i is index 1 of m_gen)
//=============================================================================
template<class ELEMENT>
void HermiteQuadMesh<ELEMENT>::generalised_macro_element_position_of_node(
const unsigned& node_num_x,
const unsigned& node_num_y,
DenseMatrix<double>& m_gen)
{
// obtain position of node
Vector<double> s_macro_N(2);
macro_coordinate_position(node_num_x, node_num_y, s_macro_N);
// set position of node in macro element coordinates
m_gen(0, 0) = s_macro_N[0];
m_gen(0, 1) = s_macro_N[1];
// if on left hand edge
if (node_num_x == 0)
{
// first dm0ds0 and dm1ds0
// get position of right node
Vector<double> s_macro_R(2);
macro_coordinate_position(node_num_x + 1, node_num_y, s_macro_R);
// compute dm0ds0
m_gen(1, 0) = 0.5 * (s_macro_R[0] - s_macro_N[0]);
// compute dm1ds0
m_gen(1, 1) = 0.5 * (s_macro_R[1] - s_macro_N[1]);
// now d2m0/ds0ds1 and d2m1/ds0ds1
// if lower left hand corner
if (node_num_y == 0)
{
// get position of upper right node
Vector<double> s_macro_UR(2);
macro_coordinate_position(node_num_x + 1, node_num_y + 1, s_macro_UR);
// get position of upper node
Vector<double> s_macro_U(2);
macro_coordinate_position(node_num_x, node_num_y + 1, s_macro_U);
// compute d2m0/ds0ds1
m_gen(3, 0) =
0.5 * (0.5 * (s_macro_UR[0] - s_macro_U[0]) - m_gen(1, 0));
// compute d2m1/ds0ds1
m_gen(3, 1) =
0.5 * (0.5 * (s_macro_UR[1] - s_macro_U[1]) - m_gen(1, 1));
}
// else if upper left hand corner
else if (node_num_y == Nelement[1])
{
// get position of lower right node
Vector<double> s_macro_DR(2);
macro_coordinate_position(node_num_x + 1, node_num_y - 1, s_macro_DR);
// get position of lower node
Vector<double> s_macro_D(2);
macro_coordinate_position(node_num_x, node_num_y - 1, s_macro_D);
// compute d2m0/ds0ds1
m_gen(3, 0) =
0.5 * (m_gen(1, 0) - 0.5 * (s_macro_DR[0] - s_macro_D[0]));
// compute d2m0/ds0ds1
m_gen(3, 1) =
0.5 * (m_gen(1, 1) - 0.5 * (s_macro_DR[1] - s_macro_D[1]));
}
// else left hand edge (not corner)
else
{
// get position of lower right node
Vector<double> s_macro_DR(2);
macro_coordinate_position(node_num_x + 1, node_num_y - 1, s_macro_DR);
// get position of lower node
Vector<double> s_macro_D(2);
macro_coordinate_position(node_num_x, node_num_y - 1, s_macro_D);
// get position of upper right node
Vector<double> s_macro_UR(2);
macro_coordinate_position(node_num_x + 1, node_num_y + 1, s_macro_UR);
// get position of upper node
Vector<double> s_macro_U(2);
macro_coordinate_position(node_num_x, node_num_y + 1, s_macro_U);
// compute d2m0/ds0ds1
m_gen(3, 0) =
0.5 * std::min(m_gen(1, 0) - 0.5 * (s_macro_DR[0] - s_macro_D[0]),
0.5 * (s_macro_UR[0] - s_macro_U[0]) - m_gen(1, 0));
// compute d2m1/ds0ds1
m_gen(3, 1) =
0.5 * std::min(m_gen(1, 1) - 0.5 * (s_macro_DR[1] - s_macro_D[1]),
0.5 * (s_macro_UR[1] - s_macro_U[1]) - m_gen(1, 1));
}
}
// if on right hand edge
else if (node_num_x == Nelement[0])
{
// first dm0ds0 and dm1ds0
// get position of left node
Vector<double> s_macro_L(2);
macro_coordinate_position(node_num_x - 1, node_num_y, s_macro_L);
// compute dm0ds0
m_gen(1, 0) = 0.5 * (s_macro_N[0] - s_macro_L[0]);
// compute dm1ds0
m_gen(1, 1) = 0.5 * (s_macro_N[1] - s_macro_L[1]);
// now d2m0/ds0ds1 and d2m1/ds0ds1
// if lower right hand corner
if (node_num_y == 0)
{
// get position of upper left node
Vector<double> s_macro_UL(2);
macro_coordinate_position(node_num_x - 1, node_num_y + 1, s_macro_UL);
// get position of upper node
Vector<double> s_macro_U(2);
macro_coordinate_position(node_num_x, node_num_y + 1, s_macro_U);
// compute d2m0/ds0ds1
m_gen(3, 0) =
0.5 * (0.5 * (s_macro_U[0] - s_macro_UL[0]) - m_gen(1, 0));
// compute d2m1/ds0ds1
m_gen(3, 1) =
0.5 * (0.5 * (s_macro_U[1] - s_macro_UL[1]) - m_gen(1, 1));
}
// else if upper right hand corner
else if (node_num_y == Nelement[1])
{
// get position of lower left node
Vector<double> s_macro_DL(2);
macro_coordinate_position(node_num_x - 1, node_num_y - 1, s_macro_DL);
// get position of lower node
Vector<double> s_macro_D(2);
macro_coordinate_position(node_num_x, node_num_y - 1, s_macro_D);
// compute d2m0/ds0ds1
m_gen(3, 0) =
0.5 * (m_gen(1, 0) - 0.5 * (s_macro_D[0] - s_macro_DL[0]));
// compute d2m0/ds0ds1
m_gen(3, 1) =
0.5 * (m_gen(1, 1) - 0.5 * (s_macro_D[1] - s_macro_DL[1]));
}
// else left hand edge (not corner)
else
{
// get position of lower left node
Vector<double> s_macro_DL(2);
macro_coordinate_position(node_num_x - 1, node_num_y - 1, s_macro_DL);
// get position of lower node
Vector<double> s_macro_D(2);
macro_coordinate_position(node_num_x, node_num_y - 1, s_macro_D);
// get position of upper left node
Vector<double> s_macro_UL(2);
macro_coordinate_position(node_num_x - 1, node_num_y + 1, s_macro_UL);
// get position of upper node
Vector<double> s_macro_U(2);
macro_coordinate_position(node_num_x, node_num_y + 1, s_macro_U);
// compute d2m0/ds0ds1
m_gen(3, 0) =
0.5 * std::min(m_gen(1, 0) - 0.5 * (s_macro_D[0] - s_macro_DL[0]),
0.5 * (s_macro_U[0] - s_macro_UL[0]) - m_gen(1, 0));
// compute d2m0/ds0ds1
m_gen(3, 1) =
0.5 * std::min(m_gen(1, 1) - 0.5 * (s_macro_D[1] - s_macro_DL[1]),
0.5 * (s_macro_U[1] - s_macro_UL[1]) - m_gen(1, 1));
}
}
//
else
{
// get position of left node
Vector<double> s_macro_L(2);
macro_coordinate_position(node_num_x - 1, node_num_y, s_macro_L);
// get position of right node
Vector<double> s_macro_R(2);
macro_coordinate_position(node_num_x + 1, node_num_y, s_macro_R);
// compute dm0/ds0
m_gen(1, 0) = 0.5 * std::min(s_macro_N[0] - s_macro_L[0],
s_macro_R[0] - s_macro_N[0]);
// compute dm1/ds0
Vector<double> node_space(2);
node_space[0] = s_macro_N[1] - s_macro_L[1];
node_space[1] = s_macro_R[1] - s_macro_N[1];
// set nodal dof
if (node_space[0] > 0 && node_space[1] > 0)
m_gen(1, 1) = 0.5 * std::min(node_space[0], node_space[1]);
else if (node_space[0] < 0 && node_space[1] < 0)
m_gen(1, 1) = 0.5 * std::max(node_space[0], node_space[1]);
else
m_gen(1, 1) = 0;
}
// if node in lower row
if (node_num_y == 0)
{
// now dm0ds1 and dm1ds1
// get position of upper node
Vector<double> s_macro_U(2);
macro_coordinate_position(node_num_x, node_num_y + 1, s_macro_U);
// compute dm0ds1
m_gen(2, 0) = 0.5 * (s_macro_U[0] - s_macro_N[0]);
// compute dm1ds1
m_gen(2, 1) = 0.5 * (s_macro_U[1] - s_macro_N[1]);
// and if not corner node
if (node_num_x > 0 && node_num_x < Nelement[0])
{
// now dm0/ds0ds1 and dm1/ds0ds1
// get position of upper left node
Vector<double> s_macro_UL(2);
macro_coordinate_position(node_num_x - 1, node_num_y + 1, s_macro_UL);
// get position of left node
Vector<double> s_macro_L(2);
macro_coordinate_position(node_num_x - 1, node_num_y, s_macro_L);
// get position of right node
Vector<double> s_macro_R(2);
macro_coordinate_position(node_num_x + 1, node_num_y, s_macro_R);
// get position of upper right node
Vector<double> s_macro_UR(2);
macro_coordinate_position(node_num_x + 1, node_num_y + 1, s_macro_UR);
// set dm0/ds0ds1
m_gen(3, 0) =
0.5 * std::min(m_gen(2, 0) - 0.5 * (s_macro_UL[0] - s_macro_L[0]),
0.5 * (s_macro_UR[0] - s_macro_R[0]) - m_gen(2, 0));
// set dm1/ds0ds1
m_gen(3, 1) =
0.5 * std::min(m_gen(2, 1) - 0.5 * (s_macro_UL[1] - s_macro_L[1]),
0.5 * (s_macro_UR[1] - s_macro_R[1]) - m_gen(2, 1));
}
}
// else if node in upper row
else if (node_num_y == Nelement[1])
{
// now dm0ds1 and dm1ds1
// get position of lower node
Vector<double> s_macro_D(2);
macro_coordinate_position(node_num_x, node_num_y - 1, s_macro_D);
// compute dm0ds1
m_gen(2, 0) = 0.5 * (s_macro_N[0] - s_macro_D[0]);
// compute dm1ds1
m_gen(2, 1) = 0.5 * (s_macro_N[1] - s_macro_D[1]);
// and if not corner node
if (node_num_x > 0 && node_num_x < Nelement[0])
{
// now dm0/ds0ds1 and dm1/ds0ds1
// get position of lower left node
Vector<double> s_macro_DL(2);
macro_coordinate_position(node_num_x - 1, node_num_y - 1, s_macro_DL);
// get position of left node
Vector<double> s_macro_L(2);
macro_coordinate_position(node_num_x - 1, node_num_y, s_macro_L);
// get position of right node
Vector<double> s_macro_R(2);
macro_coordinate_position(node_num_x + 1, node_num_y, s_macro_R);
// get position of lower right node
Vector<double> s_macro_DR(2);
macro_coordinate_position(node_num_x + 1, node_num_y - 1, s_macro_DR);
// set dm0/ds0ds1
m_gen(3, 0) =
0.5 * std::min(m_gen(2, 0) - 0.5 * (s_macro_L[0] - s_macro_DL[0]),
0.5 * (s_macro_R[0] - s_macro_DR[0]) - m_gen(2, 0));
// set dm1/ds0ds1
m_gen(3, 1) =
0.5 * std::min(m_gen(2, 1) - 0.5 * (s_macro_L[1] - s_macro_DL[1]),
0.5 * (s_macro_R[1] - s_macro_DR[1]) - m_gen(2, 1));
}
}
else
{
// get position of upper node
Vector<double> s_macro_U(2);
macro_coordinate_position(node_num_x, node_num_y + 1, s_macro_U);
// get position of lower node
Vector<double> s_macro_D(2);
macro_coordinate_position(node_num_x, node_num_y - 1, s_macro_D);
// compute dm0/ds1
Vector<double> node_space(2);
node_space[0] = s_macro_N[0] - s_macro_D[0];
node_space[1] = s_macro_U[0] - s_macro_N[0];
// set nodal coordinate
if (node_space[0] > 0 && node_space[1] > 0)
m_gen(2, 0) = 0.5 * std::min(node_space[0], node_space[1]);
else if (node_space[0] < 0 && node_space[1] < 0)
m_gen(2, 0) = 0.5 * std::max(node_space[0], node_space[1]);
else
m_gen(2, 0) = 0;
// compute dm1/ds1
m_gen(2, 1) = 0.5 * std::min(s_macro_N[1] - s_macro_D[1],
s_macro_U[1] - s_macro_N[1]);
// for interior nodes
if (node_num_x > 0 && node_num_x < Nelement[0])
{
// get position of left node
Vector<double> s_macro_L(2);
macro_coordinate_position(node_num_x - 1, node_num_y, s_macro_L);
// get position of upper left node
Vector<double> s_macro_UL(2);
macro_coordinate_position(node_num_x - 1, node_num_y + 1, s_macro_UL);
// get position of upper right node
Vector<double> s_macro_UR(2);
macro_coordinate_position(node_num_x + 1, node_num_y + 1, s_macro_UR);
// get position of right node
Vector<double> s_macro_R(2);
macro_coordinate_position(node_num_x + 1, node_num_y, s_macro_R);
// get position of lower right node
Vector<double> s_macro_DR(2);
macro_coordinate_position(node_num_x + 1, node_num_y - 1, s_macro_DR);
// get position of lower left node
Vector<double> s_macro_DL(2);
macro_coordinate_position(node_num_x - 1, node_num_y - 1, s_macro_DL);
Vector<double> node_space(2);
// comute dm0/ds0ds1 wrt to node above and below
node_space[0] =
m_gen(1, 0) - 0.5 * std::min(s_macro_D[0] - s_macro_DL[0],
s_macro_DR[0] - s_macro_D[0]);
node_space[1] = 0.5 * std::min(s_macro_U[0] - s_macro_UL[0],
s_macro_UR[0] - s_macro_U[0]) -
m_gen(1, 0);
// set nodal dof
if (node_space[0] > 0 && node_space[1] > 0)
m_gen(3, 0) = 0.5 * std::min(node_space[0], node_space[1]);
else if (node_space[0] < 0 && node_space[1] < 0)
m_gen(3, 0) = 0.5 * std::max(node_space[0], node_space[1]);
else
m_gen(3, 0) = 0;
// comute dm1/ds0ds1 wrt node left and right
node_space[0] =
m_gen(2, 1) - 0.5 * std::min(s_macro_L[0] - s_macro_DL[0],
s_macro_UL[0] - s_macro_L[0]);
node_space[1] = 0.5 * std::min(s_macro_R[0] - s_macro_DR[0],
s_macro_UR[0] - s_macro_R[0]) -
m_gen(2, 1);
// set nodal dof
if (node_space[0] > 0 && node_space[1] > 0)
m_gen(3, 1) = 0.5 * std::min(node_space[0], node_space[1]);
else if (node_space[0] < 0 && node_space[1] < 0)
m_gen(3, 1) = 0.5 * std::max(node_space[0], node_space[1]);
else
m_gen(3, 1) = 0;
}
}
}
//=============================================================================
/// Generic mesh construction function to build the mesh
//=============================================================================
template<class ELEMENT>
void HermiteQuadMesh<ELEMENT>::build_mesh(TimeStepper* time_stepper_pt)
{
// Mesh can only be built with 2D QHermiteElements.
MeshChecker::assert_geometric_element<QHermiteElementBase, ELEMENT>(2);
// Set the number of boundaries
set_nboundary(4);
// Allocate the store for the elements
Element_pt.resize(Nelement[0] * Nelement[1]);
// Allocate the memory for the first element
Element_pt[0] = new ELEMENT;
finite_element_pt(0)->set_macro_elem_pt(Domain_pt->macro_element_pt(0));
// Can now allocate the store for the nodes
Node_pt.resize((1 + Nelement[0]) * (1 + Nelement[1]));
// Set up geometrical data
unsigned long node_count = 0;
// Now assign the topology
// Boundaries are numbered 0 1 2 3 from the bottom proceeding anticlockwise
// Pinned value are denoted by an integer value 1
// Thus if a node is on two boundaries, ORing the values of the
// boundary conditions will give the most restrictive case (pinning)
// we first create the lowest row of elements
// ##########################################
// ##########################################
// FIRST ELEMENT - lower left hand corner
// **************************************
// LOWER LEFT HAND NODE
// Set the corner node
// Allocate memory for the node
Node_pt[node_count] =
finite_element_pt(0)->construct_boundary_node(0, time_stepper_pt);
// Push the node back onto boundaries
add_boundary_node(0, Node_pt[node_count]);
add_boundary_node(3, Node_pt[node_count]);
// set the position of the boundary node
set_position_of_boundary_node(
0, 0, dynamic_cast<BoundaryNode<Node>*>(Node_pt[node_count]));
// Increment the node number
node_count++;
// LOWER RIGHT HAND NODE
// Allocate memory for the node
Node_pt[node_count] =
finite_element_pt(0)->construct_boundary_node(1, time_stepper_pt);
// Push the node back onto boundaries
add_boundary_node(0, Node_pt[node_count]);
// If we only have one column then the RHS node is on the right boundary
if (Nelement[0] == 1)
{
add_boundary_node(1, Node_pt[node_count]);
}
// set the position of the node
set_position_of_boundary_node(
1, 0, dynamic_cast<BoundaryNode<Node>*>(Node_pt[node_count]));
// Increment the node number
node_count++;
// UPPER LEFT HAND NODE
// Allocate memory for the node
Node_pt[node_count] =
finite_element_pt(0)->construct_boundary_node(2, time_stepper_pt);
// Push the node back onto boundaries
add_boundary_node(3, Node_pt[node_count]);
// If we only have one row, then the top node is on the top boundary
if (Nelement[1] == 1)
{
add_boundary_node(2, Node_pt[node_count]);
}
// set the position of the boundary node
set_position_of_boundary_node(
0, 1, dynamic_cast<BoundaryNode<Node>*>(Node_pt[node_count]));
// Increment the node number
node_count++;
// UPPER RIGHT NODE
// Allocate the memory for the node
Node_pt[node_count] =
finite_element_pt(0)->construct_node(3, time_stepper_pt);
// If we only have one column then the RHS node is on the right boundary
if (Nelement[0] == 1)
{
add_boundary_node(1, Node_pt[node_count]);
}
// If we only have one row, then the top node is on the top boundary
if (Nelement[1] == 1)
{
add_boundary_node(2, Node_pt[node_count]);
}
// if the node is a boundary node
if (Nelement[0] == 1 || Nelement[1] == 1)
{
// set the position of the boundary node
set_position_of_boundary_node(
1, 1, dynamic_cast<BoundaryNode<Node>*>(Node_pt[node_count]));
}
else
{
// set the position of the node
set_position_of_node(1, 1, Node_pt[node_count]);
}
// Increment the node number
node_count++;
// END OF FIRST ELEMENT
// CENTRE OF FIRST ROW OF ELEMENTS
// *******************************
// Now loop over the first row of elements, apart from final element
for (unsigned j = 1; j < (Nelement[0] - 1); j++)
{
// Allocate memory for new element
Element_pt[j] = new ELEMENT;
finite_element_pt(j)->set_macro_elem_pt(Domain_pt->macro_element_pt(0));
// LOWER LEFT NODE
// lower left hand node column of nodes is same as lower right hand node
// in neighbouring element
finite_element_pt(j)->node_pt(0) = finite_element_pt(j - 1)->node_pt(1);
// LOWER RIGHT NODE
// Allocate memory for the nodes
Node_pt[node_count] =
finite_element_pt(j)->construct_boundary_node(1, time_stepper_pt);
// Push the node back onto boundaries
add_boundary_node(0, Node_pt[node_count]);
// set the position of the boundary node
set_position_of_boundary_node(
j + 1, 0, dynamic_cast<BoundaryNode<Node>*>(Node_pt[node_count]));
// Increment the node number
node_count++;
// UPPER LEFT NODE
// First column of nodes is same as neighbouring element
finite_element_pt(j)->node_pt(2) = finite_element_pt(j - 1)->node_pt(3);
// UPPER RIGHT NODE
// Allocate memory for the nodes
Node_pt[node_count] =
finite_element_pt(j)->construct_node(3, time_stepper_pt);
// If we only have one row, then the top node is on the top boundary
if (Nelement[0] == 1)
{
add_boundary_node(2, Node_pt[node_count]);
}
// set the position of the (boundary) node
if (Nelement[0] == 1)
set_position_of_boundary_node(
j + 1, 1, dynamic_cast<BoundaryNode<Node>*>(Node_pt[node_count]));
else
set_position_of_node(j + 1, 1, Node_pt[node_count]);
// Increment the node number
node_count++;
}
// FINAL ELEMENT IN FIRST ROW (lower right corner element)
// **************************
// Only allocate if there is more than one element in the row
if (Nelement[0] > 1)
{
// Allocate memory for element
Element_pt[Nelement[0] - 1] = new ELEMENT;
finite_element_pt(Nelement[0] - 1)
->set_macro_elem_pt(Domain_pt->macro_element_pt(0));
// LOWER LEFT NODE
// First column of nodes is same as neighbouring element
finite_element_pt(Nelement[0] - 1)->node_pt(0) =
finite_element_pt(Nelement[0] - 2)->node_pt(1);
// LOWER RIGHT NODE
// If we have an Xperiodic mesh then the final node is the first node in
// the row
if (Xperiodic == true)
{
// Note that this is periodic in the x-direction
finite_element_pt(Nelement[0] - 1)->node_pt(1) =
finite_element_pt(0)->node_pt(0);
}
// Otherwise it's a new final node
else
{
// Allocate memory for the node
Node_pt[node_count] = finite_element_pt(Nelement[0] - 1)
->construct_boundary_node(1, time_stepper_pt);
}
// Push the node back onto boundaries
add_boundary_node(0, Node_pt[node_count]);
add_boundary_node(1, Node_pt[node_count]);
// set the position of the boundary node
set_position_of_boundary_node(
Nelement[0], 0, dynamic_cast<BoundaryNode<Node>*>(Node_pt[node_count]));
// if not periodic mesh
if (Xperiodic == false)
{
node_count++;
}
// UPPER LEFT NODE
// same as upper right node in element to left
finite_element_pt(Nelement[0] - 1)->node_pt(2) =
finite_element_pt(Nelement[0] - 2)->node_pt(3);
// If we only have one row, then the top node is on the top boundary
if (Nelement[1] == 1)
{
add_boundary_node(2, Node_pt[node_count]);
}
// set the position of the (boundary) node
if (Nelement[1] == 1)
set_position_of_boundary_node(
Nelement[0] - 1,
1,
dynamic_cast<BoundaryNode<Node>*>(
finite_element_pt(Nelement[0] - 2)->node_pt(3)));
// UPPER RIGHT NODE
// If we have an Xperiodic mesh then the nodes in the final column are
// those in the first column
if (Xperiodic == true)
{
// Note that these are periodic in the x-direction
finite_element_pt(Nelement[0] - 1)->node_pt(3) =
finite_element_pt(0)->node_pt(2);
}
// Otherwise we need new nodes for the final column
else
{
// Allocate memory for node
Node_pt[node_count] = finite_element_pt(Nelement[0] - 1)
->construct_boundary_node(3, time_stepper_pt);
}
// If we only have one row, then the top node is on the top boundary
if (Nelement[1] == 1)
{
add_boundary_node(2, Node_pt[node_count]);
}
// boundary 1 node
add_boundary_node(1, Node_pt[node_count]);
// set the position of the boundary node
set_position_of_boundary_node(
Nelement[0], 1, dynamic_cast<BoundaryNode<Node>*>(Node_pt[node_count]));
// Increment the node number
if (Xperiodic == false)
{
// Increment the node number
node_count++;
}
}
// now create all remaining central rows
// #####################################
// #####################################
// Loop over remaining element rows in the mesh
for (unsigned i = 1; i < (Nelement[1] - 1); i++)
{
// set the first element in the row
// ********************************
// Allocate memory for element
Element_pt[Nelement[0] * i] = new ELEMENT;
finite_element_pt(Nelement[0] * i)
->set_macro_elem_pt(Domain_pt->macro_element_pt(0));
// The first row of nodes is copied from the element below
for (unsigned l = 0; l < 2; l++)
{
finite_element_pt(Nelement[0] * i)->node_pt(l) =
finite_element_pt(Nelement[0] * (i - 1))->node_pt(2 + l);
}
// UPPER LEFT HAND NODE
// Allocate memory for node
Node_pt[node_count] = finite_element_pt(Nelement[0] * i)
->construct_boundary_node(2, time_stepper_pt);
// Push the node back onto boundaries
add_boundary_node(3, Node_pt[node_count]);
// set the position of the boundary node
set_position_of_boundary_node(
0, i + 1, dynamic_cast<BoundaryNode<Node>*>(Node_pt[node_count]));
// Increment the node number
node_count++;
// UPPER RIGHT HAND NODE
// If we only have one column, the node could be on the boundary
if (Nelement[0] == 1)
{
Node_pt[node_count] = finite_element_pt(Nelement[0] * i)
->construct_boundary_node(3, time_stepper_pt);
}
else
{
Node_pt[node_count] = finite_element_pt(Nelement[0] * i)
->construct_node(3, time_stepper_pt);
}
// If we only have one column then the RHS node is on the
// right boundary
if (Nelement[0] == 1)
{
add_boundary_node(1, Node_pt[node_count]);
}
// set the position of the (boundary) node
if (Nelement[0] == 1)
set_position_of_boundary_node(
1, i + 1, dynamic_cast<BoundaryNode<Node>*>(Node_pt[node_count]));
else
set_position_of_node(1, i + 1, Node_pt[node_count]);
// Increment the node number
node_count++;
// loop over central elements in row
// *********************************
// Now loop over the rest of the elements in the row, apart from the last
for (unsigned j = 1; j < (Nelement[0] - 1); j++)
{
// Allocate memory for new element
Element_pt[Nelement[0] * i + j] = new ELEMENT;
finite_element_pt(Nelement[0] * i + j)
->set_macro_elem_pt(Domain_pt->macro_element_pt(0));
// LOWER LEFT AND RIGHT NODES
// The first row is copied from the lower element
for (unsigned l = 0; l < 2; l++)
{
finite_element_pt(Nelement[0] * i + j)->node_pt(l) =
finite_element_pt(Nelement[0] * (i - 1) + j)->node_pt(2 + l);
}
// UPPER LEFT NODE
// First column is same as neighbouring element
finite_element_pt(Nelement[0] * i + j)->node_pt(2) =
finite_element_pt(Nelement[0] * i + (j - 1))->node_pt(3);
// UPPER RIGHT NODE
// Allocate memory for the nodes
Node_pt[node_count] = finite_element_pt(Nelement[0] * i + j)
->construct_node(3, time_stepper_pt);
// set position of node
set_position_of_node(j + 1, i + 1, Node_pt[node_count]);
// Increment the node number
node_count++;
}
// final element in row
// ********************
// Only if there is more than one column
if (Nelement[0] > 1)
{
// Allocate memory for element
Element_pt[Nelement[0] * i + Nelement[0] - 1] = new ELEMENT;
finite_element_pt(Nelement[0] * i + Nelement[0] - 1)
->set_macro_elem_pt(Domain_pt->macro_element_pt(0));
// LOWER LEFT AND RIGHT NODES
// The first row is copied from the lower element
for (unsigned l = 0; l < 2; l++)
{
finite_element_pt(Nelement[0] * i + Nelement[0] - 1)->node_pt(l) =
finite_element_pt(Nelement[0] * (i - 1) + Nelement[0] - 1)
->node_pt(2 + l);
}
// UPPER LEFT NODE
// First node is same as neighbouring element
finite_element_pt(Nelement[0] * i + Nelement[0] - 1)->node_pt(2) =
finite_element_pt(Nelement[0] * i + Nelement[0] - 2)->node_pt(3);
// UPPER RIGHT NODE
// If we have an Xperiodic mesh then this node is the same
// as the first node
if (Xperiodic == true)
{
// Allocate memory for node, periodic in x-direction
finite_element_pt(Nelement[0] * i + Nelement[0] - 1)->node_pt(3) =
finite_element_pt(Nelement[0] * i)->node_pt(2);
}
// Otherwise allocate memory for a new node
else
{
Node_pt[node_count] =
finite_element_pt(Nelement[0] * i + Nelement[0] - 1)
->construct_boundary_node(3, time_stepper_pt);
}
// Push the node back onto boundaries
add_boundary_node(1, Node_pt[node_count]);
// set position of boundary node
set_position_of_boundary_node(
Nelement[0],
i + 1,
dynamic_cast<BoundaryNode<Node>*>(Node_pt[node_count]));
// Increment the node number
node_count++;
}
}
// final element row
// #################
// #################
// only if there is more than one row
if (Nelement[1] > 1)
{
// first element in upper row (upper left corner)
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Allocate memory for element
Element_pt[Nelement[0] * (Nelement[1] - 1)] = new ELEMENT;
finite_element_pt(Nelement[0] * (Nelement[1] - 1))
->set_macro_elem_pt(Domain_pt->macro_element_pt(0));
// LOWER LEFT AND LOWER RIGHT NODES
// The first row of nodes is copied from the element below
for (unsigned l = 0; l < 2; l++)
{
finite_element_pt(Nelement[0] * (Nelement[1] - 1))->node_pt(l) =
finite_element_pt(Nelement[0] * (Nelement[1] - 2))->node_pt(2 + l);
}
// UPPER LEFT NODE
// Allocate memory for node
Node_pt[node_count] = finite_element_pt(Nelement[0] * (Nelement[1] - 1))
->construct_boundary_node(2, time_stepper_pt);
// Push the node back onto boundaries
add_boundary_node(2, Node_pt[node_count]);
add_boundary_node(3, Node_pt[node_count]);
// set position of boundary node
set_position_of_boundary_node(
0, Nelement[1], dynamic_cast<BoundaryNode<Node>*>(Node_pt[node_count]));
// Increment the node number
node_count++;
// UPPER RIGHT NODE
// Allocate memory for the node
Node_pt[node_count] = finite_element_pt(Nelement[0] * (Nelement[1] - 1))
->construct_boundary_node(3, time_stepper_pt);
// Push the node back onto boundaries
add_boundary_node(2, Node_pt[node_count]);
// set position of boundary node
set_position_of_boundary_node(
1, Nelement[1], dynamic_cast<BoundaryNode<Node>*>(Node_pt[node_count]));
// Increment the node number
node_count++;
// loop over central elements of upper element row
// ***********************************************
// Now loop over the rest of the elements in the row, apart from the last
for (unsigned j = 1; j < (Nelement[0] - 1); j++)
{
// Allocate memory for element
Element_pt[Nelement[0] * (Nelement[1] - 1) + j] = new ELEMENT;
finite_element_pt(Nelement[0] * (Nelement[1] - 1) + j)
->set_macro_elem_pt(Domain_pt->macro_element_pt(0));
// LOWER LEFT AND LOWER RIGHT NODES
// The first row is copied from the lower element
for (unsigned l = 0; l < 2; l++)
{
finite_element_pt(Nelement[0] * (Nelement[1] - 1) + j)->node_pt(l) =
finite_element_pt(Nelement[0] * (Nelement[1] - 2) + j)
->node_pt(2 + l);
}
// UPPER LEFT NODE
// First column is same as neighbouring element
finite_element_pt(Nelement[0] * (Nelement[1] - 1) + j)->node_pt(2) =
finite_element_pt(Nelement[0] * (Nelement[1] - 1) + (j - 1))
->node_pt(3);
// UPPER RIGHT NODE
// Allocate memory for node
Node_pt[node_count] =
finite_element_pt(Nelement[0] * (Nelement[1] - 1) + j)
->construct_boundary_node(3, time_stepper_pt);
// Push the node back onto boundaries
add_boundary_node(2, Node_pt[node_count]);
// set position of boundary node
set_position_of_boundary_node(
j + 1,
Nelement[1],
dynamic_cast<BoundaryNode<Node>*>(Node_pt[node_count]));
// Increment the node number
node_count++;
} // End of loop over central elements in row
// final element in row (upper right corner)
// *****************************************
// Only if there is more than one column
if (Nelement[0] > 1)
{
// Allocate memory for element
Element_pt[Nelement[0] * (Nelement[1] - 1) + Nelement[0] - 1] =
new ELEMENT;
finite_element_pt(Nelement[0] * (Nelement[1] - 1) + Nelement[0] - 1)
->set_macro_elem_pt(Domain_pt->macro_element_pt(0));
// LOWER LEFT AND LOWER RIGHT NODES
// The first row is copied from the lower element
for (unsigned l = 0; l < 2; l++)
{
finite_element_pt(Nelement[0] * (Nelement[1] - 1) + Nelement[0] - 1)
->node_pt(l) =
finite_element_pt(Nelement[0] * (Nelement[1] - 2) + Nelement[0] - 1)
->node_pt(2 + l);
}
// UPPER LEFT NODE
// First column is same as neighbouring element
finite_element_pt(Nelement[0] * (Nelement[1] - 1) + Nelement[0] - 1)
->node_pt(2) =
finite_element_pt(Nelement[0] * (Nelement[1] - 1) + Nelement[0] - 2)
->node_pt(3);
// UPPER RIGHT NODE
// If we have an Xperiodic mesh, the node must be copied from
// the first column
if (Xperiodic == true)
{
// Allocate memory for node, periodic in x-direction
finite_element_pt(Nelement[0] * (Nelement[1] - 1) + Nelement[0] - 1)
->node_pt(3) =
finite_element_pt(Nelement[0] * (Nelement[1] - 1))->node_pt(2);
}
// Otherwise, allocate new memory for node
else
{
Node_pt[node_count] =
finite_element_pt(Nelement[0] * (Nelement[1] - 1) + Nelement[0] - 1)
->construct_boundary_node(3, time_stepper_pt);
}
// Push the node back onto boundaries
add_boundary_node(1, Node_pt[node_count]);
add_boundary_node(2, Node_pt[node_count]);
// set position of boundary node
set_position_of_boundary_node(
Nelement[0],
Nelement[1],
dynamic_cast<BoundaryNode<Node>*>(Node_pt[node_count]));
// Increment the node number
node_count++;
}
}
// Setup boundary element lookup schemes
setup_boundary_element_info();
}
//=============================================================================
/// Setup lookup schemes which establish which elements are located
/// next to which boundaries (Doc to outfile if it's open). Specific version
/// for HermiteQuadMesh to ensure that the order of the elements in
/// Boundary_element_pt matches the actual order along the boundary. This is
/// required when hijacking the BiharmonicElement to apply the
/// BiharmonicFluidBoundaryElement in
/// BiharmonicFluidProblem::impose_traction_free_edge(...)
//================================================================
template<class ELEMENT>
void HermiteQuadMesh<ELEMENT>::setup_boundary_element_info(
std::ostream& outfile)
{
bool doc = false;
if (outfile) doc = true;
// Number of boundaries
unsigned nbound = nboundary();
// Wipe/allocate storage for arrays
Boundary_element_pt.clear();
Face_index_at_boundary.clear();
Boundary_element_pt.resize(nbound);
Face_index_at_boundary.resize(nbound);
// Temporary vector of sets of pointers to elements on the boundaries:
Vector<Vector<FiniteElement*>> vector_of_boundary_element_pt;
vector_of_boundary_element_pt.resize(nbound);
// Matrix map for working out the fixed local coord for elements on boundary
MapMatrixMixed<unsigned, FiniteElement*, Vector<int>*> boundary_identifier;
// Loop over elements
//-------------------
unsigned nel = nelement();
for (unsigned e = 0; e < nel; e++)
{
// Get pointer to element
FiniteElement* fe_pt = finite_element_pt(e);
if (doc) outfile << "Element: " << e << " " << fe_pt << std::endl;
// Only include 2D elements! Some meshes contain interface elements too.
if (fe_pt->dim() == 2)
{
// Loop over the element's nodes and find out which boundaries they're
// on
// ----------------------------------------------------------------------
unsigned nnode_1d = fe_pt->nnode_1d();
// Loop over nodes in order
for (unsigned i0 = 0; i0 < nnode_1d; i0++)
{
for (unsigned i1 = 0; i1 < nnode_1d; i1++)
{
// Local node number
unsigned j = i0 + i1 * nnode_1d;
// Get pointer to vector of boundaries that this
// node lives on
std::set<unsigned>* boundaries_pt = 0;
fe_pt->node_pt(j)->get_boundaries_pt(boundaries_pt);
// If the node lives on some boundaries....
if (boundaries_pt != 0)
{
// Loop over boundaries
// unsigned nbound=(*boundaries_pt).size();
for (std::set<unsigned>::iterator it = boundaries_pt->begin();
it != boundaries_pt->end();
++it)
{
// Add pointer to finite element to set for the appropriate
// boundary -- storage in set makes sure we don't count elements
// multiple times
unsigned temp_size = vector_of_boundary_element_pt[*it].size();
bool temp_flag = true;
for (unsigned temp_i = 0; temp_i < temp_size; temp_i++)
{
if (vector_of_boundary_element_pt[*it][temp_i] == fe_pt)
temp_flag = false;
}
if (temp_flag)
vector_of_boundary_element_pt[*it].push_back(fe_pt);
// For the current element/boundary combination, create
// a vector that stores an indicator which element boundaries
// the node is located (boundary_identifier=-/+1 for nodes
// on the left/right boundary; boundary_identifier=-/+2 for
// nodes on the lower/upper boundary. We determine these indices
// for all corner nodes of the element and add them to a vector
// to a vector. This allows us to decide which face of the
// element coincides with the boundary since the (quad!) element
// must have exactly two corner nodes on the boundary.
if (boundary_identifier(*it, fe_pt) == 0)
{
boundary_identifier(*it, fe_pt) = new Vector<int>;
}
// Are we at a corner node?
if (((i0 == 0) || (i0 == nnode_1d - 1)) &&
((i1 == 0) || (i1 == nnode_1d - 1)))
{
// Create index to represent position relative to s_0
(*boundary_identifier(*it, fe_pt))
.push_back(1 * (2 * i0 / (nnode_1d - 1) - 1));
// Create index to represent position relative to s_1
(*boundary_identifier(*it, fe_pt))
.push_back(2 * (2 * i1 / (nnode_1d - 1) - 1));
}
}
}
// else
// {
// oomph_info << "...does not live on any boundaries " <<
// std::endl;
// }
}
}
}
// else
//{
// oomph_info << "Element " << e << " does not qualify" << std::endl;
//}
}
// Now copy everything across into permanent arrays
//-------------------------------------------------
// Note: vector_of_boundary_element_pt contains all elements
// that have (at least) one corner node on a boundary -- can't copy
// them across into Boundary_element_pt
// yet because some of them might have only one node on the
// the boundary in which case they don't qualify as
// boundary elements!
// Loop over boundaries
//---------------------
for (unsigned i = 0; i < nbound; i++)
{
// Number of elements on this boundary (currently stored in a set)
unsigned nel = vector_of_boundary_element_pt[i].size();
// Allocate storage for the coordinate identifiers
Face_index_at_boundary[i].resize(nel);
// Loop over elements that have at least one corner node on this boundary
//-----------------------------------------------------------------------
unsigned e_count = 0;
typedef Vector<FiniteElement*>::iterator IT;
for (IT it = vector_of_boundary_element_pt[i].begin();
it != vector_of_boundary_element_pt[i].end();
it++)
{
// Recover pointer to element
FiniteElement* fe_pt = *it;
// Initialise count for boundary identiers (-2,-1,1,2)
std::map<int, unsigned> count;
// Loop over coordinates
for (unsigned ii = 0; ii < 2; ii++)
{
// Loop over upper/lower end of coordinates
for (int sign = -1; sign < 3; sign += 2)
{
count[(ii + 1) * sign] = 0;
}
}
// Loop over boundary indicators for this element/boundary
unsigned n_indicators = (*boundary_identifier(i, fe_pt)).size();
for (unsigned j = 0; j < n_indicators; j++)
{
count[(*boundary_identifier(i, fe_pt))[j]]++;
}
delete boundary_identifier(i, fe_pt);
// Determine the correct boundary indicator by checking that it
// occurs twice (since two corner nodes of the element's boundary
// need to be located on the domain boundary
int indicator = -10;
// Check that we're finding exactly one boundary indicator
bool found = false;
// Loop over coordinates
for (unsigned ii = 0; ii < 2; ii++)
{
// Loop over upper/lower end of coordinates
for (int sign = -1; sign < 3; sign += 2)
{
if (count[(ii + 1) * sign] == 2)
{
// Check that we haven't found multiple boundaries
if (found)
{
std::string error_message =
"Trouble: Multiple boundary identifiers!\n";
error_message += "Elements should only have at most 2 corner ";
error_message += "nodes on any one boundary.\n";
throw OomphLibError(error_message,
OOMPH_CURRENT_FUNCTION,
OOMPH_EXCEPTION_LOCATION);
}
found = true;
indicator = (ii + 1) * sign;
}
}
}
// Element has exactly two corner nodes on boundary
if (found)
{
// Add to permanent storage
Boundary_element_pt[i].push_back(fe_pt);
// Now convert boundary indicator into information required
// for FaceElements
switch (indicator)
{
case -2:
// s_1 is fixed at -1.0:
Face_index_at_boundary[i][e_count] = -2;
break;
case -1:
// s_0 is fixed at -1.0:
Face_index_at_boundary[i][e_count] = -1;
break;
case 1:
// s_0 is fixed at 1.0:
Face_index_at_boundary[i][e_count] = 1;
break;
case 2:
// s_1 is fixed at 1.0:
Face_index_at_boundary[i][e_count] = 2;
break;
default:
throw OomphLibError("Never get here",
OOMPH_CURRENT_FUNCTION,
OOMPH_EXCEPTION_LOCATION);
}
// Increment counter
e_count++;
}
}
}
// Doc?
//-----
if (doc)
{
// Loop over boundaries
for (unsigned i = 0; i < nbound; i++)
{
unsigned nel = Boundary_element_pt[i].size();
outfile << "Boundary: " << i << " is adjacent to " << nel << " elements"
<< std::endl;
// Loop over elements on given boundary
for (unsigned e = 0; e < nel; e++)
{
FiniteElement* fe_pt = Boundary_element_pt[i][e];
outfile << "Boundary element:" << fe_pt
<< " Face index of element along boundary is "
<< Face_index_at_boundary[i][e] << std::endl;
}
}
}
// Lookup scheme has now been setup yet
Lookup_for_elements_next_boundary_is_setup = true;
}
} // namespace oomph
#endif
| 34.088803 | 81 | 0.563069 | pkeuchel |
c9c01d9391098e84726256cf59347d89fb4ed591 | 1,132 | cpp | C++ | Crypt.cpp | wolframtheta/cell | 71c14c391c00b2a125621a5134b5440a48c39d98 | [
"MIT"
] | null | null | null | Crypt.cpp | wolframtheta/cell | 71c14c391c00b2a125621a5134b5440a48c39d98 | [
"MIT"
] | null | null | null | Crypt.cpp | wolframtheta/cell | 71c14c391c00b2a125621a5134b5440a48c39d98 | [
"MIT"
] | null | null | null | #include "utils.hpp"
#include "ListCells.hpp"
#include "Crypt.hpp"
Crypt::Crypt(){
this->rate = -1;
}
Crypt::Crypt(Cell cellCrypt) {
this->cell = cellCrypt;
this->rate = 0.0;
this->listCells = ListCells();
this->meanIntensity = 0.0;
this->meanRawIntensity = 0.0;
}
double Crypt::getMeanIntensity() {
return this->meanIntensity;
}
double Crypt::getMeanRawIntensity() {
return this->meanRawIntensity;
}
void Crypt::setMeanIntensity(double meanIntensity) {
this->meanIntensity = meanIntensity;
}
void Crypt::setMeanRawIntensity(double meanRawIntensity) {
this->meanRawIntensity = meanRawIntensity;
}
ListCells Crypt::getListCells() {
return this->listCells;
}
double Crypt::getRate() {
return this->rate;
}
Cell Crypt::getCell() {
return this->cell;
}
void Crypt::addCell(Cell cell) {
this->listCells.addCell(cell);
}
void Crypt::setRate(double rate) {
this->rate = rate;
}
void Crypt::print() {
cout << "Crypt: " << cell.getPerimeter() << " Rate: " << this->rate << " Intensity: " << cell.getIntensity() << endl;
listCells.print();
}
bool Crypt::isEmpty() {
return (this->rate == -1);
}
| 18.258065 | 118 | 0.675795 | wolframtheta |
c9c088467e31b7ec78805e207ac1147fffc14eb5 | 8,042 | cc | C++ | GraphLib/graphviz/graphviz.cc | intact-software-systems/cpp-software-patterns | e463fc7eeba4946b365b5f0b2eecf3da0f4c895b | [
"MIT"
] | 1 | 2020-09-03T07:23:11.000Z | 2020-09-03T07:23:11.000Z | GraphLib/graphviz/graphviz.cc | intact-software-systems/cpp-software-patterns | e463fc7eeba4946b365b5f0b2eecf3da0f4c895b | [
"MIT"
] | null | null | null | GraphLib/graphviz/graphviz.cc | intact-software-systems/cpp-software-patterns | e463fc7eeba4946b365b5f0b2eecf3da0f4c895b | [
"MIT"
] | null | null | null | /***************************************************************************
graphviz.h - description
-------------------
begin : Thu Nov 25 2005
copyright : (C) 2005 by Knut-Helge Vik
email : knuthelv@ifi.uio.no
***************************************************************************/
#include "graphviz.h"
#include "../graphstats/recordtree.h"
#include "fstream"
#include "iostream"
#include <string>
using namespace std;
using namespace TreeAlgorithms;
void
GraphVisualization::VizGraph(ostream &outfile, const GraphN &g)
{
// start writing Vertices, Edges and....
outfile << "*Vertices " << num_vertices(g) << "\n";
pair<vertex_iteratorN, vertex_iteratorN> pvit;
int i;
std::vector<float> map(num_vertices(g));
for(pvit = vertices(g), i = 1; pvit.first != pvit.second; ++pvit.first, i++)
{
outfile << " " << i << " \"" << *(pvit.first) << "\" \n";
map[*(pvit.first)] = i;
}
outfile << "*Edges " << num_edges(g) << "\n";
pair<out_edge_iteratorN, out_edge_iteratorN> sp_eit;
for(pvit = vertices(g); pvit.first != pvit.second; ++pvit.first)
{
for(sp_eit = out_edges(*(pvit.first), g); sp_eit.first != sp_eit.second; ++sp_eit.first)
{
vertex_descriptorN src = source(*sp_eit.first, g), targ = target(*sp_eit.first, g);
outfile <<" " << map[src] << " " << map[targ] << " " << get(&EdgeProp::weight, g)[*(sp_eit.first)]; // << "\n";
//outfile << " " << (src) << " " << (targ) << " " << get(&EdgeProp::weight, g)[*(sp_eit.first)] << "\n";
outfile << " l \"" <<(src) << " -> " << (targ) << "\" ";
outfile << "\n";
}
}
outfile << "\n";
}
void
GraphVisualization::VizTree(ostream &outfile, const TreeStructure &T)
{
outfile << "*Vertices " << T.V.size() << "\n";
GraphN g = T.g;
std::vector<float> map(num_vertices(g));
int i;
VertexSet_it vit;
for(vit = T.V.begin(), i = 1; vit != T.V.end(); ++vit, i++)
{
outfile << " " << i << " \"" << *vit << "\" " << g[*vit].xpos/1000 << " " << g[*vit].ypos/1000 << " 0";
outfile << "\tbc Black";
// different colors
if(get(&VertexProp::vertexState, g)[*vit] == STEINER_POINT) // steiner node
outfile << " box x_fact 3 y_fact 3 ic Black ";
//outfile << " box ic Black ";
else if(get(&VertexProp::vertexState, g)[*vit] == GROUP_MEMBER)
outfile << " ellipse ic White "; // group member znode
else cerr << "[Error] Not a znode or steiner " << *vit << endl;
map[*vit] = i;
outfile << "\n";
}
for(vit = T.C.begin(); vit != T.C.end(); ++vit, i++)
{
if(T.V.contains(*vit)) continue;
outfile << " " << i << " \"" << *vit << "\" " << g[*vit].xpos/1000 << " " << g[*vit].ypos/1000 << " 0";
outfile << "\tbc Black";
outfile << " box x_fact 3 y_fact 3 ic Black ";
outfile << "\n";
map[*vit] = i;
}
if(T.E.size())
outfile << "*Edges " << T.E.size() << "\n";
EdgeList::const_iterator eit, eit_end;
for(eit = T.E.begin(), eit_end = T.E.end(); eit != eit_end; ++eit)
{
vertex_descriptorN src = source((*eit), g), targ = target((*eit), g);
pair<edge_descriptorN, bool> e = edge(src, targ, g);
assert(e.second);
outfile << " " << map[src] << " " << map[targ] << " " << get(&EdgeProp::weight, g)[e.first];
outfile << " l \"" <<(src) << " -> " << (targ) << "\" ";
// TODO add different edgetypes
outfile << " p Solid w 1.0 c Black ";
outfile << "\n";
}
outfile << "\n";
}
void
GraphVisualization::VizTree(ostream &outfile, const TreeStructure &T, const TreeStructure &prevT)
{
EdgePair diffEp = Statistics::findDifference(T.Ep, prevT.Ep);
outfile << "*Vertices " << T.V.size() << "\n";
GraphN g = T.g;
std::vector<float> map(num_vertices(g));
int i;
VertexSet_it vit;
for(vit = T.V.begin(), i = 1; vit != T.V.end(); ++vit, i++)
{
outfile << " " << i << " \"" << *vit << "\" " << g[*vit].xpos/1000 << " " << g[*vit].ypos/1000 << " 0";
stringstream tstream;
if(!prevT.V.contains(*vit))
tstream << " bc Blue ";
else tstream << " bc Black";
if(get(&VertexProp::vertexState, g)[*vit] == STEINER_POINT) // steiner node
tstream << " box ic Black ";
else if(get(&VertexProp::vertexState, g)[*vit] == GROUP_MEMBER)
tstream << " ellipse ic White "; // group member znode
else cerr << "[Error] Not a znode or steiner " << *vit << endl;
outfile << tstream.str() ;
map[*vit] = i;
outfile << "\n";
}
outfile << "*Edges " << T.E.size() << "\n";
EdgeList::const_iterator eit, eit_end;
for(eit = T.E.begin(), eit_end = T.E.end(); eit != eit_end; ++eit)
{
vertex_descriptorN src = source((*eit), g), targ = target((*eit), g);
pair<edge_descriptorN, bool> e = edge(src, targ, g);
assert(e.second);
outfile << " " << map[src] << " " << map[targ] << " " << get(&EdgeProp::weight, g)[e.first];
outfile << " l \"" <<(src) << " -> " << (targ) << "\" ";
// TODO add different edgetypes
bool found = false;
stringstream tstream;
EdgeId eid(src, targ);
for(EdgePair::iterator epit = diffEp.begin(), epit_end = diffEp.end(); epit != epit_end; ++epit)
{
if(*epit == eid)
{
found = true;
tstream << " p Dots w 1.5 c Black ";
break;
}
}
if(!found)
tstream << " p Solid w 1.0 c Black ";
outfile << tstream.str() ;
outfile << "\n";
}
outfile << "\n";
}
void
GraphVisualization::VizGraph(const char *filename, const GraphN &g)
{
// open file for writing
ofstream outfile(filename, ios::out);
// start writing Vertices, Edges and....
outfile << "*Vertices " << num_vertices(g) << "\n";
pair<vertex_iteratorN, vertex_iteratorN> pvit;
int i;
std::vector<float> map(num_vertices(g));
for(pvit = vertices(g), i = 1; pvit.first != pvit.second; ++pvit.first, i++)
{
outfile << " " << i << " \"" << *(pvit.first) << "\" \n";
map[*(pvit.first)] = i;
}
outfile << "*Edges " << num_edges(g) << "\n";
pair<out_edge_iteratorN, out_edge_iteratorN> sp_eit;
for(pvit = vertices(g); pvit.first != pvit.second; ++pvit.first)
{
for(sp_eit = out_edges(*(pvit.first), g); sp_eit.first != sp_eit.second; ++sp_eit.first)
{
vertex_descriptorN src = source(*sp_eit.first, g), targ = target(*sp_eit.first, g);
outfile <<" " << map[src] << " " << map[targ] << " " << get(&EdgeProp::weight, g)[*(sp_eit.first)]; // << "\n";
//outfile << " " << (src) << " " << (targ) << " " << get(&EdgeProp::weight, g)[*(sp_eit.first)] << "\n";
outfile << " l \"" <<(src) << " -> " << (targ) << "\" ";
outfile << "\n";
}
}
outfile << "\n";
outfile.close();
}
void
GraphVisualization::VizTree(const char *filename, const TreeStructure &T)
{
ofstream outfile(filename, ios::out);
outfile << "*Vertices " << T.V.size() << "\n";
GraphN g = T.g;
std::vector<float> map(num_vertices(g));
int i;
VertexSet_it vit;
for(vit = T.V.begin(), i = 1; vit != T.V.end(); ++vit, i++)
{
outfile << " " << i << " \"" << *vit << "\" " << g[*vit].xpos/1000 << " " << g[*vit].ypos/1000 << " 0";
// different colors
if(get(&VertexProp::vertexState, g)[*vit] == STEINER_POINT) // steiner node
outfile << " x_fact 3 y_fact 3 ic Blue ";
else if(get(&VertexProp::vertexState, g)[*vit] == GROUP_MEMBER)
outfile << " ic Red "; // group member znode
else cerr << "[Error] Not a znode or steiner " << *vit << endl;
map[*vit] = i;
outfile << "\n";
}
outfile << "*Edges " << T.E.size() << "\n";
EdgeList::const_iterator eit, eit_end;
for(eit = T.E.begin(), eit_end = T.E.end(); eit != eit_end; ++eit)
{
vertex_descriptorN src = source((*eit), g), targ = target((*eit), g);
pair<edge_descriptorN, bool> e = edge(src, targ, g);
assert(e.second);
outfile << " " << map[src] << " " << map[targ] << " " << get(&EdgeProp::weight, g)[e.first];
outfile << " l \"" <<(src) << " -> " << (targ) << "\" ";
// TODO add different edgetypes
outfile << "\n";
}
outfile << "\n";
outfile.close();
}
| 31.050193 | 125 | 0.531957 | intact-software-systems |
c9c4d5fa82d61f0418e3b3411dec22be8bf588fe | 1,066 | hpp | C++ | library/ATF/_personal_automine_uninstall_circle_zoclInfo.hpp | lemkova/Yorozuya | f445d800078d9aba5de28f122cedfa03f26a38e4 | [
"MIT"
] | 29 | 2017-07-01T23:08:31.000Z | 2022-02-19T10:22:45.000Z | library/ATF/_personal_automine_uninstall_circle_zoclInfo.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 90 | 2017-10-18T21:24:51.000Z | 2019-06-06T02:30:33.000Z | library/ATF/_personal_automine_uninstall_circle_zoclInfo.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 44 | 2017-12-19T08:02:59.000Z | 2022-02-24T23:15:01.000Z | // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <_personal_automine_uninstall_circle_zocl.hpp>
START_ATF_NAMESPACE
namespace Info
{
using _personal_automine_uninstall_circle_zoclctor__personal_automine_uninstall_circle_zocl2_ptr = void (WINAPIV*)(struct _personal_automine_uninstall_circle_zocl*);
using _personal_automine_uninstall_circle_zoclctor__personal_automine_uninstall_circle_zocl2_clbk = void (WINAPIV*)(struct _personal_automine_uninstall_circle_zocl*, _personal_automine_uninstall_circle_zoclctor__personal_automine_uninstall_circle_zocl2_ptr);
using _personal_automine_uninstall_circle_zoclsize4_ptr = int (WINAPIV*)(struct _personal_automine_uninstall_circle_zocl*);
using _personal_automine_uninstall_circle_zoclsize4_clbk = int (WINAPIV*)(struct _personal_automine_uninstall_circle_zocl*, _personal_automine_uninstall_circle_zoclsize4_ptr);
}; // end namespace Info
END_ATF_NAMESPACE
| 59.222222 | 266 | 0.839587 | lemkova |
c9c7160376a9a4ec133969578a1479b55cb57477 | 6,076 | cpp | C++ | collection/cp/bcw_codebook-master/Contest/ASC35/pE.cpp | daemonslayer/Notebook | a9880be9bd86955afd6b8f7352822bc18673eda3 | [
"Apache-2.0"
] | 1 | 2019-03-24T13:12:01.000Z | 2019-03-24T13:12:01.000Z | collection/cp/bcw_codebook-master/Contest/ASC35/pE.cpp | daemonslayer/Notebook | a9880be9bd86955afd6b8f7352822bc18673eda3 | [
"Apache-2.0"
] | null | null | null | collection/cp/bcw_codebook-master/Contest/ASC35/pE.cpp | daemonslayer/Notebook | a9880be9bd86955afd6b8f7352822bc18673eda3 | [
"Apache-2.0"
] | null | null | null | #include<bits/stdc++.h>
#include<unistd.h>
using namespace std;
#define FZ(n) memset((n),0,sizeof(n))
#define FMO(n) memset((n),-1,sizeof(n))
#define F first
#define S second
#define PB push_back
#define ALL(x) begin(x),end(x)
#define SZ(x) ((int)(x).size())
#define IOS ios_base::sync_with_stdio(0); cin.tie(0)
#ifdef ONLINE_JUDGE
#define FILEIO(name) \
freopen(name".in", "r", stdin); \
freopen(name".out", "w", stdout);
#else
#define FILEIO(name)
#endif
template<typename A, typename B>
ostream& operator <<(ostream &s, const pair<A,B> &p) {
return s<<"("<<p.first<<","<<p.second<<")";
}
template<typename T>
ostream& operator <<(ostream &s, const vector<T> &c) {
s<<"[ ";
for (auto it : c) s << it << " ";
s<<"]";
return s;
}
// Let's Fight!
struct Bigint{
static const int LEN = 60;
static const int BIGMOD = 10000;
int s;
int vl, v[LEN];
// vector<int> v;
Bigint() : s(1) { vl = 0; }
Bigint(long long a) {
s = 1; vl = 0;
if (a < 0) { s = -1; a = -a; }
while (a) {
push_back(a % BIGMOD);
a /= BIGMOD;
}
}
Bigint(string str) {
s = 1; vl = 0;
int stPos = 0, num = 0;
if (!str.empty() && str[0] == '-') {
stPos = 1;
s = -1;
}
for (int i=SZ(str)-1, q=1; i>=stPos; i--) {
num += (str[i] - '0') * q;
if ((q *= 10) >= BIGMOD) {
push_back(num);
num = 0; q = 1;
}
}
if (num) push_back(num);
}
int len() const {
return vl;
// return SZ(v);
}
bool empty() const { return len() == 0; }
void push_back(int x) {
v[vl++] = x;
// v.PB(x);
}
void pop_back() {
vl--;
// v.pop_back();
}
int back() const {
return v[vl-1];
// return v.back();
}
void n() {
while (!empty() && !back()) pop_back();
}
void resize(int nl) {
vl = nl;
fill(v, v+vl, 0);
// v.resize(nl);
// fill(ALL(v), 0);
}
void print() const {
if (empty()) { putchar('0'); return; }
if (s == -1) putchar('-');
printf("%d", back());
for (int i=len()-2; i>=0; i--) printf("%.4d",v[i]);
}
friend std::ostream& operator << (std::ostream& out, const Bigint &a) {
if (a.empty()) { out << "0"; return out; }
if (a.s == -1) out << "-";
out << a.back();
for (int i=a.len()-2; i>=0; i--) {
char str[10];
snprintf(str, 5, "%.4d", a.v[i]);
out << str;
}
return out;
}
int cp3(const Bigint &b)const {
if (s != b.s) return s > b.s;
if (s == -1) return -(-*this).cp3(-b);
if (len() != b.len()) return len()>b.len()?1:-1;
for (int i=len()-1; i>=0; i--)
if (v[i]!=b.v[i]) return v[i]>b.v[i]?1:-1;
return 0;
}
bool operator < (const Bigint &b)const{ return cp3(b)==-1; }
bool operator == (const Bigint &b)const{ return cp3(b)==0; }
bool operator > (const Bigint &b)const{ return cp3(b)==1; }
Bigint operator - () const {
Bigint r = (*this);
r.s = -r.s;
return r;
}
Bigint operator + (const Bigint &b) const {
if (s == -1) return -(-(*this)+(-b));
if (b.s == -1) return (*this)-(-b);
Bigint r;
int nl = max(len(), b.len());
r.resize(nl + 1);
for (int i=0; i<nl; i++) {
if (i < len()) r.v[i] += v[i];
if (i < b.len()) r.v[i] += b.v[i];
if(r.v[i] >= BIGMOD) {
r.v[i+1] += r.v[i] / BIGMOD;
r.v[i] %= BIGMOD;
}
}
r.n();
return r;
}
Bigint operator - (const Bigint &b) const {
if (s == -1) return -(-(*this)-(-b));
if (b.s == -1) return (*this)+(-b);
if ((*this) < b) return -(b-(*this));
Bigint r;
r.resize(len());
for (int i=0; i<len(); i++) {
r.v[i] += v[i];
if (i < b.len()) r.v[i] -= b.v[i];
if (r.v[i] < 0) {
r.v[i] += BIGMOD;
r.v[i+1]--;
}
}
r.n();
return r;
}
Bigint operator * (const Bigint &b) {
Bigint r;
r.resize(len() + b.len() + 1);
r.s = s * b.s;
for (int i=0; i<len(); i++) {
for (int j=0; j<b.len(); j++) {
r.v[i+j] += v[i] * b.v[j];
if(r.v[i+j] >= BIGMOD) {
r.v[i+j+1] += r.v[i+j] / BIGMOD;
r.v[i+j] %= BIGMOD;
}
}
}
r.n();
return r;
}
Bigint operator / (const Bigint &b) {
Bigint r;
r.resize(max(1, len()-b.len()+1));
int oriS = s;
Bigint b2 = b; // b2 = abs(b)
s = b2.s = r.s = 1;
for (int i=r.len()-1; i>=0; i--) {
int d=0, u=BIGMOD-1;
while(d<u) {
int m = (d+u+1)>>1;
r.v[i] = m;
if((r*b2) > (*this)) u = m-1;
else d = m;
}
r.v[i] = d;
}
s = oriS;
r.s = s * b.s;
r.n();
return r;
}
Bigint operator % (const Bigint &b) {
return (*this)-(*this)/b*b;
}
};
const int MAXN = 514;
const int MAXC = 36;
int B;
bool canuse[MAXC];
int N;
int dig[MAXN];
int dp[MAXN][2*MAXC], prv[MAXN][2*MAXC];
char pchar[MAXN][2*MAXC];
int main() {
FILEIO("digits");
IOS;
string s, s2;
cin>>B>>s>>s2;
for(auto c: s)
{
if(c >= '0' && c <= '9')
canuse[c-'0'] = true;
else
canuse[c-'A'+10] = true;
}
Bigint n(s2);
while(n > 0)
{
dig[N++] = (n % B).v[0];
n = n / B;
}
dp[0][MAXC+dig[0]] = 1;
for(int i=0; i<N; i++)
{
for(int j=-MAXC; j<MAXC; j++)
{
int jj = j + MAXC;
int jm = ((j%B)+B)%B;
if(dp[i][jj] == 0) continue;
// cout<<"dp["<<i<<"]["<<j<<"] = "<<dp[i][jj]<<endl;
for(int c=0; c<MAXC; c++)
{
if(!canuse[c]) continue;
if(c % B != jm) continue;
int nw = dig[i+1] + (j-c)/B + MAXC;
dp[i+1][nw] += dp[i][jj];
if(dp[i+1][nw] > 2) dp[i+1][nw] = 2;
prv[i+1][nw] = jj;
pchar[i+1][nw] = (c>=10 ? 'A'+c-10 : '0'+c);
// cout<<i<<","<<j<<" + "<<c<<" => "<<i+1<<","<<nw-MAXC<<endl;
}
}
}
int z = dp[N][MAXC];
if(z == 0)
cout<<"Impossible"<<endl;
else
{
if(z == 1)
cout<<"Unique"<<endl;
else
cout<<"Ambiguous"<<endl;
string ss = "";
int pos = MAXC;
for(int i=N; i>0; i--)
{
ss.PB(pchar[i][pos]);
pos = prv[i][pos];
}
while(ss.size()>=2 && ss[0] == '0')
ss = ss.substr(1);
cout<<ss<<endl;
}
return 0;
}
| 21.170732 | 73 | 0.453588 | daemonslayer |
c9c9e62749f9f582f2ed451c25f411f88b6c5f96 | 12,936 | cpp | C++ | android/android_9/frameworks/av/media/mtp/tests/MtpFfsHandle_test.cpp | yakuizhao/intel-vaapi-driver | b2bb0383352694941826543a171b557efac2219b | [
"MIT"
] | null | null | null | android/android_9/frameworks/av/media/mtp/tests/MtpFfsHandle_test.cpp | yakuizhao/intel-vaapi-driver | b2bb0383352694941826543a171b557efac2219b | [
"MIT"
] | null | null | null | android/android_9/frameworks/av/media/mtp/tests/MtpFfsHandle_test.cpp | yakuizhao/intel-vaapi-driver | b2bb0383352694941826543a171b557efac2219b | [
"MIT"
] | 2 | 2021-07-08T07:42:11.000Z | 2021-07-09T21:56:10.000Z | /*
* Copyright 2016 The Android Open Source Project
*
* 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.
*/
#define LOG_TAG "MtpFfsHandle_test.cpp"
#include <android-base/unique_fd.h>
#include <android-base/test_utils.h>
#include <fcntl.h>
#include <gtest/gtest.h>
#include <memory>
#include <random>
#include <string>
#include <unistd.h>
#include <log/log.h>
#include "MtpDescriptors.h"
#include "MtpFfsHandle.h"
#include "MtpFfsCompatHandle.h"
namespace android {
constexpr int TEST_PACKET_SIZE = 500;
constexpr int SMALL_MULT = 30;
constexpr int MED_MULT = 510;
static const std::string dummyDataStr =
"/*\n * Copyright 2015 The Android Open Source Project\n *\n * Licensed un"
"der the Apache License, Version 2.0 (the \"License\");\n * you may not us"
"e this file except in compliance with the License.\n * You may obtain a c"
"opy of the License at\n *\n * http://www.apache.org/licenses/LICENSE"
"-2.0\n *\n * Unless required by applicable law or agreed to in writing, s"
"oftware\n * distributed under the License is distributed on an \"AS IS\" "
"BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express o"
"r im";
/**
* Functional tests for the MtpFfsHandle class. Ensures header and data integrity
* by mocking ffs endpoints as pipes to capture input / output.
*/
template <class T>
class MtpFfsHandleTest : public ::testing::Test {
protected:
std::unique_ptr<MtpFfsHandle> handle;
// Pipes for reading endpoint data
android::base::unique_fd control;
android::base::unique_fd bulk_in;
android::base::unique_fd bulk_out;
android::base::unique_fd intr;
TemporaryFile dummy_file;
MtpFfsHandleTest() {
int fd[2];
handle = std::make_unique<T>(-1);
EXPECT_EQ(pipe(fd), 0);
control.reset(fd[0]);
handle->mControl.reset(fd[1]);
EXPECT_EQ(pipe(fd), 0);
EXPECT_EQ(fcntl(fd[0], F_SETPIPE_SZ, 1048576), 1048576);
bulk_in.reset(fd[0]);
handle->mBulkIn.reset(fd[1]);
EXPECT_EQ(pipe(fd), 0);
EXPECT_EQ(fcntl(fd[0], F_SETPIPE_SZ, 1048576), 1048576);
bulk_out.reset(fd[1]);
handle->mBulkOut.reset(fd[0]);
EXPECT_EQ(pipe(fd), 0);
intr.reset(fd[0]);
handle->mIntr.reset(fd[1]);
EXPECT_EQ(handle->start(false), 0);
}
~MtpFfsHandleTest() {
handle->close();
}
};
typedef ::testing::Types<MtpFfsHandle, MtpFfsCompatHandle> mtpHandles;
TYPED_TEST_CASE(MtpFfsHandleTest, mtpHandles);
TYPED_TEST(MtpFfsHandleTest, testMtpControl) {
EXPECT_TRUE(this->handle->writeDescriptors(false));
struct desc_v2 desc;
struct functionfs_strings strings;
EXPECT_EQ(read(this->control, &desc, sizeof(desc)), (long)sizeof(desc));
EXPECT_EQ(read(this->control, &strings, sizeof(strings)), (long)sizeof(strings));
EXPECT_TRUE(std::memcmp(&desc, &mtp_desc_v2, sizeof(desc)) == 0);
EXPECT_TRUE(std::memcmp(&strings, &mtp_strings, sizeof(strings)) == 0);
}
TYPED_TEST(MtpFfsHandleTest, testPtpControl) {
EXPECT_TRUE(this->handle->writeDescriptors(true));
struct desc_v2 desc;
struct functionfs_strings strings;
EXPECT_EQ(read(this->control, &desc, sizeof(desc)), (long)sizeof(desc));
EXPECT_EQ(read(this->control, &strings, sizeof(strings)), (long)sizeof(strings));
EXPECT_TRUE(std::memcmp(&desc, &ptp_desc_v2, sizeof(desc)) == 0);
EXPECT_TRUE(std::memcmp(&strings, &mtp_strings, sizeof(strings)) == 0);
}
TYPED_TEST(MtpFfsHandleTest, testRead) {
EXPECT_EQ(write(this->bulk_out, dummyDataStr.c_str(), TEST_PACKET_SIZE), TEST_PACKET_SIZE);
char buf[TEST_PACKET_SIZE + 1];
buf[TEST_PACKET_SIZE] = '\0';
EXPECT_EQ(this->handle->read(buf, TEST_PACKET_SIZE), TEST_PACKET_SIZE);
EXPECT_STREQ(buf, dummyDataStr.c_str());
}
TYPED_TEST(MtpFfsHandleTest, testReadLarge) {
std::stringstream ss;
int size = TEST_PACKET_SIZE * MED_MULT;
char buf[size + 1];
buf[size] = '\0';
for (int i = 0; i < MED_MULT; i++)
ss << dummyDataStr;
EXPECT_EQ(write(this->bulk_out, ss.str().c_str(), size), size);
EXPECT_EQ(this->handle->read(buf, size), size);
EXPECT_STREQ(buf, ss.str().c_str());
}
TYPED_TEST(MtpFfsHandleTest, testWrite) {
char buf[TEST_PACKET_SIZE + 1];
buf[TEST_PACKET_SIZE] = '\0';
EXPECT_EQ(this->handle->write(dummyDataStr.c_str(), TEST_PACKET_SIZE), TEST_PACKET_SIZE);
EXPECT_EQ(read(this->bulk_in, buf, TEST_PACKET_SIZE), TEST_PACKET_SIZE);
EXPECT_STREQ(buf, dummyDataStr.c_str());
}
TYPED_TEST(MtpFfsHandleTest, testWriteLarge) {
std::stringstream ss;
int size = TEST_PACKET_SIZE * MED_MULT;
char buf[size + 1];
buf[size] = '\0';
for (int i = 0; i < MED_MULT; i++)
ss << dummyDataStr;
EXPECT_EQ(this->handle->write(ss.str().c_str(), size), size);
EXPECT_EQ(read(this->bulk_in, buf, size), size);
EXPECT_STREQ(buf, ss.str().c_str());
}
TYPED_TEST(MtpFfsHandleTest, testReceiveFileEmpty) {
std::stringstream ss;
mtp_file_range mfr;
int size = 0;
char buf[size + 1];
buf[size] = '\0';
mfr.offset = 0;
mfr.length = size;
mfr.fd = this->dummy_file.fd;
EXPECT_EQ(write(this->bulk_out, ss.str().c_str(), size), size);
EXPECT_EQ(this->handle->receiveFile(mfr, false), 0);
EXPECT_EQ(read(this->dummy_file.fd, buf, size), size);
}
TYPED_TEST(MtpFfsHandleTest, testReceiveFileSmall) {
std::stringstream ss;
mtp_file_range mfr;
int size = TEST_PACKET_SIZE * SMALL_MULT;
char buf[size + 1];
buf[size] = '\0';
mfr.offset = 0;
mfr.length = size;
mfr.fd = this->dummy_file.fd;
for (int i = 0; i < SMALL_MULT; i++)
ss << dummyDataStr;
EXPECT_EQ(write(this->bulk_out, ss.str().c_str(), size), size);
EXPECT_EQ(this->handle->receiveFile(mfr, false), 0);
EXPECT_EQ(read(this->dummy_file.fd, buf, size), size);
EXPECT_STREQ(buf, ss.str().c_str());
}
TYPED_TEST(MtpFfsHandleTest, testReceiveFileMed) {
std::stringstream ss;
mtp_file_range mfr;
int size = TEST_PACKET_SIZE * MED_MULT;
char buf[size + 1];
buf[size] = '\0';
mfr.offset = 0;
mfr.length = size;
mfr.fd = this->dummy_file.fd;
for (int i = 0; i < MED_MULT; i++)
ss << dummyDataStr;
EXPECT_EQ(write(this->bulk_out, ss.str().c_str(), size), size);
EXPECT_EQ(this->handle->receiveFile(mfr, false), 0);
EXPECT_EQ(read(this->dummy_file.fd, buf, size), size);
EXPECT_STREQ(buf, ss.str().c_str());
}
TYPED_TEST(MtpFfsHandleTest, testReceiveFileMedPartial) {
std::stringstream ss;
mtp_file_range mfr;
int size = TEST_PACKET_SIZE * MED_MULT;
char buf[size + 1];
buf[size] = '\0';
mfr.fd = this->dummy_file.fd;
for (int i = 0; i < MED_MULT; i++)
ss << dummyDataStr;
EXPECT_EQ(write(this->bulk_out, ss.str().c_str(), size), size);
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, TEST_PACKET_SIZE);
int offset = 0;
while (offset != size) {
mfr.offset = offset;
int length = std::min(size - offset, dis(gen));
mfr.length = length;
EXPECT_EQ(this->handle->receiveFile(mfr, false), 0);
offset += length;
}
EXPECT_EQ(read(this->dummy_file.fd, buf, size), size);
EXPECT_STREQ(buf, ss.str().c_str());
}
TYPED_TEST(MtpFfsHandleTest, testSendFileSmall) {
std::stringstream ss;
mtp_file_range mfr;
mfr.command = 42;
mfr.transaction_id = 1337;
mfr.offset = 0;
int size = TEST_PACKET_SIZE * SMALL_MULT;
char buf[size + sizeof(mtp_data_header) + 1];
buf[size + sizeof(mtp_data_header)] = '\0';
mfr.length = size;
mfr.fd = this->dummy_file.fd;
for (int i = 0; i < SMALL_MULT; i++)
ss << dummyDataStr;
EXPECT_EQ(write(this->dummy_file.fd, ss.str().c_str(), size), size);
EXPECT_EQ(this->handle->sendFile(mfr), 0);
EXPECT_EQ(read(this->bulk_in, buf, size + sizeof(mtp_data_header)),
static_cast<long>(size + sizeof(mtp_data_header)));
struct mtp_data_header *header = reinterpret_cast<struct mtp_data_header*>(buf);
EXPECT_STREQ(buf + sizeof(mtp_data_header), ss.str().c_str());
EXPECT_EQ(header->length, static_cast<unsigned int>(size + sizeof(mtp_data_header)));
EXPECT_EQ(header->type, static_cast<unsigned int>(2));
EXPECT_EQ(header->command, static_cast<unsigned int>(42));
EXPECT_EQ(header->transaction_id, static_cast<unsigned int>(1337));
}
TYPED_TEST(MtpFfsHandleTest, testSendFileMed) {
std::stringstream ss;
mtp_file_range mfr;
mfr.command = 42;
mfr.transaction_id = 1337;
mfr.offset = 0;
int size = TEST_PACKET_SIZE * MED_MULT;
char buf[size + sizeof(mtp_data_header) + 1];
buf[size + sizeof(mtp_data_header)] = '\0';
mfr.length = size;
mfr.fd = this->dummy_file.fd;
for (int i = 0; i < MED_MULT; i++)
ss << dummyDataStr;
EXPECT_EQ(write(this->dummy_file.fd, ss.str().c_str(), size), size);
EXPECT_EQ(this->handle->sendFile(mfr), 0);
EXPECT_EQ(read(this->bulk_in, buf, size + sizeof(mtp_data_header)),
static_cast<long>(size + sizeof(mtp_data_header)));
struct mtp_data_header *header = reinterpret_cast<struct mtp_data_header*>(buf);
EXPECT_STREQ(buf + sizeof(mtp_data_header), ss.str().c_str());
EXPECT_EQ(header->length, static_cast<unsigned int>(size + sizeof(mtp_data_header)));
EXPECT_EQ(header->type, static_cast<unsigned int>(2));
EXPECT_EQ(header->command, static_cast<unsigned int>(42));
EXPECT_EQ(header->transaction_id, static_cast<unsigned int>(1337));
}
TYPED_TEST(MtpFfsHandleTest, testSendFileMedPartial) {
std::stringstream ss;
mtp_file_range mfr;
mfr.fd = this->dummy_file.fd;
mfr.command = 42;
mfr.transaction_id = 1337;
int size = TEST_PACKET_SIZE * MED_MULT;
char buf[size + 1];
buf[size] = '\0';
for (int i = 0; i < MED_MULT; i++)
ss << dummyDataStr;
EXPECT_EQ(write(this->dummy_file.fd, ss.str().c_str(), size), size);
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, TEST_PACKET_SIZE);
int offset = 0;
while (offset != size) {
mfr.offset = offset;
int length = std::min(size - offset, dis(gen));
mfr.length = length;
char temp_buf[length + sizeof(mtp_data_header)];
EXPECT_EQ(this->handle->sendFile(mfr), 0);
EXPECT_EQ(read(this->bulk_in, temp_buf, length + sizeof(mtp_data_header)),
static_cast<long>(length + sizeof(mtp_data_header)));
struct mtp_data_header *header = reinterpret_cast<struct mtp_data_header*>(temp_buf);
EXPECT_EQ(header->length, static_cast<unsigned int>(length + sizeof(mtp_data_header)));
EXPECT_EQ(header->type, static_cast<unsigned int>(2));
EXPECT_EQ(header->command, static_cast<unsigned int>(42));
EXPECT_EQ(header->transaction_id, static_cast<unsigned int>(1337));
memcpy(buf + offset, temp_buf + sizeof(mtp_data_header), length);
offset += length;
}
EXPECT_STREQ(buf, ss.str().c_str());
}
TYPED_TEST(MtpFfsHandleTest, testSendFileEmpty) {
mtp_file_range mfr;
mfr.command = 42;
mfr.transaction_id = 1337;
mfr.offset = 0;
int size = 0;
char buf[size + sizeof(mtp_data_header) + 1];
buf[size + sizeof(mtp_data_header)] = '\0';
mfr.length = size;
mfr.fd = this->dummy_file.fd;
EXPECT_EQ(this->handle->sendFile(mfr), 0);
EXPECT_EQ(read(this->bulk_in, buf, size + sizeof(mtp_data_header)),
static_cast<long>(size + sizeof(mtp_data_header)));
struct mtp_data_header *header = reinterpret_cast<struct mtp_data_header*>(buf);
EXPECT_EQ(header->length, static_cast<unsigned int>(size + sizeof(mtp_data_header)));
EXPECT_EQ(header->type, static_cast<unsigned int>(2));
EXPECT_EQ(header->command, static_cast<unsigned int>(42));
EXPECT_EQ(header->transaction_id, static_cast<unsigned int>(1337));
}
TYPED_TEST(MtpFfsHandleTest, testSendEvent) {
struct mtp_event event;
event.length = TEST_PACKET_SIZE;
event.data = const_cast<char*>(dummyDataStr.c_str());
char buf[TEST_PACKET_SIZE + 1];
buf[TEST_PACKET_SIZE] = '\0';
this->handle->sendEvent(event);
read(this->intr, buf, TEST_PACKET_SIZE);
EXPECT_STREQ(buf, dummyDataStr.c_str());
}
} // namespace android
| 33.254499 | 95 | 0.666976 | yakuizhao |
c9cf419ddd7f079c3362c7d339281faab65c63b3 | 745 | inl | C++ | src/ServiceLocator.inl | HumpaLumpa007/LowPolyEngine | 800cfa84f6113424a2643a4a99fe214195e45cd5 | [
"MIT"
] | 6 | 2017-11-20T15:10:17.000Z | 2018-03-07T14:59:25.000Z | src/ServiceLocator.inl | ClemensGerstung/LowPolyEngine | 800cfa84f6113424a2643a4a99fe214195e45cd5 | [
"MIT"
] | null | null | null | src/ServiceLocator.inl | ClemensGerstung/LowPolyEngine | 800cfa84f6113424a2643a4a99fe214195e45cd5 | [
"MIT"
] | 1 | 2021-03-03T12:09:42.000Z | 2021-03-03T12:09:42.000Z | #pragma once
template <typename TService>
std::weak_ptr<TService> lpe::Locator<TService>::Get() const
{
return service;
}
//template <typename TService, typename TNullService>
//template <typename>
//void src::Locator<TService, TNullService>::Provide(TService* service)
//{
// if (service == nullptr)
// {
// this->service.reset(&this->nullService);
// }
// else
// {
// this->service = std::make_shared<TService>(*service);
// }
//}
template<typename TService>
template<typename TServiceImpl, typename>
void lpe::Locator<TService>::Provide(TServiceImpl * service)
{
if (service == nullptr)
{
/*this->service.reset(&this->nullService);*/
}
else
{
this->service = std::make_shared<TServiceImpl>(*service);
}
} | 21.285714 | 71 | 0.673826 | HumpaLumpa007 |
c9d2a8e4d445d19f18c2b94e84370e933d1293fb | 1,070 | cc | C++ | vendor/chromium/base/process/process_handle_fuchsia.cc | thorium-cfx/fivem | 587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c | [
"MIT"
] | 5,411 | 2017-04-14T08:57:56.000Z | 2022-03-30T19:35:15.000Z | vendor/chromium/base/process/process_handle_fuchsia.cc | big-rip/fivem-1 | c08af22110802e77816dfdde29df1662f8dea563 | [
"MIT"
] | 802 | 2017-04-21T14:18:36.000Z | 2022-03-31T21:20:48.000Z | vendor/chromium/base/process/process_handle_fuchsia.cc | big-rip/fivem-1 | c08af22110802e77816dfdde29df1662f8dea563 | [
"MIT"
] | 2,011 | 2017-04-14T09:44:15.000Z | 2022-03-31T15:40:39.000Z | // Copyright 2017 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 "base/process/process_handle.h"
#include <zircon/process.h>
#include <zircon/status.h>
#include <zircon/syscalls.h>
#include "base/logging.h"
namespace base {
ProcessId GetCurrentProcId() {
return GetProcId(GetCurrentProcessHandle());
}
ProcessHandle GetCurrentProcessHandle() {
// Note that zx_process_self() returns a real handle, and ownership is not
// transferred to the caller (i.e. this should never be closed).
return zx_process_self();
}
ProcessId GetProcId(ProcessHandle process) {
zx_info_handle_basic_t basic;
zx_status_t status = zx_object_get_info(process, ZX_INFO_HANDLE_BASIC, &basic,
sizeof(basic), nullptr, nullptr);
if (status != ZX_OK) {
DLOG(ERROR) << "zx_object_get_info failed: "
<< zx_status_get_string(status);
return ZX_KOID_INVALID;
}
return basic.koid;
}
} // namespace base
| 28.157895 | 80 | 0.706542 | thorium-cfx |
c9d2d6f7e2aae925899a9b18fde73b32451fed98 | 2,123 | cpp | C++ | GpuMiner/XDagCore/XTaskWrapper.cpp | swordlet/DaggerAOCLminer | f4fa5b5aec4942863c234463d3aeb244c472eae4 | [
"MIT"
] | 5 | 2019-03-08T11:26:35.000Z | 2022-01-15T12:53:57.000Z | GpuMiner/XDagCore/XTaskWrapper.cpp | swordlet/DaggerAOCLminer | f4fa5b5aec4942863c234463d3aeb244c472eae4 | [
"MIT"
] | null | null | null | GpuMiner/XDagCore/XTaskWrapper.cpp | swordlet/DaggerAOCLminer | f4fa5b5aec4942863c234463d3aeb244c472eae4 | [
"MIT"
] | 6 | 2019-03-07T08:46:33.000Z | 2022-02-15T17:38:18.000Z | // Task data
// Author: Evgeniy Sukhomlinov
// 2018
// Licensed under GNU General Public License, Version 3. See the LICENSE file.
#include "XTaskWrapper.h"
#include "Core/Log.h"
#include "Utils/Utils.h"
#include "Utils/Random.h"
#include "Hash/sha256_mod.h"
#define bytereverse(x) ( ((x) << 24) | (((x) << 8) & 0x00ff0000) | (((x) >> 8) & 0x0000ff00) | ((x) >> 24) )
XTaskWrapper::XTaskWrapper()
:_taskIndex(0),
_isShareFound(false)
{
}
XTaskWrapper::~XTaskWrapper()
{
}
void XTaskWrapper::FillAndPrecalc(xdag_field* data, xdag_hash_t addressHash)
{
_task.main_time = GetMainTime();
XHash::SetHashState(&_task.ctx, data[0].data, sizeof(struct xdag_block) - 2 * sizeof(struct xdag_field));
XHash::HashUpdate(&_task.ctx, data[1].data, sizeof(struct xdag_field));
XHash::HashUpdate(&_task.ctx, addressHash, sizeof(xdag_hashlow_t));
CRandom::FillRandomArray((uint8_t*)&_task.nonce.amount, sizeof(uint64_t));
memcpy(_task.nonce.data, addressHash, sizeof(xdag_hashlow_t));
memcpy(_task.lastfield.data, _task.nonce.data, sizeof(xdag_hash_t));
//we manually set the initial target difficulty of shares
memset(_task.minhash.data, 0xff, 24);
_task.minhash.data[3] = 0x000008ffffffffff;
//some precalculations on task data for GPU mining
shamod::PrecalcState(_task.ctx.state, _task.ctx.data, _preCalcState);
for(uint32_t i = 0; i < 14; ++i)
{
_reversedData[i] = bytereverse(((uint32_t*)_task.ctx.data)[i]);
}
}
void XTaskWrapper::SetShare(xdag_hash_t last, xdag_hash_t hash)
{
if(XHash::CompareHashes(hash, _task.minhash.data) < 0)
{
_shareMutex.lock();
if(XHash::CompareHashes(hash, _task.minhash.data) < 0)
{
memcpy(_task.minhash.data, hash, sizeof(xdag_hash_t));
memcpy(_task.lastfield.data, last, sizeof(xdag_hash_t));
_isShareFound = true;
}
_shareMutex.unlock();
}
}
void XTaskWrapper::DumpTask()
{
clog(XDag::DebugChannel) << "MinHash " << HashToHexString(_task.minhash.data);
}
| 31.220588 | 110 | 0.651908 | swordlet |
c9d636119049f8425a753a8b30ea887a9659b8b2 | 18,057 | cpp | C++ | src/asm/RegisterFixes.cpp | doe300/VC4C | f69ba1f7114be0e97de421301c788176daafef29 | [
"MIT"
] | 111 | 2017-11-02T14:46:45.000Z | 2022-03-15T21:32:59.000Z | src/asm/RegisterFixes.cpp | doe300/VC4C | f69ba1f7114be0e97de421301c788176daafef29 | [
"MIT"
] | 139 | 2017-10-09T07:39:01.000Z | 2021-11-20T15:31:27.000Z | src/asm/RegisterFixes.cpp | doe300/VC4C | f69ba1f7114be0e97de421301c788176daafef29 | [
"MIT"
] | 33 | 2017-10-10T10:19:58.000Z | 2022-02-27T15:59:50.000Z | /*
* Author: doe300
*
* See the file "LICENSE" for the full license governing this code.
*/
#include "RegisterFixes.h"
#include "../Method.h"
#include "../analysis/ControlFlowGraph.h"
#include "../analysis/LivenessAnalysis.h"
#include "../intermediate/VectorHelper.h"
#include "../intermediate/operators.h"
#include "GraphColoring.h"
using namespace vc4c;
using namespace vc4c::qpu_asm;
using namespace vc4c::operators;
// TODO make steps: 1. only small fixes, 2. group locals, "spill" to vector, rematerialize, 3. spill into VPM
const std::vector<std::pair<std::string, RegisterFixupStep>> qpu_asm::FIXUP_STEPS = {
// For the first two steps, try to run our in-graph fix-ups
{"Small rewrites",
[](Method& method, const Configuration& config, GraphColoring& coloredGraph) -> FixupResult {
// even though we might have fixed some register errors, these fixed make sure the colored graph is up to
// date with the changes, so we do not need to recreate it
return coloredGraph.fixErrors() ? FixupResult::ALL_FIXED : FixupResult::FIXES_APPLIED_KEEP_GRAPH;
}},
{"Small rewrites",
[](Method& method, const Configuration& config, GraphColoring& coloredGraph) -> FixupResult {
// same as above
return coloredGraph.fixErrors() ? FixupResult::ALL_FIXED : FixupResult::FIXES_APPLIED_KEEP_GRAPH;
}},
// Try to group pointer parameters into vectors to save registers used
{"Group parameters", groupParameters},
// Try to group any scalar/pointer local into vectors to save registers used
{"Group scalar locals (conversative)",
[](Method& method, const Configuration& config, GraphColoring& coloredGraph) -> FixupResult {
// In the first run, skip e.g. locals which are used inside of (nested) loops
return groupScalarLocals(method, config, coloredGraph, true);
}},
{"Small rewrites",
[](Method& method, const Configuration& config, GraphColoring& coloredGraph) -> FixupResult {
// same as above
return coloredGraph.fixErrors() ? FixupResult::ALL_FIXED : FixupResult::FIXES_APPLIED_KEEP_GRAPH;
}},
{"Group scalar locals (aggressive)",
[](Method& method, const Configuration& config, GraphColoring& coloredGraph) -> FixupResult {
return groupScalarLocals(method, config, coloredGraph, false);
}},
};
/**
* We currently have no concept of "vector of pointers", but is some cases we have a pointer value (which is by default
* a scalar value) where we use the upper vector elements (if the value is a splat value), e.g. to calculate the
* addresses of the upper TMU elements to load.
* Since combining multiple "scalar" pointer locals into a single SIMD vector and then extraction the corresponding
* elements again destroys the splat property, we need to check for such usage.
*/
static bool isUsedAsSplatValue(const Local* loc)
{
FastSet<const Local*> openSet;
FastSet<const Local*> closedSet;
openSet.emplace(loc);
while(!openSet.empty())
{
auto local = *openSet.begin();
closedSet.emplace(local);
openSet.erase(openSet.begin());
bool multipleElementsMayBeUsed = false;
local->forUsers(LocalUse::Type::READER, [&](const LocalUser* reader) {
// TODO can be improved by e.g. checking for single-element insertion into other local (if we only
// insert 0th element, we have no problem)
if(reader->checkOutputRegister() & &Register::isTextureMemoryUnit)
multipleElementsMayBeUsed = true;
else if(reader->checkOutputRegister() & &Register::isSpecialFunctionsUnit)
multipleElementsMayBeUsed = true;
else if(auto outputLoc = reader->checkOutputLocal())
{
if(closedSet.find(outputLoc) == closedSet.end())
openSet.emplace(outputLoc);
}
});
if(multipleElementsMayBeUsed)
return true;
}
return false;
}
FixupResult qpu_asm::groupParameters(Method& method, const Configuration& config, GraphColoring& coloredGraph)
{
analysis::LocalUsageRangeAnalysis localUsageRangeAnalysis(&coloredGraph.getLivenessAnalysis());
localUsageRangeAnalysis(method);
bool somethingChanged = false;
FastAccessList<const Parameter*> parametersToBeGrouped;
for(const auto& entry : localUsageRangeAnalysis.getOverallUsages())
{
if(entry.numLoops > 0)
continue;
// TODO some better values?
if(entry.numAccesses > 3)
// don't group parameter with too many accessed, would need to rotate too often
continue;
if(entry.numInstructions <= 32)
// don't group parameter with too short a usage range, we would likely not gain anything
continue;
if(auto param = entry.local->as<Parameter>())
{
if(!param->type.getPointerType())
continue;
if(!dynamic_cast<const intermediate::ExtendedInstruction*>(param->getSingleWriter()))
// this should not happen for any parameter, but just to be sure
continue;
parametersToBeGrouped.emplace_back(param);
}
}
CPPLOG_LAZY(logging::Level::DEBUG,
log << "Trying to group " << parametersToBeGrouped.size() << " parameters..." << logging::endl);
Optional<Value> groupedValue = NO_VALUE;
uint8_t groupIndex = 0;
// Creating this lookup map is more efficient than searching every instruction in the whole kernel function
FastMap<const Parameter*, std::pair<InstructionWalker, FastAccessList<InstructionWalker>>> instructionMapping;
for(auto& block : method)
{
auto it = block.walk();
while(!it.isEndOfBlock())
{
for(auto param : parametersToBeGrouped)
{
if(it->writesLocal(param))
instructionMapping[param].first = it;
if(it->readsLocal(param))
instructionMapping[param].second.emplace_back(it);
}
it.nextInBlock();
}
}
// the parameter at which to stop if a new group would be created
auto endParam = parametersToBeGrouped.end();
if(!parametersToBeGrouped.empty() && parametersToBeGrouped.size() < 3)
endParam = parametersToBeGrouped.begin();
else
endParam = parametersToBeGrouped.end() - 3;
for(auto paramIt = parametersToBeGrouped.begin(); paramIt != parametersToBeGrouped.end(); ++paramIt)
{
auto mappingIt = instructionMapping.find(*paramIt);
if(mappingIt == instructionMapping.end() || mappingIt->second.first.isEndOfBlock() ||
mappingIt->second.second.empty())
{
CPPLOG_LAZY(logging::Level::DEBUG,
log << "Skipping grouping of parameter: " << (*paramIt)->to_string() << logging::endl);
continue;
}
if(!groupedValue || groupIndex == NATIVE_VECTOR_SIZE)
{
if(paramIt >= endParam)
// don't create an extra group for the last few parameters left
break;
// XXX actual type should be <16 x void*>, but can't form vector of pointers
groupedValue = method.addNewLocal(TYPE_INT32.toVectorType(NATIVE_VECTOR_SIZE), "%param_group");
groupIndex = 0;
}
CPPLOG_LAZY(logging::Level::DEBUG,
log << "Grouping parameter '" << (*paramIt)->to_string() << "' into " << groupedValue->to_string()
<< " at position: " << static_cast<uint32_t>(groupIndex) << logging::endl);
auto it = mappingIt->second.first;
auto cond = assignNop(it) = selectSIMDElement(groupIndex);
it.get<intermediate::ExtendedInstruction>()->setCondition(cond);
it->setOutput(groupedValue);
for(auto& readerIt : mappingIt->second.second)
{
// Doing a full vector rotation forces the now long-living parameter group into accumulator!! So create we a
// temporary copy right away, since we will need to do so anyway
auto tmpGroup = assign(readerIt, groupedValue->type, std::string{(*paramIt)->name}) = *groupedValue;
auto tmp = method.addNewLocal((*paramIt)->type, (*paramIt)->name);
readerIt = intermediate::insertVectorExtraction(
readerIt, method, tmpGroup, Value(SmallImmediate(groupIndex), TYPE_INT8), tmp);
readerIt->replaceLocal(*paramIt, tmp);
if(isUsedAsSplatValue(tmp.local()))
{
// we need to recreate the splat property by replicating the value
auto splatTmp = method.addNewLocal((*paramIt)->type, (*paramIt)->name);
readerIt = intermediate::insertReplication(readerIt, tmp, splatTmp);
readerIt->replaceLocal(tmp.local(), splatTmp);
}
}
// paramIt is incremented in the loop header
++groupIndex;
somethingChanged = true;
}
return somethingChanged ? FixupResult::FIXES_APPLIED_RECREATE_GRAPH : FixupResult::NOTHING_FIXED;
}
static std::pair<const Local*, uint8_t> reserveGroupSpace(
Method& method, FastMap<const Local*, std::array<const Local*, NATIVE_VECTOR_SIZE>>& groups, const Local* loc)
{
for(auto& group : groups)
{
for(std::size_t i = 0; i < group.second.size(); ++i)
{
if(group.second[i] == nullptr)
{
group.second[i] = loc;
return std::make_pair(group.first, static_cast<uint8_t>(i));
}
}
}
// insert new group
auto group = method.addNewLocal(TYPE_INT32.toVectorType(NATIVE_VECTOR_SIZE), "%local_group").local();
groups[group].fill(nullptr);
groups[group][0] = loc;
return std::make_pair(group, 0);
}
FixupResult qpu_asm::groupScalarLocals(
Method& method, const Configuration& config, const GraphColoring& coloredGraph, bool runConservative)
{
FastMap<const Local*, InstructionWalker> candidateLocals;
FastMap<const Local*, FastSet<InstructionWalker>> localReaders;
for(auto& block : method)
{
FastMap<const Local*, InstructionWalker> localsWrittenInBlock;
// the value is a list (as in not-unique) on purpose to keep the count correct for i.e. combined instructions
FastMap<const Local*, FastAccessList<InstructionWalker>> localsReadInBlock;
for(auto it = block.walk(); !it.isEndOfBlock(); it.nextInBlock())
{
if(!it.get())
continue;
it->forUsedLocals(
[&](const Local* loc, LocalUse::Type use, const intermediate::IntermediateInstruction& instr) {
if(loc->type.isLabelType() || (!loc->type.isScalarType() && !loc->type.getPointerType()))
// XXX out of simplicity, for now only handle scalar values
return;
if(has_flag(use, LocalUse::Type::WRITER))
{
if(!instr.hasConditionalExecution() && loc->getSingleWriter() == &instr &&
!instr.hasDecoration(intermediate::InstructionDecorations::PHI_NODE))
// track only unconditionally written locals with a single writer
// XXX otherwise we would need to write-back the updated result into the group vector
// also don't track phi-writes, since they are always used immediately after the branch
// destination label and therefore don't really have a large usage range
localsWrittenInBlock.emplace(loc, it);
}
if(has_flag(use, LocalUse::Type::READER))
{
localsReadInBlock[loc].emplace_back(it);
localReaders[loc].emplace(it);
}
});
}
for(auto& pair : localsWrittenInBlock)
{
auto readIt = localsReadInBlock.find(pair.first);
if(readIt != localsReadInBlock.end())
{
if(readIt->second.size() == pair.first->countUsers(LocalUse::Type::READER))
// exclude all locals which have all readers inside the block they are written in - locals which are
// only live inside a single block
// TODO to simplify, could skip all locals which have any readers inside the block they are
// written?! this would reduce the number of locals grouped and therefore the number of registers
// freed, but also the number of instructions inserted
continue;
if(!readIt->second.empty())
{
// if the local is read inside this and other blocks, do some optimization
// 1. remove all reads inside this block from the tracked reads, so we do not spill/rematerialize
// inside a single block
auto& readers = localReaders[pair.first];
for(auto& inst : readIt->second)
readers.erase(inst);
// 2. move the position to insert the spilling code after the last read
candidateLocals.emplace(pair.first, readIt->second.back());
}
}
candidateLocals.emplace(pair);
}
}
if(runConservative)
{
analysis::LocalUsageRangeAnalysis localUsageRangeAnalysis(&coloredGraph.getLivenessAnalysis());
localUsageRangeAnalysis(method);
for(const auto& entry : localUsageRangeAnalysis.getOverallUsages())
{
auto candIt = candidateLocals.find(entry.local);
if(candIt == candidateLocals.end())
continue;
if(entry.numLoops > 1)
// skip locals used in nested loops
candidateLocals.erase(candIt);
else if(entry.numAccesses > 8)
// skip locals with too many accesses
candidateLocals.erase(candIt);
}
}
if(candidateLocals.size() < 4)
// for 0 and 1 locals this does not help anything at all anyway...
return FixupResult::NOTHING_FIXED;
// map of "original" local -> group local (+ index in group) where it is located in
FastMap<const Local*, std::pair<const Local*, uint8_t>> currentlyGroupedLocals;
// map of group local -> contained "original" locals and their positions
FastMap<const Local*, std::array<const Local*, NATIVE_VECTOR_SIZE>> groups;
for(auto& entry : candidateLocals)
{
// allocate an element in our spill register
auto pos = reserveGroupSpace(method, groups, entry.first);
currentlyGroupedLocals.emplace(entry.first, pos);
CPPLOG_LAZY(logging::Level::DEBUG,
log << "Grouping local '" << entry.first->to_string() << "' into " << pos.first->to_string() << " at index "
<< static_cast<unsigned>(pos.second) << logging::endl);
// after the local write (or the last read within the writing block), insert the spill code
// we spill a copy to not force the local to an accumulator (since we do full vector rotation)
{
auto spillIt = entry.second.nextInBlock();
auto tmpValue = assign(spillIt, entry.first->type) = entry.first->createReference();
spillIt = intermediate::insertVectorInsertion(
spillIt, method, pos.first->createReference(), Value(SmallImmediate(pos.second), TYPE_INT8), tmpValue);
if(!spillIt.isEndOfBlock() && spillIt.get() && spillIt->readsLocal(pos.first))
// if we happen to insert a write just before a read of the same container, insert a NOP to prevent the
// container to be forced to an accumulator
nop(spillIt, intermediate::DelayType::WAIT_REGISTER);
}
// before all reads (not located in the writing block), insert a dematerialization and use a new temporary
// local in the read
auto& readers = localReaders[entry.first];
for(auto reader : readers)
{
auto checkIt = reader.copy().previousInBlock();
if(!checkIt.isEndOfBlock() && checkIt.get() && checkIt->writesLocal(pos.first))
// if we happen to insert a read just after a write of the same container, insert a NOP to prevent the
// container to be forced to an accumulator
nop(reader, intermediate::DelayType::WAIT_REGISTER);
// need to extract from temporary container to not force the group container to an accumulator
auto tmpValue = method.addNewLocal(entry.first->type, entry.first->name);
auto tmpContainer = assign(reader, pos.first->type) = pos.first->createReference();
reader = intermediate::insertVectorExtraction(
reader, method, tmpContainer, Value(SmallImmediate(pos.second), TYPE_INT8), tmpValue);
if(reader->hasUnpackMode() || reader->readsLiteral() || reader->getVectorRotation())
// insert a NOP before the actually reading instruction to allow for e.g. unpack-modes
nop(reader, intermediate::DelayType::WAIT_REGISTER);
reader->replaceLocal(entry.first, tmpValue);
if(isUsedAsSplatValue(tmpValue.local()))
{
// we need to recreate the splat property by replicating the value
auto splatTmp = method.addNewLocal(entry.first->type, entry.first->name);
reader = intermediate::insertReplication(reader, tmpValue, splatTmp);
reader->replaceLocal(tmpValue.local(), splatTmp);
}
}
}
return FixupResult::FIXES_APPLIED_RECREATE_GRAPH;
}
| 47.393701 | 120 | 0.619261 | doe300 |
c9d7910cae2c3669ed1a66f50a8e7a8d9979636a | 3,266 | cc | C++ | syzygy/reorder/dead_code_finder.cc | dandv/syzygy | 2444520c8e6e0b45b2f45b680d878d60b9636f45 | [
"Apache-2.0"
] | 1 | 2019-04-03T13:56:37.000Z | 2019-04-03T13:56:37.000Z | syzygy/reorder/dead_code_finder.cc | pombreda/syzygy | 7bac6936c0c28872bfabc10a1108e0157ff65d4a | [
"Apache-2.0"
] | 1 | 2015-03-19T18:20:25.000Z | 2015-03-19T18:20:25.000Z | syzygy/reorder/dead_code_finder.cc | sebmarchand/syzygy | 6c6db0e70e8161f1fec171138a825f6412e7778a | [
"Apache-2.0"
] | 1 | 2020-10-10T16:09:45.000Z | 2020-10-10T16:09:45.000Z | // Copyright 2011 Google Inc. 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 "syzygy/reorder/dead_code_finder.h"
namespace reorder {
DeadCodeFinder::DeadCodeFinder()
: Reorderer::OrderGenerator("Dead Code Finder") {
}
DeadCodeFinder::~DeadCodeFinder() {
}
bool DeadCodeFinder::OnCodeBlockEntry(const Block* block,
RelativeAddress /*address*/,
uint32 /*process_id*/,
uint32 /*thread_id*/,
const UniqueTime& /*time*/) {
visited_blocks_.insert(block);
return true;
}
bool DeadCodeFinder::IsDead(const Block* block) const {
// We don't consider gap blocks as interesting for the purposes of dead code
// identification. We don't have good names for these blocks, so they end up
// just being noise (not easily actionable) for the consumer of the dead code
// finder's output.
return ((block->attributes() & BlockGraph::GAP_BLOCK) == 0)
&& (visited_blocks_.find(block) == visited_blocks_.end());
}
bool DeadCodeFinder::CalculateReordering(const PEFile& pe_file,
const ImageLayout& image,
bool reorder_code,
bool reorder_data,
Order* order) {
DCHECK(order != NULL);
order->comment = "Unvisited blocks per section";
order->sections.clear();
order->sections.resize(image.sections.size());
for (size_t i = 0; i < image.sections.size(); ++i) {
const ImageLayout::SectionInfo& section = image.sections[i];
order->sections[i].id = i;
order->sections[i].name = section.name;
order->sections[i].characteristics = section.characteristics;
if ((section.characteristics & IMAGE_SCN_CNT_CODE) == 0)
continue;
// Prepare to iterate over all block in the section.
BlockGraph::AddressSpace::Range section_range(section.addr, section.size);
AddressSpace::RangeMapConstIterPair section_blocks(
image.blocks.GetIntersectingBlocks(
section_range.start(), section_range.size()));
// Gather up all unvisited blocks within the section in the "order".
AddressSpace::RangeMapConstIter& section_it = section_blocks.first;
const AddressSpace::RangeMapConstIter& section_end = section_blocks.second;
Order::BlockSpecVector& block_vector = order->sections[i].blocks;
for (; section_it != section_end; ++section_it) {
const BlockGraph::Block* block = section_it->second;
if (IsDead(block)) {
block_vector.push_back(Order::BlockSpec(block));
}
}
}
return true;
}
} // namespace reorder
| 38.880952 | 79 | 0.650031 | dandv |
c9d983f1ac0e5afdc7de86f2ec2f35749dcded16 | 96,717 | cpp | C++ | build/linux-build/Sources/src/nape/constraint/LineJoint.cpp | HedgehogFog/TimeOfDeath | b78abacf940e1a88c8b987d99764ebb6876c5dc6 | [
"MIT"
] | null | null | null | build/linux-build/Sources/src/nape/constraint/LineJoint.cpp | HedgehogFog/TimeOfDeath | b78abacf940e1a88c8b987d99764ebb6876c5dc6 | [
"MIT"
] | null | null | null | build/linux-build/Sources/src/nape/constraint/LineJoint.cpp | HedgehogFog/TimeOfDeath | b78abacf940e1a88c8b987d99764ebb6876c5dc6 | [
"MIT"
] | null | null | null | // Generated by Haxe 4.0.0-preview.5
#include <hxcpp.h>
#ifndef INCLUDED_nape_constraint_Constraint
#include <hxinc/nape/constraint/Constraint.h>
#endif
#ifndef INCLUDED_nape_constraint_LineJoint
#include <hxinc/nape/constraint/LineJoint.h>
#endif
#ifndef INCLUDED_nape_geom_MatMN
#include <hxinc/nape/geom/MatMN.h>
#endif
#ifndef INCLUDED_nape_geom_Vec2
#include <hxinc/nape/geom/Vec2.h>
#endif
#ifndef INCLUDED_nape_geom_Vec3
#include <hxinc/nape/geom/Vec3.h>
#endif
#ifndef INCLUDED_nape_phys_Body
#include <hxinc/nape/phys/Body.h>
#endif
#ifndef INCLUDED_nape_phys_Interactor
#include <hxinc/nape/phys/Interactor.h>
#endif
#ifndef INCLUDED_nape_space_Space
#include <hxinc/nape/space/Space.h>
#endif
#ifndef INCLUDED_zpp_nape_constraint_ZPP_Constraint
#include <hxinc/zpp_nape/constraint/ZPP_Constraint.h>
#endif
#ifndef INCLUDED_zpp_nape_constraint_ZPP_LineJoint
#include <hxinc/zpp_nape/constraint/ZPP_LineJoint.h>
#endif
#ifndef INCLUDED_zpp_nape_geom_ZPP_MatMN
#include <hxinc/zpp_nape/geom/ZPP_MatMN.h>
#endif
#ifndef INCLUDED_zpp_nape_geom_ZPP_Vec2
#include <hxinc/zpp_nape/geom/ZPP_Vec2.h>
#endif
#ifndef INCLUDED_zpp_nape_phys_ZPP_Body
#include <hxinc/zpp_nape/phys/ZPP_Body.h>
#endif
#ifndef INCLUDED_zpp_nape_phys_ZPP_Interactor
#include <hxinc/zpp_nape/phys/ZPP_Interactor.h>
#endif
#ifndef INCLUDED_zpp_nape_space_ZPP_Space
#include <hxinc/zpp_nape/space/ZPP_Space.h>
#endif
#ifndef INCLUDED_zpp_nape_util_ZNPList_ZPP_Constraint
#include <hxinc/zpp_nape/util/ZNPList_ZPP_Constraint.h>
#endif
#ifndef INCLUDED_zpp_nape_util_ZPP_PubPool
#include <hxinc/zpp_nape/util/ZPP_PubPool.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_09c49cc38fbc8a37_208_new,"nape.constraint.LineJoint","new",0xe137bcfd,"nape.constraint.LineJoint.new","nape/constraint/LineJoint.hx",208,0xe7850eb3)
HX_LOCAL_STACK_FRAME(_hx_pos_09c49cc38fbc8a37_222_get_body1,"nape.constraint.LineJoint","get_body1",0x71dff003,"nape.constraint.LineJoint.get_body1","nape/constraint/LineJoint.hx",222,0xe7850eb3)
HX_LOCAL_STACK_FRAME(_hx_pos_09c49cc38fbc8a37_224_set_body1,"nape.constraint.LineJoint","set_body1",0x5530dc0f,"nape.constraint.LineJoint.set_body1","nape/constraint/LineJoint.hx",224,0xe7850eb3)
HX_LOCAL_STACK_FRAME(_hx_pos_09c49cc38fbc8a37_260_get_body2,"nape.constraint.LineJoint","get_body2",0x71dff004,"nape.constraint.LineJoint.get_body2","nape/constraint/LineJoint.hx",260,0xe7850eb3)
HX_LOCAL_STACK_FRAME(_hx_pos_09c49cc38fbc8a37_262_set_body2,"nape.constraint.LineJoint","set_body2",0x5530dc10,"nape.constraint.LineJoint.set_body2","nape/constraint/LineJoint.hx",262,0xe7850eb3)
HX_LOCAL_STACK_FRAME(_hx_pos_09c49cc38fbc8a37_296_get_anchor1,"nape.constraint.LineJoint","get_anchor1",0x6f599dd0,"nape.constraint.LineJoint.get_anchor1","nape/constraint/LineJoint.hx",296,0xe7850eb3)
HX_LOCAL_STACK_FRAME(_hx_pos_09c49cc38fbc8a37_300_set_anchor1,"nape.constraint.LineJoint","set_anchor1",0x79c6a4dc,"nape.constraint.LineJoint.set_anchor1","nape/constraint/LineJoint.hx",300,0xe7850eb3)
HX_LOCAL_STACK_FRAME(_hx_pos_09c49cc38fbc8a37_321_get_anchor2,"nape.constraint.LineJoint","get_anchor2",0x6f599dd1,"nape.constraint.LineJoint.get_anchor2","nape/constraint/LineJoint.hx",321,0xe7850eb3)
HX_LOCAL_STACK_FRAME(_hx_pos_09c49cc38fbc8a37_325_set_anchor2,"nape.constraint.LineJoint","set_anchor2",0x79c6a4dd,"nape.constraint.LineJoint.set_anchor2","nape/constraint/LineJoint.hx",325,0xe7850eb3)
HX_LOCAL_STACK_FRAME(_hx_pos_09c49cc38fbc8a37_347_get_direction,"nape.constraint.LineJoint","get_direction",0xdf8ee8f3,"nape.constraint.LineJoint.get_direction","nape/constraint/LineJoint.hx",347,0xe7850eb3)
HX_LOCAL_STACK_FRAME(_hx_pos_09c49cc38fbc8a37_351_set_direction,"nape.constraint.LineJoint","set_direction",0x2494caff,"nape.constraint.LineJoint.set_direction","nape/constraint/LineJoint.hx",351,0xe7850eb3)
HX_LOCAL_STACK_FRAME(_hx_pos_09c49cc38fbc8a37_373_get_jointMin,"nape.constraint.LineJoint","get_jointMin",0x0929c634,"nape.constraint.LineJoint.get_jointMin","nape/constraint/LineJoint.hx",373,0xe7850eb3)
HX_LOCAL_STACK_FRAME(_hx_pos_09c49cc38fbc8a37_375_set_jointMin,"nape.constraint.LineJoint","set_jointMin",0x1e22e9a8,"nape.constraint.LineJoint.set_jointMin","nape/constraint/LineJoint.hx",375,0xe7850eb3)
HX_LOCAL_STACK_FRAME(_hx_pos_09c49cc38fbc8a37_398_get_jointMax,"nape.constraint.LineJoint","get_jointMax",0x0929bf46,"nape.constraint.LineJoint.get_jointMax","nape/constraint/LineJoint.hx",398,0xe7850eb3)
HX_LOCAL_STACK_FRAME(_hx_pos_09c49cc38fbc8a37_400_set_jointMax,"nape.constraint.LineJoint","set_jointMax",0x1e22e2ba,"nape.constraint.LineJoint.set_jointMax","nape/constraint/LineJoint.hx",400,0xe7850eb3)
HX_LOCAL_STACK_FRAME(_hx_pos_09c49cc38fbc8a37_455_impulse,"nape.constraint.LineJoint","impulse",0xf2f04fd2,"nape.constraint.LineJoint.impulse","nape/constraint/LineJoint.hx",455,0xe7850eb3)
HX_LOCAL_STACK_FRAME(_hx_pos_09c49cc38fbc8a37_464_bodyImpulse,"nape.constraint.LineJoint","bodyImpulse",0x465fc7d0,"nape.constraint.LineJoint.bodyImpulse","nape/constraint/LineJoint.hx",464,0xe7850eb3)
HX_LOCAL_STACK_FRAME(_hx_pos_09c49cc38fbc8a37_483_visitBodies,"nape.constraint.LineJoint","visitBodies",0xcb1c4548,"nape.constraint.LineJoint.visitBodies","nape/constraint/LineJoint.hx",483,0xe7850eb3)
namespace nape{
namespace constraint{
void LineJoint_obj::__construct( ::nape::phys::Body body1, ::nape::phys::Body body2, ::nape::geom::Vec2 anchor1, ::nape::geom::Vec2 anchor2, ::nape::geom::Vec2 direction,Float jointMin,Float jointMax){
HX_GC_STACKFRAME(&_hx_pos_09c49cc38fbc8a37_208_new)
HXLINE( 212) this->zpp_inner_zn = null();
HXLINE( 430) this->zpp_inner_zn = ::zpp_nape::constraint::ZPP_LineJoint_obj::__alloc( HX_CTX );
HXLINE( 431) this->zpp_inner = this->zpp_inner_zn;
HXLINE( 432) this->zpp_inner->outer = hx::ObjectPtr<OBJ_>(this);
HXLINE( 433) this->zpp_inner_zn->outer_zn = hx::ObjectPtr<OBJ_>(this);
HXLINE( 435) ::nape::constraint::Constraint_obj::zpp_internalAlloc = true;
HXLINE( 436) super::__construct();
HXLINE( 437) ::nape::constraint::Constraint_obj::zpp_internalAlloc = false;
HXLINE( 442) {
HXLINE( 442) {
HXLINE( 442) this->zpp_inner->immutable_midstep((HX_("Constraint::",7d,10,25,6e) + HX_("body1",4f,d3,ef,b6)));
HXDLIN( 442) ::zpp_nape::phys::ZPP_Body inbody1;
HXDLIN( 442) if (hx::IsNull( body1 )) {
HXLINE( 442) inbody1 = null();
}
else {
HXLINE( 442) inbody1 = body1->zpp_inner;
}
HXDLIN( 442) if (hx::IsNotEq( inbody1,this->zpp_inner_zn->b1 )) {
HXLINE( 442) if (hx::IsNotNull( this->zpp_inner_zn->b1 )) {
HXLINE( 442) bool _hx_tmp;
HXDLIN( 442) ::nape::space::Space _hx_tmp1;
HXDLIN( 442) if (hx::IsNull( this->zpp_inner->space )) {
HXLINE( 442) _hx_tmp1 = null();
}
else {
HXLINE( 442) _hx_tmp1 = this->zpp_inner->space->outer;
}
HXDLIN( 442) if (hx::IsNotNull( _hx_tmp1 )) {
HXLINE( 442) _hx_tmp = hx::IsNotEq( this->zpp_inner_zn->b2,this->zpp_inner_zn->b1 );
}
else {
HXLINE( 442) _hx_tmp = false;
}
HXDLIN( 442) if (_hx_tmp) {
HXLINE( 442) if (hx::IsNotNull( this->zpp_inner_zn->b1 )) {
HXLINE( 442) this->zpp_inner_zn->b1->constraints->remove(this->zpp_inner);
}
}
HXDLIN( 442) bool _hx_tmp2;
HXDLIN( 442) if (this->zpp_inner->active) {
HXLINE( 442) ::nape::space::Space _hx_tmp3;
HXDLIN( 442) if (hx::IsNull( this->zpp_inner->space )) {
HXLINE( 442) _hx_tmp3 = null();
}
else {
HXLINE( 442) _hx_tmp3 = this->zpp_inner->space->outer;
}
HXDLIN( 442) _hx_tmp2 = hx::IsNotNull( _hx_tmp3 );
}
else {
HXLINE( 442) _hx_tmp2 = false;
}
HXDLIN( 442) if (_hx_tmp2) {
HXLINE( 442) this->zpp_inner_zn->b1->wake();
}
}
HXDLIN( 442) this->zpp_inner_zn->b1 = inbody1;
HXDLIN( 442) bool _hx_tmp4;
HXDLIN( 442) bool _hx_tmp5;
HXDLIN( 442) ::nape::space::Space _hx_tmp6;
HXDLIN( 442) if (hx::IsNull( this->zpp_inner->space )) {
HXLINE( 442) _hx_tmp6 = null();
}
else {
HXLINE( 442) _hx_tmp6 = this->zpp_inner->space->outer;
}
HXDLIN( 442) if (hx::IsNotNull( _hx_tmp6 )) {
HXLINE( 442) _hx_tmp5 = hx::IsNotNull( inbody1 );
}
else {
HXLINE( 442) _hx_tmp5 = false;
}
HXDLIN( 442) if (_hx_tmp5) {
HXLINE( 442) _hx_tmp4 = hx::IsNotEq( this->zpp_inner_zn->b2,inbody1 );
}
else {
HXLINE( 442) _hx_tmp4 = false;
}
HXDLIN( 442) if (_hx_tmp4) {
HXLINE( 442) if (hx::IsNotNull( inbody1 )) {
HXLINE( 442) inbody1->constraints->add(this->zpp_inner);
}
}
HXDLIN( 442) bool _hx_tmp7;
HXDLIN( 442) if (this->zpp_inner->active) {
HXLINE( 442) ::nape::space::Space _hx_tmp8;
HXDLIN( 442) if (hx::IsNull( this->zpp_inner->space )) {
HXLINE( 442) _hx_tmp8 = null();
}
else {
HXLINE( 442) _hx_tmp8 = this->zpp_inner->space->outer;
}
HXDLIN( 442) _hx_tmp7 = hx::IsNotNull( _hx_tmp8 );
}
else {
HXLINE( 442) _hx_tmp7 = false;
}
HXDLIN( 442) if (_hx_tmp7) {
HXLINE( 442) this->zpp_inner->wake();
HXDLIN( 442) if (hx::IsNotNull( inbody1 )) {
HXLINE( 442) inbody1->wake();
}
}
}
}
HXDLIN( 442) bool _hx_tmp9 = hx::IsNull( this->zpp_inner_zn->b1 );
}
HXLINE( 443) {
HXLINE( 443) {
HXLINE( 443) this->zpp_inner->immutable_midstep((HX_("Constraint::",7d,10,25,6e) + HX_("body2",50,d3,ef,b6)));
HXDLIN( 443) ::zpp_nape::phys::ZPP_Body inbody2;
HXDLIN( 443) if (hx::IsNull( body2 )) {
HXLINE( 443) inbody2 = null();
}
else {
HXLINE( 443) inbody2 = body2->zpp_inner;
}
HXDLIN( 443) if (hx::IsNotEq( inbody2,this->zpp_inner_zn->b2 )) {
HXLINE( 443) if (hx::IsNotNull( this->zpp_inner_zn->b2 )) {
HXLINE( 443) bool _hx_tmp10;
HXDLIN( 443) ::nape::space::Space _hx_tmp11;
HXDLIN( 443) if (hx::IsNull( this->zpp_inner->space )) {
HXLINE( 443) _hx_tmp11 = null();
}
else {
HXLINE( 443) _hx_tmp11 = this->zpp_inner->space->outer;
}
HXDLIN( 443) if (hx::IsNotNull( _hx_tmp11 )) {
HXLINE( 443) _hx_tmp10 = hx::IsNotEq( this->zpp_inner_zn->b1,this->zpp_inner_zn->b2 );
}
else {
HXLINE( 443) _hx_tmp10 = false;
}
HXDLIN( 443) if (_hx_tmp10) {
HXLINE( 443) if (hx::IsNotNull( this->zpp_inner_zn->b2 )) {
HXLINE( 443) this->zpp_inner_zn->b2->constraints->remove(this->zpp_inner);
}
}
HXDLIN( 443) bool _hx_tmp12;
HXDLIN( 443) if (this->zpp_inner->active) {
HXLINE( 443) ::nape::space::Space _hx_tmp13;
HXDLIN( 443) if (hx::IsNull( this->zpp_inner->space )) {
HXLINE( 443) _hx_tmp13 = null();
}
else {
HXLINE( 443) _hx_tmp13 = this->zpp_inner->space->outer;
}
HXDLIN( 443) _hx_tmp12 = hx::IsNotNull( _hx_tmp13 );
}
else {
HXLINE( 443) _hx_tmp12 = false;
}
HXDLIN( 443) if (_hx_tmp12) {
HXLINE( 443) this->zpp_inner_zn->b2->wake();
}
}
HXDLIN( 443) this->zpp_inner_zn->b2 = inbody2;
HXDLIN( 443) bool _hx_tmp14;
HXDLIN( 443) bool _hx_tmp15;
HXDLIN( 443) ::nape::space::Space _hx_tmp16;
HXDLIN( 443) if (hx::IsNull( this->zpp_inner->space )) {
HXLINE( 443) _hx_tmp16 = null();
}
else {
HXLINE( 443) _hx_tmp16 = this->zpp_inner->space->outer;
}
HXDLIN( 443) if (hx::IsNotNull( _hx_tmp16 )) {
HXLINE( 443) _hx_tmp15 = hx::IsNotNull( inbody2 );
}
else {
HXLINE( 443) _hx_tmp15 = false;
}
HXDLIN( 443) if (_hx_tmp15) {
HXLINE( 443) _hx_tmp14 = hx::IsNotEq( this->zpp_inner_zn->b1,inbody2 );
}
else {
HXLINE( 443) _hx_tmp14 = false;
}
HXDLIN( 443) if (_hx_tmp14) {
HXLINE( 443) if (hx::IsNotNull( inbody2 )) {
HXLINE( 443) inbody2->constraints->add(this->zpp_inner);
}
}
HXDLIN( 443) bool _hx_tmp17;
HXDLIN( 443) if (this->zpp_inner->active) {
HXLINE( 443) ::nape::space::Space _hx_tmp18;
HXDLIN( 443) if (hx::IsNull( this->zpp_inner->space )) {
HXLINE( 443) _hx_tmp18 = null();
}
else {
HXLINE( 443) _hx_tmp18 = this->zpp_inner->space->outer;
}
HXDLIN( 443) _hx_tmp17 = hx::IsNotNull( _hx_tmp18 );
}
else {
HXLINE( 443) _hx_tmp17 = false;
}
HXDLIN( 443) if (_hx_tmp17) {
HXLINE( 443) this->zpp_inner->wake();
HXDLIN( 443) if (hx::IsNotNull( inbody2 )) {
HXLINE( 443) inbody2->wake();
}
}
}
}
HXDLIN( 443) bool _hx_tmp19 = hx::IsNull( this->zpp_inner_zn->b2 );
}
HXLINE( 444) {
HXLINE( 444) {
HXLINE( 444) bool _hx_tmp20;
HXDLIN( 444) if (hx::IsNotNull( anchor1 )) {
HXLINE( 444) _hx_tmp20 = anchor1->zpp_disp;
}
else {
HXLINE( 444) _hx_tmp20 = false;
}
HXDLIN( 444) if (_hx_tmp20) {
HXLINE( 444) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 444) if (hx::IsNull( anchor1 )) {
HXLINE( 444) HX_STACK_DO_THROW(((HX_("Error: Constraint::",cb,f5,02,d5) + HX_("anchor1",1c,ec,a1,02)) + HX_(" cannot be null",07,dc,5d,15)));
}
HXDLIN( 444) {
HXLINE( 444) if (hx::IsNull( this->zpp_inner_zn->wrap_a1 )) {
HXLINE( 444) this->zpp_inner_zn->setup_a1();
}
HXDLIN( 444) ::nape::geom::Vec2 _this = this->zpp_inner_zn->wrap_a1;
HXDLIN( 444) bool _hx_tmp21;
HXDLIN( 444) if (hx::IsNotNull( _this )) {
HXLINE( 444) _hx_tmp21 = _this->zpp_disp;
}
else {
HXLINE( 444) _hx_tmp21 = false;
}
HXDLIN( 444) if (_hx_tmp21) {
HXLINE( 444) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 444) bool _hx_tmp22;
HXDLIN( 444) if (hx::IsNotNull( anchor1 )) {
HXLINE( 444) _hx_tmp22 = anchor1->zpp_disp;
}
else {
HXLINE( 444) _hx_tmp22 = false;
}
HXDLIN( 444) if (_hx_tmp22) {
HXLINE( 444) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 444) {
HXLINE( 444) ::zpp_nape::geom::ZPP_Vec2 _this1 = _this->zpp_inner;
HXDLIN( 444) if (_this1->_immutable) {
HXLINE( 444) HX_STACK_DO_THROW(HX_("Error: Vec2 is immutable",60,ee,1f,bc));
}
HXDLIN( 444) if (hx::IsNotNull( _this1->_isimmutable )) {
HXLINE( 444) _this1->_isimmutable();
}
}
HXDLIN( 444) if (hx::IsNull( anchor1 )) {
HXLINE( 444) HX_STACK_DO_THROW(HX_("Error: Cannot assign null Vec2",95,15,46,66));
}
HXDLIN( 444) bool _hx_tmp23;
HXDLIN( 444) if (hx::IsNotNull( anchor1 )) {
HXLINE( 444) _hx_tmp23 = anchor1->zpp_disp;
}
else {
HXLINE( 444) _hx_tmp23 = false;
}
HXDLIN( 444) if (_hx_tmp23) {
HXLINE( 444) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 444) {
HXLINE( 444) ::zpp_nape::geom::ZPP_Vec2 _this2 = anchor1->zpp_inner;
HXDLIN( 444) if (hx::IsNotNull( _this2->_validate )) {
HXLINE( 444) _this2->_validate();
}
}
HXDLIN( 444) Float x = anchor1->zpp_inner->x;
HXDLIN( 444) bool _hx_tmp24;
HXDLIN( 444) if (hx::IsNotNull( anchor1 )) {
HXLINE( 444) _hx_tmp24 = anchor1->zpp_disp;
}
else {
HXLINE( 444) _hx_tmp24 = false;
}
HXDLIN( 444) if (_hx_tmp24) {
HXLINE( 444) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 444) {
HXLINE( 444) ::zpp_nape::geom::ZPP_Vec2 _this3 = anchor1->zpp_inner;
HXDLIN( 444) if (hx::IsNotNull( _this3->_validate )) {
HXLINE( 444) _this3->_validate();
}
}
HXDLIN( 444) Float y = anchor1->zpp_inner->y;
HXDLIN( 444) bool _hx_tmp25;
HXDLIN( 444) if (hx::IsNotNull( _this )) {
HXLINE( 444) _hx_tmp25 = _this->zpp_disp;
}
else {
HXLINE( 444) _hx_tmp25 = false;
}
HXDLIN( 444) if (_hx_tmp25) {
HXLINE( 444) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 444) {
HXLINE( 444) ::zpp_nape::geom::ZPP_Vec2 _this4 = _this->zpp_inner;
HXDLIN( 444) if (_this4->_immutable) {
HXLINE( 444) HX_STACK_DO_THROW(HX_("Error: Vec2 is immutable",60,ee,1f,bc));
}
HXDLIN( 444) if (hx::IsNotNull( _this4->_isimmutable )) {
HXLINE( 444) _this4->_isimmutable();
}
}
HXDLIN( 444) bool _hx_tmp26;
HXDLIN( 444) if ((x == x)) {
HXLINE( 444) _hx_tmp26 = (y != y);
}
else {
HXLINE( 444) _hx_tmp26 = true;
}
HXDLIN( 444) if (_hx_tmp26) {
HXLINE( 444) HX_STACK_DO_THROW(HX_("Error: Vec2 components cannot be NaN",85,ba,d8,c1));
}
HXDLIN( 444) bool _hx_tmp27;
HXDLIN( 444) bool _hx_tmp28;
HXDLIN( 444) if (hx::IsNotNull( _this )) {
HXLINE( 444) _hx_tmp28 = _this->zpp_disp;
}
else {
HXLINE( 444) _hx_tmp28 = false;
}
HXDLIN( 444) if (_hx_tmp28) {
HXLINE( 444) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 444) {
HXLINE( 444) ::zpp_nape::geom::ZPP_Vec2 _this5 = _this->zpp_inner;
HXDLIN( 444) if (hx::IsNotNull( _this5->_validate )) {
HXLINE( 444) _this5->_validate();
}
}
HXDLIN( 444) if ((_this->zpp_inner->x == x)) {
HXLINE( 444) bool _hx_tmp29;
HXDLIN( 444) if (hx::IsNotNull( _this )) {
HXLINE( 444) _hx_tmp29 = _this->zpp_disp;
}
else {
HXLINE( 444) _hx_tmp29 = false;
}
HXDLIN( 444) if (_hx_tmp29) {
HXLINE( 444) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 444) {
HXLINE( 444) ::zpp_nape::geom::ZPP_Vec2 _this6 = _this->zpp_inner;
HXDLIN( 444) if (hx::IsNotNull( _this6->_validate )) {
HXLINE( 444) _this6->_validate();
}
}
HXDLIN( 444) _hx_tmp27 = (_this->zpp_inner->y == y);
}
else {
HXLINE( 444) _hx_tmp27 = false;
}
HXDLIN( 444) if (!(_hx_tmp27)) {
HXLINE( 444) {
HXLINE( 444) _this->zpp_inner->x = x;
HXDLIN( 444) _this->zpp_inner->y = y;
}
HXDLIN( 444) {
HXLINE( 444) ::zpp_nape::geom::ZPP_Vec2 _this7 = _this->zpp_inner;
HXDLIN( 444) if (hx::IsNotNull( _this7->_invalidate )) {
HXLINE( 444) _this7->_invalidate(_this7);
}
}
}
HXDLIN( 444) ::nape::geom::Vec2 ret = _this;
HXDLIN( 444) if (anchor1->zpp_inner->weak) {
HXLINE( 444) bool _hx_tmp30;
HXDLIN( 444) if (hx::IsNotNull( anchor1 )) {
HXLINE( 444) _hx_tmp30 = anchor1->zpp_disp;
}
else {
HXLINE( 444) _hx_tmp30 = false;
}
HXDLIN( 444) if (_hx_tmp30) {
HXLINE( 444) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 444) {
HXLINE( 444) ::zpp_nape::geom::ZPP_Vec2 _this8 = anchor1->zpp_inner;
HXDLIN( 444) if (_this8->_immutable) {
HXLINE( 444) HX_STACK_DO_THROW(HX_("Error: Vec2 is immutable",60,ee,1f,bc));
}
HXDLIN( 444) if (hx::IsNotNull( _this8->_isimmutable )) {
HXLINE( 444) _this8->_isimmutable();
}
}
HXDLIN( 444) if (anchor1->zpp_inner->_inuse) {
HXLINE( 444) HX_STACK_DO_THROW(HX_("Error: This Vec2 is not disposable",b5,d1,d1,d8));
}
HXDLIN( 444) ::zpp_nape::geom::ZPP_Vec2 inner = anchor1->zpp_inner;
HXDLIN( 444) anchor1->zpp_inner->outer = null();
HXDLIN( 444) anchor1->zpp_inner = null();
HXDLIN( 444) {
HXLINE( 444) ::nape::geom::Vec2 o = anchor1;
HXDLIN( 444) o->zpp_pool = null();
HXDLIN( 444) if (hx::IsNotNull( ::zpp_nape::util::ZPP_PubPool_obj::nextVec2 )) {
HXLINE( 444) ::zpp_nape::util::ZPP_PubPool_obj::nextVec2->zpp_pool = o;
}
else {
HXLINE( 444) ::zpp_nape::util::ZPP_PubPool_obj::poolVec2 = o;
}
HXDLIN( 444) ::zpp_nape::util::ZPP_PubPool_obj::nextVec2 = o;
HXDLIN( 444) o->zpp_disp = true;
}
HXDLIN( 444) {
HXLINE( 444) ::zpp_nape::geom::ZPP_Vec2 o1 = inner;
HXDLIN( 444) {
HXLINE( 444) if (hx::IsNotNull( o1->outer )) {
HXLINE( 444) o1->outer->zpp_inner = null();
HXDLIN( 444) o1->outer = null();
}
HXDLIN( 444) o1->_isimmutable = null();
HXDLIN( 444) o1->_validate = null();
HXDLIN( 444) o1->_invalidate = null();
}
HXDLIN( 444) o1->next = ::zpp_nape::geom::ZPP_Vec2_obj::zpp_pool;
HXDLIN( 444) ::zpp_nape::geom::ZPP_Vec2_obj::zpp_pool = o1;
}
}
}
}
HXDLIN( 444) if (hx::IsNull( this->zpp_inner_zn->wrap_a1 )) {
HXLINE( 444) this->zpp_inner_zn->setup_a1();
}
}
HXLINE( 445) {
HXLINE( 445) {
HXLINE( 445) bool _hx_tmp31;
HXDLIN( 445) if (hx::IsNotNull( anchor2 )) {
HXLINE( 445) _hx_tmp31 = anchor2->zpp_disp;
}
else {
HXLINE( 445) _hx_tmp31 = false;
}
HXDLIN( 445) if (_hx_tmp31) {
HXLINE( 445) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 445) if (hx::IsNull( anchor2 )) {
HXLINE( 445) HX_STACK_DO_THROW(((HX_("Error: Constraint::",cb,f5,02,d5) + HX_("anchor2",1d,ec,a1,02)) + HX_(" cannot be null",07,dc,5d,15)));
}
HXDLIN( 445) {
HXLINE( 445) if (hx::IsNull( this->zpp_inner_zn->wrap_a2 )) {
HXLINE( 445) this->zpp_inner_zn->setup_a2();
}
HXDLIN( 445) ::nape::geom::Vec2 _this9 = this->zpp_inner_zn->wrap_a2;
HXDLIN( 445) bool _hx_tmp32;
HXDLIN( 445) if (hx::IsNotNull( _this9 )) {
HXLINE( 445) _hx_tmp32 = _this9->zpp_disp;
}
else {
HXLINE( 445) _hx_tmp32 = false;
}
HXDLIN( 445) if (_hx_tmp32) {
HXLINE( 445) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 445) bool _hx_tmp33;
HXDLIN( 445) if (hx::IsNotNull( anchor2 )) {
HXLINE( 445) _hx_tmp33 = anchor2->zpp_disp;
}
else {
HXLINE( 445) _hx_tmp33 = false;
}
HXDLIN( 445) if (_hx_tmp33) {
HXLINE( 445) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 445) {
HXLINE( 445) ::zpp_nape::geom::ZPP_Vec2 _this10 = _this9->zpp_inner;
HXDLIN( 445) if (_this10->_immutable) {
HXLINE( 445) HX_STACK_DO_THROW(HX_("Error: Vec2 is immutable",60,ee,1f,bc));
}
HXDLIN( 445) if (hx::IsNotNull( _this10->_isimmutable )) {
HXLINE( 445) _this10->_isimmutable();
}
}
HXDLIN( 445) if (hx::IsNull( anchor2 )) {
HXLINE( 445) HX_STACK_DO_THROW(HX_("Error: Cannot assign null Vec2",95,15,46,66));
}
HXDLIN( 445) bool _hx_tmp34;
HXDLIN( 445) if (hx::IsNotNull( anchor2 )) {
HXLINE( 445) _hx_tmp34 = anchor2->zpp_disp;
}
else {
HXLINE( 445) _hx_tmp34 = false;
}
HXDLIN( 445) if (_hx_tmp34) {
HXLINE( 445) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 445) {
HXLINE( 445) ::zpp_nape::geom::ZPP_Vec2 _this11 = anchor2->zpp_inner;
HXDLIN( 445) if (hx::IsNotNull( _this11->_validate )) {
HXLINE( 445) _this11->_validate();
}
}
HXDLIN( 445) Float x1 = anchor2->zpp_inner->x;
HXDLIN( 445) bool _hx_tmp35;
HXDLIN( 445) if (hx::IsNotNull( anchor2 )) {
HXLINE( 445) _hx_tmp35 = anchor2->zpp_disp;
}
else {
HXLINE( 445) _hx_tmp35 = false;
}
HXDLIN( 445) if (_hx_tmp35) {
HXLINE( 445) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 445) {
HXLINE( 445) ::zpp_nape::geom::ZPP_Vec2 _this12 = anchor2->zpp_inner;
HXDLIN( 445) if (hx::IsNotNull( _this12->_validate )) {
HXLINE( 445) _this12->_validate();
}
}
HXDLIN( 445) Float y1 = anchor2->zpp_inner->y;
HXDLIN( 445) bool _hx_tmp36;
HXDLIN( 445) if (hx::IsNotNull( _this9 )) {
HXLINE( 445) _hx_tmp36 = _this9->zpp_disp;
}
else {
HXLINE( 445) _hx_tmp36 = false;
}
HXDLIN( 445) if (_hx_tmp36) {
HXLINE( 445) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 445) {
HXLINE( 445) ::zpp_nape::geom::ZPP_Vec2 _this13 = _this9->zpp_inner;
HXDLIN( 445) if (_this13->_immutable) {
HXLINE( 445) HX_STACK_DO_THROW(HX_("Error: Vec2 is immutable",60,ee,1f,bc));
}
HXDLIN( 445) if (hx::IsNotNull( _this13->_isimmutable )) {
HXLINE( 445) _this13->_isimmutable();
}
}
HXDLIN( 445) bool _hx_tmp37;
HXDLIN( 445) if ((x1 == x1)) {
HXLINE( 445) _hx_tmp37 = (y1 != y1);
}
else {
HXLINE( 445) _hx_tmp37 = true;
}
HXDLIN( 445) if (_hx_tmp37) {
HXLINE( 445) HX_STACK_DO_THROW(HX_("Error: Vec2 components cannot be NaN",85,ba,d8,c1));
}
HXDLIN( 445) bool _hx_tmp38;
HXDLIN( 445) bool _hx_tmp39;
HXDLIN( 445) if (hx::IsNotNull( _this9 )) {
HXLINE( 445) _hx_tmp39 = _this9->zpp_disp;
}
else {
HXLINE( 445) _hx_tmp39 = false;
}
HXDLIN( 445) if (_hx_tmp39) {
HXLINE( 445) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 445) {
HXLINE( 445) ::zpp_nape::geom::ZPP_Vec2 _this14 = _this9->zpp_inner;
HXDLIN( 445) if (hx::IsNotNull( _this14->_validate )) {
HXLINE( 445) _this14->_validate();
}
}
HXDLIN( 445) if ((_this9->zpp_inner->x == x1)) {
HXLINE( 445) bool _hx_tmp40;
HXDLIN( 445) if (hx::IsNotNull( _this9 )) {
HXLINE( 445) _hx_tmp40 = _this9->zpp_disp;
}
else {
HXLINE( 445) _hx_tmp40 = false;
}
HXDLIN( 445) if (_hx_tmp40) {
HXLINE( 445) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 445) {
HXLINE( 445) ::zpp_nape::geom::ZPP_Vec2 _this15 = _this9->zpp_inner;
HXDLIN( 445) if (hx::IsNotNull( _this15->_validate )) {
HXLINE( 445) _this15->_validate();
}
}
HXDLIN( 445) _hx_tmp38 = (_this9->zpp_inner->y == y1);
}
else {
HXLINE( 445) _hx_tmp38 = false;
}
HXDLIN( 445) if (!(_hx_tmp38)) {
HXLINE( 445) {
HXLINE( 445) _this9->zpp_inner->x = x1;
HXDLIN( 445) _this9->zpp_inner->y = y1;
}
HXDLIN( 445) {
HXLINE( 445) ::zpp_nape::geom::ZPP_Vec2 _this16 = _this9->zpp_inner;
HXDLIN( 445) if (hx::IsNotNull( _this16->_invalidate )) {
HXLINE( 445) _this16->_invalidate(_this16);
}
}
}
HXDLIN( 445) ::nape::geom::Vec2 ret1 = _this9;
HXDLIN( 445) if (anchor2->zpp_inner->weak) {
HXLINE( 445) bool _hx_tmp41;
HXDLIN( 445) if (hx::IsNotNull( anchor2 )) {
HXLINE( 445) _hx_tmp41 = anchor2->zpp_disp;
}
else {
HXLINE( 445) _hx_tmp41 = false;
}
HXDLIN( 445) if (_hx_tmp41) {
HXLINE( 445) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 445) {
HXLINE( 445) ::zpp_nape::geom::ZPP_Vec2 _this17 = anchor2->zpp_inner;
HXDLIN( 445) if (_this17->_immutable) {
HXLINE( 445) HX_STACK_DO_THROW(HX_("Error: Vec2 is immutable",60,ee,1f,bc));
}
HXDLIN( 445) if (hx::IsNotNull( _this17->_isimmutable )) {
HXLINE( 445) _this17->_isimmutable();
}
}
HXDLIN( 445) if (anchor2->zpp_inner->_inuse) {
HXLINE( 445) HX_STACK_DO_THROW(HX_("Error: This Vec2 is not disposable",b5,d1,d1,d8));
}
HXDLIN( 445) ::zpp_nape::geom::ZPP_Vec2 inner1 = anchor2->zpp_inner;
HXDLIN( 445) anchor2->zpp_inner->outer = null();
HXDLIN( 445) anchor2->zpp_inner = null();
HXDLIN( 445) {
HXLINE( 445) ::nape::geom::Vec2 o2 = anchor2;
HXDLIN( 445) o2->zpp_pool = null();
HXDLIN( 445) if (hx::IsNotNull( ::zpp_nape::util::ZPP_PubPool_obj::nextVec2 )) {
HXLINE( 445) ::zpp_nape::util::ZPP_PubPool_obj::nextVec2->zpp_pool = o2;
}
else {
HXLINE( 445) ::zpp_nape::util::ZPP_PubPool_obj::poolVec2 = o2;
}
HXDLIN( 445) ::zpp_nape::util::ZPP_PubPool_obj::nextVec2 = o2;
HXDLIN( 445) o2->zpp_disp = true;
}
HXDLIN( 445) {
HXLINE( 445) ::zpp_nape::geom::ZPP_Vec2 o3 = inner1;
HXDLIN( 445) {
HXLINE( 445) if (hx::IsNotNull( o3->outer )) {
HXLINE( 445) o3->outer->zpp_inner = null();
HXDLIN( 445) o3->outer = null();
}
HXDLIN( 445) o3->_isimmutable = null();
HXDLIN( 445) o3->_validate = null();
HXDLIN( 445) o3->_invalidate = null();
}
HXDLIN( 445) o3->next = ::zpp_nape::geom::ZPP_Vec2_obj::zpp_pool;
HXDLIN( 445) ::zpp_nape::geom::ZPP_Vec2_obj::zpp_pool = o3;
}
}
}
}
HXDLIN( 445) if (hx::IsNull( this->zpp_inner_zn->wrap_a2 )) {
HXLINE( 445) this->zpp_inner_zn->setup_a2();
}
}
HXLINE( 446) {
HXLINE( 446) {
HXLINE( 446) bool _hx_tmp42;
HXDLIN( 446) if (hx::IsNotNull( direction )) {
HXLINE( 446) _hx_tmp42 = direction->zpp_disp;
}
else {
HXLINE( 446) _hx_tmp42 = false;
}
HXDLIN( 446) if (_hx_tmp42) {
HXLINE( 446) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 446) if (hx::IsNull( direction )) {
HXLINE( 446) HX_STACK_DO_THROW(((HX_("Error: Constraint::",cb,f5,02,d5) + HX_("direction",3f,62,40,10)) + HX_(" cannot be null",07,dc,5d,15)));
}
HXDLIN( 446) {
HXLINE( 446) if (hx::IsNull( this->zpp_inner_zn->wrap_n )) {
HXLINE( 446) this->zpp_inner_zn->setup_n();
}
HXDLIN( 446) ::nape::geom::Vec2 _this18 = this->zpp_inner_zn->wrap_n;
HXDLIN( 446) bool _hx_tmp43;
HXDLIN( 446) if (hx::IsNotNull( _this18 )) {
HXLINE( 446) _hx_tmp43 = _this18->zpp_disp;
}
else {
HXLINE( 446) _hx_tmp43 = false;
}
HXDLIN( 446) if (_hx_tmp43) {
HXLINE( 446) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 446) bool _hx_tmp44;
HXDLIN( 446) if (hx::IsNotNull( direction )) {
HXLINE( 446) _hx_tmp44 = direction->zpp_disp;
}
else {
HXLINE( 446) _hx_tmp44 = false;
}
HXDLIN( 446) if (_hx_tmp44) {
HXLINE( 446) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 446) {
HXLINE( 446) ::zpp_nape::geom::ZPP_Vec2 _this19 = _this18->zpp_inner;
HXDLIN( 446) if (_this19->_immutable) {
HXLINE( 446) HX_STACK_DO_THROW(HX_("Error: Vec2 is immutable",60,ee,1f,bc));
}
HXDLIN( 446) if (hx::IsNotNull( _this19->_isimmutable )) {
HXLINE( 446) _this19->_isimmutable();
}
}
HXDLIN( 446) if (hx::IsNull( direction )) {
HXLINE( 446) HX_STACK_DO_THROW(HX_("Error: Cannot assign null Vec2",95,15,46,66));
}
HXDLIN( 446) bool _hx_tmp45;
HXDLIN( 446) if (hx::IsNotNull( direction )) {
HXLINE( 446) _hx_tmp45 = direction->zpp_disp;
}
else {
HXLINE( 446) _hx_tmp45 = false;
}
HXDLIN( 446) if (_hx_tmp45) {
HXLINE( 446) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 446) {
HXLINE( 446) ::zpp_nape::geom::ZPP_Vec2 _this20 = direction->zpp_inner;
HXDLIN( 446) if (hx::IsNotNull( _this20->_validate )) {
HXLINE( 446) _this20->_validate();
}
}
HXDLIN( 446) Float x2 = direction->zpp_inner->x;
HXDLIN( 446) bool _hx_tmp46;
HXDLIN( 446) if (hx::IsNotNull( direction )) {
HXLINE( 446) _hx_tmp46 = direction->zpp_disp;
}
else {
HXLINE( 446) _hx_tmp46 = false;
}
HXDLIN( 446) if (_hx_tmp46) {
HXLINE( 446) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 446) {
HXLINE( 446) ::zpp_nape::geom::ZPP_Vec2 _this21 = direction->zpp_inner;
HXDLIN( 446) if (hx::IsNotNull( _this21->_validate )) {
HXLINE( 446) _this21->_validate();
}
}
HXDLIN( 446) Float y2 = direction->zpp_inner->y;
HXDLIN( 446) bool _hx_tmp47;
HXDLIN( 446) if (hx::IsNotNull( _this18 )) {
HXLINE( 446) _hx_tmp47 = _this18->zpp_disp;
}
else {
HXLINE( 446) _hx_tmp47 = false;
}
HXDLIN( 446) if (_hx_tmp47) {
HXLINE( 446) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 446) {
HXLINE( 446) ::zpp_nape::geom::ZPP_Vec2 _this22 = _this18->zpp_inner;
HXDLIN( 446) if (_this22->_immutable) {
HXLINE( 446) HX_STACK_DO_THROW(HX_("Error: Vec2 is immutable",60,ee,1f,bc));
}
HXDLIN( 446) if (hx::IsNotNull( _this22->_isimmutable )) {
HXLINE( 446) _this22->_isimmutable();
}
}
HXDLIN( 446) bool _hx_tmp48;
HXDLIN( 446) if ((x2 == x2)) {
HXLINE( 446) _hx_tmp48 = (y2 != y2);
}
else {
HXLINE( 446) _hx_tmp48 = true;
}
HXDLIN( 446) if (_hx_tmp48) {
HXLINE( 446) HX_STACK_DO_THROW(HX_("Error: Vec2 components cannot be NaN",85,ba,d8,c1));
}
HXDLIN( 446) bool _hx_tmp49;
HXDLIN( 446) bool _hx_tmp50;
HXDLIN( 446) if (hx::IsNotNull( _this18 )) {
HXLINE( 446) _hx_tmp50 = _this18->zpp_disp;
}
else {
HXLINE( 446) _hx_tmp50 = false;
}
HXDLIN( 446) if (_hx_tmp50) {
HXLINE( 446) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 446) {
HXLINE( 446) ::zpp_nape::geom::ZPP_Vec2 _this23 = _this18->zpp_inner;
HXDLIN( 446) if (hx::IsNotNull( _this23->_validate )) {
HXLINE( 446) _this23->_validate();
}
}
HXDLIN( 446) if ((_this18->zpp_inner->x == x2)) {
HXLINE( 446) bool _hx_tmp51;
HXDLIN( 446) if (hx::IsNotNull( _this18 )) {
HXLINE( 446) _hx_tmp51 = _this18->zpp_disp;
}
else {
HXLINE( 446) _hx_tmp51 = false;
}
HXDLIN( 446) if (_hx_tmp51) {
HXLINE( 446) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 446) {
HXLINE( 446) ::zpp_nape::geom::ZPP_Vec2 _this24 = _this18->zpp_inner;
HXDLIN( 446) if (hx::IsNotNull( _this24->_validate )) {
HXLINE( 446) _this24->_validate();
}
}
HXDLIN( 446) _hx_tmp49 = (_this18->zpp_inner->y == y2);
}
else {
HXLINE( 446) _hx_tmp49 = false;
}
HXDLIN( 446) if (!(_hx_tmp49)) {
HXLINE( 446) {
HXLINE( 446) _this18->zpp_inner->x = x2;
HXDLIN( 446) _this18->zpp_inner->y = y2;
}
HXDLIN( 446) {
HXLINE( 446) ::zpp_nape::geom::ZPP_Vec2 _this25 = _this18->zpp_inner;
HXDLIN( 446) if (hx::IsNotNull( _this25->_invalidate )) {
HXLINE( 446) _this25->_invalidate(_this25);
}
}
}
HXDLIN( 446) ::nape::geom::Vec2 ret2 = _this18;
HXDLIN( 446) if (direction->zpp_inner->weak) {
HXLINE( 446) bool _hx_tmp52;
HXDLIN( 446) if (hx::IsNotNull( direction )) {
HXLINE( 446) _hx_tmp52 = direction->zpp_disp;
}
else {
HXLINE( 446) _hx_tmp52 = false;
}
HXDLIN( 446) if (_hx_tmp52) {
HXLINE( 446) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 446) {
HXLINE( 446) ::zpp_nape::geom::ZPP_Vec2 _this26 = direction->zpp_inner;
HXDLIN( 446) if (_this26->_immutable) {
HXLINE( 446) HX_STACK_DO_THROW(HX_("Error: Vec2 is immutable",60,ee,1f,bc));
}
HXDLIN( 446) if (hx::IsNotNull( _this26->_isimmutable )) {
HXLINE( 446) _this26->_isimmutable();
}
}
HXDLIN( 446) if (direction->zpp_inner->_inuse) {
HXLINE( 446) HX_STACK_DO_THROW(HX_("Error: This Vec2 is not disposable",b5,d1,d1,d8));
}
HXDLIN( 446) ::zpp_nape::geom::ZPP_Vec2 inner2 = direction->zpp_inner;
HXDLIN( 446) direction->zpp_inner->outer = null();
HXDLIN( 446) direction->zpp_inner = null();
HXDLIN( 446) {
HXLINE( 446) ::nape::geom::Vec2 o4 = direction;
HXDLIN( 446) o4->zpp_pool = null();
HXDLIN( 446) if (hx::IsNotNull( ::zpp_nape::util::ZPP_PubPool_obj::nextVec2 )) {
HXLINE( 446) ::zpp_nape::util::ZPP_PubPool_obj::nextVec2->zpp_pool = o4;
}
else {
HXLINE( 446) ::zpp_nape::util::ZPP_PubPool_obj::poolVec2 = o4;
}
HXDLIN( 446) ::zpp_nape::util::ZPP_PubPool_obj::nextVec2 = o4;
HXDLIN( 446) o4->zpp_disp = true;
}
HXDLIN( 446) {
HXLINE( 446) ::zpp_nape::geom::ZPP_Vec2 o5 = inner2;
HXDLIN( 446) {
HXLINE( 446) if (hx::IsNotNull( o5->outer )) {
HXLINE( 446) o5->outer->zpp_inner = null();
HXDLIN( 446) o5->outer = null();
}
HXDLIN( 446) o5->_isimmutable = null();
HXDLIN( 446) o5->_validate = null();
HXDLIN( 446) o5->_invalidate = null();
}
HXDLIN( 446) o5->next = ::zpp_nape::geom::ZPP_Vec2_obj::zpp_pool;
HXDLIN( 446) ::zpp_nape::geom::ZPP_Vec2_obj::zpp_pool = o5;
}
}
}
}
HXDLIN( 446) if (hx::IsNull( this->zpp_inner_zn->wrap_n )) {
HXLINE( 446) this->zpp_inner_zn->setup_n();
}
}
HXLINE( 447) {
HXLINE( 447) this->zpp_inner->immutable_midstep(HX_("LineJoint::jointMin",3e,e1,3a,51));
HXDLIN( 447) if ((jointMin != jointMin)) {
HXLINE( 447) HX_STACK_DO_THROW(HX_("Error: AngleJoint::jointMin cannot be NaN",a8,63,9e,8c));
}
HXDLIN( 447) if ((this->zpp_inner_zn->jointMin != jointMin)) {
HXLINE( 447) this->zpp_inner_zn->jointMin = jointMin;
HXDLIN( 447) this->zpp_inner->wake();
}
}
HXLINE( 448) {
HXLINE( 448) this->zpp_inner->immutable_midstep(HX_("LineJoint::jointMax",50,da,3a,51));
HXDLIN( 448) if ((jointMax != jointMax)) {
HXLINE( 448) HX_STACK_DO_THROW(HX_("Error: AngleJoint::jointMax cannot be NaN",3a,58,f1,24));
}
HXDLIN( 448) if ((this->zpp_inner_zn->jointMax != jointMax)) {
HXLINE( 448) this->zpp_inner_zn->jointMax = jointMax;
HXDLIN( 448) this->zpp_inner->wake();
}
}
}
Dynamic LineJoint_obj::__CreateEmpty() { return new LineJoint_obj; }
void *LineJoint_obj::_hx_vtable = 0;
Dynamic LineJoint_obj::__Create(hx::DynamicArray inArgs)
{
hx::ObjectPtr< LineJoint_obj > _hx_result = new LineJoint_obj();
_hx_result->__construct(inArgs[0],inArgs[1],inArgs[2],inArgs[3],inArgs[4],inArgs[5],inArgs[6]);
return _hx_result;
}
bool LineJoint_obj::_hx_isInstanceOf(int inClassId) {
if (inClassId<=(int)0x00e9fd26) {
return inClassId==(int)0x00000001 || inClassId==(int)0x00e9fd26;
} else {
return inClassId==(int)0x4a50e1f1;
}
}
::nape::phys::Body LineJoint_obj::get_body1(){
HX_STACKFRAME(&_hx_pos_09c49cc38fbc8a37_222_get_body1)
HXDLIN( 222) if (hx::IsNull( this->zpp_inner_zn->b1 )) {
HXDLIN( 222) return null();
}
else {
HXDLIN( 222) return this->zpp_inner_zn->b1->outer;
}
HXDLIN( 222) return null();
}
HX_DEFINE_DYNAMIC_FUNC0(LineJoint_obj,get_body1,return )
::nape::phys::Body LineJoint_obj::set_body1( ::nape::phys::Body body1){
HX_STACKFRAME(&_hx_pos_09c49cc38fbc8a37_224_set_body1)
HXLINE( 225) {
HXLINE( 226) this->zpp_inner->immutable_midstep((HX_("Constraint::",7d,10,25,6e) + HX_("body1",4f,d3,ef,b6)));
HXLINE( 227) ::zpp_nape::phys::ZPP_Body inbody1;
HXDLIN( 227) if (hx::IsNull( body1 )) {
HXLINE( 227) inbody1 = null();
}
else {
HXLINE( 227) inbody1 = body1->zpp_inner;
}
HXLINE( 228) if (hx::IsNotEq( inbody1,this->zpp_inner_zn->b1 )) {
HXLINE( 229) if (hx::IsNotNull( this->zpp_inner_zn->b1 )) {
HXLINE( 230) bool _hx_tmp;
HXDLIN( 230) ::nape::space::Space _hx_tmp1;
HXDLIN( 230) if (hx::IsNull( this->zpp_inner->space )) {
HXLINE( 230) _hx_tmp1 = null();
}
else {
HXLINE( 230) _hx_tmp1 = this->zpp_inner->space->outer;
}
HXDLIN( 230) if (hx::IsNotNull( _hx_tmp1 )) {
HXLINE( 230) _hx_tmp = hx::IsNotEq( this->zpp_inner_zn->b2,this->zpp_inner_zn->b1 );
}
else {
HXLINE( 230) _hx_tmp = false;
}
HXDLIN( 230) if (_hx_tmp) {
HXLINE( 232) if (hx::IsNotNull( this->zpp_inner_zn->b1 )) {
HXLINE( 232) this->zpp_inner_zn->b1->constraints->remove(this->zpp_inner);
}
}
HXLINE( 235) bool _hx_tmp2;
HXDLIN( 235) if (this->zpp_inner->active) {
HXLINE( 235) ::nape::space::Space _hx_tmp3;
HXDLIN( 235) if (hx::IsNull( this->zpp_inner->space )) {
HXLINE( 235) _hx_tmp3 = null();
}
else {
HXLINE( 235) _hx_tmp3 = this->zpp_inner->space->outer;
}
HXDLIN( 235) _hx_tmp2 = hx::IsNotNull( _hx_tmp3 );
}
else {
HXLINE( 235) _hx_tmp2 = false;
}
HXDLIN( 235) if (_hx_tmp2) {
HXLINE( 235) this->zpp_inner_zn->b1->wake();
}
}
HXLINE( 237) this->zpp_inner_zn->b1 = inbody1;
HXLINE( 238) bool _hx_tmp4;
HXDLIN( 238) bool _hx_tmp5;
HXDLIN( 238) ::nape::space::Space _hx_tmp6;
HXDLIN( 238) if (hx::IsNull( this->zpp_inner->space )) {
HXLINE( 238) _hx_tmp6 = null();
}
else {
HXLINE( 238) _hx_tmp6 = this->zpp_inner->space->outer;
}
HXDLIN( 238) if (hx::IsNotNull( _hx_tmp6 )) {
HXLINE( 238) _hx_tmp5 = hx::IsNotNull( inbody1 );
}
else {
HXLINE( 238) _hx_tmp5 = false;
}
HXDLIN( 238) if (_hx_tmp5) {
HXLINE( 238) _hx_tmp4 = hx::IsNotEq( this->zpp_inner_zn->b2,inbody1 );
}
else {
HXLINE( 238) _hx_tmp4 = false;
}
HXDLIN( 238) if (_hx_tmp4) {
HXLINE( 240) if (hx::IsNotNull( inbody1 )) {
HXLINE( 240) inbody1->constraints->add(this->zpp_inner);
}
}
HXLINE( 243) bool _hx_tmp7;
HXDLIN( 243) if (this->zpp_inner->active) {
HXLINE( 243) ::nape::space::Space _hx_tmp8;
HXDLIN( 243) if (hx::IsNull( this->zpp_inner->space )) {
HXLINE( 243) _hx_tmp8 = null();
}
else {
HXLINE( 243) _hx_tmp8 = this->zpp_inner->space->outer;
}
HXDLIN( 243) _hx_tmp7 = hx::IsNotNull( _hx_tmp8 );
}
else {
HXLINE( 243) _hx_tmp7 = false;
}
HXDLIN( 243) if (_hx_tmp7) {
HXLINE( 244) this->zpp_inner->wake();
HXLINE( 245) if (hx::IsNotNull( inbody1 )) {
HXLINE( 245) inbody1->wake();
}
}
}
}
HXLINE( 249) if (hx::IsNull( this->zpp_inner_zn->b1 )) {
HXLINE( 249) return null();
}
else {
HXLINE( 249) return this->zpp_inner_zn->b1->outer;
}
HXDLIN( 249) return null();
}
HX_DEFINE_DYNAMIC_FUNC1(LineJoint_obj,set_body1,return )
::nape::phys::Body LineJoint_obj::get_body2(){
HX_STACKFRAME(&_hx_pos_09c49cc38fbc8a37_260_get_body2)
HXDLIN( 260) if (hx::IsNull( this->zpp_inner_zn->b2 )) {
HXDLIN( 260) return null();
}
else {
HXDLIN( 260) return this->zpp_inner_zn->b2->outer;
}
HXDLIN( 260) return null();
}
HX_DEFINE_DYNAMIC_FUNC0(LineJoint_obj,get_body2,return )
::nape::phys::Body LineJoint_obj::set_body2( ::nape::phys::Body body2){
HX_STACKFRAME(&_hx_pos_09c49cc38fbc8a37_262_set_body2)
HXLINE( 263) {
HXLINE( 264) this->zpp_inner->immutable_midstep((HX_("Constraint::",7d,10,25,6e) + HX_("body2",50,d3,ef,b6)));
HXLINE( 265) ::zpp_nape::phys::ZPP_Body inbody2;
HXDLIN( 265) if (hx::IsNull( body2 )) {
HXLINE( 265) inbody2 = null();
}
else {
HXLINE( 265) inbody2 = body2->zpp_inner;
}
HXLINE( 266) if (hx::IsNotEq( inbody2,this->zpp_inner_zn->b2 )) {
HXLINE( 267) if (hx::IsNotNull( this->zpp_inner_zn->b2 )) {
HXLINE( 268) bool _hx_tmp;
HXDLIN( 268) ::nape::space::Space _hx_tmp1;
HXDLIN( 268) if (hx::IsNull( this->zpp_inner->space )) {
HXLINE( 268) _hx_tmp1 = null();
}
else {
HXLINE( 268) _hx_tmp1 = this->zpp_inner->space->outer;
}
HXDLIN( 268) if (hx::IsNotNull( _hx_tmp1 )) {
HXLINE( 268) _hx_tmp = hx::IsNotEq( this->zpp_inner_zn->b1,this->zpp_inner_zn->b2 );
}
else {
HXLINE( 268) _hx_tmp = false;
}
HXDLIN( 268) if (_hx_tmp) {
HXLINE( 270) if (hx::IsNotNull( this->zpp_inner_zn->b2 )) {
HXLINE( 270) this->zpp_inner_zn->b2->constraints->remove(this->zpp_inner);
}
}
HXLINE( 273) bool _hx_tmp2;
HXDLIN( 273) if (this->zpp_inner->active) {
HXLINE( 273) ::nape::space::Space _hx_tmp3;
HXDLIN( 273) if (hx::IsNull( this->zpp_inner->space )) {
HXLINE( 273) _hx_tmp3 = null();
}
else {
HXLINE( 273) _hx_tmp3 = this->zpp_inner->space->outer;
}
HXDLIN( 273) _hx_tmp2 = hx::IsNotNull( _hx_tmp3 );
}
else {
HXLINE( 273) _hx_tmp2 = false;
}
HXDLIN( 273) if (_hx_tmp2) {
HXLINE( 273) this->zpp_inner_zn->b2->wake();
}
}
HXLINE( 275) this->zpp_inner_zn->b2 = inbody2;
HXLINE( 276) bool _hx_tmp4;
HXDLIN( 276) bool _hx_tmp5;
HXDLIN( 276) ::nape::space::Space _hx_tmp6;
HXDLIN( 276) if (hx::IsNull( this->zpp_inner->space )) {
HXLINE( 276) _hx_tmp6 = null();
}
else {
HXLINE( 276) _hx_tmp6 = this->zpp_inner->space->outer;
}
HXDLIN( 276) if (hx::IsNotNull( _hx_tmp6 )) {
HXLINE( 276) _hx_tmp5 = hx::IsNotNull( inbody2 );
}
else {
HXLINE( 276) _hx_tmp5 = false;
}
HXDLIN( 276) if (_hx_tmp5) {
HXLINE( 276) _hx_tmp4 = hx::IsNotEq( this->zpp_inner_zn->b1,inbody2 );
}
else {
HXLINE( 276) _hx_tmp4 = false;
}
HXDLIN( 276) if (_hx_tmp4) {
HXLINE( 278) if (hx::IsNotNull( inbody2 )) {
HXLINE( 278) inbody2->constraints->add(this->zpp_inner);
}
}
HXLINE( 281) bool _hx_tmp7;
HXDLIN( 281) if (this->zpp_inner->active) {
HXLINE( 281) ::nape::space::Space _hx_tmp8;
HXDLIN( 281) if (hx::IsNull( this->zpp_inner->space )) {
HXLINE( 281) _hx_tmp8 = null();
}
else {
HXLINE( 281) _hx_tmp8 = this->zpp_inner->space->outer;
}
HXDLIN( 281) _hx_tmp7 = hx::IsNotNull( _hx_tmp8 );
}
else {
HXLINE( 281) _hx_tmp7 = false;
}
HXDLIN( 281) if (_hx_tmp7) {
HXLINE( 282) this->zpp_inner->wake();
HXLINE( 283) if (hx::IsNotNull( inbody2 )) {
HXLINE( 283) inbody2->wake();
}
}
}
}
HXLINE( 287) if (hx::IsNull( this->zpp_inner_zn->b2 )) {
HXLINE( 287) return null();
}
else {
HXLINE( 287) return this->zpp_inner_zn->b2->outer;
}
HXDLIN( 287) return null();
}
HX_DEFINE_DYNAMIC_FUNC1(LineJoint_obj,set_body2,return )
::nape::geom::Vec2 LineJoint_obj::get_anchor1(){
HX_STACKFRAME(&_hx_pos_09c49cc38fbc8a37_296_get_anchor1)
HXLINE( 297) if (hx::IsNull( this->zpp_inner_zn->wrap_a1 )) {
HXLINE( 297) this->zpp_inner_zn->setup_a1();
}
HXLINE( 298) return this->zpp_inner_zn->wrap_a1;
}
HX_DEFINE_DYNAMIC_FUNC0(LineJoint_obj,get_anchor1,return )
::nape::geom::Vec2 LineJoint_obj::set_anchor1( ::nape::geom::Vec2 anchor1){
HX_STACKFRAME(&_hx_pos_09c49cc38fbc8a37_300_set_anchor1)
HXLINE( 301) {
HXLINE( 304) bool _hx_tmp;
HXDLIN( 304) if (hx::IsNotNull( anchor1 )) {
HXLINE( 304) _hx_tmp = anchor1->zpp_disp;
}
else {
HXLINE( 304) _hx_tmp = false;
}
HXDLIN( 304) if (_hx_tmp) {
HXLINE( 304) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXLINE( 308) if (hx::IsNull( anchor1 )) {
HXLINE( 308) HX_STACK_DO_THROW(((HX_("Error: Constraint::",cb,f5,02,d5) + HX_("anchor1",1c,ec,a1,02)) + HX_(" cannot be null",07,dc,5d,15)));
}
HXLINE( 310) {
HXLINE( 310) if (hx::IsNull( this->zpp_inner_zn->wrap_a1 )) {
HXLINE( 310) this->zpp_inner_zn->setup_a1();
}
HXDLIN( 310) ::nape::geom::Vec2 _this = this->zpp_inner_zn->wrap_a1;
HXDLIN( 310) bool _hx_tmp1;
HXDLIN( 310) if (hx::IsNotNull( _this )) {
HXLINE( 310) _hx_tmp1 = _this->zpp_disp;
}
else {
HXLINE( 310) _hx_tmp1 = false;
}
HXDLIN( 310) if (_hx_tmp1) {
HXLINE( 310) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 310) bool _hx_tmp2;
HXDLIN( 310) if (hx::IsNotNull( anchor1 )) {
HXLINE( 310) _hx_tmp2 = anchor1->zpp_disp;
}
else {
HXLINE( 310) _hx_tmp2 = false;
}
HXDLIN( 310) if (_hx_tmp2) {
HXLINE( 310) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 310) {
HXLINE( 310) ::zpp_nape::geom::ZPP_Vec2 _this1 = _this->zpp_inner;
HXDLIN( 310) if (_this1->_immutable) {
HXLINE( 310) HX_STACK_DO_THROW(HX_("Error: Vec2 is immutable",60,ee,1f,bc));
}
HXDLIN( 310) if (hx::IsNotNull( _this1->_isimmutable )) {
HXLINE( 310) _this1->_isimmutable();
}
}
HXDLIN( 310) if (hx::IsNull( anchor1 )) {
HXLINE( 310) HX_STACK_DO_THROW(HX_("Error: Cannot assign null Vec2",95,15,46,66));
}
HXDLIN( 310) bool _hx_tmp3;
HXDLIN( 310) if (hx::IsNotNull( anchor1 )) {
HXLINE( 310) _hx_tmp3 = anchor1->zpp_disp;
}
else {
HXLINE( 310) _hx_tmp3 = false;
}
HXDLIN( 310) if (_hx_tmp3) {
HXLINE( 310) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 310) {
HXLINE( 310) ::zpp_nape::geom::ZPP_Vec2 _this2 = anchor1->zpp_inner;
HXDLIN( 310) if (hx::IsNotNull( _this2->_validate )) {
HXLINE( 310) _this2->_validate();
}
}
HXDLIN( 310) Float x = anchor1->zpp_inner->x;
HXDLIN( 310) bool _hx_tmp4;
HXDLIN( 310) if (hx::IsNotNull( anchor1 )) {
HXLINE( 310) _hx_tmp4 = anchor1->zpp_disp;
}
else {
HXLINE( 310) _hx_tmp4 = false;
}
HXDLIN( 310) if (_hx_tmp4) {
HXLINE( 310) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 310) {
HXLINE( 310) ::zpp_nape::geom::ZPP_Vec2 _this3 = anchor1->zpp_inner;
HXDLIN( 310) if (hx::IsNotNull( _this3->_validate )) {
HXLINE( 310) _this3->_validate();
}
}
HXDLIN( 310) Float y = anchor1->zpp_inner->y;
HXDLIN( 310) bool _hx_tmp5;
HXDLIN( 310) if (hx::IsNotNull( _this )) {
HXLINE( 310) _hx_tmp5 = _this->zpp_disp;
}
else {
HXLINE( 310) _hx_tmp5 = false;
}
HXDLIN( 310) if (_hx_tmp5) {
HXLINE( 310) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 310) {
HXLINE( 310) ::zpp_nape::geom::ZPP_Vec2 _this4 = _this->zpp_inner;
HXDLIN( 310) if (_this4->_immutable) {
HXLINE( 310) HX_STACK_DO_THROW(HX_("Error: Vec2 is immutable",60,ee,1f,bc));
}
HXDLIN( 310) if (hx::IsNotNull( _this4->_isimmutable )) {
HXLINE( 310) _this4->_isimmutable();
}
}
HXDLIN( 310) bool _hx_tmp6;
HXDLIN( 310) if ((x == x)) {
HXLINE( 310) _hx_tmp6 = (y != y);
}
else {
HXLINE( 310) _hx_tmp6 = true;
}
HXDLIN( 310) if (_hx_tmp6) {
HXLINE( 310) HX_STACK_DO_THROW(HX_("Error: Vec2 components cannot be NaN",85,ba,d8,c1));
}
HXDLIN( 310) bool _hx_tmp7;
HXDLIN( 310) bool _hx_tmp8;
HXDLIN( 310) if (hx::IsNotNull( _this )) {
HXLINE( 310) _hx_tmp8 = _this->zpp_disp;
}
else {
HXLINE( 310) _hx_tmp8 = false;
}
HXDLIN( 310) if (_hx_tmp8) {
HXLINE( 310) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 310) {
HXLINE( 310) ::zpp_nape::geom::ZPP_Vec2 _this5 = _this->zpp_inner;
HXDLIN( 310) if (hx::IsNotNull( _this5->_validate )) {
HXLINE( 310) _this5->_validate();
}
}
HXDLIN( 310) if ((_this->zpp_inner->x == x)) {
HXLINE( 310) bool _hx_tmp9;
HXDLIN( 310) if (hx::IsNotNull( _this )) {
HXLINE( 310) _hx_tmp9 = _this->zpp_disp;
}
else {
HXLINE( 310) _hx_tmp9 = false;
}
HXDLIN( 310) if (_hx_tmp9) {
HXLINE( 310) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 310) {
HXLINE( 310) ::zpp_nape::geom::ZPP_Vec2 _this6 = _this->zpp_inner;
HXDLIN( 310) if (hx::IsNotNull( _this6->_validate )) {
HXLINE( 310) _this6->_validate();
}
}
HXDLIN( 310) _hx_tmp7 = (_this->zpp_inner->y == y);
}
else {
HXLINE( 310) _hx_tmp7 = false;
}
HXDLIN( 310) if (!(_hx_tmp7)) {
HXLINE( 310) {
HXLINE( 310) _this->zpp_inner->x = x;
HXDLIN( 310) _this->zpp_inner->y = y;
}
HXDLIN( 310) {
HXLINE( 310) ::zpp_nape::geom::ZPP_Vec2 _this7 = _this->zpp_inner;
HXDLIN( 310) if (hx::IsNotNull( _this7->_invalidate )) {
HXLINE( 310) _this7->_invalidate(_this7);
}
}
}
HXDLIN( 310) ::nape::geom::Vec2 ret = _this;
HXDLIN( 310) if (anchor1->zpp_inner->weak) {
HXLINE( 310) bool _hx_tmp10;
HXDLIN( 310) if (hx::IsNotNull( anchor1 )) {
HXLINE( 310) _hx_tmp10 = anchor1->zpp_disp;
}
else {
HXLINE( 310) _hx_tmp10 = false;
}
HXDLIN( 310) if (_hx_tmp10) {
HXLINE( 310) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 310) {
HXLINE( 310) ::zpp_nape::geom::ZPP_Vec2 _this8 = anchor1->zpp_inner;
HXDLIN( 310) if (_this8->_immutable) {
HXLINE( 310) HX_STACK_DO_THROW(HX_("Error: Vec2 is immutable",60,ee,1f,bc));
}
HXDLIN( 310) if (hx::IsNotNull( _this8->_isimmutable )) {
HXLINE( 310) _this8->_isimmutable();
}
}
HXDLIN( 310) if (anchor1->zpp_inner->_inuse) {
HXLINE( 310) HX_STACK_DO_THROW(HX_("Error: This Vec2 is not disposable",b5,d1,d1,d8));
}
HXDLIN( 310) ::zpp_nape::geom::ZPP_Vec2 inner = anchor1->zpp_inner;
HXDLIN( 310) anchor1->zpp_inner->outer = null();
HXDLIN( 310) anchor1->zpp_inner = null();
HXDLIN( 310) {
HXLINE( 310) ::nape::geom::Vec2 o = anchor1;
HXDLIN( 310) o->zpp_pool = null();
HXDLIN( 310) if (hx::IsNotNull( ::zpp_nape::util::ZPP_PubPool_obj::nextVec2 )) {
HXLINE( 310) ::zpp_nape::util::ZPP_PubPool_obj::nextVec2->zpp_pool = o;
}
else {
HXLINE( 310) ::zpp_nape::util::ZPP_PubPool_obj::poolVec2 = o;
}
HXDLIN( 310) ::zpp_nape::util::ZPP_PubPool_obj::nextVec2 = o;
HXDLIN( 310) o->zpp_disp = true;
}
HXDLIN( 310) {
HXLINE( 310) ::zpp_nape::geom::ZPP_Vec2 o1 = inner;
HXDLIN( 310) {
HXLINE( 310) if (hx::IsNotNull( o1->outer )) {
HXLINE( 310) o1->outer->zpp_inner = null();
HXDLIN( 310) o1->outer = null();
}
HXDLIN( 310) o1->_isimmutable = null();
HXDLIN( 310) o1->_validate = null();
HXDLIN( 310) o1->_invalidate = null();
}
HXDLIN( 310) o1->next = ::zpp_nape::geom::ZPP_Vec2_obj::zpp_pool;
HXDLIN( 310) ::zpp_nape::geom::ZPP_Vec2_obj::zpp_pool = o1;
}
}
}
}
HXLINE( 312) if (hx::IsNull( this->zpp_inner_zn->wrap_a1 )) {
HXLINE( 312) this->zpp_inner_zn->setup_a1();
}
HXDLIN( 312) return this->zpp_inner_zn->wrap_a1;
}
HX_DEFINE_DYNAMIC_FUNC1(LineJoint_obj,set_anchor1,return )
::nape::geom::Vec2 LineJoint_obj::get_anchor2(){
HX_STACKFRAME(&_hx_pos_09c49cc38fbc8a37_321_get_anchor2)
HXLINE( 322) if (hx::IsNull( this->zpp_inner_zn->wrap_a2 )) {
HXLINE( 322) this->zpp_inner_zn->setup_a2();
}
HXLINE( 323) return this->zpp_inner_zn->wrap_a2;
}
HX_DEFINE_DYNAMIC_FUNC0(LineJoint_obj,get_anchor2,return )
::nape::geom::Vec2 LineJoint_obj::set_anchor2( ::nape::geom::Vec2 anchor2){
HX_STACKFRAME(&_hx_pos_09c49cc38fbc8a37_325_set_anchor2)
HXLINE( 326) {
HXLINE( 329) bool _hx_tmp;
HXDLIN( 329) if (hx::IsNotNull( anchor2 )) {
HXLINE( 329) _hx_tmp = anchor2->zpp_disp;
}
else {
HXLINE( 329) _hx_tmp = false;
}
HXDLIN( 329) if (_hx_tmp) {
HXLINE( 329) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXLINE( 333) if (hx::IsNull( anchor2 )) {
HXLINE( 333) HX_STACK_DO_THROW(((HX_("Error: Constraint::",cb,f5,02,d5) + HX_("anchor2",1d,ec,a1,02)) + HX_(" cannot be null",07,dc,5d,15)));
}
HXLINE( 335) {
HXLINE( 335) if (hx::IsNull( this->zpp_inner_zn->wrap_a2 )) {
HXLINE( 335) this->zpp_inner_zn->setup_a2();
}
HXDLIN( 335) ::nape::geom::Vec2 _this = this->zpp_inner_zn->wrap_a2;
HXDLIN( 335) bool _hx_tmp1;
HXDLIN( 335) if (hx::IsNotNull( _this )) {
HXLINE( 335) _hx_tmp1 = _this->zpp_disp;
}
else {
HXLINE( 335) _hx_tmp1 = false;
}
HXDLIN( 335) if (_hx_tmp1) {
HXLINE( 335) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 335) bool _hx_tmp2;
HXDLIN( 335) if (hx::IsNotNull( anchor2 )) {
HXLINE( 335) _hx_tmp2 = anchor2->zpp_disp;
}
else {
HXLINE( 335) _hx_tmp2 = false;
}
HXDLIN( 335) if (_hx_tmp2) {
HXLINE( 335) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 335) {
HXLINE( 335) ::zpp_nape::geom::ZPP_Vec2 _this1 = _this->zpp_inner;
HXDLIN( 335) if (_this1->_immutable) {
HXLINE( 335) HX_STACK_DO_THROW(HX_("Error: Vec2 is immutable",60,ee,1f,bc));
}
HXDLIN( 335) if (hx::IsNotNull( _this1->_isimmutable )) {
HXLINE( 335) _this1->_isimmutable();
}
}
HXDLIN( 335) if (hx::IsNull( anchor2 )) {
HXLINE( 335) HX_STACK_DO_THROW(HX_("Error: Cannot assign null Vec2",95,15,46,66));
}
HXDLIN( 335) bool _hx_tmp3;
HXDLIN( 335) if (hx::IsNotNull( anchor2 )) {
HXLINE( 335) _hx_tmp3 = anchor2->zpp_disp;
}
else {
HXLINE( 335) _hx_tmp3 = false;
}
HXDLIN( 335) if (_hx_tmp3) {
HXLINE( 335) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 335) {
HXLINE( 335) ::zpp_nape::geom::ZPP_Vec2 _this2 = anchor2->zpp_inner;
HXDLIN( 335) if (hx::IsNotNull( _this2->_validate )) {
HXLINE( 335) _this2->_validate();
}
}
HXDLIN( 335) Float x = anchor2->zpp_inner->x;
HXDLIN( 335) bool _hx_tmp4;
HXDLIN( 335) if (hx::IsNotNull( anchor2 )) {
HXLINE( 335) _hx_tmp4 = anchor2->zpp_disp;
}
else {
HXLINE( 335) _hx_tmp4 = false;
}
HXDLIN( 335) if (_hx_tmp4) {
HXLINE( 335) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 335) {
HXLINE( 335) ::zpp_nape::geom::ZPP_Vec2 _this3 = anchor2->zpp_inner;
HXDLIN( 335) if (hx::IsNotNull( _this3->_validate )) {
HXLINE( 335) _this3->_validate();
}
}
HXDLIN( 335) Float y = anchor2->zpp_inner->y;
HXDLIN( 335) bool _hx_tmp5;
HXDLIN( 335) if (hx::IsNotNull( _this )) {
HXLINE( 335) _hx_tmp5 = _this->zpp_disp;
}
else {
HXLINE( 335) _hx_tmp5 = false;
}
HXDLIN( 335) if (_hx_tmp5) {
HXLINE( 335) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 335) {
HXLINE( 335) ::zpp_nape::geom::ZPP_Vec2 _this4 = _this->zpp_inner;
HXDLIN( 335) if (_this4->_immutable) {
HXLINE( 335) HX_STACK_DO_THROW(HX_("Error: Vec2 is immutable",60,ee,1f,bc));
}
HXDLIN( 335) if (hx::IsNotNull( _this4->_isimmutable )) {
HXLINE( 335) _this4->_isimmutable();
}
}
HXDLIN( 335) bool _hx_tmp6;
HXDLIN( 335) if ((x == x)) {
HXLINE( 335) _hx_tmp6 = (y != y);
}
else {
HXLINE( 335) _hx_tmp6 = true;
}
HXDLIN( 335) if (_hx_tmp6) {
HXLINE( 335) HX_STACK_DO_THROW(HX_("Error: Vec2 components cannot be NaN",85,ba,d8,c1));
}
HXDLIN( 335) bool _hx_tmp7;
HXDLIN( 335) bool _hx_tmp8;
HXDLIN( 335) if (hx::IsNotNull( _this )) {
HXLINE( 335) _hx_tmp8 = _this->zpp_disp;
}
else {
HXLINE( 335) _hx_tmp8 = false;
}
HXDLIN( 335) if (_hx_tmp8) {
HXLINE( 335) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 335) {
HXLINE( 335) ::zpp_nape::geom::ZPP_Vec2 _this5 = _this->zpp_inner;
HXDLIN( 335) if (hx::IsNotNull( _this5->_validate )) {
HXLINE( 335) _this5->_validate();
}
}
HXDLIN( 335) if ((_this->zpp_inner->x == x)) {
HXLINE( 335) bool _hx_tmp9;
HXDLIN( 335) if (hx::IsNotNull( _this )) {
HXLINE( 335) _hx_tmp9 = _this->zpp_disp;
}
else {
HXLINE( 335) _hx_tmp9 = false;
}
HXDLIN( 335) if (_hx_tmp9) {
HXLINE( 335) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 335) {
HXLINE( 335) ::zpp_nape::geom::ZPP_Vec2 _this6 = _this->zpp_inner;
HXDLIN( 335) if (hx::IsNotNull( _this6->_validate )) {
HXLINE( 335) _this6->_validate();
}
}
HXDLIN( 335) _hx_tmp7 = (_this->zpp_inner->y == y);
}
else {
HXLINE( 335) _hx_tmp7 = false;
}
HXDLIN( 335) if (!(_hx_tmp7)) {
HXLINE( 335) {
HXLINE( 335) _this->zpp_inner->x = x;
HXDLIN( 335) _this->zpp_inner->y = y;
}
HXDLIN( 335) {
HXLINE( 335) ::zpp_nape::geom::ZPP_Vec2 _this7 = _this->zpp_inner;
HXDLIN( 335) if (hx::IsNotNull( _this7->_invalidate )) {
HXLINE( 335) _this7->_invalidate(_this7);
}
}
}
HXDLIN( 335) ::nape::geom::Vec2 ret = _this;
HXDLIN( 335) if (anchor2->zpp_inner->weak) {
HXLINE( 335) bool _hx_tmp10;
HXDLIN( 335) if (hx::IsNotNull( anchor2 )) {
HXLINE( 335) _hx_tmp10 = anchor2->zpp_disp;
}
else {
HXLINE( 335) _hx_tmp10 = false;
}
HXDLIN( 335) if (_hx_tmp10) {
HXLINE( 335) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 335) {
HXLINE( 335) ::zpp_nape::geom::ZPP_Vec2 _this8 = anchor2->zpp_inner;
HXDLIN( 335) if (_this8->_immutable) {
HXLINE( 335) HX_STACK_DO_THROW(HX_("Error: Vec2 is immutable",60,ee,1f,bc));
}
HXDLIN( 335) if (hx::IsNotNull( _this8->_isimmutable )) {
HXLINE( 335) _this8->_isimmutable();
}
}
HXDLIN( 335) if (anchor2->zpp_inner->_inuse) {
HXLINE( 335) HX_STACK_DO_THROW(HX_("Error: This Vec2 is not disposable",b5,d1,d1,d8));
}
HXDLIN( 335) ::zpp_nape::geom::ZPP_Vec2 inner = anchor2->zpp_inner;
HXDLIN( 335) anchor2->zpp_inner->outer = null();
HXDLIN( 335) anchor2->zpp_inner = null();
HXDLIN( 335) {
HXLINE( 335) ::nape::geom::Vec2 o = anchor2;
HXDLIN( 335) o->zpp_pool = null();
HXDLIN( 335) if (hx::IsNotNull( ::zpp_nape::util::ZPP_PubPool_obj::nextVec2 )) {
HXLINE( 335) ::zpp_nape::util::ZPP_PubPool_obj::nextVec2->zpp_pool = o;
}
else {
HXLINE( 335) ::zpp_nape::util::ZPP_PubPool_obj::poolVec2 = o;
}
HXDLIN( 335) ::zpp_nape::util::ZPP_PubPool_obj::nextVec2 = o;
HXDLIN( 335) o->zpp_disp = true;
}
HXDLIN( 335) {
HXLINE( 335) ::zpp_nape::geom::ZPP_Vec2 o1 = inner;
HXDLIN( 335) {
HXLINE( 335) if (hx::IsNotNull( o1->outer )) {
HXLINE( 335) o1->outer->zpp_inner = null();
HXDLIN( 335) o1->outer = null();
}
HXDLIN( 335) o1->_isimmutable = null();
HXDLIN( 335) o1->_validate = null();
HXDLIN( 335) o1->_invalidate = null();
}
HXDLIN( 335) o1->next = ::zpp_nape::geom::ZPP_Vec2_obj::zpp_pool;
HXDLIN( 335) ::zpp_nape::geom::ZPP_Vec2_obj::zpp_pool = o1;
}
}
}
}
HXLINE( 337) if (hx::IsNull( this->zpp_inner_zn->wrap_a2 )) {
HXLINE( 337) this->zpp_inner_zn->setup_a2();
}
HXDLIN( 337) return this->zpp_inner_zn->wrap_a2;
}
HX_DEFINE_DYNAMIC_FUNC1(LineJoint_obj,set_anchor2,return )
::nape::geom::Vec2 LineJoint_obj::get_direction(){
HX_STACKFRAME(&_hx_pos_09c49cc38fbc8a37_347_get_direction)
HXLINE( 348) if (hx::IsNull( this->zpp_inner_zn->wrap_n )) {
HXLINE( 348) this->zpp_inner_zn->setup_n();
}
HXLINE( 349) return this->zpp_inner_zn->wrap_n;
}
HX_DEFINE_DYNAMIC_FUNC0(LineJoint_obj,get_direction,return )
::nape::geom::Vec2 LineJoint_obj::set_direction( ::nape::geom::Vec2 direction){
HX_STACKFRAME(&_hx_pos_09c49cc38fbc8a37_351_set_direction)
HXLINE( 352) {
HXLINE( 355) bool _hx_tmp;
HXDLIN( 355) if (hx::IsNotNull( direction )) {
HXLINE( 355) _hx_tmp = direction->zpp_disp;
}
else {
HXLINE( 355) _hx_tmp = false;
}
HXDLIN( 355) if (_hx_tmp) {
HXLINE( 355) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXLINE( 359) if (hx::IsNull( direction )) {
HXLINE( 359) HX_STACK_DO_THROW(((HX_("Error: Constraint::",cb,f5,02,d5) + HX_("direction",3f,62,40,10)) + HX_(" cannot be null",07,dc,5d,15)));
}
HXLINE( 361) {
HXLINE( 361) if (hx::IsNull( this->zpp_inner_zn->wrap_n )) {
HXLINE( 361) this->zpp_inner_zn->setup_n();
}
HXDLIN( 361) ::nape::geom::Vec2 _this = this->zpp_inner_zn->wrap_n;
HXDLIN( 361) bool _hx_tmp1;
HXDLIN( 361) if (hx::IsNotNull( _this )) {
HXLINE( 361) _hx_tmp1 = _this->zpp_disp;
}
else {
HXLINE( 361) _hx_tmp1 = false;
}
HXDLIN( 361) if (_hx_tmp1) {
HXLINE( 361) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 361) bool _hx_tmp2;
HXDLIN( 361) if (hx::IsNotNull( direction )) {
HXLINE( 361) _hx_tmp2 = direction->zpp_disp;
}
else {
HXLINE( 361) _hx_tmp2 = false;
}
HXDLIN( 361) if (_hx_tmp2) {
HXLINE( 361) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 361) {
HXLINE( 361) ::zpp_nape::geom::ZPP_Vec2 _this1 = _this->zpp_inner;
HXDLIN( 361) if (_this1->_immutable) {
HXLINE( 361) HX_STACK_DO_THROW(HX_("Error: Vec2 is immutable",60,ee,1f,bc));
}
HXDLIN( 361) if (hx::IsNotNull( _this1->_isimmutable )) {
HXLINE( 361) _this1->_isimmutable();
}
}
HXDLIN( 361) if (hx::IsNull( direction )) {
HXLINE( 361) HX_STACK_DO_THROW(HX_("Error: Cannot assign null Vec2",95,15,46,66));
}
HXDLIN( 361) bool _hx_tmp3;
HXDLIN( 361) if (hx::IsNotNull( direction )) {
HXLINE( 361) _hx_tmp3 = direction->zpp_disp;
}
else {
HXLINE( 361) _hx_tmp3 = false;
}
HXDLIN( 361) if (_hx_tmp3) {
HXLINE( 361) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 361) {
HXLINE( 361) ::zpp_nape::geom::ZPP_Vec2 _this2 = direction->zpp_inner;
HXDLIN( 361) if (hx::IsNotNull( _this2->_validate )) {
HXLINE( 361) _this2->_validate();
}
}
HXDLIN( 361) Float x = direction->zpp_inner->x;
HXDLIN( 361) bool _hx_tmp4;
HXDLIN( 361) if (hx::IsNotNull( direction )) {
HXLINE( 361) _hx_tmp4 = direction->zpp_disp;
}
else {
HXLINE( 361) _hx_tmp4 = false;
}
HXDLIN( 361) if (_hx_tmp4) {
HXLINE( 361) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 361) {
HXLINE( 361) ::zpp_nape::geom::ZPP_Vec2 _this3 = direction->zpp_inner;
HXDLIN( 361) if (hx::IsNotNull( _this3->_validate )) {
HXLINE( 361) _this3->_validate();
}
}
HXDLIN( 361) Float y = direction->zpp_inner->y;
HXDLIN( 361) bool _hx_tmp5;
HXDLIN( 361) if (hx::IsNotNull( _this )) {
HXLINE( 361) _hx_tmp5 = _this->zpp_disp;
}
else {
HXLINE( 361) _hx_tmp5 = false;
}
HXDLIN( 361) if (_hx_tmp5) {
HXLINE( 361) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 361) {
HXLINE( 361) ::zpp_nape::geom::ZPP_Vec2 _this4 = _this->zpp_inner;
HXDLIN( 361) if (_this4->_immutable) {
HXLINE( 361) HX_STACK_DO_THROW(HX_("Error: Vec2 is immutable",60,ee,1f,bc));
}
HXDLIN( 361) if (hx::IsNotNull( _this4->_isimmutable )) {
HXLINE( 361) _this4->_isimmutable();
}
}
HXDLIN( 361) bool _hx_tmp6;
HXDLIN( 361) if ((x == x)) {
HXLINE( 361) _hx_tmp6 = (y != y);
}
else {
HXLINE( 361) _hx_tmp6 = true;
}
HXDLIN( 361) if (_hx_tmp6) {
HXLINE( 361) HX_STACK_DO_THROW(HX_("Error: Vec2 components cannot be NaN",85,ba,d8,c1));
}
HXDLIN( 361) bool _hx_tmp7;
HXDLIN( 361) bool _hx_tmp8;
HXDLIN( 361) if (hx::IsNotNull( _this )) {
HXLINE( 361) _hx_tmp8 = _this->zpp_disp;
}
else {
HXLINE( 361) _hx_tmp8 = false;
}
HXDLIN( 361) if (_hx_tmp8) {
HXLINE( 361) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 361) {
HXLINE( 361) ::zpp_nape::geom::ZPP_Vec2 _this5 = _this->zpp_inner;
HXDLIN( 361) if (hx::IsNotNull( _this5->_validate )) {
HXLINE( 361) _this5->_validate();
}
}
HXDLIN( 361) if ((_this->zpp_inner->x == x)) {
HXLINE( 361) bool _hx_tmp9;
HXDLIN( 361) if (hx::IsNotNull( _this )) {
HXLINE( 361) _hx_tmp9 = _this->zpp_disp;
}
else {
HXLINE( 361) _hx_tmp9 = false;
}
HXDLIN( 361) if (_hx_tmp9) {
HXLINE( 361) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 361) {
HXLINE( 361) ::zpp_nape::geom::ZPP_Vec2 _this6 = _this->zpp_inner;
HXDLIN( 361) if (hx::IsNotNull( _this6->_validate )) {
HXLINE( 361) _this6->_validate();
}
}
HXDLIN( 361) _hx_tmp7 = (_this->zpp_inner->y == y);
}
else {
HXLINE( 361) _hx_tmp7 = false;
}
HXDLIN( 361) if (!(_hx_tmp7)) {
HXLINE( 361) {
HXLINE( 361) _this->zpp_inner->x = x;
HXDLIN( 361) _this->zpp_inner->y = y;
}
HXDLIN( 361) {
HXLINE( 361) ::zpp_nape::geom::ZPP_Vec2 _this7 = _this->zpp_inner;
HXDLIN( 361) if (hx::IsNotNull( _this7->_invalidate )) {
HXLINE( 361) _this7->_invalidate(_this7);
}
}
}
HXDLIN( 361) ::nape::geom::Vec2 ret = _this;
HXDLIN( 361) if (direction->zpp_inner->weak) {
HXLINE( 361) bool _hx_tmp10;
HXDLIN( 361) if (hx::IsNotNull( direction )) {
HXLINE( 361) _hx_tmp10 = direction->zpp_disp;
}
else {
HXLINE( 361) _hx_tmp10 = false;
}
HXDLIN( 361) if (_hx_tmp10) {
HXLINE( 361) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74)));
}
HXDLIN( 361) {
HXLINE( 361) ::zpp_nape::geom::ZPP_Vec2 _this8 = direction->zpp_inner;
HXDLIN( 361) if (_this8->_immutable) {
HXLINE( 361) HX_STACK_DO_THROW(HX_("Error: Vec2 is immutable",60,ee,1f,bc));
}
HXDLIN( 361) if (hx::IsNotNull( _this8->_isimmutable )) {
HXLINE( 361) _this8->_isimmutable();
}
}
HXDLIN( 361) if (direction->zpp_inner->_inuse) {
HXLINE( 361) HX_STACK_DO_THROW(HX_("Error: This Vec2 is not disposable",b5,d1,d1,d8));
}
HXDLIN( 361) ::zpp_nape::geom::ZPP_Vec2 inner = direction->zpp_inner;
HXDLIN( 361) direction->zpp_inner->outer = null();
HXDLIN( 361) direction->zpp_inner = null();
HXDLIN( 361) {
HXLINE( 361) ::nape::geom::Vec2 o = direction;
HXDLIN( 361) o->zpp_pool = null();
HXDLIN( 361) if (hx::IsNotNull( ::zpp_nape::util::ZPP_PubPool_obj::nextVec2 )) {
HXLINE( 361) ::zpp_nape::util::ZPP_PubPool_obj::nextVec2->zpp_pool = o;
}
else {
HXLINE( 361) ::zpp_nape::util::ZPP_PubPool_obj::poolVec2 = o;
}
HXDLIN( 361) ::zpp_nape::util::ZPP_PubPool_obj::nextVec2 = o;
HXDLIN( 361) o->zpp_disp = true;
}
HXDLIN( 361) {
HXLINE( 361) ::zpp_nape::geom::ZPP_Vec2 o1 = inner;
HXDLIN( 361) {
HXLINE( 361) if (hx::IsNotNull( o1->outer )) {
HXLINE( 361) o1->outer->zpp_inner = null();
HXDLIN( 361) o1->outer = null();
}
HXDLIN( 361) o1->_isimmutable = null();
HXDLIN( 361) o1->_validate = null();
HXDLIN( 361) o1->_invalidate = null();
}
HXDLIN( 361) o1->next = ::zpp_nape::geom::ZPP_Vec2_obj::zpp_pool;
HXDLIN( 361) ::zpp_nape::geom::ZPP_Vec2_obj::zpp_pool = o1;
}
}
}
}
HXLINE( 363) if (hx::IsNull( this->zpp_inner_zn->wrap_n )) {
HXLINE( 363) this->zpp_inner_zn->setup_n();
}
HXDLIN( 363) return this->zpp_inner_zn->wrap_n;
}
HX_DEFINE_DYNAMIC_FUNC1(LineJoint_obj,set_direction,return )
Float LineJoint_obj::get_jointMin(){
HX_STACKFRAME(&_hx_pos_09c49cc38fbc8a37_373_get_jointMin)
HXDLIN( 373) return this->zpp_inner_zn->jointMin;
}
HX_DEFINE_DYNAMIC_FUNC0(LineJoint_obj,get_jointMin,return )
Float LineJoint_obj::set_jointMin(Float jointMin){
HX_STACKFRAME(&_hx_pos_09c49cc38fbc8a37_375_set_jointMin)
HXLINE( 376) {
HXLINE( 377) this->zpp_inner->immutable_midstep(HX_("LineJoint::jointMin",3e,e1,3a,51));
HXLINE( 379) if ((jointMin != jointMin)) {
HXLINE( 380) HX_STACK_DO_THROW(HX_("Error: AngleJoint::jointMin cannot be NaN",a8,63,9e,8c));
}
HXLINE( 383) if ((this->zpp_inner_zn->jointMin != jointMin)) {
HXLINE( 384) this->zpp_inner_zn->jointMin = jointMin;
HXLINE( 385) this->zpp_inner->wake();
}
}
HXLINE( 388) return this->zpp_inner_zn->jointMin;
}
HX_DEFINE_DYNAMIC_FUNC1(LineJoint_obj,set_jointMin,return )
Float LineJoint_obj::get_jointMax(){
HX_STACKFRAME(&_hx_pos_09c49cc38fbc8a37_398_get_jointMax)
HXDLIN( 398) return this->zpp_inner_zn->jointMax;
}
HX_DEFINE_DYNAMIC_FUNC0(LineJoint_obj,get_jointMax,return )
Float LineJoint_obj::set_jointMax(Float jointMax){
HX_STACKFRAME(&_hx_pos_09c49cc38fbc8a37_400_set_jointMax)
HXLINE( 401) {
HXLINE( 402) this->zpp_inner->immutable_midstep(HX_("LineJoint::jointMax",50,da,3a,51));
HXLINE( 404) if ((jointMax != jointMax)) {
HXLINE( 405) HX_STACK_DO_THROW(HX_("Error: AngleJoint::jointMax cannot be NaN",3a,58,f1,24));
}
HXLINE( 408) if ((this->zpp_inner_zn->jointMax != jointMax)) {
HXLINE( 409) this->zpp_inner_zn->jointMax = jointMax;
HXLINE( 410) this->zpp_inner->wake();
}
}
HXLINE( 413) return this->zpp_inner_zn->jointMax;
}
HX_DEFINE_DYNAMIC_FUNC1(LineJoint_obj,set_jointMax,return )
::nape::geom::MatMN LineJoint_obj::impulse(){
HX_GC_STACKFRAME(&_hx_pos_09c49cc38fbc8a37_455_impulse)
HXLINE( 456) ::nape::geom::MatMN ret = ::nape::geom::MatMN_obj::__alloc( HX_CTX ,2,1);
HXLINE( 457) {
HXLINE( 457) bool _hx_tmp;
HXDLIN( 457) if ((0 < ret->zpp_inner->m)) {
HXLINE( 457) _hx_tmp = (0 >= ret->zpp_inner->n);
}
else {
HXLINE( 457) _hx_tmp = true;
}
HXDLIN( 457) if (_hx_tmp) {
HXLINE( 457) HX_STACK_DO_THROW(HX_("Error: MatMN indices out of range",cc,72,58,e6));
}
HXDLIN( 457) ret->zpp_inner->x[(0 * ret->zpp_inner->n)] = this->zpp_inner_zn->jAccx;
}
HXLINE( 458) {
HXLINE( 458) bool _hx_tmp1;
HXDLIN( 458) if ((1 < ret->zpp_inner->m)) {
HXLINE( 458) _hx_tmp1 = (0 >= ret->zpp_inner->n);
}
else {
HXLINE( 458) _hx_tmp1 = true;
}
HXDLIN( 458) if (_hx_tmp1) {
HXLINE( 458) HX_STACK_DO_THROW(HX_("Error: MatMN indices out of range",cc,72,58,e6));
}
HXDLIN( 458) ret->zpp_inner->x[ret->zpp_inner->n] = this->zpp_inner_zn->jAccy;
}
HXLINE( 459) return ret;
}
::nape::geom::Vec3 LineJoint_obj::bodyImpulse( ::nape::phys::Body body){
HX_STACKFRAME(&_hx_pos_09c49cc38fbc8a37_464_bodyImpulse)
HXLINE( 466) if (hx::IsNull( body )) {
HXLINE( 467) HX_STACK_DO_THROW(HX_("Error: Cannot evaluate impulse on null body",9d,b5,dc,16));
}
HXLINE( 469) bool _hx_tmp;
HXDLIN( 469) ::nape::phys::Body _hx_tmp1;
HXDLIN( 469) if (hx::IsNull( this->zpp_inner_zn->b1 )) {
HXLINE( 469) _hx_tmp1 = null();
}
else {
HXLINE( 469) _hx_tmp1 = this->zpp_inner_zn->b1->outer;
}
HXDLIN( 469) if (hx::IsNotEq( body,_hx_tmp1 )) {
HXLINE( 469) ::nape::phys::Body _hx_tmp2;
HXDLIN( 469) if (hx::IsNull( this->zpp_inner_zn->b2 )) {
HXLINE( 469) _hx_tmp2 = null();
}
else {
HXLINE( 469) _hx_tmp2 = this->zpp_inner_zn->b2->outer;
}
HXDLIN( 469) _hx_tmp = hx::IsNotEq( body,_hx_tmp2 );
}
else {
HXLINE( 469) _hx_tmp = false;
}
HXDLIN( 469) if (_hx_tmp) {
HXLINE( 470) HX_STACK_DO_THROW(HX_("Error: Body is not linked to this constraint",2e,e5,48,bf));
}
HXLINE( 473) if (!(this->zpp_inner->active)) {
HXLINE( 474) return ::nape::geom::Vec3_obj::get(null(),null(),null());
}
else {
HXLINE( 477) return this->zpp_inner_zn->bodyImpulse(body->zpp_inner);
}
HXLINE( 473) return null();
}
void LineJoint_obj::visitBodies( ::Dynamic lambda){
HX_STACKFRAME(&_hx_pos_09c49cc38fbc8a37_483_visitBodies)
HXLINE( 484) ::nape::phys::Body _hx_tmp;
HXDLIN( 484) if (hx::IsNull( this->zpp_inner_zn->b1 )) {
HXLINE( 484) _hx_tmp = null();
}
else {
HXLINE( 484) _hx_tmp = this->zpp_inner_zn->b1->outer;
}
HXDLIN( 484) if (hx::IsNotNull( _hx_tmp )) {
HXLINE( 485) ::nape::phys::Body _hx_tmp1;
HXDLIN( 485) if (hx::IsNull( this->zpp_inner_zn->b1 )) {
HXLINE( 485) _hx_tmp1 = null();
}
else {
HXLINE( 485) _hx_tmp1 = this->zpp_inner_zn->b1->outer;
}
HXDLIN( 485) lambda(_hx_tmp1);
}
HXLINE( 487) bool _hx_tmp2;
HXDLIN( 487) ::nape::phys::Body _hx_tmp3;
HXDLIN( 487) if (hx::IsNull( this->zpp_inner_zn->b2 )) {
HXLINE( 487) _hx_tmp3 = null();
}
else {
HXLINE( 487) _hx_tmp3 = this->zpp_inner_zn->b2->outer;
}
HXDLIN( 487) if (hx::IsNotNull( _hx_tmp3 )) {
HXLINE( 487) ::nape::phys::Body _hx_tmp4;
HXDLIN( 487) if (hx::IsNull( this->zpp_inner_zn->b2 )) {
HXLINE( 487) _hx_tmp4 = null();
}
else {
HXLINE( 487) _hx_tmp4 = this->zpp_inner_zn->b2->outer;
}
HXDLIN( 487) ::nape::phys::Body _hx_tmp5;
HXDLIN( 487) if (hx::IsNull( this->zpp_inner_zn->b1 )) {
HXLINE( 487) _hx_tmp5 = null();
}
else {
HXLINE( 487) _hx_tmp5 = this->zpp_inner_zn->b1->outer;
}
HXDLIN( 487) _hx_tmp2 = hx::IsNotEq( _hx_tmp4,_hx_tmp5 );
}
else {
HXLINE( 487) _hx_tmp2 = false;
}
HXDLIN( 487) if (_hx_tmp2) {
HXLINE( 488) ::nape::phys::Body _hx_tmp6;
HXDLIN( 488) if (hx::IsNull( this->zpp_inner_zn->b2 )) {
HXLINE( 488) _hx_tmp6 = null();
}
else {
HXLINE( 488) _hx_tmp6 = this->zpp_inner_zn->b2->outer;
}
HXDLIN( 488) lambda(_hx_tmp6);
}
}
hx::ObjectPtr< LineJoint_obj > LineJoint_obj::__new( ::nape::phys::Body body1, ::nape::phys::Body body2, ::nape::geom::Vec2 anchor1, ::nape::geom::Vec2 anchor2, ::nape::geom::Vec2 direction,Float jointMin,Float jointMax) {
hx::ObjectPtr< LineJoint_obj > __this = new LineJoint_obj();
__this->__construct(body1,body2,anchor1,anchor2,direction,jointMin,jointMax);
return __this;
}
hx::ObjectPtr< LineJoint_obj > LineJoint_obj::__alloc(hx::Ctx *_hx_ctx, ::nape::phys::Body body1, ::nape::phys::Body body2, ::nape::geom::Vec2 anchor1, ::nape::geom::Vec2 anchor2, ::nape::geom::Vec2 direction,Float jointMin,Float jointMax) {
LineJoint_obj *__this = (LineJoint_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(LineJoint_obj), true, "nape.constraint.LineJoint"));
*(void **)__this = LineJoint_obj::_hx_vtable;
__this->__construct(body1,body2,anchor1,anchor2,direction,jointMin,jointMax);
return __this;
}
LineJoint_obj::LineJoint_obj()
{
}
void LineJoint_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(LineJoint);
HX_MARK_MEMBER_NAME(zpp_inner_zn,"zpp_inner_zn");
::nape::constraint::Constraint_obj::__Mark(HX_MARK_ARG);
HX_MARK_END_CLASS();
}
void LineJoint_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(zpp_inner_zn,"zpp_inner_zn");
::nape::constraint::Constraint_obj::__Visit(HX_VISIT_ARG);
}
hx::Val LineJoint_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 5:
if (HX_FIELD_EQ(inName,"body1") ) { if (inCallProp == hx::paccAlways) return hx::Val( get_body1() ); }
if (HX_FIELD_EQ(inName,"body2") ) { if (inCallProp == hx::paccAlways) return hx::Val( get_body2() ); }
break;
case 7:
if (HX_FIELD_EQ(inName,"anchor1") ) { if (inCallProp == hx::paccAlways) return hx::Val( get_anchor1() ); }
if (HX_FIELD_EQ(inName,"anchor2") ) { if (inCallProp == hx::paccAlways) return hx::Val( get_anchor2() ); }
if (HX_FIELD_EQ(inName,"impulse") ) { return hx::Val( impulse_dyn() ); }
break;
case 8:
if (HX_FIELD_EQ(inName,"jointMin") ) { if (inCallProp == hx::paccAlways) return hx::Val( get_jointMin() ); }
if (HX_FIELD_EQ(inName,"jointMax") ) { if (inCallProp == hx::paccAlways) return hx::Val( get_jointMax() ); }
break;
case 9:
if (HX_FIELD_EQ(inName,"get_body1") ) { return hx::Val( get_body1_dyn() ); }
if (HX_FIELD_EQ(inName,"set_body1") ) { return hx::Val( set_body1_dyn() ); }
if (HX_FIELD_EQ(inName,"get_body2") ) { return hx::Val( get_body2_dyn() ); }
if (HX_FIELD_EQ(inName,"set_body2") ) { return hx::Val( set_body2_dyn() ); }
if (HX_FIELD_EQ(inName,"direction") ) { if (inCallProp == hx::paccAlways) return hx::Val( get_direction() ); }
break;
case 11:
if (HX_FIELD_EQ(inName,"get_anchor1") ) { return hx::Val( get_anchor1_dyn() ); }
if (HX_FIELD_EQ(inName,"set_anchor1") ) { return hx::Val( set_anchor1_dyn() ); }
if (HX_FIELD_EQ(inName,"get_anchor2") ) { return hx::Val( get_anchor2_dyn() ); }
if (HX_FIELD_EQ(inName,"set_anchor2") ) { return hx::Val( set_anchor2_dyn() ); }
if (HX_FIELD_EQ(inName,"bodyImpulse") ) { return hx::Val( bodyImpulse_dyn() ); }
if (HX_FIELD_EQ(inName,"visitBodies") ) { return hx::Val( visitBodies_dyn() ); }
break;
case 12:
if (HX_FIELD_EQ(inName,"zpp_inner_zn") ) { return hx::Val( zpp_inner_zn ); }
if (HX_FIELD_EQ(inName,"get_jointMin") ) { return hx::Val( get_jointMin_dyn() ); }
if (HX_FIELD_EQ(inName,"set_jointMin") ) { return hx::Val( set_jointMin_dyn() ); }
if (HX_FIELD_EQ(inName,"get_jointMax") ) { return hx::Val( get_jointMax_dyn() ); }
if (HX_FIELD_EQ(inName,"set_jointMax") ) { return hx::Val( set_jointMax_dyn() ); }
break;
case 13:
if (HX_FIELD_EQ(inName,"get_direction") ) { return hx::Val( get_direction_dyn() ); }
if (HX_FIELD_EQ(inName,"set_direction") ) { return hx::Val( set_direction_dyn() ); }
}
return super::__Field(inName,inCallProp);
}
hx::Val LineJoint_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 5:
if (HX_FIELD_EQ(inName,"body1") ) { if (inCallProp == hx::paccAlways) return hx::Val( set_body1(inValue.Cast< ::nape::phys::Body >()) ); }
if (HX_FIELD_EQ(inName,"body2") ) { if (inCallProp == hx::paccAlways) return hx::Val( set_body2(inValue.Cast< ::nape::phys::Body >()) ); }
break;
case 7:
if (HX_FIELD_EQ(inName,"anchor1") ) { if (inCallProp == hx::paccAlways) return hx::Val( set_anchor1(inValue.Cast< ::nape::geom::Vec2 >()) ); }
if (HX_FIELD_EQ(inName,"anchor2") ) { if (inCallProp == hx::paccAlways) return hx::Val( set_anchor2(inValue.Cast< ::nape::geom::Vec2 >()) ); }
break;
case 8:
if (HX_FIELD_EQ(inName,"jointMin") ) { if (inCallProp == hx::paccAlways) return hx::Val( set_jointMin(inValue.Cast< Float >()) ); }
if (HX_FIELD_EQ(inName,"jointMax") ) { if (inCallProp == hx::paccAlways) return hx::Val( set_jointMax(inValue.Cast< Float >()) ); }
break;
case 9:
if (HX_FIELD_EQ(inName,"direction") ) { if (inCallProp == hx::paccAlways) return hx::Val( set_direction(inValue.Cast< ::nape::geom::Vec2 >()) ); }
break;
case 12:
if (HX_FIELD_EQ(inName,"zpp_inner_zn") ) { zpp_inner_zn=inValue.Cast< ::zpp_nape::constraint::ZPP_LineJoint >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void LineJoint_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_("zpp_inner_zn",22,84,fa,e0));
outFields->push(HX_("body1",4f,d3,ef,b6));
outFields->push(HX_("body2",50,d3,ef,b6));
outFields->push(HX_("anchor1",1c,ec,a1,02));
outFields->push(HX_("anchor2",1d,ec,a1,02));
outFields->push(HX_("direction",3f,62,40,10));
outFields->push(HX_("jointMin",68,fa,25,55));
outFields->push(HX_("jointMax",7a,f3,25,55));
super::__GetFields(outFields);
};
#ifdef HXCPP_SCRIPTABLE
static hx::StorageInfo LineJoint_obj_sMemberStorageInfo[] = {
{hx::fsObject /* ::zpp_nape::constraint::ZPP_LineJoint */ ,(int)offsetof(LineJoint_obj,zpp_inner_zn),HX_("zpp_inner_zn",22,84,fa,e0)},
{ hx::fsUnknown, 0, null()}
};
static hx::StaticInfo *LineJoint_obj_sStaticStorageInfo = 0;
#endif
static ::String LineJoint_obj_sMemberFields[] = {
HX_("zpp_inner_zn",22,84,fa,e0),
HX_("get_body1",a6,2f,99,fa),
HX_("set_body1",b2,1b,ea,dd),
HX_("get_body2",a7,2f,99,fa),
HX_("set_body2",b3,1b,ea,dd),
HX_("get_anchor1",33,4c,9c,88),
HX_("set_anchor1",3f,53,09,93),
HX_("get_anchor2",34,4c,9c,88),
HX_("set_anchor2",40,53,09,93),
HX_("get_direction",16,36,a4,d1),
HX_("set_direction",22,18,aa,16),
HX_("get_jointMin",71,ae,3f,0a),
HX_("set_jointMin",e5,d1,38,1f),
HX_("get_jointMax",83,a7,3f,0a),
HX_("set_jointMax",f7,ca,38,1f),
HX_("impulse",b5,50,bd,6d),
HX_("bodyImpulse",33,76,a2,5f),
HX_("visitBodies",ab,f3,5e,e4),
::String(null()) };
hx::Class LineJoint_obj::__mClass;
void LineJoint_obj::__register()
{
LineJoint_obj _hx_dummy;
LineJoint_obj::_hx_vtable = *(void **)&_hx_dummy;
hx::Static(__mClass) = new hx::Class_obj();
__mClass->mName = HX_("nape.constraint.LineJoint",8b,7a,04,05);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField;
__mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = hx::Class_obj::dupFunctions(LineJoint_obj_sMemberFields);
__mClass->mCanCast = hx::TCanCast< LineJoint_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = LineJoint_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = LineJoint_obj_sStaticStorageInfo;
#endif
hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace nape
} // end namespace constraint
| 41.349722 | 241 | 0.570169 | HedgehogFog |
c9da4e6c9d8f47afc84586e0ca5c231ffe408c3a | 5,409 | cc | C++ | src/ufo/profile/ProfileStandardLevels.cc | NOAA-EMC/ufo | 3bf1407731b79eab16ceff64129552577d9cfcd0 | [
"Apache-2.0"
] | null | null | null | src/ufo/profile/ProfileStandardLevels.cc | NOAA-EMC/ufo | 3bf1407731b79eab16ceff64129552577d9cfcd0 | [
"Apache-2.0"
] | 10 | 2020-12-10T22:57:51.000Z | 2020-12-17T15:57:04.000Z | src/ufo/profile/ProfileStandardLevels.cc | NOAA-EMC/ufo | 3bf1407731b79eab16ceff64129552577d9cfcd0 | [
"Apache-2.0"
] | 3 | 2020-12-10T18:38:22.000Z | 2020-12-11T01:36:37.000Z | /*
* (C) Crown copyright 2020, Met Office
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*/
#include "ufo/profile/ProfileStandardLevels.h"
namespace ufo {
ProfileStandardLevels::ProfileStandardLevels
(const ConventionalProfileProcessingParameters &options)
: optionsSL_(options)
{
StandardLevels_ = optionsSL_.StandardLevels.value();
BigGaps_ = optionsSL_.BigGaps.value();
}
void ProfileStandardLevels::calcStdLevels(const int numProfileLevels,
const std::vector <float> &pressures,
const std::vector <float> &tObs,
const std::vector <int> &tFlags)
{
oops::Log::debug() << " Finding standard levels" << std::endl;
// Reset calculated values
NumSig_ = 0;
NumStd_ = 0;
StdLev_.assign(numProfileLevels, -1);
SigBelow_.assign(numProfileLevels, -1);
SigAbove_.assign(numProfileLevels, -1);
LogP_.assign(numProfileLevels, 0.0);
IndStd_.assign(numProfileLevels, -1);
/// Missing value (float)
const float missingValueFloat = util::missingValue(1.0f);
int SigPrev = -1; // Previous significant level
int jlevStdA = 0; // Standard level below previous significant level
for (int jlev = 0; jlev < numProfileLevels; ++jlev) {
// Ignore this level if it has been flagged as rejected.
if (tFlags[jlev] & ufo::MetOfficeQCFlags::Elem::FinalRejectFlag) continue;
if (tObs[jlev] != missingValueFloat &&
pressures[jlev] > optionsSL_.FS_MinP.value()) {
LogP_[jlev] = (pressures[jlev] > 0 ? std::log(pressures[jlev]) : 0.0);
if (tFlags[jlev] & ufo::MetOfficeQCFlags::Profile::SurfaceLevelFlag) {
// Surface
NumStd_++;
StdLev_[NumStd_ - 1] = jlev;
} else if (tFlags[jlev] & ufo::MetOfficeQCFlags::Profile::StandardLevelFlag) {
// Standard level
NumStd_++;
StdLev_[NumStd_ - 1] = jlev;
SigBelow_[NumStd_ - 1] = SigPrev;
} else {
NumSig_++;
for (int jlevStd = jlevStdA; jlevStd < NumStd_; ++jlevStd) {
SigAbove_[jlevStd] = jlev;
}
jlevStdA = NumStd_;
SigPrev = jlev;
}
}
}
// Calculate IndStd_ (standard level indices)
for (int jlevstd = 0; jlevstd < NumStd_; ++jlevstd) {
int jlev = StdLev_[jlevstd]; // Standard level
if (tFlags[jlev] & ufo::MetOfficeQCFlags::Profile::SurfaceLevelFlag) continue;
int IPStd = std::round(pressures[jlev] * 0.01); // Pressure rounded to nearest hPa
for (size_t i = 0; i < StandardLevels_.size(); ++i) {
if (IPStd == StandardLevels_[i])
IndStd_[jlevstd] = static_cast<int> (i); // Index at which standard level appears
if (StandardLevels_[i] <= IPStd) break;
}
}
}
void ProfileStandardLevels::findHCheckStdLevs()
{
// Find indices in StandardLevels that are closest to 925 and 100 hPa
// Required for hydrostatic check
// StandardLevels_ must contain decreasing pressures
for (size_t jstdlev = 0; jstdlev < StandardLevels_.size() - 1; ++jstdlev) {
if (StandardLevels_[jstdlev] < StandardLevels_[jstdlev + 1]) {
throw eckit::BadValue("Standard levels in wrong order", Here());
}
}
// Find indices using reverse iterators
auto it925 = std::lower_bound(StandardLevels_.rbegin(), StandardLevels_.rend(), 925.0);
Ind925_ = std::distance(StandardLevels_.begin(), it925.base()) - 1;
auto it100 = std::lower_bound(StandardLevels_.rbegin(), StandardLevels_.rend(), 100.0);
Ind100_ = std::distance(StandardLevels_.begin(), it100.base()) - 1;
}
void ProfileStandardLevels::calcStdLevelsUV(const int numProfileLevels,
const std::vector <float> &pressures,
const std::vector <float> &uObs,
const std::vector <float> &vObs,
const std::vector <bool> &uDiagFlagsProfileStdLev)
{
oops::Log::debug() << " Finding standard levels for U and V data" << std::endl;
// Reset calculated values
NumSig_ = 0;
NumStd_ = 0;
StdLev_.assign(numProfileLevels, -1);
SigBelow_.assign(numProfileLevels, -1);
SigAbove_.assign(numProfileLevels, -1);
LogP_.assign(numProfileLevels, 0.0);
/// Missing value (float)
const float missingValueFloat = util::missingValue(1.0f);
int SigPrev = -1; // Previous significant level
int jlevStdA = 0; // Standard level below previous significant level
for (int jlev = 0; jlev < numProfileLevels; ++jlev) {
if (uObs[jlev] != missingValueFloat && vObs[jlev] != missingValueFloat) {
LogP_[jlev] = std::log(pressures[jlev]);
if (uDiagFlagsProfileStdLev[jlev]) { // Standard level
NumStd_++;
StdLev_[NumStd_ - 1] = jlev;
SigBelow_[NumStd_ - 1] = SigPrev;
} else {
NumSig_++;
for (int jlevstd = jlevStdA; jlevstd < NumStd_; ++jlevstd) {
SigAbove_[jlevstd] = jlev;
}
jlevStdA = NumStd_;
SigPrev = jlev;
}
}
}
}
} // namespace ufo
| 38.913669 | 96 | 0.60159 | NOAA-EMC |
c9e0859e598a2be5cb4d3bef0e9a451794c877ba | 1,321 | cpp | C++ | src/intro_tf2/src/intro_tf2_broadcaster.cpp | davidmball/ros_examples | c5ee7a4de5a61c4ffc0e0c36f3a62728220be3e8 | [
"BSD-3-Clause"
] | 1 | 2017-09-26T07:15:19.000Z | 2017-09-26T07:15:19.000Z | src/intro_tf2/src/intro_tf2_broadcaster.cpp | davidmball/ros_examples | c5ee7a4de5a61c4ffc0e0c36f3a62728220be3e8 | [
"BSD-3-Clause"
] | 5 | 2017-07-01T22:43:09.000Z | 2017-10-02T22:18:22.000Z | src/intro_tf2/src/intro_tf2_broadcaster.cpp | davidmball/ros_examples | c5ee7a4de5a61c4ffc0e0c36f3a62728220be3e8 | [
"BSD-3-Clause"
] | null | null | null | #include <ros/ros.h>
#include <tf2/LinearMath/Quaternion.h>
#include <tf2_ros/transform_broadcaster.h>
#include <geometry_msgs/TransformStamped.h>
class BroadcasterNode
{
public:
BroadcasterNode()
: tf2_br_() {}
void broadcast_robot_pose(double x, double y, double theta)
{
geometry_msgs::TransformStamped transform_stamped;
transform_stamped.header.stamp = ros::Time::now();
transform_stamped.header.frame_id = "map";
transform_stamped.child_frame_id = "base_link";
transform_stamped.transform.translation.x = x;
transform_stamped.transform.translation.y = y;
transform_stamped.transform.translation.z = 0.0;
tf2::Quaternion q;
q.setRPY(0, 0, theta);
transform_stamped.transform.rotation.x = q.x();
transform_stamped.transform.rotation.y = q.y();
transform_stamped.transform.rotation.z = q.z();
transform_stamped.transform.rotation.w = q.w();
tf2_br_.sendTransform(transform_stamped);
}
void spin()
{
ros::Rate rate(5);
while (ros::ok())
{
broadcast_robot_pose(0,0,0);
ros::spinOnce();
rate.sleep();
}
}
private:
tf2_ros::TransformBroadcaster tf2_br_;
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "tf2_broadcaster_node");
BroadcasterNode node;
node.spin();
return EXIT_SUCCESS;
}
| 24.018182 | 61 | 0.696442 | davidmball |
c9e0d00a9b69f145b2e0c116fc58f3d65ed095de | 3,689 | hpp | C++ | Nacro/SDK/FN_SK_M_Med_Soldier_04_Skeleton_AnimBP_classes.hpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 11 | 2021-08-08T23:25:10.000Z | 2022-02-19T23:07:22.000Z | Nacro/SDK/FN_SK_M_Med_Soldier_04_Skeleton_AnimBP_classes.hpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 1 | 2022-01-01T22:51:59.000Z | 2022-01-08T16:14:15.000Z | Nacro/SDK/FN_SK_M_Med_Soldier_04_Skeleton_AnimBP_classes.hpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 8 | 2021-08-09T13:51:54.000Z | 2022-01-26T20:33:37.000Z | #pragma once
// Fortnite (1.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// AnimBlueprintGeneratedClass SK_M_Med_Soldier_04_Skeleton_AnimBP.SK_M_Med_Soldier_04_Skeleton_AnimBP_C
// 0x1728 (0x1B38 - 0x0410)
class USK_M_Med_Soldier_04_Skeleton_AnimBP_C : public UCustomCharacterPartAnimInstance
{
public:
struct FPointerToUberGraphFrame UberGraphFrame; // 0x0410(0x0008) (Transient, DuplicateTransient)
struct FAnimNode_Root AnimGraphNode_Root_78EB935A430054ADF5E2E89005D9D000; // 0x0418(0x0048)
struct FAnimNode_AnimDynamics AnimGraphNode_AnimDynamics_5B5C2BC342A9E2373684A581DE190146;// 0x0460(0x0268)
struct FAnimNode_AnimDynamics AnimGraphNode_AnimDynamics_58B7F723420BD05107F77090484DA4F7;// 0x06C8(0x0268)
struct FAnimNode_AnimDynamics AnimGraphNode_AnimDynamics_B614050A427F32E2A71520A396D4981D;// 0x0930(0x0268)
struct FAnimNode_AnimDynamics AnimGraphNode_AnimDynamics_D4E756144665125C57D74F847DF5CAE2;// 0x0B98(0x0268)
struct FAnimNode_ConvertLocalToComponentSpace AnimGraphNode_LocalToComponentSpace_D3F10A774DCEBBC7CF6FACA843FAA56D;// 0x0E00(0x0048)
struct FAnimNode_ConvertComponentToLocalSpace AnimGraphNode_ComponentToLocalSpace_F50D097B4AF8FD409EBDB7A56995EB71;// 0x0E48(0x0048)
struct FAnimNode_CopyPoseFromMesh AnimGraphNode_CopyPoseFromMesh_5984D2B3487D5E3495C1419E61FA91AE;// 0x0E90(0x0098)
struct FAnimNode_AnimDynamics AnimGraphNode_AnimDynamics_AF49CEBA41A86A5239B445ACCA2A35D2;// 0x0F28(0x0268)
struct FAnimNode_AnimDynamics AnimGraphNode_AnimDynamics_E019B8DC42D4A76813488292D50D4442;// 0x1190(0x0268)
struct FAnimNode_AnimDynamics AnimGraphNode_AnimDynamics_53B6F76442E1E5367E83198574A7E337;// 0x13F8(0x0268)
struct FAnimNode_AnimDynamics AnimGraphNode_AnimDynamics_3B49A128489AAE9305B9BEACDF5446C4;// 0x1660(0x0268)
struct FAnimNode_AnimDynamics AnimGraphNode_AnimDynamics_01F0D350476ED069A3D9B380171159E1;// 0x18C8(0x0268)
class USkeletalMeshComponent* MeshToCopy; // 0x1B30(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("AnimBlueprintGeneratedClass SK_M_Med_Soldier_04_Skeleton_AnimBP.SK_M_Med_Soldier_04_Skeleton_AnimBP_C");
return ptr;
}
void EvaluateGraphExposedInputs_ExecuteUbergraph_SK_M_Med_Soldier_04_Skeleton_AnimBP_AnimGraphNode_AnimDynamics_53B6F76442E1E5367E83198574A7E337();
void EvaluateGraphExposedInputs_ExecuteUbergraph_SK_M_Med_Soldier_04_Skeleton_AnimBP_AnimGraphNode_AnimDynamics_E019B8DC42D4A76813488292D50D4442();
void EvaluateGraphExposedInputs_ExecuteUbergraph_SK_M_Med_Soldier_04_Skeleton_AnimBP_AnimGraphNode_AnimDynamics_AF49CEBA41A86A5239B445ACCA2A35D2();
void EvaluateGraphExposedInputs_ExecuteUbergraph_SK_M_Med_Soldier_04_Skeleton_AnimBP_AnimGraphNode_CopyPoseFromMesh_5984D2B3487D5E3495C1419E61FA91AE();
void EvaluateGraphExposedInputs_ExecuteUbergraph_SK_M_Med_Soldier_04_Skeleton_AnimBP_AnimGraphNode_AnimDynamics_3B49A128489AAE9305B9BEACDF5446C4();
void BlueprintInitializeAnimation();
void ExecuteUbergraph_SK_M_Med_Soldier_04_Skeleton_AnimBP(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 63.603448 | 208 | 0.765248 | Milxnor |
c9e2c611339fe864413fe23d431748bb1a288b1e | 57 | hpp | C++ | src/underlying_enum_types.hpp | bernardosulzbach/cpp-experiments | 66170fa03451f92ed3d6143c53a83d248766b760 | [
"BSD-3-Clause"
] | null | null | null | src/underlying_enum_types.hpp | bernardosulzbach/cpp-experiments | 66170fa03451f92ed3d6143c53a83d248766b760 | [
"BSD-3-Clause"
] | null | null | null | src/underlying_enum_types.hpp | bernardosulzbach/cpp-experiments | 66170fa03451f92ed3d6143c53a83d248766b760 | [
"BSD-3-Clause"
] | null | null | null | namespace Experiments {
void testUnderlyingEnumTypes();
} | 19 | 31 | 0.824561 | bernardosulzbach |
518649b440b1e8601cf694034eac0f4402f378d9 | 3,996 | cpp | C++ | experimenting_music.cpp | harasstheworld/network-programming | f99a8ca2e5f5aa88268ec6ac07290262e84d8b15 | [
"MIT"
] | 1 | 2022-03-25T05:41:46.000Z | 2022-03-25T05:41:46.000Z | experimenting_music.cpp | harasstheworld/network-programming | f99a8ca2e5f5aa88268ec6ac07290262e84d8b15 | [
"MIT"
] | null | null | null | experimenting_music.cpp | harasstheworld/network-programming | f99a8ca2e5f5aa88268ec6ac07290262e84d8b15 | [
"MIT"
] | null | null | null | //This program works under the OSS library
#include <sys/ioctl.h> //for ioctl()
#include <math.h> //sin(), floor()
#include <stdio.h> //perror
#include <fcntl.h> //open, O_WRONLY
#include <linux/soundcard.h> //SOUND_PCM*
#include <iostream>
#include <stdlib.h>
using namespace std;
#define LENGTH 1 //number of seconds
#define RATE 44100 //sampling rate
#define SIZE sizeof(short) //size of sample, in bytes
#define CHANNELS 1 // number of stereo channels
#define PI 3.14159
#define SAMPLE_MAX 32767 // should this end in 8?
#define MIDDLE_C 262
#define SEMITONE 1.05946
enum types {BACK = 0, MAJOR, MINOR};
double getFreq(int index){
return MIDDLE_C * pow(SEMITONE, index-1);
}
int getInput(){
char c;
string str;
int i;
while ((c = getchar()) != '\n' && c != EOF)
str += c;
for (i = 0; i < str.length(); ++i)
str.at(i) = tolower(str.at(i));
if (c == EOF || str == "quit")
exit(0);
return atoi(str.c_str());
}
int getIndex()
{
int input;
cout
<< "Choose one of the following:\n"
<< "\t1) C\n"
<< "\t2) C sharp/D flat\n"
<< "\t3) D\n"
<< "\t4) D sharp/E flat\n"
<< "\t5) E\n"
<< "\t6) F\n"
<< "\t7) F sharp/G flat\n"
<< "\t8) G\n"
<< "\t9) G sharp/A flat\n"
<< "\t10) A\n"
<< "\t11) A sharp/B flat\n"
<< "\t12) B\n"
<< "\tor type quit to quit\n";
input = getInput();
if (! (input >= BACK && input <= 12))
return -1;
return input;
}
void writeToSoundDevice(short buf[], int buffSize, int deviceID) {
int status;
status = write(deviceID, buf, buffSize);
if (status != buffSize)
perror("Wrote wrong number of bytes\n");
status = ioctl(deviceID, SOUND_PCM_SYNC, 0);
if (status == -1)
perror("SOUND_PCM_SYNC failed\n");
}
int getScaleType(){
int input;
cout
<< "Choose one of the following:\n"
<< "\t" << MAJOR << ") for major\n"
<< "\t" << MINOR << ") for minor\n"
<< "\t" << BACK << ") to back up\n"
<< "\tor type quit to quit\n";
input = getInput();
return input;
}
void playScale(int deviceID){
int arraySize, note, steps, index, scaleType;
int break1; // only one half step to here
int break2; // only one half step to here
int t, off;
double f;
short *buf;
arraySize = 8 * LENGTH * RATE * CHANNELS;
buf = new short[arraySize];
while ((index = getIndex()) < 0)
cout << "Input out of bounds. Please try again.\n";
f = getFreq(index);
while ((scaleType = getScaleType()) < 0)
cout << "Input out of bounds. Please try again.\n";
switch (scaleType) {
case MAJOR :
break1 = 3;
break2 = 7;
break;
case MINOR :
break1 = 2;
break2 = 5;
break;
case BACK :
return;
default :
playScale(deviceID);
}
arraySize = LENGTH * RATE * CHANNELS;
for (note = off = 0; note < 8; ++note, off += t) {
if (note == 0)
steps = 0;
else if (note == break1 || note == break2)
steps = 1;
else steps = 2;
f *= pow(SEMITONE, steps);
for (t = 0; t < arraySize; ++t)
buf[t + off] = floor(SAMPLE_MAX*sin(2*PI*f*t/RATE));
}
arraySize = 8 * LENGTH * RATE * SIZE * CHANNELS;
writeToSoundDevice(buf, arraySize, deviceID);
delete buf;
return;
}
int main(){
int deviceID, arg, status, index;
deviceID = open("/dev/dsp", O_WRONLY, 0);
if (deviceID < 0)
perror("Opening /dev/dsp failed\n");
arg = SIZE * 8;
status = ioctl(deviceID, SOUND_PCM_WRITE_BITS, &arg);
if (status == -1)
perror("Unable to set sample size\n");
arg = CHANNELS;
status = ioctl(deviceID, SOUND_PCM_WRITE_CHANNELS, &arg);
if (status == -1)
perror("Unable to set number of channels\n");
arg = RATE;
status = ioctl(deviceID, SOUND_PCM_WRITE_RATE, &arg);
if (status == -1)
perror("Unable to set sampling rate\n");
while (true)
playScale(deviceID);
}
| 28.340426 | 66 | 0.565065 | harasstheworld |
51870a2f12b4852111ca8ae3f50067e51cd9929f | 697 | cpp | C++ | Source/Core/Matrix/Vector3.cpp | X1aoyueyue/KVS | ad47d62bef4fdd9ddd3412a26ee6557b63f0543b | [
"BSD-3-Clause"
] | 42 | 2015-07-24T23:05:07.000Z | 2022-03-16T01:31:04.000Z | Source/Core/Matrix/Vector3.cpp | X1aoyueyue/KVS | ad47d62bef4fdd9ddd3412a26ee6557b63f0543b | [
"BSD-3-Clause"
] | 4 | 2015-03-17T05:42:49.000Z | 2020-08-09T15:21:45.000Z | Source/Core/Matrix/Vector3.cpp | X1aoyueyue/KVS | ad47d62bef4fdd9ddd3412a26ee6557b63f0543b | [
"BSD-3-Clause"
] | 29 | 2015-01-03T05:56:32.000Z | 2021-10-05T15:28:33.000Z | /****************************************************************************/
/**
* @file Vector3.cpp
* @author Naohisa Sakamoto
*/
/****************************************************************************/
#include "Vector3.h"
#include <kvs/Type>
namespace kvs
{
// Template instantiation.
template class Vector3<kvs::Int8>;
template class Vector3<kvs::UInt8>;
template class Vector3<kvs::Int16>;
template class Vector3<kvs::UInt16>;
template class Vector3<kvs::Int32>;
template class Vector3<kvs::UInt32>;
template class Vector3<kvs::Int64>;
template class Vector3<kvs::UInt64>;
template class Vector3<kvs::Real32>;
template class Vector3<kvs::Real64>;
} // end of namespace kvs
| 25.814815 | 78 | 0.571019 | X1aoyueyue |
51879fcf4cf60cc6b4fea4cf89a1dee530ea24ed | 3,063 | cpp | C++ | mp2-lab5-list/ConsoleMain.cpp | alexChurkin/mp2-lab5-list | e3cfdabcdc9cf12989f82565f9e13d0b02c95ecf | [
"Apache-2.0"
] | null | null | null | mp2-lab5-list/ConsoleMain.cpp | alexChurkin/mp2-lab5-list | e3cfdabcdc9cf12989f82565f9e13d0b02c95ecf | [
"Apache-2.0"
] | null | null | null | mp2-lab5-list/ConsoleMain.cpp | alexChurkin/mp2-lab5-list | e3cfdabcdc9cf12989f82565f9e13d0b02c95ecf | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include "TPolynom.h"
using namespace std;
void LaunchTListDemo()
{
cout << "TList demo\n";
cout << "===================\n";
TList<int> l;
l.InsFirst(3);
l.InsFirst(2);
l.InsFirst(1);
cout << l << "\n";
l.InsLast(4);
cout << l << '\n';
l.Reset();
l.InsCurr(0);
cout << l << '\n';
l.InsCurr(5);
cout << l << '\n';
l.Reset();
l.GoNext();
l.InsCurr(777);
cout << l << '\n';
l.DelFirst();
cout << l << '\n';
l.Reset();
l.DelCurr();
cout << l << '\n';
l.DelFirst();
cout << l << '\n';
}
void LaunchTPolynomPrintDemo()
{
cout << "TPolynom print demo\n";
cout << "===================\n";
//P1 = 1
TPolynom p1;
p1.AddMonom(TMonom(1, 0, 0, 0));
cout << "P1 = " << p1 << '\n';
//P1 = -1
TPolynom p2;
p2.AddMonom(TMonom(-1, 0, 0, 0));
cout << "P2 = " << p2 << '\n';
//P3 = 5
TPolynom p3;
p3.AddMonom(TMonom(5, 0, 0, 0));
cout << "P3 = " << p3 << '\n';
//P4 = x + 1
TPolynom p4;
p4.AddMonom(TMonom(1, 1, 0, 0));
p4.AddMonom(TMonom(1, 0, 0, 0));
cout << "P4 = " << p4 << '\n';
//P5 = x - 1
TPolynom p5;
p5.AddMonom(TMonom(1, 1, 0, 0));
p5.AddMonom(TMonom(-1, 0, 0, 0));
cout << "P5 = " << p5 << '\n';
//P6 = x2 + x + 1
TPolynom p6;
p6.AddMonom(TMonom(1, 2, 0, 0));
p6.AddMonom(TMonom(1, 1, 0, 0));
p6.AddMonom(TMonom(1, 0, 0, 0));
cout << "P6 = " << p6 << '\n';
//P7 = 2*x2 - 4*x + 10
TPolynom p7;
p7.AddMonom(TMonom(2, 2, 0, 0));
p7.AddMonom(TMonom(-4, 1, 0, 0));
p7.AddMonom(TMonom(10, 0, 0, 0));
cout << "P7 = " << p7 << '\n';
//P8 = xyz
TPolynom p8;
p8.AddMonom(TMonom(1, 1, 1, 1));
cout << "P8 = " << p8 << '\n';
//P9 = -x2y
TPolynom p9;
p9.AddMonom(TMonom(-1, 2, 1, 0));
cout << "P9 = " << p9 << '\n';
//P10 = -10*x3y2z + 5*yz - 3*y + 3
TPolynom p10;
p10.AddMonom(TMonom(-10, 3, 2, 1));
p10.AddMonom(TMonom(5, 0, 1, 1));
p10.AddMonom(TMonom(-3, 0, 1, 0));
p10.AddMonom(TMonom(3, 0, 0, 0));
cout << "P10 = " << p10 << '\n';
}
void LaunchTPolynomDemo()
{
cout << "TPolynom sum demo\n";
cout << "===================\n";
TPolynom p3;
p3.AddMonom(TMonom(1, 1, 0, 0));
p3.AddMonom(TMonom(2, 0, 0, 0));
cout << "P3 = " << p3 << '\n';
TPolynom p4;
p4.AddMonom(TMonom(-1, 1, 0, 0));
p4.AddMonom(TMonom(-2, 0, 0, 0));
cout << "P4 = " << p4 << '\n';
cout << "P4 + P3 = " << p4 + p3 << '\n';
}
int main()
{
LaunchTListDemo();
cout << '\n';
LaunchTPolynomPrintDemo();
cout << '\n';
LaunchTPolynomDemo();
cout << '\n';
cout << "Polynomial Calculator\n";
cout << "====================\n";
while (true)
{
char ch;
std::string str;
cout << "p1 = ";
getline(cin, str);
TPolynom p1(str);
//cout << "p1 now: " << p1 << '\n';
cout << "p2 = ";
getline(cin, str);
TPolynom p2(str);
//cout << "p2 now: " << p2 << '\n';
cout << "Operation: ";
cin >> ch;
switch (ch)
{
case '+':
cout << "result = " << p1 + p2 << "\n\n";
break;
case '-':
cout << "result = " << p1 - p2 << "\n\n";
break;
case '*':
cout << "result = " << p1 * p2 << "\n\n";
break;
}
cin.ignore(256, '\n');
}
return 0;
} | 17.403409 | 44 | 0.481554 | alexChurkin |
5188a4493230303fb7592bb4eff82c44186d7c5d | 36,804 | cc | C++ | CalibTracker/SiStripLorentzAngle/plugins/SiStripCalibLorentzAngle.cc | bisnupriyasahu/cmssw | 6cf37ca459246525be0e8a6f5172c6123637d259 | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | CalibTracker/SiStripLorentzAngle/plugins/SiStripCalibLorentzAngle.cc | bisnupriyasahu/cmssw | 6cf37ca459246525be0e8a6f5172c6123637d259 | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | CalibTracker/SiStripLorentzAngle/plugins/SiStripCalibLorentzAngle.cc | bisnupriyasahu/cmssw | 6cf37ca459246525be0e8a6f5172c6123637d259 | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | #include <memory>
#include <string>
#include <iostream>
#include <fstream>
#include "CondCore/DBOutputService/interface/PoolDBOutputService.h"
#include "CalibTracker/SiStripLorentzAngle/interface/SiStripCalibLorentzAngle.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "Geometry/TrackerGeometryBuilder/interface/StripGeomDetUnit.h"
#include "DataFormats/SiStripDetId/interface/StripSubdetector.h"
#include "Geometry/Records/interface/TrackerDigiGeometryRecord.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "CLHEP/Random/RandGauss.h"
#include "CondFormats/DataRecord/interface/SiStripLorentzAngleRcd.h"
#include "DQM/SiStripCommon/interface/SiStripHistoId.h"
#include "DQMServices/Core/interface/MonitorElement.h"
#include "DQMServices/Core/interface/DQMStore.h"
#include "Geometry/CommonTopologies/interface/StripTopology.h"
#include "DQM/SiStripCommon/interface/ExtractTObject.h"
#include "DataFormats/TrackerCommon/interface/TrackerTopology.h"
#include "Geometry/Records/interface/TrackerTopologyRcd.h"
SiStripCalibLorentzAngle::SiStripCalibLorentzAngle(edm::ParameterSet const& conf) : ConditionDBWriter<SiStripLorentzAngle>(conf) , tTopo(nullptr), conf_(conf) {}
void SiStripCalibLorentzAngle::algoBeginJob(const edm::EventSetup& c){
//Retrieve tracker topology from geometry
edm::ESHandle<TrackerTopology> tTopoHandle;
c.get<TrackerTopologyRcd>().get(tTopoHandle);
tTopo = tTopoHandle.product();
c.get<TrackerDigiGeometryRecord>().get(estracker);
tracker=&(*estracker);
//get magnetic field and geometry from ES
edm::ESHandle<MagneticField> magfield_;
c.get<IdealMagneticFieldRecord>().get(magfield_);
edm::ESHandle<SiStripLorentzAngle> SiStripLorentzAngle_;
c.get<SiStripLorentzAngleRcd>().get(SiStripLorentzAngle_);
detid_la= SiStripLorentzAngle_->getLorentzAngles();
DQMStore* dbe_ = edm::Service<DQMStore>().operator->();
std::string inputFile_ =conf_.getUntrackedParameter<std::string>("fileName", "LAProfiles.root");
std::string LAreport_ =conf_.getUntrackedParameter<std::string>("LA_Report", "LA_Report.txt");
std::string NoEntriesHisto_ =conf_.getUntrackedParameter<std::string>("NoEntriesHisto", "NoEntriesHisto.txt");
std::string Dir_Name_ =conf_.getUntrackedParameter<std::string>("Dir_Name", "SiStrip");
LayerDB = conf_.getUntrackedParameter<bool>("LayerDB", false);
CalibByMC = conf_.getUntrackedParameter<bool>("CalibByMC", false);
dbe_->open(inputFile_);
// use SistripHistoId for producing histogram id (and title)
SiStripHistoId hidmanager;
edm::LogInfo("SiStripCalibLorentzAngle")<<"### DIR-NAME = "<<Dir_Name_;
histolist= dbe_->getAllContents(Dir_Name_);
std::vector<MonitorElement*>::iterator histo;
hFile = new TFile (conf_.getUntrackedParameter<std::string>("out_fileName").c_str(), "RECREATE" );
LorentzAngle_Plots = hFile->mkdir("LorentzAngle_Plots");
Rootple = LorentzAngle_Plots->mkdir("Rootple");
MuH = LorentzAngle_Plots->mkdir("MuH");
TIB_MuH = MuH->mkdir("TIB_MuH");
TOB_MuH = MuH->mkdir("TOB_MuH");
MuH_vs_Phi = LorentzAngle_Plots->mkdir("MuH_vs_Phi");
TIB_Phi = MuH_vs_Phi->mkdir("TIB_Phi");
TOB_Phi = MuH_vs_Phi->mkdir("TOB_Phi");
MuH_vs_Eta = LorentzAngle_Plots->mkdir("MuH_vs_Eta");
TIB_Eta = MuH_vs_Eta->mkdir("TIB_Eta");
TOB_Eta = MuH_vs_Eta->mkdir("TOB_Eta");
FirstIT_GoodFit_Histos = LorentzAngle_Plots->mkdir("1IT_GoodFit_Histos");
TIB_1IT_GoodFit = FirstIT_GoodFit_Histos->mkdir("TIB_1IT_GoodFit");
TOB_1IT_GoodFit = FirstIT_GoodFit_Histos->mkdir("TOB_1IT_GoodFit");
SecondIT_GoodFit_Histos = LorentzAngle_Plots->mkdir("2IT_GoodFit_Histos");
TIB_2IT_GoodFit = SecondIT_GoodFit_Histos->mkdir("TIB_2IT_GoodFit");
TOB_2IT_GoodFit = SecondIT_GoodFit_Histos->mkdir("TOB_2IT_GoodFit");
SecondIT_BadFit_Histos = LorentzAngle_Plots->mkdir("2IT_BadFit_Histos");
TIB_2IT_BadFit = SecondIT_BadFit_Histos->mkdir("TIB_2IT_BadFit");
TOB_2IT_BadFit = SecondIT_BadFit_Histos->mkdir("TOB_2IT_BadFit");
TH1Ds["LA_TIB"] = new TH1D("TanLAPerTesla TIB","TanLAPerTesla TIB",1000,-0.5,0.5);
TH1Ds["LA_TIB"]->SetDirectory(MuH);
TH1Ds["LA_TOB"] = new TH1D("TanLAPerTesla TOB","TanLAPerTesla TOB",1000,-0.5,0.5);
TH1Ds["LA_TOB"]->SetDirectory(MuH);
TH1Ds["LA_err_TIB"] = new TH1D("TanLAPerTesla Error TIB","TanLAPerTesla Error TIB",1000,0,1);
TH1Ds["LA_err_TIB"]->SetDirectory(MuH);
TH1Ds["LA_err_TOB"] = new TH1D("TanLAPerTesla Error TOB","TanLAPerTesla Error TOB",1000,0,1);
TH1Ds["LA_err_TOB"]->SetDirectory(MuH);
TH1Ds["LA_chi2norm_TIB"] = new TH1D("TanLAPerTesla Chi2norm TIB","TanLAPerTesla Chi2norm TIB",2000,0,10);
TH1Ds["LA_chi2norm_TIB"]->SetDirectory(MuH);
TH1Ds["LA_chi2norm_TOB"] = new TH1D("TanLAPerTesla Chi2norm TOB","TanLAPerTesla Chi2norm TOB",2000,0,10);
TH1Ds["LA_chi2norm_TOB"]->SetDirectory(MuH);
TH1Ds["MagneticField"] = new TH1D("MagneticField","MagneticField",500,0,5);
TH1Ds["MagneticField"]->SetDirectory(MuH);
TH2Ds["LA_TIB_graph"] = new TH2D("TanLAPerTesla TIB Layers","TanLAPerTesla TIB Layers",60,0,5,1000,-0.3,0.3);
TH2Ds["LA_TIB_graph"]->SetDirectory(MuH);
TH2Ds["LA_TIB_graph"]->SetNdivisions(6);
TH2Ds["LA_TOB_graph"] = new TH2D("TanLAPerTesla TOB Layers","TanLAPerTesla TOB Layers",80,0,7,1000,-0.3,0.3);
TH2Ds["LA_TOB_graph"]->SetDirectory(MuH);
TH2Ds["LA_TOB_graph"]->SetNdivisions(8);
TH1Ds["LA_TIB_1"] = new TH1D("TanLAPerTesla TIB1","TanLAPerTesla TIB1",2000,-0.5,0.5);
TH1Ds["LA_TIB_1"]->SetDirectory(TIB_MuH);
TH1Ds["LA_TIB_1_mono"] = new TH1D("TanLAPerTesla TIB1 MONO","TanLAPerTesla TIB1 MONO",2000,-0.5,0.5);
TH1Ds["LA_TIB_1_mono"]->SetDirectory(TIB_MuH);
TH1Ds["LA_TIB_1_stereo"] = new TH1D("TanLAPerTesla TIB1 STEREO","TanLAPerTesla TIB1 STEREO",2000,-0.5,0.5);
TH1Ds["LA_TIB_1_stereo"]->SetDirectory(TIB_MuH);
TH1Ds["LA_TIB_2"] = new TH1D("TanLAPerTesla TIB2","TanLAPerTesla TIB2",2000,-0.5,0.5);
TH1Ds["LA_TIB_2"]->SetDirectory(TIB_MuH);
TH1Ds["LA_TIB_2_mono"] = new TH1D("TanLAPerTesla TIB2 MONO","TanLAPerTesla TIB2 MONO",2000,-0.5,0.5);
TH1Ds["LA_TIB_2_mono"]->SetDirectory(TIB_MuH);
TH1Ds["LA_TIB_2_stereo"] = new TH1D("TanLAPerTesla TIB2 STEREO","TanLAPerTesla TIB2 STEREO",2000,-0.5,0.5);
TH1Ds["LA_TIB_2_stereo"]->SetDirectory(TIB_MuH);
TH1Ds["LA_TIB_3"] = new TH1D("TanLAPerTesla_TIB 3","TanLAPerTesla TIB3",2000,-0.5,0.5);
TH1Ds["LA_TIB_3"]->SetDirectory(TIB_MuH);
TH1Ds["LA_TIB_4"] = new TH1D("TanLAPerTesla_TIB 4","TanLAPerTesla TIB4",2000,-0.5,0.5);
TH1Ds["LA_TIB_4"]->SetDirectory(TIB_MuH);
TH1Ds["LA_TOB_1"] = new TH1D("TanLAPerTesla TOB1","TanLAPerTesla TOB1",2000,-0.5,0.5);
TH1Ds["LA_TOB_1"]->SetDirectory(TOB_MuH);
TH1Ds["LA_TOB_1_mono"] = new TH1D("TanLAPerTesla TOB1 MONO","TanLAPerTesla TOB1 MONO",2000,-0.5,0.5);
TH1Ds["LA_TOB_1_mono"]->SetDirectory(TOB_MuH);
TH1Ds["LA_TOB_1_stereo"] = new TH1D("TanLAPerTesla TOB1 STEREO","TanLAPerTesla TOB1 STEREO",2000,-0.5,0.5);
TH1Ds["LA_TOB_1_stereo"]->SetDirectory(TOB_MuH);
TH1Ds["LA_TOB_2"] = new TH1D("TanLAPerTesla TOB2","TanLAPerTesla TOB2",2000,-0.5,0.5);
TH1Ds["LA_TOB_2"]->SetDirectory(TOB_MuH);
TH1Ds["LA_TOB_2_mono"] = new TH1D("TanLAPerTesla TOB2 MONO","TanLAPerTesla TOB2 MONO",2000,-0.5,0.5);
TH1Ds["LA_TOB_2_mono"]->SetDirectory(TOB_MuH);
TH1Ds["LA_TOB_2_stereo"] = new TH1D("TanLAPerTesla TOB2 STEREO","TanLAPerTesla TOB2 STEREO",2000,-0.5,0.5);
TH1Ds["LA_TOB_2_stereo"]->SetDirectory(TOB_MuH);
TH1Ds["LA_TOB_3"] = new TH1D("TanLAPerTesla TOB3","TanLAPerTesla TOB3",2000,-0.5,0.5);
TH1Ds["LA_TOB_3"]->SetDirectory(TOB_MuH);
TH1Ds["LA_TOB_4"] = new TH1D("TanLAPerTesla TOB4","TanLAPerTesla TOB4",2000,-0.5,0.5);
TH1Ds["LA_TOB_4"]->SetDirectory(TOB_MuH);
TH1Ds["LA_TOB_5"] = new TH1D("TanLAPerTesla TOB5","TanLAPerTesla TOB5",2000,-0.5,0.5);
TH1Ds["LA_TOB_5"]->SetDirectory(TOB_MuH);
TH1Ds["LA_TOB_6"] = new TH1D("TanLAPerTesla TOB6","TanLAPerTesla TOB6",2000,-0.5,0.5);
TH1Ds["LA_TOB_6"]->SetDirectory(TOB_MuH);
TH2Ds["LA_phi_TIB"] = new TH2D("TanLAPerTesla vs Phi TIB","TanLAPerTesla vs Phi TIB",800,-4,4,600,-0.3,0.3);
TH2Ds["LA_phi_TIB"]->SetDirectory(MuH_vs_Phi);
TH2Ds["LA_phi_TOB"] = new TH2D("TanLAPerTesla vs Phi TOB","TanLAPerTesla vs Phi TOB",800,-4,4,600,-0.3,0.3);
TH2Ds["LA_phi_TOB"]->SetDirectory(MuH_vs_Phi);
TH2Ds["LA_phi_TIB1"] = new TH2D("TanLAPerTesla vs Phi TIB1","TanLAPerTesla vs Phi TIB1",800,-4,4,600,-0.3,0.3);
TH2Ds["LA_phi_TIB1"]->SetDirectory(TIB_Phi);
TH2Ds["LA_phi_TIB1_mono"] = new TH2D("TanLAPerTesla vs Phi TIB1 MONO","TanLAPerTesla vs Phi TIB1 MONO",800,-4,4,600,-0.3,0.3);
TH2Ds["LA_phi_TIB1_mono"]->SetDirectory(TIB_Phi);
TH2Ds["LA_phi_TIB1_stereo"] = new TH2D("TanLAPerTesla vs Phi TIB1 STEREO","TanLAPerTesla vs Phi TIB1 STEREO",800,-4,4,600,-0.3,0.3);
TH2Ds["LA_phi_TIB1_stereo"]->SetDirectory(TIB_Phi);
TH2Ds["LA_phi_TIB2"] = new TH2D("TanLAPerTesla vs Phi TIB2","TanLAPerTesla vs Phi TIB2",800,-4,4,600,-0.3,0.3);
TH2Ds["LA_phi_TIB2"]->SetDirectory(TIB_Phi);
TH2Ds["LA_phi_TIB2_mono"] = new TH2D("TanLAPerTesla vs Phi TIB2 MONO","TanLAPerTesla vs Phi TIB2 MONO",800,-4,4,600,-0.3,0.3);
TH2Ds["LA_phi_TIB2_mono"]->SetDirectory(TIB_Phi);
TH2Ds["LA_phi_TIB2_stereo"] = new TH2D("TanLAPerTesla vs Phi TIB2 STEREO","TanLAPerTesla vs Phi TIB2 STEREO",800,-4,4,600,-0.3,0.3);
TH2Ds["LA_phi_TIB2_stereo"]->SetDirectory(TIB_Phi);
TH2Ds["LA_phi_TIB3"] = new TH2D("TanLAPerTesla vs Phi TIB3","TanLAPerTesla vs Phi TIB3",800,-4,4,600,-0.3,0.3);
TH2Ds["LA_phi_TIB3"]->SetDirectory(TIB_Phi);
TH2Ds["LA_phi_TIB4"] = new TH2D("TanLAPerTesla vs Phi TIB4","TanLAPerTesla vs Phi TIB4",800,-4,4,600,-0.3,0.3);
TH2Ds["LA_phi_TIB4"]->SetDirectory(TIB_Phi);
TH2Ds["LA_phi_TOB1"] = new TH2D("TanLAPerTesla vs Phi TOB1","TanLAPerTesla vs Phi TOB1",800,-4,4,600,-0.3,0.3);
TH2Ds["LA_phi_TOB1"]->SetDirectory(TOB_Phi);
TH2Ds["LA_phi_TOB1_mono"] = new TH2D("TanLAPerTesla vs Phi TOB1 MONO","TanLAPerTesla vs Phi TOB1 MONO",800,-4,4,600,-0.3,0.3);
TH2Ds["LA_phi_TOB1_mono"]->SetDirectory(TOB_Phi);
TH2Ds["LA_phi_TOB1_stereo"] = new TH2D("TanLAPerTesla vs Phi TOB1 STEREO","TanLAPerTesla vs Phi TOB1 STEREO",800,-4,4,600,-0.3,0.3);
TH2Ds["LA_phi_TOB1_stereo"]->SetDirectory(TOB_Phi);
TH2Ds["LA_phi_TOB2"] = new TH2D("TanLAPerTesla vs Phi TOB2","TanLAPerTesla vs Phi TOB2",800,-4,4,600,-0.3,0.3);
TH2Ds["LA_phi_TOB2"]->SetDirectory(TOB_Phi);
TH2Ds["LA_phi_TOB2_mono"] = new TH2D("TanLAPerTesla vs Phi TOB2 MONO","TanLAPerTesla vs Phi TOB2 MONO",800,-4,4,600,-0.3,0.3);
TH2Ds["LA_phi_TOB2_mono"]->SetDirectory(TOB_Phi);
TH2Ds["LA_phi_TOB2_stereo"] = new TH2D("TanLAPerTesla vs Phi TOB2 STEREO","TanLAPerTesla vs Phi TOB2 STEREO",800,-4,4,600,-0.3,0.3);
TH2Ds["LA_phi_TOB2_stereo"]->SetDirectory(TOB_Phi);
TH2Ds["LA_phi_TOB3"] = new TH2D("TanLAPerTesla vs Phi TOB3","TanLAPerTesla vs Phi TOB3",800,-4,4,600,-0.3,0.3);
TH2Ds["LA_phi_TOB3"]->SetDirectory(TOB_Phi);
TH2Ds["LA_phi_TOB4"] = new TH2D("TanLAPerTesla vs Phi TOB4","TanLAPerTesla vs Phi TOB4",800,-4,4,600,-0.3,0.3);
TH2Ds["LA_phi_TOB4"]->SetDirectory(TOB_Phi);
TH2Ds["LA_phi_TOB5"] = new TH2D("TanLAPerTesla vs Phi TOB5","TanLAPerTesla vs Phi TOB5",800,-4,4,600,-0.3,0.3);
TH2Ds["LA_phi_TOB5"]->SetDirectory(TOB_Phi);
TH2Ds["LA_phi_TOB6"] = new TH2D("TanLAPerTesla vs Phi TOB6","TanLAPerTesla vs Phi TOB6",800,-4,4,600,-0.3,0.3);
TH2Ds["LA_phi_TOB6"]->SetDirectory(TOB_Phi);
TH2Ds["LA_eta_TIB"] = new TH2D("TanLAPerTesla vs Eta TIB","TanLAPerTesla vs Eta TIB",800,-2.6,2.6,600,-0.3,0.3);
TH2Ds["LA_eta_TIB"]->SetDirectory(MuH_vs_Eta);
TH2Ds["LA_eta_TOB"] = new TH2D("TanLAPerTesla vs Eta TOB","TanLAPerTesla vs Eta TOB",800,-2.6,2.6,600,-0.3,0.3);
TH2Ds["LA_eta_TOB"]->SetDirectory(MuH_vs_Eta);
TH2Ds["LA_eta_TIB1"] = new TH2D("TanLAPerTesla vs Eta TIB1","TanLAPerTesla vs Eta TIB1",800,-2.6,2.6,600,-0.3,0.3);
TH2Ds["LA_eta_TIB1"]->SetDirectory(TIB_Eta);
TH2Ds["LA_eta_TIB1_mono"] = new TH2D("TanLAPerTesla vs Eta TIB1 MONO","TanLAPerTesla vs Eta TIB1 MONO",800,-2.6,2.6,600,-0.3,0.3);
TH2Ds["LA_eta_TIB1_mono"]->SetDirectory(TIB_Eta);
TH2Ds["LA_eta_TIB1_stereo"] = new TH2D("TanLAPerTesla vs Eta TIB1 STEREO","TanLAPerTesla vs Eta TIB1 STEREO",800,-2.6,2.6,600,-0.3,0.3);
TH2Ds["LA_eta_TIB1_stereo"]->SetDirectory(TIB_Eta);
TH2Ds["LA_eta_TIB2"] = new TH2D("TanLAPerTesla vs Eta TIB2","TanLAPerTesla vs Eta TIB2",800,-2.6,2.6,600,-0.3,0.3);
TH2Ds["LA_eta_TIB2"]->SetDirectory(TIB_Eta);
TH2Ds["LA_eta_TIB2_mono"] = new TH2D("TanLAPerTesla vs Eta TIB2 MONO","TanLAPerTesla vs Eta TIB2 MONO",800,-2.6,2.6,600,-0.3,0.3);
TH2Ds["LA_eta_TIB2_mono"]->SetDirectory(TIB_Eta);
TH2Ds["LA_eta_TIB2_stereo"] = new TH2D("TanLAPerTesla vs Eta TIB2 STEREO","TanLAPerTesla vs Eta TIB2 STEREO",800,-2.6,2.6,600,-0.3,0.3);
TH2Ds["LA_eta_TIB2_stereo"]->SetDirectory(TIB_Eta);
TH2Ds["LA_eta_TIB3"] = new TH2D("TanLAPerTesla vs Eta TIB3","TanLAPerTesla vs Eta TIB3",800,-2.6,2.6,600,-0.3,0.3);
TH2Ds["LA_eta_TIB3"]->SetDirectory(TIB_Eta);
TH2Ds["LA_eta_TIB4"] = new TH2D("TanLAPerTesla vs Eta TIB4","TanLAPerTesla vs Eta TIB4",800,-2.6,2.6,600,-0.3,0.3);
TH2Ds["LA_eta_TIB4"]->SetDirectory(TIB_Eta);
TH2Ds["LA_eta_TOB1"] = new TH2D("TanLAPerTesla vs Eta TOB1","TanLAPerTesla vs Eta TOB1",800,-2.6,2.6,600,-0.3,0.3);
TH2Ds["LA_eta_TOB1"]->SetDirectory(TIB_Eta);
TH2Ds["LA_eta_TOB1_mono"] = new TH2D("TanLAPerTesla vs Eta TOB1 MONO","TanLAPerTesla vs Eta TOB1 MONO",800,-2.6,2.6,600,-0.3,0.3);
TH2Ds["LA_eta_TOB1_mono"]->SetDirectory(TIB_Eta);
TH2Ds["LA_eta_TOB1_stereo"] = new TH2D("TanLAPerTesla vs Eta TOB1 STEREO","TanLAPerTesla vs Eta TOB1 STEREO",800,-2.6,2.6,600,-0.3,0.3);
TH2Ds["LA_eta_TOB1_stereo"]->SetDirectory(TIB_Eta);
TH2Ds["LA_eta_TOB2"] = new TH2D("TanLAPerTesla vs Eta TOB2","TanLAPerTesla vs Eta TOB2",800,-2.6,2.6,600,-0.3,0.3);
TH2Ds["LA_eta_TOB2"]->SetDirectory(TIB_Eta);
TH2Ds["LA_eta_TOB2_mono"] = new TH2D("TanLAPerTesla vs Eta TOB2 MONO","TanLAPerTesla vs Eta TOB2 MONO",800,-2.6,2.6,600,-0.3,0.3);
TH2Ds["LA_eta_TOB2_mono"]->SetDirectory(TIB_Eta);
TH2Ds["LA_eta_TOB2_stereo"] = new TH2D("TanLAPerTesla vs Eta TOB2 STEREO","TanLAPerTesla vs Eta TOB2 STEREO",800,-2.6,2.6,600,-0.3,0.3);
TH2Ds["LA_eta_TOB2_stereo"]->SetDirectory(TIB_Eta);
TH2Ds["LA_eta_TOB3"] = new TH2D("TanLAPerTesla vs Eta TOB3","TanLAPerTesla vs Eta TOB3",800,-2.6,2.6,600,-0.3,0.3);
TH2Ds["LA_eta_TOB3"]->SetDirectory(TIB_Eta);
TH2Ds["LA_eta_TOB4"] = new TH2D("TanLAPerTesla vs Eta TOB4","TanLAPerTesla vs Eta TOB4",800,-2.6,2.6,600,-0.3,0.3);
TH2Ds["LA_eta_TOB4"]->SetDirectory(TIB_Eta);
TH2Ds["LA_eta_TOB5"] = new TH2D("TanLAPerTesla vs Eta TOB5","TanLAPerTesla vs Eta TOB5",800,-2.6,2.6,600,-0.3,0.3);
TH2Ds["LA_eta_TOB5"]->SetDirectory(TIB_Eta);
TH2Ds["LA_eta_TOB6"] = new TH2D("TanLAPerTesla vs Eta TOB6","TanLAPerTesla vs Eta TOB6",800,-2.6,2.6,600,-0.3,0.3);
TH2Ds["LA_eta_TOB6"]->SetDirectory(TIB_Eta);
ModuleTree = new TTree("ModuleTree", "ModuleTree");
ModuleTree->Branch("histoEntries", &histoEntries, "histoEntries/F");
ModuleTree->Branch("globalX", &globalX, "globalX/F");
ModuleTree->Branch("globalY", &globalY, "globalY/F");
ModuleTree->Branch("globalZ", &globalZ, "globalZ/F");
ModuleTree->Branch("gphi", &gphi, "gphi/F");
ModuleTree->Branch("geta", &geta, "geta/F");
ModuleTree->Branch("gR", &gR, "gR/F");
ModuleTree->Branch("goodFit", &goodFit, "goodFit/I");
ModuleTree->Branch("goodFit1IT", &goodFit1IT, "goodFit1IT/I");
ModuleTree->Branch("badFit", &badFit, "badFit/I");
ModuleTree->Branch("TIB", &TIB, "TIB/I");
ModuleTree->Branch("TOB", &TOB, "TOB/I");
ModuleTree->Branch("Layer", &Layer, "Layer/I");
ModuleTree->Branch("MonoStereo", &MonoStereo, "MonoStereo/I");
ModuleTree->Branch("theBfield", &theBfield, "theBfield/F");
ModuleTree->Branch("muH", &muH, "muH/F");
ModuleTree->SetDirectory(Rootple);
int histocounter = 0;
int NotEnoughEntries = 0;
int ZeroEntries = 0;
int GoodFit = 0;
int FirstIT_goodfit = 0;
int FirstIT_badfit = 0;
int SecondIT_badfit = 0;
int SecondIT_goodfit = 0;
int no_mod_histo = 0;
float chi2norm = 0;
LocalPoint p =LocalPoint(0,0,0);
double ModuleRangeMin=conf_.getParameter<double>("ModuleFitXMin");
double ModuleRangeMax=conf_.getParameter<double>("ModuleFitXMax");
double ModuleRangeMin2IT=conf_.getParameter<double>("ModuleFit2ITXMin");
double ModuleRangeMax2IT=conf_.getParameter<double>("ModuleFit2ITXMax");
double FitCuts_Entries=conf_.getParameter<double>("FitCuts_Entries");
double FitCuts_p0=conf_.getParameter<double>("FitCuts_p0");
double FitCuts_p1=conf_.getParameter<double>("FitCuts_p1");
double FitCuts_p2=conf_.getParameter<double>("FitCuts_p2");
double FitCuts_chi2=conf_.getParameter<double>("FitCuts_chi2");
double FitCuts_ParErr_p0=conf_.getParameter<double>("FitCuts_ParErr_p0");
double p0_guess=conf_.getParameter<double>("p0_guess");
double p1_guess=conf_.getParameter<double>("p1_guess");
double p2_guess=conf_.getParameter<double>("p2_guess");
double TIB1calib = 1.;
double TIB2calib = 1.;
double TIB3calib = 1.;
double TIB4calib = 1.;
double TOB1calib = 1.;
double TOB2calib = 1.;
double TOB3calib = 1.;
double TOB4calib = 1.;
double TOB5calib = 1.;
double TOB6calib = 1.;
if(CalibByMC==true){
//Calibration factors evaluated by using MC analysis
TIB1calib=conf_.getParameter<double>("TIB1calib");
TIB2calib=conf_.getParameter<double>("TIB2calib");
TIB3calib=conf_.getParameter<double>("TIB3calib");
TIB4calib=conf_.getParameter<double>("TIB4calib");
TOB1calib=conf_.getParameter<double>("TOB1calib");
TOB2calib=conf_.getParameter<double>("TOB2calib");
TOB3calib=conf_.getParameter<double>("TOB3calib");
TOB4calib=conf_.getParameter<double>("TOB4calib");
TOB5calib=conf_.getParameter<double>("TOB5calib");
TOB6calib=conf_.getParameter<double>("TOB6calib");
}
auto fitfunc= std::make_unique<TF1>("fitfunc","([4]/[3])*[1]*(TMath::Abs(x-[0]))+[2]",-1,1);
auto fitfunc2IT= std::make_unique<TF1>("fitfunc2IT","([4]/[3])*[1]*(TMath::Abs(x-[0]))+[2]",-1,1);
std::ofstream NoEntries;
NoEntries.open(NoEntriesHisto_.c_str());
std::ofstream Rep;
Rep.open(LAreport_.c_str());
gStyle->SetOptStat(1110);
for(histo=histolist.begin();histo!=histolist.end();++histo){
FitFunction = nullptr;
FitFunction2IT = nullptr;
bool Good2ITFit = false;
bool ModuleHisto = true;
histoEntries = -99;
gphi=-99;
geta=-99;
gz = -99;
gR=-1;
globalX = -99;
globalY = -99;
globalZ = -99;
goodFit = 0;
goodFit1IT = 0;
badFit = 0;
muH = -1;
TIB = 0;
TOB = 0;
MonoStereo = -1;
uint32_t id=hidmanager.getComponentId((*histo)->getName());
DetId detid(id);
StripSubdetector subid(id);
const GeomDetUnit * stripdet;
MonoStereo = subid.stereo();
if(!(stripdet=tracker->idToDetUnit(subid))){
no_mod_histo++;
ModuleHisto=false;
edm::LogInfo("SiStripCalibLorentzAngle")<<"### NO MODULE HISTOGRAM";}
if(stripdet!=nullptr && ModuleHisto==true){
if(subid.subdetId() == int (StripSubdetector::TIB)){
Layer = tTopo->tibLayer(detid);
TIB = 1;}
if(subid.subdetId() == int (StripSubdetector::TOB)){
Layer = tTopo->tobLayer(detid);
TOB = 1;}
//get module coordinates
const GlobalPoint gposition = (stripdet->surface()).toGlobal(p);
histoEntries = (*histo)->getEntries();
globalX = gposition.x();
globalY = gposition.y();
globalZ = gposition.z();
gphi = gposition.phi();
geta = gposition.eta();
gR = sqrt(pow(gposition.x(),2)+pow(gposition.y(),2));
gz = gposition.z();
//get magnetic field
const StripGeomDetUnit* det = dynamic_cast<const StripGeomDetUnit*>(estracker->idToDetUnit(detid));
if (det==nullptr){
edm::LogError("SiStripCalibLorentzAngle") << "[SiStripCalibLorentzAngle::getNewObject] the detID " << id << " doesn't seem to belong to Tracker" <<std::endl;
continue;
}
LocalVector lbfield=(det->surface()).toLocal(magfield_->inTesla(det->surface().position()));
theBfield = lbfield.mag();
theBfield = (theBfield > 0) ? theBfield : 0.00001;
TH1Ds["MagneticField"]->Fill(theBfield);
}
if(stripdet==nullptr)continue;
if(((*histo)->getEntries()<=FitCuts_Entries)&&ModuleHisto==true){
if(((*histo)->getEntries()==0)&&ModuleHisto==true){
NoEntries<<"NO ENTRIES MODULE, ID = "<<id<<std::endl;
edm::LogInfo("SiStripCalibLorentzAngle")<<"### HISTOGRAM WITH 0 ENTRIES => TYPE:"<<subid.subdetId();
ZeroEntries++;
}else{
edm::LogInfo("SiStripCalibLorentzAngle")<<"### HISTOGRAM WITH NR. ENTRIES <= ENTRIES_CUT => TYPE:"<<subid.subdetId();
NotEnoughEntries++;}
}
std::string name;
if(TIB==1){
name+="TIB";
}else{
name+="TOB";}
std::stringstream LayerStream;
LayerStream<<Layer;
name+=LayerStream.str();
std::stringstream idnum;
idnum<<id;
name+="_Id_";
name+=idnum.str();
gStyle->SetOptFit(111);
//Extract TProfile from Monitor Element to ProfileMap
Profiles[name] = new TProfile;
TProfile* theProfile=ExtractTObject<TProfile>().extract(*histo);
theProfile->Copy(*Profiles[name]);
Profiles[name]->SetName(name.c_str());
if(((*histo)->getEntries()>FitCuts_Entries) && ModuleHisto==true){
histocounter++;
if(TIB==1){
edm::LogInfo("SiStripCalibLorentzAngle")<<"TIB layer = "<<Layer;}
if(TOB==1){
edm::LogInfo("SiStripCalibLorentzAngle")<<"TOB layer = "<<Layer;}
edm::LogInfo("SiStripCalibLorentzAngle")<<"id: "<<id;
float thickness=stripdet->specificSurface().bounds().thickness();
const StripTopology& topol=(const StripTopology&)stripdet->topology();
float pitch = topol.localPitch(p);
fitfunc->SetParameter(0, p0_guess);
fitfunc->SetParameter(1, p1_guess);
fitfunc->SetParameter(2, p2_guess);
fitfunc->FixParameter(3, pitch);
fitfunc->FixParameter(4, thickness);
Profiles[name]->Fit(fitfunc.get(),"E","",ModuleRangeMin, ModuleRangeMax);
FitFunction = fitfunc.get();
chi2norm = FitFunction->GetChisquare()/FitFunction->GetNDF();
if(FitFunction->GetParameter(0)>FitCuts_p0 || FitFunction->GetParameter(1)<FitCuts_p1 || FitFunction->GetParameter(2)<FitCuts_p2 || chi2norm>FitCuts_chi2 || FitFunction->GetParError(0)<FitCuts_ParErr_p0){
FirstIT_badfit++;
fitfunc2IT->SetParameter(0, p0_guess);
fitfunc2IT->SetParameter(1, p1_guess);
fitfunc2IT->SetParameter(2, p2_guess);
fitfunc2IT->FixParameter(3, pitch);
fitfunc2IT->FixParameter(4, thickness);
//2nd Iteration
Profiles[name]->Fit(fitfunc2IT.get(),"E","",ModuleRangeMin2IT, ModuleRangeMax2IT);
FitFunction = fitfunc2IT.get();
chi2norm = FitFunction->GetChisquare()/FitFunction->GetNDF();
//2nd Iteration failed
if(FitFunction->GetParameter(0)>FitCuts_p0 || FitFunction->GetParameter(1)<FitCuts_p1 || FitFunction->GetParameter(2)<FitCuts_p2 || chi2norm>FitCuts_chi2 || FitFunction->GetParError(0)<FitCuts_ParErr_p0){
if(subid.subdetId() == int (StripSubdetector::TIB)){
Profiles[name]->SetDirectory(TIB_2IT_BadFit);
}else{
Profiles[name]->SetDirectory(TOB_2IT_BadFit);}
SecondIT_badfit++;
badFit=1;
}
//2nd Iteration ok
if(FitFunction->GetParameter(0)<FitCuts_p0 && FitFunction->GetParameter(1)>FitCuts_p1 && FitFunction->GetParameter(2)>FitCuts_p2 && chi2norm<FitCuts_chi2 && FitFunction->GetParError(0)>FitCuts_ParErr_p0){
if(subid.subdetId() == int (StripSubdetector::TIB)){
Profiles[name]->SetDirectory(TIB_2IT_GoodFit);
}else{
Profiles[name]->SetDirectory(TOB_2IT_GoodFit);}
SecondIT_goodfit++;
Good2ITFit = true;
}
}
if(FitFunction->GetParameter(0)<FitCuts_p0 && FitFunction->GetParameter(1)>FitCuts_p1 && FitFunction->GetParameter(2)>FitCuts_p2 && chi2norm<FitCuts_chi2 && FitFunction->GetParError(0)>FitCuts_ParErr_p0){
if(Good2ITFit==false){
FirstIT_goodfit++;
goodFit1IT = 1;
if(subid.subdetId() == int (StripSubdetector::TIB)){
Profiles[name]->SetDirectory(TIB_1IT_GoodFit);
}else{
Profiles[name]->SetDirectory(TOB_1IT_GoodFit);}
}
GoodFit++;
goodFit=1;
LorentzAngle_Plots->cd();
edm::LogInfo("SiStripCalibLorentzAngle")<<FitFunction->GetParameter(0);
muH = -(FitFunction->GetParameter(0))/theBfield;
if(TIB==1){
if(Layer==1) muH = muH/TIB1calib;
if(Layer==2) muH = muH/TIB2calib;
if(Layer==3) muH = muH/TIB3calib;
if(Layer==4) muH = muH/TIB4calib;
}
if(TOB==1){
if(Layer==1) muH = muH/TOB1calib;
if(Layer==2) muH = muH/TOB2calib;
if(Layer==3) muH = muH/TOB3calib;
if(Layer==4) muH = muH/TOB4calib;
if(Layer==5) muH = muH/TOB5calib;
if(Layer==6) muH = muH/TOB6calib;
}
detid_la[id]= muH;
if(TIB==1){
TH1Ds["LA_TIB"]->Fill(muH);
TH1Ds["LA_err_TIB"]->Fill(FitFunction->GetParError(0)/theBfield);
TH1Ds["LA_chi2norm_TIB"]->Fill(chi2norm);
TH2Ds["LA_phi_TIB"]->Fill(gphi,muH);
TH2Ds["LA_eta_TIB"]->Fill(geta,muH);
TH2Ds["LA_TIB_graph"]->Fill(Layer,muH);
if(Layer==1){
TH1Ds["LA_TIB_1"]->Fill(muH);
TH2Ds["LA_phi_TIB1"]->Fill(gphi,muH);
TH2Ds["LA_eta_TIB1"]->Fill(geta,muH);
if(MonoStereo==0){
TH1Ds["LA_TIB_1_mono"]->Fill(muH);
TH2Ds["LA_phi_TIB1_mono"]->Fill(gphi,muH);
TH2Ds["LA_eta_TIB1_mono"]->Fill(geta,muH);}
if(MonoStereo==1){
TH1Ds["LA_TIB_1_stereo"]->Fill(muH);
TH2Ds["LA_phi_TIB1_stereo"]->Fill(gphi,muH);
TH2Ds["LA_eta_TIB1_stereo"]->Fill(geta,muH);}
}
if(Layer==2){
TH1Ds["LA_TIB_2"]->Fill(muH);
TH2Ds["LA_phi_TIB2"]->Fill(gphi,muH);
TH2Ds["LA_eta_TIB2"]->Fill(geta,muH);
if(MonoStereo==0){
TH1Ds["LA_TIB_2_mono"]->Fill(muH);
TH2Ds["LA_phi_TIB2_mono"]->Fill(gphi,muH);
TH2Ds["LA_eta_TIB2_mono"]->Fill(geta,muH);}
if(MonoStereo==1){
TH1Ds["LA_TIB_2_stereo"]->Fill(muH);
TH2Ds["LA_phi_TIB2_stereo"]->Fill(gphi,muH);
TH2Ds["LA_eta_TIB2_stereo"]->Fill(geta,muH);}
}
if(Layer==3){
TH1Ds["LA_TIB_3"]->Fill(muH);
TH2Ds["LA_phi_TIB3"]->Fill(gphi,muH);
TH2Ds["LA_eta_TIB3"]->Fill(geta,muH);
}
if(Layer==4){
TH1Ds["LA_TIB_4"]->Fill(muH);
TH2Ds["LA_phi_TIB4"]->Fill(gphi,muH);
TH2Ds["LA_eta_TIB4"]->Fill(geta,muH);
}
}
if(TOB==1){
TH1Ds["LA_TOB"]->Fill(muH);
TH1Ds["LA_err_TOB"]->Fill(FitFunction->GetParError(0)/theBfield);
TH1Ds["LA_chi2norm_TOB"]->Fill(chi2norm);
TH2Ds["LA_phi_TOB"]->Fill(gphi,muH);
TH2Ds["LA_eta_TOB"]->Fill(geta,muH);
TH2Ds["LA_TOB_graph"]->Fill(Layer,muH);
if(Layer==1){
TH1Ds["LA_TOB_1"]->Fill(muH);
TH2Ds["LA_phi_TOB1"]->Fill(gphi,muH);
TH2Ds["LA_eta_TOB1"]->Fill(geta,muH);
if(MonoStereo==0){
TH1Ds["LA_TOB_1_mono"]->Fill(muH);
TH2Ds["LA_phi_TOB1_mono"]->Fill(gphi,muH);
TH2Ds["LA_eta_TOB1_mono"]->Fill(geta,muH);}
if(MonoStereo==1){
TH1Ds["LA_TOB_1_stereo"]->Fill(muH);
TH2Ds["LA_phi_TOB1_stereo"]->Fill(gphi,muH);
TH2Ds["LA_eta_TOB1_stereo"]->Fill(geta,muH);}
}
if(Layer==2){
TH1Ds["LA_TOB_2"]->Fill(muH);
TH2Ds["LA_phi_TOB2"]->Fill(gphi,muH);
TH2Ds["LA_eta_TOB2"]->Fill(geta,muH);
if(MonoStereo==0){
TH1Ds["LA_TOB_2_mono"]->Fill(muH);
TH2Ds["LA_phi_TOB2_mono"]->Fill(gphi,muH);
TH2Ds["LA_eta_TOB2_mono"]->Fill(geta,muH);}
if(MonoStereo==1){
TH1Ds["LA_TOB_2_stereo"]->Fill(muH);
TH2Ds["LA_phi_TOB2_stereo"]->Fill(gphi,muH);
TH2Ds["LA_eta_TOB2_stereo"]->Fill(geta,muH);}
}
if(Layer==3){
TH1Ds["LA_TOB_3"]->Fill(muH);
TH2Ds["LA_phi_TOB3"]->Fill(gphi,muH);
TH2Ds["LA_eta_TOB3"]->Fill(geta,muH);
}
if(Layer==4){
TH1Ds["LA_TOB_4"]->Fill(muH);
TH2Ds["LA_phi_TOB4"]->Fill(gphi,muH);
TH2Ds["LA_eta_TOB4"]->Fill(geta,muH);
}
if(Layer==5){
TH1Ds["LA_TOB_5"]->Fill(muH);
TH2Ds["LA_phi_TOB5"]->Fill(gphi,muH);
TH2Ds["LA_eta_TOB5"]->Fill(geta,muH);
}
if(Layer==6){
TH1Ds["LA_TOB_6"]->Fill(muH);
TH2Ds["LA_phi_TOB6"]->Fill(gphi,muH);
TH2Ds["LA_eta_TOB6"]->Fill(geta,muH);
}
}
}
}
ModuleTree->Fill();
}
double GaussFitRange=conf_.getParameter<double>("GaussFitRange");
auto gaus = std::make_unique<TF1>("gaus","gaus");
TH1Ds["LA_TIB_1"]->Fit(gaus.get(),"","",-GaussFitRange,GaussFitRange);
mean_TIB1 = gaus->GetParameter(1);
float err_mean_TIB1 = gaus->GetParError(1);
float rms_TIB1 = gaus->GetParameter(2);
TH1Ds["LA_TIB_2"]->Fit(gaus.get(),"","",-GaussFitRange,GaussFitRange);
mean_TIB2 = gaus->GetParameter(1);
float err_mean_TIB2 = gaus->GetParError(1);
float rms_TIB2 = gaus->GetParameter(2);
TH1Ds["LA_TIB_3"]->Fit(gaus.get(),"","",-GaussFitRange,GaussFitRange);
mean_TIB3 = gaus->GetParameter(1);
float err_mean_TIB3 = gaus->GetParError(1);
float rms_TIB3 = gaus->GetParameter(2);
TH1Ds["LA_TIB_4"]->Fit(gaus.get(),"","",-GaussFitRange,GaussFitRange);
mean_TIB4 = gaus->GetParameter(1);
float err_mean_TIB4 = gaus->GetParError(1);
float rms_TIB4 = gaus->GetParameter(2);
TH1Ds["LA_TOB_1"]->Fit(gaus.get(),"","",-GaussFitRange,GaussFitRange);
mean_TOB1 = gaus->GetParameter(1);
float err_mean_TOB1 = gaus->GetParError(1);
float rms_TOB1 = gaus->GetParameter(2);
TH1Ds["LA_TOB_2"]->Fit(gaus.get(),"","",-GaussFitRange,GaussFitRange);
mean_TOB2 = gaus->GetParameter(1);
float err_mean_TOB2 = gaus->GetParError(1);
float rms_TOB2 = gaus->GetParameter(2);
TH1Ds["LA_TOB_3"]->Fit(gaus.get(),"","",-GaussFitRange,GaussFitRange);
mean_TOB3 = gaus->GetParameter(1);
float err_mean_TOB3 = gaus->GetParError(1);
float rms_TOB3 = gaus->GetParameter(2);
TH1Ds["LA_TOB_4"]->Fit(gaus.get(),"","",-GaussFitRange,GaussFitRange);
mean_TOB4 = gaus->GetParameter(1);
float err_mean_TOB4 = gaus->GetParError(1);
float rms_TOB4 = gaus->GetParameter(2);
TH1Ds["LA_TOB_5"]->Fit(gaus.get(),"","",-GaussFitRange,GaussFitRange);
mean_TOB5 = gaus->GetParameter(1);
float err_mean_TOB5 = gaus->GetParError(1);
float rms_TOB5 = gaus->GetParameter(2);
TH1Ds["LA_TOB_6"]->Fit(gaus.get(),"","",-GaussFitRange,GaussFitRange);
mean_TOB6 = gaus->GetParameter(1);
float err_mean_TOB6 = gaus->GetParError(1);
float rms_TOB6 = gaus->GetParameter(2);
int nlayersTIB = 4;
float TIBx[4]={1,2,3,4};
float TIBex[4]={0,0,0,0};
float TIBy[4]={mean_TIB1, mean_TIB2, mean_TIB3, mean_TIB4};
float TIBey[4]={err_mean_TIB1, err_mean_TIB2, err_mean_TIB3, err_mean_TIB4};
int nlayersTOB = 6;
float TOBx[6]={1,2,3,4,5,6};
float TOBex[6]={0,0,0,0,0,0};
float TOBy[6]={mean_TOB1, mean_TOB2, mean_TOB3, mean_TOB4, mean_TOB5, mean_TOB6};
float TOBey[6]={err_mean_TOB1, err_mean_TOB2, err_mean_TOB3, err_mean_TOB4, err_mean_TOB5, err_mean_TOB6};
TIB_graph = new TGraphErrors(nlayersTIB,TIBx,TIBy,TIBex,TIBey);
TOB_graph = new TGraphErrors(nlayersTOB,TOBx,TOBy,TOBex,TOBey);
//TF1 *fit_TIB= new TF1("fit_TIB","[0]",0,4);
//TF1 *fit_TOB= new TF1("fit_TOB","[0]",0,6);
gStyle->SetOptFit(111);
gStyle->SetOptStat(111);
TIB_graph->SetTitle("TIB Layers #mu_{H}");
TIB_graph->GetXaxis()->SetTitle("Layers");
TIB_graph->GetXaxis()->SetNdivisions(4);
TIB_graph->GetYaxis()->SetTitle("#mu_{H}");
TIB_graph->SetMarkerStyle(20);
TIB_graph->GetYaxis()->SetTitleOffset(1.3);
TIB_graph->Fit("fit_TIB","E","",1,4);
meanMobility_TIB = TIB_graph->GetFunction("fit_TIB")->GetParameter(0);
TOB_graph->SetTitle("TOB Layers #mu_{H}");
TOB_graph->GetXaxis()->SetTitle("Layers");
TOB_graph->GetXaxis()->SetNdivisions(6);
TOB_graph->GetYaxis()->SetTitle("#mu_{H}");
TOB_graph->SetMarkerStyle(20);
TOB_graph->GetYaxis()->SetTitleOffset(1.3);
TOB_graph->Fit("fit_TOB","E","",1,6);
meanMobility_TOB = TOB_graph->GetFunction("fit_TOB")->GetParameter(0);
TIB_graph->Write("TIB_graph");
TOB_graph->Write("TOB_graph");
Rep<<"- NR.OF TIB AND TOB MODULES = 7932"<<std::endl<<std::endl<<std::endl;
Rep<<"- NO MODULE HISTOS FOUND = "<<no_mod_histo<<std::endl<<std::endl;
Rep<<"- NR.OF HISTOS WITH ENTRIES > "<<FitCuts_Entries<<" = "<<histocounter<<std::endl<<std::endl;
Rep<<"- NR.OF HISTOS WITH ENTRIES <= "<<FitCuts_Entries<<" (!=0) = "<<NotEnoughEntries<<std::endl<<std::endl;
Rep<<"- NR.OF HISTOS WITH 0 ENTRIES = "<<ZeroEntries<<std::endl<<std::endl<<std::endl;
Rep<<"- NR.OF GOOD FIT (FIRST IT + SECOND IT GOOD FIT)= "<<GoodFit<<std::endl<<std::endl;
Rep<<"- NR.OF FIRST IT GOOD FIT = "<<FirstIT_goodfit<<std::endl<<std::endl;
Rep<<"- NR.OF SECOND IT GOOD FIT = "<<SecondIT_goodfit<<std::endl<<std::endl;
Rep<<"- NR.OF FIRST IT BAD FIT = "<<FirstIT_badfit<<std::endl<<std::endl;
Rep<<"- NR.OF SECOND IT BAD FIT = "<<SecondIT_badfit<<std::endl<<std::endl<<std::endl;
Rep<<"--------------- Mean MuH values per Layer -------------------"<<std::endl<<std::endl<<std::endl;
Rep<<"TIB1 = "<<mean_TIB1<<" +- "<<err_mean_TIB1<<" RMS = "<<rms_TIB1<<std::endl;
Rep<<"TIB2 = "<<mean_TIB2<<" +- "<<err_mean_TIB2<<" RMS = "<<rms_TIB2<<std::endl;
Rep<<"TIB3 = "<<mean_TIB3<<" +- "<<err_mean_TIB3<<" RMS = "<<rms_TIB3<<std::endl;
Rep<<"TIB4 = "<<mean_TIB4<<" +- "<<err_mean_TIB4<<" RMS = "<<rms_TIB4<<std::endl;
Rep<<"TOB1 = "<<mean_TOB1<<" +- "<<err_mean_TOB1<<" RMS = "<<rms_TOB1<<std::endl;
Rep<<"TOB2 = "<<mean_TOB2<<" +- "<<err_mean_TOB2<<" RMS = "<<rms_TOB2<<std::endl;
Rep<<"TOB3 = "<<mean_TOB3<<" +- "<<err_mean_TOB3<<" RMS = "<<rms_TOB3<<std::endl;
Rep<<"TOB4 = "<<mean_TOB4<<" +- "<<err_mean_TOB4<<" RMS = "<<rms_TOB4<<std::endl;
Rep<<"TOB5 = "<<mean_TOB5<<" +- "<<err_mean_TOB5<<" RMS = "<<rms_TOB5<<std::endl;
Rep<<"TOB6 = "<<mean_TOB6<<" +- "<<err_mean_TOB6<<" RMS = "<<rms_TOB6<<std::endl<<std::endl;
Rep<<"Mean Hall Mobility TIB = "<<meanMobility_TIB<<" +- "<<TIB_graph->GetFunction("fit_TIB")->GetParError(0)<<std::endl;
Rep<<"Mean Hall Mobility TOB = "<<meanMobility_TOB<<" +- "<<TOB_graph->GetFunction("fit_TOB")->GetParError(0)<<std::endl<<std::endl<<std::endl;
Rep.close();
NoEntries.close();
hFile->Write();
hFile->Close();
}
// Virtual destructor needed.
SiStripCalibLorentzAngle::~SiStripCalibLorentzAngle(){
delete hFile;
}
// Analyzer: Functions that gets called by framework every event
std::unique_ptr<SiStripLorentzAngle> SiStripCalibLorentzAngle::getNewObject(){
auto LorentzAngle = std::make_unique<SiStripLorentzAngle>();
if(!LayerDB){
for(std::map<uint32_t, float>::iterator it = detid_la.begin(); it != detid_la.end(); it++){
float langle=it->second;
if ( ! LorentzAngle->putLorentzAngle(it->first,langle) )
edm::LogError("SiStripCalibLorentzAngle")<<"[SiStripCalibLorentzAngle::analyze] detid already exists"<<std::endl;
}
}
else{
const TrackerGeometry::DetIdContainer& Id = estracker->detIds();
TrackerGeometry::DetIdContainer::const_iterator Iditer;
for(Iditer=Id.begin();Iditer!=Id.end();Iditer++){
StripSubdetector subid(Iditer->rawId());
hallMobility = 0.;
if(subid.subdetId() == int (StripSubdetector::TIB)){
uint32_t tibLayer = tTopo->tibLayer(*Iditer);
if(tibLayer==1){
hallMobility=mean_TIB1;}
if(tibLayer==2){
hallMobility=mean_TIB2;}
if(tibLayer==3){
hallMobility=mean_TIB3;}
if(tibLayer==4){
hallMobility=mean_TIB4;}
if (!LorentzAngle->putLorentzAngle(Iditer->rawId(),hallMobility)) edm::LogError("SiStripLorentzAngleGenerator")<<" detid already exists"<<std::endl;
}
if(subid.subdetId() == int (StripSubdetector::TOB)){
uint32_t tobLayer = tTopo->tobLayer(*Iditer);
if(tobLayer==1){
hallMobility=mean_TOB1;}
if(tobLayer==2){
hallMobility=mean_TOB2;}
if(tobLayer==3){
hallMobility=mean_TOB3;}
if(tobLayer==4){
hallMobility=mean_TOB4;}
if(tobLayer==5){
hallMobility=mean_TOB5;}
if(tobLayer==6){
hallMobility=mean_TOB6;}
if (!LorentzAngle->putLorentzAngle(Iditer->rawId(),hallMobility)) edm::LogError("SiStripLorentzAngleGenerator")<<" detid already exists"<<std::endl;
}
if( subid.subdetId() == int(StripSubdetector::TID) ) {
hallMobility=meanMobility_TIB;
if (!LorentzAngle->putLorentzAngle(Iditer->rawId(),hallMobility)) edm::LogError("SiStripLorentzAngleGenerator")<<" detid already exists"<<std::endl;
}
if( subid.subdetId() == int(StripSubdetector::TEC) ) {
if(tTopo->tecRing(subid)<5 ) {
hallMobility=meanMobility_TIB;
}else{
hallMobility=meanMobility_TOB;
}
if (!LorentzAngle->putLorentzAngle(Iditer->rawId(),hallMobility)) edm::LogError("SiStripLorentzAngleGenerator")<<" detid already exists"<<std::endl;
}
}
}
return LorentzAngle;
}
| 42.995327 | 210 | 0.688376 | bisnupriyasahu |
5188bffa5620cb9c9521eaba5ee56c4526a74f7c | 39,638 | cpp | C++ | src/mmlib/forcefields/nonbonded.cpp | JonnyWideFoot/pd.arcus | a6197a5a2a18c0e3f752e15aa982d1e44d052730 | [
"BSD-4-Clause-UC"
] | null | null | null | src/mmlib/forcefields/nonbonded.cpp | JonnyWideFoot/pd.arcus | a6197a5a2a18c0e3f752e15aa982d1e44d052730 | [
"BSD-4-Clause-UC"
] | null | null | null | src/mmlib/forcefields/nonbonded.cpp | JonnyWideFoot/pd.arcus | a6197a5a2a18c0e3f752e15aa982d1e44d052730 | [
"BSD-4-Clause-UC"
] | null | null | null | #include "global.h"
#include "forcefields/nonbonded.h" // provides base class
#include "workspace/workspace.h"
#include "workspace/neighbourlist.h"
#include "workspace/space.h"
#include "traits.h"
#include "exception.h"
#include "funcgen.h"
namespace Physics
{
/// \details calculates both vacuum electrostatics as well as VdW forces & energies
/// in one function for an arbitrary boundary (no boundary, periodic boundary, etc..)
/// Basic structure:
/// For every atom
/// For every atom in neighbor list
/// calculate potential energy
/// calculate Forces along i<->j
///
/// VdW: A = 2.0*Maths::Maths::sqr(radius^6)/d12;
/// B = radius^6/d6;
/// potential energy: 4.0*epsilon*(0.5*A-B);
/// force: -(24.0*epsilon/Dist_ij) * (A-B);
///
/// Electrostatics:
/// potential energy: (1/(PhysicsConst::4pi_e0*Dielectric)) * (qi*qj)/(Dist_ij);
/// force: -elec_potential/Dist_ij;
///
/// This function is a "generator" function - it provides a blue print or template
/// vor various specialized and generic versions of it
/// This is implemented using c++ templates and traits.
/// The idea is when an instantiation of a particular template, certain parts
/// of the generator function are excluded/included in the compilation process.
/// this is achieved using traits:
/// In the function body there will be if-block like this one:
///
/// if(is_same_type<T_Space,PeriodicBox>::value){
/// ...
/// }
///
/// is_same_type<A,B> returns true when the two types are identical or false
/// otherwise. However this result is known at **compile time** which means
/// that when the compiler gets to the optimisation stage it sees a
/// if(true){ ... } or if(false){ ... }
/// Any reaasonable compiler will thus optimise the if statement away leaving only
/// the content of the if statement bare (if the test evaluated to true) or
/// nothing if the test evaluated to false.
///
/// This mechanism enables one to write hand-inlined code to do certain operations
/// much faster than calling a function (as does the GenericSpace version)
template <typename T_Space, bool verbosemode>
void FF_NonBonded_CalcEnergies_Update_T(
FF_NonBonded &ff,
WorkSpace& wspace,
std::vector <size_t> &changed_atom,
std::vector <size_t> &old_changed_atom,
double &epot_reference,
ForcefieldBase::AtomicVerbosity verbose_level = ForcefieldBase::Summary)
{
using namespace Maths;
// set up proxies to workspace to make code more readable.
size_t natom = wspace.atom.size(); // number of atoms in workspace
const ParticleStore& atomparam = wspace.atom; // atom parameter array
SnapShotAtom *atom = wspace.cur.atom; // atom coordinate array
const NeighbourData *fnbor = wspace.nlist().getData(); // neighborlist
// Basic stuff
int i, j, nj; // i&j are atom indices, nj count through neighbor list
dvector fv; // force dvector
double force_magnitude= 0; // force magnitude
double intvir = 0; // part of internal virial
double vdw_force = 0; // individual force magnitudes
double elec_force = 0;
double vdw_potential = 0; // individual potential energy contributions
double elec_potential = 0;
double vdw14scale = 1.0;
double elec14scale = 1.0;
double sqrdistij,Dist_ij; // distance in Angstrom
double invdistij; //, invd6;
const double sqrcutoff = sqr(ff.Cutoff);
const double sqrinnercutoff = sqr(ff.InnerCutoff);
double radiusij, epsilon, A, B;
double qi, qj;
const double invdielectric = 1.0 / ff.Dielectric;
// periodic spaces
unsigned image;
const unsigned maximages = wspace.boundary().ncells();
unsigned nimages;
PeriodicBox *periodic_box;
if(is_same_type<T_Space,PeriodicBox>::value)
{
periodic_box = (PeriodicBox *) &wspace.boundary();
}
// local temporary variables
dvector dc;
double atomi_radius;
double atomi_epsilon;
dvector fv_iatom;
dvector fv_jatom;
// elec switching
const double Swidth = ff.Cutoff - ff.InnerCutoff;
const double invSwidth = 1.0 / Swidth;
double S;
//double dSdd;
// vdw switching
const double vdwSwidth = ff.VdwCutoff - ff.VdwInnerCutoff;
const double vdwinvSwidth = 1.0 / vdwSwidth;
double vdwS;
//double vdwdSdd;
// precalculated stuff for force switching
const double sA = 1.0/cube( sqr(ff.Cutoff) - sqr(ff.InnerCutoff) );
const double sB = -( cube(sqr(ff.Cutoff)) - 3.0* sqr(ff.Cutoff) * sqr(ff.Cutoff) * sqr(ff.InnerCutoff));
const double sC = 6.0* sqr(ff.Cutoff) * sqr(ff.InnerCutoff);
const double sD = -(sqr(ff.Cutoff) + sqr(ff.InnerCutoff));
const double sE = 2.0/5.0;
const double fswitch_innerV = sA * (sB * (1.0/ff.InnerCutoff) + sC * ff.InnerCutoff + sD * cube(ff.InnerCutoff) + sE * cube(ff.InnerCutoff) * sqr(ff.InnerCutoff));
const double fswitch_cutoffV = sA * (sB * (1.0/ff.Cutoff) + sC * ff.Cutoff + sD * cube(ff.Cutoff) + sE * cube(ff.Cutoff) * sqr(ff.Cutoff));
double eshift;
if(ff.InnerCutoff < ff.Cutoff) eshift = 1/ff.InnerCutoff + (fswitch_innerV - fswitch_cutoffV);
else eshift = 0;
// statistics
int totalpairs = 0;
int pairs14 = 0;
int vdwpairs = 0;
int elecpairs = 0;
// DONT set epot to zero - we need its old value
// epot = 0;
//if(has changed
double refmul=-1;
int twoloopstart = 0;
wspace.ene.epot_vdw = 0;
wspace.ene.epot_elec = 0;
old_changed_atom = changed_atom;
changed_atom.clear();
// loop over all particles
for(i = 0; i < natom; i++){
if( !(wspace.old.atom[i].p == wspace.cur.atom[i].p) ) changed_atom.push_back(i);
}
// check if THE SAME particles have move since last time
if(old_changed_atom == changed_atom){
// if so skip the first par tof the inner loop
twoloopstart=1;
ff.epot = epot_reference;
}else{
// else do both parts but record a new reference energy for next time
epot_reference=ff.epot;
}
// loop over all changed particles
size_t ichanged;
for(ichanged = 0; ichanged < changed_atom.size(); ichanged++)
{
i = changed_atom[ichanged];
//for(i = 0; i < natom; i++){
// if( wspace.old.atom[i].p == wspace.cur.atom[i].p ) continue;
atomi_radius = atomparam[i].radius;
atomi_epsilon = atomparam[i].epsilon;
qi = atomparam[i].charge;
fv_iatom.zero();
// loop over all it's neighbors
for(nj = 0; nj < fnbor[i].n; nj++)
{
j = fnbor[i].i[nj];
fv_jatom.zero();
if( (fnbor[i].Type[nj] & 127) > 1) continue;// only get non-bonded and 1-4 neighbors but include shadows!
if( ff.IgnoreIntraResidue )
if( atomparam[i].ir == atomparam[j].ir ) continue;
// if j has also moved, only calculate interaction once
if( !(wspace.old.atom[j].p == wspace.cur.atom[j].p) ){
if( (fnbor[i].Type[nj]) > 1) continue;
}
vdw14scale = 1.0;
elec14scale = 1.0;
if(fnbor[i].Type[nj] == 1) {
pairs14++;
vdw14scale = ff.Vdw14Scaling;
elec14scale = ff.Elec14Scaling;
}
//force_magnitude= 0;
//intvir = 0;
double mul;
mul=-1.0;
refmul=-1.0;
int twoloop;
dc.diff(wspace.old.atom[j].p,wspace.old.atom[i].p);
for(twoloop=twoloopstart;twoloop<2;twoloop++){
if(twoloop == 1){
dc.diff(wspace.cur.atom[j].p,wspace.cur.atom[i].p);
mul *= -1.0;
refmul = 0.0;
}
nimages=maximages;
if(is_same_type<T_Space,PeriodicBox>::value){
if(maximages > 1)
if( dc.innerdot() < sqr( periodic_box->savedist*2.0 - ff.Cutoff )){
nimages = 1;
}
}
image = 0;
imageloop:
fv.setTo(dc);
if(is_same_type<T_Space,PeriodicBox>::value){
// Specialised code for PeriodicBox space boundaries
fv.add(periodic_box->celloffset[image]);
while(fv.x > periodic_box->halfCellSize.x) fv.x -= periodic_box->cellSize.x;
while(fv.x < -periodic_box->halfCellSize.x) fv.x += periodic_box->cellSize.x;
while(fv.y > periodic_box->halfCellSize.y) fv.y -= periodic_box->cellSize.y;
while(fv.y < -periodic_box->halfCellSize.y) fv.y += periodic_box->cellSize.y;
while(fv.z > periodic_box->halfCellSize.z) fv.z -= periodic_box->cellSize.z;
while(fv.z < -periodic_box->halfCellSize.z) fv.z += periodic_box->cellSize.z;
sqrdistij = fv.innerdot();
if(sqrdistij > sqrcutoff) goto imageloop_continue;
Dist_ij = sqrt(sqrdistij);
}
else if(is_same_type<T_Space,InfiniteSpace>::value){
// Specialised code for InfiniteSpace space boundaries
// I.e.: do nothing in infinite space - the real and imaginary
// images are identical.
sqrdistij = fv.innerdot();
Dist_ij = sqrt(sqrdistij);
}
else
{
// Specialised code for PeriodicBox space boundaries
wspace.boundary().getImage(fv,image);
sqrdistij = fv.innerdot();
if(sqrdistij > sqrcutoff) goto imageloop_continue;
Dist_ij = sqrt(sqrdistij);
}
totalpairs++;
invdistij = 1.0 / Dist_ij;
// Van der Waals Force
vdw_potential = 0;
vdw_force = 0;
elec_potential = 0;
elec_force = 0;
if(ff.DoVdw){
if(Dist_ij < ff.VdwCutoff) {
vdwpairs++;
// first calculate well depth (epsilon) and zero-force-separation (radiusij)
// Use Lorentz-Berthelot mixing rules
// arthemic mean for radiusij (=sum of radii) and geometric mean for epsilon
radiusij = atomi_radius + atomparam[j].radius;
// radiusij *= 0.890898718; // div 2^(1/6)
// two different mixing rules - at the moment only geometric mean is implemented
epsilon = vdw14scale * atomi_epsilon * atomparam[j].epsilon;
B = sqr(radiusij*invdistij); // * sqr(radiusij) * sqr(radiusij) * invd6;
B *=B*B;
A = sqr(B);
vdw_potential = (2.0 * epsilon) * (0.5 * A - B);
if(Dist_ij > ff.VdwInnerCutoff) {
vdwS = (1.0 - sqr(vdwinvSwidth * (Dist_ij - ff.VdwInnerCutoff))); // Dimension less
vdwS = sqr(vdwS);
vdw_potential *= vdwS;
}
}
}
// electrostatics --------------------------------
if(ff.DoElec) {
if(Dist_ij < ff.Cutoff) {
qj = atomparam[j].charge;
elecpairs++;
if(ff.EnergySwitch){
if(ff.DDDielectric) { // distance dependent ff.Dielectric
double incdistij = ((ff.Dielectric + ff.DDDielectricAlpha * Dist_ij) * Dist_ij);
elec_potential = PhysicsConst::econv_joule * elec14scale * (qi * qj) / incdistij;
} else {
elec_potential = PhysicsConst::econv_joule * invdielectric * elec14scale * (qi * qj) * invdistij;
}
if(Dist_ij > ff.InnerCutoff) {
S = (1.0 - sqr(invSwidth * (Dist_ij - ff.InnerCutoff))); // Dimension less
S = sqr(S);
elec_potential *= S;
}
} else
if(ff.ForceSwitch){
elec_potential = PhysicsConst::econv_joule * invdielectric * elec14scale * (qi * qj);
if(Dist_ij > ff.InnerCutoff) {
elec_potential *= - ( sA * Dist_ij *
(sB * sqr(invdistij) +
sC +
sD * sqrdistij +
sE * sqr(sqrdistij))
-fswitch_cutoffV);
}else{
elec_potential *= (invdistij - eshift);
}
} else {
elec_potential = PhysicsConst::econv_joule * invdielectric * elec14scale * (qi * qj) * invdistij;
}
}
}
// add up potentials -----------------------------
// update energy
ff.epot += mul*(vdw_potential + elec_potential);
epot_reference += refmul*(vdw_potential + elec_potential);
// an "explicit" for loop
imageloop_continue:
if(!is_same_type<T_Space,InfiniteSpace>::value){
image++;
if(image<nimages) goto imageloop;
}
} // twoloop (in the first sweep 'remove' the old interactions, in the second add the new ones)
}
}
wspace.ene.epot += ff.epot;
}
void FF_NonBonded::calc_LJ_Coulomb_Force(
// general
double Dist_ij,
double invdistij,
// vdw
double radiusij,
double epsilon,
// elec
double qi,
double qj,
// result
double &vdw_potential,
double &vdw_force,
double &elec_potential,
double &elec_force
){
using namespace Maths;
double A, B;
const double invdielectric = 1.0 / Dielectric;
const double sqrcutoff = sqr(Cutoff);
const double sqrinnercutoff = sqr(InnerCutoff);
// elec switching
const double Swidth = Cutoff - InnerCutoff;
const double invSwidth = 1.0 / Swidth;
double S;
double dSdd;
// vdw switching
const double vdwSwidth = VdwCutoff - VdwInnerCutoff;
const double vdwinvSwidth = 1.0 / vdwSwidth;
double vdwS;
double vdwdSdd;
// precalculated stuff for force switching
const double sA = 1.0/cube( sqr(Cutoff) - sqr(InnerCutoff) );
const double sB = -( cube(sqr(Cutoff)) - 3.0* sqr(Cutoff) * sqr(Cutoff) * sqr(InnerCutoff));
const double sC = 6.0* sqr(Cutoff) * sqr(InnerCutoff);
const double sD = -(sqr(Cutoff) + sqr(InnerCutoff));
const double sE = 2.0/5.0;
const double fswitch_innerV = sA * (sB * (1.0/InnerCutoff) + sC * InnerCutoff + sD * cube(InnerCutoff) + sE * cube(InnerCutoff) * sqr(InnerCutoff));
const double fswitch_cutoffV = sA * (sB * (1.0/Cutoff) + sC * Cutoff + sD * cube(Cutoff) + sE * cube(Cutoff) * sqr(Cutoff));
double eshift;
double sqrdistij = sqr(Dist_ij);
if(InnerCutoff < Cutoff) eshift = 1/InnerCutoff + (fswitch_innerV - fswitch_cutoffV);
else eshift = 0;
// Van der Waals Force
vdw_potential = 0;
vdw_force = 0;
elec_potential = 0;
elec_force = 0;
if(Dist_ij < VdwCutoff) {
B = sqr(radiusij*invdistij); // * sqr(radiusij) * sqr(radiusij) * invd6;
B *=B*B;
A = sqr(B);
vdw_potential = (2.0 * epsilon) * (0.5 * A - B);
vdw_force = -(12.0E10 * epsilon * invdistij) * (A - B);
if(Dist_ij > VdwInnerCutoff) {
vdwS = (1.0 - sqr(vdwinvSwidth * (Dist_ij - VdwInnerCutoff))); // Dimension less
vdwdSdd = -4.0E10 * sqr(vdwinvSwidth) * (Dist_ij - VdwInnerCutoff) * vdwS; // Units of per meter (not per angstrom!)
vdwS = sqr(vdwS);
vdw_force = vdwS * vdw_force + vdw_potential * vdwdSdd;
vdw_potential *= vdwS;
}
}
// electrostatics --------------------------------
if(Dist_ij < Cutoff) {
if(EnergySwitch){
if(DDDielectric) { // distance dependent Dielectric
double incdistij = ((Dielectric + DDDielectricAlpha * Dist_ij) * Dist_ij);
elec_potential = PhysicsConst::econv_joule * (qi * qj) / incdistij;
elec_force = -elec_potential * (Dielectric + 2.0 * DDDielectricAlpha * Dist_ij) / (incdistij * PhysicsConst::Angstrom);
} else {
elec_potential = PhysicsConst::econv_joule * invdielectric * (qi * qj) * invdistij;
elec_force = -elec_potential * invdistij * 1E10;
}
if(Dist_ij > InnerCutoff) {
S = (1.0 - sqr(invSwidth * (Dist_ij - InnerCutoff))); // Dimension less
dSdd = -4.0E10 * sqr(invSwidth) * (Dist_ij - InnerCutoff) * S ; // Units of per meter (not per angstrom!)
S = sqr(S);
elec_force = S * elec_force + elec_potential * dSdd;
elec_potential *= S;
}
} else
if(ForceSwitch){
elec_potential = PhysicsConst::econv_joule * invdielectric * (qi * qj);
if(Dist_ij > InnerCutoff) {
elec_force = -1E10 * elec_potential*
sA * sqr(invdistij) *
sqr(sqrcutoff - sqrdistij)*
(sqrcutoff - 3.0*sqrinnercutoff + 2.0*sqrdistij);
elec_potential *= - ( sA * Dist_ij *
(sB * sqr(invdistij) +
sC +
sD * sqrdistij +
sE * sqr(sqrdistij))
-fswitch_cutoffV);
}else{
elec_force = -1E10 * elec_potential* sqr(invdistij);
elec_potential *= (invdistij - eshift);
}
} else {
elec_potential = PhysicsConst::econv_joule * invdielectric * (qi * qj) * invdistij;
elec_force = -elec_potential * invdistij * 1E10;
}
}
}
/// Latest Fast & Tempalated NonBonded Calculation
const int T_SqrtFPU = 0; // use built-in sqrt function
const int T_SqrtTable = 1; // use sqrttable + 1 Newton-Raphson iteration (single precision)
const int T_VdwMode_None = 0; // No VDW
const int T_VdwMode_Normal = 1; // Normal VDW, no switching
const int T_VdwMode_EnergySwitch = 2; // VDW + Energy Switch
const int T_ElecMode_None = 0; // No electrostatics
const int T_ElecMode_Normal = 1; // Normal electrostatics, no switching
const int T_ElecMode_DDDielectric_Levitt = 2; // As above but with DDDielectric (a la Levitt)
const int T_ElecMode_EnergySwitch = 3; // Energy Switching
const int T_ElecMode_ForceSwitch = 4; // Force switching
const int T_VerboseMode_False = 0;
const int T_VerboseMode_True = 1;
template <
int T_SqrtMode,
int T_VdwMode,
int T_ElecMode,
int T_VerboseMode
>
void FF_NonBonded_CalcForces_T_fast2(
FF_NonBonded &ff,
NonBonded_Pack *local_atomparam,
Maths::dvector *basisvector,
WorkSpace &wspace,
ForcefieldBase::AtomicVerbosity verbose_level = ForcefieldBase::Summary)
{
using namespace Maths;
// set up proxies to workspace to make code more readable.
size_t natom = wspace.atom.size(); // number of atoms in workspace
const ParticleStore& atomparam = wspace.atom; // atom parameter array
SnapShotAtom *atom = wspace.cur.atom; // atom coordinate array
const NeighbourData *fnbor = wspace.nlist().getData(); // neighborlist
// Basic stuff
int j, nbor_type, i , nj; // i&j are atom indices, nj count through neighbor list
dvector fv; // force dvector
double force_magnitude= 0.0; // force magnitude
double intvir = 0.0; // part of internal virial
double vdw_force = 0.0; // individual force magnitudes
double elec_force = 0.0;
double vdw_potential = 0.0; // individual potential energy contributions
double elec_potential = 0.0;
double vdw14scale = 1.0;
double elec14scale = 1.0;
double sqrdistij,Dist_ij; // distance in Angstrom
double invdistij;
const double sqrcutoff = sqr(ff.Cutoff);
const double sqrinnercutoff = sqr(ff.InnerCutoff);
double radiusij=0.0, epsilon=0.0, A, B;
double qi, qj = DBL_MAX;
const double invdielectric = 1.0 / ff.Dielectric;
// local temporary variables
double atomi_radius=0;
double atomi_epsilon=0;
dvector fv_iatom;
dvector fv_jatom;
// elec switching
const double Swidth = ff.Cutoff - ff.InnerCutoff;
const double invSwidth = 1.0 / Swidth;
double S;
double dSdd;
// vdw switching
const double vdwSwidth = ff.VdwCutoff - ff.VdwInnerCutoff;
const double vdwinvSwidth = 1.0 / vdwSwidth;
double vdwS;
double vdwdSdd;
// precalculated stuff for force switching
const double sA = 1.0/cube( sqr(ff.Cutoff) - sqr(ff.InnerCutoff) );
const double sB = -( cube(sqr(ff.Cutoff)) - 3.0* sqr(ff.Cutoff) * sqr(ff.Cutoff) * sqr(ff.InnerCutoff));
const double sC = 6.0* sqr(ff.Cutoff) * sqr(ff.InnerCutoff);
const double sD = -(sqr(ff.Cutoff) + sqr(ff.InnerCutoff));
const double sE = 2.0/5.0;
const double fswitch_innerV = sA * (sB * (1.0/ff.InnerCutoff) +
sC * ff.InnerCutoff +
sD * cube(ff.InnerCutoff) +
sE * cube(ff.InnerCutoff) * sqr(ff.InnerCutoff));
const double fswitch_cutoffV = sA * (sB * (1.0/ff.Cutoff) +
sC * ff.Cutoff +
sD * cube(ff.Cutoff) +
sE * cube(ff.Cutoff) * sqr(ff.Cutoff));
double eshift;
if(ff.InnerCutoff < ff.Cutoff) eshift = 1/ff.InnerCutoff + (fswitch_innerV - fswitch_cutoffV);
else eshift = 0;
// statistics
int totalpairs = 0;
int pairs14 = 0;
int vdwpairs = 0;
int elecpairs = 0;
// stuff for the verbose modes
double lastenergy_vdw = 0;
double lastenergy_elec = 0;
// low bondorder scaling
double tabVdw14Scaling[8] = {0.0, 0.0, 0.0, ff.Vdw14Scaling, 1.0, 1.0, 1.0, 1.0};
double tabElec14Scaling[8] = {0.0, 0.0, 0.0, ff.Elec14Scaling, 1.0, 1.0, 1.0, 1.0};
// inv sqrt tables precalcs
int invsqrttable_bins = 256;
double invsqrttable_binsize;
double invinvsqrttable_binsize;
double *invsqrttable;
if( T_SqrtMode != T_SqrtFPU ){
invsqrttable_binsize = sqr(ff.Cutoff+4.0)/double(invsqrttable_bins);
invinvsqrttable_binsize = 1.0/invsqrttable_binsize;
invsqrttable = new double [invsqrttable_bins];
for(i=0;i<invsqrttable_bins;i++){
invsqrttable[i] = 1.0/sqrt(invsqrttable_binsize* (i+1) );
}
}
if(T_VerboseMode==T_VerboseMode_True)
{
// only in the verbose instantiation
printf("\nPairwise simple forces \n\n");
if(verbose_level == ForcefieldBase::Detailed)
printf("Pair: i nr(Name) nj nr(Name) Vdw: dist radiusij Vvdw Elec: chgi chgj Dist_ij Velec \n\n");
}
// initialise energies
ff.epot = 0;
wspace.ene.epot_vdw = 0;
wspace.ene.epot_elec = 0;
// make a little proxy
int *nlistptr=&fnbor[0].i[0];
// loop over all particles
for(i = 0; i < natom; i++)
{
// get properties of atom i
atomi_radius = local_atomparam[i].radius;
atomi_epsilon = local_atomparam[i].epsilon;
qi = local_atomparam[i].charge;
fv_iatom.zero();
int const fnborn = fnbor[i].n;
nlistptr=&fnbor[i].i[0];
// loop over all its neighbors
for(nj = 0; nj < fnborn; nj++)
{
// work out the atom number and extra info such as bondorder and space vector.
// the atom number is in the lower 24 bits, the bondorder and space vector index in the remainder
//j = *(nlistptr); nlistptr++;
//nbor_type = *(nlistptr); nlistptr++;
j = *(nlistptr); nlistptr++;
nbor_type = j>>24;
j &= 0x00FFFFFF;
if( j >= i ) break; // ignore shadow neighbors !!
// determine scaling factors - grab them out of a table using the bornorder (which is
// now in the lower 4 bits of the variable nbor_type
vdw14scale = tabVdw14Scaling[(nbor_type&7)];
elec14scale = tabElec14Scaling[(nbor_type&7)];
intvir = 0;
// obtain the vector from atom i to atom j and add the periodic space shift vector
// also read out of an array
fv.diff(wspace.cur.atom[j].p,wspace.cur.atom[i].p);
fv.add( basisvector[ (nbor_type>>3)&31] );
// get the squared distance and determine if we need to consider this atom pair
sqrdistij = fv.innerdot();
if( sqrdistij > sqrcutoff ){
continue;
}
totalpairs++;
// get the distance and inverse distance
if( T_SqrtMode == T_SqrtFPU ){
Dist_ij = sqrt(sqrdistij);
invdistij = 1.0 / Dist_ij;
}else{
invdistij = invsqrttable[ int(sqrdistij * invinvsqrttable_binsize) ];
invdistij = 0.5*(3.0 - sqr(invdistij)*sqrdistij)*invdistij;
Dist_ij = sqrdistij*invdistij;
}
// Van der Waals Force
vdw_potential = 0;
vdw_force = 0;
if( T_VdwMode > T_VdwMode_None){
if(Dist_ij < ff.VdwCutoff){
radiusij = atomi_radius + local_atomparam[j].radius;
epsilon = vdw14scale * atomi_epsilon * local_atomparam[j].epsilon;
B = sqr(radiusij*invdistij);
B *=B*B;
A = sqr(B);
vdw_potential = (2.0 * epsilon) * (0.5 * A - B);
vdw_force = -(12.0E10 * epsilon * invdistij) * (A - B);
if( T_VdwMode == T_VdwMode_EnergySwitch ){
if(Dist_ij > ff.VdwInnerCutoff) {
vdwS = (1.0 - sqr(vdwinvSwidth * (Dist_ij - ff.VdwInnerCutoff)));
vdwdSdd = -4.0E10 * sqr(vdwinvSwidth) * (Dist_ij - ff.VdwInnerCutoff) * vdwS;
vdwS = sqr(vdwS);
vdw_force = vdwS * vdw_force + vdw_potential * vdwdSdd;
vdw_potential *= vdwS;
}
}
}
}
if( T_ElecMode > T_ElecMode_None){
qj = local_atomparam[j].charge;
if( T_ElecMode == T_ElecMode_Normal )
{
elec_potential = PhysicsConst::econv_joule * invdielectric * elec14scale * (qi * qj) * invdistij;
elec_force = -elec_potential * invdistij * 1E10;
}
if( T_ElecMode == T_ElecMode_DDDielectric_Levitt )
{
double incdistij = ((ff.Dielectric + ff.DDDielectricAlpha * Dist_ij) * Dist_ij);
elec_potential = PhysicsConst::econv_joule * elec14scale * (qi * qj) / incdistij;
elec_force = -elec_potential * (ff.Dielectric + 2.0 * ff.DDDielectricAlpha * Dist_ij) / (incdistij * PhysicsConst::Angstrom);
}
if( T_ElecMode == T_ElecMode_EnergySwitch )
{
elec_potential = PhysicsConst::econv_joule * invdielectric * elec14scale * (qi * qj) * invdistij;
elec_force = -elec_potential * invdistij * 1E10;
if(Dist_ij > ff.InnerCutoff) {
S = (1.0 - sqr(invSwidth * (Dist_ij - ff.InnerCutoff))); // Dimension less
dSdd = -4.0E10 * sqr(invSwidth) * (Dist_ij - ff.InnerCutoff) * S ; // Units of per meter (not per angstrom!)
S = sqr(S);
elec_force = S * elec_force + elec_potential * dSdd;
elec_potential *= S;
}
//printf("%e %e %e \n",Dist_ij, elec_potential / qi / qj, elec_force /qi /qj );
}
if( T_ElecMode == T_ElecMode_ForceSwitch )
{
elec_potential = PhysicsConst::econv_joule * invdielectric * elec14scale * (qi * qj);
if(Dist_ij > ff.InnerCutoff) {
elec_force = -1E10 * elec_potential*
sA * sqr(invdistij) *
sqr(sqrcutoff - sqrdistij)*
(sqrcutoff - 3.0*sqrinnercutoff + 2.0*sqrdistij);
elec_potential *= - ( sA * Dist_ij *
(sB * sqr(invdistij) +
sC +
sD * sqrdistij +
sE * sqr(sqrdistij))
-fswitch_cutoffV);
}else{
elec_force = -1E10 * elec_potential* sqr(invdistij);
elec_potential *= (invdistij - eshift);
}
}
}else{
elec_potential = 0;
elec_force = 0;
}
wspace.ene.epot += vdw_potential + elec_potential;;
wspace.ene.epot_vdw += vdw_potential;
wspace.ene.epot_elec += elec_potential;
force_magnitude= vdw_force + elec_force;
// for intermolecular forces add up virial components
wspace.ene.InternalVirial += Dist_ij * force_magnitude* PhysicsConst::Angstrom;
fv.mul(invdistij * force_magnitude);
fv_iatom.add(fv);
if( T_VerboseMode == T_VerboseMode_True){
if(verbose_level == ForcefieldBase::Detailed) {
printf("Pair:%5d(%4s)%5d(%4s) Vdw: %5.2lf %5.2lf %5.2lf %8.3lf Elec: % 4.2lf % 4.2lf %5.2lf % 8.3lf\n",
i, atomparam[i].pdbname.c_str(),
j, atomparam[j].pdbname.c_str(),
Dist_ij,
radiusij,
epsilon * PhysicsConst::J2kcal * PhysicsConst::Na,
vdw_potential * PhysicsConst::J2kcal * PhysicsConst::Na,
qi,
qj,
Dist_ij,
elec_potential * PhysicsConst::J2kcal * PhysicsConst::Na);
}
}
atom[j].f.sub(fv);
}
atom[i].f.add(fv_iatom);
// add a vdw correction if required
if(ff.VdwCor){
// this correction is the analytical integral of the attractive portion of the LJ potential
// from ff.VdwCorCutoff to infinity. usually you;d want to set ff.VdwCorCutoff == ff.VdwCutoff;
vdw_potential = -0.5*ff.VdwCorDensity * ff.VdwCorEpsilon / (PhysicsConst::J2kcal * PhysicsConst::Na)
* (8.0/3.0) * MathConst::PI * sqr(ff.VdwCorRadius) *
sqr(ff.VdwCorRadius) * sqr(ff.VdwCorRadius) /
cube(ff.VdwCorCutoff);
// for the purpose of vdw path assume it's non hydrogen/non hydorgen
wspace.ene.epot += vdw_potential;
wspace.ene.epot_vdw += vdw_potential;
wspace.ene.epot_vdw_att += vdw_potential;
}
if( T_VerboseMode == T_VerboseMode_True){
printf("Atom: %12.7lf %12.7lf %12.7lf %5d(%4s) %5d Rad: %6.4lf Eps: %6.4lf Vdw: % 8.3lf Elec: % 4.4lf % 8.3lf\n",
atom[i].p.x, atom[i].p.y, atom[i].p.z,
i, atomparam[i].pdbname.c_str(),
fnbor[i].n,
atomparam[i].radius,
sqr(atomparam[i].epsilon) * PhysicsConst::J2kcal * PhysicsConst::Na,
(wspace.ene.epot_vdw - lastenergy_vdw) * PhysicsConst::J2kcal * PhysicsConst::Na,
atomparam[i].charge,
(wspace.ene.epot_elec - lastenergy_elec) * PhysicsConst::J2kcal * PhysicsConst::Na);
lastenergy_vdw = wspace.ene.epot_vdw;
lastenergy_elec = wspace.ene.epot_elec;
}
}
if(T_VerboseMode == T_VerboseMode_True){
printf("\n");
printf(" ----------------- -----------------\n");
printf(" Total: %8.3lf Total: %8.3lf \n\n\n",
wspace.ene.epot_vdw * PhysicsConst::J2kcal * PhysicsConst::Na,
wspace.ene.epot_elec * PhysicsConst::J2kcal * PhysicsConst::Na);
printf(" Total number of interactions:\n");
printf(" Total: %8d\n",totalpairs);
printf(" 1-4: %8d\n",pairs14);
printf(" Van d. Waals: %8d\n",vdwpairs);
printf(" Electrostatic: %8d\n",elecpairs);
}
ff.epot = wspace.ene.epot_vdw + wspace.ene.epot_elec;
if( T_SqrtMode != T_SqrtFPU ){
delete [] invsqrttable;
}
}
template <int a, int b, int c, int d>
struct FF_NonBonded_CalcForces_T_fast2_wrap{
FF_NonBonded_CalcForces_T_fast2_wrap():ptr(&FF_NonBonded_CalcForces_T_fast2<a, b, c, d>){}
typedef void (*Tptr)(
FF_NonBonded &ff,
NonBonded_Pack *local_atomparam,
Maths::dvector *basisvector,
WorkSpace &wspace,
ForcefieldBase::AtomicVerbosity verbose_level);
Tptr ptr;
const static int limita=T_SqrtTable;
const static int limitb=T_VdwMode_EnergySwitch;
const static int limitc=T_ElecMode_ForceSwitch;
const static int limitd=T_VerboseMode_True;
static void overflow(){
throw(CodeException("CODE ERROR: FF_NonBonded_CalcForces_T_fast2_wrap template requested that is out of bounds.") );
}
};
FF_NonBonded::FF_NonBonded( WorkSpace &newwspace ):
ForcefieldBase( newwspace )
{
name = "Non-Bonded Forcefield";
ShortName = "NonBonded";
local_atomparam = NULL;
settodefault();
}
FF_NonBonded* FF_NonBonded::clone() const
{
return new FF_NonBonded(*this);
}
FF_NonBonded::~FF_NonBonded()
{
delete [] local_atomparam;
}
/// prints a little block of parameter information
void FF_NonBonded::info() const
{
ForcefieldBase::info(); // standard info
printf("Solute Dielectric: %4.1lf\n", Dielectric);
printf("VDW 1-4 scaling factor: %6.3lf\n", Vdw14Scaling);
printf("Elec 1-4 scaling factor: %12.8lf\n", Elec14Scaling);
printf("Distance dep. Dielectric: %s\n", DDDielectric == true ? "yes" : "no");
if(DDDielectric)
{
printf("DDD form: e(r) = %3.2lf + %3.2lf*r\n",Dielectric, DDDielectricAlpha);
}
printf("VDW Cutoff: %4.1lf A\n", VdwCutoff);
printf("VDW inner Cutoff: %4.1lf A\n", VdwInnerCutoff);
printf("Elec.static Cutoff: %4.1lf A\n", Cutoff);
printf("Elec.static inner Cutoff: %4.1lf A\n", InnerCutoff);
printf("Switching: %s\n", ForceSwitch ? "Force switching" : (EnergySwitch ? "Potential switch" : "none"));
if(VdwCor)
{
printf("VDW correction yes\n");
printf(" +- density %9.6lf N/A^3\n",VdwCorDensity);
printf(" +- epsilon %7.3lf kcal/mol\n",VdwCorEpsilon);
printf(" +- radius %4.2lf A\n",VdwCorRadius);
printf(" `- Cutoff %4.2lf A\n",VdwCorCutoff);
}
printf("UsePartialRecalc: %s\n", UsePartialRecalc ? "Yes" : "No");
printf("IgnoreIntraResidue: %s\n", IgnoreIntraResidue ? "Yes" : "No");
}
void FF_NonBonded::settodefault()
{
DoVdw = true;
DoElec = true;
Cutoff = 15;
InnerCutoff = 12;
VdwCutoff = Cutoff;
VdwInnerCutoff = InnerCutoff;
VdwAttenuator = 1.0;
ElecAttenuator = 1.0;
AutoScaling14 = true;
Vdw14Scaling = 1.0;
Elec14Scaling = 1.0;
Dielectric = 1.0;
DDDielectric = false;
DDDielectricAlpha = 1.0;
ForceSwitch=true;
EnergySwitch=false;
// longrange vdw correction
VdwCor = false;
VdwCorDensity = 0.0;
VdwCorEpsilon = 0.0;
VdwCorRadius = 0.0;
VdwCorCutoff = 0.0;
fullrecalc = true;
UsePartialRecalc = false;
IgnoreIntraResidue = false;
fast = 0;
}
// The setup function sets up some general stuff before runtime
void FF_NonBonded::setup()
{
// Proxies
WorkSpace& wspace = getWSpace();
Active = true;
wspace.nlist().requestCutoff(Maths::max(Cutoff,VdwCutoff));
if(AutoScaling14)
{
Vdw14Scaling = wspace.ffps().Vdw14Scaling;
Elec14Scaling = wspace.ffps().Elec14Scaling;
}
// setting up atom energy array
fullrecalc = true; // next calculation must be a full one
// load local parameters (for faster access)
local_atomparam = new NonBonded_Pack[wspace.nAtoms()];
for(int i = 0; i < wspace.nAtoms(); i ++)
{
local_atomparam[i].epsilon = wspace.atom[i].epsilon;
local_atomparam[i].radius = wspace.atom[i].radius;
local_atomparam[i].charge = wspace.atom[i].charge;
}
setupBasisVectors();
}
void FF_NonBonded::setupBasisVectors(){
// periodic space make local basisvector table
WorkSpace& wspace = getWSpace();
Space *space = &wspace.boundary();
int nbasisvecs = space->nBasisVectors();
if( nbasisvecs > 32 )
{
throw(ProcedureException(
"FF_NonBonded: Cannot use more than 32 periodic boundary image vectors ("
+ int2str(nbasisvecs) + " basis vectors). \nThis may be because you have chosen " +
"a non-bonded cutoff which is greater than half the periodic box width.\n"
"Your settings are: Cutoff=" + double2str(Cutoff) + "\n"+
" Half Smallest Box width=" + double2str(space->getSmallestChord()/2.0) + "\n"
"Such a setup is not supported by this forcefield. \n"));
}
for(int b=0;b<nbasisvecs;b++)
{
basisvector[b] = space->getBasisVector(b);
}
}
// Include all variables who's change should trigger a resetup
unsigned long FF_NonBonded::calcCheckSum()
{
unsigned long sum = ForcefieldBase::calcCheckSum();
sum += (unsigned long)( Cutoff*VdwCutoff*100000.0 ) +
1354231*(int)AutoScaling14;;
return sum;
}
void FF_NonBonded::infoLine() const
{
// prints a line of current energies
const WorkSpace& wspace = getWSpace();
const Hamiltonian *printene = &wspace.ene;
printf("% 8.1lf% 8.1lf",
double(printene->epot_vdw) * PhysicsConst::J2kcal * PhysicsConst::Na,
double(printene->epot_elec) * PhysicsConst::J2kcal * PhysicsConst::Na);
}
void FF_NonBonded::infoLineHeader() const
{
// prints the headers for the above function
printf("%8s%8s", "EVdw", "Ecoul");
}
void FF_NonBonded::calcEnergiesVerbose(ForcefieldBase::AtomicVerbosity level)
{
WorkSpace& wspace = getWSpace();
if(level == Summary)
{
calcForces();
printf(" VdW: %10.3lf kcal/mol\n", double(wspace.ene.epot_vdw) * PhysicsConst::J2kcal * PhysicsConst::Na);
printf(" Electrostatic: %10.3lf kcal/mol\n", double(wspace.ene.epot_elec) * PhysicsConst::J2kcal * PhysicsConst::Na);
// // DEBUG STUFF TO TEST VIRIAL
// wspace.ene.InternalVirial = 0;
// calcForces();
// double ene0 = wspace.ene.epot_elec + wspace.ene.epot_vdw;
// printf("Ene: %e Virial: %e\n", ene0, wspace.ene.InternalVirial );
// ClosedSpace *cs = dynamic_cast<ClosedSpace *> (&wspace.boundary());
// double v1 = cs->volume();
// double dV = 1.0000001;
// wspace.scaleSystem(dV);
// wspace.ene.InternalVirial = 0;
// calcForces();
// double ene1 = wspace.ene.epot_elec + wspace.ene.epot_vdw;
//
// printf("Ene: %e Virial: %e V1 %e\n", ene1, wspace.ene.InternalVirial, v1 );
// printf("dEnedV = %e %e \n ", (ene1 - ene0)/(v1*dV- v1), wspace.ene.InternalVirial / (3.0 * v1));
// printf("dEne = %e \n", ene1 - ene0 );
// printf("V1 V2 dV : %e %e %e \n",v1,cs->volume(), (v1*dV- v1) );
// //wspace.
return;
}
verbose_level = level;
setupBasisVectors();
int T_SqrtMode = T_SqrtFPU;
int T_VdwMode = T_VdwMode_EnergySwitch;
int T_ElecMode = T_ElecMode_Normal;
int T_VerboseMode = T_VerboseMode_True;
if(EnergySwitch)T_ElecMode = T_ElecMode_EnergySwitch;
if(ForceSwitch) T_ElecMode = T_ElecMode_ForceSwitch;
if(!DoElec)T_ElecMode = T_ElecMode_None;
if(!DoVdw)T_VdwMode = T_VdwMode_None;
tcall4<FF_NonBonded_CalcForces_T_fast2_wrap>
(T_SqrtMode, T_VdwMode, T_ElecMode, T_VerboseMode)
( *this,local_atomparam, &basisvector[0], wspace, level );
epot_elec = wspace.ene.epot_elec;
epot_vdw = wspace.ene.epot_vdw;
};
void FF_NonBonded::calcEnergies(){
setupBasisVectors();
// force a full recalculation of the energy if the neighbor list has been updated
unsigned currentCount = getWSpace().nlist().getFullUpdateCount();
if ( currentCount != m_Nlist_FullUpdateCount){
fullrecalc = true;
m_Nlist_FullUpdateCount = currentCount; // remember latest count for next time
}
if( (!fullrecalc) && (UsePartialRecalc) ){
//getWSpace().old = getWSpace().cur;
//calcEnergies_T<false>();
calcEnergies_Update();
//printf("A-Partial: %f \n", epot * PhysicsConst::J2kcal * PhysicsConst::Na );
//double epot_s = epot;
//calcEnergies_T<false>();
//printf("Echeck: %f \n", (epot - epot_s) * PhysicsConst::J2kcal * PhysicsConst::Na );
// save the coordinates for the fast energy evaluation to work next time
getWSpace().old = getWSpace().cur;
}else{
calcEnergies_Full();
// save the coordinates for the fast energy evaluation to work next time
getWSpace().old = getWSpace().cur;
fullrecalc = false; // full recalc not needed anymore
}
};
void FF_NonBonded::calcEnergies_Full(){
WorkSpace& wspace = getWSpace();
int T_SqrtMode = T_SqrtFPU;
int T_VdwMode = T_VdwMode_EnergySwitch;
int T_ElecMode = T_ElecMode_Normal;
int T_VerboseMode = T_VerboseMode_False;
if(EnergySwitch)T_ElecMode = T_ElecMode_EnergySwitch;
if(ForceSwitch) T_ElecMode = T_ElecMode_ForceSwitch;
if(!DoElec)T_ElecMode = T_ElecMode_None;
if(!DoVdw)T_VdwMode = T_VdwMode_None;
tcall4<FF_NonBonded_CalcForces_T_fast2_wrap>
(T_SqrtMode, T_VdwMode, T_ElecMode, 0)
( *this,local_atomparam, &basisvector[0], wspace, Forcefield::Summary );
epot_elec = wspace.ene.epot_elec;
epot_vdw = wspace.ene.epot_vdw;
};
void FF_NonBonded::calcEnergies_Update(){
WorkSpace& wspace = getWSpace();
if( dynamic_cast<const PeriodicBox*>(&wspace.boundary() ) != NULL ){
FF_NonBonded_CalcEnergies_Update_T<PeriodicBox, false> ( *this, wspace, changed_atom, old_changed_atom, epot_reference );
} else
if( dynamic_cast<const InfiniteSpace*>(&wspace.boundary() ) != NULL ){
FF_NonBonded_CalcEnergies_Update_T<InfiniteSpace, false> ( *this, wspace, changed_atom, old_changed_atom, epot_reference );
} else {
FF_NonBonded_CalcEnergies_Update_T<int , false> ( *this, wspace, changed_atom, old_changed_atom, epot_reference );
}
epot_elec = wspace.ene.epot_elec;
epot_vdw = wspace.ene.epot_vdw;
};
void FF_NonBonded::calcForces()
{
setupBasisVectors();
WorkSpace& wspace = getWSpace();
int T_SqrtMode = T_SqrtFPU;
int T_VdwMode = T_VdwMode_EnergySwitch;
int T_ElecMode = T_ElecMode_Normal;
int T_VerboseMode = T_VerboseMode_False;
if(EnergySwitch)T_ElecMode = T_ElecMode_EnergySwitch;
if(ForceSwitch) T_ElecMode = T_ElecMode_ForceSwitch;
if(!DoElec)T_ElecMode = T_ElecMode_None;
if(!DoVdw)T_VdwMode = T_VdwMode_None;
tcall4<FF_NonBonded_CalcForces_T_fast2_wrap>
(T_SqrtMode, T_VdwMode, T_ElecMode, 0)
( *this,local_atomparam, &basisvector[0], wspace, Forcefield::Summary );
epot_elec = wspace.ene.epot_elec;
epot_vdw = wspace.ene.epot_vdw;
};
}
| 32.069579 | 165 | 0.642969 | JonnyWideFoot |
518940db55e3f8d50991d492c919d4788c784703 | 2,186 | hpp | C++ | modules/core/linalg/include/nt2/linalg/functions/gallery/frank.hpp | pbrunet/nt2 | 2aeca0f6a315725b335efd5d9dc95d72e10a7fb7 | [
"BSL-1.0"
] | null | null | null | modules/core/linalg/include/nt2/linalg/functions/gallery/frank.hpp | pbrunet/nt2 | 2aeca0f6a315725b335efd5d9dc95d72e10a7fb7 | [
"BSL-1.0"
] | null | null | null | modules/core/linalg/include/nt2/linalg/functions/gallery/frank.hpp | pbrunet/nt2 | 2aeca0f6a315725b335efd5d9dc95d72e10a7fb7 | [
"BSL-1.0"
] | null | null | null | //==============================================================================
// Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_LINALG_FUNCTIONS_GALLERY_FRANK_HPP_INCLUDED
#define NT2_LINALG_FUNCTIONS_GALLERY_FRANK_HPP_INCLUDED
#include <nt2/linalg/functions/frank.hpp>
#include <nt2/include/functions/minij.hpp>
#include <nt2/include/functions/triu.hpp>
#include <nt2/include/functions/fliplr.hpp>
#include <nt2/include/functions/flipud.hpp>
#include <nt2/include/functions/transpose.hpp>
namespace nt2 {namespace ext
{
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::frank1_, tag::cpu_,
(A0)(T),
(scalar_<integer_<A0> >)
(target_<scalar_<unspecified_<T> > >)
)
{
typedef typename meta::call<tag::minij_(A0 const&, T)>::type T1;
typedef typename meta::call<tag::offset_triu_(T1, ptrdiff_t)>::type result_type;
BOOST_FORCEINLINE result_type operator()(A0 const& n,T const &)
{
return triu(minij(n,T()), ptrdiff_t(-1));
}
};
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::frank0_, tag::cpu_,
(A0)(T),
(scalar_<integer_<A0> >)
(target_<scalar_<unspecified_<T> > >)
)
{
typedef typename meta::call<tag::frank1_(A0 const&,T)>::type T1;
typedef typename meta::call<tag::fliplr_(T1)>::type T2;
typedef typename meta::call<tag::flipud_(T2)>::type T3;
typedef typename meta::call<tag::transpose_(T3)>::type result_type;
BOOST_FORCEINLINE result_type operator()(A0 const& n, T const &)
{
return nt2::trans(nt2::flipud(nt2::fliplr(nt2::frank1(n, T()))));
}
};
} }
#endif
| 39.745455 | 86 | 0.548033 | pbrunet |
518958fd446c4f34d0736d90e32e6f3cf68a2a65 | 5,515 | cpp | C++ | src/Runtime/RtMemRef.cpp | gperrotta/onnx-mlir | 75930ffbcf14cfbaccd8417c47c3598f56342926 | [
"Apache-2.0"
] | null | null | null | src/Runtime/RtMemRef.cpp | gperrotta/onnx-mlir | 75930ffbcf14cfbaccd8417c47c3598f56342926 | [
"Apache-2.0"
] | null | null | null | src/Runtime/RtMemRef.cpp | gperrotta/onnx-mlir | 75930ffbcf14cfbaccd8417c47c3598f56342926 | [
"Apache-2.0"
] | null | null | null | //===----------- RtMemRef.cpp - Dynamic MemRef Implementation ------------===//
//
// Copyright 2019-2020 The IBM Research Authors.
//
// =============================================================================
//
// This file contains implementations of Dynamic MemRef data structures and
// helper functions.
//
//===----------------------------------------------------------------------===//
#include <cassert>
#include <map>
#include <string>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "RtMemRef.h"
namespace {
// Helper function to compute cartisian product.
inline std::vector<std::vector<INDEX_TYPE>> CartProduct(
const std::vector<std::vector<INDEX_TYPE>> &v) {
std::vector<std::vector<INDEX_TYPE>> s = {{}};
for (const auto &u : v) {
std::vector<std::vector<INDEX_TYPE>> r;
for (const auto &x : s) {
for (const auto y : u) {
r.push_back(x);
r.back().push_back(y);
}
}
s = move(r);
}
return s;
}
} // namespace
RtMemRef::RtMemRef(int _rank) {
rank = _rank;
sizes = (INDEX_TYPE *)malloc(rank * sizeof(INDEX_TYPE));
strides = (int64_t *)malloc(rank * sizeof(int64_t));
}
INDEX_TYPE RtMemRef::size() const {
return std::accumulate(sizes, sizes + rank, 1, std::multiplies<>());
}
std::vector<std::vector<INDEX_TYPE>> RtMemRef::indexSet() const {
// First, we create index set of each dimension separately.
// i.e., for a tensor/RMR of shape (2, 3), its dimWiseIdxSet will be:
// {{0,1}, {0,1,2}};
std::vector<std::vector<INDEX_TYPE>> dimWiseIdxSet;
for (auto dimSize : std::vector<INDEX_TYPE>(sizes, sizes + rank)) {
std::vector<INDEX_TYPE> dimIdxSet(dimSize);
std::iota(std::begin(dimIdxSet), std::end(dimIdxSet), 0);
dimWiseIdxSet.emplace_back(dimIdxSet);
}
// Then, the cartesian product of vectors within dimWiseIdxSet will be the
// index set for the whole RMR.
return CartProduct(dimWiseIdxSet);
}
INDEX_TYPE RtMemRef::computeOffset(std::vector<INDEX_TYPE> &idxs) const {
auto dimStrides = std::vector<INDEX_TYPE>(strides, strides + rank);
INDEX_TYPE elemOffset = std::inner_product(
idxs.begin(), idxs.end(), dimStrides.begin(), (INDEX_TYPE)0);
return elemOffset;
}
std::vector<int64_t> RtMemRef::computeStridesFromSizes() const {
// Shift dimension sizes one to the left, fill in the vacated rightmost
// element with 1; this gets us a vector that'll be more useful for computing
// strides of memory access along each dimension using prefix product (aka
// partial_sum with a multiply operator below). The intuition is that the size
// of the leading dimension does not matter when computing strides.
std::vector<int64_t> sizesVec(sizes + 1, sizes + rank);
sizesVec.push_back(1);
std::vector<int64_t> dimStrides(rank);
std::partial_sum(sizesVec.rbegin(), sizesVec.rend(), dimStrides.rbegin(),
std::multiplies<>());
return dimStrides;
}
RtMemRef::~RtMemRef() {
free(data);
free(sizes);
free(strides);
}
// An ordered dynamic MemRef dictionary.
// The goal is to support accessing dynamic memory ref by name and by index.
// Currently, only accessing by index is supported.
struct OrderedRtMemRefDict {
std::map<std::string, RtMemRef *> tensorDict;
std::vector<std::string> orderedNames;
};
int numRtMemRefs(OrderedRtMemRefDict *dict) {
return dict->orderedNames.size();
}
OrderedRtMemRefDict *createOrderedRtMemRefDict() {
return new OrderedRtMemRefDict();
}
RtMemRef *createRtMemRef(int rank) { return new RtMemRef(rank); }
RtMemRef *getRtMemRef(OrderedRtMemRefDict *tensorDict, int idx) {
return tensorDict->tensorDict[tensorDict->orderedNames[idx]];
}
void setRtMemRef(OrderedRtMemRefDict *tensorDict, int idx, RtMemRef *tensor) {
if (tensorDict->orderedNames.size() <= idx)
tensorDict->orderedNames.resize(idx + 1);
// The dynamic memref is essentially anonymous, since we are storing it by
// indexed position.
// TODO: can use random string as names to reduce chance of collision.
auto unique_name = std::to_string(idx);
assert(tensorDict->tensorDict.count(unique_name) == 0 &&
"duplicate dynamic mem ref name");
tensorDict->orderedNames[idx] = unique_name;
tensorDict->tensorDict[tensorDict->orderedNames[idx]] = tensor;
}
void *getData(RtMemRef *dynMemRef) { return dynMemRef->data; }
void setData(RtMemRef *dynMemRef, void *dataPtr) { dynMemRef->data = dataPtr; }
void *getAlignedData(RtMemRef *dynMemRef) { return dynMemRef->alignedData; }
void setAlignedData(RtMemRef *dynMemRef, void *dataPtr) {
dynMemRef->alignedData = dataPtr;
}
INDEX_TYPE *getSizes(RtMemRef *dynMemRef) { return dynMemRef->sizes; }
void setSizes(RtMemRef *dynMemRef, INDEX_TYPE *sizes) {
for (int i = 0; i < dynMemRef->rank; i++)
dynMemRef->sizes[i] = sizes[i];
}
int64_t *getStrides(RtMemRef *dynMemRef) { return dynMemRef->strides; }
int64_t getSize(OrderedRtMemRefDict *dict) { return dict->orderedNames.size(); }
INDEX_TYPE getDataSize(RtMemRef *rtMemRef) {
INDEX_TYPE n = rtMemRef->sizes[0];
for (int i = 1; i < rtMemRef->rank; i++)
n *= rtMemRef->sizes[i];
return n;
}
void setDType(RtMemRef *dynMemRef, int onnxType) {
dynMemRef->onnx_dtype = onnxType;
}
int getDType(RtMemRef *dynMemRef) { return dynMemRef->onnx_dtype; }
unsigned int getRank(RtMemRef *dynMemRef) { return dynMemRef->rank; }
void setStrides(RtMemRef *dynMemRef, int64_t *strides) {
for (int i = 0; i < dynMemRef->rank; i++)
dynMemRef->strides[i] = strides[i];
}
| 32.063953 | 80 | 0.682684 | gperrotta |
51932d9be7ec94d4790ed9eeb406972a1f6acc2e | 462 | hpp | C++ | src/modules/socket/server/allocator.hpp | saurabh-dua/openperf | 43fb850725a0afc563a5d75c3395d3de46c3129a | [
"Apache-2.0"
] | null | null | null | src/modules/socket/server/allocator.hpp | saurabh-dua/openperf | 43fb850725a0afc563a5d75c3395d3de46c3129a | [
"Apache-2.0"
] | null | null | null | src/modules/socket/server/allocator.hpp | saurabh-dua/openperf | 43fb850725a0afc563a5d75c3395d3de46c3129a | [
"Apache-2.0"
] | null | null | null | #ifndef _OP_SOCKET_SERVER_ALLOCATOR_HPP_
#define _OP_SOCKET_SERVER_ALLOCATOR_HPP_
#include "memory/std_allocator.hpp"
#include "memory/allocator/free_list.hpp"
namespace openperf {
namespace socket {
namespace server {
typedef openperf::memory::std_allocator<uint8_t,
openperf::memory::allocator::free_list>
allocator;
}
} // namespace socket
} // namespace openperf
#endif /* _OP_SOCKET_SERVER_ALLOCATOR_HPP_ */
| 23.1 | 79 | 0.729437 | saurabh-dua |
5196b437b54d2d77be1f81d5f74bf370d5cabb38 | 7,547 | cxx | C++ | osprey/be/cg/cg_swp_allocator_test.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | osprey/be/cg/cg_swp_allocator_test.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | osprey/be/cg/cg_swp_allocator_test.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | /*
Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved.
This program is free software; you can redistribute it and/or modify it
under the terms of version 2 of the GNU General Public License as
published by the Free Software Foundation.
This program is distributed in the hope that it would be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Further, this software is distributed without any warranty that it is
free of the rightful claim of any third person regarding infringement
or the like. Any license provided herein, whether implied or
otherwise, applies only to this software file. Patent licenses, if
any, provided herein do not apply to combinations of this program with
other software, or any other product whatsoever.
You should have received a copy of the GNU General Public License along
with this program; if not, write the Free Software Foundation, Inc., 59
Temple Place - Suite 330, Boston MA 02111-1307, USA.
Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky,
Mountain View, CA 94043, or:
http://www.sgi.com
For further information regarding this notice, see:
http://oss.sgi.com/projects/GenInfo/NoticeExplan
*/
//-*-c++-*-
// =======================================================================
// =======================================================================
//
// Module: cg_swp_allocator_test.cxx
// $Revision: 1.2 $
// $Date: 02/11/07 23:41:21-00:00 $
// $Author: fchow@keyresearch.com $
// $Source: /scratch/mee/2.4-65/kpro64-pending/be/cg/SCCS/s.cg_swp_allocator_test.cxx $
//
// Revision comments:
//
// 01-May-1999 - Initial version
//
// Description:
// ------------
// Build the tester as follows to produce an a.out file.
//
// $TOOLROOT/usr/bin/CC -g -DSTANDALONE_SWP_ALLOCATOR
// -I../../common/util -I../../common/com -I../../common/stl
// cg_swp_allocator.cxx cg_swp_allocator_test.cxx
//
// The tester provides a simple command-line interface to enter
// lifetimes and test the register allocatator for correctness and
// optimality. It outputs time vs register plots of the resultant
// allocation, and indicates illegal allocations by the '*' character
// in the plot (i.e. for overlapping register usages).
//
// An example, taken from Rau's paper, is built into this
// implementation, and an interesting supplement to his example
// can be created by appending the following lifetimes:
//
// 10 15 2 3
// 20 27 1 0
// 30 35 0 2
// 10 20 2 2
// 1 2 0 0
//
// where using a sort based only on start-time does better than the
// adjacency sort. Appending
//
// 6 8 0 0
//
// will cause adjacency sort to do better.
//
// ====================================================================
// ====================================================================
#include <stdio.h>
#include <vector>
#include "defs.h"
#include "cg_swp_allocator.h"
static const char *
Read_Line()
{
static char line[512];
if (gets(line) == NULL)
line[0] = '\0';
return line;
}
static INT32
Get_A_Number()
{
INT32 num, status = 0;
while (status != 1)
{
status = sscanf(Read_Line(), "%d", &num);
if (status != 1)
printf("\n<Try again! Enter a single integer> ");
}
return num;
} // Get_A_Number
static INT32
Get_Bounded_Number(INT32 min, INT32 max)
{
INT32 num = Get_A_Number();
while (num > max || num < min)
{
printf("\nInvalid option! Enter a digit between %d and %d>", min, max);
num = Get_A_Number();
}
return num;
}
static void
Get_A_Lifetime(SWP_LIFETIME <)
{
INT32 from_tunit, to_tunit, omega, alpha, status = 0;
printf("\n<Enter lifetime (start_cycle end_cycle omega alpha)> ");
while (status != 4)
{
status = sscanf(Read_Line(), "%d %d %d %d",
&from_tunit, &to_tunit, &omega, &alpha);
if (status != 4)
printf("\n<Try again! Enter 4 space separated integers> ");
}
lt = SWP_LIFETIME(from_tunit, to_tunit, omega, alpha);
} // Get_A_Lifetime
static void
Get_Lifetimes(std::vector<SWP_LIFETIME> <v)
{
INT32 number_of_values = -1;
SWP_LIFETIME lt;
printf("\n<How many lifetimes do you wish to enter> ");
number_of_values = Get_Bounded_Number(0, 100);
for (INT32 i = 0; i < number_of_values; i++)
{
Get_A_Lifetime(lt);
ltv.push_back(lt);
} // for each value
} // Get_Lifetimes
void main()
{
BOOL more = TRUE;
INT32 option;
std::vector<SWP_LIFETIME> ltv;
INT32 ii = 2, sc = 10, num_regs = 64, num_its = 15, num_cols = 70;
while (more)
{
printf("\n----------- Testing swp allocator -----------");
printf("\n");
printf("\n 0) Exit");
printf("\n 1) Set ii (default %d)", ii);
printf("\n 2) Set sc (default %d)", sc);
printf("\n 3) Set max registers (default %d)", num_regs);
printf("\n 4) Set number of iterations to plot (default %d)", num_its);
printf("\n 5) Set column-width of plot (default %d)", num_cols);
printf("\n 6) Enter new set of lifetimes");
printf("\n 7) Append to existing set of lifetimes");
printf("\n 8) Allocate and trace with adjacency ordering");
printf("\n 9) Allocate and trace without adjacency ordering");
printf("\n 10) Example from Rau's paper (page 287)");
printf("\n");
printf("\nNOTES on plot:\n");
printf("\n \">\" indicates live value carried in/out of loop");
printf("\n \"*\" indicates overlapped lifetimes (i.e. an error)");
printf("\n");
printf("\n<Enter an option (0-10)> ");
option = Get_Bounded_Number(0, 10);
switch (option)
{
case 0: // Exit
more = FALSE;
break;
case 1: // Set ii
printf("\nEnter ii (1..1000)> ");
ii = Get_Bounded_Number(1, 1000);
break;
case 2: // Set sc
printf("\nEnter sc (1..1000)> ");
sc = Get_Bounded_Number(1, 1000);
break;
case 3: // Set max registers
printf("\nEnter number of registers (1..256)> ");
num_regs = Get_Bounded_Number(1, 256);
break;
case 4: // Set number of iterations to plot
printf("\nEnter number of iteration (1..256)> ");
num_its = Get_Bounded_Number(1, 256);
break;
case 5: // Set column-width of plot
printf("\nEnter number of columns (1..256)> ");
num_cols = Get_Bounded_Number(1, 256);
break;
case 6: // Enter new set of lifetimes
ltv.clear();
Get_Lifetimes(ltv);
break;
case 7: // Add to existing set of lifetimes
Get_Lifetimes(ltv);
break;
case 8: // Allocate and trace
{
SWP_ALLOCATOR reg_alloc(ii, sc, num_regs, ltv.begin(), ltv.end(),
Malloc_Mem_Pool, TRUE);
reg_alloc.print(stdout, num_its, num_cols);
break;
}
case 9: // Allocate and trace without adjacency ordering
{
SWP_ALLOCATOR reg_alloc(ii, sc, num_regs, ltv.begin(), ltv.end(),
Malloc_Mem_Pool, FALSE);
reg_alloc.print(stdout, num_its, num_cols);
break;
}
case 10: // Rau's example
{
ii = 2;
sc = 10;
num_regs = 64;
ltv.clear();
ltv.push_back(SWP_LIFETIME(13,17,1,1));
ltv.push_back(SWP_LIFETIME(18,21,0,0));
ltv.push_back(SWP_LIFETIME(15,20,0,0));
ltv.push_back(SWP_LIFETIME(0,20,0,0));
ltv.push_back(SWP_LIFETIME(0,23,1,0));
SWP_ALLOCATOR reg_alloc(ii, sc, num_regs, ltv.begin(), ltv.end());
reg_alloc.print(stdout, num_its, num_cols);
break;
}
} // switch on option
} // while more
} // main
| 29.365759 | 88 | 0.619054 | sharugupta |
519b9b08b03e4191c5ccd8beffeee258cecd83ca | 5,338 | hxx | C++ | OCC/inc/XSControl_TransferWriter.hxx | cy15196/FastCAE | 0870752ec2e590f3ea6479e909ebf6c345ac2523 | [
"BSD-3-Clause"
] | 117 | 2020-03-07T12:07:05.000Z | 2022-03-27T07:35:22.000Z | opencascade/XSControl_TransferWriter.hxx | CadQuery/cpp-py-bindgen | 66e7376d3a27444393fc99acbdbef40bbc7031ae | [
"Apache-2.0"
] | 33 | 2019-11-13T18:09:51.000Z | 2021-11-26T17:24:12.000Z | opencascade/XSControl_TransferWriter.hxx | CadQuery/cpp-py-bindgen | 66e7376d3a27444393fc99acbdbef40bbc7031ae | [
"Apache-2.0"
] | 76 | 2020-03-16T01:47:46.000Z | 2022-03-21T16:37:07.000Z | // Created on: 1996-03-13
// Created by: Christian CAILLET
// Copyright (c) 1996-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _XSControl_TransferWriter_HeaderFile
#define _XSControl_TransferWriter_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <Standard_Transient.hxx>
#include <IFSelect_ReturnStatus.hxx>
#include <Transfer_FinderProcess.hxx>
class XSControl_Controller;
class Standard_Transient;
class Interface_InterfaceModel;
class TopoDS_Shape;
class Interface_CheckIterator;
class XSControl_TransferWriter;
DEFINE_STANDARD_HANDLE(XSControl_TransferWriter, Standard_Transient)
//! TransferWriter gives help to control transfer to write a file
//! after having converted data from Cascade/Imagine
//!
//! It works with a Controller (which itself can work with an
//! Actor to Write) and a FinderProcess. It records results and
//! checks
class XSControl_TransferWriter : public Standard_Transient
{
public:
//! Creates a TransferWriter, empty, ready to run
//! with an empty FinderProcess (but no controller, etc)
XSControl_TransferWriter()
: myTransferWriter(new Transfer_FinderProcess),
myTransferMode(0)
{}
//! Returns the FinderProcess itself
const Handle(Transfer_FinderProcess) & FinderProcess() const
{ return myTransferWriter; }
//! Sets a new FinderProcess and forgets the former one
void SetFinderProcess (const Handle(Transfer_FinderProcess)& theFP)
{ myTransferWriter = theFP; }
//! Returns the currently used Controller
const Handle(XSControl_Controller) & Controller() const
{ return myController; }
//! Sets a new Controller, also sets a new FinderProcess
void SetController (const Handle(XSControl_Controller)& theCtl)
{
myController = theCtl;
Clear(-1);
}
//! Clears recorded data according a mode
//! 0 clears FinderProcess (results, checks)
//! -1 create a new FinderProcess
Standard_EXPORT void Clear (const Standard_Integer theMode);
//! Returns the current Transfer Mode (an Integer)
//! It will be interpreted by the Controller to run Transfers
//! This call form could be later replaced by more specific ones
//! (parameters suited for each norm / transfer case)
Standard_Integer TransferMode() const
{ return myTransferMode; }
//! Changes the Transfer Mode
void SetTransferMode (const Standard_Integer theMode)
{ myTransferMode = theMode; }
//! Prints statistics on current Trace File, according what,mode
//! See PrintStatsProcess for details
Standard_EXPORT void PrintStats (const Standard_Integer theWhat, const Standard_Integer theMode = 0) const;
//! Tells if a transient object (from an application) is a valid
//! candidate for a transfer to a model
//! Asks the Controller (RecognizeWriteTransient)
//! If <obj> is a HShape, calls RecognizeShape
Standard_EXPORT Standard_Boolean RecognizeTransient (const Handle(Standard_Transient)& theObj);
//! Transfers a Transient object (from an application) to a model
//! of current norm, according to the last call to SetTransferMode
//! Works by calling the Controller
//! Returns status : =0 if OK, >0 if error during transfer, <0 if
//! transfer badly initialised
Standard_EXPORT IFSelect_ReturnStatus TransferWriteTransient (const Handle(Interface_InterfaceModel)& theModel, const Handle(Standard_Transient)& theObj);
//! Tells if a Shape is valid for a transfer to a model
//! Asks the Controller (RecognizeWriteShape)
Standard_EXPORT Standard_Boolean RecognizeShape (const TopoDS_Shape& theShape);
//! Transfers a Shape from CasCade to a model of current norm,
//! according to the last call to SetTransferMode
//! Works by calling the Controller
//! Returns status : =0 if OK, >0 if error during transfer, <0 if
//! transfer badly initialised
Standard_EXPORT IFSelect_ReturnStatus TransferWriteShape (const Handle(Interface_InterfaceModel)& theModel, const TopoDS_Shape& theShape);
//! Returns the check-list of last transfer (write), i.e. the
//! check-list currently recorded in the FinderProcess
Standard_EXPORT Interface_CheckIterator CheckList() const;
//! Returns the check-list of last transfer (write), but tries
//! to bind to each check, the resulting entity in the model
//! instead of keeping the original Mapper, whenever known
Standard_EXPORT Interface_CheckIterator ResultCheckList (const Handle(Interface_InterfaceModel)& theModel) const;
DEFINE_STANDARD_RTTIEXT(XSControl_TransferWriter,Standard_Transient)
private:
Handle(XSControl_Controller) myController;
Handle(Transfer_FinderProcess) myTransferWriter;
Standard_Integer myTransferMode;
};
#endif // _XSControl_TransferWriter_HeaderFile
| 39.540741 | 156 | 0.769389 | cy15196 |
519c6b3abe3e2cd2428dde8de641453fe9b49c0d | 11,793 | cpp | C++ | qactionmanager/keyconfigdialog.cpp | SAT1226/XManga | d69f4c31838ffa99efde0bd10f5ca1c5f818eb80 | [
"MIT"
] | 1 | 2022-03-19T11:52:44.000Z | 2022-03-19T11:52:44.000Z | qactionmanager/keyconfigdialog.cpp | SAT1226/XManga | d69f4c31838ffa99efde0bd10f5ca1c5f818eb80 | [
"MIT"
] | null | null | null | qactionmanager/keyconfigdialog.cpp | SAT1226/XManga | d69f4c31838ffa99efde0bd10f5ca1c5f818eb80 | [
"MIT"
] | null | null | null | #include <QtWidgets>
#include "keyconfigdialog.h"
#include "shortcutbutton.h"
#include "ui_keyconfigdialog.h"
static int translateModifiers(Qt::KeyboardModifiers state,
const QString &text)
{
int result = 0;
// The shift modifier only counts when it is not used to type a symbol
// that is only reachable using the shift key anyway
if ((state & Qt::ShiftModifier) && (text.size() == 0
|| !text.at(0).isPrint()
|| text.at(0).isLetterOrNumber()
|| text.at(0).isSpace()))
result |= Qt::SHIFT;
if (state & Qt::ControlModifier)
result |= Qt::CTRL;
if (state & Qt::MetaModifier)
result |= Qt::META;
if (state & Qt::AltModifier)
result |= Qt::ALT;
if (state & Qt::KeypadModifier)
result |= Qt::KeypadModifier;
return result;
}
static QString keySequenceToEditString(const QKeySequence &sequence)
{
QString text = sequence.toString(QKeySequence::PortableText);
// if (Utils::HostOsInfo::isMacHost()) {
// // adapt the modifier names
// text.replace(QLatin1String("Ctrl"), QLatin1String("Cmd"), Qt::CaseInsensitive);
// text.replace(QLatin1String("Alt"), QLatin1String("Opt"), Qt::CaseInsensitive);
// text.replace(QLatin1String("Meta"), QLatin1String("Ctrl"), Qt::CaseInsensitive);
// }
return text;
}
static QKeySequence keySequenceFromEditString(const QString &editString)
{
QString text = editString;
// if (Utils::HostOsInfo::isMacHost()) {
// // adapt the modifier names
// text.replace(QLatin1String("Opt"), QLatin1String("Alt"), Qt::CaseInsensitive);
// text.replace(QLatin1String("Ctrl"), QLatin1String("Meta"), Qt::CaseInsensitive);
// text.replace(QLatin1String("Cmd"), QLatin1String("Ctrl"), Qt::CaseInsensitive);
// }
return QKeySequence::fromString(text, QKeySequence::PortableText);
}
static bool keySequenceIsValid(const QKeySequence &sequence)
{
if (sequence.isEmpty())
return true;
for (int i = 0; i < sequence.count(); ++i) {
if (sequence[i] == Qt::Key_unknown)
return false;
}
return true;
}
ShortcutButton::ShortcutButton(QWidget *parent)
: QPushButton(parent)
, m_key({{0, 0, 0, 0}})
{
// Using ShortcutButton::tr() as workaround for QTBUG-34128
setToolTip(ShortcutButton::tr("Click and enter a new shortcut key.", "Gray text to be displayed on LineEdit to input the shortcut key"));
setCheckable(true);
m_checkedText = ShortcutButton::tr("Stop Recording", "Button for canceling shortcut key input");
m_uncheckedText = ShortcutButton::tr("Record", "Button for starting entering the shortcut key");
updateText();
connect(this, &ShortcutButton::toggled, this, &ShortcutButton::handleToggleChange);
}
QSize ShortcutButton::sizeHint() const
{
if (m_preferredWidth < 0) { // initialize size hint
const QString originalText = text();
ShortcutButton *that = const_cast<ShortcutButton *>(this);
that->setText(m_checkedText);
m_preferredWidth = QPushButton::sizeHint().width();
that->setText(m_uncheckedText);
int otherWidth = QPushButton::sizeHint().width();
if (otherWidth > m_preferredWidth)
m_preferredWidth = otherWidth;
that->setText(originalText);
}
return QSize(m_preferredWidth, QPushButton::sizeHint().height());
}
bool ShortcutButton::eventFilter(QObject *obj, QEvent *evt)
{
if (evt->type() == QEvent::ShortcutOverride) {
evt->accept();
return true;
}
if (evt->type() == QEvent::KeyRelease
|| evt->type() == QEvent::Shortcut
|| evt->type() == QEvent::Close/*Escape tries to close dialog*/) {
return true;
}
if (evt->type() == QEvent::MouseButtonPress && isChecked()) {
setChecked(false);
return true;
}
if (evt->type() == QEvent::KeyPress) {
QKeyEvent *k = static_cast<QKeyEvent*>(evt);
int nextKey = k->key();
if (m_keyNum > 3
|| nextKey == Qt::Key_Control
|| nextKey == Qt::Key_Shift
|| nextKey == Qt::Key_Meta
|| nextKey == Qt::Key_Alt) {
return false;
}
nextKey |= translateModifiers(k->modifiers(), k->text());
switch (m_keyNum) {
case 0:
m_key[0] = nextKey;
break;
case 1:
m_key[1] = nextKey;
break;
case 2:
m_key[2] = nextKey;
break;
case 3:
m_key[3] = nextKey;
break;
default:
break;
}
m_keyNum++;
k->accept();
emit keySequenceChanged(QKeySequence(m_key[0], m_key[1], m_key[2], m_key[3]));
if (m_keyNum > 3)
setChecked(false);
return true;
}
return QPushButton::eventFilter(obj, evt);
}
void ShortcutButton::updateText()
{
setText(isChecked() ? m_checkedText : m_uncheckedText);
}
void ShortcutButton::handleToggleChange(bool toogleState)
{
updateText();
m_keyNum = m_key[0] = m_key[1] = m_key[2] = m_key[3] = 0;
if (toogleState) {
if (qApp->focusWidget())
qApp->focusWidget()->clearFocus(); // funny things happen otherwise
qApp->installEventFilter(this);
} else {
qApp->removeEventFilter(this);
}
}
KeyConfigDialog::KeyConfigDialog(KeyConfigDialog::KeyActionManager &keyActions, QWidget *parent)
: QDialog(parent)
, ui(new Ui::KeyConfigDialog)
, m_keyActions(keyActions)
, m_keyCapturing(false)
, m_ignoreEdited(false)
{
ui->setupUi(this);
ui->frameMouseOptions->setVisible(false);
ui->addSequenceButton->setVisible(false);
connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
connect(ui->buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
connect(ui->buttonBox, SIGNAL(clicked(QAbstractButton*)), this, SLOT(onStandardButton_clicked(QAbstractButton*)));
connect(ui->treeWidget, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), this, SLOT(onTreeWidget_currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)));
connect(ui->resetButton, SIGNAL(clicked()), this, SLOT(onResetButton_clicked()));
connect(ui->shortcutEdit, SIGNAL(textChanged(QString)), this, SLOT(onShortcutEdit_textChanged(QString)));
connect(ui->recordButton, &ShortcutButton::keySequenceChanged,
this, &KeyConfigDialog::onRecordButton_keySequenceChanged);
ui->treeWidget->sortByColumn(0, Qt::AscendingOrder);
QTreeWidgetItem *header = ui->treeWidget->headerItem();
// header->setText(0, tr("Motions", "Title of the column of Action to be registered with the shortcut key"));
header->setText(0, tr("Group", "Group of the Action to be registered with the shortcut key"));
header->setText(1, tr("Description", "Title of the column that displays the meaning of the action to be registered with the shortcut key"));
header->setText(2, tr("CurrentShortcut", "Title of the column of the content of the shortcut key registered for Action"));
// header->setSizeHint(0, QSize(100, 30));
// header->setSizeHint(1, QSize(300, 30));
// header->setSizeHint(2, QSize(300, 30));
resetView();
}
void KeyConfigDialog::resetView()
{
ui->treeWidget->clear();
m_actionNameByIconText.clear();
QMap<QString, QAction*>& actions = m_keyActions.actions();
QMap<QString, QKeySequence>& keyconfigs = m_keyActions.keyMaps();
// foreach(const QString& key, actions.keys()) {
// QAction* action = actions[key];
// if(!action) continue;
// QTreeWidgetItem* item = new QTreeWidgetItem;
// item->setText(0, key);
// item->setText(1, action->iconText());
// item->setText(2, keyconfigs.contains(key) ? keyconfigs[key].toString() : "");
//// item->setSizeHint(0, QSize(240, 20));
//// item->setSizeHint(1, QSize(240, 20));
// ui->treeWidget->addTopLevelItem(item);
// }
const QMultiMap<QString, QString>& nameByGroups = m_keyActions.nameByGroups();
foreach(const QString& groupName, nameByGroups.uniqueKeys()) {
foreach(const QString& key, nameByGroups.values(groupName)) {
QAction* action = actions[key];
if(!action) continue;
QTreeWidgetItem* item = new QTreeWidgetItem;
item->setText(0, groupName);
item->setText(1, action->iconText());
item->setText(2, keyconfigs.contains(key) ? keyconfigs[key].toString() : "");
// item->setSizeHint(0, QSize(240, 20));
// item->setSizeHint(1, QSize(300, 20));
ui->treeWidget->addTopLevelItem(item);
m_actionNameByIconText[action->iconText()] = key;
}
}
}
KeyConfigDialog::~KeyConfigDialog()
{
delete ui;
}
bool KeyConfigDialog::eventFilter(QObject *obj, QEvent *event)
{
return QObject::eventFilter(obj, event);
}
void KeyConfigDialog::setEditTextWithoutSignal(QString text)
{
m_ignoreEdited = true;
ui->shortcutEdit->setText(text);
m_ignoreEdited = false;
}
void KeyConfigDialog::onTreeWidget_currentItemChanged(QTreeWidgetItem *item, QTreeWidgetItem *)
{
//qDebug() << "on_currentCommandChanged: " << (item ? item->text(0):"nullptr") << (previous ? previous->text(0) :"nullptr");
if(item) {
// m_actionName = item->text(0);
m_actionName = m_actionNameByIconText[item->text(1)];
ui->shortcutGroupBox->setEnabled(true);
ui->shortcutEdit->setText(item->text(2));
}
}
void KeyConfigDialog::onRecordButton_keySequenceChanged(QKeySequence key)
{
QString shortcutText = keySequenceToEditString(key);
setEditTextWithoutSignal(shortcutText);
if(!keySequenceIsValid(key)) {
ui->warningLabel->setText(tr("Invalid key sequence.", "Message when rejecting input contents of inappropriate shortcut key"));
return;
}
if(m_keyActions.markCollisions(m_actionName, key)) {
ui->warningLabel->setText(tr("Key sequence has potential conflicts.", "Text to be displayed when the entered shortcut key conflicts with another shortcut key"));
return;
}
ui->warningLabel->clear();
QTreeWidgetItem *current = ui->treeWidget->currentItem();
current->setText(2, shortcutText);
m_keyActions.updateKey(m_actionName, key);
}
void KeyConfigDialog::onResetButton_clicked()
{
QKeySequence key = m_keyActions.getKeyDefault(m_actionName);
QString shortcutText = keySequenceToEditString(key);
setEditTextWithoutSignal(shortcutText);
if(m_keyActions.markCollisions(m_actionName, key)) {
ui->warningLabel->setText(tr("Key sequence has potential conflicts.", "Text to be displayed when the entered shortcut key conflicts with another shortcut key"));
return;
}
ui->warningLabel->clear();
QTreeWidgetItem *current = ui->treeWidget->currentItem();
current->setText(2, shortcutText);
m_keyActions.updateKey(m_actionName, key);
}
void KeyConfigDialog::onShortcutEdit_textChanged(QString text)
{
if(!m_ignoreEdited) {
QKeySequence key(text);
if(!keySequenceIsValid(key)) {
ui->warningLabel->setText(tr("Invalid key sequence.", "Message when rejecting input contents of inappropriate shortcut key"));
return;
}
onRecordButton_keySequenceChanged(key);
}
}
void KeyConfigDialog::onStandardButton_clicked(QAbstractButton *button)
{
switch(ui->buttonBox->standardButton(button)) {
case QDialogButtonBox::RestoreDefaults:
m_keyActions.resetByDefault();
resetView();
break;
}
}
| 36.968652 | 171 | 0.642669 | SAT1226 |
519e37fdd00caac8fbb8d7195eab57ac88157733 | 483 | cpp | C++ | src/main.cpp | biomotion/eos-2020-final | c19b81250a13ac41dcb0ebbda345dd3c7223fdb2 | [
"MIT"
] | null | null | null | src/main.cpp | biomotion/eos-2020-final | c19b81250a13ac41dcb0ebbda345dd3c7223fdb2 | [
"MIT"
] | null | null | null | src/main.cpp | biomotion/eos-2020-final | c19b81250a13ac41dcb0ebbda345dd3c7223fdb2 | [
"MIT"
] | 1 | 2021-08-02T04:48:58.000Z | 2021-08-02T04:48:58.000Z | #include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <signal.h>
#include <iostream>
#include "game.h"
using namespace std;
void intHandler(int);
int main(int argc, char *argv[])
{
// play
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = intHandler;
sigaction(SIGINT, &sa, NULL);
myGame.gameLoop();
return 0;
}
void intHandler(int signum){
printf("catch SIGING\n");
myGame.gameStop();
} | 15.09375 | 32 | 0.674948 | biomotion |
51aaf6f4b44684083721281ac37c12423528dac2 | 2,313 | cpp | C++ | mdec/movie/main.cpp | ggrtk/ps1-tests | 072a2f2dc2cc2ce5e63414147917969231808485 | [
"MIT"
] | 34 | 2019-09-22T15:52:29.000Z | 2022-01-16T16:14:15.000Z | mdec/movie/main.cpp | ggrtk/ps1-tests | 072a2f2dc2cc2ce5e63414147917969231808485 | [
"MIT"
] | 3 | 2020-03-28T15:12:56.000Z | 2021-02-08T09:25:29.000Z | mdec/movie/main.cpp | ggrtk/ps1-tests | 072a2f2dc2cc2ce5e63414147917969231808485 | [
"MIT"
] | 8 | 2020-03-20T13:15:33.000Z | 2022-01-15T03:43:58.000Z | #include <common.h>
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <io.h>
#include <dma.hpp>
#include <mdec.h>
#include <gpu.h>
#include "bad_apple.h"
#define SCR_W 256
#define SCR_H 240
uint32_t* buffer = nullptr;
void decodeAndDisplayFrame(uint8_t* frame, size_t frameLen, uint16_t frameWidth, uint16_t frameHeight) {
const int STRIPE_WIDTH = 16;
const int STRIPE_HEIGHT = frameHeight;
#ifdef USE_24BIT
const ColorDepth depth = ColorDepth::bit_24;
const int copyWidth = STRIPE_WIDTH * 3/2;
#define BYTES_PER_PIXEL 3
#else
const ColorDepth depth = ColorDepth::bit_15;
const int copyWidth = STRIPE_WIDTH;
#define BYTES_PER_PIXEL 2
#endif
mdec_decodeDma((uint16_t*)frame, frameLen, depth, false, false);
if (buffer == nullptr) {
buffer = (uint32_t*)malloc(STRIPE_WIDTH * STRIPE_HEIGHT * BYTES_PER_PIXEL / 4 * sizeof(uint32_t));
}
for (int c = 0; c < frameWidth / STRIPE_WIDTH; c++) {
mdec_readDecodedDma(buffer, STRIPE_WIDTH * STRIPE_HEIGHT * BYTES_PER_PIXEL);
vramWriteDMA(c * copyWidth, 0, copyWidth, STRIPE_HEIGHT, (uint16_t*)buffer);
}
}
int main() {
SetVideoMode(MODE_NTSC);
initVideo(SCR_W, SCR_H);
printf("\nmdec/frame\n");
#ifdef USE_24BIT
extern DISPENV disp;
disp.isrgb24 = true;
PutDispEnv(&disp);
printf("Using framebuffer in 24bit mode\n");
#endif
clearScreen();
mdec_reset();
mdec_quantTable(quant, true);
mdec_idctTable((int16_t*)idct);
mdec_enableDma();
for (int i = 0; i<60*2; i++) {
VSync(0);
}
for (int i = 0; i<FRAME_COUNT; i++) {
frame_t frame = frames[i];
decodeAndDisplayFrame(&movieBitstream[frame.offset], frame.size, SCR_W, SCR_H);
VSync(0);
}
free(buffer);
printf("Done\n");
// Stop all pending DMA transfers
write32(DMA::CH_CONTROL_ADDR + 0x10 * (int)DMA::Channel::MDECin, 0);
write32(DMA::CH_CONTROL_ADDR + 0x10 * (int)DMA::Channel::MDECout, 0);
write32(DMA::CH_CONTROL_ADDR + 0x10 * (int)DMA::Channel::GPU, 0);
DMA::masterEnable(DMA::Channel::MDECout, false);
DMA::masterEnable(DMA::Channel::MDECin, false);
DMA::masterEnable(DMA::Channel::GPU, false);
mdec_reset();
for (;;) {
VSync(0);
}
return 0;
} | 27.211765 | 106 | 0.65067 | ggrtk |
51ac58e8bc26d1385945ed843dbeaf9e39217efe | 1,502 | cpp | C++ | src/main.cpp | jroivas/lisp-alike | c87e99f6bf9ebbb3ec37a53f51e2dad1e31e0213 | [
"MIT"
] | null | null | null | src/main.cpp | jroivas/lisp-alike | c87e99f6bf9ebbb3ec37a53f51e2dad1e31e0213 | [
"MIT"
] | null | null | null | src/main.cpp | jroivas/lisp-alike | c87e99f6bf9ebbb3ec37a53f51e2dad1e31e0213 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <sstream>
#include <unistd.h>
#include "tokenize.hh"
#include "parse.hh"
#include "symbols.hh"
#include "builtin.hh"
#include "eval.hh"
#include "env.hh"
#ifdef HAVE_READLINE
#include <readline/readline.h>
#include <readline/history.h>
#include <readline/tilde.h>
static char *history_file = nullptr;
#endif
bool getline(bool term, const char *prompt, std::string &line)
{
#ifdef HAVE_READLINE
if (term) {
char *res = readline(prompt);
if (res == nullptr) return false;
add_history(res);
append_history(1, history_file);
line = res;
return true;
}
#endif
std::cout << prompt;
std::getline(std::cin, line);
if (std::cin.eof()) return false;
return true;
}
int repl(bool terminal)
{
std::string line;
Symbols s;
Env env;
Builtin b(s);
b.install(&env);
while (!std::cin.eof()) {
if (!getline(terminal, terminal ? "lisp> " : "", line))
break;
try {
Value *ev = evalLine(s, env, line);
if (ev != nullptr) {
std::cout << ev->toString() << "\n";
} else std::cout << "nil\n";
}
catch (std::string s) {
std::cerr << s << "\n";
}
}
return 0;
}
int main(int argc, char **argv)
{
#ifdef HAVE_READLINE
history_file = tilde_expand("~/.lisp-alike-history");
read_history(history_file);
#endif
return repl(isatty(fileno(stdin)));
}
| 21.15493 | 63 | 0.573901 | jroivas |
51af94beb1e087dcb0b900d302eb72ce51bf86af | 5,198 | cc | C++ | src/bexclfit_fcts.cc | hanswenzel/bfit | 70da497b81bf983ca3e2c9dad3858a4209e279cf | [
"BSD-4-Clause-UC"
] | null | null | null | src/bexclfit_fcts.cc | hanswenzel/bfit | 70da497b81bf983ca3e2c9dad3858a4209e279cf | [
"BSD-4-Clause-UC"
] | null | null | null | src/bexclfit_fcts.cc | hanswenzel/bfit | 70da497b81bf983ca3e2c9dad3858a4209e279cf | [
"BSD-4-Clause-UC"
] | null | null | null | #include <iostream>
#include "bexclfit_fcts.h"
#include "TMath.h"
#include "global.h"
extern int offset,combine_flg;
//extern Double_t sbmasswin,masswin;
void testfun()
{
printf("offset = %d\n",offset);
printf("combine_flg = %d\n",combine_flg);
}
Double_t signalmassdis(Double_t x, Double_t sig, Double_t *parms)
{
//---------------------------------------------------------------------------
// This is a simple function to parameterize the pure B-signal in the
// mass distribution. This is parametrized by a simple normalized gaussian
// distribution.
//---------------------------------------------------------------------------
Double_t result,m=x,sigma;
sigma = parms[mscale]*sig;
result = (exp(-((m-parms[mpeak])*(m-parms[mpeak]))/(2.0*sigma*sigma)))/(sigma*sqrt2pi);
return result;
}
Double_t bgrmassdis(Double_t x, Double_t *parms, double mmin, double mmax)
{
//---------------------------------------------------------------------------
// This is a simple function to parameterize the background in the
// mass distribution. This is parametrized by a simple linear function.
//---------------------------------------------------------------------------
Double_t result,m=x;
Double_t a;
a = 2.0/(mmax*mmax-mmin*mmin) - (2.0 *parms[mconst+offset])/(mmax+mmin);
result = a * m + parms[mconst+offset];
return result;
}
Double_t backgr(Double_t *x,Double_t *par)
{
//---------------------------------------------------------------------------
// This is a simple function to parameterize the shape of the bgr in the
// exclusive lifetime distribution. This function is used in the binned fit.
//
// par[0]: NORMALIZATION FACTOR
// par[1]: SIGMA OF GAUSSIAN
// par[2]: LAMBDA1 OF RIGHT SIDE EXPONENTIAL
// par[3]: F1 OF RIGHT SIDE EXPONENTIAL
// par[4]: LAMBDA2 OF LEFT SIDE EXPONENTIAL
// par[5]: F2 OF LEFT SIDE EXPONENTIAL
// par[6]: LAMBDA3 OF RIGHT SIDE EXPONENTIAL 2
// par[7]: F3 OF RIGHT SIDE EXPONENTIAL 2
//---------------------------------------------------------------------------
Double_t result,l=*x;
result = exp((-0.5*l*l)/(par[1]*par[1]))*(par[0]/(par[1]*sqrt2pi));
//if (l>=0) {
// result=(1-par[3]-par[5])*result+par[0]*(par[3]/par[2])*exp(-l/par[2]);
//} else {
// result=(1-par[3]-par[5])*result+par[0]*(par[5]/par[4])*exp(l/par[4]);
//}
if (l>=0) {
result=(1-par[3]-par[5]-par[7])*result+par[0]*(par[3]/par[2])*exp(-l/par[2])+par[0]*(par[7]/par[6])*exp(-l/par[6]);
} else {
result=(1-par[3]-par[5])*result+par[0]*(par[5]/par[4])*exp(l/par[4]);
}
return result;
}
Double_t bgrctdis(Double_t x, Double_t sig, Double_t *parms)
{
//----------------------------------------------------------------------------
// This is a simple function to parameterize the shape of the bgr in the
// exclusive lifetime distribution.
//----------------------------------------------------------------------------
Double_t result,l=x, sigma=sig;
sigma = sigma*parms[ctscale];
Double_t norm=1.0/(sigma*sqrt2pi);
result =norm*exp((-0.5*l*l)/(sigma*sigma));
if (l>=0) {
result=(1-parms[fracpos+offset]-parms[fracneg+offset]-parms[fracpos2+offset])*result+(parms[fracpos+offset]/parms[lbdapos+offset])*exp(-l/parms[lbdapos+offset])+(parms[fracpos2+offset]/parms[lbdapos2+offset])*exp(-l/parms[lbdapos2+offset]);
} else {
result=(1-parms[fracpos+offset]-parms[fracneg+offset]-parms[fracpos2+offset])*result+(parms[fracneg+offset]/parms[lbdaneg+offset])*exp(l/parms[lbdaneg+offset]);
}
return result;
}
/*
Double_t signalctdis(Double_t x, Double_t sig, Double_t *parms)
{
//---------------------------------------------------------------------------
// This is a simple function to parameterize the shape of the signal
// in the exclusive lifetime distribution.
//---------------------------------------------------------------------------
Double_t result,l=x;
Double_t sigma = sig;
sigma = sigma*parms[ctscale];
result = ((0.5/parms[ctau])*exp((0.5*sigma*sigma)/(parms[ctau]*parms[ctau])-l/parms[ctau])*(1+TMath::Erf(l/(sqrt2*sigma)-sigma/(parms[ctau]*sqrt2))));
return result;
}
*/
Double_t signalctdis(Double_t x, Double_t sig, Double_t *parms)
{
//---------------------------------------------------------------------------
// This is a simple function to parameterize the shape of the signal
// in the exclusive lifetime distribution.
//---------------------------------------------------------------------------
Double_t result,l=x;
Double_t sigma = sig;
Double_t s2 = 0.100;
sigma = sigma*parms[ctscale];
// result = ((0.5/parms[ctau])*exp((0.5*sigma*sigma)/(parms[ctau]*parms[ctau])-l/parms[ctau])*(1+TMath::Erf(l/(sqrt2*sigma)-sigma/(parms[ctau]*sqrt2))));
result = (0.5/parms[ctau])*(
(1-parms[tailfrac])*(exp((0.5*sigma*sigma)/(parms[ctau]*parms[ctau])-l/parms[ctau])*(1+TMath::Erf(l/(sqrt2*sigma)-sigma/(parms[ctau]*sqrt2))))
+parms[tailfrac]*(exp((0.5*s2*s2)/(parms[ctau]*parms[ctau])-l/parms[ctau])*(1+TMath::Erf(l/(sqrt2*s2)-s2/(parms[ctau]*sqrt2))))
);
return result;
}
| 35.60274 | 244 | 0.534052 | hanswenzel |
51b0bc5023b24223395db4d64ca1adbbb8738c5a | 1,256 | cpp | C++ | 7_shortcutkey_diff_by_beyondcompare_in_qtcreator/main.cpp | ZYV037/QT_Example | 916e343894346389f796f42a63d4162bb8429555 | [
"WTFPL"
] | 4 | 2018-12-26T11:10:21.000Z | 2021-02-05T10:31:30.000Z | 7_shortcutkey_diff_by_beyondcompare_in_qtcreator/main.cpp | ZYV037/QT_Example | 916e343894346389f796f42a63d4162bb8429555 | [
"WTFPL"
] | null | null | null | 7_shortcutkey_diff_by_beyondcompare_in_qtcreator/main.cpp | ZYV037/QT_Example | 916e343894346389f796f42a63d4162bb8429555 | [
"WTFPL"
] | 2 | 2021-02-05T10:31:37.000Z | 2021-04-04T17:25:07.000Z | #include <stdio.h>
#include<stdlib.h>
#include <string>
#include <iostream>
#include <QProcess>
#pragma comment( linker, “/subsystem:windows /entry:mainCRTStartup” )
//"C:\Program Files\TortoiseSVN\bin\svn_wrapper.exe" diff System/WMPS/DIS/UI/DisEventVariationUI/DisEventVariationUI.cpp
//C:\WtgeoProducts: "C:\Program Files\TortoiseSVN\bin\svn_wrapper.exe" diff --internal-diff System/WMPS/App/DIS/DIS.pro
int main(int argc, char *argv[])
{
if(argc < 3)
{
std::string cmd = "Cmd error: " ;
for(int i = 0; i < argc; ++ i)
{
cmd += argv[i];
cmd += " ";
}
std::cout << cmd << std::endl;
return -1;
}
std::string cmd1 = argv[1];
if( cmd1 != "diff" )
{
return -1;
}
if(argc == 3)
{
std::string cmd = "TortoiseProc.exe /command:diff /path:";
cmd += argv[2];
return QProcess::execute(cmd.c_str());
}
std::string cmd2 = argv[2];
if( cmd2 == "--internal-diff" )
{
std::string cmd = "TortoiseProc.exe /command:diff /path:";
cmd += argv[3];
return QProcess::execute(cmd.c_str());
}
// int res = system(cmd.c_str());
// std::cout << cmd << std::endl;
return -1;
}
| 24.153846 | 120 | 0.55414 | ZYV037 |
51b28c7a4ec3d325b98b22d50a9c84f2f6f40bd0 | 110 | cpp | C++ | src/main.cpp | payano/mMesh | 151ab475ad6ea66a608566098755dbad39eca058 | [
"MIT"
] | null | null | null | src/main.cpp | payano/mMesh | 151ab475ad6ea66a608566098755dbad39eca058 | [
"MIT"
] | 37 | 2020-03-02T18:31:57.000Z | 2020-05-20T07:18:14.000Z | src/main.cpp | payano/mMesh | 151ab475ad6ea66a608566098755dbad39eca058 | [
"MIT"
] | 2 | 2020-03-10T17:35:27.000Z | 2020-04-24T10:51:47.000Z | #ifdef UNIX
#include "Mesh.h"
#include <stdio.h>
int main(void)
{
printf("MAIN MAIN\n");
return 0;
}
#endif
| 11 | 23 | 0.654545 | payano |
51b35810327fc15d7f57918e4b6bdd9de50304fb | 6,598 | cpp | C++ | servern/boinclib/msg_log.cpp | tomasbrod/tbboinc | c125cc355b2dc9a1e536b5e5ded028d4e7f4613a | [
"MIT"
] | null | null | null | servern/boinclib/msg_log.cpp | tomasbrod/tbboinc | c125cc355b2dc9a1e536b5e5ded028d4e7f4613a | [
"MIT"
] | 4 | 2020-09-07T15:54:45.000Z | 2020-09-27T16:47:16.000Z | servern/boinclib/msg_log.cpp | tomasbrod/tbboinc | c125cc355b2dc9a1e536b5e5ded028d4e7f4613a | [
"MIT"
] | null | null | null | // This file is part of BOINC.
// http://boinc.berkeley.edu
// Copyright (C) 2008 University of California
//
// BOINC is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any later version.
//
// BOINC is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with BOINC. If not, see <http://www.gnu.org/licenses/>.
#ifdef _WIN32
#include "boinc_win.h"
#else
#include <cstring>
#include <string>
#endif
#ifdef _USING_FCGI_
#include "boinc_fcgi.h"
#endif
#include "str_util.h"
#include "str_replace.h"
#include "util.h"
#include "msg_log.h"
using std::string;
// MSG_LOG is a base class for writing messages not intended for the end user.
// This includes all server messages and client debugging messages.
// SCHED_MSG_LOG (in sched/sched_msg_log.C) decides which scheduler messages
// to print and formats the "kind" keyword;
// CLIENT_MSG_LOG does the same thing for client debugging output.
//
// MSG_LOG has an "indent_level" state for how many spaces to indent output.
// This corresponds in general to the function-call recursion level.
// Call MSG_LOG::enter_level() to increase or decrease by 1 level.
// The SCOPE_MSG_LOG class takes care of these calls for you.
// Create a SCOPE_MSG_LOG object on the stack at the beginning of a function;
// it will increment the level by 1 on construction,
// and decrement the level by 1 on destruction at end of scope.
// This way you don't have to worry about decrementing
// before mid-function returns, exceptions, etc.
// Each [v]printf* function prints the timestamp, the formatted KIND string,
// indentation level, then the specified string.
// The string to print can be a one-line string (including the trailing \n),
// a multi-line string (it's broken up into lines
// to get the prefix on each line), or a file (also broken up into lines).
// Scheduler functions should use "sched_messages" which is an instance of
// SCHED_MSG_LOG. Client functions should use "client_messages",
// which is an instance of CLIENT_MSG_LOG.
// See sched/sched_msg_log.C and client/client_msg_log.C for those classes.
MSG_LOG::MSG_LOG(FILE* output_) {
debug_level = 0;
output = output_;
indent_level = 0;
pid = 0;
spaces[0] = 0;
for (int i=1; i<80; i++) {
spaces[i] = 0;
}
}
void MSG_LOG::enter_level(int diff) {
if (indent_level <= 0 ) indent_level = 0;
if ((indent_level + diff) <= 0) return;
if (indent_level >= 39 ) indent_level = 39;
if ((indent_level + diff) >= 39) return;
spaces[indent_level] = ' ';
indent_level += diff*2;
spaces[indent_level] = 0;
}
void MSG_LOG::set_indent_level(const int new_indent_level) {
if (new_indent_level < 0) indent_level = 0;
else if (new_indent_level > 39) indent_level = 39;
else indent_level = new_indent_level;
memset(spaces, ' ', sizeof(spaces));
spaces[indent_level] = 0;
}
void MSG_LOG::vprintf(int kind, const char* format, va_list va) {
char buf[256];
const char* now_timestamp = precision_time_to_string(dtime());
if (!v_message_wanted(kind)) return;
if (pid) {
sprintf(buf, " [PID=%-5d]", pid);
} else {
buf[0] = 0;
}
fprintf(output, "%s%s %s%s ", now_timestamp, buf, v_format_kind(kind), spaces);
vfprintf(output, format, va);
}
// break a multi-line string into lines (so that we show prefix on each line)
//
void MSG_LOG::vprintf_multiline(
int kind, const char* str, const char* prefix_format, va_list va
) {
if (!v_message_wanted(kind)) return;
if (str == NULL) return;
char sprefix[256] = "";
if (prefix_format) {
vsnprintf(sprefix, sizeof(sprefix),prefix_format, va);
}
const char* now_timestamp = precision_time_to_string(dtime());
const char* skind = v_format_kind(kind);
string line;
while (*str) {
if (*str == '\n') {
fprintf(output, "%s %s%s %s%s\n", now_timestamp, skind, spaces, sprefix, line.c_str());
line.erase();
} else {
line += *str;
}
++str;
}
if (!line.empty()) {
fprintf(output, "%s %s[%s] %s%s\n", now_timestamp, spaces, skind, sprefix, line.c_str());
}
}
void MSG_LOG::vprintf_file(
int kind, const char* filename, const char* prefix_format, va_list va
) {
if (!v_message_wanted(kind)) return;
char sprefix[256] = "";
if (prefix_format) {
vsnprintf(sprefix, sizeof(sprefix), prefix_format, va);
}
const char* now_timestamp = precision_time_to_string(dtime());
const char* skind = v_format_kind(kind);
FILE* f = fopen(filename, "r");
if (!f) return;
char buf[256];
while (fgets(buf, 256, f)) {
fprintf(output, "%s %s%s %s%s\n", now_timestamp, skind, spaces, sprefix, buf);
}
fclose(f);
}
void MSG_LOG::printf(int kind, const char* format, ...) {
va_list va;
va_start(va, format);
vprintf(kind, format, va);
va_end(va);
}
void MSG_LOG::printf_multiline(
int kind, const char* str, const char* prefix_format, ...
) {
va_list va;
va_start(va, prefix_format);
vprintf_multiline(kind, str, prefix_format, va);
va_end(va);
}
void MSG_LOG::printf_file(
int kind, const char* filename, const char* prefix_format, ...
) {
va_list va;
va_start(va, prefix_format);
vprintf_file(kind, filename, prefix_format, va);
va_end(va);
}
// These SCOPE_MSG_LOG functions are utility functions that call their
// corresponding MSG_LOG functions with the same name, passing the KIND that
// was specified on creation of the SCOPE_MSG_LOG object.
void SCOPE_MSG_LOG::printf(const char* format, ...) {
va_list va;
va_start(va, format);
messages.vprintf(kind, format, va);
va_end(va);
}
void SCOPE_MSG_LOG::printf_multiline(
const char* str, const char* prefix_format, ...
) {
va_list va;
va_start(va, prefix_format);
messages.vprintf_multiline(kind, str, prefix_format, va);
va_end(va);
}
void SCOPE_MSG_LOG::printf_file(
const char* filename, const char* prefix_format, ...
) {
va_list va;
va_start(va, prefix_format);
messages.vprintf_file(kind, filename, prefix_format, va);
va_end(va);
}
| 30.831776 | 99 | 0.677326 | tomasbrod |
51b55f65bd4124e39e33605dd344e9af94d97f00 | 56,356 | cpp | C++ | dbms/src/Interpreters/InterpreterSelectQuery.cpp | pingcap/tiflash | 580821ad8351b6a944ea413eb2603b6f4295f3e4 | [
"Apache-2.0"
] | 85 | 2022-03-25T09:03:16.000Z | 2022-03-25T09:45:03.000Z | dbms/src/Interpreters/InterpreterSelectQuery.cpp | pingcap/tiflash | 580821ad8351b6a944ea413eb2603b6f4295f3e4 | [
"Apache-2.0"
] | 7 | 2022-03-25T08:59:10.000Z | 2022-03-25T09:40:13.000Z | dbms/src/Interpreters/InterpreterSelectQuery.cpp | pingcap/tiflash | 580821ad8351b6a944ea413eb2603b6f4295f3e4 | [
"Apache-2.0"
] | 11 | 2022-03-25T09:15:36.000Z | 2022-03-25T09:45:07.000Z | // Copyright 2022 PingCAP, 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 <Columns/Collator.h>
#include <Common/Logger.h>
#include <Common/TiFlashException.h>
#include <Common/typeid_cast.h>
#include <Core/Field.h>
#include <DataStreams/AggregatingBlockInputStream.h>
#include <DataStreams/AsynchronousBlockInputStream.h>
#include <DataStreams/ConcatBlockInputStream.h>
#include <DataStreams/CreatingSetsBlockInputStream.h>
#include <DataStreams/DistinctBlockInputStream.h>
#include <DataStreams/DistinctSortedBlockInputStream.h>
#include <DataStreams/ExpressionBlockInputStream.h>
#include <DataStreams/FilterBlockInputStream.h>
#include <DataStreams/LimitBlockInputStream.h>
#include <DataStreams/LimitByBlockInputStream.h>
#include <DataStreams/MaterializingBlockInputStream.h>
#include <DataStreams/MergeSortingBlockInputStream.h>
#include <DataStreams/MergingAggregatedBlockInputStream.h>
#include <DataStreams/MergingAggregatedMemoryEfficientBlockInputStream.h>
#include <DataStreams/MergingSortedBlockInputStream.h>
#include <DataStreams/NullBlockInputStream.h>
#include <DataStreams/ParallelAggregatingBlockInputStream.h>
#include <DataStreams/PartialSortingBlockInputStream.h>
#include <DataStreams/TotalsHavingBlockInputStream.h>
#include <DataStreams/UnionBlockInputStream.h>
#include <DataStreams/copyData.h>
#include <Encryption/FileProvider.h>
#include <Interpreters/ExpressionAnalyzer.h>
#include <Interpreters/InterpreterSelectQuery.h>
#include <Interpreters/InterpreterSelectWithUnionQuery.h>
#include <Interpreters/InterpreterSetQuery.h>
#include <Parsers/ASTFunction.h>
#include <Parsers/ASTIdentifier.h>
#include <Parsers/ASTLiteral.h>
#include <Parsers/ASTOrderByElement.h>
#include <Parsers/ASTSelectQuery.h>
#include <Parsers/ASTSelectWithUnionQuery.h>
#include <Parsers/ASTTablesInSelectQuery.h>
#include <Storages/IManageableStorage.h>
#include <Storages/IStorage.h>
#include <Storages/RegionQueryInfo.h>
#include <Storages/Transaction/LearnerRead.h>
#include <Storages/Transaction/RegionRangeKeys.h>
#include <Storages/Transaction/StorageEngineType.h>
#include <Storages/Transaction/TMTContext.h>
#include <Storages/Transaction/TiKVRange.h>
#include <TableFunctions/ITableFunction.h>
#include <TableFunctions/TableFunctionFactory.h>
#include <TiDB/Schema/SchemaSyncer.h>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#include <Poco/Dynamic/Var.h>
#include <Poco/JSON/Array.h>
#include <Poco/JSON/Object.h>
#include <Poco/JSON/Parser.h>
#pragma GCC diagnostic pop
#include <google/protobuf/text_format.h>
namespace ProfileEvents
{
extern const Event SelectQuery;
}
namespace DB
{
namespace ErrorCodes
{
extern const int TOO_DEEP_SUBQUERIES;
extern const int THERE_IS_NO_COLUMN;
extern const int SAMPLING_NOT_SUPPORTED;
extern const int ILLEGAL_FINAL;
extern const int ILLEGAL_PREWHERE;
extern const int TOO_MANY_COLUMNS;
extern const int LOGICAL_ERROR;
extern const int NOT_IMPLEMENTED;
extern const int SCHEMA_VERSION_ERROR;
extern const int UNKNOWN_EXCEPTION;
} // namespace ErrorCodes
InterpreterSelectQuery::InterpreterSelectQuery(
const ASTPtr & query_ptr_,
const Context & context_,
const Names & required_result_column_names_,
QueryProcessingStage::Enum to_stage_,
size_t subquery_depth_,
const BlockInputStreamPtr & input,
bool only_analyze)
: query_ptr(query_ptr_->clone()) /// Note: the query is cloned because it will be modified during analysis.
, query(typeid_cast<ASTSelectQuery &>(*query_ptr))
, context(context_)
, to_stage(to_stage_)
, subquery_depth(subquery_depth_)
, only_analyze(only_analyze)
, input(input)
, log(Logger::get("InterpreterSelectQuery"))
{
init(required_result_column_names_);
}
InterpreterSelectQuery::InterpreterSelectQuery(OnlyAnalyzeTag, const ASTPtr & query_ptr_, const Context & context_)
: query_ptr(query_ptr_->clone())
, query(typeid_cast<ASTSelectQuery &>(*query_ptr))
, context(context_)
, to_stage(QueryProcessingStage::Complete)
, subquery_depth(0)
, only_analyze(true)
, log(Logger::get("InterpreterSelectQuery"))
{
init({});
}
InterpreterSelectQuery::~InterpreterSelectQuery() = default;
void InterpreterSelectQuery::init(const Names & required_result_column_names)
{
ProfileEvents::increment(ProfileEvents::SelectQuery);
if (!context.hasQueryContext())
context.setQueryContext(context);
initSettings();
const Settings & settings = context.getSettingsRef();
if (settings.max_subquery_depth && subquery_depth > settings.max_subquery_depth)
throw Exception("Too deep subqueries. Maximum: " + settings.max_subquery_depth.toString(),
ErrorCodes::TOO_DEEP_SUBQUERIES);
max_streams = settings.max_threads;
const auto & table_expression = query.table();
NamesAndTypesList source_columns;
if (input)
{
/// Read from prepared input.
source_columns = input->getHeader().getNamesAndTypesList();
}
else if (table_expression && typeid_cast<const ASTSelectWithUnionQuery *>(table_expression.get()))
{
/// Read from subquery.
source_columns = InterpreterSelectWithUnionQuery::getSampleBlock(table_expression, context).getNamesAndTypesList();
}
else if (table_expression && typeid_cast<const ASTFunction *>(table_expression.get()))
{
/// Read from table function.
storage = context.getQueryContext().executeTableFunction(table_expression);
table_lock = storage->lockForShare(context.getCurrentQueryId());
}
else
{
/// Read from table. Even without table expression (implicit SELECT ... FROM system.one).
String database_name;
String table_name;
getDatabaseAndTableNames(database_name, table_name);
if (settings.schema_version == DEFAULT_UNSPECIFIED_SCHEMA_VERSION)
{
storage = context.getTable(database_name, table_name);
table_lock = storage->lockForShare(context.getCurrentQueryId());
}
else
{
getAndLockStorageWithSchemaVersion(database_name, table_name, settings.schema_version);
}
}
query_analyzer = std::make_unique<ExpressionAnalyzer>(
query_ptr,
context,
storage,
source_columns,
required_result_column_names,
subquery_depth,
!only_analyze);
if (!only_analyze)
{
if (query.sample_size() && (input || !storage || !storage->supportsSampling()))
throw Exception("Illegal SAMPLE: table doesn't support sampling", ErrorCodes::SAMPLING_NOT_SUPPORTED);
if (query.final() && (input || !storage || !storage->supportsFinal()))
throw Exception((!input && storage) ? "Storage " + storage->getName() + " doesn't support FINAL" : "Illegal FINAL", ErrorCodes::ILLEGAL_FINAL);
if (query.prewhere_expression && (input || !storage || !storage->supportsPrewhere()))
throw Exception((!input && storage) ? "Storage " + storage->getName() + " doesn't support PREWHERE" : "Illegal PREWHERE", ErrorCodes::ILLEGAL_PREWHERE);
/// Save the new temporary tables in the query context
for (const auto & it : query_analyzer->getExternalTables())
if (!context.tryGetExternalTable(it.first))
context.addExternalTable(it.first, it.second);
}
}
void InterpreterSelectQuery::getAndLockStorageWithSchemaVersion(const String & database_name, const String & table_name, Int64 query_schema_version)
{
const String qualified_name = database_name + "." + table_name;
/// Get current schema version in schema syncer for a chance to shortcut.
const auto global_schema_version = context.getTMTContext().getSchemaSyncer()->getCurrentVersion();
/// Lambda for get storage, then align schema version under the read lock.
auto get_and_lock_storage = [&](bool schema_synced) -> std::tuple<StoragePtr, TableLockHolder, Int64, bool> {
/// Get storage in case it's dropped then re-created.
// If schema synced, call getTable without try, leading to exception on table not existing.
auto storage_tmp = schema_synced ? context.getTable(database_name, table_name) : context.tryGetTable(database_name, table_name);
if (!storage_tmp)
return std::make_tuple(nullptr, nullptr, DEFAULT_UNSPECIFIED_SCHEMA_VERSION, false);
const auto managed_storage = std::dynamic_pointer_cast<IManageableStorage>(storage_tmp);
if (!managed_storage
|| !(managed_storage->engineType() == ::TiDB::StorageEngine::TMT || managed_storage->engineType() == ::TiDB::StorageEngine::DT))
{
throw Exception("Specifying schema_version for storage: " + storage_tmp->getName()
+ ", table: " + qualified_name + " is not allowed",
ErrorCodes::LOGICAL_ERROR);
}
/// Lock storage.
auto lock = storage_tmp->lockForShare(context.getCurrentQueryId());
/// Check schema version, requiring TiDB/TiSpark and TiFlash both use exactly the same schema.
// We have three schema versions, two in TiFlash:
// 1. Storage: the version that this TiFlash table (storage) was last altered.
// 2. Global: the version that TiFlash global schema is at.
// And one from TiDB/TiSpark:
// 3. Query: the version that TiDB/TiSpark used for this query.
auto storage_schema_version = managed_storage->getTableInfo().schema_version;
// Not allow storage > query in any case, one example is time travel queries.
if (storage_schema_version > query_schema_version)
throw TiFlashException("Table " + qualified_name + " schema version " + toString(storage_schema_version) + " newer than query schema version " + toString(query_schema_version),
Errors::Table::SchemaVersionError);
// From now on we have storage <= query.
// If schema was synced, it implies that global >= query, as mentioned above we have storage <= query, we are OK to serve.
if (schema_synced)
return std::make_tuple(storage_tmp, lock, storage_schema_version, true);
// From now on the schema was not synced.
// 1. storage == query, TiDB/TiSpark is using exactly the same schema that altered this table, we are just OK to serve.
// 2. global >= query, TiDB/TiSpark is using a schema older than TiFlash global, but as mentioned above we have storage <= query,
// meaning that the query schema is still newer than the time when this table was last altered, so we still OK to serve.
if (storage_schema_version == query_schema_version || global_schema_version >= query_schema_version)
return std::make_tuple(storage_tmp, lock, storage_schema_version, true);
// From now on we have global < query.
// Return false for outer to sync and retry.
return std::make_tuple(nullptr, nullptr, storage_schema_version, false);
};
/// Try get storage and lock once.
StoragePtr storage_tmp;
TableLockHolder lock;
Int64 storage_schema_version;
auto log_schema_version = [&](const String & result) {
LOG_FMT_DEBUG(log, "Table {} schema {} Schema version [storage, global, query]: [{}, {}, {}].", qualified_name, result, storage_schema_version, global_schema_version, query_schema_version);
};
bool ok;
{
std::tie(storage_tmp, lock, storage_schema_version, ok) = get_and_lock_storage(false);
if (ok)
{
log_schema_version("OK, no syncing required.");
storage = storage_tmp;
table_lock = lock;
return;
}
}
/// If first try failed, sync schema and try again.
{
log_schema_version("not OK, syncing schemas.");
auto start_time = Clock::now();
context.getTMTContext().getSchemaSyncer()->syncSchemas(context);
auto schema_sync_cost = std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start_time).count();
LOG_FMT_DEBUG(log, "Table {} schema sync cost {}ms.", qualified_name, schema_sync_cost);
std::tie(storage_tmp, lock, storage_schema_version, ok) = get_and_lock_storage(true);
if (ok)
{
log_schema_version("OK after syncing.");
storage = storage_tmp;
table_lock = lock;
return;
}
throw Exception("Shouldn't reach here", ErrorCodes::UNKNOWN_EXCEPTION);
}
}
void InterpreterSelectQuery::getDatabaseAndTableNames(String & database_name, String & table_name)
{
auto query_database = query.database();
auto query_table = query.table();
/** If the table is not specified - use the table `system.one`.
* If the database is not specified - use the current database.
*/
if (query_database)
database_name = typeid_cast<ASTIdentifier &>(*query_database).name;
if (query_table)
table_name = typeid_cast<ASTIdentifier &>(*query_table).name;
if (!query_table)
{
database_name = "system";
table_name = "one";
}
else if (!query_database)
{
if (context.tryGetTable("", table_name))
database_name = "";
else
database_name = context.getCurrentDatabase();
}
}
Block InterpreterSelectQuery::getSampleBlock()
{
Pipeline pipeline;
executeImpl(pipeline, input, true);
auto res = pipeline.firstStream()->getHeader();
return res;
}
Block InterpreterSelectQuery::getSampleBlock(const ASTPtr & query_ptr_, const Context & context_)
{
return InterpreterSelectQuery(OnlyAnalyzeTag(), query_ptr_, context_).getSampleBlock();
}
BlockIO InterpreterSelectQuery::execute()
{
Pipeline pipeline;
executeImpl(pipeline, input, false);
executeUnion(pipeline);
BlockIO res;
res.in = pipeline.firstStream();
return res;
}
BlockInputStreams InterpreterSelectQuery::executeWithMultipleStreams()
{
Pipeline pipeline;
executeImpl(pipeline, input, false);
return pipeline.streams;
}
InterpreterSelectQuery::AnalysisResult InterpreterSelectQuery::analyzeExpressions(QueryProcessingStage::Enum from_stage)
{
AnalysisResult res;
/// Do I need to perform the first part of the pipeline - running on remote servers during distributed processing.
res.first_stage = from_stage < QueryProcessingStage::WithMergeableState
&& to_stage >= QueryProcessingStage::WithMergeableState;
/// Do I need to execute the second part of the pipeline - running on the initiating server during distributed processing.
res.second_stage = from_stage <= QueryProcessingStage::WithMergeableState
&& to_stage > QueryProcessingStage::WithMergeableState;
/** First we compose a chain of actions and remember the necessary steps from it.
* Regardless of from_stage and to_stage, we will compose a complete sequence of actions to perform optimization and
* throw out unnecessary columns based on the entire query. In unnecessary parts of the query, we will not execute subqueries.
*/
{
ExpressionActionsChain chain;
res.need_aggregate = query_analyzer->hasAggregation();
query_analyzer->appendArrayJoin(chain, !res.first_stage);
if (query_analyzer->appendJoin(chain, !res.first_stage))
{
res.has_join = true;
res.before_join = chain.getLastActions();
chain.addStep();
}
if (query_analyzer->appendWhere(chain, !res.first_stage))
{
res.has_where = true;
res.before_where = chain.getLastActions();
chain.addStep();
}
if (res.need_aggregate)
{
query_analyzer->appendGroupBy(chain, !res.first_stage);
query_analyzer->appendAggregateFunctionsArguments(chain, !res.first_stage);
res.before_aggregation = chain.getLastActions();
chain.finalize();
chain.clear();
if (query_analyzer->appendHaving(chain, !res.second_stage))
{
res.has_having = true;
res.before_having = chain.getLastActions();
chain.addStep();
}
}
/// If there is aggregation, we execute expressions in SELECT and ORDER BY on the initiating server, otherwise on the source servers.
query_analyzer->appendSelect(chain, res.need_aggregate ? !res.second_stage : !res.first_stage);
res.selected_columns = chain.getLastStep().required_output;
res.has_order_by = query_analyzer->appendOrderBy(chain, res.need_aggregate ? !res.second_stage : !res.first_stage);
res.before_order_and_select = chain.getLastActions();
chain.addStep();
if (query_analyzer->appendLimitBy(chain, !res.second_stage))
{
res.has_limit_by = true;
res.before_limit_by = chain.getLastActions();
chain.addStep();
}
query_analyzer->appendProjectResult(chain);
res.final_projection = chain.getLastActions();
chain.finalize();
chain.clear();
}
/// Before executing WHERE and HAVING, remove the extra columns from the block (mostly the aggregation keys).
if (res.has_where)
res.before_where->prependProjectInput();
if (res.has_having)
res.before_having->prependProjectInput();
res.subqueries_for_sets = query_analyzer->getSubqueriesForSets();
return res;
}
void InterpreterSelectQuery::executeImpl(Pipeline & pipeline, const BlockInputStreamPtr & input, bool dry_run)
{
if (input)
pipeline.streams.push_back(input);
/** Streams of data. When the query is executed in parallel, we have several data streams.
* If there is no GROUP BY, then perform all operations before ORDER BY and LIMIT in parallel, then
* if there is an ORDER BY, then glue the streams using UnionBlockInputStream, and then MergeSortingBlockInputStream,
* if not, then glue it using UnionBlockInputStream,
* then apply LIMIT.
* If there is GROUP BY, then we will perform all operations up to GROUP BY, inclusive, in parallel;
* a parallel GROUP BY will glue streams into one,
* then perform the remaining operations with one resulting stream.
*/
/** Read the data from Storage. from_stage - to what stage the request was completed in Storage. */
QueryProcessingStage::Enum from_stage = executeFetchColumns(pipeline, dry_run);
if (from_stage == QueryProcessingStage::WithMergeableState && to_stage == QueryProcessingStage::WithMergeableState)
throw Exception("Distributed on Distributed is not supported", ErrorCodes::NOT_IMPLEMENTED);
if (!dry_run)
LOG_FMT_TRACE(log, "{} -> {}", QueryProcessingStage::toString(from_stage), QueryProcessingStage::toString(to_stage));
AnalysisResult expressions = analyzeExpressions(from_stage);
const Settings & settings = context.getSettingsRef();
if (to_stage > QueryProcessingStage::FetchColumns)
{
/// Now we will compose block streams that perform the necessary actions.
/// Do I need to aggregate in a separate row rows that have not passed max_rows_to_group_by.
bool aggregate_overflow_row = expressions.need_aggregate && query.group_by_with_totals && settings.max_rows_to_group_by && settings.group_by_overflow_mode == OverflowMode::ANY && settings.totals_mode != TotalsMode::AFTER_HAVING_EXCLUSIVE;
/// Do I need to immediately finalize the aggregate functions after the aggregation?
bool aggregate_final = expressions.need_aggregate && to_stage > QueryProcessingStage::WithMergeableState && !query.group_by_with_totals;
if (expressions.first_stage)
{
if (expressions.has_join)
{
const auto & join = static_cast<const ASTTableJoin &>(*query.join()->table_join);
if (join.kind == ASTTableJoin::Kind::Full || join.kind == ASTTableJoin::Kind::Right)
pipeline.stream_with_non_joined_data = expressions.before_join->createStreamWithNonJoinedDataIfFullOrRightJoin(
pipeline.firstStream()->getHeader(),
0,
1,
settings.max_block_size);
for (auto & stream : pipeline.streams) /// Applies to all sources except stream_with_non_joined_data.
stream = std::make_shared<ExpressionBlockInputStream>(stream, expressions.before_join, /*req_id=*/"");
}
if (expressions.has_where)
executeWhere(pipeline, expressions.before_where);
if (expressions.need_aggregate)
executeAggregation(pipeline, expressions.before_aggregation, context.getFileProvider(), aggregate_overflow_row, aggregate_final);
else
{
executeExpression(pipeline, expressions.before_order_and_select);
executeDistinct(pipeline, true, expressions.selected_columns);
}
/** For distributed query processing,
* if no GROUP, HAVING set,
* but there is an ORDER or LIMIT,
* then we will perform the preliminary sorting and LIMIT on the remote server.
*/
if (!expressions.second_stage && !expressions.need_aggregate && !expressions.has_having)
{
if (expressions.has_order_by)
executeOrder(pipeline);
if (expressions.has_order_by && query.limit_length)
executeDistinct(pipeline, false, expressions.selected_columns);
if (query.limit_length)
executePreLimit(pipeline);
}
}
if (expressions.second_stage)
{
bool need_second_distinct_pass = false;
bool need_merge_streams = false;
if (expressions.need_aggregate)
{
/// If you need to combine aggregated results from multiple servers
if (!expressions.first_stage)
executeMergeAggregated(pipeline, aggregate_overflow_row, aggregate_final);
if (!aggregate_final)
executeTotalsAndHaving(pipeline, expressions.has_having, expressions.before_having, aggregate_overflow_row);
else if (expressions.has_having)
executeHaving(pipeline, expressions.before_having);
executeExpression(pipeline, expressions.before_order_and_select);
executeDistinct(pipeline, true, expressions.selected_columns);
need_second_distinct_pass = query.distinct && pipeline.hasMoreThanOneStream();
}
else
{
need_second_distinct_pass = query.distinct && pipeline.hasMoreThanOneStream();
if (query.group_by_with_totals && !aggregate_final)
executeTotalsAndHaving(pipeline, false, nullptr, aggregate_overflow_row);
}
if (expressions.has_order_by)
{
/** If there is an ORDER BY for distributed query processing,
* but there is no aggregation, then on the remote servers ORDER BY was made
* - therefore, we merge the sorted streams from remote servers.
*/
if (!expressions.first_stage && !expressions.need_aggregate && !(query.group_by_with_totals && !aggregate_final))
executeMergeSorted(pipeline);
else /// Otherwise, just sort.
executeOrder(pipeline);
}
/** Optimization - if there are several sources and there is LIMIT, then first apply the preliminary LIMIT,
* limiting the number of rows in each up to `offset + limit`.
*/
if (query.limit_length && pipeline.hasMoreThanOneStream() && !query.distinct && !expressions.has_limit_by && !settings.extremes)
{
executePreLimit(pipeline);
}
if (need_second_distinct_pass
|| query.limit_length
|| query.limit_by_expression_list
|| pipeline.stream_with_non_joined_data)
{
need_merge_streams = true;
}
if (need_merge_streams)
executeUnion(pipeline);
/** If there was more than one stream,
* then DISTINCT needs to be performed once again after merging all streams.
*/
if (need_second_distinct_pass)
executeDistinct(pipeline, false, expressions.selected_columns);
if (expressions.has_limit_by)
{
executeExpression(pipeline, expressions.before_limit_by);
executeLimitBy(pipeline);
}
/** We must do projection after DISTINCT because projection may remove some columns.
*/
executeProjection(pipeline, expressions.final_projection);
/** Extremes are calculated before LIMIT, but after LIMIT BY. This is Ok.
*/
executeExtremes(pipeline);
executeLimit(pipeline);
}
}
if (!expressions.subqueries_for_sets.empty())
executeSubqueriesInSetsAndJoins(pipeline, expressions.subqueries_for_sets);
}
static void getLimitLengthAndOffset(ASTSelectQuery & query, size_t & length, size_t & offset)
{
length = 0;
offset = 0;
if (query.limit_length)
{
length = safeGet<UInt64>(typeid_cast<ASTLiteral &>(*query.limit_length).value);
if (query.limit_offset)
offset = safeGet<UInt64>(typeid_cast<ASTLiteral &>(*query.limit_offset).value);
}
}
QueryProcessingStage::Enum InterpreterSelectQuery::executeFetchColumns(Pipeline & pipeline, bool dry_run)
{
/// List of columns to read to execute the query.
Names required_columns = query_analyzer->getRequiredSourceColumns();
/// Actions to calculate ALIAS if required.
ExpressionActionsPtr alias_actions;
/// Are ALIAS columns required for query execution?
auto alias_columns_required = false;
if (storage && !storage->getColumns().aliases.empty())
{
const auto & column_defaults = storage->getColumns().defaults;
for (const auto & column : required_columns)
{
const auto default_it = column_defaults.find(column);
if (default_it != std::end(column_defaults) && default_it->second.kind == ColumnDefaultKind::Alias)
{
alias_columns_required = true;
break;
}
}
if (alias_columns_required)
{
/// We will create an expression to return all the requested columns, with the calculation of the required ALIAS columns.
auto required_columns_expr_list = std::make_shared<ASTExpressionList>();
for (const auto & column : required_columns)
{
const auto default_it = column_defaults.find(column);
if (default_it != std::end(column_defaults) && default_it->second.kind == ColumnDefaultKind::Alias)
required_columns_expr_list->children.emplace_back(setAlias(default_it->second.expression->clone(), column));
else
required_columns_expr_list->children.emplace_back(std::make_shared<ASTIdentifier>(column));
}
alias_actions = ExpressionAnalyzer(required_columns_expr_list, context, storage).getActions(true);
/// The set of required columns could be added as a result of adding an action to calculate ALIAS.
required_columns = alias_actions->getRequiredColumns();
}
}
/// The subquery interpreter, if the subquery
std::unique_ptr<InterpreterSelectWithUnionQuery> interpreter_subquery;
auto query_table = query.table();
if (query_table && typeid_cast<ASTSelectWithUnionQuery *>(query_table.get()))
{
/** There are no limits on the maximum size of the result for the subquery.
* Since the result of the query is not the result of the entire query.
*/
Context subquery_context = context;
Settings subquery_settings = context.getSettings();
subquery_settings.max_result_rows = 0;
subquery_settings.max_result_bytes = 0;
/// The calculation of extremes does not make sense and is not necessary (if you do it, then the extremes of the subquery can be taken for whole query).
subquery_settings.extremes = false;
subquery_context.setSettings(subquery_settings);
interpreter_subquery = std::make_unique<InterpreterSelectWithUnionQuery>(
query_table,
subquery_context,
required_columns,
QueryProcessingStage::Complete,
subquery_depth + 1);
/// If there is an aggregation in the outer query, WITH TOTALS is ignored in the subquery.
if (query_analyzer->hasAggregation())
interpreter_subquery->ignoreWithTotals();
}
const Settings & settings = context.getSettingsRef();
/// Limitation on the number of columns to read.
/// It's not applied in 'dry_run' mode, because the query could be analyzed without removal of unnecessary columns.
if (!dry_run && settings.max_columns_to_read && required_columns.size() > settings.max_columns_to_read)
throw Exception("Limit for number of columns to read exceeded. "
"Requested: "
+ toString(required_columns.size())
+ ", maximum: " + settings.max_columns_to_read.toString(),
ErrorCodes::TOO_MANY_COLUMNS);
size_t limit_length = 0;
size_t limit_offset = 0;
getLimitLengthAndOffset(query, limit_length, limit_offset);
/** With distributed query processing, almost no computations are done in the threads,
* but wait and receive data from remote servers.
* If we have 20 remote servers, and max_threads = 8, then it would not be very good
* connect and ask only 8 servers at a time.
* To simultaneously query more remote servers,
* instead of max_threads, max_distributed_connections is used.
*/
bool is_remote = false;
if (storage && storage->isRemote())
{
is_remote = true;
max_streams = settings.max_distributed_connections;
}
size_t max_block_size = settings.max_block_size;
/** Optimization - if not specified DISTINCT, WHERE, GROUP, HAVING, ORDER, LIMIT BY but LIMIT is specified, and limit + offset < max_block_size,
* then as the block size we will use limit + offset (not to read more from the table than requested),
* and also set the number of threads to 1.
*/
if (!query.distinct
&& !query.prewhere_expression
&& !query.where_expression
&& !query.group_expression_list
&& !query.having_expression
&& !query.order_expression_list
&& !query.limit_by_expression_list
&& query.limit_length
&& !query_analyzer->hasAggregation()
&& limit_length + limit_offset < max_block_size)
{
max_block_size = limit_length + limit_offset;
max_streams = 1;
}
QueryProcessingStage::Enum from_stage = QueryProcessingStage::FetchColumns;
/// Initialize the initial data streams to which the query transforms are superimposed. Table or subquery or prepared input?
if (!pipeline.streams.empty())
{
/// Prepared input.
}
else if (interpreter_subquery)
{
/// Subquery.
if (!dry_run)
pipeline.streams = interpreter_subquery->executeWithMultipleStreams();
else
pipeline.streams.emplace_back(std::make_shared<NullBlockInputStream>(interpreter_subquery->getSampleBlock()));
}
else if (storage)
{
/// Table.
if (max_streams == 0)
throw Exception("Logical error: zero number of streams requested", ErrorCodes::LOGICAL_ERROR);
/// If necessary, we request more sources than the number of threads - to distribute the work evenly over the threads.
if (max_streams > 1 && !is_remote)
max_streams *= settings.max_streams_to_max_threads_ratio;
query_analyzer->makeSetsForIndex();
SelectQueryInfo query_info;
query_info.query = query_ptr;
query_info.sets = query_analyzer->getPreparedSets();
query_info.mvcc_query_info = std::make_unique<MvccQueryInfo>(settings.resolve_locks, settings.read_tso);
const String & request_str = settings.regions;
if (!request_str.empty())
{
TableID table_id = InvalidTableID;
if (auto managed_storage = std::dynamic_pointer_cast<IManageableStorage>(storage); managed_storage)
{
table_id = managed_storage->getTableInfo().id;
}
else
{
throw Exception("Not supported request on non-manageable storage");
}
Poco::JSON::Parser parser;
Poco::Dynamic::Var result = parser.parse(request_str);
auto obj = result.extract<Poco::JSON::Object::Ptr>();
Poco::Dynamic::Var regions_obj = obj->get("regions");
auto arr = regions_obj.extract<Poco::JSON::Array::Ptr>();
for (size_t i = 0; i < arr->size(); i++)
{
auto str = arr->getElement<String>(i);
::metapb::Region region;
::google::protobuf::TextFormat::ParseFromString(str, ®ion);
const auto & epoch = region.region_epoch();
RegionQueryInfo info(region.id(), epoch.version(), epoch.conf_ver(), table_id);
if (const auto & managed_storage = std::dynamic_pointer_cast<IManageableStorage>(storage))
{
// Extract the handle range according to current table
TiKVKey start_key = RecordKVFormat::encodeAsTiKVKey(region.start_key());
TiKVKey end_key = RecordKVFormat::encodeAsTiKVKey(region.end_key());
RegionRangeKeys region_range(std::move(start_key), std::move(end_key));
info.range_in_table = region_range.rawKeys();
}
query_info.mvcc_query_info->regions_query_info.push_back(info);
}
if (query_info.mvcc_query_info->regions_query_info.empty())
throw Exception("[InterpreterSelectQuery::executeFetchColumns] no region query", ErrorCodes::LOGICAL_ERROR);
query_info.mvcc_query_info->concurrent = 0.0;
}
/// PARTITION SELECT only supports MergeTree family now.
if (const auto * select_query = typeid_cast<const ASTSelectQuery *>(query_info.query.get()))
{
if (select_query->partition_expression_list)
{
throw Exception("PARTITION SELECT only supports MergeTree family.");
}
}
if (!dry_run)
{
LearnerReadSnapshot learner_read_snapshot;
// TODO: Note that we should do learner read without holding table's structure lock,
// or there will be deadlocks between learner read and raft threads (#815).
// Here we do not follow the rule because this is not use in production environment
// and it is hard to move learner read before acuqiring table's lock.
// Do learner read only For DeltaTree.
auto & tmt = context.getTMTContext();
if (auto managed_storage = std::dynamic_pointer_cast<IManageableStorage>(storage);
managed_storage && managed_storage->engineType() == TiDB::StorageEngine::DT)
{
if (const auto * select_query = typeid_cast<const ASTSelectQuery *>(query_info.query.get()))
{
// With `no_kvsotre` is true, we do not do learner read
if (likely(!select_query->no_kvstore))
{
auto table_info = managed_storage->getTableInfo();
learner_read_snapshot = doLearnerRead(table_info.id, *query_info.mvcc_query_info, max_streams, false, context, log);
}
}
}
pipeline.streams = storage->read(required_columns, query_info, context, from_stage, max_block_size, max_streams);
if (!learner_read_snapshot.empty())
{
validateQueryInfo(*query_info.mvcc_query_info, learner_read_snapshot, tmt, log);
}
}
if (pipeline.streams.empty())
pipeline.streams.emplace_back(std::make_shared<NullBlockInputStream>(storage->getSampleBlockForColumns(required_columns)));
pipeline.transform([&](auto & stream) {
stream->addTableLock(table_lock);
});
/// Set the limits and quota for reading data, the speed and time of the query.
{
IProfilingBlockInputStream::LocalLimits limits;
limits.mode = IProfilingBlockInputStream::LIMITS_TOTAL;
limits.size_limits = SizeLimits(settings.max_rows_to_read, settings.max_bytes_to_read, settings.read_overflow_mode);
limits.max_execution_time = settings.max_execution_time;
limits.timeout_overflow_mode = settings.timeout_overflow_mode;
/** Quota and minimal speed restrictions are checked on the initiating server of the request, and not on remote servers,
* because the initiating server has a summary of the execution of the request on all servers.
*
* But limits on data size to read and maximum execution time are reasonable to check both on initiator and
* additionally on each remote server, because these limits are checked per block of data processed,
* and remote servers may process way more blocks of data than are received by initiator.
*/
if (to_stage == QueryProcessingStage::Complete)
{
limits.min_execution_speed = settings.min_execution_speed;
limits.timeout_before_checking_execution_speed = settings.timeout_before_checking_execution_speed;
}
QuotaForIntervals & quota = context.getQuota();
pipeline.transform([&](auto & stream) {
if (auto * p_stream = dynamic_cast<IProfilingBlockInputStream *>(stream.get()))
{
p_stream->setLimits(limits);
if (to_stage == QueryProcessingStage::Complete)
p_stream->setQuota(quota);
}
});
}
}
else
throw Exception("Logical error in InterpreterSelectQuery: nowhere to read", ErrorCodes::LOGICAL_ERROR);
/// Aliases in table declaration.
if (from_stage == QueryProcessingStage::FetchColumns && alias_actions)
{
pipeline.transform([&](auto & stream) {
stream = std::make_shared<ExpressionBlockInputStream>(stream, alias_actions, /*req_id=*/"");
});
}
return from_stage;
}
void InterpreterSelectQuery::executeWhere(Pipeline & pipeline, const ExpressionActionsPtr & expression)
{
pipeline.transform([&](auto & stream) {
stream = std::make_shared<FilterBlockInputStream>(stream, expression, query.where_expression->getColumnName(), /*req_id=*/"");
});
}
void InterpreterSelectQuery::executeAggregation(Pipeline & pipeline, const ExpressionActionsPtr & expression, const FileProviderPtr & file_provider, bool overflow_row, bool final)
{
pipeline.transform([&](auto & stream) {
stream = std::make_shared<ExpressionBlockInputStream>(stream, expression, /*req_id=*/"");
});
Names key_names;
AggregateDescriptions aggregates;
query_analyzer->getAggregateInfo(key_names, aggregates);
Block header = pipeline.firstStream()->getHeader();
ColumnNumbers keys;
for (const auto & name : key_names)
keys.push_back(header.getPositionByName(name));
for (auto & descr : aggregates)
if (descr.arguments.empty())
for (const auto & name : descr.argument_names)
descr.arguments.push_back(header.getPositionByName(name));
const Settings & settings = context.getSettingsRef();
/** Two-level aggregation is useful in two cases:
* 1. Parallel aggregation is done, and the results should be merged in parallel.
* 2. An aggregation is done with store of temporary data on the disk, and they need to be merged in a memory efficient way.
*/
bool allow_to_use_two_level_group_by = pipeline.streams.size() > 1 || settings.max_bytes_before_external_group_by != 0;
Aggregator::Params params(header, keys, aggregates, overflow_row, settings.max_rows_to_group_by, settings.group_by_overflow_mode, allow_to_use_two_level_group_by ? settings.group_by_two_level_threshold : SettingUInt64(0), allow_to_use_two_level_group_by ? settings.group_by_two_level_threshold_bytes : SettingUInt64(0), settings.max_bytes_before_external_group_by, settings.empty_result_for_aggregation_by_empty_set, context.getTemporaryPath());
/// If there are several sources, then we perform parallel aggregation
if (pipeline.streams.size() > 1)
{
pipeline.firstStream() = std::make_shared<ParallelAggregatingBlockInputStream>(
pipeline.streams,
pipeline.stream_with_non_joined_data,
params,
file_provider,
final,
max_streams,
settings.aggregation_memory_efficient_merge_threads
? static_cast<size_t>(settings.aggregation_memory_efficient_merge_threads)
: static_cast<size_t>(settings.max_threads),
/*req_id=*/"");
pipeline.stream_with_non_joined_data = nullptr;
pipeline.streams.resize(1);
}
else
{
BlockInputStreams inputs;
if (!pipeline.streams.empty())
inputs.push_back(pipeline.firstStream());
else
pipeline.streams.resize(1);
if (pipeline.stream_with_non_joined_data)
inputs.push_back(pipeline.stream_with_non_joined_data);
pipeline.firstStream() = std::make_shared<AggregatingBlockInputStream>(
std::make_shared<ConcatBlockInputStream>(inputs, /*req_id=*/""),
params,
file_provider,
final,
/*req_id=*/"");
pipeline.stream_with_non_joined_data = nullptr;
}
}
void InterpreterSelectQuery::executeMergeAggregated(Pipeline & pipeline, bool overflow_row, bool final)
{
Names key_names;
AggregateDescriptions aggregates;
query_analyzer->getAggregateInfo(key_names, aggregates);
Block header = pipeline.firstStream()->getHeader();
ColumnNumbers keys;
for (const auto & name : key_names)
keys.push_back(header.getPositionByName(name));
/** There are two modes of distributed aggregation.
*
* 1. In different threads read from the remote servers blocks.
* Save all the blocks in the RAM. Merge blocks.
* If the aggregation is two-level - parallelize to the number of buckets.
*
* 2. In one thread, read blocks from different servers in order.
* RAM stores only one block from each server.
* If the aggregation is a two-level aggregation, we consistently merge the blocks of each next level.
*
* The second option consumes less memory (up to 256 times less)
* in the case of two-level aggregation, which is used for large results after GROUP BY,
* but it can work more slowly.
*/
Aggregator::Params params(header, keys, aggregates, overflow_row);
const Settings & settings = context.getSettingsRef();
if (!settings.distributed_aggregation_memory_efficient)
{
/// We union several sources into one, parallelizing the work.
executeUnion(pipeline);
/// Now merge the aggregated blocks
pipeline.firstStream() = std::make_shared<MergingAggregatedBlockInputStream>(pipeline.firstStream(), params, final, settings.max_threads);
}
else
{
pipeline.firstStream() = std::make_shared<MergingAggregatedMemoryEfficientBlockInputStream>(
pipeline.streams,
params,
final,
max_streams,
settings.aggregation_memory_efficient_merge_threads ? static_cast<size_t>(settings.aggregation_memory_efficient_merge_threads) : static_cast<size_t>(settings.max_threads),
/*req_id=*/"");
pipeline.streams.resize(1);
}
}
void InterpreterSelectQuery::executeHaving(Pipeline & pipeline, const ExpressionActionsPtr & expression)
{
pipeline.transform([&](auto & stream) {
stream = std::make_shared<FilterBlockInputStream>(stream, expression, query.having_expression->getColumnName(), /*req_id=*/"");
});
}
void InterpreterSelectQuery::executeTotalsAndHaving(Pipeline & pipeline, bool has_having, const ExpressionActionsPtr & expression, bool overflow_row)
{
executeUnion(pipeline);
const Settings & settings = context.getSettingsRef();
pipeline.firstStream() = std::make_shared<TotalsHavingBlockInputStream>(
pipeline.firstStream(),
overflow_row,
expression,
has_having ? query.having_expression->getColumnName() : "",
settings.totals_mode,
settings.totals_auto_threshold);
}
void InterpreterSelectQuery::executeExpression(Pipeline & pipeline, const ExpressionActionsPtr & expression) // NOLINT
{
pipeline.transform([&](auto & stream) {
stream = std::make_shared<ExpressionBlockInputStream>(stream, expression, /*req_id=*/"");
});
}
static SortDescription getSortDescription(ASTSelectQuery & query)
{
SortDescription order_descr;
order_descr.reserve(query.order_expression_list->children.size());
for (const auto & elem : query.order_expression_list->children)
{
String name = elem->children.front()->getColumnName();
const ASTOrderByElement & order_by_elem = typeid_cast<const ASTOrderByElement &>(*elem);
std::shared_ptr<ICollator> collator;
if (order_by_elem.collation)
collator = std::make_shared<Collator>(typeid_cast<const ASTLiteral &>(*order_by_elem.collation).value.get<String>());
order_descr.emplace_back(name, order_by_elem.direction, order_by_elem.nulls_direction, collator);
}
return order_descr;
}
static size_t getLimitForSorting(ASTSelectQuery & query)
{
/// Partial sort can be done if there is LIMIT but no DISTINCT or LIMIT BY.
size_t limit = 0;
if (!query.distinct && !query.limit_by_expression_list)
{
size_t limit_length = 0;
size_t limit_offset = 0;
getLimitLengthAndOffset(query, limit_length, limit_offset);
limit = limit_length + limit_offset;
}
return limit;
}
void InterpreterSelectQuery::executeOrder(Pipeline & pipeline)
{
SortDescription order_descr = getSortDescription(query);
size_t limit = getLimitForSorting(query);
const Settings & settings = context.getSettingsRef();
pipeline.transform([&](auto & stream) {
auto sorting_stream = std::make_shared<PartialSortingBlockInputStream>(stream, order_descr, /*req_id=*/"", limit);
/// Limits on sorting
IProfilingBlockInputStream::LocalLimits limits;
limits.mode = IProfilingBlockInputStream::LIMITS_TOTAL;
limits.size_limits = SizeLimits(settings.max_rows_to_sort, settings.max_bytes_to_sort, settings.sort_overflow_mode);
sorting_stream->setLimits(limits);
stream = sorting_stream;
});
/// If there are several streams, we merge them into one
executeUnion(pipeline);
/// Merge the sorted blocks.
pipeline.firstStream() = std::make_shared<MergeSortingBlockInputStream>(
pipeline.firstStream(),
order_descr,
settings.max_block_size,
limit,
settings.max_bytes_before_external_sort,
context.getTemporaryPath(),
/*req_id=*/"");
}
void InterpreterSelectQuery::executeMergeSorted(Pipeline & pipeline)
{
SortDescription order_descr = getSortDescription(query);
size_t limit = getLimitForSorting(query);
const Settings & settings = context.getSettingsRef();
/// If there are several streams, then we merge them into one
if (pipeline.hasMoreThanOneStream())
{
/** MergingSortedBlockInputStream reads the sources sequentially.
* To make the data on the remote servers prepared in parallel, we wrap it in AsynchronousBlockInputStream.
*/
pipeline.transform([&](auto & stream) {
stream = std::make_shared<AsynchronousBlockInputStream>(stream);
});
/// Merge the sorted sources into one sorted source.
pipeline.firstStream() = std::make_shared<MergingSortedBlockInputStream>(pipeline.streams, order_descr, settings.max_block_size, limit);
pipeline.streams.resize(1);
}
}
void InterpreterSelectQuery::executeProjection(Pipeline & pipeline, const ExpressionActionsPtr & expression) // NOLINT
{
pipeline.transform([&](auto & stream) {
stream = std::make_shared<ExpressionBlockInputStream>(stream, expression, /*req_id=*/"");
});
}
void InterpreterSelectQuery::executeDistinct(Pipeline & pipeline, bool before_order, Names columns)
{
if (query.distinct)
{
const Settings & settings = context.getSettingsRef();
size_t limit_length = 0;
size_t limit_offset = 0;
getLimitLengthAndOffset(query, limit_length, limit_offset);
size_t limit_for_distinct = 0;
/// If after this stage of DISTINCT ORDER BY is not executed, then you can get no more than limit_length + limit_offset of different rows.
if (!query.order_expression_list || !before_order)
limit_for_distinct = limit_length + limit_offset;
pipeline.transform([&](auto & stream) {
SizeLimits limits(settings.max_rows_in_distinct, settings.max_bytes_in_distinct, settings.distinct_overflow_mode);
if (stream->isGroupedOutput())
stream = std::make_shared<DistinctSortedBlockInputStream>(stream, limits, limit_for_distinct, columns);
else
stream = std::make_shared<DistinctBlockInputStream>(stream, limits, limit_for_distinct, columns);
});
}
}
void InterpreterSelectQuery::executeUnion(Pipeline & pipeline)
{
/// If there are still several streams, then we combine them into one
if (pipeline.hasMoreThanOneStream())
{
pipeline.firstStream() = std::make_shared<UnionBlockInputStream<>>(
pipeline.streams,
pipeline.stream_with_non_joined_data,
max_streams,
/*req_id=*/"");
pipeline.stream_with_non_joined_data = nullptr;
pipeline.streams.resize(1);
}
else if (pipeline.stream_with_non_joined_data)
{
pipeline.streams.push_back(pipeline.stream_with_non_joined_data);
pipeline.stream_with_non_joined_data = nullptr;
}
}
/// Preliminary LIMIT - is used in every source, if there are several sources, before they are combined.
void InterpreterSelectQuery::executePreLimit(Pipeline & pipeline)
{
size_t limit_length = 0;
size_t limit_offset = 0;
getLimitLengthAndOffset(query, limit_length, limit_offset);
/// If there is LIMIT
if (query.limit_length)
{
pipeline.transform([&](auto & stream) {
stream = std::make_shared<LimitBlockInputStream>(stream, limit_length + limit_offset, 0, /*req_id=*/"", false);
});
}
}
void InterpreterSelectQuery::executeLimitBy(Pipeline & pipeline) // NOLINT
{
if (!query.limit_by_value || !query.limit_by_expression_list)
return;
Names columns;
for (const auto & elem : query.limit_by_expression_list->children)
columns.emplace_back(elem->getColumnName());
auto value = safeGet<UInt64>(typeid_cast<ASTLiteral &>(*query.limit_by_value).value);
pipeline.transform([&](auto & stream) {
stream = std::make_shared<LimitByBlockInputStream>(stream, value, columns);
});
}
bool hasWithTotalsInAnySubqueryInFromClause(const ASTSelectQuery & query)
{
if (query.group_by_with_totals)
return true;
/** NOTE You can also check that the table in the subquery is distributed, and that it only looks at one shard.
* In other cases, totals will be computed on the initiating server of the query, and it is not necessary to read the data to the end.
*/
auto query_table = query.table();
if (query_table)
{
const auto * ast_union = typeid_cast<const ASTSelectWithUnionQuery *>(query_table.get());
if (ast_union)
{
for (const auto & elem : ast_union->list_of_selects->children)
if (hasWithTotalsInAnySubqueryInFromClause(typeid_cast<const ASTSelectQuery &>(*elem)))
return true;
}
}
return false;
}
void InterpreterSelectQuery::executeLimit(Pipeline & pipeline)
{
size_t limit_length = 0;
size_t limit_offset = 0;
getLimitLengthAndOffset(query, limit_length, limit_offset);
/// If there is LIMIT
if (query.limit_length)
{
/** Rare case:
* if there is no WITH TOTALS and there is a subquery in FROM, and there is WITH TOTALS on one of the levels,
* then when using LIMIT, you should read the data to the end, rather than cancel the query earlier,
* because if you cancel the query, we will not get `totals` data from the remote server.
*
* Another case:
* if there is WITH TOTALS and there is no ORDER BY, then read the data to the end,
* otherwise TOTALS is counted according to incomplete data.
*/
bool always_read_till_end = false;
if (query.group_by_with_totals && !query.order_expression_list)
always_read_till_end = true;
if (!query.group_by_with_totals && hasWithTotalsInAnySubqueryInFromClause(query))
always_read_till_end = true;
pipeline.transform([&](auto & stream) {
stream = std::make_shared<LimitBlockInputStream>(stream, limit_length, limit_offset, /*req_id=*/"", always_read_till_end);
});
}
}
void InterpreterSelectQuery::executeExtremes(Pipeline & pipeline)
{
if (!context.getSettingsRef().extremes)
return;
pipeline.transform([&](auto & stream) {
if (auto * p_stream = dynamic_cast<IProfilingBlockInputStream *>(stream.get()))
p_stream->enableExtremes();
});
}
void InterpreterSelectQuery::executeSubqueriesInSetsAndJoins(Pipeline & pipeline, SubqueriesForSets & subqueries_for_sets)
{
const Settings & settings = context.getSettingsRef();
executeUnion(pipeline);
pipeline.firstStream() = std::make_shared<CreatingSetsBlockInputStream>(
pipeline.firstStream(),
subqueries_for_sets,
SizeLimits(settings.max_rows_to_transfer, settings.max_bytes_to_transfer, settings.transfer_overflow_mode),
/*req_id=*/"");
}
void InterpreterSelectQuery::ignoreWithTotals()
{
query.group_by_with_totals = false;
}
void InterpreterSelectQuery::initSettings()
{
if (query.settings)
InterpreterSetQuery(query.settings, context).executeForCurrentContext();
}
} // namespace DB
| 40.778582 | 449 | 0.670452 | pingcap |
51b8a7338093cc50265f302911d9b11b6fca5810 | 207 | cpp | C++ | VerifEye/main.cpp | sanket26jadhav/VerifEye | 493f9ef0872b20ad482fcec0fa60306457ec44c7 | [
"Apache-2.0"
] | 4 | 2018-04-07T11:04:51.000Z | 2018-12-27T15:34:14.000Z | VerifEye/main.cpp | sanket26jadhav/VerifEye | 493f9ef0872b20ad482fcec0fa60306457ec44c7 | [
"Apache-2.0"
] | null | null | null | VerifEye/main.cpp | sanket26jadhav/VerifEye | 493f9ef0872b20ad482fcec0fa60306457ec44c7 | [
"Apache-2.0"
] | 3 | 2018-04-07T06:44:15.000Z | 2018-10-27T08:15:49.000Z | #include "VerifEye.h"
#include <direct.h>
#include <QtWidgets/QApplication>
int main(int argc, char *argv[])
{
_mkdir("./data-db");
QApplication a(argc, argv);
VerifEye w;
w.show();
return a.exec();
}
| 15.923077 | 33 | 0.666667 | sanket26jadhav |
51b90dfb14d924ecafc66fe11b4134cdcfc78a8a | 903 | hpp | C++ | gearoenix/glc3/pipeline/gx-glc3-pip-skybox-cube-resource-set.hpp | Hossein-Noroozpour/gearoenix | c8fa8b8946c03c013dad568d6d7a97d81097c051 | [
"BSD-Source-Code"
] | 35 | 2018-01-07T02:34:38.000Z | 2022-02-09T05:19:03.000Z | gearoenix/glc3/pipeline/gx-glc3-pip-skybox-cube-resource-set.hpp | Hossein-Noroozpour/gearoenix | c8fa8b8946c03c013dad568d6d7a97d81097c051 | [
"BSD-Source-Code"
] | 111 | 2017-09-20T09:12:36.000Z | 2020-12-27T12:52:03.000Z | gearoenix/glc3/pipeline/gx-glc3-pip-skybox-cube-resource-set.hpp | Hossein-Noroozpour/gearoenix | c8fa8b8946c03c013dad568d6d7a97d81097c051 | [
"BSD-Source-Code"
] | 5 | 2020-02-11T11:17:37.000Z | 2021-01-08T17:55:43.000Z | #ifndef GEAROENIX_GLC3_PIPELINE_SKYBOX_CUBE_RESOURCE_SET_HPP
#define GEAROENIX_GLC3_PIPELINE_SKYBOX_CUBE_RESOURCE_SET_HPP
#include "../../core/gx-cr-build-configuration.hpp"
#ifdef GX_USE_OPENGL_CLASS_3
#include "../../core/sync/gx-cr-sync-end-caller.hpp"
#include "../../gl/gx-gl-types.hpp"
#include "../../render/pipeline/gx-rnd-pip-skybox-cube-resource-set.hpp"
namespace gearoenix::glc3::shader {
class SkyboxCube;
}
namespace gearoenix::glc3::pipeline {
class SkyboxCube;
class ResourceSet;
class SkyboxCubeResourceSet final : public render::pipeline::SkyboxCubeResourceSet {
GX_GET_UCPTR_PRV(glc3::pipeline::ResourceSet, base)
public:
SkyboxCubeResourceSet(const std::shared_ptr<shader::SkyboxCube>& shd, std::shared_ptr<SkyboxCube const> pip) noexcept;
~SkyboxCubeResourceSet() noexcept final;
void bind_final(gl::uint& bound_shader_program) const noexcept;
};
}
#endif
#endif
| 33.444444 | 122 | 0.781838 | Hossein-Noroozpour |
51b95da646c64f4066b8b497711aab313801eafb | 363 | hpp | C++ | src/Traits.hpp | spraetor/amdis2 | 53c45c81a65752a8fafbb54f9ae6724a86639dcd | [
"MIT"
] | 2 | 2018-07-04T16:44:04.000Z | 2021-01-03T07:26:27.000Z | src/Traits.hpp | spraetor/amdis2 | 53c45c81a65752a8fafbb54f9ae6724a86639dcd | [
"MIT"
] | null | null | null | src/Traits.hpp | spraetor/amdis2 | 53c45c81a65752a8fafbb54f9ae6724a86639dcd | [
"MIT"
] | null | null | null | #pragma once
// #include <iostream>
#include "AMDiS_fwd.hpp"
#include "FixVec.hpp"
#include "MatrixVector.hpp"
#include "traits/basic.hpp"
#include "traits/category.hpp"
#include "traits/meta_basic.hpp"
#include "traits/num_cols.hpp"
#include "traits/num_rows.hpp"
#include "traits/size.hpp"
#include "traits/tag.hpp"
namespace AMDiS {} // end namespace AMDiS
| 21.352941 | 41 | 0.746556 | spraetor |
51c10b57cbc80539fcf325f830bc4670dd13c73f | 435 | cpp | C++ | Torre.cpp | JasonDeras/P3Lab9_JasonDeras9 | 4bd160482644d398476ecbecca77113a540aace5 | [
"MIT"
] | null | null | null | Torre.cpp | JasonDeras/P3Lab9_JasonDeras9 | 4bd160482644d398476ecbecca77113a540aace5 | [
"MIT"
] | null | null | null | Torre.cpp | JasonDeras/P3Lab9_JasonDeras9 | 4bd160482644d398476ecbecca77113a540aace5 | [
"MIT"
] | null | null | null | #include<iostream>
#include<string>
#include "Pieza.cpp"
#ifndef TORRE_CPP
#define TORRE_CPP
using namespace std;
class Torre:public Pieza{
protected:
public:
Torre():Pieza("Torre"){
}//Fin del constructor simple
bool Validar_Movimiento(int x, int y){
bool valido = false;
if( (*this).getY() == y || (*this).getX() == x ) valido = true;
return valido;
}
~Torre(){
}//Destructor
};
#endif | 14.5 | 69 | 0.622989 | JasonDeras |
51c42aa213540dfc3d0625f1768fc1d7c78d45e2 | 1,362 | cpp | C++ | c/arr_of_ptrs_to_funcs.cpp | bheckel/code | 98309e8aa145901e49460546643c911eaaff54e6 | [
"Apache-2.0"
] | 1 | 2019-08-11T00:39:34.000Z | 2019-08-11T00:39:34.000Z | c/arr_of_ptrs_to_funcs.cpp | bheckel/code | 98309e8aa145901e49460546643c911eaaff54e6 | [
"Apache-2.0"
] | null | null | null | c/arr_of_ptrs_to_funcs.cpp | bheckel/code | 98309e8aa145901e49460546643c911eaaff54e6 | [
"Apache-2.0"
] | 1 | 2020-07-28T05:58:47.000Z | 2020-07-28T05:58:47.000Z | //////////////////////////////////////////////////////////////////////////////
// Name: arr_of_ptrs_to_funcs.cpp
//
// Summary: Using an array of pointers to functions.
//
// Creates some dummy functions using a preprocessor macro, then
// creates an array of pointers to those functions using automatic
// aggregate initialization. As you can see, it is easy to add or
// remove functions from the table (and thus, functionality from the
// program) by changing a small amount of code.
//
// Adapted: Wed 17 Oct 2001 10:24:57 (Bob Heckel -- Thinking in C++)
//////////////////////////////////////////////////////////////////////////////
#include <iostream>
using namespace std;
// A macro to define dummy functions (uses preprocessor's stringizer feature):
#define DF(N) void N() { \
cout << "function " #N " called..." << endl; \
}
DF(a); DF(b); DF(c); DF(d); DF(e); DF(f); DF(g);
void (*func_table[])() = { a, b, c, d, e, f, g };
int main() {
while( 1 ) {
cout << "press a key from 'a' to 'g' or q to quit" << endl;
char c, cr;
cin.get(c); cin.get(cr); // second one for tossing CR out
if ( c == 'q' )
break; // out of while( 1 )
if ( c < 'a' || c > 'g' )
continue;
(*func_table[c - 'a'])();
}
}
| 31.674419 | 78 | 0.490455 | bheckel |
51c58ff0cb05e1a6ccc41dd496e0e79b871e4ed7 | 817 | cpp | C++ | src/shapes/cubic_asymmetric_vertex.cpp | kariem2k/rive-cpp | f58c3b3d48ea03947a76971bce17e7f567cf0de0 | [
"MIT"
] | 139 | 2020-08-17T20:10:24.000Z | 2022-03-28T12:22:44.000Z | src/shapes/cubic_asymmetric_vertex.cpp | kariem2k/rive-cpp | f58c3b3d48ea03947a76971bce17e7f567cf0de0 | [
"MIT"
] | 89 | 2020-08-28T16:41:01.000Z | 2022-03-28T19:10:49.000Z | src/shapes/cubic_asymmetric_vertex.cpp | kariem2k/rive-cpp | f58c3b3d48ea03947a76971bce17e7f567cf0de0 | [
"MIT"
] | 19 | 2020-10-19T00:54:40.000Z | 2022-02-28T05:34:17.000Z | #include "rive/shapes/cubic_asymmetric_vertex.hpp"
#include "rive/math/vec2d.hpp"
#include <cmath>
using namespace rive;
void CubicAsymmetricVertex::computeIn()
{
Vec2D::add(m_InPoint,
Vec2D(x(), y()),
Vec2D(cos(rotation()) * -inDistance(),
sin(rotation()) * -inDistance()));
}
void CubicAsymmetricVertex::computeOut()
{
Vec2D::add(m_OutPoint,
Vec2D(x(), y()),
Vec2D(cos(rotation()) * outDistance(),
sin(rotation()) * outDistance()));
}
void CubicAsymmetricVertex::rotationChanged()
{
m_InValid = false;
m_OutValid = false;
markPathDirty();
}
void CubicAsymmetricVertex::inDistanceChanged()
{
m_InValid = false;
markPathDirty();
}
void CubicAsymmetricVertex::outDistanceChanged()
{
m_OutValid = false;
markPathDirty();
} | 21.5 | 52 | 0.651163 | kariem2k |
51c8c220b398d34ebd3241f1f7d76fd3ba01ce5c | 449 | cpp | C++ | MC/MC/app/app.cpp | yunwei37/mc | 03fa8aaffaff1f518a5dc07500e05f6beb5ce16d | [
"MIT"
] | 1 | 2021-11-18T04:55:29.000Z | 2021-11-18T04:55:29.000Z | MC/MC/app/app.cpp | yunwei37/mc | 03fa8aaffaff1f518a5dc07500e05f6beb5ce16d | [
"MIT"
] | null | null | null | MC/MC/app/app.cpp | yunwei37/mc | 03fa8aaffaff1f518a5dc07500e05f6beb5ce16d | [
"MIT"
] | 3 | 2020-07-30T08:57:59.000Z | 2022-03-17T04:27:34.000Z | #include "app.h"
App::App()
{
if ((window = ViewModel::createViewModel()) == NULL) {
exit(-1);
}
glfwSetFramebufferSizeCallback(window, &ViewModel::framebuffer_size_callback);
glfwSetCursorPosCallback(window, &ViewModel::mouse_move_callback);
glfwSetScrollCallback(window, &ViewModel::scroll_callback);
glfwSetMouseButtonCallback(window, &ViewModel::mouse_click_callback);
}
App::~App()
{
}
int App::run()
{
return ViewModel::run();
}
| 19.521739 | 79 | 0.737194 | yunwei37 |
51c93424fa96d9fa33a4d095bd18aed41d89f8fc | 1,295 | cpp | C++ | src/paint/insets.cpp | tralf-strues/simple-gui-library | cf72b11d0d245d1a1fefbae10e4aa7fb9e763bff | [
"MIT"
] | null | null | null | src/paint/insets.cpp | tralf-strues/simple-gui-library | cf72b11d0d245d1a1fefbae10e4aa7fb9e763bff | [
"MIT"
] | null | null | null | src/paint/insets.cpp | tralf-strues/simple-gui-library | cf72b11d0d245d1a1fefbae10e4aa7fb9e763bff | [
"MIT"
] | null | null | null | /**
* @author Nikita Mochalov (github.com/tralf-strues)
* @file insets.cpp
* @date 2021-11-06
*
* @copyright Copyright (c) 2021
*/
#include "paint/insets.h"
namespace Sgl
{
const Insets Insets::EMPTY = Insets{0, 0, 0, 0};
Insets::Insets(int32_t top, int32_t right, int32_t bottom, int32_t left)
: top(top), right(right), bottom(bottom), left(left) {}
Insets::Insets(int32_t topBottom, int32_t rightLeft)
: Insets(topBottom, rightLeft, topBottom, rightLeft) {}
Insets::Insets(int32_t inset)
: Insets(inset, inset) {}
Insets& Insets::operator+=(const Insets& second)
{
top += second.top;
right += second.right;
bottom += second.bottom;
left += second.left;
return *this;
}
Insets& Insets::operator-=(const Insets& second)
{
top -= second.top;
right -= second.right;
bottom -= second.bottom;
left -= second.left;
return *this;
}
Insets operator+(const Insets& first, const Insets& second)
{
Insets sum{first};
sum += second;
return sum;
}
Insets operator-(const Insets& first, const Insets& second)
{
Insets dif{first};
dif -= second;
return dif;
}
} | 21.949153 | 76 | 0.573745 | tralf-strues |
51c938dfefd58fca698bbb36b0f5270cf09aa717 | 383 | cpp | C++ | common/os/file.cpp | JustSlavic/gl2 | 1b4752d3273a1e401c970e18ae7151bba004a4ec | [
"MIT"
] | null | null | null | common/os/file.cpp | JustSlavic/gl2 | 1b4752d3273a1e401c970e18ae7151bba004a4ec | [
"MIT"
] | 2 | 2021-05-29T20:34:50.000Z | 2021-05-29T20:39:25.000Z | common/os/file.cpp | JustSlavic/gl2 | 1b4752d3273a1e401c970e18ae7151bba004a4ec | [
"MIT"
] | null | null | null | #include "file.hpp"
namespace os {
#ifdef PLATFORM_LINUX
#include "linux/file.cpp"
#endif
#ifdef PLATFORM_WINDOWS
#include "windows/file.cpp"
#endif
#ifdef PLATFORM_APPLE
#error "Path for APPLE is not implemented!"
// #include "apple/path.cpp"
#endif
template <>
i32 file::writer::write (i32 value) {
ASSERT(descriptor);
return fprintf(descriptor, "%d", value);
}
} // os
| 13.678571 | 43 | 0.710183 | JustSlavic |
51ca8f9c528915e8dba94ce7213f68b8828ac494 | 1,373 | cpp | C++ | interviews/ClevestInterview/tester/tester/main.cpp | Kiandr/dataStructure | 5cf8bd07df1c115cac9fcc69ae359500a72ad986 | [
"Apache-2.0"
] | null | null | null | interviews/ClevestInterview/tester/tester/main.cpp | Kiandr/dataStructure | 5cf8bd07df1c115cac9fcc69ae359500a72ad986 | [
"Apache-2.0"
] | null | null | null | interviews/ClevestInterview/tester/tester/main.cpp | Kiandr/dataStructure | 5cf8bd07df1c115cac9fcc69ae359500a72ad986 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <fstream>
#include <vector>
#include<algorithm>
#include <iostream>
#include <string>
// Solution: Q1
long MeterReader(char *array) {
long visitedHouses = 1;
long x = 0;
long y = 0;
std::pair<long, long> coordinate;
std::vector<std::pair<long, long> > myList;
char *prt = array;
std::pair<int, int>(x, y);
while (prt != NULL && *prt != '\0') {
if (*prt == '^')
coordinate.second++;
if (*prt == 'v')
coordinate.second--;
if (*prt == '>')
coordinate.first++;
if (*prt == '<')
coordinate.first--;
auto res = std::find(myList.begin(), myList.end(), coordinate);
if (res == myList.end())
myList.push_back(coordinate);
prt++;
}
for (unsigned i =0; i< myList.size(); i++)
{
std::cout << myList.at(i).first<<myList.at(i).second<<std::endl;
}
return myList.size();
}
int main() {
std::ifstream ifs("question02_input.txt");
std::string s;
getline(ifs, s, (char)ifs.eof());
// checking if the file was opened properly!
// std::cout<<s;
int n = 10;
//n = s.length();
// declaring character array
char * char_array = new char[s.length() + 1];
//strcpy(char_array, s.c_str());
// copying the contents of the point array
strcpy(char_array, s.c_str());
char myArray[] = "^v^v^v";
printf("Numberof houses I have visisted is %ld", MeterReader(char_array));
return 0;
}
| 17.831169 | 75 | 0.608886 | Kiandr |
51ce6e0d46e3a89ff529abb7b3055475b78c418e | 481 | cpp | C++ | src/false_object.cpp | scwfri/natalie | 11e874607a8ac7b934e57c4c7e5790623afaee7a | [
"MIT"
] | 7 | 2022-03-08T08:47:54.000Z | 2022-03-29T15:08:36.000Z | src/false_object.cpp | scwfri/natalie | 11e874607a8ac7b934e57c4c7e5790623afaee7a | [
"MIT"
] | 12 | 2022-03-10T13:04:42.000Z | 2022-03-24T01:40:23.000Z | src/false_object.cpp | scwfri/natalie | 11e874607a8ac7b934e57c4c7e5790623afaee7a | [
"MIT"
] | 5 | 2022-03-13T17:46:16.000Z | 2022-03-31T07:28:26.000Z | #include "natalie.hpp"
namespace Natalie {
bool FalseObject::and_method(Env *env, Value other) {
return false;
}
bool FalseObject::or_method(Env *env, Value other) {
return other->is_truthy();
}
Value FalseObject::to_s(Env *env) {
if (!s_string)
s_string = new StringObject { "false" };
return s_string;
}
void FalseObject::visit_children(Visitor &visitor) {
Object::visit_children(visitor);
if (s_string)
visitor.visit(s_string);
}
}
| 18.5 | 53 | 0.671518 | scwfri |
51d3ab020bd2bae1f12b66cac0da5383c813d5d7 | 2,895 | hpp | C++ | 3rdparty/libprocess/3rdparty/stout/include/stout/flags/loader.hpp | dharmeshkakadia/mesos | d418c17b89856a9e9d43ece0a7c656f2489a922a | [
"Apache-2.0"
] | 1 | 2015-11-06T09:33:10.000Z | 2015-11-06T09:33:10.000Z | 3rdparty/libprocess/3rdparty/stout/include/stout/flags/loader.hpp | dharmeshkakadia/mesos | d418c17b89856a9e9d43ece0a7c656f2489a922a | [
"Apache-2.0"
] | 1 | 2015-12-21T23:47:34.000Z | 2015-12-21T23:47:47.000Z | 3rdparty/libprocess/3rdparty/stout/include/stout/flags/loader.hpp | dharmeshkakadia/mesos | d418c17b89856a9e9d43ece0a7c656f2489a922a | [
"Apache-2.0"
] | null | null | null | /**
* 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 __STOUT_FLAGS_LOADER_HPP__
#define __STOUT_FLAGS_LOADER_HPP__
#include <string>
#include <stout/error.hpp>
#include <stout/lambda.hpp>
#include <stout/nothing.hpp>
#include <stout/option.hpp>
#include <stout/some.hpp>
#include <stout/try.hpp>
#include <stout/flags/parse.hpp>
namespace flags {
// Forward declaration.
class FlagsBase;
template <typename T>
struct Loader
{
static Try<Nothing> load(
T* flag,
const lambda::function<Try<T>(const std::string&)>& parse,
const std::string& name,
const std::string& value)
{
Try<T> t = parse(value);
if (t.isSome()) {
*flag = t.get();
} else {
return Error("Failed to load value '" + value + "': " + t.error());
}
return Nothing();
}
};
template <typename T>
struct OptionLoader
{
static Try<Nothing> load(
Option<T>* flag,
const lambda::function<Try<T>(const std::string&)>& parse,
const std::string& name,
const std::string& value)
{
Try<T> t = parse(value);
if (t.isSome()) {
*flag = Some(t.get());
} else {
return Error("Failed to load value '" + value + "': " + t.error());
}
return Nothing();
}
};
template <typename F, typename T>
struct MemberLoader
{
static Try<Nothing> load(
FlagsBase* base,
T F::*flag,
const lambda::function<Try<T>(const std::string&)>& parse,
const std::string& name,
const std::string& value)
{
F* f = dynamic_cast<F*>(base);
if (f != NULL) {
Try<T> t = parse(value);
if (t.isSome()) {
f->*flag = t.get();
} else {
return Error("Failed to load value '" + value + "': " + t.error());
}
}
return Nothing();
}
};
template <typename F, typename T>
struct OptionMemberLoader
{
static Try<Nothing> load(
FlagsBase* base,
Option<T> F::*flag,
const lambda::function<Try<T>(const std::string&)>& parse,
const std::string& name,
const std::string& value)
{
F* f = dynamic_cast<F*>(base);
if (f != NULL) {
Try<T> t = parse(value);
if (t.isSome()) {
f->*flag = Some(t.get());
} else {
return Error("Failed to load value '" + value + "': " + t.error());
}
}
return Nothing();
}
};
} // namespace flags {
#endif // __STOUT_FLAGS_LOADER_HPP__
| 23.536585 | 75 | 0.607254 | dharmeshkakadia |
51d3db77a72eae41df3542aea74eb67c686d78a0 | 6,671 | cpp | C++ | omnn/math/Variable.cpp | leannejdong/openmind | 69af704c420ffa89100ecd3709ad9ff39ee4da05 | [
"BSD-3-Clause"
] | 1 | 2020-06-25T06:47:44.000Z | 2020-06-25T06:47:44.000Z | omnn/math/Variable.cpp | leannejdong/openmind | 69af704c420ffa89100ecd3709ad9ff39ee4da05 | [
"BSD-3-Clause"
] | null | null | null | omnn/math/Variable.cpp | leannejdong/openmind | 69af704c420ffa89100ecd3709ad9ff39ee4da05 | [
"BSD-3-Clause"
] | null | null | null | //
// Created by Сергей Кривонос on 25.09.17.
//
#include "Variable.h"
#include "Exponentiation.h"
#include "Integer.h"
#include "Modulo.h"
#include "Product.h"
#include "Sum.h"
#include "VarHost.h"
namespace omnn{
namespace math {
Variable::Variable()
: varSetHost(&VarHost::Global<>(), [](auto){})
, varId(VarHost::Global<>().NewVarId())
{
hash = varSetHost->Hash(varId);
maxVaExp=1;
}
Variable::Variable(const Variable& v)
: varSetHost(v.varSetHost)
, varId(v.varSetHost->CloneId(v.varId))
{
hash = v.Hash();
maxVaExp=1;
}
void Variable::SetId(boost::any id) {
varId = id;
hash = varSetHost->Hash(id);
}
Variable::Variable(VarHost::ptr varHost)
: varSetHost(varHost)
{
if(!varHost)
throw "the varHost is mandatory parameter";
maxVaExp=1;
}
Valuable Variable::operator -() const
{
return Product{-1, *this};
}
Valuable& Variable::operator +=(const Valuable& v)
{
auto c = cast(v);
if(c && *c==*this)
{
Become(Product{2, *this});
}
else
Become(Sum{*this, v});
return *this;
}
Valuable& Variable::operator *=(const Valuable& v)
{
if (Same(v)) {
return Become(Exponentiation(*this, 2));
}
else if (Exponentiation::cast(v))
return Become(v**this);
return Become(Product{*this, v});
}
bool Variable::MultiplyIfSimplifiable(const Valuable& v)
{
auto is = v.IsVa();
if (is) {
is = operator==(v);
if (is) {
sq();
}
} else if (v.IsSimple()) {
} else {
auto s = v.IsMultiplicationSimplifiable(*this);
is = s.first;
if (is) {
Become(std::move(s.second));
}
}
return is;
}
std::pair<bool,Valuable> Variable::IsMultiplicationSimplifiable(const Valuable& v) const
{
std::pair<bool,Valuable> is;
is.first = v.IsVa() && operator==(v);
if (is.first) {
is.second = Sq();
} else if (v.IsSimple()) {
} else {
is = v.IsMultiplicationSimplifiable(v);
}
return is;
}
Valuable& Variable::operator /=(const Valuable& v)
{
auto i = cast(v);
if (i && *this==*i)
{
Become(Integer(1));
}
else
{
*this *= 1 / v;
}
return *this;
}
Valuable& Variable::operator %=(const Valuable& v)
{
return Become(Modulo(*this, v));
}
Valuable& Variable::operator^=(const Valuable& v)
{
if(v.IsInt() && v == 0_v)
Become(1_v);
else
Become(Exponentiation(*this, v));
return *this;
}
Valuable& Variable::d(const Variable& x)
{
return Become(1_v);
}
bool Variable::operator <(const Valuable& v) const
{
auto i = cast(v);
if (i)
{
if (varSetHost != i->varSetHost) {
throw "Unable to compare variable sequence numbers from different var hosts. Do you need a lambda for delayed comparision during evaluation? implement then.";
}
return varSetHost->CompareIdsLess(varId, i->varId);
}
// not implemented comparison to this Valuable descent
return base::operator <(v);
}
bool Variable::operator ==(const Valuable& v) const
{
if (v.IsVa())
{
auto i = cast(v);
if (varSetHost != i->varSetHost) {
throw "Unable to compare variable sequence numbers from different var hosts. Do you need a lambda for delayed comparision during evaluation? implement then.";
}
return hash == v.Hash()
&& varSetHost->CompareIdsEqual(varId, i->varId);
}
else
{ // compare with non-va
return false;
}
// not implemented comparison to this Valuable descent
return base::operator ==(v);
}
std::ostream& Variable::print(std::ostream& out) const
{
return varSetHost->print(out, varId);
}
bool Variable::IsComesBefore(const Valuable& v) const
{
auto mve = getMaxVaExp();
auto vmve = v.getMaxVaExp();
auto is = mve > vmve;
if (mve != vmve)
{}
else if (v.IsVa())
is = base::IsComesBefore(v);
else if (v.IsProduct())
is = Product{*this}.IsComesBefore(v);
else
is = !v.FindVa();
return is;
}
void Variable::CollectVa(std::set<Variable>& s) const
{
s.insert(*this);
}
void Variable::CollectVaNames(std::map<std::string, Variable>& s) const{
s[str()] = *this;
}
bool Variable::eval(const std::map<Variable, Valuable>& with) {
auto it = with.find(*this);
auto evaluated = it != with.end();
if(evaluated) {
auto c = it->second;
Become(std::move(c));
}
return evaluated;
}
void Variable::Eval(const Variable& va, const Valuable& v)
{
if(va==*this)
{
auto copy = v;
Become(std::move(copy));
}
}
const Valuable::vars_cont_t& Variable::getCommonVars() const
{
vars[*this] = 1_v;
if(vars.size()>1)
{
vars.clear();
getCommonVars();
}
return vars;
}
Valuable Variable::InCommonWith(const Valuable& v) const
{
auto c = 1_v;
if (v.IsProduct()) {
c = v.InCommonWith(*this);
} else if (v.IsExponentiation()) {
auto e = Exponentiation::cast(v);
if (e->getBase() == *this) {
if (e->getExponentiation().IsInt()) {
if (e->getExponentiation() > 0) {
c = *this;
}
} else {
IMPLEMENT
}
}
} else if (v.IsVa()) {
if (*this == v)
c = v;
} else if (v.IsInt() || v.IsSimpleFraction()) {
} else {
IMPLEMENT
}
return c;
}
Valuable Variable::operator()(const Variable& va, const Valuable& augmentation) const
{
if (*this == va) {
return {augmentation};
}
else
IMPLEMENT
}
}}
| 24.891791 | 174 | 0.485235 | leannejdong |
51d599938510d83224a340bd109409d3271930ce | 12,216 | cpp | C++ | src/dicom/DICOMBrowser.cpp | RWTHmediTEC/CarnaDICOM | b767cc5f7484b85d24b7557d5d86efebad57b2ef | [
"BSD-3-Clause"
] | null | null | null | src/dicom/DICOMBrowser.cpp | RWTHmediTEC/CarnaDICOM | b767cc5f7484b85d24b7557d5d86efebad57b2ef | [
"BSD-3-Clause"
] | 1 | 2015-07-25T13:26:42.000Z | 2015-07-25T13:26:42.000Z | src/dicom/DICOMBrowser.cpp | RWTHmediTEC/CarnaDICOM | b767cc5f7484b85d24b7557d5d86efebad57b2ef | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2010 - 2015 Leonid Kostrykin
*
* Chair of Medical Engineering (mediTEC)
* RWTH Aachen University
* Pauwelsstr. 20
* 52074 Aachen
* Germany
*
*/
#include <Carna/dicom/CarnaDICOM.h>
#if !CARNAQT_DISABLED
#include <Carna/dicom/DICOMBrowser.h>
#include <Carna/dicom/DICOMBrowserDetails.h>
#include <Carna/dicom/SeriesView.h>
#include <Carna/dicom/DicomManager.h>
#include <Carna/dicom/Series.h>
#include <QProgressDialog>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QFileDialog>
#include <QDoubleSpinBox>
#include <QLabel>
#include <QThread>
#include <QMessageBox>
#include <QCheckBox>
#include <climits>
#include <sstream>
namespace Carna
{
namespace dicom
{
// ----------------------------------------------------------------------------------
// DICOMBrowser :: Details
// ----------------------------------------------------------------------------------
DICOMBrowser::Details::Details( DICOMBrowser& self )
: self( self )
, seriesView( new SeriesView() )
, laSpacingZ( new QLabel( "Z-Spacing:" ) )
, sbSpacingZ( new QDoubleSpinBox() )
, buSaveIndex( new QPushButton( "Save Index..." ) )
, buExtract( new QPushButton( "Extract Series..." ) )
, cbNormals( new QCheckBox( "Compute Normals" ) )
, buLoad( new QPushButton( "Load Series" ) )
, workThread( new QThread() )
, dir( new AsyncDirectory() )
, vgf( new AsyncVolumeGridFactory() )
, spacing( new base::math::Vector3f() )
, patients( nullptr )
{
connect( workThread, SIGNAL( finished() ), workThread, SLOT( deleteLater() ) );
connect( workThread, SIGNAL( finished() ), dir, SLOT( deleteLater() ) );
connect( workThread, SIGNAL( finished() ), vgf, SLOT( deleteLater() ) );
dir->moveToThread( workThread );
vgf->moveToThread( workThread );
workThread->start();
connect( this, SIGNAL( openDirectory( const QString& ) ), dir, SLOT( open( const QString& ) ) );
connect( this, SIGNAL( loadVolumeGrid() ), vgf, SLOT( load() ) );
}
DICOMBrowser::Details::~Details()
{
workThread->quit();
}
void DICOMBrowser::Details::setPatients( const std::vector< Patient* >& patients )
{
this->patients = &patients;
seriesView->clear();
for( auto patientItr = patients.begin(); patientItr != patients.end(); ++patientItr )
{
seriesView->addPatient( **patientItr );
}
buSaveIndex->setEnabled( true );
}
void DICOMBrowser::Details::loadSeries( const Series& series )
{
QProgressDialog progress( "Loading data...", "", 0, 0, &self );
progress.setCancelButton( nullptr );
progress.setAutoReset( false );
connect( vgf, SIGNAL( workAmountChanged( int ) ), &progress, SLOT( setMaximum( int ) ) );
connect( vgf, SIGNAL( workAmountDone( int ) ), &progress, SLOT( setValue( int ) ) );
connect( vgf, SIGNAL( workHintChanged( const QString& ) ), &progress, SLOT( setLabelText( const QString& ) ) );
connect( vgf, SIGNAL( finished() ), &progress, SLOT( reset() ) );
vgf->setSeries( series );
vgf->setNormals( cbNormals->isChecked() );
emit loadVolumeGrid();
progress.exec();
}
// ----------------------------------------------------------------------------------
// DICOMBrowser
// ----------------------------------------------------------------------------------
DICOMBrowser::DICOMBrowser()
: pimpl( new Details( *this ) )
{
//qRegisterMetaType< Carna::dicom::DicomExtractionSettings >( "Carna::dicom::DicomExtractionSettings" );
// ---------------------------------------------------------------------------------
QVBoxLayout* const master = new QVBoxLayout();
QHBoxLayout* const controls = new QHBoxLayout();
// ---------------------------------------------------------------------------------
QPushButton* const buOpenDirectory = new QPushButton( "Scan Directory..." );
QPushButton* const buOpenIndex = new QPushButton( "Open Index..." );
pimpl->sbSpacingZ->setRange( 0.01, std::numeric_limits< double >::max() );
pimpl->sbSpacingZ->setSingleStep( 0.1 );
pimpl->sbSpacingZ->setDecimals( 3 );
pimpl->sbSpacingZ->setSuffix( " mm" );
pimpl->laSpacingZ->setBuddy( pimpl->sbSpacingZ );
pimpl->laSpacingZ->setAlignment( Qt::AlignRight | Qt::AlignVCenter );
controls->addWidget( buOpenDirectory );
controls->addWidget( buOpenIndex );
controls->addWidget( pimpl->buSaveIndex );
//controls->addWidget( pimpl->buExtract );
controls->addWidget( pimpl->cbNormals );
controls->addWidget( pimpl->laSpacingZ );
controls->addWidget( pimpl->sbSpacingZ );
controls->addWidget( pimpl->buLoad );
master->addLayout( controls );
master->addWidget( pimpl->seriesView );
connect( buOpenDirectory, SIGNAL( clicked() ), this, SLOT( openDirectory() ) );
connect( buOpenIndex, SIGNAL( clicked() ), this, SLOT( openIndex() ) );
connect( pimpl->buSaveIndex, SIGNAL( clicked() ), this, SLOT( saveIndex() ) );
connect( pimpl->seriesView, SIGNAL( selectionChanged() ), this, SLOT( updateSelectionState() ) );
connect( pimpl->buExtract, SIGNAL( clicked() ), this, SLOT( extractSeries() ) );
connect( pimpl->buLoad, SIGNAL( clicked() ), this, SLOT( loadSeries() ) );
connect
( pimpl->seriesView, SIGNAL( seriesSelected( const Carna::dicom::Series& ) )
, this, SLOT( setSelectedSeries( const Carna::dicom::Series& ) ) );
connect
( pimpl->seriesView, SIGNAL( seriesDoubleClicked( const Carna::dicom::Series& ) )
, this, SLOT( loadSeries( const Carna::dicom::Series& ) ) );
pimpl->buSaveIndex->setEnabled( false );
pimpl->buExtract->setEnabled( false );
updateSelectionState();
// ---------------------------------------------------------------------------------
this->setLayout( master );
}
DICOMBrowser::~DICOMBrowser()
{
}
void DICOMBrowser::openDirectory()
{
closePatients();
// ---------------------------------------------------------------------------------
const QString dirName = QFileDialog::getExistingDirectory
( this
, "Open Directory", ""
, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks | QFileDialog::HideNameFilterDetails );
if( !dirName.isEmpty() )
{
QProgressDialog progress( dirName, "Cancel", 0, 100, this );
connect( pimpl->dir, SIGNAL( fileCountDetermined( int ) ), &progress, SLOT( setMaximum( int ) ) );
connect( pimpl->dir, SIGNAL( fileProcessed( int ) ), &progress, SLOT( setValue( int ) ) );
connect( &progress, SIGNAL( canceled() ), pimpl->dir, SLOT( cancel() ) );
emit pimpl->openDirectory( dirName );
progress.exec();
/* Report files that failed to be read.
*/
if( !pimpl->dir->failedFiles().empty() )
{
std::stringstream failedFiles;
for( auto it = pimpl->dir->failedFiles().begin(); it != pimpl->dir->failedFiles().end(); ++it )
{
failedFiles << ( *it ) << std::endl;
}
QMessageBox msgBox;
msgBox.setIcon( QMessageBox::Warning );
msgBox.setText
( "Failed to read "
+ QString::number( pimpl->dir->failedFiles().size() )
+ " file(s). Refer to the details section for a full list." );
msgBox.setDetailedText( QString::fromStdString( failedFiles.str() ) );
msgBox.setStandardButtons( QMessageBox::Ok );
msgBox.setDefaultButton( QMessageBox::Ok );
msgBox.setEscapeButton( QMessageBox::Ok );
msgBox.exec();
}
/* Update UI.
*/
pimpl->setPatients( pimpl->dir->patients() );
}
}
void DICOMBrowser::openIndex()
{
closePatients();
// ----------------------------------------------------------------------------------
const QString fileName = QFileDialog::getOpenFileName
( this
, "Open Index", "", "Index Files (*.idx);;XML Files (*.xml);;All files (*.*)"
, 0, QFileDialog::ReadOnly | QFileDialog::HideNameFilterDetails );
if( !fileName.isEmpty() )
{
pimpl->ifr.open( fileName );
pimpl->setPatients( pimpl->ifr.patients() );
}
}
void DICOMBrowser::saveIndex()
{
CARNA_ASSERT( pimpl->patients != nullptr );
const QString fileName = QFileDialog::getSaveFileName
( this
, "Save Index", "", "Index Files (*.idx);;XML Files (*.xml);;All files (*.*)"
, 0, QFileDialog::DontResolveSymlinks| QFileDialog::HideNameFilterDetails );
if( !fileName.isEmpty() )
{
pimpl->ifw.write( fileName, *pimpl->patients );
}
}
void DICOMBrowser::closePatients()
{
pimpl->patients = nullptr;
pimpl->seriesView->clear();
pimpl->buSaveIndex->setEnabled( false );
}
void DICOMBrowser::updateSelectionState()
{
const unsigned int selected_series_count = pimpl->seriesView->getSelectedSeries().size();
pimpl->laSpacingZ->setEnabled( selected_series_count == 1 );
pimpl->sbSpacingZ->setEnabled( selected_series_count == 1 );
pimpl->buLoad->setEnabled( selected_series_count == 1 );
pimpl->buExtract->setEnabled( selected_series_count > 0 );
}
void DICOMBrowser::setSelectedSeries( const Series& series )
{
pimpl->sbSpacingZ->setValue( series.spacingZ() );
}
void DICOMBrowser::extractSeries()
{
/*
const auto& selected_series = seriesView->getSelectedSeries();
if( selected_series.empty() )
{
return;
}
QString dirName = QFileDialog::getExistingDirectory( this
, "Extract Series"
, ""
, QFileDialog::ShowDirsOnly
| QFileDialog::DontResolveSymlinks );
if( dirName.isEmpty() )
{
return;
}
QPushButton* const cancelButton = new QPushButton( "Cancel" );
cancelButton->setEnabled( false );
base::qt::CarnaProgressDialog extractingController( dirName, "Cancel", 0, 0, this );
extractingController.setCancelButton( cancelButton );
extractingController.setWindowTitle( "Extract Series" );
extractingController.setWindowModality( Qt::WindowModal );
extractingController.setModal( true );
connect( manager, SIGNAL( finished() ), &extractingController, SLOT( accept() ) );
connect( manager, SIGNAL( failed() ), &extractingController, SLOT( reject() ) );
connect( manager, SIGNAL( failed( const QString& ) ), this, SLOT( extractionFailed( const QString& ) ) );
connect( manager, SIGNAL( totalFilesCountChanged( unsigned int ) ), &extractingController, SLOT( setMaximum( unsigned int ) ) );
connect( manager, SIGNAL( processedFilesCountChanged( unsigned int ) ), &extractingController, SLOT( setValue( unsigned int ) ) );
DicomExtractionSettings settings( dirName, selected_series );
emit extractSeries( settings );
extractingController.exec();
disconnect( manager, SIGNAL( failed( const QString& ) ), this, SLOT( extractionFailed( const QString& ) ) );
*/
}
void DICOMBrowser::loadSeries()
{
const auto& selectedSeries = pimpl->seriesView->getSelectedSeries();
if( selectedSeries.size() == 1 )
{
pimpl->loadSeries( **selectedSeries.begin() );
const double zSpacing = pimpl->sbSpacingZ->value();
base::math::Vector3f& spacing = *pimpl->spacing;
spacing = pimpl->vgf->spacing();
spacing.z() = zSpacing;
emit volumeGridLoaded();
}
}
void DICOMBrowser::loadSeries( const Series& series )
{
pimpl->loadSeries( series );
base::math::Vector3f& spacing = *pimpl->spacing;
spacing = pimpl->vgf->spacing();
emit volumeGridLoaded();
}
Carna::helpers::VolumeGridHelperBase* DICOMBrowser::takeLoadedVolumeGrid()
{
return pimpl->vgf->takeLoadedVolumeGrid();
}
Carna::helpers::VolumeGridHelperBase::Spacing DICOMBrowser::loadedVolumeGridSpacing() const
{
return Carna::helpers::VolumeGridHelperBase::Spacing( *pimpl->spacing );
}
} // namespace Carna :: dicom
} // namespace Carna
#endif // CARNAQT_DISABLED
| 32.75067 | 134 | 0.597168 | RWTHmediTEC |
51e152025e8a55b81457a4fd504e9317802e134f | 498 | cpp | C++ | uhk/CF3.1.cpp | Hyyyyyyyyyy/acm | d7101755b2c2868d51bb056f094e024d0333b56f | [
"MIT"
] | null | null | null | uhk/CF3.1.cpp | Hyyyyyyyyyy/acm | d7101755b2c2868d51bb056f094e024d0333b56f | [
"MIT"
] | null | null | null | uhk/CF3.1.cpp | Hyyyyyyyyyy/acm | d7101755b2c2868d51bb056f094e024d0333b56f | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
int bx, by, ex, ey, X, Y;
int main()
{
int i, j, k, u, n, m, a, b, c, d;
while (scanf("%d %d %d %d", &bx, &by, &ex, &ey) != EOF)
{
scanf("%d %d", &X, &Y);
if (abs(bx - ex) % X != 0 || abs(by - ey) % Y != 0)
{
printf("NO\n");
continue;
}
int t1 = abs(bx - ex) / X;
int t2 = abs(by - ey) / Y;
if (abs(t1 - t2) % 2 == 0)
printf("YES\n");
else
printf("NO\n");
}
return 0;
} | 19.153846 | 56 | 0.487952 | Hyyyyyyyyyy |
51e44bc7aadacc1bf880a5918a0445670103cc49 | 64,352 | cpp | C++ | deployed/Il2CppOutputProject/Source/il2cppOutput/Bulk_UnityEngine.StandardEvents_0.cpp | PaulDixon/HelloWorld | f73f1eb2f972b3bc03420727e3c383ff63041af9 | [
"MIT"
] | null | null | null | deployed/Il2CppOutputProject/Source/il2cppOutput/Bulk_UnityEngine.StandardEvents_0.cpp | PaulDixon/HelloWorld | f73f1eb2f972b3bc03420727e3c383ff63041af9 | [
"MIT"
] | null | null | null | deployed/Il2CppOutputProject/Source/il2cppOutput/Bulk_UnityEngine.StandardEvents_0.cpp | PaulDixon/HelloWorld | f73f1eb2f972b3bc03420727e3c383ff63041af9 | [
"MIT"
] | null | null | null | #include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <cstring>
#include <string.h>
#include <stdio.h>
#include <cmath>
#include <limits>
#include <assert.h>
#include <stdint.h>
#include "il2cpp-class-internals.h"
#include "codegen/il2cpp-codegen.h"
#include "il2cpp-object-internals.h"
template <typename R>
struct InterfaceFuncInvoker0
{
typedef R (*Func)(void*, const RuntimeMethod*);
static inline R Invoke (Il2CppMethodSlot slot, RuntimeClass* declaringInterface, RuntimeObject* obj)
{
const VirtualInvokeData& invokeData = il2cpp_codegen_get_interface_invoke_data(slot, obj, declaringInterface);
return ((Func)invokeData.methodPtr)(obj, invokeData.method);
}
};
struct InterfaceActionInvoker0
{
typedef void (*Action)(void*, const RuntimeMethod*);
static inline void Invoke (Il2CppMethodSlot slot, RuntimeClass* declaringInterface, RuntimeObject* obj)
{
const VirtualInvokeData& invokeData = il2cpp_codegen_get_interface_invoke_data(slot, obj, declaringInterface);
((Action)invokeData.methodPtr)(obj, invokeData.method);
}
};
// System.String
struct String_t;
// System.ArgumentException
struct ArgumentException_t132251570;
// System.Collections.Generic.IDictionary`2<System.String,System.Object>
struct IDictionary_2_t1329213854;
// System.Object[]
struct ObjectU5BU5D_t2843939325;
// System.Collections.Generic.Dictionary`2<System.String,System.Object>
struct Dictionary_2_t2865362463;
// System.Collections.Generic.Dictionary`2<System.Object,System.Object>
struct Dictionary_2_t132545152;
// System.Collections.Generic.Dictionary`2<System.String,System.String>
struct Dictionary_2_t1632706988;
// System.Int32[]
struct Int32U5BU5D_t385246372;
// System.Collections.Generic.Dictionary`2/Entry<System.String,System.String>[]
struct EntryU5BU5D_t885026589;
// System.Collections.Generic.IEqualityComparer`1<System.String>
struct IEqualityComparer_1_t3954782707;
// System.Collections.Generic.Dictionary`2/KeyCollection<System.String,System.String>
struct KeyCollection_t1822382459;
// System.Collections.Generic.Dictionary`2/ValueCollection<System.String,System.String>
struct ValueCollection_t3348751306;
// System.Collections.Generic.Dictionary`2/Entry<System.String,System.Object>[]
struct EntryU5BU5D_t2447176574;
// System.Collections.Generic.Dictionary`2/KeyCollection<System.String,System.Object>
struct KeyCollection_t3055037934;
// System.Collections.Generic.Dictionary`2/ValueCollection<System.String,System.Object>
struct ValueCollection_t286439485;
// System.Collections.IDictionary
struct IDictionary_t1363984059;
// System.Runtime.Serialization.SafeSerializationManager
struct SafeSerializationManager_t2481557153;
// System.Diagnostics.StackTrace[]
struct StackTraceU5BU5D_t1169129676;
// System.IntPtr[]
struct IntPtrU5BU5D_t4013366056;
// System.Char[]
struct CharU5BU5D_t3528271667;
extern RuntimeClass* AnalyticsEvent_t4058973021_il2cpp_TypeInfo_var;
extern const uint32_t AnalyticsEvent_get_debugMode_m2240954048_MetadataUsageId;
extern RuntimeClass* ArgumentException_t132251570_il2cpp_TypeInfo_var;
extern const RuntimeMethod* AnalyticsEvent_OnValidationFailed_m2609604624_RuntimeMethod_var;
extern const uint32_t AnalyticsEvent_OnValidationFailed_m2609604624_MetadataUsageId;
extern RuntimeClass* String_t_il2cpp_TypeInfo_var;
extern RuntimeClass* ICollection_1_t3796219568_il2cpp_TypeInfo_var;
extern RuntimeClass* Int32_t2950945753_il2cpp_TypeInfo_var;
extern RuntimeClass* IEnumerable_1_t4242887519_il2cpp_TypeInfo_var;
extern RuntimeClass* IEnumerator_1_t1400637802_il2cpp_TypeInfo_var;
extern RuntimeClass* IEnumerator_t1853284238_il2cpp_TypeInfo_var;
extern RuntimeClass* IDisposable_t3640265483_il2cpp_TypeInfo_var;
extern RuntimeClass* ObjectU5BU5D_t2843939325_il2cpp_TypeInfo_var;
extern RuntimeClass* AnalyticsResult_t2273004240_il2cpp_TypeInfo_var;
extern RuntimeClass* Debug_t3317548046_il2cpp_TypeInfo_var;
extern const RuntimeMethod* KeyValuePair_2_get_Key_m256823211_RuntimeMethod_var;
extern const RuntimeMethod* KeyValuePair_2_get_Value_m4108279609_RuntimeMethod_var;
extern String_t* _stringLiteral3082188891;
extern String_t* _stringLiteral3848816014;
extern String_t* _stringLiteral3610066572;
extern String_t* _stringLiteral3713525075;
extern String_t* _stringLiteral1348467685;
extern String_t* _stringLiteral69560130;
extern String_t* _stringLiteral2157825051;
extern const uint32_t AnalyticsEvent_Custom_m227997836_MetadataUsageId;
extern RuntimeClass* Dictionary_2_t2865362463_il2cpp_TypeInfo_var;
extern RuntimeClass* Dictionary_2_t1632706988_il2cpp_TypeInfo_var;
extern const RuntimeMethod* Dictionary_2__ctor_m15304876_RuntimeMethod_var;
extern const RuntimeMethod* Dictionary_2__ctor_m444307833_RuntimeMethod_var;
extern const RuntimeMethod* Dictionary_2_Add_m3045345476_RuntimeMethod_var;
extern String_t* _stringLiteral314968592;
extern String_t* _stringLiteral223781046;
extern String_t* _stringLiteral591401181;
extern String_t* _stringLiteral2670495305;
extern String_t* _stringLiteral3038431854;
extern String_t* _stringLiteral1860111314;
extern String_t* _stringLiteral3191806752;
extern String_t* _stringLiteral2793515199;
extern String_t* _stringLiteral1822927358;
extern String_t* _stringLiteral3946338038;
extern String_t* _stringLiteral1285374328;
extern String_t* _stringLiteral1477325238;
extern String_t* _stringLiteral359657463;
extern String_t* _stringLiteral2913916239;
extern String_t* _stringLiteral4063851185;
extern String_t* _stringLiteral2569810339;
extern String_t* _stringLiteral243880865;
extern const uint32_t AnalyticsEvent__cctor_m3994162614_MetadataUsageId;
struct Exception_t_marshaled_pinvoke;
struct Exception_t_marshaled_com;
struct ObjectU5BU5D_t2843939325;
#ifndef U3CMODULEU3E_T692745553_H
#define U3CMODULEU3E_T692745553_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// <Module>
struct U3CModuleU3E_t692745553
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // U3CMODULEU3E_T692745553_H
#ifndef RUNTIMEOBJECT_H
#define RUNTIMEOBJECT_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Object
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // RUNTIMEOBJECT_H
#ifndef DICTIONARY_2_T1632706988_H
#define DICTIONARY_2_T1632706988_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Collections.Generic.Dictionary`2<System.String,System.String>
struct Dictionary_2_t1632706988 : public RuntimeObject
{
public:
// System.Int32[] System.Collections.Generic.Dictionary`2::buckets
Int32U5BU5D_t385246372* ___buckets_0;
// System.Collections.Generic.Dictionary`2/Entry<TKey,TValue>[] System.Collections.Generic.Dictionary`2::entries
EntryU5BU5D_t885026589* ___entries_1;
// System.Int32 System.Collections.Generic.Dictionary`2::count
int32_t ___count_2;
// System.Int32 System.Collections.Generic.Dictionary`2::version
int32_t ___version_3;
// System.Int32 System.Collections.Generic.Dictionary`2::freeList
int32_t ___freeList_4;
// System.Int32 System.Collections.Generic.Dictionary`2::freeCount
int32_t ___freeCount_5;
// System.Collections.Generic.IEqualityComparer`1<TKey> System.Collections.Generic.Dictionary`2::comparer
RuntimeObject* ___comparer_6;
// System.Collections.Generic.Dictionary`2/KeyCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::keys
KeyCollection_t1822382459 * ___keys_7;
// System.Collections.Generic.Dictionary`2/ValueCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::values
ValueCollection_t3348751306 * ___values_8;
// System.Object System.Collections.Generic.Dictionary`2::_syncRoot
RuntimeObject * ____syncRoot_9;
public:
inline static int32_t get_offset_of_buckets_0() { return static_cast<int32_t>(offsetof(Dictionary_2_t1632706988, ___buckets_0)); }
inline Int32U5BU5D_t385246372* get_buckets_0() const { return ___buckets_0; }
inline Int32U5BU5D_t385246372** get_address_of_buckets_0() { return &___buckets_0; }
inline void set_buckets_0(Int32U5BU5D_t385246372* value)
{
___buckets_0 = value;
Il2CppCodeGenWriteBarrier((&___buckets_0), value);
}
inline static int32_t get_offset_of_entries_1() { return static_cast<int32_t>(offsetof(Dictionary_2_t1632706988, ___entries_1)); }
inline EntryU5BU5D_t885026589* get_entries_1() const { return ___entries_1; }
inline EntryU5BU5D_t885026589** get_address_of_entries_1() { return &___entries_1; }
inline void set_entries_1(EntryU5BU5D_t885026589* value)
{
___entries_1 = value;
Il2CppCodeGenWriteBarrier((&___entries_1), value);
}
inline static int32_t get_offset_of_count_2() { return static_cast<int32_t>(offsetof(Dictionary_2_t1632706988, ___count_2)); }
inline int32_t get_count_2() const { return ___count_2; }
inline int32_t* get_address_of_count_2() { return &___count_2; }
inline void set_count_2(int32_t value)
{
___count_2 = value;
}
inline static int32_t get_offset_of_version_3() { return static_cast<int32_t>(offsetof(Dictionary_2_t1632706988, ___version_3)); }
inline int32_t get_version_3() const { return ___version_3; }
inline int32_t* get_address_of_version_3() { return &___version_3; }
inline void set_version_3(int32_t value)
{
___version_3 = value;
}
inline static int32_t get_offset_of_freeList_4() { return static_cast<int32_t>(offsetof(Dictionary_2_t1632706988, ___freeList_4)); }
inline int32_t get_freeList_4() const { return ___freeList_4; }
inline int32_t* get_address_of_freeList_4() { return &___freeList_4; }
inline void set_freeList_4(int32_t value)
{
___freeList_4 = value;
}
inline static int32_t get_offset_of_freeCount_5() { return static_cast<int32_t>(offsetof(Dictionary_2_t1632706988, ___freeCount_5)); }
inline int32_t get_freeCount_5() const { return ___freeCount_5; }
inline int32_t* get_address_of_freeCount_5() { return &___freeCount_5; }
inline void set_freeCount_5(int32_t value)
{
___freeCount_5 = value;
}
inline static int32_t get_offset_of_comparer_6() { return static_cast<int32_t>(offsetof(Dictionary_2_t1632706988, ___comparer_6)); }
inline RuntimeObject* get_comparer_6() const { return ___comparer_6; }
inline RuntimeObject** get_address_of_comparer_6() { return &___comparer_6; }
inline void set_comparer_6(RuntimeObject* value)
{
___comparer_6 = value;
Il2CppCodeGenWriteBarrier((&___comparer_6), value);
}
inline static int32_t get_offset_of_keys_7() { return static_cast<int32_t>(offsetof(Dictionary_2_t1632706988, ___keys_7)); }
inline KeyCollection_t1822382459 * get_keys_7() const { return ___keys_7; }
inline KeyCollection_t1822382459 ** get_address_of_keys_7() { return &___keys_7; }
inline void set_keys_7(KeyCollection_t1822382459 * value)
{
___keys_7 = value;
Il2CppCodeGenWriteBarrier((&___keys_7), value);
}
inline static int32_t get_offset_of_values_8() { return static_cast<int32_t>(offsetof(Dictionary_2_t1632706988, ___values_8)); }
inline ValueCollection_t3348751306 * get_values_8() const { return ___values_8; }
inline ValueCollection_t3348751306 ** get_address_of_values_8() { return &___values_8; }
inline void set_values_8(ValueCollection_t3348751306 * value)
{
___values_8 = value;
Il2CppCodeGenWriteBarrier((&___values_8), value);
}
inline static int32_t get_offset_of__syncRoot_9() { return static_cast<int32_t>(offsetof(Dictionary_2_t1632706988, ____syncRoot_9)); }
inline RuntimeObject * get__syncRoot_9() const { return ____syncRoot_9; }
inline RuntimeObject ** get_address_of__syncRoot_9() { return &____syncRoot_9; }
inline void set__syncRoot_9(RuntimeObject * value)
{
____syncRoot_9 = value;
Il2CppCodeGenWriteBarrier((&____syncRoot_9), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DICTIONARY_2_T1632706988_H
struct Il2CppArrayBounds;
#ifndef RUNTIMEARRAY_H
#define RUNTIMEARRAY_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Array
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // RUNTIMEARRAY_H
#ifndef DICTIONARY_2_T2865362463_H
#define DICTIONARY_2_T2865362463_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Collections.Generic.Dictionary`2<System.String,System.Object>
struct Dictionary_2_t2865362463 : public RuntimeObject
{
public:
// System.Int32[] System.Collections.Generic.Dictionary`2::buckets
Int32U5BU5D_t385246372* ___buckets_0;
// System.Collections.Generic.Dictionary`2/Entry<TKey,TValue>[] System.Collections.Generic.Dictionary`2::entries
EntryU5BU5D_t2447176574* ___entries_1;
// System.Int32 System.Collections.Generic.Dictionary`2::count
int32_t ___count_2;
// System.Int32 System.Collections.Generic.Dictionary`2::version
int32_t ___version_3;
// System.Int32 System.Collections.Generic.Dictionary`2::freeList
int32_t ___freeList_4;
// System.Int32 System.Collections.Generic.Dictionary`2::freeCount
int32_t ___freeCount_5;
// System.Collections.Generic.IEqualityComparer`1<TKey> System.Collections.Generic.Dictionary`2::comparer
RuntimeObject* ___comparer_6;
// System.Collections.Generic.Dictionary`2/KeyCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::keys
KeyCollection_t3055037934 * ___keys_7;
// System.Collections.Generic.Dictionary`2/ValueCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::values
ValueCollection_t286439485 * ___values_8;
// System.Object System.Collections.Generic.Dictionary`2::_syncRoot
RuntimeObject * ____syncRoot_9;
public:
inline static int32_t get_offset_of_buckets_0() { return static_cast<int32_t>(offsetof(Dictionary_2_t2865362463, ___buckets_0)); }
inline Int32U5BU5D_t385246372* get_buckets_0() const { return ___buckets_0; }
inline Int32U5BU5D_t385246372** get_address_of_buckets_0() { return &___buckets_0; }
inline void set_buckets_0(Int32U5BU5D_t385246372* value)
{
___buckets_0 = value;
Il2CppCodeGenWriteBarrier((&___buckets_0), value);
}
inline static int32_t get_offset_of_entries_1() { return static_cast<int32_t>(offsetof(Dictionary_2_t2865362463, ___entries_1)); }
inline EntryU5BU5D_t2447176574* get_entries_1() const { return ___entries_1; }
inline EntryU5BU5D_t2447176574** get_address_of_entries_1() { return &___entries_1; }
inline void set_entries_1(EntryU5BU5D_t2447176574* value)
{
___entries_1 = value;
Il2CppCodeGenWriteBarrier((&___entries_1), value);
}
inline static int32_t get_offset_of_count_2() { return static_cast<int32_t>(offsetof(Dictionary_2_t2865362463, ___count_2)); }
inline int32_t get_count_2() const { return ___count_2; }
inline int32_t* get_address_of_count_2() { return &___count_2; }
inline void set_count_2(int32_t value)
{
___count_2 = value;
}
inline static int32_t get_offset_of_version_3() { return static_cast<int32_t>(offsetof(Dictionary_2_t2865362463, ___version_3)); }
inline int32_t get_version_3() const { return ___version_3; }
inline int32_t* get_address_of_version_3() { return &___version_3; }
inline void set_version_3(int32_t value)
{
___version_3 = value;
}
inline static int32_t get_offset_of_freeList_4() { return static_cast<int32_t>(offsetof(Dictionary_2_t2865362463, ___freeList_4)); }
inline int32_t get_freeList_4() const { return ___freeList_4; }
inline int32_t* get_address_of_freeList_4() { return &___freeList_4; }
inline void set_freeList_4(int32_t value)
{
___freeList_4 = value;
}
inline static int32_t get_offset_of_freeCount_5() { return static_cast<int32_t>(offsetof(Dictionary_2_t2865362463, ___freeCount_5)); }
inline int32_t get_freeCount_5() const { return ___freeCount_5; }
inline int32_t* get_address_of_freeCount_5() { return &___freeCount_5; }
inline void set_freeCount_5(int32_t value)
{
___freeCount_5 = value;
}
inline static int32_t get_offset_of_comparer_6() { return static_cast<int32_t>(offsetof(Dictionary_2_t2865362463, ___comparer_6)); }
inline RuntimeObject* get_comparer_6() const { return ___comparer_6; }
inline RuntimeObject** get_address_of_comparer_6() { return &___comparer_6; }
inline void set_comparer_6(RuntimeObject* value)
{
___comparer_6 = value;
Il2CppCodeGenWriteBarrier((&___comparer_6), value);
}
inline static int32_t get_offset_of_keys_7() { return static_cast<int32_t>(offsetof(Dictionary_2_t2865362463, ___keys_7)); }
inline KeyCollection_t3055037934 * get_keys_7() const { return ___keys_7; }
inline KeyCollection_t3055037934 ** get_address_of_keys_7() { return &___keys_7; }
inline void set_keys_7(KeyCollection_t3055037934 * value)
{
___keys_7 = value;
Il2CppCodeGenWriteBarrier((&___keys_7), value);
}
inline static int32_t get_offset_of_values_8() { return static_cast<int32_t>(offsetof(Dictionary_2_t2865362463, ___values_8)); }
inline ValueCollection_t286439485 * get_values_8() const { return ___values_8; }
inline ValueCollection_t286439485 ** get_address_of_values_8() { return &___values_8; }
inline void set_values_8(ValueCollection_t286439485 * value)
{
___values_8 = value;
Il2CppCodeGenWriteBarrier((&___values_8), value);
}
inline static int32_t get_offset_of__syncRoot_9() { return static_cast<int32_t>(offsetof(Dictionary_2_t2865362463, ____syncRoot_9)); }
inline RuntimeObject * get__syncRoot_9() const { return ____syncRoot_9; }
inline RuntimeObject ** get_address_of__syncRoot_9() { return &____syncRoot_9; }
inline void set__syncRoot_9(RuntimeObject * value)
{
____syncRoot_9 = value;
Il2CppCodeGenWriteBarrier((&____syncRoot_9), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DICTIONARY_2_T2865362463_H
#ifndef EXCEPTION_T_H
#define EXCEPTION_T_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Exception
struct Exception_t : public RuntimeObject
{
public:
// System.String System.Exception::_className
String_t* ____className_1;
// System.String System.Exception::_message
String_t* ____message_2;
// System.Collections.IDictionary System.Exception::_data
RuntimeObject* ____data_3;
// System.Exception System.Exception::_innerException
Exception_t * ____innerException_4;
// System.String System.Exception::_helpURL
String_t* ____helpURL_5;
// System.Object System.Exception::_stackTrace
RuntimeObject * ____stackTrace_6;
// System.String System.Exception::_stackTraceString
String_t* ____stackTraceString_7;
// System.String System.Exception::_remoteStackTraceString
String_t* ____remoteStackTraceString_8;
// System.Int32 System.Exception::_remoteStackIndex
int32_t ____remoteStackIndex_9;
// System.Object System.Exception::_dynamicMethods
RuntimeObject * ____dynamicMethods_10;
// System.Int32 System.Exception::_HResult
int32_t ____HResult_11;
// System.String System.Exception::_source
String_t* ____source_12;
// System.Runtime.Serialization.SafeSerializationManager System.Exception::_safeSerializationManager
SafeSerializationManager_t2481557153 * ____safeSerializationManager_13;
// System.Diagnostics.StackTrace[] System.Exception::captured_traces
StackTraceU5BU5D_t1169129676* ___captured_traces_14;
// System.IntPtr[] System.Exception::native_trace_ips
IntPtrU5BU5D_t4013366056* ___native_trace_ips_15;
public:
inline static int32_t get_offset_of__className_1() { return static_cast<int32_t>(offsetof(Exception_t, ____className_1)); }
inline String_t* get__className_1() const { return ____className_1; }
inline String_t** get_address_of__className_1() { return &____className_1; }
inline void set__className_1(String_t* value)
{
____className_1 = value;
Il2CppCodeGenWriteBarrier((&____className_1), value);
}
inline static int32_t get_offset_of__message_2() { return static_cast<int32_t>(offsetof(Exception_t, ____message_2)); }
inline String_t* get__message_2() const { return ____message_2; }
inline String_t** get_address_of__message_2() { return &____message_2; }
inline void set__message_2(String_t* value)
{
____message_2 = value;
Il2CppCodeGenWriteBarrier((&____message_2), value);
}
inline static int32_t get_offset_of__data_3() { return static_cast<int32_t>(offsetof(Exception_t, ____data_3)); }
inline RuntimeObject* get__data_3() const { return ____data_3; }
inline RuntimeObject** get_address_of__data_3() { return &____data_3; }
inline void set__data_3(RuntimeObject* value)
{
____data_3 = value;
Il2CppCodeGenWriteBarrier((&____data_3), value);
}
inline static int32_t get_offset_of__innerException_4() { return static_cast<int32_t>(offsetof(Exception_t, ____innerException_4)); }
inline Exception_t * get__innerException_4() const { return ____innerException_4; }
inline Exception_t ** get_address_of__innerException_4() { return &____innerException_4; }
inline void set__innerException_4(Exception_t * value)
{
____innerException_4 = value;
Il2CppCodeGenWriteBarrier((&____innerException_4), value);
}
inline static int32_t get_offset_of__helpURL_5() { return static_cast<int32_t>(offsetof(Exception_t, ____helpURL_5)); }
inline String_t* get__helpURL_5() const { return ____helpURL_5; }
inline String_t** get_address_of__helpURL_5() { return &____helpURL_5; }
inline void set__helpURL_5(String_t* value)
{
____helpURL_5 = value;
Il2CppCodeGenWriteBarrier((&____helpURL_5), value);
}
inline static int32_t get_offset_of__stackTrace_6() { return static_cast<int32_t>(offsetof(Exception_t, ____stackTrace_6)); }
inline RuntimeObject * get__stackTrace_6() const { return ____stackTrace_6; }
inline RuntimeObject ** get_address_of__stackTrace_6() { return &____stackTrace_6; }
inline void set__stackTrace_6(RuntimeObject * value)
{
____stackTrace_6 = value;
Il2CppCodeGenWriteBarrier((&____stackTrace_6), value);
}
inline static int32_t get_offset_of__stackTraceString_7() { return static_cast<int32_t>(offsetof(Exception_t, ____stackTraceString_7)); }
inline String_t* get__stackTraceString_7() const { return ____stackTraceString_7; }
inline String_t** get_address_of__stackTraceString_7() { return &____stackTraceString_7; }
inline void set__stackTraceString_7(String_t* value)
{
____stackTraceString_7 = value;
Il2CppCodeGenWriteBarrier((&____stackTraceString_7), value);
}
inline static int32_t get_offset_of__remoteStackTraceString_8() { return static_cast<int32_t>(offsetof(Exception_t, ____remoteStackTraceString_8)); }
inline String_t* get__remoteStackTraceString_8() const { return ____remoteStackTraceString_8; }
inline String_t** get_address_of__remoteStackTraceString_8() { return &____remoteStackTraceString_8; }
inline void set__remoteStackTraceString_8(String_t* value)
{
____remoteStackTraceString_8 = value;
Il2CppCodeGenWriteBarrier((&____remoteStackTraceString_8), value);
}
inline static int32_t get_offset_of__remoteStackIndex_9() { return static_cast<int32_t>(offsetof(Exception_t, ____remoteStackIndex_9)); }
inline int32_t get__remoteStackIndex_9() const { return ____remoteStackIndex_9; }
inline int32_t* get_address_of__remoteStackIndex_9() { return &____remoteStackIndex_9; }
inline void set__remoteStackIndex_9(int32_t value)
{
____remoteStackIndex_9 = value;
}
inline static int32_t get_offset_of__dynamicMethods_10() { return static_cast<int32_t>(offsetof(Exception_t, ____dynamicMethods_10)); }
inline RuntimeObject * get__dynamicMethods_10() const { return ____dynamicMethods_10; }
inline RuntimeObject ** get_address_of__dynamicMethods_10() { return &____dynamicMethods_10; }
inline void set__dynamicMethods_10(RuntimeObject * value)
{
____dynamicMethods_10 = value;
Il2CppCodeGenWriteBarrier((&____dynamicMethods_10), value);
}
inline static int32_t get_offset_of__HResult_11() { return static_cast<int32_t>(offsetof(Exception_t, ____HResult_11)); }
inline int32_t get__HResult_11() const { return ____HResult_11; }
inline int32_t* get_address_of__HResult_11() { return &____HResult_11; }
inline void set__HResult_11(int32_t value)
{
____HResult_11 = value;
}
inline static int32_t get_offset_of__source_12() { return static_cast<int32_t>(offsetof(Exception_t, ____source_12)); }
inline String_t* get__source_12() const { return ____source_12; }
inline String_t** get_address_of__source_12() { return &____source_12; }
inline void set__source_12(String_t* value)
{
____source_12 = value;
Il2CppCodeGenWriteBarrier((&____source_12), value);
}
inline static int32_t get_offset_of__safeSerializationManager_13() { return static_cast<int32_t>(offsetof(Exception_t, ____safeSerializationManager_13)); }
inline SafeSerializationManager_t2481557153 * get__safeSerializationManager_13() const { return ____safeSerializationManager_13; }
inline SafeSerializationManager_t2481557153 ** get_address_of__safeSerializationManager_13() { return &____safeSerializationManager_13; }
inline void set__safeSerializationManager_13(SafeSerializationManager_t2481557153 * value)
{
____safeSerializationManager_13 = value;
Il2CppCodeGenWriteBarrier((&____safeSerializationManager_13), value);
}
inline static int32_t get_offset_of_captured_traces_14() { return static_cast<int32_t>(offsetof(Exception_t, ___captured_traces_14)); }
inline StackTraceU5BU5D_t1169129676* get_captured_traces_14() const { return ___captured_traces_14; }
inline StackTraceU5BU5D_t1169129676** get_address_of_captured_traces_14() { return &___captured_traces_14; }
inline void set_captured_traces_14(StackTraceU5BU5D_t1169129676* value)
{
___captured_traces_14 = value;
Il2CppCodeGenWriteBarrier((&___captured_traces_14), value);
}
inline static int32_t get_offset_of_native_trace_ips_15() { return static_cast<int32_t>(offsetof(Exception_t, ___native_trace_ips_15)); }
inline IntPtrU5BU5D_t4013366056* get_native_trace_ips_15() const { return ___native_trace_ips_15; }
inline IntPtrU5BU5D_t4013366056** get_address_of_native_trace_ips_15() { return &___native_trace_ips_15; }
inline void set_native_trace_ips_15(IntPtrU5BU5D_t4013366056* value)
{
___native_trace_ips_15 = value;
Il2CppCodeGenWriteBarrier((&___native_trace_ips_15), value);
}
};
struct Exception_t_StaticFields
{
public:
// System.Object System.Exception::s_EDILock
RuntimeObject * ___s_EDILock_0;
public:
inline static int32_t get_offset_of_s_EDILock_0() { return static_cast<int32_t>(offsetof(Exception_t_StaticFields, ___s_EDILock_0)); }
inline RuntimeObject * get_s_EDILock_0() const { return ___s_EDILock_0; }
inline RuntimeObject ** get_address_of_s_EDILock_0() { return &___s_EDILock_0; }
inline void set_s_EDILock_0(RuntimeObject * value)
{
___s_EDILock_0 = value;
Il2CppCodeGenWriteBarrier((&___s_EDILock_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.Exception
struct Exception_t_marshaled_pinvoke
{
char* ____className_1;
char* ____message_2;
RuntimeObject* ____data_3;
Exception_t_marshaled_pinvoke* ____innerException_4;
char* ____helpURL_5;
Il2CppIUnknown* ____stackTrace_6;
char* ____stackTraceString_7;
char* ____remoteStackTraceString_8;
int32_t ____remoteStackIndex_9;
Il2CppIUnknown* ____dynamicMethods_10;
int32_t ____HResult_11;
char* ____source_12;
SafeSerializationManager_t2481557153 * ____safeSerializationManager_13;
StackTraceU5BU5D_t1169129676* ___captured_traces_14;
intptr_t* ___native_trace_ips_15;
};
// Native definition for COM marshalling of System.Exception
struct Exception_t_marshaled_com
{
Il2CppChar* ____className_1;
Il2CppChar* ____message_2;
RuntimeObject* ____data_3;
Exception_t_marshaled_com* ____innerException_4;
Il2CppChar* ____helpURL_5;
Il2CppIUnknown* ____stackTrace_6;
Il2CppChar* ____stackTraceString_7;
Il2CppChar* ____remoteStackTraceString_8;
int32_t ____remoteStackIndex_9;
Il2CppIUnknown* ____dynamicMethods_10;
int32_t ____HResult_11;
Il2CppChar* ____source_12;
SafeSerializationManager_t2481557153 * ____safeSerializationManager_13;
StackTraceU5BU5D_t1169129676* ___captured_traces_14;
intptr_t* ___native_trace_ips_15;
};
#endif // EXCEPTION_T_H
#ifndef VALUETYPE_T3640485471_H
#define VALUETYPE_T3640485471_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ValueType
struct ValueType_t3640485471 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.ValueType
struct ValueType_t3640485471_marshaled_pinvoke
{
};
// Native definition for COM marshalling of System.ValueType
struct ValueType_t3640485471_marshaled_com
{
};
#endif // VALUETYPE_T3640485471_H
#ifndef STRING_T_H
#define STRING_T_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.String
struct String_t : public RuntimeObject
{
public:
// System.Int32 System.String::m_stringLength
int32_t ___m_stringLength_0;
// System.Char System.String::m_firstChar
Il2CppChar ___m_firstChar_1;
public:
inline static int32_t get_offset_of_m_stringLength_0() { return static_cast<int32_t>(offsetof(String_t, ___m_stringLength_0)); }
inline int32_t get_m_stringLength_0() const { return ___m_stringLength_0; }
inline int32_t* get_address_of_m_stringLength_0() { return &___m_stringLength_0; }
inline void set_m_stringLength_0(int32_t value)
{
___m_stringLength_0 = value;
}
inline static int32_t get_offset_of_m_firstChar_1() { return static_cast<int32_t>(offsetof(String_t, ___m_firstChar_1)); }
inline Il2CppChar get_m_firstChar_1() const { return ___m_firstChar_1; }
inline Il2CppChar* get_address_of_m_firstChar_1() { return &___m_firstChar_1; }
inline void set_m_firstChar_1(Il2CppChar value)
{
___m_firstChar_1 = value;
}
};
struct String_t_StaticFields
{
public:
// System.String System.String::Empty
String_t* ___Empty_5;
public:
inline static int32_t get_offset_of_Empty_5() { return static_cast<int32_t>(offsetof(String_t_StaticFields, ___Empty_5)); }
inline String_t* get_Empty_5() const { return ___Empty_5; }
inline String_t** get_address_of_Empty_5() { return &___Empty_5; }
inline void set_Empty_5(String_t* value)
{
___Empty_5 = value;
Il2CppCodeGenWriteBarrier((&___Empty_5), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // STRING_T_H
#ifndef ANALYTICSEVENT_T4058973021_H
#define ANALYTICSEVENT_T4058973021_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Analytics.AnalyticsEvent
struct AnalyticsEvent_t4058973021 : public RuntimeObject
{
public:
public:
};
struct AnalyticsEvent_t4058973021_StaticFields
{
public:
// System.String UnityEngine.Analytics.AnalyticsEvent::k_SdkVersion
String_t* ___k_SdkVersion_0;
// System.Collections.Generic.Dictionary`2<System.String,System.Object> UnityEngine.Analytics.AnalyticsEvent::m_EventData
Dictionary_2_t2865362463 * ___m_EventData_1;
// System.Boolean UnityEngine.Analytics.AnalyticsEvent::_debugMode
bool ____debugMode_2;
// System.Collections.Generic.Dictionary`2<System.String,System.String> UnityEngine.Analytics.AnalyticsEvent::enumRenameTable
Dictionary_2_t1632706988 * ___enumRenameTable_3;
public:
inline static int32_t get_offset_of_k_SdkVersion_0() { return static_cast<int32_t>(offsetof(AnalyticsEvent_t4058973021_StaticFields, ___k_SdkVersion_0)); }
inline String_t* get_k_SdkVersion_0() const { return ___k_SdkVersion_0; }
inline String_t** get_address_of_k_SdkVersion_0() { return &___k_SdkVersion_0; }
inline void set_k_SdkVersion_0(String_t* value)
{
___k_SdkVersion_0 = value;
Il2CppCodeGenWriteBarrier((&___k_SdkVersion_0), value);
}
inline static int32_t get_offset_of_m_EventData_1() { return static_cast<int32_t>(offsetof(AnalyticsEvent_t4058973021_StaticFields, ___m_EventData_1)); }
inline Dictionary_2_t2865362463 * get_m_EventData_1() const { return ___m_EventData_1; }
inline Dictionary_2_t2865362463 ** get_address_of_m_EventData_1() { return &___m_EventData_1; }
inline void set_m_EventData_1(Dictionary_2_t2865362463 * value)
{
___m_EventData_1 = value;
Il2CppCodeGenWriteBarrier((&___m_EventData_1), value);
}
inline static int32_t get_offset_of__debugMode_2() { return static_cast<int32_t>(offsetof(AnalyticsEvent_t4058973021_StaticFields, ____debugMode_2)); }
inline bool get__debugMode_2() const { return ____debugMode_2; }
inline bool* get_address_of__debugMode_2() { return &____debugMode_2; }
inline void set__debugMode_2(bool value)
{
____debugMode_2 = value;
}
inline static int32_t get_offset_of_enumRenameTable_3() { return static_cast<int32_t>(offsetof(AnalyticsEvent_t4058973021_StaticFields, ___enumRenameTable_3)); }
inline Dictionary_2_t1632706988 * get_enumRenameTable_3() const { return ___enumRenameTable_3; }
inline Dictionary_2_t1632706988 ** get_address_of_enumRenameTable_3() { return &___enumRenameTable_3; }
inline void set_enumRenameTable_3(Dictionary_2_t1632706988 * value)
{
___enumRenameTable_3 = value;
Il2CppCodeGenWriteBarrier((&___enumRenameTable_3), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ANALYTICSEVENT_T4058973021_H
#ifndef SYSTEMEXCEPTION_T176217640_H
#define SYSTEMEXCEPTION_T176217640_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.SystemException
struct SystemException_t176217640 : public Exception_t
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SYSTEMEXCEPTION_T176217640_H
#ifndef BOOLEAN_T97287965_H
#define BOOLEAN_T97287965_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Boolean
struct Boolean_t97287965
{
public:
// System.Boolean System.Boolean::m_value
bool ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Boolean_t97287965, ___m_value_0)); }
inline bool get_m_value_0() const { return ___m_value_0; }
inline bool* get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(bool value)
{
___m_value_0 = value;
}
};
struct Boolean_t97287965_StaticFields
{
public:
// System.String System.Boolean::TrueString
String_t* ___TrueString_5;
// System.String System.Boolean::FalseString
String_t* ___FalseString_6;
public:
inline static int32_t get_offset_of_TrueString_5() { return static_cast<int32_t>(offsetof(Boolean_t97287965_StaticFields, ___TrueString_5)); }
inline String_t* get_TrueString_5() const { return ___TrueString_5; }
inline String_t** get_address_of_TrueString_5() { return &___TrueString_5; }
inline void set_TrueString_5(String_t* value)
{
___TrueString_5 = value;
Il2CppCodeGenWriteBarrier((&___TrueString_5), value);
}
inline static int32_t get_offset_of_FalseString_6() { return static_cast<int32_t>(offsetof(Boolean_t97287965_StaticFields, ___FalseString_6)); }
inline String_t* get_FalseString_6() const { return ___FalseString_6; }
inline String_t** get_address_of_FalseString_6() { return &___FalseString_6; }
inline void set_FalseString_6(String_t* value)
{
___FalseString_6 = value;
Il2CppCodeGenWriteBarrier((&___FalseString_6), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BOOLEAN_T97287965_H
#ifndef ENUM_T4135868527_H
#define ENUM_T4135868527_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Enum
struct Enum_t4135868527 : public ValueType_t3640485471
{
public:
public:
};
struct Enum_t4135868527_StaticFields
{
public:
// System.Char[] System.Enum::enumSeperatorCharArray
CharU5BU5D_t3528271667* ___enumSeperatorCharArray_0;
public:
inline static int32_t get_offset_of_enumSeperatorCharArray_0() { return static_cast<int32_t>(offsetof(Enum_t4135868527_StaticFields, ___enumSeperatorCharArray_0)); }
inline CharU5BU5D_t3528271667* get_enumSeperatorCharArray_0() const { return ___enumSeperatorCharArray_0; }
inline CharU5BU5D_t3528271667** get_address_of_enumSeperatorCharArray_0() { return &___enumSeperatorCharArray_0; }
inline void set_enumSeperatorCharArray_0(CharU5BU5D_t3528271667* value)
{
___enumSeperatorCharArray_0 = value;
Il2CppCodeGenWriteBarrier((&___enumSeperatorCharArray_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.Enum
struct Enum_t4135868527_marshaled_pinvoke
{
};
// Native definition for COM marshalling of System.Enum
struct Enum_t4135868527_marshaled_com
{
};
#endif // ENUM_T4135868527_H
#ifndef VOID_T1185182177_H
#define VOID_T1185182177_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Void
struct Void_t1185182177
{
public:
union
{
struct
{
};
uint8_t Void_t1185182177__padding[1];
};
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // VOID_T1185182177_H
#ifndef KEYVALUEPAIR_2_T968067334_H
#define KEYVALUEPAIR_2_T968067334_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Collections.Generic.KeyValuePair`2<System.String,System.Object>
struct KeyValuePair_2_t968067334
{
public:
// TKey System.Collections.Generic.KeyValuePair`2::key
String_t* ___key_0;
// TValue System.Collections.Generic.KeyValuePair`2::value
RuntimeObject * ___value_1;
public:
inline static int32_t get_offset_of_key_0() { return static_cast<int32_t>(offsetof(KeyValuePair_2_t968067334, ___key_0)); }
inline String_t* get_key_0() const { return ___key_0; }
inline String_t** get_address_of_key_0() { return &___key_0; }
inline void set_key_0(String_t* value)
{
___key_0 = value;
Il2CppCodeGenWriteBarrier((&___key_0), value);
}
inline static int32_t get_offset_of_value_1() { return static_cast<int32_t>(offsetof(KeyValuePair_2_t968067334, ___value_1)); }
inline RuntimeObject * get_value_1() const { return ___value_1; }
inline RuntimeObject ** get_address_of_value_1() { return &___value_1; }
inline void set_value_1(RuntimeObject * value)
{
___value_1 = value;
Il2CppCodeGenWriteBarrier((&___value_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // KEYVALUEPAIR_2_T968067334_H
#ifndef KEYVALUEPAIR_2_T2530217319_H
#define KEYVALUEPAIR_2_T2530217319_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Collections.Generic.KeyValuePair`2<System.Object,System.Object>
struct KeyValuePair_2_t2530217319
{
public:
// TKey System.Collections.Generic.KeyValuePair`2::key
RuntimeObject * ___key_0;
// TValue System.Collections.Generic.KeyValuePair`2::value
RuntimeObject * ___value_1;
public:
inline static int32_t get_offset_of_key_0() { return static_cast<int32_t>(offsetof(KeyValuePair_2_t2530217319, ___key_0)); }
inline RuntimeObject * get_key_0() const { return ___key_0; }
inline RuntimeObject ** get_address_of_key_0() { return &___key_0; }
inline void set_key_0(RuntimeObject * value)
{
___key_0 = value;
Il2CppCodeGenWriteBarrier((&___key_0), value);
}
inline static int32_t get_offset_of_value_1() { return static_cast<int32_t>(offsetof(KeyValuePair_2_t2530217319, ___value_1)); }
inline RuntimeObject * get_value_1() const { return ___value_1; }
inline RuntimeObject ** get_address_of_value_1() { return &___value_1; }
inline void set_value_1(RuntimeObject * value)
{
___value_1 = value;
Il2CppCodeGenWriteBarrier((&___value_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // KEYVALUEPAIR_2_T2530217319_H
#ifndef INT32_T2950945753_H
#define INT32_T2950945753_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Int32
struct Int32_t2950945753
{
public:
// System.Int32 System.Int32::m_value
int32_t ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Int32_t2950945753, ___m_value_0)); }
inline int32_t get_m_value_0() const { return ___m_value_0; }
inline int32_t* get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(int32_t value)
{
___m_value_0 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // INT32_T2950945753_H
#ifndef ANALYTICSRESULT_T2273004240_H
#define ANALYTICSRESULT_T2273004240_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Analytics.AnalyticsResult
struct AnalyticsResult_t2273004240
{
public:
// System.Int32 UnityEngine.Analytics.AnalyticsResult::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(AnalyticsResult_t2273004240, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ANALYTICSRESULT_T2273004240_H
#ifndef ARGUMENTEXCEPTION_T132251570_H
#define ARGUMENTEXCEPTION_T132251570_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ArgumentException
struct ArgumentException_t132251570 : public SystemException_t176217640
{
public:
// System.String System.ArgumentException::m_paramName
String_t* ___m_paramName_16;
public:
inline static int32_t get_offset_of_m_paramName_16() { return static_cast<int32_t>(offsetof(ArgumentException_t132251570, ___m_paramName_16)); }
inline String_t* get_m_paramName_16() const { return ___m_paramName_16; }
inline String_t** get_address_of_m_paramName_16() { return &___m_paramName_16; }
inline void set_m_paramName_16(String_t* value)
{
___m_paramName_16 = value;
Il2CppCodeGenWriteBarrier((&___m_paramName_16), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ARGUMENTEXCEPTION_T132251570_H
// System.Object[]
struct ObjectU5BU5D_t2843939325 : public RuntimeArray
{
public:
ALIGN_FIELD (8) RuntimeObject * m_Items[1];
public:
inline RuntimeObject * GetAt(il2cpp_array_size_t index) const
{
IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length);
return m_Items[index];
}
inline RuntimeObject ** GetAddressAt(il2cpp_array_size_t index)
{
IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length);
return m_Items + index;
}
inline void SetAt(il2cpp_array_size_t index, RuntimeObject * value)
{
IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length);
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
inline RuntimeObject * GetAtUnchecked(il2cpp_array_size_t index) const
{
return m_Items[index];
}
inline RuntimeObject ** GetAddressAtUnchecked(il2cpp_array_size_t index)
{
return m_Items + index;
}
inline void SetAtUnchecked(il2cpp_array_size_t index, RuntimeObject * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// !0 System.Collections.Generic.KeyValuePair`2<System.Object,System.Object>::get_Key()
extern "C" RuntimeObject * KeyValuePair_2_get_Key_m4184817181_gshared (KeyValuePair_2_t2530217319 * __this, const RuntimeMethod* method);
// !1 System.Collections.Generic.KeyValuePair`2<System.Object,System.Object>::get_Value()
extern "C" RuntimeObject * KeyValuePair_2_get_Value_m1132502692_gshared (KeyValuePair_2_t2530217319 * __this, const RuntimeMethod* method);
// System.Void System.Collections.Generic.Dictionary`2<System.Object,System.Object>::.ctor()
extern "C" void Dictionary_2__ctor_m518943619_gshared (Dictionary_2_t132545152 * __this, const RuntimeMethod* method);
// System.Void System.Collections.Generic.Dictionary`2<System.Object,System.Object>::Add(!0,!1)
extern "C" void Dictionary_2_Add_m3105409630_gshared (Dictionary_2_t132545152 * __this, RuntimeObject * p0, RuntimeObject * p1, const RuntimeMethod* method);
// System.Void System.ArgumentException::.ctor(System.String)
extern "C" void ArgumentException__ctor_m1312628991 (ArgumentException_t132251570 * __this, String_t* p0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR;
// System.Boolean System.String::IsNullOrEmpty(System.String)
extern "C" bool String_IsNullOrEmpty_m2969720369 (RuntimeObject * __this /* static, unused */, String_t* p0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR;
// System.Void UnityEngine.Analytics.AnalyticsEvent::OnValidationFailed(System.String)
extern "C" void AnalyticsEvent_OnValidationFailed_m2609604624 (RuntimeObject * __this /* static, unused */, String_t* ___message0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR;
// UnityEngine.Analytics.AnalyticsResult UnityEngine.Analytics.Analytics::CustomEvent(System.String)
extern "C" int32_t Analytics_CustomEvent_m692224174 (RuntimeObject * __this /* static, unused */, String_t* p0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR;
// UnityEngine.Analytics.AnalyticsResult UnityEngine.Analytics.Analytics::CustomEvent(System.String,System.Collections.Generic.IDictionary`2<System.String,System.Object>)
extern "C" int32_t Analytics_CustomEvent_m3835919949 (RuntimeObject * __this /* static, unused */, String_t* p0, RuntimeObject* p1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR;
// System.Boolean UnityEngine.Analytics.AnalyticsEvent::get_debugMode()
extern "C" bool AnalyticsEvent_get_debugMode_m2240954048 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) IL2CPP_METHOD_ATTR;
// System.String System.String::Concat(System.String,System.String)
extern "C" String_t* String_Concat_m3937257545 (RuntimeObject * __this /* static, unused */, String_t* p0, String_t* p1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR;
// System.String System.String::Format(System.String,System.Object)
extern "C" String_t* String_Format_m2844511972 (RuntimeObject * __this /* static, unused */, String_t* p0, RuntimeObject * p1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR;
// !0 System.Collections.Generic.KeyValuePair`2<System.String,System.Object>::get_Key()
#define KeyValuePair_2_get_Key_m256823211(__this, method) (( String_t* (*) (KeyValuePair_2_t968067334 *, const RuntimeMethod*))KeyValuePair_2_get_Key_m4184817181_gshared)(__this, method)
// !1 System.Collections.Generic.KeyValuePair`2<System.String,System.Object>::get_Value()
#define KeyValuePair_2_get_Value_m4108279609(__this, method) (( RuntimeObject * (*) (KeyValuePair_2_t968067334 *, const RuntimeMethod*))KeyValuePair_2_get_Value_m1132502692_gshared)(__this, method)
// System.String System.String::Format(System.String,System.Object,System.Object)
extern "C" String_t* String_Format_m2556382932 (RuntimeObject * __this /* static, unused */, String_t* p0, RuntimeObject * p1, RuntimeObject * p2, const RuntimeMethod* method) IL2CPP_METHOD_ATTR;
// System.Void UnityEngine.Debug::LogFormat(System.String,System.Object[])
extern "C" void Debug_LogFormat_m309087137 (RuntimeObject * __this /* static, unused */, String_t* p0, ObjectU5BU5D_t2843939325* p1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR;
// System.Void UnityEngine.Debug::LogErrorFormat(System.String,System.Object[])
extern "C" void Debug_LogErrorFormat_m575266265 (RuntimeObject * __this /* static, unused */, String_t* p0, ObjectU5BU5D_t2843939325* p1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR;
// System.Void UnityEngine.Debug::LogWarningFormat(System.String,System.Object[])
extern "C" void Debug_LogWarningFormat_m2535776735 (RuntimeObject * __this /* static, unused */, String_t* p0, ObjectU5BU5D_t2843939325* p1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR;
// System.Void System.Collections.Generic.Dictionary`2<System.String,System.Object>::.ctor()
#define Dictionary_2__ctor_m15304876(__this, method) (( void (*) (Dictionary_2_t2865362463 *, const RuntimeMethod*))Dictionary_2__ctor_m518943619_gshared)(__this, method)
// System.Void System.Collections.Generic.Dictionary`2<System.String,System.String>::.ctor()
#define Dictionary_2__ctor_m444307833(__this, method) (( void (*) (Dictionary_2_t1632706988 *, const RuntimeMethod*))Dictionary_2__ctor_m518943619_gshared)(__this, method)
// System.Void System.Collections.Generic.Dictionary`2<System.String,System.String>::Add(!0,!1)
#define Dictionary_2_Add_m3045345476(__this, p0, p1, method) (( void (*) (Dictionary_2_t1632706988 *, String_t*, String_t*, const RuntimeMethod*))Dictionary_2_Add_m3105409630_gshared)(__this, p0, p1, method)
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Boolean UnityEngine.Analytics.AnalyticsEvent::get_debugMode()
extern "C" bool AnalyticsEvent_get_debugMode_m2240954048 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_method (AnalyticsEvent_get_debugMode_m2240954048_MetadataUsageId);
s_Il2CppMethodInitialized = true;
}
bool V_0 = false;
{
IL2CPP_RUNTIME_CLASS_INIT(AnalyticsEvent_t4058973021_il2cpp_TypeInfo_var);
bool L_0 = ((AnalyticsEvent_t4058973021_StaticFields*)il2cpp_codegen_static_fields_for(AnalyticsEvent_t4058973021_il2cpp_TypeInfo_var))->get__debugMode_2();
V_0 = L_0;
goto IL_000c;
}
IL_000c:
{
bool L_1 = V_0;
return L_1;
}
}
// System.Void UnityEngine.Analytics.AnalyticsEvent::OnValidationFailed(System.String)
extern "C" void AnalyticsEvent_OnValidationFailed_m2609604624 (RuntimeObject * __this /* static, unused */, String_t* ___message0, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_method (AnalyticsEvent_OnValidationFailed_m2609604624_MetadataUsageId);
s_Il2CppMethodInitialized = true;
}
{
String_t* L_0 = ___message0;
ArgumentException_t132251570 * L_1 = (ArgumentException_t132251570 *)il2cpp_codegen_object_new(ArgumentException_t132251570_il2cpp_TypeInfo_var);
ArgumentException__ctor_m1312628991(L_1, L_0, /*hidden argument*/NULL);
IL2CPP_RAISE_MANAGED_EXCEPTION(L_1,AnalyticsEvent_OnValidationFailed_m2609604624_RuntimeMethod_var);
}
}
// UnityEngine.Analytics.AnalyticsResult UnityEngine.Analytics.AnalyticsEvent::Custom(System.String,System.Collections.Generic.IDictionary`2<System.String,System.Object>)
extern "C" int32_t AnalyticsEvent_Custom_m227997836 (RuntimeObject * __this /* static, unused */, String_t* ___eventName0, RuntimeObject* ___eventData1, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_method (AnalyticsEvent_Custom_m227997836_MetadataUsageId);
s_Il2CppMethodInitialized = true;
}
int32_t V_0 = 0;
String_t* V_1 = NULL;
KeyValuePair_2_t968067334 V_2;
memset(&V_2, 0, sizeof(V_2));
RuntimeObject* V_3 = NULL;
int32_t V_4 = 0;
Exception_t * __last_unhandled_exception = 0;
NO_UNUSED_WARNING (__last_unhandled_exception);
Exception_t * __exception_local = 0;
NO_UNUSED_WARNING (__exception_local);
int32_t __leave_target = 0;
NO_UNUSED_WARNING (__leave_target);
{
V_0 = 7;
String_t* L_0 = ((String_t_StaticFields*)il2cpp_codegen_static_fields_for(String_t_il2cpp_TypeInfo_var))->get_Empty_5();
V_1 = L_0;
String_t* L_1 = ___eventName0;
bool L_2 = String_IsNullOrEmpty_m2969720369(NULL /*static, unused*/, L_1, /*hidden argument*/NULL);
if (!L_2)
{
goto IL_0020;
}
}
{
IL2CPP_RUNTIME_CLASS_INIT(AnalyticsEvent_t4058973021_il2cpp_TypeInfo_var);
AnalyticsEvent_OnValidationFailed_m2609604624(NULL /*static, unused*/, _stringLiteral3082188891, /*hidden argument*/NULL);
}
IL_0020:
{
RuntimeObject* L_3 = ___eventData1;
if (L_3)
{
goto IL_0034;
}
}
{
String_t* L_4 = ___eventName0;
int32_t L_5 = Analytics_CustomEvent_m692224174(NULL /*static, unused*/, L_4, /*hidden argument*/NULL);
V_0 = L_5;
goto IL_003e;
}
IL_0034:
{
String_t* L_6 = ___eventName0;
RuntimeObject* L_7 = ___eventData1;
int32_t L_8 = Analytics_CustomEvent_m3835919949(NULL /*static, unused*/, L_6, L_7, /*hidden argument*/NULL);
V_0 = L_8;
}
IL_003e:
{
IL2CPP_RUNTIME_CLASS_INIT(AnalyticsEvent_t4058973021_il2cpp_TypeInfo_var);
bool L_9 = AnalyticsEvent_get_debugMode_m2240954048(NULL /*static, unused*/, /*hidden argument*/NULL);
if (!L_9)
{
goto IL_00d3;
}
}
{
RuntimeObject* L_10 = ___eventData1;
if (L_10)
{
goto IL_0062;
}
}
{
String_t* L_11 = V_1;
String_t* L_12 = String_Concat_m3937257545(NULL /*static, unused*/, L_11, _stringLiteral3848816014, /*hidden argument*/NULL);
V_1 = L_12;
goto IL_00d2;
}
IL_0062:
{
String_t* L_13 = V_1;
RuntimeObject* L_14 = ___eventData1;
NullCheck(L_14);
int32_t L_15 = InterfaceFuncInvoker0< int32_t >::Invoke(0 /* System.Int32 System.Collections.Generic.ICollection`1<System.Collections.Generic.KeyValuePair`2<System.String,System.Object>>::get_Count() */, ICollection_1_t3796219568_il2cpp_TypeInfo_var, L_14);
int32_t L_16 = L_15;
RuntimeObject * L_17 = Box(Int32_t2950945753_il2cpp_TypeInfo_var, &L_16);
String_t* L_18 = String_Format_m2844511972(NULL /*static, unused*/, _stringLiteral3610066572, L_17, /*hidden argument*/NULL);
String_t* L_19 = String_Concat_m3937257545(NULL /*static, unused*/, L_13, L_18, /*hidden argument*/NULL);
V_1 = L_19;
RuntimeObject* L_20 = ___eventData1;
NullCheck(L_20);
RuntimeObject* L_21 = InterfaceFuncInvoker0< RuntimeObject* >::Invoke(0 /* System.Collections.Generic.IEnumerator`1<!0> System.Collections.Generic.IEnumerable`1<System.Collections.Generic.KeyValuePair`2<System.String,System.Object>>::GetEnumerator() */, IEnumerable_1_t4242887519_il2cpp_TypeInfo_var, L_20);
V_3 = L_21;
}
IL_0087:
try
{ // begin try (depth: 1)
{
goto IL_00b4;
}
IL_008c:
{
RuntimeObject* L_22 = V_3;
NullCheck(L_22);
KeyValuePair_2_t968067334 L_23 = InterfaceFuncInvoker0< KeyValuePair_2_t968067334 >::Invoke(0 /* !0 System.Collections.Generic.IEnumerator`1<System.Collections.Generic.KeyValuePair`2<System.String,System.Object>>::get_Current() */, IEnumerator_1_t1400637802_il2cpp_TypeInfo_var, L_22);
V_2 = L_23;
String_t* L_24 = V_1;
String_t* L_25 = KeyValuePair_2_get_Key_m256823211((&V_2), /*hidden argument*/KeyValuePair_2_get_Key_m256823211_RuntimeMethod_var);
RuntimeObject * L_26 = KeyValuePair_2_get_Value_m4108279609((&V_2), /*hidden argument*/KeyValuePair_2_get_Value_m4108279609_RuntimeMethod_var);
String_t* L_27 = String_Format_m2556382932(NULL /*static, unused*/, _stringLiteral3713525075, L_25, L_26, /*hidden argument*/NULL);
String_t* L_28 = String_Concat_m3937257545(NULL /*static, unused*/, L_24, L_27, /*hidden argument*/NULL);
V_1 = L_28;
}
IL_00b4:
{
RuntimeObject* L_29 = V_3;
NullCheck(L_29);
bool L_30 = InterfaceFuncInvoker0< bool >::Invoke(0 /* System.Boolean System.Collections.IEnumerator::MoveNext() */, IEnumerator_t1853284238_il2cpp_TypeInfo_var, L_29);
if (L_30)
{
goto IL_008c;
}
}
IL_00bf:
{
IL2CPP_LEAVE(0xD1, FINALLY_00c4);
}
} // end try (depth: 1)
catch(Il2CppExceptionWrapper& e)
{
__last_unhandled_exception = (Exception_t *)e.ex;
goto FINALLY_00c4;
}
FINALLY_00c4:
{ // begin finally (depth: 1)
{
RuntimeObject* L_31 = V_3;
if (!L_31)
{
goto IL_00d0;
}
}
IL_00ca:
{
RuntimeObject* L_32 = V_3;
NullCheck(L_32);
InterfaceActionInvoker0::Invoke(0 /* System.Void System.IDisposable::Dispose() */, IDisposable_t3640265483_il2cpp_TypeInfo_var, L_32);
}
IL_00d0:
{
IL2CPP_END_FINALLY(196)
}
} // end finally (depth: 1)
IL2CPP_CLEANUP(196)
{
IL2CPP_JUMP_TBL(0xD1, IL_00d1)
IL2CPP_RETHROW_IF_UNHANDLED(Exception_t *)
}
IL_00d1:
{
}
IL_00d2:
{
}
IL_00d3:
{
int32_t L_33 = V_0;
switch (L_33)
{
case 0:
{
goto IL_00f5;
}
case 1:
{
goto IL_00e9;
}
case 2:
{
goto IL_00e9;
}
case 3:
{
goto IL_0127;
}
}
}
IL_00e9:
{
int32_t L_34 = V_0;
if ((((int32_t)L_34) == ((int32_t)6)))
{
goto IL_0127;
}
}
{
goto IL_014d;
}
IL_00f5:
{
IL2CPP_RUNTIME_CLASS_INIT(AnalyticsEvent_t4058973021_il2cpp_TypeInfo_var);
bool L_35 = AnalyticsEvent_get_debugMode_m2240954048(NULL /*static, unused*/, /*hidden argument*/NULL);
if (!L_35)
{
goto IL_0122;
}
}
{
ObjectU5BU5D_t2843939325* L_36 = ((ObjectU5BU5D_t2843939325*)SZArrayNew(ObjectU5BU5D_t2843939325_il2cpp_TypeInfo_var, (uint32_t)3));
String_t* L_37 = ___eventName0;
NullCheck(L_36);
ArrayElementTypeCheck (L_36, L_37);
(L_36)->SetAt(static_cast<il2cpp_array_size_t>(0), (RuntimeObject *)L_37);
ObjectU5BU5D_t2843939325* L_38 = L_36;
int32_t L_39 = V_0;
int32_t L_40 = L_39;
RuntimeObject * L_41 = Box(AnalyticsResult_t2273004240_il2cpp_TypeInfo_var, &L_40);
NullCheck(L_38);
ArrayElementTypeCheck (L_38, L_41);
(L_38)->SetAt(static_cast<il2cpp_array_size_t>(1), (RuntimeObject *)L_41);
ObjectU5BU5D_t2843939325* L_42 = L_38;
String_t* L_43 = V_1;
NullCheck(L_42);
ArrayElementTypeCheck (L_42, L_43);
(L_42)->SetAt(static_cast<il2cpp_array_size_t>(2), (RuntimeObject *)L_43);
IL2CPP_RUNTIME_CLASS_INIT(Debug_t3317548046_il2cpp_TypeInfo_var);
Debug_LogFormat_m309087137(NULL /*static, unused*/, _stringLiteral1348467685, L_42, /*hidden argument*/NULL);
}
IL_0122:
{
goto IL_0173;
}
IL_0127:
{
ObjectU5BU5D_t2843939325* L_44 = ((ObjectU5BU5D_t2843939325*)SZArrayNew(ObjectU5BU5D_t2843939325_il2cpp_TypeInfo_var, (uint32_t)3));
String_t* L_45 = ___eventName0;
NullCheck(L_44);
ArrayElementTypeCheck (L_44, L_45);
(L_44)->SetAt(static_cast<il2cpp_array_size_t>(0), (RuntimeObject *)L_45);
ObjectU5BU5D_t2843939325* L_46 = L_44;
int32_t L_47 = V_0;
int32_t L_48 = L_47;
RuntimeObject * L_49 = Box(AnalyticsResult_t2273004240_il2cpp_TypeInfo_var, &L_48);
NullCheck(L_46);
ArrayElementTypeCheck (L_46, L_49);
(L_46)->SetAt(static_cast<il2cpp_array_size_t>(1), (RuntimeObject *)L_49);
ObjectU5BU5D_t2843939325* L_50 = L_46;
String_t* L_51 = V_1;
NullCheck(L_50);
ArrayElementTypeCheck (L_50, L_51);
(L_50)->SetAt(static_cast<il2cpp_array_size_t>(2), (RuntimeObject *)L_51);
IL2CPP_RUNTIME_CLASS_INIT(Debug_t3317548046_il2cpp_TypeInfo_var);
Debug_LogErrorFormat_m575266265(NULL /*static, unused*/, _stringLiteral69560130, L_50, /*hidden argument*/NULL);
goto IL_0173;
}
IL_014d:
{
ObjectU5BU5D_t2843939325* L_52 = ((ObjectU5BU5D_t2843939325*)SZArrayNew(ObjectU5BU5D_t2843939325_il2cpp_TypeInfo_var, (uint32_t)3));
String_t* L_53 = ___eventName0;
NullCheck(L_52);
ArrayElementTypeCheck (L_52, L_53);
(L_52)->SetAt(static_cast<il2cpp_array_size_t>(0), (RuntimeObject *)L_53);
ObjectU5BU5D_t2843939325* L_54 = L_52;
int32_t L_55 = V_0;
int32_t L_56 = L_55;
RuntimeObject * L_57 = Box(AnalyticsResult_t2273004240_il2cpp_TypeInfo_var, &L_56);
NullCheck(L_54);
ArrayElementTypeCheck (L_54, L_57);
(L_54)->SetAt(static_cast<il2cpp_array_size_t>(1), (RuntimeObject *)L_57);
ObjectU5BU5D_t2843939325* L_58 = L_54;
String_t* L_59 = V_1;
NullCheck(L_58);
ArrayElementTypeCheck (L_58, L_59);
(L_58)->SetAt(static_cast<il2cpp_array_size_t>(2), (RuntimeObject *)L_59);
IL2CPP_RUNTIME_CLASS_INIT(Debug_t3317548046_il2cpp_TypeInfo_var);
Debug_LogWarningFormat_m2535776735(NULL /*static, unused*/, _stringLiteral2157825051, L_58, /*hidden argument*/NULL);
goto IL_0173;
}
IL_0173:
{
int32_t L_60 = V_0;
V_4 = L_60;
goto IL_017b;
}
IL_017b:
{
int32_t L_61 = V_4;
return L_61;
}
}
// System.Void UnityEngine.Analytics.AnalyticsEvent::.cctor()
extern "C" void AnalyticsEvent__cctor_m3994162614 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_method (AnalyticsEvent__cctor_m3994162614_MetadataUsageId);
s_Il2CppMethodInitialized = true;
}
Dictionary_2_t1632706988 * V_0 = NULL;
{
((AnalyticsEvent_t4058973021_StaticFields*)il2cpp_codegen_static_fields_for(AnalyticsEvent_t4058973021_il2cpp_TypeInfo_var))->set_k_SdkVersion_0(_stringLiteral314968592);
Dictionary_2_t2865362463 * L_0 = (Dictionary_2_t2865362463 *)il2cpp_codegen_object_new(Dictionary_2_t2865362463_il2cpp_TypeInfo_var);
Dictionary_2__ctor_m15304876(L_0, /*hidden argument*/Dictionary_2__ctor_m15304876_RuntimeMethod_var);
((AnalyticsEvent_t4058973021_StaticFields*)il2cpp_codegen_static_fields_for(AnalyticsEvent_t4058973021_il2cpp_TypeInfo_var))->set_m_EventData_1(L_0);
((AnalyticsEvent_t4058973021_StaticFields*)il2cpp_codegen_static_fields_for(AnalyticsEvent_t4058973021_il2cpp_TypeInfo_var))->set__debugMode_2((bool)0);
Dictionary_2_t1632706988 * L_1 = (Dictionary_2_t1632706988 *)il2cpp_codegen_object_new(Dictionary_2_t1632706988_il2cpp_TypeInfo_var);
Dictionary_2__ctor_m444307833(L_1, /*hidden argument*/Dictionary_2__ctor_m444307833_RuntimeMethod_var);
V_0 = L_1;
Dictionary_2_t1632706988 * L_2 = V_0;
NullCheck(L_2);
Dictionary_2_Add_m3045345476(L_2, _stringLiteral223781046, _stringLiteral591401181, /*hidden argument*/Dictionary_2_Add_m3045345476_RuntimeMethod_var);
Dictionary_2_t1632706988 * L_3 = V_0;
NullCheck(L_3);
Dictionary_2_Add_m3045345476(L_3, _stringLiteral2670495305, _stringLiteral3038431854, /*hidden argument*/Dictionary_2_Add_m3045345476_RuntimeMethod_var);
Dictionary_2_t1632706988 * L_4 = V_0;
NullCheck(L_4);
Dictionary_2_Add_m3045345476(L_4, _stringLiteral1860111314, _stringLiteral3191806752, /*hidden argument*/Dictionary_2_Add_m3045345476_RuntimeMethod_var);
Dictionary_2_t1632706988 * L_5 = V_0;
NullCheck(L_5);
Dictionary_2_Add_m3045345476(L_5, _stringLiteral2793515199, _stringLiteral1822927358, /*hidden argument*/Dictionary_2_Add_m3045345476_RuntimeMethod_var);
Dictionary_2_t1632706988 * L_6 = V_0;
NullCheck(L_6);
Dictionary_2_Add_m3045345476(L_6, _stringLiteral3946338038, _stringLiteral1285374328, /*hidden argument*/Dictionary_2_Add_m3045345476_RuntimeMethod_var);
Dictionary_2_t1632706988 * L_7 = V_0;
NullCheck(L_7);
Dictionary_2_Add_m3045345476(L_7, _stringLiteral1477325238, _stringLiteral359657463, /*hidden argument*/Dictionary_2_Add_m3045345476_RuntimeMethod_var);
Dictionary_2_t1632706988 * L_8 = V_0;
NullCheck(L_8);
Dictionary_2_Add_m3045345476(L_8, _stringLiteral2913916239, _stringLiteral4063851185, /*hidden argument*/Dictionary_2_Add_m3045345476_RuntimeMethod_var);
Dictionary_2_t1632706988 * L_9 = V_0;
NullCheck(L_9);
Dictionary_2_Add_m3045345476(L_9, _stringLiteral2569810339, _stringLiteral243880865, /*hidden argument*/Dictionary_2_Add_m3045345476_RuntimeMethod_var);
Dictionary_2_t1632706988 * L_10 = V_0;
((AnalyticsEvent_t4058973021_StaticFields*)il2cpp_codegen_static_fields_for(AnalyticsEvent_t4058973021_il2cpp_TypeInfo_var))->set_enumRenameTable_3(L_10);
return;
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| 39.167377 | 309 | 0.805445 | PaulDixon |
51e61c57b7bfbcdfaea86939ab4f66a62ac79872 | 714 | hpp | C++ | source/quantum-script-extension-xml--export.hpp | g-stefan/quantum-script-extension-xml | b8184dcdeeb820447578fc7cc5e2efc3301148a2 | [
"MIT",
"Unlicense"
] | null | null | null | source/quantum-script-extension-xml--export.hpp | g-stefan/quantum-script-extension-xml | b8184dcdeeb820447578fc7cc5e2efc3301148a2 | [
"MIT",
"Unlicense"
] | null | null | null | source/quantum-script-extension-xml--export.hpp | g-stefan/quantum-script-extension-xml | b8184dcdeeb820447578fc7cc5e2efc3301148a2 | [
"MIT",
"Unlicense"
] | null | null | null | //
// Quantum Script Extension XML
//
// Copyright (c) 2020-2021 Grigore Stefan <g_stefan@yahoo.com>
// Created by Grigore Stefan <g_stefan@yahoo.com>
//
// MIT License (MIT) <http://opensource.org/licenses/MIT>
//
#ifndef QUANTUM_SCRIPT_EXTENSION_XML__EXPORT_HPP
#define QUANTUM_SCRIPT_EXTENSION_XML__EXPORT_HPP
#ifndef XYO__EXPORT_HPP
#include "xyo--export.hpp"
#endif
#ifdef XYO_COMPILE_DYNAMIC_LIBRARY
# ifdef QUANTUM_SCRIPT_EXTENSION_XML_INTERNAL
# define QUANTUM_SCRIPT_EXTENSION_XML_EXPORT XYO_LIBRARY_EXPORT
# else
# define QUANTUM_SCRIPT_EXTENSION_XML_EXPORT XYO_LIBRARY_IMPORT
# endif
#else
# define QUANTUM_SCRIPT_EXTENSION_XML_EXPORT
#endif
#endif
| 24.62069 | 70 | 0.761905 | g-stefan |
51e6260b89be41930cab597106f0898fbed3c605 | 13,422 | cpp | C++ | MOS_6502_Emulator/Processor.cpp | yu830425/MOS-6502-Simulator | b08495e1225b65df51ba2ad561f27b048a506c31 | [
"MIT"
] | null | null | null | MOS_6502_Emulator/Processor.cpp | yu830425/MOS-6502-Simulator | b08495e1225b65df51ba2ad561f27b048a506c31 | [
"MIT"
] | null | null | null | MOS_6502_Emulator/Processor.cpp | yu830425/MOS-6502-Simulator | b08495e1225b65df51ba2ad561f27b048a506c31 | [
"MIT"
] | null | null | null | #include "Processor.h"
#include <iostream>
Processor::Processor()
{
m_stack = make_shared<Stack>();
m_processingUnit = make_shared<ProcessingUnit>();
m_processingUnit->setStackController(m_stack);
m_commandTable = createCommandMap();
m_commandMap = std::unordered_map<string, any>{
{"LDA", std::function<void(BYTE)>([&](BYTE _1){m_processingUnit->LDA(_1);})},
{"LDX", std::function<void(BYTE)>([&](BYTE _1){m_processingUnit->LDX(_1);})},
{"LDY", std::function<void(BYTE)>([&](BYTE _1){m_processingUnit->LDY(_1);})},
{"STA", std::function<BYTE(void)>([&](){return m_processingUnit->STA();})},
{"STX", std::function<BYTE(void)>([&](){return m_processingUnit->STX();})},
{"STY", std::function<BYTE(void)>([&](){return m_processingUnit->STY();})},
{"SEC", std::function<void(void)>([&](){m_processingUnit->SEC();})},
{"CLC", std::function<void(void)>([&](){m_processingUnit->CLC();})},
{"CLD", std::function<void(void)>([&](){m_processingUnit->CLD();})},
{"SED", std::function<void(void)>([&](){m_processingUnit->SED();})},
{"SEI", std::function<void(void)>([&](){m_processingUnit->SEI();})},
{"CLI", std::function<void(void)>([&](){m_processingUnit->CLI();})},
{"CLV", std::function<void(void)>([&](){m_processingUnit->CLV();})},
{"ADC", std::function<void(BYTE)>([&](BYTE _1){m_processingUnit->ADC(_1);})},
{"SBC", std::function<void(BYTE)>([&](BYTE _1){m_processingUnit->SBC(_1);})},
{"INC", std::function<BYTE(BYTE)>([&](BYTE _1){ return m_processingUnit->INC(_1);})},
{"INX", std::function<void(void)>([&](){m_processingUnit->INX();})},
{"INY", std::function<void(void)>([&](){m_processingUnit->INY();})},
{"DEC", std::function<BYTE(BYTE)>([&](BYTE _1){ return m_processingUnit->DEC(_1);})},
{"DEX", std::function<void(void)>([&](){m_processingUnit->DEX();})},
{"DEY", std::function<void(void)>([&](){m_processingUnit->DEY();})},
{"ASL", std::function<BYTE(BYTE)>([&](BYTE _1){ return m_processingUnit->ASL(_1);})},
{"LSR", std::function<BYTE(BYTE)>([&](BYTE _1){ return m_processingUnit->LSR(_1);})},
{"ROL", std::function<BYTE(BYTE)>([&](BYTE _1){ return m_processingUnit->ROL(_1);})},
{"ROR", std::function<BYTE(BYTE)>([&](BYTE _1){ return m_processingUnit->ROR(_1);})},
{"AND", std::function<void(BYTE)>([&](BYTE _1){m_processingUnit->AND(_1);})},
{"ORA", std::function<void(BYTE)>([&](BYTE _1){m_processingUnit->ORA(_1);})},
{"EOR", std::function<void(BYTE)>([&](BYTE _1){m_processingUnit->EOR(_1);})},
{"PHA", std::function<void(void)>([&](){m_processingUnit->PHA();})},
{"PLA", std::function<void(void)>([&](){m_processingUnit->PLA();})},
{"PHP", std::function<void(void)>([&](){m_processingUnit->PHP();})},
{"PLP", std::function<void(void)>([&](){m_processingUnit->PLP();})},
{"TAX", std::function<void(void)>([&](){m_processingUnit->TAX();})},
{"TAY", std::function<void(void)>([&](){m_processingUnit->TAY();})},
{"TXA", std::function<void(void)>([&](){m_processingUnit->TXA();})},
{"TYA", std::function<void(void)>([&](){m_processingUnit->TYA();})},
{"TSX", std::function<void(void)>([&](){m_processingUnit->TSX();})},
{"TXS", std::function<void(void)>([&](){m_processingUnit->TXS();})},
{"CMP", std::function<void(BYTE)>([&](BYTE _1){m_processingUnit->CMP(_1);})},
{"CPX", std::function<void(BYTE)>([&](BYTE _1){m_processingUnit->CPX(_1);})},
{"CPY", std::function<void(BYTE)>([&](BYTE _1){m_processingUnit->CPY(_1);})},
{"BIT", std::function<void(BYTE)>([&](BYTE _1){m_processingUnit->BIT(_1);})},
{"BCC", std::function<void(BYTE)>([&](BYTE _1){m_processingUnit->BCC(_1);})},
{"BCS", std::function<void(BYTE)>([&](BYTE _1){m_processingUnit->BCS(_1);})},
{"BNE", std::function<void(BYTE)>([&](BYTE _1){m_processingUnit->BNE(_1);})},
{"BEQ", std::function<void(BYTE)>([&](BYTE _1){m_processingUnit->BEQ(_1);})},
{"BPL", std::function<void(BYTE)>([&](BYTE _1){m_processingUnit->BPL(_1);})},
{"BMI", std::function<void(BYTE)>([&](BYTE _1){m_processingUnit->BMI(_1);})},
{"BVC", std::function<void(BYTE)>([&](BYTE _1){m_processingUnit->BVC(_1);})},
{"BVS", std::function<void(BYTE)>([&](BYTE _1){m_processingUnit->BVS(_1);})},
{"JMP", std::function<void(WORD)>([&](WORD _1){m_processingUnit->JMP(_1);})},
{"JSR", std::function<void(WORD)>([&](WORD _1){m_processingUnit->JSR(_1);})},
{"RTS", std::function<void(void)>([&](){m_processingUnit->RTS();})}
};
}
void Processor::setProcessingUnit(std::shared_ptr<ProcessingUnit> processingUnit)
{
m_processingUnit = processingUnit;
}
void Processor::setBus(std::shared_ptr<Bus> bus)
{
m_bus = bus;
m_stack->setBus(m_bus);
}
void Processor::setProgramCounter(WORD address)
{
m_processingUnit->setProgramCounter(address);
}
void Processor::run()
{
while (true)
{
bool increaseProgramCounter = true;
//Fetch
auto programCounter = m_processingUnit->getProgramCounter();
auto x = m_processingUnit->getRegisterX();
auto acc = m_processingUnit->getAccumulator();
auto y = m_processingUnit->getRegisterY();
auto opCode = m_bus->read(programCounter, 1)[0];
if (programCounter == 0xFFF9)
{
cout << endl;
cout << "Emulator is terminated. return code = " << (int)m_processingUnit->getAccumulator() << endl;
break;
}
//Decode
auto command = m_commandTable[opCode];
//cout << command.commandName << endl;
//Read
WORD value = 0;
bool writeback = false;
if (command.mode == AddressMode::Accumulator)
{
value = m_processingUnit->getAccumulator();
}
else if (command.mode == AddressMode::Immediate)
{
value = m_bus->read(programCounter + 1, 1)[0];
}
else if (command.mode == AddressMode::Absolute)
{
auto parameter = m_bus->read(programCounter + 1, 2);
auto address = ((WORD)parameter[1] << 8) + parameter[0];
value = m_bus->read(address, 1)[0];
}
else if (command.mode == AddressMode::ZeroPage)
{
auto address = m_bus->read(programCounter + 1, 1)[0];
value = m_bus->read(address, 1)[0];
}
else if (command.mode == AddressMode::AbsoluteIndirect)
{
auto parameter = m_bus->read(programCounter + 1, 2);
auto address = ((WORD)parameter[1] << 8) + parameter[0];
auto temp = m_bus->read(address, 2);
value = ((WORD)temp[1] << 8) + temp[0];
}
else if (command.mode == AddressMode::AbsoluteIndexedX)
{
auto parameter = m_bus->read(programCounter + 1, 2);
auto address = ((WORD)parameter[1] << 8) + parameter[0];
value = m_bus->read(address + m_processingUnit->getRegisterX(), 1)[0];
}
else if (command.mode == AddressMode::AbsoulteIndexedY)
{
auto parameter = m_bus->read(programCounter + 1, 2);
auto address = ((WORD)parameter[1] << 8) + parameter[0];
value = m_bus->read(address + m_processingUnit->getRegisterY(), 1)[0];
}
else if (command.mode == AddressMode::ZeroPageIndexedX)
{
auto zeroPageAddress = m_bus->read(programCounter + 1, 1)[0];
auto indexX = m_processingUnit->getRegisterX();
value = m_bus->read(zeroPageAddress + indexX, 1)[0];
}
else if (command.mode == AddressMode::ZeroPageIndexedY)
{
auto zeroPageAddress = m_bus->read(programCounter + 1, 1)[0];
auto indexY = m_processingUnit->getRegisterY();
value = m_bus->read(zeroPageAddress + indexY, 1)[0];
}
else if (command.mode == AddressMode::ZeroPageIndexedIndirect)
{
auto zeroPageAddress = m_bus->read(programCounter + 1, 1)[0];
auto indexX = m_processingUnit->getRegisterX();
auto indirectAddress = m_bus->read(zeroPageAddress + indexX, 2);
auto address = ((WORD)indirectAddress[1] << 8) + indirectAddress[0];
value = m_bus->read(address, 1)[0];
}
else if (command.mode == AddressMode::ZeroPageIndirectIndexedY)
{
auto zeroPageAddress = m_bus->read(programCounter + 1, 1)[0];
auto indexY = m_processingUnit->getRegisterY();
auto indirectAddress = m_bus->read(zeroPageAddress, 2);
auto address = ((WORD)indirectAddress[1] << 8) + indirectAddress[0];
value = m_bus->read(address + indexY, 1)[0];
}
//Jump and Branch
if (command.mode == AddressMode::Relative)
{
auto offset = m_bus->read(programCounter + 1, 1)[0];
auto commandAction = std::any_cast<std::function<void(BYTE)>>(m_commandMap[command.commandName]);
commandAction(offset);
continue;
}
if (command.commandName == "JMP" || command.commandName == "JSR")
{
auto commandAction = std::any_cast<std::function<void(WORD)>>(m_commandMap[command.commandName]);
if (command.mode == AddressMode::Absolute)
{
auto parameter = m_bus->read(programCounter + 1, 2);
auto address = ((WORD)parameter[1] << 8) + parameter[0];
commandAction(address);
}
else if (command.mode == AddressMode::AbsoluteIndirect)
{
commandAction(value);
}
continue;
}
if (command.commandName == "RTS")
{
auto commandAction = std::any_cast<std::function<void()>>(m_commandMap[command.commandName]);
commandAction();
continue;
}
//Execute
if (m_commandMap[command.commandName].type() == typeid(std::function<void()>))
{
auto commandAction = std::any_cast<std::function<void()>>(m_commandMap[command.commandName]);
commandAction();
}
else if (m_commandMap[command.commandName].type() == typeid(std::function<void(BYTE)>))
{
auto commandAction = std::any_cast<std::function<void(BYTE)>>(m_commandMap[command.commandName]);
commandAction(value);
}
else if (m_commandMap[command.commandName].type() == typeid(std::function<BYTE()>))
{
auto commandAction = std::any_cast<std::function<BYTE()>>(m_commandMap[command.commandName]);
writeback = true;
value = commandAction();
}
else if (m_commandMap[command.commandName].type() == typeid(std::function<BYTE(BYTE)>))
{
auto commandAction = std::any_cast<std::function<BYTE(BYTE)>>(m_commandMap[command.commandName]);
value = commandAction(value);
}
else
{
std::cout << "Unsupported command" << std::endl;
break;
}
//Write back
if (writeback)
{
if (command.mode == AddressMode::Accumulator)
{
m_processingUnit->setAccumulator(value);
}
else if (command.mode == AddressMode::Absolute)
{
auto parameter = m_bus->read(programCounter + 1, 2);
auto address = ((WORD)parameter[1] << 8) + parameter[0];
m_bus->write(address, std::vector<BYTE>{ (BYTE)value});
}
else if (command.mode == AddressMode::ZeroPage)
{
auto address = m_bus->read(programCounter + 1, 1)[0];
m_bus->write(address, std::vector<BYTE>{ (BYTE)value});
}
else if (command.mode == AddressMode::AbsoluteIndexedX)
{
auto parameter = m_bus->read(programCounter + 1, 2);
auto address = ((WORD)parameter[1] << 8) + parameter[0];
m_bus->write(address + m_processingUnit->getRegisterX(), std::vector<BYTE>{ (BYTE)value});
}
else if (command.mode == AddressMode::AbsoulteIndexedY)
{
auto parameter = m_bus->read(programCounter + 1, 2);
auto address = ((WORD)parameter[1] << 8) + parameter[0];
m_bus->write(address + m_processingUnit->getRegisterY(), std::vector<BYTE>{ (BYTE)value});
}
else if (command.mode == AddressMode::ZeroPageIndexedX)
{
auto zeroPageAddress = m_bus->read(programCounter + 1, 1)[0];
auto indexX = m_processingUnit->getRegisterX();
m_bus->write(zeroPageAddress + indexX, std::vector<BYTE>{ (BYTE)value});
}
else if (command.mode == AddressMode::ZeroPageIndexedY)
{
auto zeroPageAddress = m_bus->read(programCounter + 1, 1)[0];
auto indexY = m_processingUnit->getRegisterY();
m_bus->write(zeroPageAddress + indexY, std::vector<BYTE>{ (BYTE)value});
}
else if (command.mode == AddressMode::ZeroPageIndexedIndirect)
{
auto zeroPageAddress = m_bus->read(programCounter + 1, 1)[0];
auto indexX = m_processingUnit->getRegisterX();
auto indirectAddress = m_bus->read(zeroPageAddress + indexX, 2);
auto address = ((WORD)indirectAddress[1] << 8) + indirectAddress[0];
m_bus->write(address, std::vector<BYTE>{ (BYTE)value});
}
else if (command.mode == AddressMode::ZeroPageIndirectIndexedY)
{
auto zeroPageAddress = m_bus->read(programCounter + 1, 1)[0];
auto indexY = m_processingUnit->getRegisterY();
auto indirectAddress = m_bus->read(zeroPageAddress, 2);
auto address = ((WORD)indirectAddress[1] << 8) + indirectAddress[0];
m_bus->write(address + indexY, std::vector<BYTE>{ (BYTE)value});
//cout << (char)value << endl;
}
}
// Increase Program Counter
if (command.mode == AddressMode::Accumulator)
{
programCounter += 1;
}
else if (command.mode == AddressMode::Implied)
{
programCounter += 1;
}
else if (command.mode == AddressMode::Immediate)
{
programCounter += 2;
}
else if (command.mode == AddressMode::Absolute)
{
programCounter += 3;
}
else if (command.mode == AddressMode::ZeroPage)
{
programCounter += 2;
}
else if (command.mode == AddressMode::AbsoluteIndexedX)
{
programCounter += 3;
}
else if (command.mode == AddressMode::AbsoulteIndexedY)
{
programCounter += 3;
}
else if (command.mode == AddressMode::ZeroPageIndexedX)
{
programCounter += 2;
}
else if (command.mode == AddressMode::ZeroPageIndexedY)
{
programCounter += 2;
}
else if (command.mode == AddressMode::ZeroPageIndexedIndirect)
{
programCounter += 2;
}
else if (command.mode == AddressMode::ZeroPageIndirectIndexedY)
{
programCounter += 2;
}
m_processingUnit->setProgramCounter(programCounter);
}
}
| 35.321053 | 103 | 0.64886 | yu830425 |
51e72748504e4c3436128bf341d152c17a7ea10e | 2,755 | cpp | C++ | paradigms/greedy/134_gas-station.cpp | b1tank/leetcode | 0b71eb7a4f52291ff072b1280d6b76e68f7adfee | [
"MIT"
] | null | null | null | paradigms/greedy/134_gas-station.cpp | b1tank/leetcode | 0b71eb7a4f52291ff072b1280d6b76e68f7adfee | [
"MIT"
] | null | null | null | paradigms/greedy/134_gas-station.cpp | b1tank/leetcode | 0b71eb7a4f52291ff072b1280d6b76e68f7adfee | [
"MIT"
] | null | null | null | // Author: b1tank
// Email: b1tank@outlook.com
//=================================
/*
134_gas-station LeetCode
Solution:
- one pass: return the index after the index where the lowest possible tank is reached (total gas >= total cost)
- better draw graph to show the trend to understand the algorithm
*/
#include <iostream>
#include <sstream> // stringstream, istringstream, ostringstream
#include <string> // to_string(), stoi()
#include <cctype> // isalnum, isalpha, isdigit, islower, isupper, isspace; toupper, tolower
#include <climits> // INT_MAX 2147483647
#include <cmath> // pow(3.0, 4.0)
#include <cstdlib> // rand() % 100 + 1
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <unordered_set> // unordered_set, unordered_multiset
#include <set> // set, multiset
#include <unordered_map> // unordered_map, unordered_multimap
#include <map> // map, multimap
#include <utility> // pair<>
#include <tuple> // tuple<>
#include <algorithm> // reverse, sort, transform, find, remove, count, count_if
#include <memory> // shared_ptr<>, make_shared<>
#include <stdexcept> // invalid_argument
using namespace std;
class Solution {
// bool can_circle(int i, vector<int>& gas, vector<int>& cost) {
// int num = 0;
// int n = gas.size();
// int tank = 0;
// while (num < n) {
// if (tank + gas[i] >= cost[i]) {
// tank = tank + gas[i] - cost[i];
// i = (i+1) % n;
// num++;
// } else {
// break;
// }
// }
// return num == n;
// }
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
// 4 1 2 3
// 2 4 3 1
//0 2 -1 -2 0
//
// 3 1 1
// 1 2 2
//0 2 1 0
// int n = gas.size();
// for (int i = 0; i < n; i++) {
// if (can_circle(i, gas, cost)) {
// return i;
// }
// }
// return -1;
int n = gas.size();
int total_g = 0;
int total_c = 0;
int cur_tank = 0;
int min_tank = INT_MAX;
int min_tank_i = 0;
for (int i = 0; i < n; i++) {
total_g += gas[i];
total_c += cost[i];
cur_tank = cur_tank + gas[i] - cost[i];
if (cur_tank <= min_tank) {
min_tank = cur_tank;
min_tank_i = i;
}
}
if (total_g < total_c) {
return -1;
} else {
return (min_tank_i + 1) % n;
}
}
}; | 29.308511 | 117 | 0.476225 | b1tank |
51ea15502305cb5ec3b07b5b3cd9e3353652fc0f | 2,406 | hpp | C++ | legion/engine/core/ecs/filters/filter_info.hpp | Legion-Engine/Legion-Engine | a2b898e1cc763b82953c6990dde0b379491a30d0 | [
"MIT"
] | 258 | 2020-10-22T07:09:57.000Z | 2021-09-09T05:47:09.000Z | legion/engine/core/ecs/filters/filter_info.hpp | LeonBrands/Legion-Engine | 40aa1f4a8c59eb0824de1cdda8e17d8dba7bed7c | [
"MIT"
] | 51 | 2020-11-17T13:02:10.000Z | 2021-09-07T18:19:39.000Z | legion/engine/core/ecs/filters/filter_info.hpp | Rythe-Interactive/Rythe-Engine.rythe-legacy | c119c494524b069a73100b12dc3d8b898347830d | [
"MIT"
] | 13 | 2020-12-08T08:06:48.000Z | 2021-09-09T05:47:19.000Z | #pragma once
#include <array>
#include <unordered_set>
#include <functional>
#include <core/common/hash.hpp>
/**
* @file filter_info.hpp
*/
namespace legion::core::ecs
{
/**@struct filter_info_base
* @brief Common base class of all filter_info variants.
*/
struct filter_info_base
{
/**@brief Get variant id through polymorphism.
*/
virtual id_type id() LEGION_PURE;
/**@brief Check if the filter variant contains a component type.
* @tparam component_type Type of the component.
*/
template<typename component_type>
bool contains() { return contains(make_hash<component_type>()); }
/**@brief Polymorphically check whether the filter variant contains a certain component type.
* @param id Local id of the component type.
*/
virtual bool contains(id_type id) LEGION_PURE;
/**@brief Polymorphically check whether the filter variant overlaps a certain combination of component types.
* @param components Unordered set of component type ids.
*/
virtual bool contains(const std::unordered_set<id_type>& components) LEGION_PURE;
virtual ~filter_info_base() = default;
};
template<typename... component_types>
struct filter_info : public filter_info_base
{
private:
template<typename component_type>
constexpr static id_type generateId() noexcept
{
return make_hash<component_type>();
}
template<typename component_type0, typename component_type1, typename... component_typeN>
constexpr static id_type generateId() noexcept
{
return combine_hash(make_hash<component_type0>(), generateId<component_type1, component_typeN...>());
}
public:
/**@brief The actual id of the filter variant.
*/
static constexpr id_type filter_id = generateId<component_types...>();
/**@brief Array of the individual component type ids.
*/
static constexpr std::array<id_type, sizeof...(component_types)> composition = { make_hash<component_types>()... };
virtual id_type id();
virtual bool contains(id_type id) noexcept;
virtual bool contains(const std::unordered_set<id_type>& components);
constexpr static bool contains_direct(id_type id) noexcept;
};
}
| 31.657895 | 123 | 0.657107 | Legion-Engine |
51edc2f253669ad6caa3ee9c29458c91e32d7b16 | 7,889 | cpp | C++ | src/lib/utilities.cpp | bloomen/libunittest | b168539c70e5ac8a3c67d295e368d07f3c1854fb | [
"MIT"
] | 2 | 2020-11-05T12:38:35.000Z | 2021-03-19T06:02:03.000Z | src/lib/utilities.cpp | bloomen/libunittest | b168539c70e5ac8a3c67d295e368d07f3c1854fb | [
"MIT"
] | null | null | null | src/lib/utilities.cpp | bloomen/libunittest | b168539c70e5ac8a3c67d295e368d07f3c1854fb | [
"MIT"
] | null | null | null | #include "libunittest/utilities.hpp"
#include <thread>
#include <iostream>
#include <mutex>
#include <cstdlib>
#ifdef _MSC_VER
#include <windows.h>
#include <iomanip>
#else
#include "config.hpp"
#endif
#if HAVE_GCC_ABI_DEMANGLE==1
#include <cxxabi.h>
#endif
namespace unittest {
namespace core {
#if defined(_MSC_VER) && _MSC_VER < 1900
namespace {
const long long g_frequency = []() -> long long
{
LARGE_INTEGER frequency;
QueryPerformanceFrequency(&frequency);
return frequency.QuadPart;
}();
struct windows_high_res_clock {
typedef long long rep;
typedef std::nano period;
typedef std::chrono::duration<rep, period> duration;
typedef std::chrono::time_point<windows_high_res_clock> tp;
static const bool is_steady = true;
static tp now()
{
LARGE_INTEGER count;
QueryPerformanceCounter(&count);
return tp(duration(count.QuadPart * static_cast<rep>(period::den) / g_frequency));
}
};
}
#endif
std::chrono::microseconds
now()
{
#if defined(_MSC_VER) && _MSC_VER < 1900
const auto now = windows_high_res_clock::now();
#else
const auto now = std::chrono::high_resolution_clock::now();
#endif
return std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch());
}
std::string
xml_escape(const std::string& data)
{
std::string escaped;
escaped.reserve(data.size());
for (auto& character : data) {
switch (character) {
case '&': escaped.append("&"); break;
case '\"': escaped.append("""); break;
case '\'': escaped.append("'"); break;
case '<': escaped.append("<"); break;
case '>': escaped.append(">"); break;
default: escaped.append(1, character); break;
}
}
return escaped;
}
std::string
make_iso_timestamp(const std::chrono::system_clock::time_point& time_point,
bool local_time)
{
const auto rawtime = std::chrono::system_clock::to_time_t(time_point);
const auto iso_format = "%Y-%m-%dT%H:%M:%S";
struct std::tm timeinfo;
#ifdef _MSC_VER
if (local_time)
localtime_s(&timeinfo, &rawtime);
else
gmtime_s(&timeinfo, &rawtime);
std::stringstream buffer;
buffer << std::put_time(&timeinfo, iso_format);
return buffer.str();
#else
if (local_time)
timeinfo = *std::localtime(&rawtime);
else
timeinfo = *std::gmtime(&rawtime);
char buffer[20];
std::strftime(buffer, sizeof(buffer), iso_format, &timeinfo);
return buffer;
#endif
}
void
write_to_stream(std::ostream&)
{}
void
write_horizontal_bar(std::ostream& stream,
char character,
int length)
{
const std::string bar(length, character);
stream << bar << std::flush;
}
double
duration_in_seconds(const std::chrono::duration<double>& duration)
{
return std::chrono::duration_cast<std::chrono::duration<double>>(duration).count();
}
bool
is_regex_matched(const std::string& value,
const std::string& regex)
{
return std::regex_match(value, std::regex(regex));
}
bool
is_regex_matched(const std::string& value,
const std::regex& regex)
{
return std::regex_match(value, regex);
}
int
call_functions(const std::vector<std::function<void()>>& functions,
int n_threads)
{
const int n_runs = functions.size();
if (n_threads > n_runs)
n_threads = n_runs;
int counter = 0;
if (n_threads > 1 && n_runs > 1) {
while (counter < n_runs) {
if (n_threads > n_runs - counter)
n_threads = n_runs - counter;
std::vector<std::thread> threads(n_threads);
for (auto& thread : threads)
thread = std::thread(functions[counter++]);
for (auto& thread : threads)
thread.join();
}
} else {
for (auto& function : functions) {
function();
++counter;
}
}
return counter;
}
std::string
limit_string_length(const std::string& value,
int max_length)
{
if (int(value.size()) > max_length) {
return value.substr(0, max_length);
} else {
return value;
}
}
std::string
string_of_file_and_line(const std::string& filename,
int linenumber)
{
return string_of_tagged_text(join(filename, ":", linenumber), "SPOT");
}
std::string
string_of_tagged_text(const std::string& text, const std::string& tag)
{
const std::string id = "@" + tag + "@";
return id + text + id;
}
void
make_threads_happy(std::ostream& stream,
std::vector<std::pair<std::thread, std::shared_ptr<std::atomic_bool>>>& threads,
bool verbose)
{
int n_unfinished = 0;
for (auto& thread : threads)
if (!thread.second->load())
++n_unfinished;
if (n_unfinished && verbose)
stream << "\nWaiting for " << n_unfinished << " tests to finish ... " << std::endl;
for (auto& thread : threads)
thread.first.join();
}
bool
is_numeric(const std::string& value)
{
bool result;
try {
to_number<double>(value);
result = true;
} catch (const std::invalid_argument&) {
result = false;
}
return result;
}
template<>
bool
to_number<bool>(const std::string& value)
{
std::istringstream stream(value);
bool number;
if (stream >> number) {
return number;
} else {
throw std::invalid_argument("Not a boolean: " + value);
}
}
std::string
trim(std::string value)
{
const std::string chars = " \t\n";
std::string check;
while (check!=value) {
check = value;
for (auto& ch : chars) {
value.erase(0, value.find_first_not_of(ch));
value.erase(value.find_last_not_of(ch) + 1);
}
}
return value;
}
std::string
remove_white_spaces(std::string value)
{
value.erase(std::remove(value.begin(), value.end(), ' '), value.end());
return value;
}
std::string
extract_tagged_text(const std::string& message, const std::string& tag)
{
std::string text = "";
const std::string id = "@" + tag + "@";
auto index_start = message.find(id);
if (index_start!=std::string::npos) {
index_start += id.length();
const auto substr = message.substr(index_start);
const auto index_end = substr.find(id);
if (index_end!=std::string::npos) {
text = substr.substr(0, index_end);
}
}
return text;
}
std::string
remove_tagged_text(std::string message, const std::string& tag)
{
auto text = extract_tagged_text(message, tag);
while (!text.empty()) {
const auto token = string_of_tagged_text(text, tag);
const auto index = message.find(token);
message = message.substr(0, index) + message.substr(index+token.length());
text = extract_tagged_text(message, tag);
}
return std::move(message);
}
std::pair<std::string, int>
extract_file_and_line(const std::string& message)
{
std::string filename = "";
int linenumber = -1;
const std::string spot = extract_tagged_text(message, "SPOT");
if (!spot.empty()) {
const auto separator = spot.find_last_of(":");
if (separator!=std::string::npos) {
filename = spot.substr(0, separator);
linenumber = to_number<int>(spot.substr(separator+1));
}
}
return std::make_pair(filename, linenumber);
}
std::string
demangle_type(const std::string& type_name)
{
#if HAVE_GCC_ABI_DEMANGLE==1
int status = -1;
std::unique_ptr<char, void(*)(void*)> result{abi::__cxa_demangle(type_name.c_str(), NULL, NULL, &status), std::free};
return status==0 ? result.get() : type_name;
#else
return type_name;
#endif
}
} // core
} // unittest
| 25.285256 | 121 | 0.610724 | bloomen |
51ef02ea8aecd9d9cd738cd6892119e1c6ed9b6a | 17,497 | hpp | C++ | src/random/dice.hpp | dubkois/Tools | 9f0efdbd37597b9a78b36e9324d236cf2b006526 | [
"MIT"
] | null | null | null | src/random/dice.hpp | dubkois/Tools | 9f0efdbd37597b9a78b36e9324d236cf2b006526 | [
"MIT"
] | null | null | null | src/random/dice.hpp | dubkois/Tools | 9f0efdbd37597b9a78b36e9324d236cf2b006526 | [
"MIT"
] | null | null | null | #ifndef KGD_UTILS_DICE_HPP
#define KGD_UTILS_DICE_HPP
/******************************************************************************//**
* \file
* \brief Contains the logic for random number generation.
*
* Provides aliases for commonly used types as well as the main class Dice.
*/
#include <random>
#include <chrono>
#include <stdexcept>
#include <iostream>
#include <vector>
#include <map>
#include <mutex>
#ifndef NDEBUG
#include <sstream>
#include <exception>
#include <assert.h>
#endif
namespace rng {
/******************************************************************************//**
* \brief Naive truncated normal distribution.
*
* Converges towards a 0.5 efficiency given reasonably bad parameters
* (e.g. mean=max and min << max-stddev, tested with 10e7 evaluations)
*/
template<typename FLOAT>
class truncated_normal_distribution : public std::normal_distribution<FLOAT> {
#ifndef NDEBUG
/// The number of attempts made to generate a number before failing (Debug only)
static constexpr size_t MAX_TRIES = 100;
#endif
public:
/// Creates a normal distribution with the usual parameters mu and sigma constrained to the interval [min, max]
truncated_normal_distribution(FLOAT mu, FLOAT stddev, FLOAT min, FLOAT max, bool nonZero=true)
: std::normal_distribution<FLOAT>(mu,stddev), _min(min), _max(max), _nonZero(nonZero) {
#ifndef NDEBUG
assert(min < max); // No inverted bounds
assert(fabs(mu - min) > 2. * stddev || fabs(mu - max) > 2. * stddev); // At least 47.5% of values are valid
// e-g: min = 0; mu = max = 1; if std < 1/6 then for x a rnd number P(x in [min,max]) > 0.4985
#endif
}
/// Requests production of a new random value
template<typename RNG>
FLOAT operator() (RNG &rng) {
FLOAT res;
#ifndef NDEBUG
size_t tries = 0;
#endif
do {
#ifndef NDEBUG
if (tries++ > MAX_TRIES) {
std::ostringstream oss;
oss << "truncated_normal_distribution("
<< std::normal_distribution<FLOAT>::mean() << ", "
<< std::normal_distribution<FLOAT>::stddev() << ", "
<< _min << ", " << _max << ", " << std::boolalpha << _nonZero
<< ") failed to produce a valid in value in less than "
<< tries << " attempts";
throw std::domain_error(oss.str());
}
#endif
res = std::normal_distribution<FLOAT>::operator()(rng);
} while (res < _min || _max < res || (_nonZero && res == 0));
return res;
}
/// Prints this distribution to the provided stream
friend std::ostream& operator<< (std::ostream &os, const truncated_normal_distribution &d) {
return os << d.mean() << " " << d.stddev() << " " << d._min << " " << d._max;
}
private:
FLOAT _min; ///< The lowest value that can be produced
FLOAT _max; ///< The largest value that can be produced
bool _nonZero; ///< Is zero a forbidden value ?
};
// ===================================================================================
typedef std::uniform_real_distribution<double> uddist; ///< Alias for a decimal uniform distribution
typedef std::uniform_real_distribution<float> ufdist; ///< Alias for a small decimal uniform distribution
typedef std::uniform_int_distribution<uint> uudist; ///< Alias for an unsigned uniform integer distribution
typedef std::uniform_int_distribution<int> usdist; ///< Alias for a signed uniform integer distribution
typedef std::normal_distribution<double> ndist; ///< Alias for a decimal normal distribution
typedef truncated_normal_distribution<double> tndist; ///< Alias for a decimal truncated normal distribution
typedef std::bernoulli_distribution bdist; ///< Alias for a coin flip distribution
/// Non-empty roulette distribution
struct rdist : public std::discrete_distribution<uint> {
/// \cond internal
/// Builds a roulette distribution and asserts that the input data was not empty
template <typename InputIt>
rdist(InputIt first, InputIt last)
: std::discrete_distribution<uint>(first, last) {
if (!(std::distance(first, last) > 0))
throw std::out_of_range("Cannot create roulette distribution with empty range");
}
/// \endcond
};
// ===================================================================================
// =================================================================================================
/// \brief Random number generation for a wide range of use-cases/distributions.
class AbstractDice {
public:
/// The type used as a seed
using Seed_t = unsigned int;
/// The underlying random number generator
using BaseRNG_t = std::mt19937;
/// \return The current time, as viewed by the system, in milli seconds.
/// Used internally as the default seed for dices
static auto currentMilliTime (void) {
return std::chrono::duration_cast<std::chrono::milliseconds >(
std::chrono::high_resolution_clock::now().time_since_epoch()
).count();
}
protected:
/// Random number generator enriched with its seed
struct RNG_t : public BaseRNG_t {
/// Create a rng using the current time as a seed
RNG_t (void) : RNG_t(currentMilliTime()) {}
/// Create a rng using the providing \p seed
RNG_t (Seed_t seed) : BaseRNG_t(seed), _seed(seed) {}
/// Create a copy of the provided RNG_t
RNG_t (const RNG_t & that) = default;
/// Default destructor
virtual ~RNG_t (void) = default;
/// \return a new number from the underlying random number generator
virtual result_type operator() (void) {
return BaseRNG_t::operator ()();
}
/// Assign the provided RNG_t to this
RNG_t& operator= (RNG_t that) {
swap(*this, that);
return *this;
}
/// \return the seed used for this rng
Seed_t getSeed (void) const {
return _seed;
}
/// Compare values based on their underlying operator== and their seed value
friend bool operator== (const RNG_t &lhs, const RNG_t &rhs) {
return static_cast<const BaseRNG_t&>(lhs) == static_cast<const BaseRNG_t&>(rhs)
&& lhs._seed == rhs._seed;
}
/// Delegates serialization of the internal state of the base rng
friend std::ostream& operator<< (std::ostream &os, const RNG_t &rng) {
auto baseFlags = os.flags();
os.setf(std::ios::dec, std::ios::basefield);
os.setf(std::ios::left, std::ios::adjustfield);
auto loc = os.getloc();
os.imbue(std::locale("C"));
os << rng._seed << " " << static_cast<const BaseRNG_t&>(rng);
os.imbue(loc);
os.setf(baseFlags);
return os;
}
/// Delegates deserialization of the internal state of the base rng
friend std::istream& operator>> (std::istream &is, RNG_t &rng) {
auto baseFlags = is.flags();
is.setf(std::ios::dec, std::ios::basefield);
is.setf(std::ios::left, std::ios::adjustfield);
auto loc = is.getloc();
is.imbue(std::locale("C"));
is >> rng._seed >> static_cast<BaseRNG_t&>(rng);
is.imbue(loc);
is.setf(baseFlags);
return is;
}
/// Swaps the contents of two RNG_t objects
friend void swap (RNG_t &lhs, RNG_t &rhs) {
using std::swap;
swap(static_cast<BaseRNG_t&>(lhs), static_cast<BaseRNG_t&>(rhs));
swap(lhs._seed, rhs._seed);
}
private:
Seed_t _seed; ///< The seed used by this rng
};
private:
/// \return the random number generator used by this dice
virtual RNG_t& getRNG (void) = 0;
/// \return a const reference to the random number generator used by this dice
virtual const RNG_t& getRNG (void) const = 0;
public:
virtual ~AbstractDice (void) {}
/// Resets this dice the a blank state starting with \p newSeed
virtual void reset (Seed_t newSeed) = 0;
/// \return The value used to seed this object
Seed_t getSeed(void) const {
return getRNG().getSeed();
}
/// \return A random number following the provided distribution
/// \tparam A valid distribution \see https://en.cppreference.com/w/cpp/numeric/random
template<typename DIST>
auto operator() (DIST d, typename std::enable_if_t<std::is_invocable<DIST, RNG_t&>::value, int> = 0) {
return d(getRNG());
}
/// \return A random integer in the provided range [lower, upper]
/// \tparam I An integer type (int, uint, long, ...)
/// \throws std::invalid_argument if lower > upper
template <typename I>
typename std::enable_if<std::is_integral<I>::value, I>::type
operator() (I lower, I upper) {
if (lower > upper)
throw std::invalid_argument("Cannot operator() a dice with lower > upper");
return operator()(std::uniform_int_distribution<I>(lower, upper));
}
/// \return A random decimal in the provided range [lower, upper[ if lower < upper.
/// \tparam F A decimal type (float, double, ...)
/// \throws std::invalid_argument if lower > upper
template <typename F>
typename std::enable_if<std::is_floating_point<F>::value, F>::type
operator() (F lower, F upper) {
if (lower > upper)
throw std::invalid_argument("Cannot operator() a dice with lower >= upper");
if (lower == upper) return lower;
return operator()(std::uniform_real_distribution<F>(lower, upper));
}
/// \return A random boolean following the provided coin toss probability
bool operator() (double heads) {
return operator()(bdist(heads));
}
/// \return An iterator to a (uniformly) random position in the container
/// \tparam CONTAINER A container with accessible member functions begin() and size()
/// \attention The container MUST NOT be empty
template <typename CONTAINER>
auto operator() (CONTAINER &c) -> decltype(c.begin()) {
typedef typename std::iterator_traits<decltype(c.begin())>::iterator_category category;
if (c.empty())
throw std::invalid_argument("Cannot pick a random value from an empty container");
return operator()(c.begin(), c.size(), category());
}
/// \return An iterator to a (uniformly) random position between 'begin' and 'end'
/// \tparam IT An iterator with at least ForwardIterator capabilities
/// \see https://en.cppreference.com/w/cpp/named_req/ForwardIterator
/// \attention The distance between these iterators must be STRICTLY positive
template <typename IT, typename CAT = typename std::iterator_traits<IT>::iterator_category>
IT operator() (IT begin, IT end) {
auto dist = std::distance(begin, end);
if (dist == 0)
throw std::invalid_argument("Cannot pick a random value from an empty iterator range");
return operator()(begin, dist, CAT());
}
/// \return Either \p v1 or \p v2 depending on the result of an uniform coin toss
/// \tparam A copyable value
template <typename T>
T toss (const T &v1, const T &v2) {
return operator()(.5) ? v1 : v2;
}
/// Assigns either value from \p lhs or \p rhs 's \p field to \p res 's
template <typename T, typename O>
void toss (const O &lhs, const O &rhs, O &res, T O::*field) {
res.*field = toss(lhs.*field, rhs.*field);
}
/// Suffles the contents of \p c via an in-place implementation of the fisher-yattes algorithm
/// \see https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
/// \tparam CONTAINER type with random access capabilities (e.g. vector)
template <typename CONTAINER>
void shuffle(CONTAINER &c) {
using std::swap;
for (size_t i=0; i<c.size(); i++) {
size_t j = operator()(size_t(0), i);
swap(c[i], c[j]);
}
}
/// \return A value T taken at a random position in the map according to discrete distribution
/// described in its values
/// \tparam T a copyable type
/// \attention The map shall NOT be empty
template <typename T, typename ...Ts>
T pickOne (const std::map<T, float, Ts...> &map) {
std::vector<T> keys;
std::vector<float> values;
if (map.empty())
throw std::invalid_argument("Cannot pick a random value from an empty map");
keys.reserve(map.size());
values.reserve(map.size());
for (auto &p: map) {
keys.push_back(p.first);
values.push_back(p.second);
}
return keys.at(operator()(rdist(values.begin(), values.end())));
}
/// \return A random unit vector
/// \tparam T a double compatible type (e.g. float loses some precision, int loses at lot)
template <typename T>
void randomUnitVector (T *t) {
double cosphi = operator()(-1., 1.);
double sinphi = sqrt(1 - cosphi*cosphi);
double theta = operator()(0., 2.*M_PI);
t[0] = sinphi * cos(theta);
t[1] = sinphi * sin(theta);
t[2] = cosphi;
}
/// Write current seed
friend std::ostream& operator<< (std::ostream &os, const AbstractDice &dice) {
return os << "D" << dice.getSeed();
}
/// Retrieve current seed
friend std::istream& operator>> (std::istream &is, AbstractDice &dice) {
char D;
Seed_t seed;
is >> D >> seed;
if (is) dice.reset(seed);
return is;
}
private:
/// \return An iterator it so that \p begin <= it < \p begin + \p dist
/// \tparam IT A random access iterator
template <typename IT, typename D = typename std::iterator_traits<IT>::difference_type>
IT operator() (IT begin, D dist, std::random_access_iterator_tag) {
return begin + operator()(D(0), dist-1);
}
/// \return An iterator it so that \p begin <= it < \p begin + \p dist
/// \tparam IT An iterator with at least forward capabilities
template <typename IT, typename D = typename std::iterator_traits<IT>::difference_type>
IT operator() (IT begin, D dist, std::forward_iterator_tag) {
auto it = begin;
std::advance(it, operator()(D(0), dist-1));
return it;
}
};
/// A dice with focus on fast evaluation time.
/// \attention THREAD-UNSAFE
class FastDice : public AbstractDice {
/// The underlying random number generator
RNG_t _rng;
RNG_t& getRNG (void) override { return _rng; }
public:
/// Builds a default dice with a default seed \see rng::AbstractDice::RNG_t()
FastDice (void) {}
/// Builds a dice starting at \p seed
FastDice (Seed_t seed) : _rng(seed) {}
/// Copy-build this dice based on \p other
FastDice (const FastDice &other) : _rng(other._rng) {}
/// Copy contents of \p other into this dice
FastDice& operator= (FastDice that) {
if (this != &that) swap(_rng, that._rng);
return *this;
}
void reset (Seed_t newSeed) override {
_rng = RNG_t(newSeed);
}
const RNG_t& getRNG (void) const override { return _rng; }
/// Compare the underlying random number generator of both arguments
friend bool operator== (const FastDice &lhs, const FastDice &rhs) {
return lhs._rng == rhs._rng;
}
/// Serialize this dice, saving its complete state
friend void serialize (std::ostream &os, const FastDice &d) {
os << d._rng;
}
/// Deserialize this dice, restoring its complete state
friend void deserialize (std::istream &is, FastDice &d) {
is >> d._rng;
}
/// Asserts that two dices are equal (i-e will produce the same sequence)
friend void assertEqual (const FastDice &lhs, const FastDice &rhs,
bool deepcopy) {
if (!(lhs == rhs)) throw std::logic_error("Dice have different states");
if (deepcopy && &lhs == &rhs) throw std::logic_error("Dice have same address");
}
};
/// A dice with focus on safety over speed
/// \attention THREAD-SAFE
class AtomicDice : public AbstractDice {
/// Specialisation of the random number generator with mutex locking on access
struct AtomicRNG_t : public AbstractDice::RNG_t {
/// The base type
using Base = AbstractDice::RNG_t;
/// The lock type used
using lock = std::unique_lock<std::mutex>;
/// The mutex used for locking
mutable std::mutex mtx;
/// Use default seed \see rng::AbstractDice::RNG_t()
AtomicRNG_t(void) {}
/// Use \p seed
AtomicRNG_t(AbstractDice::Seed_t seed) : Base(seed) {}
/// Move contructible
AtomicRNG_t (AtomicRNG_t &&that) {
lock l (that.mtx);
swap(*this, that);
}
/// Assignable
AtomicRNG_t& operator= (AtomicRNG_t that) {
if (this != &that) { // prevent self lock
lock lthis (mtx, std::defer_lock), lthat(that.mtx, std::defer_lock);
std::lock(lthis, lthat);
swap(*this, that);
}
return *this;
}
/// Copy constructible
AtomicRNG_t (const AtomicRNG_t &that) : Base() {
lock l (that.mtx);
Base::operator=(that);
}
/// Request an number from the underlying generator.
/// Uses a mutex lock to ensure thread safety
AbstractDice::RNG_t::result_type operator() (void) {
lock l(mtx);
return AbstractDice::RNG_t::operator ()();
}
private:
/// Swap the contents of both arguments
void swap (AtomicRNG_t &first, AtomicRNG_t &second) {
using std::swap;
swap(static_cast<Base&>(first), static_cast<Base&>(second));
}
};
/// The underlying random number generator
AtomicRNG_t _rng;
RNG_t& getRNG (void) override { return _rng; }
const RNG_t& getRNG (void) const override { return _rng; }
public:
/// Default dice using default seed \see rng::AbstractDice::RNG_t()
AtomicDice (void) {}
/// Dice starting with \p seed
AtomicDice (Seed_t seed) : _rng(seed) {}
void reset (Seed_t newSeed) override {
_rng = AtomicRNG_t(newSeed);
}
/// AtomicDice cannot be duplicated: equality is not possible thus always returns false
friend constexpr bool operator== (const AtomicDice &, const AtomicDice &) {
return false;
}
};
} // end of namespace rng
#endif // KGD_UTILS_DICE_HPP
| 33.138258 | 113 | 0.643482 | dubkois |
51ef7de9fa709713a2d3867f94be08202fd61df3 | 5,948 | cpp | C++ | Plugins/CaptionMod/SourceSDK/vstdlib/KeyValuesSystem.cpp | anchurcn/MetaHookSv | 8408f57d5abb2109285ed9f7897e3a0776e51c87 | [
"MIT"
] | 31 | 2021-01-20T08:12:48.000Z | 2022-03-29T16:47:50.000Z | Plugins/CaptionMod/SourceSDK/vstdlib/KeyValuesSystem.cpp | anchurcn/MetaHookSv | 8408f57d5abb2109285ed9f7897e3a0776e51c87 | [
"MIT"
] | 118 | 2021-02-04T17:57:48.000Z | 2022-03-31T13:03:21.000Z | Plugins/CaptionMod/SourceSDK/vstdlib/KeyValuesSystem.cpp | anchurcn/MetaHookSv | 8408f57d5abb2109285ed9f7897e3a0776e51c87 | [
"MIT"
] | 13 | 2021-01-21T01:43:19.000Z | 2022-03-15T04:51:19.000Z | #include <interface.h>
#include <vstdlib/IKeyValuesSystem.h>
#include <tier1/KeyValues.h>
#include <tier1/mempool.h>
#include <tier1/utlsymbol.h>
#include <tier0/threadtools.h>
#include <tier1/memstack.h>
#include <vgui/ILocalize.h>
#include <tier0/memdbgon.h>
using namespace vgui;
#if 0
#ifdef NO_SBH
#define KEYVALUES_USE_POOL 1
#endif
class CKeyValuesSystem : public IKeyValuesSystem
{
public:
CKeyValuesSystem(void);
~CKeyValuesSystem(void);
public:
void RegisterSizeofKeyValues(int size);
void *AllocKeyValuesMemory(int size);
void FreeKeyValuesMemory(void *pMem);
HKeySymbol GetSymbolForString(const char *name);
const char *GetStringForSymbol(HKeySymbol symbol);
void GetLocalizedFromANSI(const char *ansi, wchar_t *outBuf, int unicodeBufferSizeInBytes);
void GetANSIFromLocalized(const wchar_t *wchar, char *outBuf, int ansiBufferSizeInBytes);
void AddKeyValuesToMemoryLeakList(void *pMem, HKeySymbol name);
void RemoveKeyValuesFromMemoryLeakList(void *pMem);
private:
#ifdef KEYVALUES_USE_POOL
CMemoryPool *m_pMemPool;
#endif
int m_iMaxKeyValuesSize;
CMemoryStack m_Strings;
struct hash_item_t
{
int stringIndex;
hash_item_t *next;
};
CMemoryPool m_HashItemMemPool;
CUtlVector<hash_item_t> m_HashTable;
int CaseInsensitiveHash(const char *string, int iBounds);
struct MemoryLeakTracker_t
{
int nameIndex;
void *pMem;
};
static bool MemoryLeakTrackerLessFunc(const MemoryLeakTracker_t &lhs, const MemoryLeakTracker_t &rhs)
{
return lhs.pMem < rhs.pMem;
}
CUtlRBTree<MemoryLeakTracker_t, int> m_KeyValuesTrackingList;
CThreadFastMutex m_mutex;
};
//EXPOSE_SINGLE_INTERFACE(CKeyValuesSystem, IKeyValuesSystem, KEYVALUES_INTERFACE_VERSION);
static CKeyValuesSystem g_KeyValuesSystem;
IKeyValuesSystem *KeyValuesSystem(void)
{
return &g_KeyValuesSystem;
}
CKeyValuesSystem::CKeyValuesSystem(void) : m_HashItemMemPool(sizeof(hash_item_t), 64, CMemoryPool::GROW_FAST, "CKeyValuesSystem::m_HashItemMemPool"), m_KeyValuesTrackingList(0, 0, MemoryLeakTrackerLessFunc)
{
m_HashTable.AddMultipleToTail(2047);
for (int i = 0; i < m_HashTable.Count(); i++)
{
m_HashTable[i].stringIndex = 0;
m_HashTable[i].next = NULL;
}
m_Strings.Init(4 * 1024 * 1024, 64 * 1024, 0, 4);
char *pszEmpty = ((char *)m_Strings.Alloc(1));
*pszEmpty = 0;
#ifdef KEYVALUES_USE_POOL
m_pMemPool = NULL;
#endif
m_iMaxKeyValuesSize = sizeof(KeyValues);
}
CKeyValuesSystem::~CKeyValuesSystem(void)
{
#ifdef KEYVALUES_USE_POOL
#ifdef _DEBUG
if (m_pMemPool && m_pMemPool->Count() > 0)
{
DevMsg("Leaked KeyValues blocks: %d\n", m_pMemPool->Count());
}
for (int i = 0; i < m_KeyValuesTrackingList.MaxElement(); i++)
{
if (m_KeyValuesTrackingList.IsValidIndex(i))
{
DevMsg("\tleaked KeyValues(%s)\n", &m_Strings[m_KeyValuesTrackingList[i].nameIndex]);
}
}
#endif
delete m_pMemPool;
#endif
}
void CKeyValuesSystem::RegisterSizeofKeyValues(int size)
{
if (size > m_iMaxKeyValuesSize)
{
m_iMaxKeyValuesSize = size;
}
}
static void KVLeak(char const *fmt, ...)
{
va_list argptr;
char data[1024];
va_start(argptr, fmt);
Q_vsnprintf(data, sizeof(data), fmt, argptr);
va_end(argptr);
Msg(data);
}
void *CKeyValuesSystem::AllocKeyValuesMemory(int size)
{
#ifdef KEYVALUES_USE_POOL
if (!m_pMemPool)
{
m_pMemPool = new CMemoryPool(m_iMaxKeyValuesSize, 1024, CMemoryPool::GROW_FAST, "CKeyValuesSystem::m_pMemPool");
m_pMemPool->SetErrorReportFunc(KVLeak);
}
return m_pMemPool->Alloc(size);
#else
return malloc(size);
#endif
}
void CKeyValuesSystem::FreeKeyValuesMemory(void *pMem)
{
#ifdef KEYVALUES_USE_POOL
m_pMemPool->Free(pMem);
#else
free(pMem);
#endif
}
HKeySymbol CKeyValuesSystem::GetSymbolForString(const char *name)
{
if (!name)
{
return (-1);
}
AUTO_LOCK(m_mutex);
int hash = CaseInsensitiveHash(name, m_HashTable.Count());
int i = 0;
hash_item_t *item = &m_HashTable[hash];
while (1)
{
if (!stricmp(name, (char *)m_Strings.GetBase() + item->stringIndex))
return (HKeySymbol)item->stringIndex;
i++;
if (item->next == NULL)
{
if (item->stringIndex != 0)
{
item->next = (hash_item_t *)m_HashItemMemPool.Alloc(sizeof(hash_item_t));
item = item->next;
}
item->next = NULL;
char *pString = (char *)m_Strings.Alloc(strlen(name) + 1);
if (!pString)
{
Error("Out of keyvalue string space");
return -1;
}
item->stringIndex = pString - (char *)m_Strings.GetBase();
strcpy(pString, name);
return (HKeySymbol)item->stringIndex;
}
item = item->next;
}
Assert(0);
return (-1);
}
const char *CKeyValuesSystem::GetStringForSymbol(HKeySymbol symbol)
{
if (symbol == -1)
return "";
return ((char *)m_Strings.GetBase() + (size_t)symbol);
}
void CKeyValuesSystem::GetLocalizedFromANSI(const char *ansi, wchar_t *outBuf, int unicodeBufferSizeInBytes)
{
// g_pLocalize->ConvertANSIToUnicode(ansi, outBuf, unicodeBufferSizeInBytes);
}
void CKeyValuesSystem::GetANSIFromLocalized(const wchar_t *wchar, char *outBuf, int ansiBufferSizeInBytes)
{
// g_pLocalize->ConvertUnicodeToANSI(wchar, outBuf, ansiBufferSizeInBytes);
}
void CKeyValuesSystem::AddKeyValuesToMemoryLeakList(void *pMem, HKeySymbol name)
{
#ifdef _DEBUG
MemoryLeakTracker_t item = { name, pMem };
m_KeyValuesTrackingList.Insert(item);
#endif
}
void CKeyValuesSystem::RemoveKeyValuesFromMemoryLeakList(void *pMem)
{
#ifdef _DEBUG
MemoryLeakTracker_t item = { 0, pMem };
int index = m_KeyValuesTrackingList.Find(item);
m_KeyValuesTrackingList.RemoveAt(index);
#endif
}
int CKeyValuesSystem::CaseInsensitiveHash(const char *string, int iBounds)
{
unsigned int hash = 0;
for ( ; *string != 0; string++)
{
if (*string >= 'A' && *string <= 'Z')
{
hash = (hash << 1) + (*string - 'A' + 'a');
}
else
{
hash = (hash << 1) + *string;
}
}
return hash % iBounds;
}
#endif
extern IKeyValuesSystem *g_pKeyValuesSystem;
IKeyValuesSystem *KeyValuesSystem(void)
{
return g_pKeyValuesSystem;
} | 20.797203 | 206 | 0.733524 | anchurcn |
51efbb8c8b48f317d727dad4a7ab1065b7afad6c | 1,638 | cpp | C++ | SpatialGDK/Source/SpatialGDK/Private/EngineClasses/SpatialNetBitWriter.cpp | cyberbibby/UnrealGDK | 9502a1ba11d21b3cb64978ba7ea178c63371cdd0 | [
"MIT"
] | 1 | 2020-07-15T12:43:02.000Z | 2020-07-15T12:43:02.000Z | SpatialGDK/Source/SpatialGDK/Private/EngineClasses/SpatialNetBitWriter.cpp | cyberbibby/UnrealGDK | 9502a1ba11d21b3cb64978ba7ea178c63371cdd0 | [
"MIT"
] | null | null | null | SpatialGDK/Source/SpatialGDK/Private/EngineClasses/SpatialNetBitWriter.cpp | cyberbibby/UnrealGDK | 9502a1ba11d21b3cb64978ba7ea178c63371cdd0 | [
"MIT"
] | null | null | null | // Copyright (c) Improbable Worlds Ltd, All Rights Reserved
#include "EngineClasses/SpatialNetBitWriter.h"
#include "UObject/WeakObjectPtr.h"
#include "EngineClasses/SpatialNetDriver.h"
#include "EngineClasses/SpatialPackageMapClient.h"
#include "Schema/UnrealObjectRef.h"
#include "SpatialConstants.h"
#include "Utils/EntityPool.h"
DEFINE_LOG_CATEGORY(LogSpatialNetSerialize);
FSpatialNetBitWriter::FSpatialNetBitWriter(USpatialPackageMapClient* InPackageMap)
: FNetBitWriter(InPackageMap, 0)
{
}
void FSpatialNetBitWriter::SerializeObjectRef(FArchive& Archive, FUnrealObjectRef& ObjectRef)
{
int64 EntityId = ObjectRef.Entity;
Archive << EntityId;
Archive << ObjectRef.Offset;
uint8 HasPath = ObjectRef.Path.IsSet();
Archive.SerializeBits(&HasPath, 1);
if (HasPath)
{
Archive << ObjectRef.Path.GetValue();
}
uint8 HasOuter = ObjectRef.Outer.IsSet();
Archive.SerializeBits(&HasOuter, 1);
if (HasOuter)
{
SerializeObjectRef(Archive, *ObjectRef.Outer);
}
Archive.SerializeBits(&ObjectRef.bNoLoadOnClient, 1);
Archive.SerializeBits(&ObjectRef.bUseClassPathToLoadObject, 1);
}
void FSpatialNetBitWriter::WriteObject(FArchive& Archive, USpatialPackageMapClient* PackageMap, UObject* Object)
{
FUnrealObjectRef ObjectRef = FUnrealObjectRef::FromObjectPtr(Object, PackageMap);
SerializeObjectRef(Archive, ObjectRef);
}
FArchive& FSpatialNetBitWriter::operator<<(UObject*& Value)
{
WriteObject(*this, Cast<USpatialPackageMapClient>(PackageMap), Value);
return *this;
}
FArchive& FSpatialNetBitWriter::operator<<(FWeakObjectPtr& Value)
{
UObject* Object = Value.Get(true);
*this << Object;
return *this;
}
| 26 | 112 | 0.783272 | cyberbibby |
51f4bef7bdaedb5ae4930af5ac27f4dcede67c77 | 24,093 | cpp | C++ | vlc_linux/vlc-3.0.16/modules/gui/qt/dialogs/extensions.cpp | Brook1711/biubiu_Qt6 | 5c4d22a1d1beef63bc6c7738dce6c477c4642803 | [
"MIT"
] | null | null | null | vlc_linux/vlc-3.0.16/modules/gui/qt/dialogs/extensions.cpp | Brook1711/biubiu_Qt6 | 5c4d22a1d1beef63bc6c7738dce6c477c4642803 | [
"MIT"
] | null | null | null | vlc_linux/vlc-3.0.16/modules/gui/qt/dialogs/extensions.cpp | Brook1711/biubiu_Qt6 | 5c4d22a1d1beef63bc6c7738dce6c477c4642803 | [
"MIT"
] | null | null | null | /*****************************************************************************
* extensions.cpp: Extensions manager for Qt: dialogs manager
****************************************************************************
* Copyright (C) 2009-2010 VideoLAN and authors
* $Id: 7b8a732e6c08add04e5692469cf9cc141357bd31 $
*
* Authors: Jean-Philippe André < jpeg # videolan.org >
*
* 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.
*****************************************************************************/
#include "extensions.hpp"
#include "extensions_manager.hpp" // for isUnloading()
#include <vlc_dialog.h>
#include <QGridLayout>
#include <QPushButton>
#include <QSignalMapper>
#include <QLabel>
#include <QPixmap>
#include <QLineEdit>
#include <QTextBrowser>
#include <QCheckBox>
#include <QListWidget>
#include <QComboBox>
#include <QCloseEvent>
#include <QCoreApplication>
#include <QKeyEvent>
#include "util/customwidgets.hpp"
ExtensionsDialogProvider *ExtensionsDialogProvider::instance = NULL;
static void DialogCallback( extension_dialog_t *p_ext_dialog,
void *p_data );
ExtensionsDialogProvider::ExtensionsDialogProvider( intf_thread_t *_p_intf,
extensions_manager_t *p_mgr )
: QObject( NULL ), p_intf( _p_intf ), p_extensions_manager( p_mgr )
{
vlc_dialog_provider_set_ext_callback( p_intf, DialogCallback, NULL );
CONNECT( this, SignalDialog( extension_dialog_t* ),
this, UpdateExtDialog( extension_dialog_t* ) );
}
ExtensionsDialogProvider::~ExtensionsDialogProvider()
{
msg_Dbg( p_intf, "ExtensionsDialogProvider is quitting..." );
vlc_dialog_provider_set_ext_callback( p_intf, NULL, NULL );
}
/** Create a dialog
* Note: Lock on p_dialog->lock must be held. */
ExtensionDialog* ExtensionsDialogProvider::CreateExtDialog(
extension_dialog_t *p_dialog )
{
ExtensionDialog *dialog = new ExtensionDialog( p_intf,
p_extensions_manager,
p_dialog );
p_dialog->p_sys_intf = (void*) dialog;
CONNECT( dialog, destroyDialog( extension_dialog_t* ),
this, DestroyExtDialog( extension_dialog_t* ) );
return dialog;
}
/** Destroy a dialog
* Note: Lock on p_dialog->lock must be held. */
int ExtensionsDialogProvider::DestroyExtDialog( extension_dialog_t *p_dialog )
{
assert( p_dialog );
ExtensionDialog *dialog = ( ExtensionDialog* ) p_dialog->p_sys_intf;
if( !dialog )
return VLC_EGENERIC;
delete dialog;
p_dialog->p_sys_intf = NULL;
vlc_cond_signal( &p_dialog->cond );
return VLC_SUCCESS;
}
/**
* Update/Create/Destroy a dialog
**/
ExtensionDialog* ExtensionsDialogProvider::UpdateExtDialog(
extension_dialog_t *p_dialog )
{
assert( p_dialog );
ExtensionDialog *dialog = ( ExtensionDialog* ) p_dialog->p_sys_intf;
if( p_dialog->b_kill && !dialog )
{
/* This extension could not be activated properly but tried
to create a dialog. We must ignore it. */
return NULL;
}
vlc_mutex_lock( &p_dialog->lock );
if( !p_dialog->b_kill && !dialog )
{
dialog = CreateExtDialog( p_dialog );
dialog->setVisible( !p_dialog->b_hide );
dialog->has_lock = false;
}
else if( !p_dialog->b_kill && dialog )
{
dialog->has_lock = true;
dialog->UpdateWidgets();
if( strcmp( qtu( dialog->windowTitle() ),
p_dialog->psz_title ) != 0 )
dialog->setWindowTitle( qfu( p_dialog->psz_title ) );
dialog->has_lock = false;
dialog->setVisible( !p_dialog->b_hide );
}
else if( p_dialog->b_kill )
{
DestroyExtDialog( p_dialog );
}
vlc_cond_signal( &p_dialog->cond );
vlc_mutex_unlock( &p_dialog->lock );
return dialog;
}
/**
* Ask the dialog manager to create/update/kill the dialog. Thread-safe.
**/
void ExtensionsDialogProvider::ManageDialog( extension_dialog_t *p_dialog )
{
assert( p_dialog );
ExtensionsManager *extMgr = ExtensionsManager::getInstance( p_intf );
assert( extMgr != NULL );
if( !extMgr->isUnloading() )
emit SignalDialog( p_dialog ); // Safe because we signal Qt thread
else
UpdateExtDialog( p_dialog ); // This is safe, we're already in Qt thread
}
/**
* Ask the dialogs provider to create a new dialog
**/
static void DialogCallback( extension_dialog_t *p_ext_dialog,
void *p_data )
{
(void) p_data;
ExtensionsDialogProvider *p_edp = ExtensionsDialogProvider::getInstance();
if( p_edp )
p_edp->ManageDialog( p_ext_dialog );
}
ExtensionDialog::ExtensionDialog( intf_thread_t *_p_intf,
extensions_manager_t *p_mgr,
extension_dialog_t *_p_dialog )
: QDialog( NULL ), p_intf( _p_intf ), p_extensions_manager( p_mgr )
, p_dialog( _p_dialog ), has_lock(true)
{
assert( p_dialog );
CONNECT( ExtensionsDialogProvider::getInstance(), destroyed(),
this, parentDestroyed() );
msg_Dbg( p_intf, "Creating a new dialog: '%s'", p_dialog->psz_title );
this->setWindowFlags( Qt::WindowMinMaxButtonsHint
| Qt::WindowCloseButtonHint );
this->setWindowTitle( qfu( p_dialog->psz_title ) );
layout = new QGridLayout( this );
clickMapper = new QSignalMapper( this );
CONNECT( clickMapper, mapped( QObject* ), this, TriggerClick( QObject* ) );
inputMapper = new QSignalMapper( this );
CONNECT( inputMapper, mapped( QObject* ), this, SyncInput( QObject* ) );
selectMapper = new QSignalMapper( this );
CONNECT( selectMapper, mapped( QObject* ), this, SyncSelection(QObject*) );
UpdateWidgets();
}
ExtensionDialog::~ExtensionDialog()
{
msg_Dbg( p_intf, "Deleting extension dialog '%s'", qtu(windowTitle()) );
}
QWidget* ExtensionDialog::CreateWidget( extension_widget_t *p_widget )
{
QLabel *label = NULL;
QPushButton *button = NULL;
QTextBrowser *textArea = NULL;
QLineEdit *textInput = NULL;
QCheckBox *checkBox = NULL;
QComboBox *comboBox = NULL;
QListWidget *list = NULL;
SpinningIcon *spinIcon = NULL;
struct extension_widget_t::extension_widget_value_t *p_value = NULL;
assert( p_widget->p_sys_intf == NULL );
switch( p_widget->type )
{
case EXTENSION_WIDGET_LABEL:
label = new QLabel( qfu( p_widget->psz_text ), this );
p_widget->p_sys_intf = label;
label->setTextFormat( Qt::RichText );
label->setOpenExternalLinks( true );
return label;
case EXTENSION_WIDGET_BUTTON:
button = new QPushButton( qfu( p_widget->psz_text ), this );
clickMapper->setMapping( button, new WidgetMapper( button, p_widget ) );
CONNECT( button, clicked(), clickMapper, map() );
p_widget->p_sys_intf = button;
return button;
case EXTENSION_WIDGET_IMAGE:
label = new QLabel( this );
label->setPixmap( QPixmap( qfu( p_widget->psz_text ) ) );
if( p_widget->i_width > 0 )
label->setMaximumWidth( p_widget->i_width );
if( p_widget->i_height > 0 )
label->setMaximumHeight( p_widget->i_height );
label->setScaledContents( true );
p_widget->p_sys_intf = label;
return label;
case EXTENSION_WIDGET_HTML:
textArea = new QTextBrowser( this );
textArea->setOpenExternalLinks( true );
textArea->setHtml( qfu( p_widget->psz_text ) );
p_widget->p_sys_intf = textArea;
return textArea;
case EXTENSION_WIDGET_TEXT_FIELD:
textInput = new QLineEdit( this );
textInput->setText( qfu( p_widget->psz_text ) );
textInput->setReadOnly( false );
textInput->setEchoMode( QLineEdit::Normal );
inputMapper->setMapping( textInput, new WidgetMapper( textInput, p_widget ) );
/// @note: maybe it would be wiser to use textEdited here?
CONNECT( textInput, textChanged(const QString &),
inputMapper, map() );
p_widget->p_sys_intf = textInput;
return textInput;
case EXTENSION_WIDGET_PASSWORD:
textInput = new QLineEdit( this );
textInput->setText( qfu( p_widget->psz_text ) );
textInput->setReadOnly( false );
textInput->setEchoMode( QLineEdit::Password );
inputMapper->setMapping( textInput, new WidgetMapper( textInput, p_widget ) );
/// @note: maybe it would be wiser to use textEdited here?
CONNECT( textInput, textChanged(const QString &),
inputMapper, map() );
p_widget->p_sys_intf = textInput;
return textInput;
case EXTENSION_WIDGET_CHECK_BOX:
checkBox = new QCheckBox( this );
checkBox->setText( qfu( p_widget->psz_text ) );
checkBox->setChecked( p_widget->b_checked );
clickMapper->setMapping( checkBox, new WidgetMapper( checkBox, p_widget ) );
CONNECT( checkBox, stateChanged( int ), clickMapper, map() );
p_widget->p_sys_intf = checkBox;
return checkBox;
case EXTENSION_WIDGET_DROPDOWN:
comboBox = new QComboBox( this );
comboBox->setEditable( false );
for( p_value = p_widget->p_values;
p_value != NULL;
p_value = p_value->p_next )
{
comboBox->addItem( qfu( p_value->psz_text ), p_value->i_id );
}
/* Set current item */
if( p_widget->psz_text )
{
int idx = comboBox->findText( qfu( p_widget->psz_text ) );
if( idx >= 0 )
comboBox->setCurrentIndex( idx );
}
selectMapper->setMapping( comboBox, new WidgetMapper( comboBox, p_widget ) );
CONNECT( comboBox, currentIndexChanged( const QString& ),
selectMapper, map() );
return comboBox;
case EXTENSION_WIDGET_LIST:
list = new QListWidget( this );
list->setSelectionMode( QAbstractItemView::ExtendedSelection );
for( p_value = p_widget->p_values;
p_value != NULL;
p_value = p_value->p_next )
{
QListWidgetItem *item =
new QListWidgetItem( qfu( p_value->psz_text ) );
item->setData( Qt::UserRole, p_value->i_id );
list->addItem( item );
}
selectMapper->setMapping( list, new WidgetMapper( list, p_widget ) );
CONNECT( list, itemSelectionChanged(),
selectMapper, map() );
return list;
case EXTENSION_WIDGET_SPIN_ICON:
spinIcon = new SpinningIcon( this );
spinIcon->play( p_widget->i_spin_loops );
p_widget->p_sys_intf = spinIcon;
return spinIcon;
default:
msg_Err( p_intf, "Widget type %d unknown", p_widget->type );
return NULL;
}
}
/**
* Forward click event to the extension
* @param object A WidgetMapper, whose data() is the p_widget
**/
int ExtensionDialog::TriggerClick( QObject *object )
{
assert( object != NULL );
WidgetMapper *mapping = static_cast< WidgetMapper* >( object );
extension_widget_t *p_widget = mapping->getWidget();
QCheckBox *checkBox = NULL;
int i_ret = VLC_EGENERIC;
bool lockedHere = false;
if( !has_lock )
{
vlc_mutex_lock( &p_dialog->lock );
has_lock = true;
lockedHere = true;
}
switch( p_widget->type )
{
case EXTENSION_WIDGET_BUTTON:
i_ret = extension_WidgetClicked( p_dialog, p_widget );
break;
case EXTENSION_WIDGET_CHECK_BOX:
checkBox = static_cast< QCheckBox* >( p_widget->p_sys_intf );
p_widget->b_checked = checkBox->isChecked();
i_ret = VLC_SUCCESS;
break;
default:
msg_Dbg( p_intf, "A click event was triggered by a wrong widget" );
break;
}
if( lockedHere )
{
vlc_mutex_unlock( &p_dialog->lock );
has_lock = false;
}
return i_ret;
}
/**
* Synchronize psz_text with the widget's text() value on update
* @param object A WidgetMapper
**/
void ExtensionDialog::SyncInput( QObject *object )
{
assert( object != NULL );
bool lockedHere = false;
if( !has_lock )
{
vlc_mutex_lock( &p_dialog->lock );
has_lock = true;
lockedHere = true;
}
WidgetMapper *mapping = static_cast< WidgetMapper* >( object );
extension_widget_t *p_widget = mapping->getWidget();
assert( p_widget->type == EXTENSION_WIDGET_TEXT_FIELD
|| p_widget->type == EXTENSION_WIDGET_PASSWORD );
/* Synchronize psz_text with the new value */
QLineEdit *widget = static_cast< QLineEdit* >( p_widget->p_sys_intf );
char *psz_text = widget->text().isNull() ? NULL : strdup( qtu( widget->text() ) );
free( p_widget->psz_text );
p_widget->psz_text = psz_text;
if( lockedHere )
{
vlc_mutex_unlock( &p_dialog->lock );
has_lock = false;
}
}
/**
* Synchronize parameter b_selected in the values list
* @param object A WidgetMapper
**/
void ExtensionDialog::SyncSelection( QObject *object )
{
assert( object != NULL );
struct extension_widget_t::extension_widget_value_t *p_value;
bool lockedHere = false;
if( !has_lock )
{
vlc_mutex_lock( &p_dialog->lock );
has_lock = true;
lockedHere = true;
}
WidgetMapper *mapping = static_cast< WidgetMapper* >( object );
extension_widget_t *p_widget = mapping->getWidget();
assert( p_widget->type == EXTENSION_WIDGET_DROPDOWN
|| p_widget->type == EXTENSION_WIDGET_LIST );
if( p_widget->type == EXTENSION_WIDGET_DROPDOWN )
{
QComboBox *combo = static_cast< QComboBox* >( p_widget->p_sys_intf );
for( p_value = p_widget->p_values;
p_value != NULL;
p_value = p_value->p_next )
{
// if( !qstrcmp( p_value->psz_text, qtu( combo->currentText() ) ) )
if( combo->itemData( combo->currentIndex(), Qt::UserRole ).toInt()
== p_value->i_id )
{
p_value->b_selected = true;
}
else
{
p_value->b_selected = false;
}
}
free( p_widget->psz_text );
p_widget->psz_text = strdup( qtu( combo->currentText() ) );
}
else if( p_widget->type == EXTENSION_WIDGET_LIST )
{
QListWidget *list = static_cast<QListWidget*>( p_widget->p_sys_intf );
QList<QListWidgetItem *> selection = list->selectedItems();
for( p_value = p_widget->p_values;
p_value != NULL;
p_value = p_value->p_next )
{
bool b_selected = false;
foreach( const QListWidgetItem *item, selection )
{
// if( !qstrcmp( qtu( item->text() ), p_value->psz_text ) )
if( item->data( Qt::UserRole ).toInt() == p_value->i_id )
{
b_selected = true;
break;
}
}
p_value->b_selected = b_selected;
}
}
if( lockedHere )
{
vlc_mutex_unlock( &p_dialog->lock );
has_lock = false;
}
}
void ExtensionDialog::UpdateWidgets()
{
assert( p_dialog );
extension_widget_t *p_widget;
FOREACH_ARRAY( p_widget, p_dialog->widgets )
{
if( !p_widget ) continue; /* Some widgets may be NULL at this point */
QWidget *widget;
int row = p_widget->i_row - 1;
int col = p_widget->i_column - 1;
if( row < 0 )
{
row = layout->rowCount();
col = 0;
}
else if( col < 0 )
col = layout->columnCount();
int hsp = __MAX( 1, p_widget->i_horiz_span );
int vsp = __MAX( 1, p_widget->i_vert_span );
if( !p_widget->p_sys_intf && !p_widget->b_kill )
{
widget = CreateWidget( p_widget );
if( !widget )
{
msg_Warn( p_intf, "Could not create a widget for dialog %s",
p_dialog->psz_title );
continue;
}
widget->setVisible( !p_widget->b_hide );
layout->addWidget( widget, row, col, vsp, hsp );
if( ( p_widget->i_width > 0 ) && ( p_widget->i_height > 0 ) )
widget->resize( p_widget->i_width, p_widget->i_height );
p_widget->p_sys_intf = widget;
this->resize( sizeHint() );
/* If an update was required, cancel it as we just created the widget */
p_widget->b_update = false;
}
else if( p_widget->p_sys_intf && !p_widget->b_kill
&& p_widget->b_update )
{
widget = UpdateWidget( p_widget );
if( !widget )
{
msg_Warn( p_intf, "Could not update a widget for dialog %s",
p_dialog->psz_title );
return;
}
widget->setVisible( !p_widget->b_hide );
layout->addWidget( widget, row, col, vsp, hsp );
if( ( p_widget->i_width > 0 ) && ( p_widget->i_height > 0 ) )
widget->resize( p_widget->i_width, p_widget->i_height );
p_widget->p_sys_intf = widget;
this->resize( sizeHint() );
/* Do not update again */
p_widget->b_update = false;
}
else if( p_widget->p_sys_intf && p_widget->b_kill )
{
DestroyWidget( p_widget );
p_widget->p_sys_intf = NULL;
this->resize( sizeHint() );
}
}
FOREACH_END()
}
QWidget* ExtensionDialog::UpdateWidget( extension_widget_t *p_widget )
{
QLabel *label = NULL;
QPushButton *button = NULL;
QTextBrowser *textArea = NULL;
QLineEdit *textInput = NULL;
QCheckBox *checkBox = NULL;
QComboBox *comboBox = NULL;
QListWidget *list = NULL;
SpinningIcon *spinIcon = NULL;
struct extension_widget_t::extension_widget_value_t *p_value = NULL;
assert( p_widget->p_sys_intf != NULL );
switch( p_widget->type )
{
case EXTENSION_WIDGET_LABEL:
label = static_cast< QLabel* >( p_widget->p_sys_intf );
label->setText( qfu( p_widget->psz_text ) );
return label;
case EXTENSION_WIDGET_BUTTON:
// FIXME: looks like removeMappings does not work
button = static_cast< QPushButton* >( p_widget->p_sys_intf );
button->setText( qfu( p_widget->psz_text ) );
clickMapper->removeMappings( button );
clickMapper->setMapping( button, new WidgetMapper( button, p_widget ) );
CONNECT( button, clicked(), clickMapper, map() );
return button;
case EXTENSION_WIDGET_IMAGE:
label = static_cast< QLabel* >( p_widget->p_sys_intf );
label->setPixmap( QPixmap( qfu( p_widget->psz_text ) ) );
return label;
case EXTENSION_WIDGET_HTML:
textArea = static_cast< QTextBrowser* >( p_widget->p_sys_intf );
textArea->setHtml( qfu( p_widget->psz_text ) );
return textArea;
case EXTENSION_WIDGET_TEXT_FIELD:
textInput = static_cast< QLineEdit* >( p_widget->p_sys_intf );
textInput->setText( qfu( p_widget->psz_text ) );
return textInput;
case EXTENSION_WIDGET_PASSWORD:
textInput = static_cast< QLineEdit* >( p_widget->p_sys_intf );
textInput->setText( qfu( p_widget->psz_text ) );
return textInput;
case EXTENSION_WIDGET_CHECK_BOX:
checkBox = static_cast< QCheckBox* >( p_widget->p_sys_intf );
checkBox->setText( qfu( p_widget->psz_text ) );
checkBox->setChecked( p_widget->b_checked );
return checkBox;
case EXTENSION_WIDGET_DROPDOWN:
comboBox = static_cast< QComboBox* >( p_widget->p_sys_intf );
// method widget:clear()
if ( p_widget->p_values == NULL )
{
comboBox->clear();
return comboBox;
}
// method widget:addvalue()
for( p_value = p_widget->p_values;
p_value != NULL;
p_value = p_value->p_next )
{
if ( comboBox->findText( qfu( p_value->psz_text ) ) < 0 )
comboBox->addItem( qfu( p_value->psz_text ), p_value->i_id );
}
return comboBox;
case EXTENSION_WIDGET_LIST:
list = static_cast< QListWidget* >( p_widget->p_sys_intf );
list->clear();
for( p_value = p_widget->p_values;
p_value != NULL;
p_value = p_value->p_next )
{
QListWidgetItem *item =
new QListWidgetItem( qfu( p_value->psz_text ) );
item->setData( Qt::UserRole, p_value->i_id );
list->addItem( item );
}
return list;
case EXTENSION_WIDGET_SPIN_ICON:
spinIcon = static_cast< SpinningIcon* >( p_widget->p_sys_intf );
if( !spinIcon->isPlaying() && p_widget->i_spin_loops != 0 )
spinIcon->play( p_widget->i_spin_loops );
else if( spinIcon->isPlaying() && p_widget->i_spin_loops == 0 )
spinIcon->stop();
p_widget->i_height = p_widget->i_width = 16;
return spinIcon;
default:
msg_Err( p_intf, "Widget type %d unknown", p_widget->type );
return NULL;
}
}
void ExtensionDialog::DestroyWidget( extension_widget_t *p_widget,
bool b_cond )
{
assert( p_widget && p_widget->b_kill );
QWidget *widget = static_cast< QWidget* >( p_widget->p_sys_intf );
delete widget;
p_widget->p_sys_intf = NULL;
if( b_cond )
vlc_cond_signal( &p_dialog->cond );
}
/** Implement closeEvent() in order to intercept the event */
void ExtensionDialog::closeEvent( QCloseEvent * )
{
assert( p_dialog != NULL );
msg_Dbg( p_intf, "Dialog '%s' received a closeEvent",
p_dialog->psz_title );
extension_DialogClosed( p_dialog );
}
/** Grab some keyboard input (ESC, ...) and handle actions manually */
void ExtensionDialog::keyPressEvent( QKeyEvent *event )
{
assert( p_dialog != NULL );
switch( event->key() )
{
case Qt::Key_Escape:
close();
return;
default:
QDialog::keyPressEvent( event );
return;
}
}
void ExtensionDialog::parentDestroyed()
{
msg_Dbg( p_intf, "About to destroy dialog '%s'", p_dialog->psz_title );
deleteLater(); // May not work at this point (event loop can be ended)
p_dialog->p_sys_intf = NULL;
vlc_cond_signal( &p_dialog->cond );
}
| 34.917391 | 90 | 0.583613 | Brook1711 |
51f60f4d28b37309b7d4d0eb515edb9dea2e292a | 7,504 | hpp | C++ | include/Zenject/ZenjectStateMachineBehaviourAutoInjecter.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/Zenject/ZenjectStateMachineBehaviourAutoInjecter.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/Zenject/ZenjectStateMachineBehaviourAutoInjecter.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-array.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Zenject
namespace Zenject {
// Forward declaring type: DiContainer
class DiContainer;
// Forward declaring type: InjectTypeInfo
class InjectTypeInfo;
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Animator
class Animator;
}
// Completed forward declares
// Type namespace: Zenject
namespace Zenject {
// Forward declaring type: ZenjectStateMachineBehaviourAutoInjecter
class ZenjectStateMachineBehaviourAutoInjecter;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::Zenject::ZenjectStateMachineBehaviourAutoInjecter);
DEFINE_IL2CPP_ARG_TYPE(::Zenject::ZenjectStateMachineBehaviourAutoInjecter*, "Zenject", "ZenjectStateMachineBehaviourAutoInjecter");
// Type namespace: Zenject
namespace Zenject {
// Size: 0x28
#pragma pack(push, 1)
// Autogenerated type: Zenject.ZenjectStateMachineBehaviourAutoInjecter
// [TokenAttribute] Offset: FFFFFFFF
class ZenjectStateMachineBehaviourAutoInjecter : public ::UnityEngine::MonoBehaviour {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// private Zenject.DiContainer _container
// Size: 0x8
// Offset: 0x18
::Zenject::DiContainer* container;
// Field size check
static_assert(sizeof(::Zenject::DiContainer*) == 0x8);
// private UnityEngine.Animator _animator
// Size: 0x8
// Offset: 0x20
::UnityEngine::Animator* animator;
// Field size check
static_assert(sizeof(::UnityEngine::Animator*) == 0x8);
public:
// Deleting conversion operator: operator ::System::IntPtr
constexpr operator ::System::IntPtr() const noexcept = delete;
// Get instance field reference: private Zenject.DiContainer _container
::Zenject::DiContainer*& dyn__container();
// Get instance field reference: private UnityEngine.Animator _animator
::UnityEngine::Animator*& dyn__animator();
// public System.Void Construct(Zenject.DiContainer container)
// Offset: 0x1CF073C
void Construct(::Zenject::DiContainer* container);
// public System.Void Start()
// Offset: 0x1CF07A8
void Start();
// static private System.Void __zenInjectMethod0(System.Object P_0, System.Object[] P_1)
// Offset: 0x1CF08A4
static void __zenInjectMethod0(::Il2CppObject* P_0, ::ArrayW<::Il2CppObject*> P_1);
// static private Zenject.InjectTypeInfo __zenCreateInjectTypeInfo()
// Offset: 0x1CF0998
static ::Zenject::InjectTypeInfo* __zenCreateInjectTypeInfo();
// public System.Void .ctor()
// Offset: 0x1CF089C
// Implemented from: UnityEngine.MonoBehaviour
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static ZenjectStateMachineBehaviourAutoInjecter* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::Zenject::ZenjectStateMachineBehaviourAutoInjecter::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<ZenjectStateMachineBehaviourAutoInjecter*, creationType>()));
}
}; // Zenject.ZenjectStateMachineBehaviourAutoInjecter
#pragma pack(pop)
static check_size<sizeof(ZenjectStateMachineBehaviourAutoInjecter), 32 + sizeof(::UnityEngine::Animator*)> __Zenject_ZenjectStateMachineBehaviourAutoInjecterSizeCheck;
static_assert(sizeof(ZenjectStateMachineBehaviourAutoInjecter) == 0x28);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: Zenject::ZenjectStateMachineBehaviourAutoInjecter::Construct
// Il2CppName: Construct
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Zenject::ZenjectStateMachineBehaviourAutoInjecter::*)(::Zenject::DiContainer*)>(&Zenject::ZenjectStateMachineBehaviourAutoInjecter::Construct)> {
static const MethodInfo* get() {
static auto* container = &::il2cpp_utils::GetClassFromName("Zenject", "DiContainer")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Zenject::ZenjectStateMachineBehaviourAutoInjecter*), "Construct", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{container});
}
};
// Writing MetadataGetter for method: Zenject::ZenjectStateMachineBehaviourAutoInjecter::Start
// Il2CppName: Start
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Zenject::ZenjectStateMachineBehaviourAutoInjecter::*)()>(&Zenject::ZenjectStateMachineBehaviourAutoInjecter::Start)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(Zenject::ZenjectStateMachineBehaviourAutoInjecter*), "Start", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: Zenject::ZenjectStateMachineBehaviourAutoInjecter::__zenInjectMethod0
// Il2CppName: __zenInjectMethod0
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(::Il2CppObject*, ::ArrayW<::Il2CppObject*>)>(&Zenject::ZenjectStateMachineBehaviourAutoInjecter::__zenInjectMethod0)> {
static const MethodInfo* get() {
static auto* P_0 = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
static auto* P_1 = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Object"), 1)->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Zenject::ZenjectStateMachineBehaviourAutoInjecter*), "__zenInjectMethod0", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{P_0, P_1});
}
};
// Writing MetadataGetter for method: Zenject::ZenjectStateMachineBehaviourAutoInjecter::__zenCreateInjectTypeInfo
// Il2CppName: __zenCreateInjectTypeInfo
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Zenject::InjectTypeInfo* (*)()>(&Zenject::ZenjectStateMachineBehaviourAutoInjecter::__zenCreateInjectTypeInfo)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(Zenject::ZenjectStateMachineBehaviourAutoInjecter*), "__zenCreateInjectTypeInfo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: Zenject::ZenjectStateMachineBehaviourAutoInjecter::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 52.111111 | 221 | 0.74467 | RedBrumbler |
51f7162278c47e1094dcfb6735dad229399bb294 | 3,732 | cpp | C++ | Code/Tools/ProjectManager/tests/UtilsTests.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-09-13T00:01:12.000Z | 2021-09-13T00:01:12.000Z | Code/Tools/ProjectManager/tests/UtilsTests.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | null | null | null | Code/Tools/ProjectManager/tests/UtilsTests.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-20T11:07:25.000Z | 2021-07-20T11:07:25.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <AzCore/UnitTest/TestTypes.h>
#include <Application.h>
#include <ProjectUtils.h>
#include <ProjectManager_Test_Traits_Platform.h>
#include <QFile>
#include <QTextStream>
#include <QTimer>
#include <QApplication>
#include <QKeyEvent>
#include <QDir>
namespace O3DE::ProjectManager
{
namespace ProjectUtils
{
class ProjectManagerUtilsTests
: public ::UnitTest::ScopedAllocatorSetupFixture
{
public:
ProjectManagerUtilsTests()
{
m_application = AZStd::make_unique<ProjectManager::Application>();
m_application->Init(false);
QDir dir;
dir.mkdir("ProjectA");
dir.mkdir("ProjectB");
QFile origFile("ProjectA/origFile.txt");
if (origFile.open(QIODevice::ReadWrite))
{
QTextStream stream(&origFile);
stream << "orig" << Qt::endl;
origFile.close();
}
QFile replaceFile("ProjectA/replaceFile.txt");
if (replaceFile.open(QIODevice::ReadWrite))
{
QTextStream stream(&replaceFile);
stream << "replace" << Qt::endl;
replaceFile.close();
}
}
~ProjectManagerUtilsTests()
{
QDir dirA("ProjectA");
dirA.removeRecursively();
QDir dirB("ProjectB");
dirB.removeRecursively();
m_application.reset();
}
AZStd::unique_ptr<ProjectManager::Application> m_application;
};
#if AZ_TRAIT_DISABLE_FAILED_PROJECT_MANAGER_TESTS
TEST_F(ProjectManagerUtilsTests, DISABLED_MoveProject_Succeeds)
#else
TEST_F(ProjectManagerUtilsTests, MoveProject_Succeeds)
#endif // !AZ_TRAIT_DISABLE_FAILED_PROJECT_MANAGER_TESTS
{
EXPECT_TRUE(MoveProject(
QDir::currentPath() + QDir::separator() + "ProjectA",
QDir::currentPath() + QDir::separator() + "ProjectB",
nullptr, true));
QFileInfo origFile("ProjectA/origFile.txt");
EXPECT_TRUE(!origFile.exists());
QFileInfo replaceFile("ProjectA/replaceFile.txt");
EXPECT_TRUE(!replaceFile.exists());
QFileInfo origFileMoved("ProjectB/origFile.txt");
EXPECT_TRUE(origFileMoved.exists() && origFileMoved.isFile());
QFileInfo replaceFileMoved("ProjectB/replaceFile.txt");
EXPECT_TRUE(replaceFileMoved.exists() && replaceFileMoved.isFile());
}
#if AZ_TRAIT_DISABLE_FAILED_PROJECT_MANAGER_TESTS
TEST_F(ProjectManagerUtilsTests, DISABLED_ReplaceFile_Succeeds)
#else
TEST_F(ProjectManagerUtilsTests, ReplaceFile_Succeeds)
#endif // !AZ_TRAIT_DISABLE_FAILED_PROJECT_MANAGER_TESTS
{
EXPECT_TRUE(ReplaceFile("ProjectA/origFile.txt", "ProjectA/replaceFile.txt", nullptr, false));
QFile origFile("ProjectA/origFile.txt");
if (origFile.open(QIODevice::ReadOnly))
{
QTextStream stream(&origFile);
QString line = stream.readLine();
EXPECT_EQ(line, "replace");
origFile.close();
}
else
{
FAIL();
}
}
} // namespace ProjectUtils
} // namespace O3DE::ProjectManager
| 32.172414 | 158 | 0.582529 | aaarsene |
51f8c620dea4e3b50e830e6d7a085944487df96f | 2,990 | cpp | C++ | elfz/program_header.cpp | cristivlas/zerobugs | 5f080c8645b123d7887fd8a64f60e8d226e3b1d5 | [
"BSL-1.0"
] | 2 | 2018-03-19T23:27:47.000Z | 2018-06-24T16:15:19.000Z | elfz/program_header.cpp | cristivlas/zerobugs | 5f080c8645b123d7887fd8a64f60e8d226e3b1d5 | [
"BSL-1.0"
] | null | null | null | elfz/program_header.cpp | cristivlas/zerobugs | 5f080c8645b123d7887fd8a64f60e8d226e3b1d5 | [
"BSL-1.0"
] | 1 | 2021-11-28T05:39:05.000Z | 2021-11-28T05:39:05.000Z | //
// $Id$
//
// -------------------------------------------------------------------------
// This file is part of ZeroBugs, Copyright (c) 2010 Cristian L. Vlasceanu
//
// 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 <stdexcept>
#include "public/binary.h"
#include "public/error.h"
#include "public/headers.h"
#include "public/program_header.h"
#ifndef __GNUC__
#define __PRETTY_FUNCTION__ __func__
#endif
using namespace std;
using namespace ELF;
#define SELECT(f) ((klass() == ELFCLASS32) ? hdr32_->f : hdr64_->f)
#define RETURN(f) assert(!is_null()); return SELECT(f)
ProgramHeader::ProgramHeader(Elf* elf)
: Selector(elf)
, hdr64_(0)
, index_(0)
{
switch (klass())
{
case ELFCLASS32:
hdr32_ = elf32_getphdr(this->elf());
break;
case ELFCLASS64:
hdr64_ = elf64_getphdr(this->elf());
break;
default:
assert(false);
}
if (is_null())
{
throw Error("elfxx_getpshdr");
}
}
ProgramHeader::ProgramHeader
(
const ProgramHeader& prev,
void* hdr,
size_t index
)
: Selector(prev)
, hdr64_(reinterpret_cast<Elf64_Phdr*>(hdr))
, index_(index)
{
}
boost::shared_ptr<ProgramHeader> ProgramHeader::next() const
{
Binary::Header header(elf());
return next(header);
}
boost::shared_ptr<ProgramHeader>
ProgramHeader::next(const Binary::Header& header) const
{
if (is_null())
{
throw out_of_range(__PRETTY_FUNCTION__);
}
boost::shared_ptr<ProgramHeader> ph;
if (index_ + 1 < header.phnum())
{
void* nxt = 0;
switch (klass())
{
case ELFCLASS32:
nxt = (hdr32_ + 1);
break;
case ELFCLASS64:
nxt = (hdr64_ + 1);
break;
default:
assert(false);
}
if (nxt)
{
boost::shared_ptr<ProgramHeader> p(
new ProgramHeader(*this, nxt, index_ + 1));
ph = p;
}
}
return ph;
}
ElfW(Word) ProgramHeader::type() const
{
RETURN(p_type);
}
ElfW(Word) ProgramHeader::flags() const
{
RETURN(p_flags);
}
ElfW(Off) ProgramHeader::offset() const
{
RETURN(p_offset);
}
ElfW(Addr) ProgramHeader::vaddr() const
{
RETURN(p_vaddr);
}
ElfW(Addr) ProgramHeader::paddr() const
{
RETURN(p_paddr);
}
ElfW(Xword) ProgramHeader::filesz() const
{
RETURN(p_filesz);
}
ElfW(Xword) ProgramHeader::memsz() const
{
RETURN(p_memsz);
}
ElfW(Xword) ProgramHeader::align() const
{
RETURN(p_align);
}
boost::shared_ptr<ProgramHeader>
IterationTraits<ProgramHeader>::first(File& file)
{
assert(file.elf());
return boost::shared_ptr<ProgramHeader>(new ProgramHeader(file.elf()));
}
// vim: tabstop=4:softtabstop=4:expandtab:shiftwidth=4
| 17.48538 | 76 | 0.582943 | cristivlas |
51fa446c6ceb10537b11092cd9baae2c077487ab | 25,583 | cpp | C++ | Crypto/C-Code/ECC/eccl.cpp | dbmcclain/Lisp-Actors | f293326c52bf658fc613237cbb4f740f1ae3b0c1 | [
"Unlicense"
] | 43 | 2020-10-29T18:05:40.000Z | 2022-03-29T03:47:01.000Z | Crypto/C-Code/ECC/eccl.cpp | dbmcclain/Lisp-Actors | f293326c52bf658fc613237cbb4f740f1ae3b0c1 | [
"Unlicense"
] | 1 | 2021-12-31T01:36:49.000Z | 2021-12-31T15:21:54.000Z | Crypto/C-Code/ECC/eccl.cpp | dbmcclain/Lisp-Actors | f293326c52bf658fc613237cbb4f740f1ae3b0c1 | [
"Unlicense"
] | 6 | 2020-11-07T07:31:27.000Z | 2022-01-09T18:48:19.000Z | // ecc.cpp -- NIST B571 ECC over F_2^571
// DMcClain/Acudora 11/11
// ---------------------------------------------
#include "ecc.h"
// ------------------------------------------------------------
static const int lmask = sizeof(ulong)-1;
// ------------------------------------------------------------
static_gf128_opnd::static_gf128_opnd()
{
opnd = bytes;
}
static_gf128_opnd::static_gf128_opnd(const gf128_opnd &op)
{
opnd = bytes;
gf128_copy(op);
}
static_gf128_opnd::static_gf128_opnd(const ubyte *pnum, uint nb)
{
opnd = bytes;
if(nb < sizeof(gf128_opnd_bytes))
{
uint nrem = sizeof(gf128_opnd_bytes) - nb;
int ix;
for(ix = 0; ix < nrem; ++ix)
opnd[ix ^ lmask] = 0;
for(int jx = 0; ix < sizeof(gf128_opnd_bytes); ++ix, ++jx)
opnd[ix ^ lmask] = pnum[jx ^ lmask];
}
else
{
uint nrem = nb - sizeof(gf128_opnd_bytes);
memmove(opnd, pnum + nrem, sizeof(gf128_opnd_bytes));
}
}
static_gf128_opnd::static_gf128_opnd(const char *str)
{
opnd = bytes;
init_from_string(str);
}
gf128_opnd& gf128_opnd::init_from_string(const char *str)
{
int ix, jx;
zero();
for(jx = sizeof(gf128_opnd_bytes), ix = strlen(str);
(--jx, ix -= 2, (jx >= 0) && (ix >= 0));
)
{
int x;
sscanf(&str[ix], "%02x", &x);
opnd[jx ^ lmask] = x;
}
if((jx >= 0) && (-1 == ix))
{
int x;
sscanf(str, "%01x", &x);
opnd[jx ^ lmask] = x;
}
}
// -----------------------------------------------------------
gf128_opnd& gf128_add(const gf128_opnd &op1, const gf128_opnd &op2, gf128_opnd &opdst)
{
ulong* pdst = (ulong*)opdst.opnd;
ulong* p1 = (ulong*)op1.opnd;
ulong* p2 = (ulong*)op2.opnd;
pdst[0] = p1[0] ^ p2[0];
pdst[1] = p1[1] ^ p2[1];
return opdst;
}
void gf128_opnd::zero()
{
memset(opnd, 0, sizeof(gf128_opnd_bytes));
}
void gf128_opnd::one()
{
zero();
opnd[(sizeof(gf128_opnd_bytes)-1)^lmask] = 1;
}
void gf128_opnd::two()
{
zero();
opnd[(sizeof(gf128_opnd_bytes)-1)^lmask] = 2;
}
void gf128_opnd::prim()
{
zero();
opnd[(sizeof(gf128_opnd_bytes)-1) ^ lmask] = 0x87;
}
bool gf128_opnd::is_one() const
{
ulong *p = (ulong*)opnd;
if(p[0])
return false;
return (1 == p[1]);
}
void gf128_opnd::step()
{
ulong *p = (ulong*)opnd;
int hibit = (opnd[0 ^ lmask] & 0x080);
static const int nrsh = 8*sizeof(ulong)-1;
p[0] = (p[0] << 1) | (p[1] >> nrsh);
p[1] <<= 1;
if(hibit)
opnd[(sizeof(gf128_opnd_bytes)-1) ^ lmask] ^= 0x087;
}
void gf128_opnd::first_bit(int &ix, ubyte &mask) const
{
ulong *p = (ulong*)opnd;
if(p[0])
ix = 0;
else if(p[1])
ix = sizeof(ulong);
else
{
ix = -1;
return;
}
ubyte b;
for(; ix < sizeof(gf128_opnd_bytes); ++ix)
if((b = opnd[ix ^ lmask])) // assignment intended
break;
for(mask = 0x080; 0 == (mask & b); mask >>= 1)
;
}
int gf128_opnd::integer_length() const
{
int ix;
ubyte mask;
first_bit(ix, mask);
if(ix < 0)
return 0;
ix = 8*(sizeof(gf128_opnd_bytes) - ix);
for(mask <<= 1; mask; mask <<= 1)
--ix;
return ix;
}
gf128_opnd& gf128_opnd::gf128_copy(const gf128_opnd &op)
{
if(opnd != op.opnd)
memmove(opnd, op.opnd, sizeof(gf128_opnd_bytes));
return *this;
}
gf128_opnd& gf128_mul(const gf128_opnd &op1, const gf128_opnd &op2, gf128_opnd &opdst)
{
int ix;
ubyte mask;
op2.first_bit(ix, mask);
if(ix < 0)
{
opdst.zero();
return opdst;
}
static_gf128_opnd ans(op1);
mask >>= 1;
if(0 == mask)
{
mask = 0x080;
++ix;
}
for(; ix < sizeof(gf128_opnd_bytes); ++ix, mask = 0x080)
{
for(; mask; mask >>= 1)
{
ans.step();
if(mask & op2.opnd[ix^lmask])
gf128_add(ans, op1, ans);
}
}
opdst.gf128_copy(ans);
return opdst;
}
#if 0
gf128_opnd& gf128_inv(const gf128_opnd &op, gf128_opnd &opdst)
{
static_gf128_opnd p(op);
opdst.one();
for(int ix = 1; ix < 128; ++ix)
{
gf128_mul(p, p, p);
gf128_mul(p, opdst, opdst);
}
return opdst;
}
#else
gf128_opnd& gf128_inv(const gf128_opnd &op, gf128_opnd &opdst)
{
if(op.is_one())
{
opdst.one();
return opdst;
}
// using extended Euclidean algorithm
static_gf128_opnd u;
static_gf128_opnd v(op);
static_gf128_opnd g1;
static_gf128_opnd g2;
static_gf128_opnd tmp;
g2.one();
{
int j = 129 - v.integer_length();
gf128_shiftl(v, j, u);
u.opnd[(sizeof(gf128_opnd_bytes)-1) ^ lmask] ^= 0x087;
gf128_shiftl(g2, j, g1);
}
while(!(u.is_one()))
{
// if(!u)
// throw("gf128_inv: zero divisor");
int j = u.integer_length() - v.integer_length();
if(j < 0)
{
ubyte *pb = u.opnd;
u.opnd = v.opnd;
v.opnd = pb;
pb = g1.opnd;
g1.opnd = g2.opnd;
g2.opnd = pb;
j = -j;
}
gf128_shiftl(v, j, tmp);
gf128_add(u, tmp, u);
gf128_shiftl(g2, j, tmp);
gf128_add(g1, tmp, g1);
}
opdst.gf128_copy(g1);
return opdst;
}
#endif
gf128_opnd& gf128_div(const gf128_opnd& op1, const gf128_opnd& op2, gf128_opnd& opdst)
{
static_gf128_opnd tmp;
gf128_inv(op2, tmp);
return gf128_mul(op1, tmp, opdst);
}
bool gf128_opnd::operator!() const
{
ulong *p = (ulong*)opnd;
return ((p[0] == 0) && (p[1] == 0));
}
gf128_opnd& gf128_oneplus(const gf128_opnd &op, gf128_opnd &opdst)
{
opdst.gf128_copy(op);
opdst.opnd[(sizeof(gf128_opnd_bytes)-1)^lmask] ^= 1;
return opdst;
}
bool gf128_opnd::operator==(const gf128_opnd &op) const
{
if(opnd == op.opnd)
return true;
ulong *p1 = (ulong*)opnd;
ulong *p2 = (ulong*)op.opnd;
return ((p1[0] == p2[0]) && (p1[1] == p2[1]));
}
gf128_opnd& gf128_shiftl(const gf128_opnd &op, int nsh, gf128_opnd &opdst)
{
int nw = nsh / (8*sizeof(ulong));
if(nw > 0)
{
int nb = nw*sizeof(ulong);
nsh -= 8 * nb;
int nrem = sizeof(gf128_opnd_bytes) - nb;
memmove(opdst.opnd, op.opnd + nb, nrem);
memset(opdst.opnd+nrem, 0, nb);
}
else
opdst.gf128_copy(op);
int nb = nsh / 8;
if(nb > 0)
{
nsh -= 8 * nb;
int ix, jx;
for(ix = 0, jx = nb; jx < sizeof(gf128_opnd_bytes); ++ix, ++jx)
opdst.opnd[ix ^ lmask] = opdst.opnd[jx ^ lmask];
for(; ix < sizeof(gf128_opnd_bytes); ++ix)
opdst.opnd[ix ^ lmask] = 0;
}
if(nsh > 0)
{
int ix;
int rsh = 8*sizeof(ulong) - nsh;
ulong *p = (ulong*)opdst.opnd;
for(ix = 0; ix < sizeof(gf128_opnd_bytes)/sizeof(ulong)-1; ++ix)
p[ix] = ((p[ix] << nsh) |
(p[ix+1] >> rsh));
p[ix] <<= nsh;
}
return opdst;
}
void gf128_opnd::show()
{
for(int ix = 0; ix < sizeof(gf128_opnd_bytes); ++ix)
printf("%02X", opnd[ix ^ lmask]);
}
// ------------------------------------------------------------
// ------------------------------------------------------------
static_gf571_opnd::static_gf571_opnd()
{
opnd = bytes;
}
static_gf571_opnd::static_gf571_opnd(const gf571_opnd &op)
{
opnd = bytes;
gf571_copy(op);
}
static_gf571_opnd::static_gf571_opnd(const ubyte *pnum, uint nb)
{
opnd = bytes;
if(nb < sizeof(gf571_opnd_bytes))
{
uint nrem = sizeof(gf571_opnd_bytes) - nb;
int ix;
for(ix = 0; ix < nrem; ++ix)
opnd[ix ^ lmask] = 0;
for(int jx = 0; ix < sizeof(gf571_opnd_bytes); ++ix, ++jx)
opnd[ix ^ lmask] = pnum[jx ^ lmask];
}
else
{
uint nrem = nb - sizeof(gf571_opnd_bytes);
memmove(opnd, pnum + nrem, sizeof(gf571_opnd_bytes));
opnd[0 ^ lmask] &= 0x07;
}
}
static_gf571_opnd::static_gf571_opnd(const char *str)
{
opnd = bytes;
init_from_string(str);
}
gf571_opnd& gf571_opnd::init_from_string(const char *str)
{
int ix, jx;
zero();
for(jx = sizeof(gf571_opnd_bytes), ix = strlen(str);
(--jx, ix -= 2, (jx >= 0) && (ix >= 0));
)
{
int x;
sscanf(&str[ix], "%02x", &x);
opnd[jx ^ lmask] = x;
}
if((jx >= 0) && (-1 == ix))
{
int x;
sscanf(str, "%01x", &x);
opnd[jx ^ lmask] = x;
}
}
// -----------------------------------------------------------
gf571_opnd& gf571_add(const gf571_opnd &op1, const gf571_opnd &op2, gf571_opnd &opdst)
{
ulong* pdst = (ulong*)opdst.opnd;
ulong* p1 = (ulong*)op1.opnd;
ulong* p2 = (ulong*)op2.opnd;
for(int ix = sizeof(gf571_opnd_bytes)/sizeof(ulong); --ix >= 0;)
*pdst++ = *p1++ ^ *p2++;
return opdst;
}
void gf571_opnd::zero()
{
memset(opnd, 0, sizeof(gf571_opnd_bytes));
}
void gf571_opnd::one()
{
zero();
opnd[(sizeof(gf571_opnd_bytes)-1)^lmask] = 1;
}
void gf571_opnd::two()
{
zero();
opnd[(sizeof(gf571_opnd_bytes)-1)^lmask] = 2;
}
void gf571_opnd::prim()
{
zero();
opnd[ 0 ^ lmask] = 0x08;
opnd[(sizeof(gf571_opnd_bytes)-2) ^ lmask] = 0x04;
opnd[(sizeof(gf571_opnd_bytes)-1) ^ lmask] = 0x25;
}
bool gf571_opnd::is_one() const
{
int ix;
ulong *p = (ulong*)opnd;
for(ix = 0; ix < sizeof(gf571_opnd_bytes)/sizeof(ulong)-1; ++ix)
if(p[ix])
return false;
return (1 == p[ix]);
}
void gf571_opnd::step()
{
int ix;
ulong *p = (ulong*)opnd;
static const int nrsh = 8*sizeof(ulong)-1;
for(ix = 0; ix < sizeof(gf571_opnd_bytes)/sizeof(ulong)-1; ++ix)
p[ix] = ((p[ix] << 1) |
(p[ix+1] >> nrsh));
p[ix] <<= 1;
if(opnd[0 ^ lmask] & 0x08)
{
opnd[ 0 ^ lmask] ^= 0x08;
opnd[(sizeof(gf571_opnd_bytes)-2) ^ lmask] ^= 0x04;
opnd[(sizeof(gf571_opnd_bytes)-1) ^ lmask] ^= 0x25;
}
}
void gf571_opnd::first_bit(int &ix, ubyte &mask) const
{
ulong *p = (ulong*)opnd;
for(ix = 0; ix < sizeof(gf571_opnd_bytes)/sizeof(ulong); ++ix)
if(p[ix])
break;
if(ix >= sizeof(gf571_opnd_bytes)/sizeof(ulong))
{
ix = -1;
return;
}
ix *= sizeof(ulong);
ubyte b;
for(; ix < sizeof(gf571_opnd_bytes); ++ix)
if(b = opnd[ix ^ lmask]) // assignment intended
break;
for(mask = 0x080; 0 == (mask & b); mask >>= 1)
;
}
int gf571_opnd::integer_length() const
{
int ix;
ubyte mask;
first_bit(ix, mask);
if(ix < 0)
return 0;
ix = 8*(sizeof(gf571_opnd_bytes) - ix);
for(mask <<= 1; mask; mask <<= 1)
--ix;
return ix;
}
gf571_opnd& gf571_opnd::gf571_copy(const gf571_opnd &op)
{
if(opnd != op.opnd)
memmove(opnd, op.opnd, sizeof(gf571_opnd_bytes));
return *this;
}
gf571_opnd& gf571_mul(const gf571_opnd &op1, const gf571_opnd &op2, gf571_opnd &opdst)
{
int ix;
ubyte mask;
op2.first_bit(ix, mask);
if(ix < 0)
{
opdst.zero();
return opdst;
}
static_gf571_opnd ans(op1);
mask >>= 1;
if(0 == mask)
{
mask = 0x080;
++ix;
}
for(; ix < sizeof(gf571_opnd_bytes); ++ix, mask = 0x080)
{
for(; mask; mask >>= 1)
{
ans.step();
if(mask & op2.opnd[ix^lmask])
gf571_add(ans, op1, ans);
}
}
opdst.gf571_copy(ans);
return opdst;
}
#if 0
gf571_opnd& gf571_inv(const gf571_opnd &op, gf571_opnd &opdst)
{
static_gf571_opnd p(op);
opdst.one();
for(int ix = 1; ix < 571; ++ix)
{
gf571_mul(p, p, p);
gf571_mul(p, opdst, opdst);
}
return opdst;
}
#else
gf571_opnd& gf571_inv(const gf571_opnd &op, gf571_opnd &opdst)
{
// using extended Euclidean algorithm
static_gf571_opnd u(op);
static_gf571_opnd v;
static_gf571_opnd g1;
static_gf571_opnd g2;
static_gf571_opnd tmp;
v.prim();
g1.one();
g2.zero();
while(!(u.is_one()))
{
// if(!u)
// throw("gf571_inv: zero divisor");
int j = u.integer_length() - v.integer_length();
if(j < 0)
{
ubyte *pb = u.opnd;
u.opnd = v.opnd;
v.opnd = pb;
pb = g1.opnd;
g1.opnd = g2.opnd;
g2.opnd = pb;
j = -j;
}
gf571_shiftl(v, j, tmp);
gf571_add(u, tmp, u);
gf571_shiftl(g2, j, tmp);
gf571_add(g1, tmp, g1);
}
opdst.gf571_copy(g1);
return opdst;
}
#endif
gf571_opnd& gf571_div(const gf571_opnd& op1, const gf571_opnd& op2, gf571_opnd& opdst)
{
static_gf571_opnd tmp;
gf571_inv(op2, tmp);
return gf571_mul(op1, tmp, opdst);
}
bool gf571_opnd::operator!() const
{
ulong *p = (ulong*)opnd;
for(int ix = sizeof(gf571_opnd_bytes)/sizeof(ulong); --ix >= 0; ++p)
if(*p)
return false;
return true;
}
gf571_opnd& gf571_oneplus(const gf571_opnd &op, gf571_opnd &opdst)
{
opdst.gf571_copy(op);
opdst.opnd[(sizeof(gf571_opnd_bytes)-1)^lmask] ^= 1;
return opdst;
}
bool gf571_opnd::operator==(const gf571_opnd &op) const
{
if(opnd == op.opnd)
return true;
ulong *p1 = (ulong*)opnd;
ulong *p2 = (ulong*)op.opnd;
for(int ix = sizeof(gf571_opnd_bytes)/sizeof(ulong); --ix >= 0; ++p1, ++p2)
if(*p1 != *p2)
return false;
return true;
}
gf571_opnd& gf571_shiftl(const gf571_opnd &op, int nsh, gf571_opnd &opdst)
{
int nw = nsh / (8*sizeof(ulong));
if(nw > 0)
{
int nb = nw*sizeof(ulong);
nsh -= 8 * nb;
int nrem = sizeof(gf571_opnd_bytes) - nb;
memmove(opdst.opnd, op.opnd + nb, nrem);
memset(opdst.opnd+nrem, 0, nb);
}
else
opdst.gf571_copy(op);
int nb = nsh / 8;
if(nb > 0)
{
nsh -= 8 * nb;
int ix, jx;
for(ix = 0, jx = nb; jx < sizeof(gf571_opnd_bytes); ++ix, ++jx)
opdst.opnd[ix ^ lmask] = opdst.opnd[jx ^ lmask];
for(; ix < sizeof(gf571_opnd_bytes); ++ix)
opdst.opnd[ix ^ lmask] = 0;
}
if(nsh > 0)
{
int ix;
int rsh = 8*sizeof(ulong) - nsh;
ulong *p = (ulong*)opdst.opnd;
for(ix = 0; ix < sizeof(gf571_opnd_bytes)/sizeof(ulong)-1; ++ix)
p[ix] = ((p[ix] << nsh) |
(p[ix+1] >> rsh));
p[ix] <<= nsh;
}
return opdst;
}
void gf571_opnd::show()
{
for(int ix = 0; ix < sizeof(gf571_opnd_bytes); ++ix)
printf("%02X", opnd[ix ^ lmask]);
}
// ------------------------------------------------------------------
static_ecc571_affine_pt::static_ecc571_affine_pt()
{
x.opnd = xbytes;
y.opnd = ybytes;
}
static_ecc571_affine_pt::static_ecc571_affine_pt(const ecc571_affine_pt &pt)
{
x.opnd = xbytes;
y.opnd = ybytes;
ecc571_copy(pt);
}
static_ecc571_affine_pt::static_ecc571_affine_pt(const char* str[2])
{
x.opnd = xbytes;
y.opnd = ybytes;
x.init_from_string(str[0]);
y.init_from_string(str[1]);
}
// ------------------------------------------------------------
ecc571_affine_pt::ecc571_affine_pt(ubyte* px, ubyte* py)
{
x.opnd = px;
y.opnd = py;
}
ecc571_affine_pt &ecc571_affine_pt::infinite()
{
x.zero();
y.zero();
return *this;
}
bool ecc571_affine_pt::infinite_p() const
{
return !x;
}
ecc571_affine_pt& ecc571_affine_pt::ecc571_copy(const ecc571_affine_pt &pt)
{
x.gf571_copy(pt.x);
y.gf571_copy(pt.y);
return *this;
}
ecc571_affine_pt& ecc571_neg(const ecc571_affine_pt &pt, ecc571_affine_pt &ptdst)
{
ptdst.x.gf571_copy(pt.x);
gf571_add(pt.x, pt.y, ptdst.y);
return ptdst;
}
ecc571_affine_pt& ecc571_sub(const ecc571_affine_pt &pt1, const ecc571_affine_pt &pt2, ecc571_affine_pt &ptdst)
{
static_ecc571_affine_pt tmp;
ecc571_neg(pt2, tmp);
return ecc571_add(pt1, tmp, ptdst);
}
ecc571_affine_pt& ecc571_double(const ecc571_affine_pt &pt, ecc571_affine_pt &ptdst)
{
if(pt.infinite_p())
{
ptdst.infinite();
return ptdst;
}
static_gf571_opnd s;
static_gf571_opnd tmp1, tmp2;
static_ecc571_affine_pt ans;
gf571_div(pt.y, pt.x, s);
gf571_add(pt.x, s, s);
gf571_mul(s, s, tmp1);
gf571_oneplus(s, tmp2);
gf571_add(tmp1, tmp2, ans.x);
gf571_mul(tmp2, ans.x, tmp1);
gf571_mul(pt.x, pt.x, tmp2);
gf571_add(tmp1, tmp2, ans.y);
ptdst.ecc571_copy(ans);
return ptdst;
}
ecc571_affine_pt &ecc571_add(const ecc571_affine_pt &pt1, const ecc571_affine_pt &pt2, ecc571_affine_pt &ptdst)
{
if(pt1.infinite_p())
{
ptdst.ecc571_copy(pt2);
return ptdst;
}
if(pt2.infinite_p())
{
ptdst.ecc571_copy(pt1);
return ptdst;
}
if(pt1.x == pt2.x)
{
if(pt1.y == pt2.y)
return ecc571_double(pt1, ptdst);
static_gf571_opnd tmp1;
gf571_add(pt1.x, pt1.y, tmp1);
if(pt2.y == tmp1)
return ptdst.infinite();
gf571_add(pt2.x, pt2.y, tmp1);
if(pt1.y == tmp1)
return ptdst.infinite();
}
static_gf571_opnd s, tmp1, tmp2;
static_ecc571_affine_pt ans;
gf571_add(pt1.y, pt2.y, tmp1);
gf571_add(pt1.x, pt2.x, tmp2);
gf571_div(tmp1, tmp2, s);
gf571_add(tmp2, s, tmp1);
gf571_mul(s, s, tmp2);
gf571_add(tmp2, tmp1, tmp1);
gf571_oneplus(tmp1, ans.x);
gf571_add(pt1.x, ans.x, tmp1);
gf571_mul(s, tmp1, tmp2);
gf571_add(tmp2, ans.x, tmp1);
gf571_add(tmp1, pt1.y, ans.y);
ptdst.ecc571_copy(ans);
return ptdst;
}
void ecc571_affine_pt::show()
{
printf("{affine\n x:");
x.show();
printf("\n y:");
y.show();
printf(" }\n");
}
// -------------------------------------------------------
static_ecc571_projective_pt::static_ecc571_projective_pt()
{
x.opnd = xbytes;
y.opnd = ybytes;
z.opnd = zbytes;
}
static_ecc571_projective_pt::static_ecc571_projective_pt(const ecc571_projective_pt &pt)
{
x.opnd = xbytes;
y.opnd = ybytes;
z.opnd = zbytes;
ecc571_copy(pt);
}
static_ecc571_projective_pt::static_ecc571_projective_pt(const ecc571_affine_pt &pt)
{
x.opnd = xbytes;
y.opnd = ybytes;
z.opnd = zbytes;
x.gf571_copy(pt.x);
y.gf571_copy(pt.y);
z.one();
}
// -------------------------------------------------------
ecc571_affine_pt& ecc571_projective_pt::convert_to_affine(ecc571_affine_pt &ptdst)
{
if(infinite_p())
ptdst.infinite();
else
{
static_gf571_opnd tmp1;
gf571_inv(z, tmp1);
gf571_mul(x, tmp1, ptdst.x);
gf571_mul(tmp1, tmp1, tmp1);
gf571_mul(y, tmp1, ptdst.y);
}
return ptdst;
}
ecc571_projective_pt &ecc571_projective_pt::ecc571_copy(const ecc571_projective_pt &pt)
{
x.gf571_copy(pt.x);
y.gf571_copy(pt.y);
z.gf571_copy(pt.z);
return *this;
}
ecc571_projective_pt &ecc571_projective_pt::infinite()
{
x.one();
y.zero();
z.zero();
return *this;
}
bool ecc571_projective_pt::infinite_p() const
{
return !z;
}
static_gf571_opnd gEcc571_b("2f40e7e2221f295de297117b7f3d62f5c6a97ffcb8ceff1cd6ba8ce4a9a18ad84ffabbd8efa59332be7ad6756a66e294afd185a78ff12aa520e4de739baca0c7ffeff7f2955727a");
ecc571_projective_pt& ecc571_double(const ecc571_projective_pt &pt, ecc571_projective_pt &ptdst)
{
if(pt.infinite_p())
{
ptdst = pt;
return ptdst;
}
static_gf571_opnd x1sq;
static_gf571_opnd z1sq;
static_gf571_opnd bz1sqsq;
static_gf571_opnd tmp1, tmp2;
static_ecc571_projective_pt ans;
gf571_mul(pt.x, pt.x, x1sq);
gf571_mul(pt.z, pt.z, z1sq);
gf571_mul(z1sq, z1sq, bz1sqsq);
gf571_mul(bz1sqsq, gEcc571_b, bz1sqsq);
gf571_mul(x1sq, z1sq, ans.z);
gf571_mul(x1sq, x1sq, tmp1);
gf571_add(tmp1, bz1sqsq, ans.x);
gf571_mul(pt.y, pt.y, tmp1);
gf571_add(tmp1, bz1sqsq, tmp1);
gf571_add(tmp1, ans.z, tmp1);
gf571_mul(ans.x, tmp1, tmp1);
gf571_mul(bz1sqsq, ans.z, tmp2);
gf571_add(tmp1, tmp2, ans.y);
ptdst.ecc571_copy(ans);
return ptdst;
}
ecc571_projective_pt& ecc571_add(const ecc571_projective_pt &pt1, const ecc571_projective_pt &pt2, ecc571_projective_pt &ptdst)
{
if(pt1.infinite_p())
{
ptdst.ecc571_copy(pt2);
return ptdst;
}
static_gf571_opnd t1;
static_gf571_opnd t2;
static_gf571_opnd t3;
static_ecc571_projective_pt ans;
gf571_mul(pt1.z, pt2.x, t1);
gf571_mul(pt1.z, pt1.z, t2);
gf571_add(pt1.x, t1, ans.x);
gf571_mul(pt1.z, ans.x, t1);
gf571_mul(t2, pt2.y, t3);
gf571_add(pt1.y, t3, ans.y);
if(!ans.x)
{
if(!ans.y)
return ecc571_double(pt2, ptdst);
else
{
ptdst.infinite();
return ptdst;
}
}
else
{
gf571_mul(t1, t1, ans.z);
gf571_mul(t1, ans.y, t3);
gf571_add(t1, t2, t1);
gf571_mul(ans.x, ans.x, t2);
gf571_mul(t2, t1, ans.x);
gf571_mul(ans.y, ans.y, t2);
gf571_add(ans.x, t2, ans.x);
gf571_add(ans.x, t3, ans.x);
gf571_mul(pt2.x, ans.z, t2);
gf571_add(t2, ans.x, t2);
gf571_mul(ans.z, ans.z, t1);
gf571_add(t3, ans.z, t3);
gf571_mul(t3, t2, ans.y);
gf571_add(pt2.x, pt2.y, t2);
gf571_mul(t1, t2, t3);
gf571_add(ans.y, t3, ans.y);
ptdst.ecc571_copy(ans);
return ptdst;
}
}
ecc571_projective_pt& ecc571_mul(const ecc571_projective_pt &pt, const gf571_opnd &n, ecc571_projective_pt &ptdst)
{
if(!n)
{
ptdst.infinite();
return ptdst;
}
if(pt.infinite_p())
{
ptdst.infinite();
return ptdst;
}
static_ecc571_projective_pt ans(pt);
int ix;
ubyte mask;
n.first_bit(ix, mask);
mask >>= 1;
if(0 == mask)
{
mask = 0x080;
++ix;
}
for(; ix < sizeof(gf571_opnd_bytes); ++ix, mask = 0x080)
{
for(; mask; mask >>= 1)
{
ecc571_double(ans, ans);
if(mask & n.opnd[ix ^ lmask])
ecc571_add(ans, pt, ans);
}
}
ptdst.ecc571_copy(ans);
return ptdst;
}
ecc571_affine_pt& ecc571_mul(const ecc571_affine_pt &pt, const gf571_opnd &n, ecc571_affine_pt &ptdst)
{
static_ecc571_projective_pt p(pt);
static_ecc571_projective_pt ans;
ecc571_mul(p, n, ans);
ans.convert_to_affine(ptdst);
return ptdst;
}
static const char* genStr[2] = {
"303001d34b856296c16c0d40d3cd7750a93d1d2955fa80aa5f40fc8db7b2abdbde53950f4c0d293cdd711a35b67fb1499ae60038614f1394abfa3b4c850d927e1e7769c8eec2d19",
"37bf27342da639b6dccfffeb73d69d78c6c27a6009cbbca1980f8533921e8a684423e43bab08a576291af8f461bb2a8b3531d2f0485c19b16e2f1516e23dd3c1a4827af1b8ac15b"
};
const static_ecc571_affine_pt gGen(genStr);
ecc571_affine_pt& ecc571_mulGen(const gf571_opnd &n, ecc571_affine_pt &ptdst)
{
return ecc571_mul(gGen, n, ptdst);
}
extern "C" {
void gf128_add(ubyte *op1, ubyte *op2, ubyte *opdst)
{
gf128_opnd p1(op1);
gf128_opnd p2(op2);
gf128_opnd pdst(opdst);
gf128_add(p1, p2, pdst);
}
void gf128_mul(ubyte *op1, ubyte *op2, ubyte *opdst)
{
gf128_opnd p1(op1);
gf128_opnd p2(op2);
gf128_opnd pdst(opdst);
gf128_mul(p1, p2, pdst);
}
void gf128_inv(ubyte *op, ubyte *opdst)
{
gf128_opnd p(op);
gf128_opnd pdst(opdst);
gf128_inv(p, pdst);
}
void gf128_div(ubyte *op1, ubyte *op2, ubyte *opdst)
{
gf128_opnd p1(op1);
gf128_opnd p2(op2);
gf128_opnd pdst(opdst);
gf128_div(p1, p2, pdst);
}
// -------------------------------------------------------
void gf571_add(ubyte *op1, ubyte *op2, ubyte *opdst)
{
gf571_opnd p1(op1);
gf571_opnd p2(op2);
gf571_opnd pdst(opdst);
gf571_add(p1, p2, pdst);
}
void gf571_mul(ubyte *op1, ubyte *op2, ubyte *opdst)
{
gf571_opnd p1(op1);
gf571_opnd p2(op2);
gf571_opnd pdst(opdst);
gf571_mul(p1, p2, pdst);
}
void gf571_inv(ubyte *op, ubyte *opdst)
{
gf571_opnd p(op);
gf571_opnd pdst(opdst);
gf571_inv(p, pdst);
}
void gf571_div(ubyte *op1, ubyte *op2, ubyte *opdst)
{
gf571_opnd p1(op1);
gf571_opnd p2(op2);
gf571_opnd pdst(opdst);
gf571_div(p1, p2, pdst);
}
// -------------------------------------------------------
#if 0
void gf571_shiftl(ubyte *op, int nsh, ubyte *opdst)
{
gf571_opnd p(op);
gf571_opnd pdst(opdst);
gf571_shiftl(p, nsh, pdst);
}
void gf571_prim(ubyte *opdst)
{
gf571_opnd pdst(opdst);
pdst.prim();
}
int gf571_is_one(ubyte *opnd)
{
gf571_opnd p(opnd);
return p.is_one();
}
int gf571_sizeof_opnd()
{
return sizeof(ulong);
}
#endif
// -------------------------------------------------------
void c_ecc571_add(ubyte *op1x, ubyte *op1y,
ubyte *op2x, ubyte *op2y,
ubyte *ansx, ubyte *ansy)
{
ecc571_affine_pt p1(op1x, op1y);
ecc571_affine_pt p2(op2x, op2y);
ecc571_affine_pt ans(ansx, ansy);
ecc571_add(p1,p2,ans);
}
void c_ecc571_sub(ubyte *op1x, ubyte *op1y,
ubyte *op2x, ubyte *op2y,
ubyte *ansx, ubyte *ansy)
{
ecc571_affine_pt p1(op1x, op1y);
ecc571_affine_pt p2(op2x, op2y);
ecc571_affine_pt ans(ansx, ansy);
ecc571_sub(p1,p2,ans);
}
void c_ecc571_mul(ubyte *op1x, ubyte *op1y,
ubyte *op2,
ubyte *ansx, ubyte *ansy)
{
ecc571_affine_pt p1(op1x, op1y);
ecc571_affine_pt ans(ansx, ansy);
gf571_opnd p2(op2);
ecc571_mul(p1,p2,ans);
}
};
| 21.643824 | 176 | 0.562092 | dbmcclain |
51fe2949a1429598277911cc559036e011c75ab8 | 699 | cpp | C++ | tests/com.oracle.truffle.llvm.tests.sulongcpp/cpp/test011.cpp | pointhi/sulong | 5446c54d360f486f9e97590af5f466cf1f5cd1f7 | [
"BSD-3-Clause"
] | 1 | 2021-01-20T08:07:04.000Z | 2021-01-20T08:07:04.000Z | tests/com.oracle.truffle.llvm.tests.sulongcpp/cpp/test011.cpp | pointhi/sulong | 5446c54d360f486f9e97590af5f466cf1f5cd1f7 | [
"BSD-3-Clause"
] | null | null | null | tests/com.oracle.truffle.llvm.tests.sulongcpp/cpp/test011.cpp | pointhi/sulong | 5446c54d360f486f9e97590af5f466cf1f5cd1f7 | [
"BSD-3-Clause"
] | 1 | 2018-11-06T21:38:57.000Z | 2018-11-06T21:38:57.000Z |
#include <stdio.h>
class Base {
public:
virtual int foo() {
return 13;
}
};
class A : public Base {
public:
int foo() {
return 11;
}
int tar() {
return 77;
}
};
class B : public Base {
public:
int foo() {
return 15;
}
int bar() {
return 99;
}
};
int foo(int a) {
if (a == 0) {
throw B();
}
return a;
}
int main(int argc, char *argv[]) {
try {
foo(0);
return 0;
} catch (const char *msg) {
return 1;
} catch (long value) {
return 2;
} catch (int *value) {
return 3;
} catch (A value) {
printf("Catch A\n");
return value.foo();
} catch (Base value) {
printf("Catch B\n");
return value.foo();
}
} | 12.709091 | 34 | 0.509299 | pointhi |
a4036081cd6c02d2ad4c99f6385f457cef1a1cac | 3,274 | hpp | C++ | samples/deeplearning/gxm/include/ConvImpl.hpp | abhisek-kundu/libxsmm | 6c8ca987e77e32253ad347a1357ce2687c448ada | [
"BSD-3-Clause"
] | 651 | 2015-03-14T23:18:44.000Z | 2022-01-19T14:08:28.000Z | samples/deeplearning/gxm/include/ConvImpl.hpp | abhisek-kundu/libxsmm | 6c8ca987e77e32253ad347a1357ce2687c448ada | [
"BSD-3-Clause"
] | 362 | 2015-01-26T16:20:28.000Z | 2022-01-26T06:19:23.000Z | samples/deeplearning/gxm/include/ConvImpl.hpp | abhisek-kundu/libxsmm | 6c8ca987e77e32253ad347a1357ce2687c448ada | [
"BSD-3-Clause"
] | 169 | 2015-09-28T17:06:28.000Z | 2021-12-18T16:02:49.000Z | /******************************************************************************
* Copyright (c) Intel Corporation - All rights reserved. *
* This file is part of the LIBXSMM library. *
* *
* For information on the license, see the LICENSE file. *
* Further information: https://github.com/hfp/libxsmm/ *
* SPDX-License-Identifier: BSD-3-Clause *
******************************************************************************/
/* Sasikanth Avancha, Dhiraj Kalamkar (Intel Corp.)
******************************************************************************/
#pragma once
#include <omp.h>
#include <assert.h>
#include <sys/time.h>
#include <string.h>
#include "common.hpp"
#include "check.hpp"
#include "Tensor.hpp"
typedef struct {
string node_name;
int nInput, nOutput;
int batch_size;
int iHeight, iWidth, iDepth;
int oHeight, oWidth, oDepth;
int ipad_h, ipad_w, ipad_d;
int opad_h, opad_w, opad_d;
int pad_h, pad_w, pad_d;
int stride_h, stride_w, stride_d;
int kh, kw, kd;
int group;
bool bias_term, compute_stats;
bool relu, bwd_relu, physical_padding;
int algType;
int bdims, tdims, wdims, bidims;
int in_data_type, out_data_type;
int num_threads;
int num_numa_nodes;
} ConvImplParams;
class ConvImpl
{
protected:
ConvImplParams *gp;
int engine;
TensorLayoutType top_layout_type, gbot_layout_type;
void *top_layout, *gbot_layout;
int top_compute_engine=-1;
int bot_compute_engine=-1;
string nname;
TensorBuf* scratchp;
public:
ConvImpl(ConvImplParams* gp_, int engine_): gp(gp_), engine(engine_) {}
void set_top_compute_engine(int e) { top_compute_engine = e;}
void set_bot_compute_engine(int e) { bot_compute_engine = e;}
void set_node_name(string s) { nname = s; }
void set_scratch_buffer(TensorBuf* sb) { scratchp = sb; }
virtual void forwardPropagate(TensorBuf *inp, TensorBuf *weightp, TensorBuf* hweightp, TensorBuf *biasp, TensorBuf *outp, int tid) = 0;
virtual void backPropagate(TensorBuf* inp, TensorBuf *deloutp, TensorBuf* weightp, TensorBuf *delinp, int tid) = 0;
virtual void weightUpdate(TensorBuf *inp, TensorBuf *deloutp, TensorBuf *delweightp, TensorBuf *delbiasp, int tid) = 0;
virtual void dumpBuffer(TensorBuf*, void*) {}
virtual void forwardPropagate(TensorBuf *inp, TensorBuf* weightp, TensorBuf* hweightp, TensorBuf* biasp, TensorBuf *outp)
{
switch(engine)
{
case XSMM:
forwardPropagate(inp, weightp, hweightp, biasp, outp, 0);
break;
}
}
virtual void backPropagate(TensorBuf* inp, TensorBuf* weightp, TensorBuf *deloutp, TensorBuf *delinp)
{
switch(engine)
{
case XSMM:
backPropagate(inp, weightp, deloutp, delinp, 0);
break;
}
}
virtual void weightUpdate(TensorBuf *inp, TensorBuf *deloutp, TensorBuf *delweightp, TensorBuf *delbiasp)
{
switch(engine)
{
case XSMM:
weightUpdate(inp, deloutp, delweightp, delbiasp, 0);
break;
}
}
};
| 32.098039 | 139 | 0.587355 | abhisek-kundu |
a40435e1b02ee5d61695a217d6ee57829275ce70 | 7,020 | cpp | C++ | CommonLib/cxBaseCommThread_thread.cpp | chrishoen/Dev_NP_TTA_NewCProc | 95a0d59e6079e6f42a11cfe5da5ec41221f67227 | [
"MIT"
] | null | null | null | CommonLib/cxBaseCommThread_thread.cpp | chrishoen/Dev_NP_TTA_NewCProc | 95a0d59e6079e6f42a11cfe5da5ec41221f67227 | [
"MIT"
] | null | null | null | CommonLib/cxBaseCommThread_thread.cpp | chrishoen/Dev_NP_TTA_NewCProc | 95a0d59e6079e6f42a11cfe5da5ec41221f67227 | [
"MIT"
] | null | null | null | /*==============================================================================
Detestion:
==============================================================================*/
//******************************************************************************
//******************************************************************************
//******************************************************************************
#include "stdafx.h"
#include "cmnPriorities.h"
#include "cxCProcParms.h"
#include "sxMsgDefs.h"
#include "cxBaseCommThread.h"
namespace CX
{
//******************************************************************************
//******************************************************************************
//******************************************************************************
// Constructor. True is tta, false is da.
BaseCommThread::BaseCommThread(int aTTAFlag)
: mRxMsgNotify(&mNotify, cRxMsgNotifyCode)
{
using namespace std::placeholders;
// Set flag.
mTTAFlag = aTTAFlag;
if (mTTAFlag) strcpy(mLabel, "TTA");
else strcpy(mLabel, "DA");
// Set base class thread variables.
if (mTTAFlag)
{
BaseClass::mShortThread->setThreadName("TTACommShort");
BaseClass::mLongThread->setThreadName("TTACommLong");
}
else
{
BaseClass::mShortThread->setThreadName("DACommShort");
BaseClass::mLongThread->setThreadName("DACommLong");
}
BaseClass::mShortThread->setThreadPriority(Cmn::gPriorities.mCommShort);
BaseClass::mShortThread->setThreadPrintLevel(0);
BaseClass::mLongThread->setThreadPriority(Cmn::gPriorities.mCommLong);
BaseClass::mLongThread->setThreadPrintLevel(0);
// Set base class call pointers.
BaseClass::mShortThread->mThreadInitCallPointer = std::bind(&BaseCommThread::threadInitFunction, this);
BaseClass::mShortThread->mThreadExitCallPointer = std::bind(&BaseCommThread::threadExitFunction, this);
BaseClass::mShortThread->mThreadExecuteOnTimerCallPointer = std::bind(&BaseCommThread::executeOnTimer, this, _1);
// Set qcalls.
mRunSeq1QCall.bind(this->mLongThread, this, &BaseCommThread::executeRunSeq1);
mSessionQCall.bind(this->mShortThread, this, &BaseCommThread::executeSession);
mRxStringQCall.bind(this->mShortThread, this, &BaseCommThread::executeRxString);
mAbortQCall.bind(this->mShortThread, this, &BaseCommThread::executeAbort);
// Set member variables.
resetVars();
}
void BaseCommThread::resetVars()
{
mSeqExitCode = 0;
mTxCount = 0;
mRxCount = 0;
mSeqState = SX::cMsgId_tst;
mFirstFlag_gsx = true;
mSeqTime1 = 0;
mSeqTime2 = 0;
mSeqDuration = 0;
}
//******************************************************************************
//******************************************************************************
//******************************************************************************
// Set the sequence waitable timer slow or fast.
void BaseCommThread::setSeqWaitableSlow()
{
if (mSeqWaitableSlow) return;
mSeqWaitable.initialize(cSlowSeqPeriod);
mSeqWaitableSlow = true;
}
void BaseCommThread::setSeqWaitableFast()
{
if (!mSeqWaitableSlow) return;
mSeqWaitable.initialize(cFastSeqPeriod);
mSeqWaitableSlow = false;
}
//******************************************************************************
//******************************************************************************
//******************************************************************************
// Thread init function. This is called by the base class immediately
// before the thread starts running.
void BaseCommThread::threadInitFunction()
{
using namespace std::placeholders;
// Instance of serial port settings.
Ris::SerialSettings tSerialSettings;
if (mTTAFlag)
{
tSerialSettings.setPortDevice("/dev/ttyO2");
}
else
{
tSerialSettings.setPortDevice("/dev/ttyO4");
}
tSerialSettings.setPortSetup("38400,N,8,1");
tSerialSettings.mRxTimeout = 0;
tSerialSettings.mTermMode = Ris::cSerialTermMode_CRLF;
tSerialSettings.mThreadPriority = Cmn::gPriorities.mSerialString;
tSerialSettings.mPrintLevel = 0;
tSerialSettings.mSessionQCall = mSessionQCall;
tSerialSettings.mRxStringQCall = mRxStringQCall;
tSerialSettings.m485Flag = true;
// Create the child thread.
mSerialStringThread = new Ris::SerialStringThread(tSerialSettings);
// Launch the child thread.
mSerialStringThread->launchThread();
// Launch the sequence qcall.
mRunSeq1QCall();
}
//******************************************************************************
//******************************************************************************
//******************************************************************************
// Thread exit function. This is called by the base class immediately
// after the thread starts running.
void BaseCommThread::threadExitFunction()
{
// Shutdown the child thread
mSerialStringThread->shutdownThread();
}
//******************************************************************************
//******************************************************************************
//******************************************************************************
// Thread shutdown function. This shuts down the two threads.
void BaseCommThread::shutdownThreads()
{
// Abort the long thread.
BaseClass::mNotify.abort();
mSeqWaitable.postSemaphore();
// Shutdown the two threads.
BaseClass::shutdownThreads();
}
//******************************************************************************
//******************************************************************************
//******************************************************************************
// The qcall function. Post to the waitable to abort the long thread
// qcall. Execute in the context of the short thread.
void BaseCommThread::executeAbort()
{
Prn::print(0, "ABORT>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
// Abort the long thread.
mSeqWaitable.postSemaphore();
}
//******************************************************************************a
//******************************************************************************
//******************************************************************************
// Serial session qcall function. This is invoked by the serial child
// thread when the serial port is opened or closed because of an error
// or when it is reopened correctly.
void BaseCommThread::executeSession(bool aConnected)
{
if (aConnected)
{
Prn::print(0, "%s serial port open CONNECTED", mLabel);
}
else
{
Prn::print(0, "%s serial port open DISCONNECTED", mLabel);
}
mConnectionFlag = aConnected;
}
//******************************************************************************
//******************************************************************************
//******************************************************************************
}//namespace | 34.411765 | 116 | 0.475499 | chrishoen |
a40731ba094803facf6e37ac33ef5c04f5776fcc | 19,877 | cpp | C++ | src/base/function/ObjectManagedFunction.cpp | IncompleteWorlds/GMAT_2020 | 624de54d00f43831a4d46b46703e069d5c8c92ff | [
"Apache-2.0"
] | null | null | null | src/base/function/ObjectManagedFunction.cpp | IncompleteWorlds/GMAT_2020 | 624de54d00f43831a4d46b46703e069d5c8c92ff | [
"Apache-2.0"
] | null | null | null | src/base/function/ObjectManagedFunction.cpp | IncompleteWorlds/GMAT_2020 | 624de54d00f43831a4d46b46703e069d5c8c92ff | [
"Apache-2.0"
] | null | null | null | //$Id$
//------------------------------------------------------------------------------
// ObjectManagedFunction
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool
//
// Copyright (c) 2002 - 2020 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All Other 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.
//
// Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract
// number NNG04CC06P.
//
// Author: Linda Jun
// Created: 2016.10.20
//
/**
* Implements the ObjectManagedFunction base class for BuiltinGmatFunction and
* UserDefinedFunction
*/
//------------------------------------------------------------------------------
#include "ObjectManagedFunction.hpp"
#include "FunctionException.hpp" // for exception
#include "StringUtil.hpp" // for GmatStringUtil::
#include "Parameter.hpp" // for GetOwner()
#include "MessageInterface.hpp"
//#define DEBUG_FUNCTION_SET
//#define DEBUG_FUNCTION_IN_OUT
//#define DEBUG_WRAPPER_CODE
//#define DEBUG_FUNCTION_OBJ
//#define DEBUG_OBJECT_MAP
//#ifndef DEBUG_MEMORY
//#define DEBUG_MEMORY
//#endif
#ifdef DEBUG_MEMORY
#include "MemoryTracker.hpp"
#endif
//---------------------------------
// static data
//---------------------------------
//------------------------------------------------------------------------------
// ObjectManagedFunction(std::string typeStr, std::string name)
//------------------------------------------------------------------------------
/**
* Constructs the ObjectManagedFunction object (default constructor).
*
* @param <typeStr> String text identifying the object type
* @param <name> Name for the object
*/
//------------------------------------------------------------------------------
ObjectManagedFunction::ObjectManagedFunction(const std::string &typeStr, const std::string &name) :
Function (typeStr, name),
objectStore (NULL),
globalObjectStore (NULL)
{
if (typeStr != "")
objectTypeNames.push_back(typeStr);
objectTypeNames.push_back("ObjectManagedFunction");
}
//------------------------------------------------------------------------------
// ~ObjectManagedFunction(void)
//------------------------------------------------------------------------------
/**
* Destroys the ObjectManagedFunction object (destructor).
*/
//------------------------------------------------------------------------------
ObjectManagedFunction::~ObjectManagedFunction()
{
}
//------------------------------------------------------------------------------
// ObjectManagedFunction(const ObjectManagedFunction &f)
//------------------------------------------------------------------------------
/**
* Constructs the ObjectManagedFunction object (copy constructor).
*
* @param <f> Object that is copied
*/
//------------------------------------------------------------------------------
ObjectManagedFunction::ObjectManagedFunction(const ObjectManagedFunction &f) :
Function (f),
inputArgMap (f.inputArgMap), // do I want to do this?
outputArgMap (f.outputArgMap), // do I want to do this?
objectStore (NULL),
globalObjectStore (NULL)
{
}
//------------------------------------------------------------------------------
// ObjectManagedFunction& operator=(const ObjectManagedFunction &f)
//------------------------------------------------------------------------------
/**
* Sets one ObjectManagedFunction object to match another (assignment operator).
*
* @param <f> The object that is copied.
*
* @return this object, with the parameters set as needed.
*/
//------------------------------------------------------------------------------
ObjectManagedFunction& ObjectManagedFunction::operator=(const ObjectManagedFunction &f)
{
if (this == &f)
return *this;
Function::operator=(f);
objectStore = NULL;
globalObjectStore = NULL;
inputArgMap = f.inputArgMap; // do I want to do this?
outputArgMap = f.outputArgMap; // do I want to do this?
return *this;
}
//------------------------------------------------------------------------------
// bool Initialize(ObjectInitializer *objInit, bool reinitialize = false)
//------------------------------------------------------------------------------
bool ObjectManagedFunction::Initialize(ObjectInitializer *objInit, bool reinitialize)
{
return true;
}
//------------------------------------------------------------------------------
// bool ObjectManagedFunction::Execute(ObjectInitializer *objInit) [default implementation]
//------------------------------------------------------------------------------
bool ObjectManagedFunction::Execute(ObjectInitializer *objInit, bool reinitialize)
{
return true;
}
//------------------------------------------------------------------------------
// bool ObjectManagedFunction::Finalize(bool cleanUp = false) [default implementation]
//------------------------------------------------------------------------------
void ObjectManagedFunction::Finalize(bool cleanUp)
{
// Anything to do here?
}
//------------------------------------------------------------------------------
// void SetFunctionObjectMap(ObjectMap *objMap)
//------------------------------------------------------------------------------
void ObjectManagedFunction::SetFunctionObjectMap(ObjectMap *objMap)
{
#ifdef DEBUG_OBJECT_MAP
ShowObjectMap(objMap, "In ObjectManagedFunction::SetFunctionObjectMap",
"Input Object Map");
#endif
objectStore = objMap;
}
//------------------------------------------------------------------------------
// void SetGlobalObjectMap(ObjectMap *objMap)
//------------------------------------------------------------------------------
void ObjectManagedFunction::SetGlobalObjectMap(ObjectMap *objMap)
{
globalObjectStore = objMap;
}
//------------------------------------------------------------------------------
// bool SetInputElementWrapper(const std::string &forName, ElementWrapper *wrapper)
//------------------------------------------------------------------------------
bool ObjectManagedFunction::SetInputElementWrapper(const std::string &forName, ElementWrapper *wrapper)
{
#ifdef DEBUG_FUNCTION_IN_OUT
MessageInterface::ShowMessage
("ObjectManagedFunction::SetInputElementWrapper() entered, wrapper name \"%s\"\n", forName.c_str());
MessageInterface::ShowMessage
(" wrapper=<%p>, wrapper type = %d, inputArgMap.size()=%d\n", wrapper,
wrapper->GetWrapperType(), inputArgMap.size());
#endif
if (inputArgMap.find(forName) == inputArgMap.end())
{
#ifdef DEBUG_FUNCTION_IN_OUT
MessageInterface::ShowMessage
("**** ERROR **** ObjectManagedFunction::SetInputElementWrapper() throwing exception: "
"Input name '%s' not found in inputArgMap\n", forName.c_str());
#endif
std::string errMsg = "Unknown input argument \"" + forName;
errMsg += "\" for function \"" + functionName + "\"";
throw FunctionException(errMsg);
}
inputArgMap[forName] = wrapper;
//@note old inputWrappers are deleted in the FunctionManager::CreateFunctionArgWrappers()
// before creates new wrappers for input arguments
#ifdef DEBUG_FUNCTION_IN_OUT
MessageInterface::ShowMessage
("ObjectManagedFunction::SetInputElementWrapper() leaving, wrapper name \"%s\"\n", forName.c_str());
#endif
return true;
}
//------------------------------------------------------------------------------
// virtual ElementWrapper* GetOutputArgument(Integer argNumber)
//------------------------------------------------------------------------------
/*
* Implements GMAT FUNCTIONS design 27.2.2.3 GmatFunction Execution
* step 4 of "Steps Performed on the Firstexecution"
*/
//------------------------------------------------------------------------------
ElementWrapper* ObjectManagedFunction::GetOutputArgument(Integer argNumber)
{
if ((argNumber < 0) || (argNumber > (Integer) outputNames.size()) ||
(argNumber> (Integer) outputArgMap.size()))
{
std::string errMsg = "Function error: argument number out-of-range\n";
throw FunctionException(errMsg);
}
std::string argName = outputNames.at(argNumber);
return GetOutputArgument(argName);
}
//------------------------------------------------------------------------------
// ElementWrapper* GetOutputArgument(const std::string &byName)
//------------------------------------------------------------------------------
ElementWrapper* ObjectManagedFunction::GetOutputArgument(const std::string &byName)
{
#ifdef DEBUG_FUNCTION_IN_OUT
MessageInterface::ShowMessage
("ObjectManagedFunction::GetOutputArgument(%s) entered, outputArgMap.size()=%d\n",
byName.c_str(), outputArgMap.size());
#endif
if (outputArgMap.find(byName) == outputArgMap.end())
{
std::string errMsg = "Function error: output \"" + byName;
errMsg += "\" from function \"" + functionName;
errMsg += "\" does not exist.\n";
throw FunctionException(errMsg);
}
ElementWrapper *ew = outputArgMap[byName];
#ifdef DEBUG_FUNCTION_IN_OUT
MessageInterface::ShowMessage
("ObjectManagedFunction::GetOutputArgument(%s) returning <%p>, type=%d\n", byName.c_str(),
ew, ew ? ew->GetDataType() : -999);
#endif
return ew;
}
//------------------------------------------------------------------------------
// WrapperArray& GetWrappersToDelete()
//------------------------------------------------------------------------------
WrapperArray& ObjectManagedFunction::GetWrappersToDelete()
{
return wrappersToDelete;
}
//------------------------------------------------------------------------------
// void ClearInOutArgMaps(bool deleteInputs, bool deleteOutputs)
//------------------------------------------------------------------------------
void ObjectManagedFunction::ClearInOutArgMaps(bool deleteInputs, bool deleteOutputs)
{
#ifdef DEBUG_WRAPPER_CODE
MessageInterface::ShowMessage
("ObjectManagedFunction::ClearInOutArgMaps() this=<%p> '%s' entered\n", this,
GetName().c_str());
MessageInterface::ShowMessage
("inputArgMap.size()=%d, outputArgMap.size()=%d\n", inputArgMap.size(),
outputArgMap.size());
#endif
std::vector<ElementWrapper *> wrappersToDelete;
std::map<std::string, ElementWrapper *>::iterator ewi;
if (deleteInputs)
{
// input wrappers map
for (ewi = inputArgMap.begin(); ewi != inputArgMap.end(); ++ewi)
{
if (ewi->second)
{
if (find(wrappersToDelete.begin(), wrappersToDelete.end(), ewi->second) ==
wrappersToDelete.end())
wrappersToDelete.push_back(ewi->second);
}
}
}
if (deleteOutputs)
{
// output wrappers
for (ewi = outputArgMap.begin(); ewi != outputArgMap.end(); ++ewi)
{
if (ewi->second)
{
if (find(wrappersToDelete.begin(), wrappersToDelete.end(), ewi->second) ==
wrappersToDelete.end())
wrappersToDelete.push_back(ewi->second);
}
}
}
#ifdef DEBUG_WRAPPER_CODE
MessageInterface::ShowMessage
(" There are %d wrappers to delete\n", wrappersToDelete.size());
#endif
// Delete old ElementWrappers (loj: 2008.11.20)
for (std::vector<ElementWrapper*>::iterator ewi = wrappersToDelete.begin();
ewi < wrappersToDelete.end(); ewi++)
{
#ifdef DEBUG_MEMORY
MemoryTracker::Instance()->Remove
((*ewi), (*ewi)->GetDescription(), "ObjectManagedFunction::ClearInOutArgMaps()",
"deleting wrapper");
#endif
delete (*ewi);
(*ewi) = NULL;
}
inputArgMap.clear();
outputArgMap.clear();
}
//------------------------------------------------------------------------------
// virtual bool TakeAction(const std::string &action,
// const std::string &actionData = "")
//------------------------------------------------------------------------------
/**
* This method performs action.
*
* @param <action> action to perform
* @param <actionData> action data associated with action ("")
* @return true if action successfully performed
*
*/
//------------------------------------------------------------------------------
bool ObjectManagedFunction::TakeAction(const std::string &action,
const std::string &actionData)
{
#ifdef DEBUG_FUNCTION_ACTION
MessageInterface::ShowMessage
("ObjectManagedFunction::TakeAction() action=%s, actionData=%s\n", action.c_str(),
actionData.c_str());
#endif
return Function::TakeAction(action, actionData);
}
//------------------------------------------------------------------------------
// bool SetStringParameter(const Integer id, const char *value)
//------------------------------------------------------------------------------
/**
* @see SetStringParameter(const Integer id, const std::string &value)
*/
//------------------------------------------------------------------------------
bool ObjectManagedFunction::SetStringParameter(const Integer id, const char *value)
{
return SetStringParameter(id, std::string(value));
}
//------------------------------------------------------------------------------
// bool SetStringParameter(const Integer id, const std::string &value)
//------------------------------------------------------------------------------
/**
* Sets the value for a std::string parameter.
*
* @param <id> Integer ID of the parameter.
* @param <value> New value for the parameter.
*
* @return If value of the parameter was set.
*/
//------------------------------------------------------------------------------
bool ObjectManagedFunction::SetStringParameter(const Integer id, const std::string &value)
{
#ifdef DEBUG_FUNCTION_SET
MessageInterface::ShowMessage
("ObjectManagedFunction::SetStringParameter() entered, id=%d, value='%s'\n", id, value.c_str());
#endif
switch (id)
{
case FUNCTION_INPUT:
{
#ifdef DEBUG_FUNCTION_SET
MessageInterface::ShowMessage(" Adding function input name '%s'\n", value.c_str());
#endif
// Ignore () as input, so that "function MyFunction()" will work as no input (LOJ: 2015.08.19)
if (value == "()")
return true;
if (inputArgMap.find(value) == inputArgMap.end())
{
inputNames.push_back(value);
inputArgMap.insert(std::make_pair(value,(ElementWrapper*) NULL));
}
else
throw FunctionException
("In function file \"" + functionPath + "\": "
"The input argument \"" + value + "\" already exists");
return Function::SetStringParameter(id, value);
}
case FUNCTION_OUTPUT:
{
#ifdef DEBUG_FUNCTION_SET
MessageInterface::ShowMessage(" Adding function output name '%s'\n", value.c_str());
#endif
if (outputArgMap.find(value) == outputArgMap.end())
{
outputNames.push_back(value);
outputArgMap.insert(std::make_pair(value,(ElementWrapper*) NULL));
}
else
throw FunctionException
("In function file \"" + functionPath + "\": "
"The output argument \"" + value + "\" already exists");
return Function::SetStringParameter(id, value);
}
default:
return Function::SetStringParameter(id, value);
}
}
//------------------------------------------------------------------------------
// bool SetStringParameter(const std::string &label, const char *value)
//------------------------------------------------------------------------------
bool ObjectManagedFunction::SetStringParameter(const std::string &label,
const char *value)
{
return SetStringParameter(GetParameterID(label), std::string(value));
}
//------------------------------------------------------------------------------
// bool SetStringParameter(const std::string &label, const std::string &value)
//------------------------------------------------------------------------------
bool ObjectManagedFunction::SetStringParameter(const std::string &label,
const std::string &value)
{
return SetStringParameter(GetParameterID(label), value);
}
//---------------------------------
// protected
//---------------------------------
//------------------------------------------------------------------------------
// void ShowObjectMap(ObjectMap *objMap, const std::string &title,
// const std::string &mapName)
//------------------------------------------------------------------------------
void ObjectManagedFunction::ShowObjectMap(ObjectMap *objMap, const std::string &title,
const std::string &mapName)
{
MessageInterface::ShowMessage("%s\n", title.c_str());
MessageInterface::ShowMessage("this=<%p>, functionName='%s'\n", this, functionName.c_str());
if (objMap == NULL)
{
MessageInterface::ShowMessage("%s is NULL\n", mapName.c_str());
return;
}
std::string objMapName = mapName;
GmatBase *obj = NULL;
std::string objName;
std::string objTypeName = "NULL";
std::string isGlobal;
std::string isLocal;
GmatBase *paramOwner = NULL;
bool isParameter = false;
std::string paramOwnerType;
std::string paramOwnerName;
if (objMapName == "")
objMapName = "object map";
MessageInterface::ShowMessage("========================================\n");
MessageInterface::ShowMessage
("Here is %s <%p>, it has %d objects\n", objMapName.c_str(), objMap, objMap->size());
for (ObjectMap::iterator i = objMap->begin(); i != objMap->end(); ++i)
{
obj = i->second;
objName = i->first;
objTypeName = "";
isGlobal = "No";
isLocal = "No";
paramOwner = NULL;
isParameter = false;
paramOwnerType = "";
paramOwnerName = "";
if (obj)
{
objTypeName = obj->GetTypeName();
if (obj->IsGlobal())
isGlobal = "Yes";
if (obj->IsLocal())
isLocal = "Yes";
if (obj->IsOfType(Gmat::PARAMETER))
{
isParameter = true;
paramOwner = ((Parameter*)obj)->GetOwner();
if (paramOwner)
{
paramOwnerType = paramOwner->GetTypeName();
paramOwnerName = paramOwner->GetName();
}
}
}
MessageInterface::ShowMessage
(" %60s <%p> %-16s IsGlobal:%-3s IsLocal:%-3s", objName.c_str(), obj,
objTypeName.c_str(), isGlobal.c_str(), isLocal.c_str());
if (isParameter)
MessageInterface::ShowMessage
(" ParameterOwner: <%p>[%s]'%s'\n", paramOwner, paramOwnerType.c_str(),
paramOwnerName.c_str());
else
MessageInterface::ShowMessage("\n");
}
}
| 35.943942 | 106 | 0.509383 | IncompleteWorlds |
a407e9485fa2e6beb466fb6d2bfa3e3cdbe42ef5 | 15,699 | cpp | C++ | source/App/vvencapp/vvencapp.cpp | Jamaika1/vvenc | 77af89362d3cfad6098cbacb9407cf6958fdfb03 | [
"BSD-3-Clause"
] | null | null | null | source/App/vvencapp/vvencapp.cpp | Jamaika1/vvenc | 77af89362d3cfad6098cbacb9407cf6958fdfb03 | [
"BSD-3-Clause"
] | null | null | null | source/App/vvencapp/vvencapp.cpp | Jamaika1/vvenc | 77af89362d3cfad6098cbacb9407cf6958fdfb03 | [
"BSD-3-Clause"
] | null | null | null | /* -----------------------------------------------------------------------------
The copyright in this software is being made available under the BSD
License, included below. No patent rights, trademark rights and/or
other Intellectual Property Rights other than the copyrights concerning
the Software are granted under this license.
For any license concerning other Intellectual Property rights than the software,
especially patent licenses, a separate Agreement needs to be closed.
For more information please contact:
Fraunhofer Heinrich Hertz Institute
Einsteinufer 37
10587 Berlin, Germany
www.hhi.fraunhofer.de/vvc
vvc@hhi.fraunhofer.de
Copyright (c) 2019-2020, Fraunhofer-Gesellschaft zur Förderung der angewandten Forschung e.V.
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 Fraunhofer 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.
------------------------------------------------------------------------------------------- */
/**
\ingroup VVEncoderApp
\file VVEncoderApp.cpp
\brief This VVEncoderApp.cpp file contains the main entry point of the application.
\author lehmann
\date 2019-10-10
*/
#include <iostream>
#include <stdio.h>
#include <string>
#include <fstream>
#include <cstring>
#include <ctime>
#include <chrono>
#include <regex>
#include "vvenc/version.h"
#include "vvenc/vvenc.h"
#include "BinFileWriter.h"
#include "CmdLineParser.h"
#include "YuvFileReader.h"
int g_verbosity = vvenc::LL_VERBOSE;
void msgFnc( int level, const char* fmt, va_list args )
{
if ( g_verbosity >= level )
{
vfprintf( level == 1 ? stderr : stdout, fmt, args );
}
}
void printVVEncErrorMsg( const std::string cAppname, const std::string cMessage, int code, const std::string cErr )
{
std::cout << cAppname << " [error]: " << cMessage << ", ";
switch( code )
{
case vvenc::VVENC_ERR_CPU : std::cout << "SSE 4.1 cpu support required."; break;
case vvenc::VVENC_ERR_PARAMETER : std::cout << "invalid parameter."; break;
default : std::cout << "error " << code; break;
};
if( !cErr.empty() )
{
std::cout << " - " << cErr;
}
std::cout << std::endl;
}
int main( int argc, char* argv[] )
{
std::string cAppname = argv[0];
std::size_t iPos = (int)cAppname.find_last_of("/");
if( std::string::npos != iPos )
{
cAppname = cAppname.substr(iPos+1 );
}
std::string cInputFile;
std::string cOutputfile = "";
vvenc::VVEncParameter cVVEncParameter;
// set desired encoding options
cVVEncParameter.m_iQp = 32; // quantization parameter 0-51
cVVEncParameter.m_iWidth = 1920; // luminance width of input picture
cVVEncParameter.m_iHeight = 1080; // luminance height of input picture
cVVEncParameter.m_iGopSize = 32; // gop size (1: intra only, 16, 32: hierarchical b frames)
cVVEncParameter.m_eDecodingRefreshType = vvenc::VVC_DRT_CRA; // intra period refresh type
cVVEncParameter.m_iIDRPeriodSec = 1; // intra period in seconds for IDR/CDR intra refresh/RAP flag (should be > 0)
cVVEncParameter.m_iIDRPeriod = 0; // intra period in frames for IDR/CDR intra refresh/RAP flag (should be a factor of m_iGopSize)
cVVEncParameter.m_eLogLevel = vvenc::LL_VERBOSE; // log level > 4 (VERBOSE) enables psnr/rate output
cVVEncParameter.m_iTemporalRate = 60; // temporal rate (fps)
cVVEncParameter.m_iTemporalScale = 1; // temporal scale (fps)
cVVEncParameter.m_iTicksPerSecond = 90000; // ticks per second e.g. 90000 for dts generation
cVVEncParameter.m_iMaxFrames = 0; // max number of frames to be encoded
cVVEncParameter.m_iFrameSkip = 0; // number of frames to skip before start encoding
cVVEncParameter.m_iThreadCount = -1; // number of worker threads (should not exceed the number of physical cpu's)
cVVEncParameter.m_iQuality = 2; // encoding quality (vs speed) 0: faster, 1: fast, 2: medium, 3: slow, 4: slower
cVVEncParameter.m_iPerceptualQPA = 2; // percepual qpa adaptation, 0 off, 1 on for sdr(wpsnr), 2 on for sdr(xpsnr), 3 on for hdr(wpsrn), 4 on for hdr(xpsnr), on for hdr(MeanLuma)
cVVEncParameter.m_iInputBitDepth = 8; // input bitdepth
cVVEncParameter.m_iInternalBitDepth = 10; // internal bitdepth
cVVEncParameter.m_eProfile = vvenc::VVC_PROFILE_MAIN_10; // profile: use main_10 or main_10_still_picture
cVVEncParameter.m_eLevel = vvenc::VVC_LEVEL_4_1; // level
cVVEncParameter.m_eTier = vvenc::VVC_TIER_MAIN; // tier
cVVEncParameter.m_eSegMode = vvenc::VVC_SEG_OFF; // segment mode
std::string cPreset = "medium";
std::string cProfile = "main10";
std::string cLevel = "4.1";
std::string cTier = "main";
if( argc > 1 && (!strcmp( (const char*) argv[1], "--help" ) || !strcmp( (const char*) argv[1], "-h" )) )
{
std::cout << cAppname << " version: " << VVENC_VERSION << std::endl;
vvcutilities::CmdLineParser::print_usage( cAppname, cVVEncParameter, cPreset, cProfile, cLevel, cTier, false );
return 0;
}
else if( argc > 1 && (!strcmp( (const char*) argv[1], "--fullhelp" ) ) )
{
std::cout << cAppname << " version: " << VVENC_VERSION << std::endl;
vvcutilities::CmdLineParser::print_usage( cAppname, cVVEncParameter, cPreset, cProfile, cLevel, cTier, true );
return 0;
}
int iRet = vvcutilities::CmdLineParser::parse_command_line( argc, argv, cVVEncParameter, cInputFile, cOutputfile );
vvenc::VVEnc::registerMsgCbf( msgFnc );
g_verbosity = cVVEncParameter.m_eLogLevel;
if( iRet != 0 )
{
if( iRet == 2 || iRet == 3 )
{
bool bFullHelp = ( iRet == 3) ? true : false;
std::cout << cAppname << " version: " << VVENC_VERSION << std::endl;
vvcutilities::CmdLineParser::print_usage( cAppname, cVVEncParameter, cPreset, cProfile, cLevel, cTier, bFullHelp);
return 0;
}
std::cerr << cAppname << " [error]: cannot parse command line. run VVEncoderApp --help to see available options" << std::endl;
return -1;
}
if( cInputFile.empty() )
{
std::cerr << cAppname << " [error]: no input file given. run VVEncoderApp --help to see available options" << std::endl;
return -1;
}
if( cOutputfile.empty() )
{
std::cout << cAppname << " [error]: no output bitstream file given." << std::endl;
return -1;
}
if( cVVEncParameter.m_eLogLevel > vvenc::LL_SILENT && cVVEncParameter.m_eLogLevel < vvenc::LL_NOTICE )
{
std::cout << "-------------------" << std::endl;
std::cout << cAppname << " version " << vvenc::VVEnc::getVersionNumber() << std::endl;
}
if( cVVEncParameter.m_iThreadCount < 0 )
{
if( cVVEncParameter.m_iWidth > 1920 || cVVEncParameter.m_iHeight > 1080)
{
cVVEncParameter.m_iThreadCount = 6;
}
else
{
cVVEncParameter.m_iThreadCount = 4;
}
}
vvenc::VVEnc cVVEnc;
// initialize the encoder
iRet = cVVEnc.init( cVVEncParameter );
if( 0 != iRet )
{
printVVEncErrorMsg( cAppname, "cannot create encoder", iRet, cVVEnc.getLastError() );
return iRet;
}
if( cVVEncParameter.m_eLogLevel > vvenc::LL_WARNING )
{
std::cout << "VVEnc info: " << cVVEnc.getEncoderInfo() << std::endl;
}
// open output file
vvcutilities::BinFileWriter cBinFileWriter;
if( !cOutputfile.empty() )
{
if( 0 != cBinFileWriter.open( cOutputfile.c_str() ) )
{
std::cout << cAppname << " [error]: failed to open output file " << cOutputfile << std::endl;
return -1;
}
}
// --- allocate memory for output packets
vvenc::VvcAccessUnit cAccessUnit;
cAccessUnit.m_iBufSize = cVVEncParameter.m_iWidth * cVVEncParameter.m_iHeight;
cAccessUnit.m_pucBuffer = new unsigned char [ cAccessUnit.m_iBufSize ];
vvenc::InputPicture cInputPicture;
iRet = cVVEnc.getPreferredBuffer( cInputPicture.m_cPicBuffer );
if( 0 != iRet )
{
printVVEncErrorMsg( cAppname, "failed to get preferred buffer", iRet, cVVEnc.getLastError() );
return iRet;
}
const unsigned char* pucDeletePicBuffer = cInputPicture.m_cPicBuffer.m_pucDeletePicBuffer;
cInputPicture.m_cPicBuffer.m_pucDeletePicBuffer = NULL;
// --- start timer
std::chrono::steady_clock::time_point cTPStart;
std::chrono::steady_clock::time_point cTPEnd;
cVVEnc.clockStartTime();
cTPStart = std::chrono::steady_clock::now();
std::time_t startTime2 = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
if( cVVEncParameter.m_eLogLevel > vvenc::LL_WARNING )
{
std::cout << "started @ " << std::ctime(&startTime2) << std::endl;
}
unsigned int uiFrames = 0;
for( int pass = 0; pass < cVVEncParameter.m_iNumPasses; pass++ )
{
// initialize the encoder pass
iRet = cVVEnc.initPass( pass );
if( 0 != iRet )
{
printVVEncErrorMsg( cAppname, "cannot init encoder", iRet, cVVEnc.getLastError() );
return iRet;
}
// open the input file
vvcutilities::YuvFileReader cYuvFileReader;
if( 0 != cYuvFileReader.open( cInputFile.c_str(), cVVEncParameter.m_iInputBitDepth, cVVEncParameter.m_iInternalBitDepth, cVVEncParameter.m_iWidth, cVVEncParameter.m_iHeight ) )
{
std::cout << cAppname << " [error]: failed to open input file " << cInputFile << std::endl;
return -1;
}
const int64_t iFrameSkip = std::max<int64_t>( cVVEncParameter.m_iFrameSkip - cVVEnc.getNumLeadFrames(), 0 );
const int64_t iMaxFrames = cVVEncParameter.m_iMaxFrames + cVVEnc.getNumLeadFrames() + cVVEnc.getNumTrailFrames();
int64_t iSeqNumber = 0;
bool bEof = false;
unsigned int uiFramesTmp = 0;
uiFrames = 0;
while( !bEof )
{
iRet = cYuvFileReader.readPicture( cInputPicture.m_cPicBuffer );
if( iRet )
{
if( cVVEncParameter.m_eLogLevel > vvenc::LL_ERROR && cVVEncParameter.m_eLogLevel < vvenc::LL_NOTICE )
{
std::cout << "EOF reached" << std::endl;
}
bEof = true;
}
if( !bEof && iSeqNumber >= iFrameSkip )
{
// set sequence number and cts
cInputPicture.m_cPicBuffer.m_uiSequenceNumber = iSeqNumber;
cInputPicture.m_cPicBuffer.m_uiCts = iSeqNumber * cVVEncParameter.m_iTicksPerSecond * cVVEncParameter.m_iTemporalScale / cVVEncParameter.m_iTemporalRate;
cInputPicture.m_cPicBuffer.m_bCtsValid = true;
//std::cout << "process picture " << cInputPicture.m_cPicBuffer.m_uiSequenceNumber << " cts " << cInputPicture.m_cPicBuffer.m_uiCts << std::endl;
// call encode
iRet = cVVEnc.encode( &cInputPicture, cAccessUnit );
if( 0 != iRet )
{
printVVEncErrorMsg( cAppname, "encoding failed", iRet, cVVEnc.getLastError() );
return iRet;
}
if( 0 != cAccessUnit.m_iUsedSize )
{
if( cBinFileWriter.isOpen())
{
// write output
cBinFileWriter.writeAU( cAccessUnit );
}
uiFrames++;
uiFramesTmp++;
if( uiFrames && cVVEncParameter.m_eLogLevel > vvenc::LL_WARNING && cVVEncParameter.m_eLogLevel < vvenc::LL_NOTICE)
{
cTPEnd = std::chrono::steady_clock::now();
double dTimeMs = (double)std::chrono::duration_cast<std::chrono::milliseconds>((cTPEnd)-(cTPStart)).count();
if( dTimeMs > 1000.0 )
{
if( cVVEncParameter.m_eLogLevel > vvenc::LL_INFO ){ std::cout << std::endl;}
std::cout << "encoded Frames: " << uiFrames << " Fps: " << uiFramesTmp << std::endl;
cTPStart = std::chrono::steady_clock::now();
uiFramesTmp = 0;
}
}
}
}
iSeqNumber++;
if( iMaxFrames > 0 && iSeqNumber >= ( iFrameSkip + iMaxFrames ) ){ break; }
}
// flush the encoder
while( true )
{
iRet = cVVEnc.flush( cAccessUnit );
if( 0 != iRet )
{
printVVEncErrorMsg( cAppname, "flush encoder failed", iRet, cVVEnc.getLastError() );
return iRet;
}
if( 0 == cAccessUnit.m_iUsedSize )
{
break;
}
uiFrames++;
if( uiFrames && cVVEncParameter.m_eLogLevel > vvenc::LL_WARNING && cVVEncParameter.m_eLogLevel < vvenc::LL_NOTICE )
{
cTPEnd = std::chrono::steady_clock::now();
double dTimeMs = (double)std::chrono::duration_cast<std::chrono::milliseconds>((cTPEnd)-(cTPStart)).count();
if( dTimeMs > 1000.0 )
{
if( cVVEncParameter.m_eLogLevel > vvenc::LL_INFO ){ std::cout << std::endl;}
std::cout << "encoded Frames: " << uiFrames << " Fps: " << uiFramesTmp << std::endl;
cTPStart = std::chrono::steady_clock::now();
uiFramesTmp = 0;
}
}
if( cBinFileWriter.isOpen() )
{
// write output
cBinFileWriter.writeAU( cAccessUnit );
}
}
cYuvFileReader.close();
}
cVVEnc.clockEndTime();
double dTimeSec = cVVEnc.clockGetTimeDiffMs() / 1000;
delete[] cAccessUnit.m_pucBuffer;
delete[] pucDeletePicBuffer;
if( cBinFileWriter.isOpen())
{
cBinFileWriter.close();
}
// un-initialize the encoder
iRet = cVVEnc.uninit();
if( 0 != iRet )
{
printVVEncErrorMsg( cAppname, "destroyencoder failed", iRet, cVVEnc.getLastError() );
return iRet;
}
if( 0 == uiFrames )
{
std::cout << "no frames encoded" << std::endl;
}
if( uiFrames && cVVEncParameter.m_eLogLevel > vvenc::LL_SILENT )
{
std::time_t endTime2 = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
double dFps = (double)uiFrames / dTimeSec;
if( cVVEncParameter.m_eLogLevel > vvenc::LL_WARNING )
{
std::cout << "finished @ " << std::ctime(&endTime2) << std::endl;
}
std::cout << "Total Time: " << dTimeSec << " sec. Fps(avg): " << dFps << " encoded Frames " << uiFrames << std::endl;
}
return 0;
}
| 37.557416 | 208 | 0.633289 | Jamaika1 |
a4112ccdd7b540b87efcad658abfece69fc896ef | 8,746 | cpp | C++ | avs/vis_avs/r_multiplier.cpp | semiessessi/vis_avs | e99a3803e9de9032e0e6759963b2c2798f3443ef | [
"BSD-3-Clause"
] | 18 | 2020-07-30T11:55:23.000Z | 2022-02-25T02:39:15.000Z | avs/vis_avs/r_multiplier.cpp | semiessessi/vis_avs | e99a3803e9de9032e0e6759963b2c2798f3443ef | [
"BSD-3-Clause"
] | 34 | 2021-01-13T02:02:12.000Z | 2022-03-23T12:09:55.000Z | avs/vis_avs/r_multiplier.cpp | semiessessi/vis_avs | e99a3803e9de9032e0e6759963b2c2798f3443ef | [
"BSD-3-Clause"
] | 3 | 2021-03-18T12:53:58.000Z | 2021-10-02T20:24:41.000Z | /*
LICENSE
-------
Copyright 2005 Nullsoft, 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 Nullsoft nor the names of its contributors may be used to
endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "c_multiplier.h"
#include "r_defs.h"
#ifndef LASER
// set up default configuration
C_THISCLASS::C_THISCLASS()
{
memset(&config, 0, sizeof(apeconfig));
config.ml = MD_X2;
}
// virtual destructor
C_THISCLASS::~C_THISCLASS()
{
}
int C_THISCLASS::render(char[2][2][576], int isBeat, int *framebuffer, int*, int w, int h)
{
if (isBeat&0x80000000) return 0;
int /*b,*/c; // TODO [cleanup]: see below
__int64 mask;
c = w*h;
switch (config.ml) {
case MD_XI:
#ifdef _MSC_VER
__asm {
mov ebx, framebuffer;
mov ecx, c;
// mov edx, b; // doesn't do anything. a leftover?
lp0:
xor eax, eax;
dec ecx;
test ecx, ecx;
jz end;
mov eax, dword ptr [ebx+ecx*4];
test eax, eax;
jz sk0;
mov eax, 0xFFFFFF;
sk0:
mov [ebx+ecx*4], eax;
jmp lp0;
}
#else // _MSC_VER
__asm__ goto (
"mov %%ebx, %0\n\t"
"mov %%ecx, %1\n"
"lp0:\n\t"
"xor %%eax, %%eax\n\t"
"dec %%ecx\n\t"
"test %%ecx, %%ecx\n\t"
"jz %l[end]\n\t"
"mov %%eax, dword ptr [%%ebx + %%ecx * 4]\n\t"
"test %%eax, %%eax\n\t"
"jz sk0\n\t"
"mov %%eax, 0xFFFFFF\n"
"sk0:\n\t"
"mov [%%ebx + %%ecx * 4], %%eax\n\t"
"jmp lp0\n\t"
:/* no outputs */
:"m"(framebuffer), "m"(c)
:"eax", "ebx", "ecx"
:end
);
#endif
break;
case MD_XS:
#ifdef _MSC_VER
__asm {
mov ebx, framebuffer;
mov ecx, c;
// mov edx, b; // doesn't do anything. a leftover?
lp9:
xor eax, eax;
dec ecx;
test ecx, ecx;
jz end;
mov eax, dword ptr [ebx+ecx*4];
cmp eax, 0xFFFFFF;
je sk9; // TODO [bugfix]: this could be jae, to account for garbage in MSByte
// TODO [performance]: the next _3_ lines could be compressed into just
// mov [ebx+ecx*4], 0x000000
// sk9:
// since the white pixel (= 0xFFFFFF) doesn't need to be rewritten
mov eax, 0x000000;
sk9:
mov [ebx+ecx*4], eax;
jmp lp9;
}
#else // _MSC_VER
__asm__ goto (
"mov %%ebx, %0\n\t"
"mov %%ecx, %1\n"
"lp9:\n\t"
"xor %%eax, %%eax\n\t"
"dec %%ecx\n\t"
"test %%ecx, %%ecx\n\t"
"jz %l[end]\n\t"
"mov %%eax, dword ptr [%%ebx + %%ecx * 4]\n\t"
"cmp %%eax, 0xFFFFFF\n\t"
"je sk9\n\t"
"mov %%eax, 0x000000\n"
"sk9:\n\t"
"mov [%%ebx + %%ecx * 4], %%eax\n\t"
"jmp lp9\n\t"
:/* no outputs */
:"m"(framebuffer), "m"(c)
:"eax", "ebx", "ecx"
:end
);
#endif
break;
case MD_X8:
c = w*h/2;
#ifdef _MSC_VER
__asm {
mov ebx, framebuffer;
mov ecx, c;
lp1:
movq mm0, [ebx];
paddusb mm0, mm0;
paddusb mm0, mm0;
paddusb mm0, mm0;
movq [ebx], mm0;
add ebx, 8;
dec ecx;
test ecx, ecx;
jz end;
jmp lp1;
}
#else // _MSC_VER
__asm__ goto (
"mov %%ebx, %0\n\t"
"mov %%ecx, %1\n"
"lp1:\n\t"
"movq %%mm0, [%%ebx]\n\t"
"paddusb %%mm0, %%mm0\n\t"
"paddusb %%mm0, %%mm0\n\t"
"paddusb %%mm0, %%mm0\n\t"
"movq [%%ebx], %%mm0\n\t"
"add %%ebx, 8\n\t"
"dec %%ecx\n\t"
"test %%ecx, %%ecx\n\t"
"jz %l[end]\n\t"
"jmp lp1\n\t"
:/* no outputs */
:"m"(framebuffer), "m"(c)
:"ebx", "ecx"
:end
);
#endif
break;
case MD_X4:
c = w*h/2;
#ifdef _MSC_VER
__asm {
mov ebx, framebuffer;
mov ecx, c;
lp2:
movq mm0, [ebx];
paddusb mm0, mm0;
paddusb mm0, mm0;
movq [ebx], mm0;
add ebx, 8;
dec ecx;
test ecx, ecx;
jz end;
jmp lp2;
}
#else // _MSC_VER
__asm__ goto (
"mov %%ebx, %0\n\t"
"mov %%ecx, %1\n"
"lp2:\n\t"
"movq %%mm0, [%%ebx]\n\t"
"paddusb %%mm0, %%mm0\n\t"
"paddusb %%mm0, %%mm0\n\t"
"movq [%%ebx], %%mm0\n\t"
"add %%ebx, 8\n\t"
"dec %%ecx\n\t"
"test %%ecx, %%ecx\n\t"
"jz %l[end]\n\t"
"jmp lp2\n\t"
:/* no outputs */
:"m"(framebuffer), "m"(c)
:"ebx", "ecx"
:end
);
#endif
break;
case MD_X2:
c = w*h/2;
#ifdef _MSC_VER
__asm {
mov ebx, framebuffer;
mov ecx, c;
lp3:
movq mm0, [ebx];
paddusb mm0, mm0;
movq [ebx], mm0;
add ebx, 8;
dec ecx;
test ecx, ecx;
jz end;
jmp lp3;
}
#else // _MSC_VER
__asm__ goto (
"mov %%ebx, %0\n\t"
"mov %%ecx, %1\n"
"lp3:\n\t"
"movq %%mm0, [%%ebx]\n\t"
"paddusb %%mm0, %%mm0\n\t"
"movq [%%ebx], %%mm0\n\t"
"add %%ebx, 8\n\t"
"dec %%ecx\n\t"
"test %%ecx, %%ecx\n\t"
"jz %l[end]\n\t"
"jmp lp3\n\t"
:/* no outputs */
:"m"(framebuffer), "m"(c)
:"ebx", "ecx"
:end
);
#endif
break;
case MD_X05:
c = w*h/2;
mask = 0x7F7F7F7F7F7F7F7F;
#ifdef _MSC_VER
__asm {
mov ebx, framebuffer;
mov ecx, c;
movq mm1, mask;
lp4:
movq mm0, [ebx];
psrlq mm0, 1;
pand mm0, mm1;
movq [ebx], mm0;
add ebx, 8;
dec ecx;
test ecx, ecx;
jz end;
jmp lp4;
}
#else // _MSC_VER
__asm__ goto (
"mov %%ebx, %0\n\t"
"mov %%ecx, %1\n\t"
"movq %%mm1, %2\n"
"lp4:\n\t"
"movq %%mm0, [%%ebx]\n\t"
"psrlq %%mm0, 1\n\t"
"pand %%mm0, %%mm1\n\t"
"movq [%%ebx], %%mm0\n\t"
"add %%ebx, 8\n\t"
"dec %%ecx\n\t"
"test %%ecx, %%ecx\n\t"
"jz %l[end]\n\t"
"jmp lp4\n\t"
:/* no outputs */
:"m"(framebuffer), "m"(c), "m"(mask)
:"ebx", "ecx"
:end
);
#endif
break;
case MD_X025:
c = w*h/2;
mask = 0x3F3F3F3F3F3F3F3F;
#ifdef _MSC_VER
__asm {
mov ebx, framebuffer;
mov ecx, c;
movq mm1, mask;
lp5:
movq mm0, [ebx];
psrlq mm0, 2;
pand mm0, mm1;
movq [ebx], mm0;
add ebx, 8;
dec ecx;
test ecx, ecx;
jz end;
jmp lp5;
}
#else // _MSC_VER
__asm__ goto (
"mov %%ebx, %0\n\t"
"mov %%ecx, %1\n\t"
"movq %%mm1, %2\n"
"lp5:\n\t"
"movq %%mm0, [%%ebx]\n\t"
"psrlq %%mm0, 2\n\t"
"pand %%mm0, %%mm1\n\t"
"movq [%%ebx], %%mm0\n\t"
"add %%ebx, 8\n\t"
"dec %%ecx\n\t"
"test %%ecx, %%ecx\n\t"
"jz %l[end]\n\t"
"jmp lp5\n\t"
:/* no outputs */
:"m"(framebuffer), "m"(c), "m"(mask)
:"ebx", "ecx"
:end
);
#endif
break;
case MD_X0125:
c = w*h/2;
mask = 0x1F1F1F1F1F1F1F1F;
#ifdef _MSC_VER
__asm {
mov ebx, framebuffer;
mov ecx, c;
movq mm1, mask;
lp6:
movq mm0, [ebx];
psrlq mm0, 3;
pand mm0, mm1;
movq [ebx], mm0;
add ebx, 8;
dec ecx;
test ecx, ecx;
jz end;
jmp lp6;
}
#else // _MSC_VER
__asm__ goto (
"mov %%ebx, %0\n\t"
"mov %%ecx, %1\n\t"
"movq %%mm1, %2\n"
"lp6:\n\t"
"movq %%mm0, [%%ebx]\n\t"
"psrlq %%mm0, 3\n\t"
"pand %%mm0, %%mm1\n\t"
"movq [%%ebx], %%mm0\n\t"
"add %%ebx, 8\n\t"
"dec %%ecx\n\t"
"test %%ecx, %%ecx\n\t"
"jz %l[end]\n\t"
"jmp lp6\n\t"
:/* no outputs */
:"m"(framebuffer), "m"(c), "m"(mask)
:"ebx", "ecx"
:end
);
#endif
break;
}
end:
#ifdef _MSC_VER
__asm emms;
#else // _MSC_VER
__asm__ __volatile__ ("emms");
#endif
return 0;
}
char *C_THISCLASS::get_desc(void)
{
return MOD_NAME;
}
void C_THISCLASS::load_config(unsigned char *data, int len)
{
if (len == sizeof(apeconfig))
memcpy(&this->config, data, len);
else
memset(&this->config, 0, sizeof(apeconfig));
}
int C_THISCLASS::save_config(unsigned char *data)
{
memcpy(data, &this->config, sizeof(apeconfig));
return sizeof(apeconfig);
}
C_RBASE *R_Multiplier(char *desc)
{
if (desc) {
strcpy(desc,MOD_NAME);
return NULL;
}
return (C_RBASE *) new C_THISCLASS();
}
#endif | 20.627358 | 102 | 0.570089 | semiessessi |
a4119f4812509d12b78f711dcc2f5ad1c2e82575 | 10,107 | hh | C++ | trex/utils/SharedVar.hh | miatauro/trex2-agent | d896f8335f3194237a8bba49949e86f5488feddb | [
"BSD-3-Clause"
] | null | null | null | trex/utils/SharedVar.hh | miatauro/trex2-agent | d896f8335f3194237a8bba49949e86f5488feddb | [
"BSD-3-Clause"
] | null | null | null | trex/utils/SharedVar.hh | miatauro/trex2-agent | d896f8335f3194237a8bba49949e86f5488feddb | [
"BSD-3-Clause"
] | null | null | null | /* -*- C++ -*- */
/** @file "SharedVar.hh"
* @brief utilities for multi-thread shared variable
*
* This header declare classes and utilities to easily
* share a variable between multiple threads.
*
* @author Frederic Py <fpy@mbari.org>
* @ingroup utils
*/
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, MBARI.
* 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 TREX Project 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.
*/
#ifndef H_SharedVar
# define H_SharedVar
# include <boost/call_traits.hpp>
# include <boost/utility.hpp>
# include <boost/thread/recursive_mutex.hpp>
# include "Exception.hh"
namespace TREX {
namespace utils {
/** @brief Bad access exception
* @relates SharedVar
*
* This exception is thrown by SharedVar when one tries
* to access a SharedVar it has not locked.
*
* @author Frederic Py <fpy@mbari.org>
*
* @note The management of this error is more a coding issue.
* It may be fine to be able to disable it when we are sure
* that this condition is respected. (?)
* @ingroup utils
*/
class AccessExcept
:public Exception {
public:
/** @brief Constructor.
*
* @param[in] message Error message.
*
* Create a new instance with associated message @p message
*/
AccessExcept(std::string const &message) throw()
:Exception(message) {}
/** @brief Destructor. */
~AccessExcept() throw() {}
}; // TREX::utils::AccessExcept
/** @brief multi-thread shared variable
*
* This class implements a simple utility to manage a variable
* which is manipulated by multiple threads. It ensures that this
* variable is accessed only by the thread which have
* reserved (locked) it.
*
* @tparam Ty Type of the variable to be shared
*
* @pre @p Ty must provides a copy constructor
* @pre @p Ty must be default constructible
*
* @author Frederic Py <fpy@mbari.org>
* @ingroup utils
*/
template<class Ty>
class SharedVar :boost::noncopyable {
private:
typedef boost::recursive_timed_mutex mutex_type;
public:
/** @brief Scoped variable locking type
*
* This type can be used to locally lock one SharedVar based
* in a C++ scope.
* A new instance of this class will lock the mutex associated
* to the SharedVar during its whiole lifetime and release the
* mutex on its destruction.
*
* This provide a simple, exception safe, way to lock a
* SharedVar during a critical section while avoiding to
* have it remains locked in the eventuality of an exception.
*
* For example on can implement the function @c getval(SharedVar const &)
* that returns the value of a SharedVar like this:
* @code
* template<class Ty>
* Ty getval(SharedVar<Ty> const &var) {
* SharedVar<Ty>::scoped_lock slock(var);
* return *var;
* }
* @endcode
* At the begining of this function the creation of @c slock locks
* the mutex associated to @c var. This alows to access to @c var
* on the next line. Finally, as we leave the function context @c slock
* will be destroyed and by doing so will release the mutex it locked during
* its creation.
*/
typedef boost::unique_lock< SharedVar<Ty> > scoped_lock;
/** @brief Constructor.
*
* @param[in] val An init value
*
* Create a new instance and set its value to @p val
*
* @post the newly created instance is not locked
*/
SharedVar(typename boost::call_traits<Ty>::param_type val=Ty())
:m_lockCount(0ul), m_var(val) {}
/** @brief Destructor */
~SharedVar() {}
/** @brief Locking method.
*
* This method locks the current variable.
*
* @note This call is blocking; If this inatnce is locked by
* another thread. The caller will be suspended until we can
* sucedsfully lock the varaible for this thread.
*
* @post The variable is locked by the current thread.
*
* @throw ErrnoExcept System error
*
* @sa unlock() const
*/
void lock() const {
m_mtx.lock();
++m_lockCount;
}
/** @brief Unlocking method.
*
* Unlock the mutex attached to this variable.
*
* @pre The variable is locked by current thread.
* @post The variable is not locked by this thread anymore.
*
* @throw AccessExcept Variable not locked by this thread.
* @throw ErrnoExcept System error.
*
* @sa lock() const
* @sa ownIt() const
*/
void unlock() const {
if( ownIt() ) {
--m_lockCount;
m_mtx.unlock();
}
}
/** @brief Assignment operator.
*
* @param[in] value A value
*
* This methods set current instance to @p value.
*
* @return @p value
*
* @note This call is thread safe and atomic. If current instance
* is not already locked by the calling thread, it will do so and
* unlock it on completion.
*
* @throw ErrnoExcept System error.
*/
typename boost::call_traits<Ty>::param_type
operator=(typename boost::call_traits<Ty>::param_type value) {
scoped_lock lock(*this);
m_var = value;
return value;
}
void swap(Ty &other) {
scoped_lock lock(*this);
std::swap(m_var, other);
}
/** @brief Check for thread ownership
*
* This methods indicates if current instance is locked by
* current thread.
* A thread can manipulate a SharedVariable if and only if
* this variable is locked by the thread. This method allows
* user to check such information.
*
* @retval true If this instance is locked by the calliung thread.
* @retval false otherwise
*
* @sa lock() const
* @sa unlock() const
*/
bool ownIt() const {
mutex_type::scoped_try_lock lock(m_mtx);
return lock.owns_lock() && m_lockCount>0;
}
/** @brief Dereferencing operator
*
* Give access to the shared variable
*
* @pre This instance is locked by current thread
*
* @return A reference to the variable
*
* @throw AccessExcept Variable is not locked by current thread.
* @throw ErrnoExcept System error
*
* @sa lock() const
* @sa ownIt() const
* @sa operator->()
* @{
*/
Ty &operator* () {
if( !ownIt() )
throw AccessExcept("Cannot access a shared var which I don't own.");
return m_var;
}
Ty const &operator* () const {
if( !ownIt() )
throw AccessExcept("Cannot access a shared var which I don't own.");
return m_var;
}
/** @} */
/** @brief Access operator.
*
* Give access to variable and more specifically to its attributes.
*
* @pre This instance is locked by current thread
*
* @return A pointer to the variable allowing access to its attributes
*
* @throw AccessExcept Variable is not owned by current thread.
* @throw ErrnoExcept System error.
*
* @sa lock() const
* @sa ownIt() const
* @sa operator* ()
* @{
*/
Ty *operator->() {
return &operator* ();
}
Ty const *operator->() const {
return &operator* ();
}
/** @} */
private:
/** @brief Mutex to lock/unlock variable */
mutable mutex_type m_mtx; //!< @brief System mutex for this variable
/** @brief mutex lock counter
*
* This attribute count the number of locks currently active on
* this instance. By design the counter will be modified only by
* the thread which is currently locking the variable.
*
* The variable is not locked by any thread as soon as this counter reaches 0.
*
* @sa lock() const
* @sa unlock() const
*/
mutable size_t m_lockCount;
/** @brief Variable value */
Ty m_var;
}; // TREX::utils::SharedVar<>
} // TREX::utils
} // TREX
#endif // H_SharedVar
| 32.498392 | 84 | 0.598793 | miatauro |
a414043fb3a5a0513723c8bb5f357577414d4000 | 1,279 | cpp | C++ | easy/nimble/main.cpp | exbibyte/hr | 100514dfc2a1c9b5366c12ec0a75e889132a620e | [
"MIT"
] | null | null | null | easy/nimble/main.cpp | exbibyte/hr | 100514dfc2a1c9b5366c12ec0a75e889132a620e | [
"MIT"
] | null | null | null | easy/nimble/main.cpp | exbibyte/hr | 100514dfc2a1c9b5366c12ec0a75e889132a620e | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <string>
#include <unordered_set>
#include <unordered_map>
#include <vector>
#include <map>
std::vector<std::pair<int,int>> moves(int x, int y ){
std::vector<std::pair<int,int>> v = { {x-2,y+1},{x-2,y-1},{x+1,y-2},{x-1,y-2} };
auto it_end = std::remove_if( v.begin(), v.end(),
[](auto a){ return a.first < 1 || a.first > 15 ||
a.second < 1 || a.second > 15; });
v.resize( std::distance(v.begin(),it_end) );
return v;
}
bool simulate(int x, int y, std::map<std::pair<int,int>,bool> & cache ){
auto m = moves(x,y);
if (m.empty()){
return false; //no moves left, current player loses
}
auto mem = cache.find({x,y});
if(mem!=cache.end()){
return mem->second;
}
bool current_player_win = false;
for(auto i: m){
bool result = !simulate(i.first,i.second, cache );
current_player_win |= result;
}
cache[{x,y}] = current_player_win;
return current_player_win;
}
int main(){
int q;
std::cin >> q;
std::map<std::pair<int,int>,bool> cache;
for(int i=0;i<q;++i){
int x,y;
std::cin >> x >> y;
bool ret = simulate(x,y,cache);
if(ret){ std::cout << "First" << std::endl; }
else{ std::cout << "Second" << std::endl; }
}
return 0;
}
| 21.677966 | 82 | 0.577795 | exbibyte |
a415d87375ae54df280b10cc84c3a54e0627b4db | 64 | hpp | C++ | src/boost_mpl_aux__preprocessed_msvc60_greater_equal.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_mpl_aux__preprocessed_msvc60_greater_equal.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_mpl_aux__preprocessed_msvc60_greater_equal.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/mpl/aux_/preprocessed/msvc60/greater_equal.hpp>
| 32 | 63 | 0.828125 | miathedev |
a417330acf645dc86bbc4a6be5d8b97a9a2b8612 | 2,132 | cpp | C++ | JsonParsing/Source/JsonParsing/JsonParser.cpp | devilmhzx/UE4-Cpp-Tutorials | 2cbf9d44dd4fa1c4eb68530f692065fc2c36b55d | [
"MIT"
] | 531 | 2016-10-19T14:04:55.000Z | 2022-03-28T06:34:25.000Z | JsonParsing/Source/JsonParsing/JsonParser.cpp | devilmhzx/UE4-Cpp-Tutorials | 2cbf9d44dd4fa1c4eb68530f692065fc2c36b55d | [
"MIT"
] | null | null | null | JsonParsing/Source/JsonParsing/JsonParser.cpp | devilmhzx/UE4-Cpp-Tutorials | 2cbf9d44dd4fa1c4eb68530f692065fc2c36b55d | [
"MIT"
] | 172 | 2016-10-18T14:53:11.000Z | 2022-03-22T10:39:44.000Z | // Fill out your copyright notice in the Description page of Project Settings.
#include "JsonParser.h"
#include "JsonUtilities.h"
// Sets default values
AJsonParser::AJsonParser()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void AJsonParser::BeginPlay()
{
Super::BeginPlay();
const FString JsonFilePath = FPaths::ProjectContentDir() + "/JsonFiles/randomgenerated.json";
FString JsonString; //Json converted to FString
FFileHelper::LoadFileToString(JsonString,*JsonFilePath);
//Displaying the json in a string format inside the output log
GLog->Log("Json String:");
GLog->Log(JsonString);
//Create a json object to store the information from the json string
//The json reader is used to deserialize the json object later on
TSharedPtr<FJsonObject> JsonObject = MakeShareable(new FJsonObject());
TSharedRef<TJsonReader<>> JsonReader = TJsonReaderFactory<>::Create(JsonString);
if (FJsonSerializer::Deserialize(JsonReader, JsonObject) && JsonObject.IsValid())
{
//The person "object" that is retrieved from the given json file
TSharedPtr<FJsonObject> PersonObject = JsonObject->GetObjectField("Person");
//Getting various properties
GLog->Log("Balance:" + PersonObject->GetStringField("balance"));
GLog->Log("Age:" + FString::FromInt(PersonObject->GetIntegerField("age")));
FString IsActiveStr = (PersonObject->GetBoolField("isActive")) ? "Active" : "Inactive";
GLog->Log("IsActive:" + IsActiveStr);
GLog->Log("Latitude:" + FString::SanitizeFloat(PersonObject->GetNumberField("latitude")));
//Retrieving an array property and printing each field
TArray<TSharedPtr<FJsonValue>> objArray=PersonObject->GetArrayField("family");
GLog->Log("printing family names...");
for(int32 index=0;index<objArray.Num();index++)
{
GLog->Log("name:"+objArray[index]->AsString());
}
}
else
{
GLog->Log("couldn't deserialize");
}
}
// Called every frame
void AJsonParser::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
| 31.352941 | 115 | 0.735929 | devilmhzx |
a417cc08b00e9e4d6b81a70df83aba4b4b8c5b1d | 306 | hpp | C++ | tests/bitset/bitset_mini.hpp | olegpublicprofile/stdfwd | 19671bcc8e53bd4c008f07656eaf25a22495e093 | [
"MIT"
] | 11 | 2021-03-15T07:06:21.000Z | 2021-09-27T13:54:25.000Z | tests/bitset/bitset_mini.hpp | olegpublicprofile/stdfwd | 19671bcc8e53bd4c008f07656eaf25a22495e093 | [
"MIT"
] | null | null | null | tests/bitset/bitset_mini.hpp | olegpublicprofile/stdfwd | 19671bcc8e53bd4c008f07656eaf25a22495e093 | [
"MIT"
] | 1 | 2021-06-24T10:46:46.000Z | 2021-06-24T10:46:46.000Z | #pragma once
//------------------------------------------------------------------------------
namespace bitset_tests {
//------------------------------------------------------------------------------
void run_mini();
//------------------------------------------------------------------------------
}
| 21.857143 | 80 | 0.140523 | olegpublicprofile |
a41beafd92f415421898e9ec4cc8cac46cf3ff3d | 2,429 | cc | C++ | tizen/mobile/sensor/sensor_provider.cc | jakegeno/crosswalk | 325ab480b5ec203b53815f072e42006dd00009ec | [
"BSD-3-Clause"
] | 3 | 2015-07-07T13:48:43.000Z | 2019-09-18T04:37:41.000Z | tizen/mobile/sensor/sensor_provider.cc | DonnaWuDongxia/crosswalk | 2eff18f2a2c30f2fc2a95de8d714d464b465a0e4 | [
"BSD-3-Clause"
] | 1 | 2022-01-20T10:49:19.000Z | 2022-01-20T12:56:47.000Z | tizen/mobile/sensor/sensor_provider.cc | DonnaWuDongxia/crosswalk | 2eff18f2a2c30f2fc2a95de8d714d464b465a0e4 | [
"BSD-3-Clause"
] | 8 | 2015-06-02T21:13:45.000Z | 2022-01-20T10:36:43.000Z | // Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/tizen/mobile/sensor/sensor_provider.h"
#include "base/logging.h"
#include "xwalk/tizen/mobile/sensor/tizen_platform_sensor.h"
namespace xwalk {
SensorProvider* SensorProvider::GetInstance() {
if (instance_.get() == NULL) {
instance_.reset(new TizenPlatformSensor());
instance_->Initialize();
}
return instance_.get();
}
SensorProvider::SensorProvider()
: last_orientation_(blink::WebScreenOrientationUndefined),
connected_(false) {
}
SensorProvider::~SensorProvider() {
Finish();
}
// Whether the platform sensors are connected.
bool SensorProvider::connected() const {
base::AutoLock lock(lock_);
return connected_;
}
void SensorProvider::AddObserver(Observer* observer) {
observers_.insert(observer);
}
void SensorProvider::RemoveObserver(Observer* observer) {
observers_.erase(observer);
}
void SensorProvider::OnScreenOrientationChanged(
blink::WebScreenOrientationType orientation) {
last_orientation_ = orientation;
std::set<Observer*>::iterator it;
for (it = observers_.begin(); it != observers_.end(); ++it)
(*it)->OnScreenOrientationChanged(orientation);
}
void SensorProvider::OnOrientationChanged(float alpha,
float beta,
float gamma) {
std::set<Observer*>::iterator it;
for (it = observers_.begin(); it != observers_.end(); ++it)
(*it)->OnOrientationChanged(alpha, beta, gamma);
}
void SensorProvider::OnAccelerationChanged(
float raw_x, float raw_y, float raw_z,
float x, float y, float z) {
std::set<Observer*>::iterator it;
for (it = observers_.begin(); it != observers_.end(); ++it)
(*it)->OnAccelerationChanged(raw_x, raw_y, raw_z, x, y, z);
}
void SensorProvider::OnRotationRateChanged(float alpha,
float beta,
float gamma) {
std::set<Observer*>::iterator it;
for (it = observers_.begin(); it != observers_.end(); ++it)
(*it)->OnRotationRateChanged(alpha, beta, gamma);
}
void SensorProvider::OnSensorConnected() {
for (auto observer : observers_)
observer->OnSensorConnected();
}
scoped_ptr<SensorProvider> SensorProvider::instance_;
} // namespace xwalk
| 29.26506 | 73 | 0.672705 | jakegeno |
a428f0bfc572b69f9ed52b90ccc296608d64ca08 | 4,656 | cpp | C++ | src/slib/network/mac_address.cpp | inogroup/SLib | 6c053c8f47f04240b8444eac5f316effdee2eb01 | [
"MIT"
] | 2 | 2021-07-29T18:29:25.000Z | 2021-09-07T08:51:14.000Z | src/slib/network/mac_address.cpp | inogroup/SLib | 6c053c8f47f04240b8444eac5f316effdee2eb01 | [
"MIT"
] | 1 | 2021-07-29T18:22:35.000Z | 2021-07-29T18:59:41.000Z | src/slib/network/mac_address.cpp | inogroup/SLib | 6c053c8f47f04240b8444eac5f316effdee2eb01 | [
"MIT"
] | 3 | 2021-07-29T17:08:12.000Z | 2021-12-14T06:21:41.000Z | /*
* Copyright (c) 2008-2021 SLIBIO <https://github.com/SLIBIO>
*
* 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 "slib/network/mac_address.h"
#include "slib/core/string.h"
namespace slib
{
SLIB_ALIGN(8) const sl_uint8 MacAddress::_zero[6] = { 0 };
SLIB_ALIGN(8) const sl_uint8 MacAddress::_broadcast[6] = { 255, 255, 255, 255, 255, 255 };
MacAddress::MacAddress(const sl_uint8* _m) noexcept
{
m[0] = _m[0];
m[1] = _m[1];
m[2] = _m[2];
m[3] = _m[3];
m[4] = _m[4];
m[5] = _m[5];
}
MacAddress::MacAddress(sl_uint8 m0, sl_uint8 m1, sl_uint8 m2, sl_uint8 m3, sl_uint8 m4, sl_uint8 m5) noexcept
{
m[0] = m0;
m[1] = m1;
m[2] = m2;
m[3] = m3;
m[4] = m4;
m[5] = m5;
}
MacAddress::MacAddress(const StringParam& address) noexcept
{
if (!(parse(address))) {
setZero();
}
}
void MacAddress::setZero() noexcept
{
m[0] = 0;
m[1] = 0;
m[2] = 0;
m[3] = 0;
m[4] = 0;
m[5] = 0;
}
void MacAddress::setBroadcast() noexcept
{
m[0] = 255;
m[1] = 255;
m[2] = 255;
m[3] = 255;
m[4] = 255;
m[5] = 255;
}
void MacAddress::makeMulticast(const IPv4Address& addrMulticast) noexcept
{
m[0] = 1;
m[1] = 0;
m[2] = 0x5e;
m[3] = addrMulticast.b & 0x7F;
m[4] = addrMulticast.c;
m[5] = addrMulticast.d;
}
void MacAddress::makeMulticast(const IPv6Address& addrMulticast) noexcept
{
m[0] = 0x33;
m[1] = 0x33;
m[2] = addrMulticast.m[12];
m[3] = addrMulticast.m[13];
m[4] = addrMulticast.m[14];
m[5] = addrMulticast.m[15];
}
void MacAddress::getBytes(sl_uint8* _m) const noexcept
{
_m[0] = m[0];
_m[1] = m[1];
_m[2] = m[2];
_m[3] = m[3];
_m[4] = m[4];
_m[5] = m[5];
}
void MacAddress::setBytes(const sl_uint8* _m) noexcept
{
m[0] = _m[0];
m[1] = _m[1];
m[2] = _m[2];
m[3] = _m[3];
m[4] = _m[4];
m[5] = _m[5];
}
String MacAddress::toString(sl_char8 sep) const noexcept
{
const char* hex = "0123456789ABCDEF";
char s[17];
char* p = s;
for (int i = 0; i < 6; i++) {
if (i) {
*(p++) = sep;
}
*(p++) = hex[m[i] >> 4];
*(p++) = hex[m[i] & 15];
}
return String(s, sizeof(s));
}
namespace priv
{
namespace mac_address
{
template <class CT>
SLIB_INLINE static sl_reg Parse(MacAddress* obj, const CT* sz, sl_size i, sl_size n) noexcept
{
int v[6];
for (int k = 0; k < 6; k++) {
int t = 0;
int s = 0;
for (; i < n; i++) {
int h = sz[i];
if (h >= '0' && h <= '9') {
s = (s << 4) | (h - '0');
if (s > 255) {
return SLIB_PARSE_ERROR;
}
t++;
} else if (h >= 'A' && h <= 'F') {
s = (s << 4) | (h - 'A' + 10);
if (s > 255) {
return SLIB_PARSE_ERROR;
}
t++;
} else if (h >= 'a' && h <= 'f') {
s = (s << 4) | (h - 'a' + 10);
if (s > 255) {
return SLIB_PARSE_ERROR;
}
t++;
} else {
break;
}
}
if (k < 5) {
if (i >= n || (sz[i] != '-' && sz[i] != ':')) {
return SLIB_PARSE_ERROR;
}
i++;
}
if (t == 0) {
return SLIB_PARSE_ERROR;
}
v[k] = s;
}
if (obj) {
obj->m[0] = (sl_uint8)(v[0]);
obj->m[1] = (sl_uint8)(v[1]);
obj->m[2] = (sl_uint8)(v[2]);
obj->m[3] = (sl_uint8)(v[3]);
obj->m[4] = (sl_uint8)(v[4]);
obj->m[5] = (sl_uint8)(v[5]);
}
return i;
}
}
}
SLIB_DEFINE_CLASS_PARSE_MEMBERS(MacAddress, priv::mac_address::Parse)
MacAddress& MacAddress::operator=(const StringParam& address) noexcept
{
if (!(parse(address))) {
setZero();
}
return *this;
}
}
| 22.712195 | 110 | 0.55756 | inogroup |
a429b28c9c8bcd72bcf2f4fe31d909beb30482f5 | 2,517 | cpp | C++ | libnd4j/include/ops/declarable/helpers/impl/where.cpp | phong-phuong/deeplearning4j | d21e8839578d328f46f4b5ca38307a78528c34f5 | [
"Apache-2.0"
] | null | null | null | libnd4j/include/ops/declarable/helpers/impl/where.cpp | phong-phuong/deeplearning4j | d21e8839578d328f46f4b5ca38307a78528c34f5 | [
"Apache-2.0"
] | null | null | null | libnd4j/include/ops/declarable/helpers/impl/where.cpp | phong-phuong/deeplearning4j | d21e8839578d328f46f4b5ca38307a78528c34f5 | [
"Apache-2.0"
] | null | null | null | /* ******************************************************************************
*
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* 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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
//
// Created by raver119 on 24/09/18.
//
#include <ops/declarable/helpers/where.h>
#include <array/NDArrayList.h>
namespace sd {
namespace ops {
namespace helpers {
template <typename T>
static void __where(NDArray &condition, NDArray& output, memory::Workspace *workspace) {
NDArrayList list(0, true);
int cnt = 0;
int idx[MAX_RANK];
for (Nd4jLong e = 0; e < condition.lengthOf(); e++) {
shape::index2coordsCPU(0, e, condition.shapeInfo(), idx);
auto offset = shape::getOffset(condition.shapeInfo(), idx);
if (condition.e<bool>(offset)) {
auto array = NDArrayFactory::create_('c', {1, condition.rankOf()}, output.dataType(), output.getContext());
for (int f = 0; f < condition.rankOf(); f++)
array->p(f, (T) idx[f]);
list.write(cnt++, array);
}
}
auto s = list.stack();
output.assign(s);
delete s;
}
BUILD_SINGLE_TEMPLATE(template ND4J_LOCAL void __where,(NDArray &condition, NDArray& output, memory::Workspace *workspace), LIBND4J_TYPES);
ND4J_LOCAL void _where(sd::LaunchContext * context, NDArray &condition, NDArray& output, memory::Workspace *workspace) {
condition.syncToHost();
BUILD_SINGLE_SELECTOR(output.dataType(), __where, (condition, output, workspace), LIBND4J_TYPES);
output.syncToDevice();
}
}
}
}
| 38.723077 | 151 | 0.556218 | phong-phuong |
a42bd6f41ba82266e29026831b75628aaa4fae92 | 2,343 | cpp | C++ | B2G/gecko/gfx/layers/opengl/TexturePoolOGL.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-08-31T15:24:31.000Z | 2020-04-24T20:31:29.000Z | B2G/gecko/gfx/layers/opengl/TexturePoolOGL.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | null | null | null | B2G/gecko/gfx/layers/opengl/TexturePoolOGL.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-07-29T07:17:15.000Z | 2020-11-04T06:55:37.000Z | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "TexturePoolOGL.h"
#include "GLContext.h"
#include "nsDeque.h"
#include "mozilla/Monitor.h"
#define TEXTURE_POOL_SIZE 10
namespace mozilla {
namespace gl {
static GLContext* sActiveContext = NULL;
static Monitor* sMonitor = NULL;
static nsDeque* sTextures = NULL;
GLuint TexturePoolOGL::AcquireTexture()
{
NS_ASSERTION(sMonitor, "not initialized");
MonitorAutoLock lock(*sMonitor);
if (!sActiveContext) {
// Wait for a context
sMonitor->Wait();
if (!sActiveContext)
return 0;
}
GLuint texture = 0;
if (sActiveContext->IsOwningThreadCurrent()) {
sActiveContext->MakeCurrent();
sActiveContext->fGenTextures(1, &texture);
} else {
while (sTextures->GetSize() == 0) {
NS_WARNING("Waiting for texture");
sMonitor->Wait();
}
GLuint* popped = (GLuint*) sTextures->Pop();
if (!popped) {
NS_ERROR("Failed to pop texture pool item");
return 0;
}
texture = *popped;
delete popped;
NS_ASSERTION(texture, "Failed to retrieve texture from pool");
}
return texture;
}
static void Clear()
{
if (!sActiveContext)
return;
sActiveContext->MakeCurrent();
GLuint* item;
while (sTextures->GetSize()) {
item = (GLuint*)sTextures->Pop();
sActiveContext->fDeleteTextures(1, item);
delete item;
}
}
void TexturePoolOGL::Fill(GLContext* aContext)
{
NS_ASSERTION(aContext, "NULL GLContext");
NS_ASSERTION(sMonitor, "not initialized");
MonitorAutoLock lock(*sMonitor);
if (sActiveContext != aContext) {
Clear();
sActiveContext = aContext;
}
if (sTextures->GetSize() == TEXTURE_POOL_SIZE)
return;
sActiveContext->MakeCurrent();
GLuint* texture = NULL;
while (sTextures->GetSize() < TEXTURE_POOL_SIZE) {
texture = (GLuint*)malloc(sizeof(GLuint));
sActiveContext->fGenTextures(1, texture);
sTextures->Push((void*) texture);
}
sMonitor->NotifyAll();
}
void TexturePoolOGL::Init()
{
sMonitor = new Monitor("TexturePoolOGL.sMonitor");
sTextures = new nsDeque();
}
void TexturePoolOGL::Shutdown()
{
delete sMonitor;
delete sTextures;
}
} // gl
} // mozilla
| 20.198276 | 76 | 0.672215 | wilebeast |
a4306f32eddf3ca9b17b2f479249da07a51ead8f | 5,431 | cpp | C++ | common/mptStringParse.cpp | ford442/openmpt | 614c44fe665b0e1cce15092ecf0d069cbb3e1fe7 | [
"BSD-3-Clause"
] | 335 | 2017-02-25T16:39:27.000Z | 2022-03-29T17:45:42.000Z | common/mptStringParse.cpp | ford442/openmpt | 614c44fe665b0e1cce15092ecf0d069cbb3e1fe7 | [
"BSD-3-Clause"
] | 7 | 2018-02-05T18:22:38.000Z | 2022-02-15T19:35:24.000Z | common/mptStringParse.cpp | ford442/openmpt | 614c44fe665b0e1cce15092ecf0d069cbb3e1fe7 | [
"BSD-3-Clause"
] | 69 | 2017-04-10T00:48:09.000Z | 2022-03-20T10:24:45.000Z | /*
* mptStringParse.cpp
* ------------------
* Purpose: Convert strings to other types.
* Notes : (currently none)
* Authors: OpenMPT Devs
* The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
*/
#include "stdafx.h"
#include "mptStringParse.h"
#include "mpt/parse/parse.hpp"
OPENMPT_NAMESPACE_BEGIN
template<typename T>
inline T ConvertStrToHelper(const std::string &str)
{
return mpt::ConvertStringTo<T>(str);
}
template<> inline bool ConvertStrToHelper(const std::string &str) { return ConvertStrToHelper<int>(str)?true:false; }
template<> inline signed char ConvertStrToHelper(const std::string &str) { return static_cast<signed char>(ConvertStrToHelper<signed int>(str)); }
template<> inline unsigned char ConvertStrToHelper(const std::string &str) { return static_cast<unsigned char>(ConvertStrToHelper<unsigned int>(str)); }
#if MPT_WSTRING_FORMAT
template<typename T>
inline T ConvertStrToHelper(const std::wstring &str)
{
return mpt::ConvertStringTo<T>(str);
}
template<> inline bool ConvertStrToHelper(const std::wstring &str) { return ConvertStrToHelper<int>(str)?true:false; }
template<> inline signed char ConvertStrToHelper(const std::wstring &str) { return static_cast<signed char>(ConvertStrToHelper<signed int>(str)); }
template<> inline unsigned char ConvertStrToHelper(const std::wstring &str) { return static_cast<unsigned char>(ConvertStrToHelper<unsigned int>(str)); }
#endif
bool ConvertStrToBool(const std::string &str) { return ConvertStrToHelper<bool>(str); }
signed char ConvertStrToSignedChar(const std::string &str) { return ConvertStrToHelper<signed char>(str); }
unsigned char ConvertStrToUnsignedChar(const std::string &str) { return ConvertStrToHelper<unsigned char>(str); }
signed short ConvertStrToSignedShort(const std::string &str) { return ConvertStrToHelper<signed short>(str); }
unsigned short ConvertStrToUnsignedShort(const std::string &str) { return ConvertStrToHelper<unsigned short>(str); }
signed int ConvertStrToSignedInt(const std::string &str) { return ConvertStrToHelper<signed int>(str); }
unsigned int ConvertStrToUnsignedInt(const std::string &str) { return ConvertStrToHelper<unsigned int>(str); }
signed long ConvertStrToSignedLong(const std::string &str) { return ConvertStrToHelper<signed long>(str); }
unsigned long ConvertStrToUnsignedLong(const std::string &str) { return ConvertStrToHelper<unsigned long>(str); }
signed long long ConvertStrToSignedLongLong(const std::string &str) { return ConvertStrToHelper<signed long long>(str); }
unsigned long long ConvertStrToUnsignedLongLong(const std::string &str) { return ConvertStrToHelper<unsigned long long>(str); }
float ConvertStrToFloat(const std::string &str) { return ConvertStrToHelper<float>(str); }
double ConvertStrToDouble(const std::string &str) { return ConvertStrToHelper<double>(str); }
long double ConvertStrToLongDouble(const std::string &str) { return ConvertStrToHelper<long double>(str); }
#if MPT_WSTRING_FORMAT
bool ConvertStrToBool(const std::wstring &str) { return ConvertStrToHelper<bool>(str); }
signed char ConvertStrToSignedChar(const std::wstring &str) { return ConvertStrToHelper<signed char>(str); }
unsigned char ConvertStrToUnsignedChar(const std::wstring &str) { return ConvertStrToHelper<unsigned char>(str); }
signed short ConvertStrToSignedShort(const std::wstring &str) { return ConvertStrToHelper<signed short>(str); }
unsigned short ConvertStrToUnsignedShort(const std::wstring &str) { return ConvertStrToHelper<unsigned short>(str); }
signed int ConvertStrToSignedInt(const std::wstring &str) { return ConvertStrToHelper<signed int>(str); }
unsigned int ConvertStrToUnsignedInt(const std::wstring &str) { return ConvertStrToHelper<unsigned int>(str); }
signed long ConvertStrToSignedLong(const std::wstring &str) { return ConvertStrToHelper<signed long>(str); }
unsigned long ConvertStrToUnsignedLong(const std::wstring &str) { return ConvertStrToHelper<unsigned long>(str); }
signed long long ConvertStrToSignedLongLong(const std::wstring &str) { return ConvertStrToHelper<signed long long>(str); }
unsigned long long ConvertStrToUnsignedLongLong(const std::wstring &str) { return ConvertStrToHelper<unsigned long long>(str); }
float ConvertStrToFloat(const std::wstring &str) { return ConvertStrToHelper<float>(str); }
double ConvertStrToDouble(const std::wstring &str) { return ConvertStrToHelper<double>(str); }
long double ConvertStrToLongDouble(const std::wstring &str) { return ConvertStrToHelper<long double>(str); }
#endif
namespace mpt
{
namespace String
{
namespace Parse
{
template<typename T>
T HexToHelper(const std::string &str)
{
return mpt::ConvertHexStringTo<T>(str);
}
template<> unsigned char HexToHelper(const std::string &str) { return static_cast<unsigned char>(HexToHelper<unsigned int>(str)); }
unsigned char HexToUnsignedChar(const std::string &str) { return HexToHelper<unsigned char>(str); }
unsigned short HexToUnsignedShort(const std::string &str) { return HexToHelper<unsigned short>(str); }
unsigned int HexToUnsignedInt(const std::string &str) { return HexToHelper<unsigned int>(str); }
unsigned long HexToUnsignedLong(const std::string &str) { return HexToHelper<unsigned long>(str); }
unsigned long long HexToUnsignedLongLong(const std::string &str) { return HexToHelper<unsigned long long>(str); }
} // namespace Parse
} // namespace String
} // namespace mpt
OPENMPT_NAMESPACE_END
| 54.858586 | 153 | 0.783097 | ford442 |
a431cf3bc2de93a61f30ca7162436681d69c84f8 | 416 | cpp | C++ | src/pieces/Piece.cpp | patryk-kacperski/chess-engine | d636bf3cab9f5d8b72523ce8f2be493b6666c660 | [
"MIT"
] | null | null | null | src/pieces/Piece.cpp | patryk-kacperski/chess-engine | d636bf3cab9f5d8b72523ce8f2be493b6666c660 | [
"MIT"
] | null | null | null | src/pieces/Piece.cpp | patryk-kacperski/chess-engine | d636bf3cab9f5d8b72523ce8f2be493b6666c660 | [
"MIT"
] | 1 | 2019-04-05T20:26:27.000Z | 2019-04-05T20:26:27.000Z | //
// Created by Patryk Kacperski on 09/07/2018.
//
#include "Piece.h"
namespace pkchessengine {
MoveResult Piece::validate(Move move) {
return MoveResult::kValid;
}
Piece::Piece(Side side, PieceType type)
{ }
Side Piece::getSide() {
return info.side;
}
PieceType Piece::getType() {
return info.type;
}
void Piece::promote(PieceType type) {
}
} | 15.407407 | 45 | 0.59375 | patryk-kacperski |
a433087d089b7a0cca96c38ac6ffc97ad328b5f3 | 3,932 | cc | C++ | sw/device/silicon_creator/lib/drivers/ast_unittest.cc | msfschaffner/opentitan-bak | de4cb1bb9e7b707a3ca2a6882d83af7ed2aa1ab8 | [
"Apache-2.0"
] | null | null | null | sw/device/silicon_creator/lib/drivers/ast_unittest.cc | msfschaffner/opentitan-bak | de4cb1bb9e7b707a3ca2a6882d83af7ed2aa1ab8 | [
"Apache-2.0"
] | 2 | 2021-11-01T15:02:37.000Z | 2022-01-17T14:34:36.000Z | sw/device/silicon_creator/lib/drivers/ast_unittest.cc | msfschaffner/opentitan-bak | de4cb1bb9e7b707a3ca2a6882d83af7ed2aa1ab8 | [
"Apache-2.0"
] | null | null | null | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
#include "sw/device/silicon_creator/lib/drivers/ast.h"
#include <array>
#include "gtest/gtest.h"
#include "sw/device/lib/arch/device.h"
#include "sw/device/lib/base/multibits.h"
#include "sw/device/lib/base/testing/mock_abs_mmio.h"
#include "sw/device/silicon_creator/lib/base/mock_csr.h"
#include "sw/device/silicon_creator/lib/drivers/mock_otp.h"
#include "sw/device/silicon_creator/testing/mask_rom_test.h"
#include "hw/top_earlgrey/sw/autogen/top_earlgrey.h"
#include "otp_ctrl_regs.h"
#include "sensor_ctrl_regs.h"
namespace ast_unittest {
namespace {
using ::testing::Return;
using ::testing::ValuesIn;
class AstTest : public mask_rom_test::MaskRomTest {
protected:
/**
* Sets up expectations to read the STATUS register of sensor_ctrl twice.
*
* @param done1 Value of the AST_INIT_DONE bit for the first read.
* @param done2 Value of the AST_INIT_DONE bit for the second read.
*
*/
void ExpectStatusRead(bool done1, bool done2) {
EXPECT_ABS_READ32(base_ + SENSOR_CTRL_STATUS_REG_OFFSET,
{{SENSOR_CTRL_STATUS_AST_INIT_DONE_BIT, done1}});
EXPECT_ABS_READ32(base_ + SENSOR_CTRL_STATUS_REG_OFFSET,
{{SENSOR_CTRL_STATUS_AST_INIT_DONE_BIT, done2}});
}
/**
* Sets up an expectation to read the AST_INIT_EN OTP item.
*
* @param val Value to return;
*/
void ExpectOtpRead(multi_bit_bool_t val) {
EXPECT_CALL(otp_, read32(OTP_CTRL_PARAM_CREATOR_SW_CFG_AST_INIT_EN_OFFSET))
.WillOnce(Return(val));
}
uint32_t base_ = TOP_EARLGREY_SENSOR_CTRL_BASE_ADDR;
mask_rom_test::MockAbsMmio mmio_;
mask_rom_test::MockOtp otp_;
mock_csr::MockCsr csr_;
};
TEST_F(AstTest, InitDoneTrue) {
ExpectStatusRead(true, true);
EXPECT_EQ(ast_init_done(), kHardenedBoolTrue);
}
TEST_F(AstTest, InitDoneFalse) {
ExpectStatusRead(false, false);
EXPECT_EQ(ast_init_done(), kHardenedBoolFalse);
ExpectStatusRead(true, false);
EXPECT_EQ(ast_init_done(), kHardenedBoolFalse);
ExpectStatusRead(false, true);
EXPECT_EQ(ast_init_done(), kHardenedBoolFalse);
}
class AstLcStateTest : public AstTest,
public testing::WithParamInterface<lifecycle_state_t> {};
constexpr std::array<lifecycle_state_t, 2> kLcStatesWithoutCheck{
kLcStateTest,
kLcStateRma,
};
class AstLcStatesWithoutCheckTest : public AstLcStateTest {};
TEST_P(AstLcStatesWithoutCheckTest, CheckLcSkip) {
EXPECT_EQ(ast_check(GetParam()), kErrorOk);
}
INSTANTIATE_TEST_SUITE_P(LcStatesWithoutCheck, AstLcStatesWithoutCheckTest,
ValuesIn(kLcStatesWithoutCheck));
constexpr std::array<lifecycle_state_t, 3> kLcStatesWithCheck{
kLcStateDev,
kLcStateProd,
kLcStateProdEnd,
};
class AstLcStatesWithCheckTest : public AstLcStateTest {};
TEST_P(AstLcStatesWithCheckTest, CheckOtpSkip) {
ExpectOtpRead(kMultiBitBool4False);
EXPECT_EQ(ast_check(GetParam()), kErrorOk);
}
TEST_P(AstLcStatesWithCheckTest, CheckTimeout) {
ExpectOtpRead(kMultiBitBool4True);
EXPECT_CSR_WRITE(CSR_REG_MCYCLE, 0);
EXPECT_CSR_READ(CSR_REG_MCYCLE, 100);
ExpectStatusRead(false, false);
EXPECT_CSR_READ(CSR_REG_MCYCLE, kAstCheckPollCpuCycles);
ExpectStatusRead(false, false);
EXPECT_EQ(ast_check(GetParam()), kErrorAstInitNotDone);
}
TEST_P(AstLcStatesWithCheckTest, CheckSuccess) {
ExpectOtpRead(kMultiBitBool4True);
EXPECT_CSR_WRITE(CSR_REG_MCYCLE, 0);
EXPECT_CSR_READ(CSR_REG_MCYCLE, 100);
ExpectStatusRead(false, false);
EXPECT_CSR_READ(CSR_REG_MCYCLE, kAstCheckPollCpuCycles);
ExpectStatusRead(true, true);
EXPECT_EQ(ast_check(GetParam()), kErrorOk);
}
INSTANTIATE_TEST_SUITE_P(LcStatesWithCheck, AstLcStatesWithCheckTest,
ValuesIn(kLcStatesWithCheck));
} // namespace
} // namespace ast_unittest
| 28.911765 | 80 | 0.753306 | msfschaffner |
bf9a838e65ef8b5bb31cf4d8b4342cc210a88ab3 | 914 | cc | C++ | plugins/meta-protobuf-v4/test/io.cc | TeravoxelTwoPhotonTomography/tilebase | 61f2e6b979d214afab8dd60d6f55afc3e4697e24 | [
"BSD-3-Clause"
] | null | null | null | plugins/meta-protobuf-v4/test/io.cc | TeravoxelTwoPhotonTomography/tilebase | 61f2e6b979d214afab8dd60d6f55afc3e4697e24 | [
"BSD-3-Clause"
] | null | null | null | plugins/meta-protobuf-v4/test/io.cc | TeravoxelTwoPhotonTomography/tilebase | 61f2e6b979d214afab8dd60d6f55afc3e4697e24 | [
"BSD-3-Clause"
] | null | null | null | // solves a std::tuple problem in vs2012
#define GTEST_HAS_TR1_TUPLE 0
#define GTEST_USE_OWN_TR1_TUPLE 1
#include <gtest/gtest.h>
#include "tilebase.h"
#include "plugins/meta-protobuf-v4/config.h"
struct FetchProtobufV4: public testing::Test
{
void SetUp()
{ ndioAddPluginPath(ND_ROOT_DIR"/bin/plugins");
}
};
TEST_F(FetchProtobufV4,NonExistent)
{ tiles_t tiles;
EXPECT_EQ((void*)NULL,tiles=TileBaseOpen("totally.not.here",NULL));
EXPECT_EQ(0,TileBaseCount(tiles));
TileBaseClose(tiles);
}
TEST_F(FetchProtobufV4,AutoDetect)
{ tiles_t tiles;
EXPECT_NE((void*)NULL,tiles=TileBaseOpen(PBUFV4_TEST_DATA_PATH "/02020",""));
EXPECT_EQ(1,TileBaseCount(tiles));
TileBaseClose(tiles);
}
TEST_F(FetchProtobufV4,ByName)
{ tiles_t tiles;
EXPECT_NE((void*)NULL,tiles=TileBaseOpen(PBUFV4_TEST_DATA_PATH "/02020","fetch.protobuf.v4"));
EXPECT_EQ(1,TileBaseCount(tiles));
TileBaseClose(tiles);
}
| 25.388889 | 96 | 0.756018 | TeravoxelTwoPhotonTomography |
bf9aca021d9566d860a6dbad176073dd0ae0a500 | 8,213 | hpp | C++ | __drivers/gv_renderer_d3d9/gv_render_target_mgr_d3d.hpp | dragonsn/gv_game_engine | dca6c1fb1f8d96e9a244f157a63f8a69da084b0f | [
"MIT"
] | 2 | 2018-12-03T13:17:31.000Z | 2020-04-08T07:00:02.000Z | __drivers/gv_renderer_d3d9/gv_render_target_mgr_d3d.hpp | dragonsn/gv_game_engine | dca6c1fb1f8d96e9a244f157a63f8a69da084b0f | [
"MIT"
] | null | null | null | __drivers/gv_renderer_d3d9/gv_render_target_mgr_d3d.hpp | dragonsn/gv_game_engine | dca6c1fb1f8d96e9a244f157a63f8a69da084b0f | [
"MIT"
] | null | null | null | namespace gv
{
struct gv_renderable_tex_d3d_info
{
gv_renderable_tex_d3d_info()
{
}
gv_renderable_tex_d3d_info(const gv_renderable_tex_d3d_info& info)
{
(*this) = info;
}
~gv_renderable_tex_d3d_info()
{
}
gv_renderable_tex_d3d_info&
operator=(const gv_renderable_tex_d3d_info& info)
{
texture = info.texture;
format = info.format;
clear = info.clear;
clear_color = info.clear_color;
size = info.size;
id = info.id;
return *this;
}
bool operator==(const gv_renderable_tex_d3d_info& info)
{
if (clear && info.clear)
{
return /*size==info.size && format==info.format &&*/ id == info.id;
}
return false;
}
gvt_ref_ptr< gv_texture > texture;
D3DFORMAT format;
gv_bool clear;
gv_color clear_color;
gv_vector2i size;
gv_id id;
};
class gv_render_target_mgr_d3d_imp : public gv_refable
{
public:
gv_render_target_mgr_d3d_imp()
{
m_is_locked = false;
};
~gv_render_target_mgr_d3d_imp()
{
}
void set_viewport(IDirect3DSurface9* surf)
{
D3DSURFACE_DESC desc;
surf->GetDesc(&desc);
D3DVIEWPORT9 port;
port.X = 0;
port.Y = 0;
port.Width = (DWORD)desc.Width;
port.Height = (DWORD)desc.Height;
port.MinZ = 0;
port.MaxZ = 1;
get_device_d3d9()->SetViewport(&port);
}
gv_texture* create_texture(const gv_id& id, gv_uint usage, gv_vector2i size,
gv_uint format, gv_bool clear)
{
gv_renderable_tex_d3d_info info;
info.clear = clear;
info.format = (D3DFORMAT)format;
info.size = size;
info.id = id;
gv_int idx = 0;
if (m_render_targets.find(info, idx))
{
return m_render_targets[idx].texture;
}
gv_texture_d3d* ptex = get_renderer_d3d9()
->get_sandbox()
->create_nameless_object< gv_texture_d3d >();
IDirect3DTexture9* ptex9;
GVM_VERIFY_D3D(get_device_d3d9()->CreateTexture(
size.get_x(), size.get_y(), 1, usage, (D3DFORMAT)format,
D3DPOOL_DEFAULT, &ptex9, 0));
ptex->set_texture_d3d(ptex9);
gv_texture* pt = get_renderer_d3d9()
->get_sandbox()
->create_nameless_object< gv_texture >();
pt->set_hardware_cache(ptex);
info.texture = pt;
m_render_targets.push_back(info);
GVM_DEBUG_LOG(render, "create render target: " << id << " size :" << size
<< " format " << format
<< gv_endl);
return pt;
}
gvt_array< gv_renderable_tex_d3d_info > m_render_targets;
IDirect3DSurface9* m_default_color_buffer;
IDirect3DSurface9* m_default_depth_buffer;
IDirect3DSurface9* m_current_color_buffer;
IDirect3DSurface9* m_current_depth_buffer;
gv_vector2i m_default_color_buffer_size;
gv_vector2i m_default_depth_buffer_size;
gv_bool m_is_locked;
};
//============================================================================================
// :
//============================================================================================
gv_render_target_mgr_d3d::gv_render_target_mgr_d3d()
{
m_impl = new gv_render_target_mgr_d3d_imp;
};
gv_render_target_mgr_d3d::~gv_render_target_mgr_d3d(){
};
void gv_render_target_mgr_d3d::on_init()
{
on_device_reset();
};
void gv_render_target_mgr_d3d::on_destroy(){
};
void gv_render_target_mgr_d3d::on_device_lost(){
};
void gv_render_target_mgr_d3d::on_device_reset()
{
get_device_d3d9()->GetRenderTarget(0, &m_impl->m_default_color_buffer);
get_device_d3d9()->GetDepthStencilSurface(&m_impl->m_default_depth_buffer);
m_impl->m_current_color_buffer = m_impl->m_default_color_buffer;
m_impl->m_current_depth_buffer = m_impl->m_default_depth_buffer;
D3DSURFACE_DESC desc;
m_impl->m_default_color_buffer->GetDesc(&desc);
m_impl->m_default_color_buffer_size.set(desc.Width, desc.Height);
m_impl->m_default_depth_buffer->GetDesc(&desc);
m_impl->m_default_depth_buffer_size.set(desc.Width, desc.Height);
};
gv_vector2i gv_render_target_mgr_d3d::get_default_color_buffer_size()
{
return m_impl->m_default_color_buffer_size;
};
gv_vector2i gv_render_target_mgr_d3d::get_default_depth_buffer_size()
{
return m_impl->m_default_depth_buffer_size;
};
gv_texture* gv_render_target_mgr_d3d::create_color_texture(
const gv_id& id, gv_vector2i size, gve_pixel_format format, gv_bool clear)
{
return m_impl->create_texture(id, D3DUSAGE_RENDERTARGET, size,
gv_to_d3d_format(format), clear);
};
gv_texture* gv_render_target_mgr_d3d::create_depth_texture(
const gv_id& id, gv_vector2i size, gve_pixel_format format, gv_bool clear)
{
return m_impl->create_texture(id, D3DUSAGE_DEPTHSTENCIL, size,
gv_to_d3d_format(format), clear);
};
void gv_render_target_mgr_d3d::begin_render_target(gv_texture* color_texture,
gv_texture* depth_texture,
bool clear,
gv_color clear_color)
{
if (m_impl->m_is_locked)
return;
// [9/1/2011 Administrator]
#pragma GV_REMINDER( \
"when use PIX must return in this function , ... must be PIX bug!!!")
// return;
GV_PROFILE_EVENT_PIX(set_render_target, 0)
IDirect3DSurface9* color_surface = m_impl->m_default_color_buffer;
IDirect3DSurface9* depth_surface = NULL;
m_impl->m_current_depth_buffer;
;
for (int stage = 0; stage < DX9_MAX_TEXTURE; ++stage)
{
get_device_d3d9()->SetTexture(stage, NULL);
}
if (color_texture)
color_surface =
color_texture->get_hardware_cache< gv_texture_d3d >()->get_surface_d3d();
if (depth_texture)
depth_surface =
depth_texture->get_hardware_cache< gv_texture_d3d >()->get_surface_d3d();
if (color_surface == m_impl->m_current_color_buffer &&
depth_surface == m_impl->m_current_depth_buffer)
{
return;
}
get_device_d3d9()->SetRenderTarget(0, color_surface);
if (depth_surface)
{
get_device_d3d9()->SetDepthStencilSurface(depth_surface);
}
else
{
get_device_d3d9()->SetDepthStencilSurface(NULL);
}
if (clear)
{
gv_uint clear_flag = D3DCLEAR_TARGET;
if (depth_texture)
clear_flag |= D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL;
get_device_d3d9()->Clear(0, NULL, clear_flag, clear_color.BGRA().fixed32,
1.0f, 0);
}
m_impl->set_viewport(color_surface);
m_impl->m_current_color_buffer = color_surface;
m_impl->m_current_depth_buffer = depth_surface;
};
void gv_render_target_mgr_d3d::set_default_render_target()
{
if (m_impl->m_is_locked)
return;
if (m_impl->m_current_color_buffer == m_impl->m_default_color_buffer &&
m_impl->m_current_depth_buffer == m_impl->m_default_depth_buffer)
{
return;
}
{
GV_PROFILE_EVENT_PIX(set_default_render_target, 0)
get_device_d3d9()->SetRenderTarget(0, m_impl->m_default_color_buffer);
get_device_d3d9()->SetDepthStencilSurface(m_impl->m_default_depth_buffer);
m_impl->set_viewport(m_impl->m_default_color_buffer);
m_impl->m_current_color_buffer = m_impl->m_default_color_buffer;
m_impl->m_current_depth_buffer = m_impl->m_default_depth_buffer;
}
};
void gv_render_target_mgr_d3d::end_render_target(){
};
void gv_render_target_mgr_d3d::resolve_backbuffer(gv_texture* tex)
{
IDirect3DSurface9 *pBackBuffer, *pDestBuffer;
get_device_d3d9()->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &pBackBuffer);
pDestBuffer = tex->get_hardware_cache< gv_texture_d3d >()->get_surface_d3d();
RECT rect;
D3DSURFACE_DESC desc;
pDestBuffer->GetDesc(&desc);
rect.left = rect.top = 0;
rect.right = desc.Width;
rect.bottom = desc.Height;
GVM_VERIFY_D3D(get_device_d3d9()->StretchRect(pBackBuffer, &rect, pDestBuffer,
NULL, D3DTEXF_NONE));
// pBackBuffer->Release();
// pDestBuffer->Release();
};
void gv_render_target_mgr_d3d::precache(gv_effect_renderable_texture* texture)
{
if (texture->m_texture)
return;
// if (texture->m_name =="g_color_buffer" ) return;
// if (texture->m_name =="g_depth_buffer" ) return;
// if (texture->m_name =="g_shadow_map" ) return;
gv_vector2i size = texture->m_size;
if (texture->m_use_window_size)
{
size = get_renderer_d3d9()->get_screen_size();
size.x = (int)(size.x * texture->m_width_ratio);
size.y = (int)(size.y * texture->m_height_ratio);
if (size.get_x() * size.get_y() < 1)
{
size = get_renderer_d3d9()->get_screen_size();
}
}
texture->m_texture = m_impl->create_texture(
texture->m_name, D3DUSAGE_RENDERTARGET, size, texture->m_format, true);
};
void gv_render_target_mgr_d3d::lock_render_target(gv_bool lock)
{
m_impl->m_is_locked = lock;
}
} | 28.32069 | 94 | 0.725435 | dragonsn |
bf9b4ded67484ad53149e829b54698bcfcbcfc3f | 1,122 | cpp | C++ | OIandACM/OJ/LeetCode/first/medium-406-根据身高重建队列.cpp | ASC8384/MyCodeSnippets | aa74afa85672601bd25bf625590f26ac909b2042 | [
"CC0-1.0"
] | 8 | 2019-08-09T14:28:13.000Z | 2021-02-23T03:22:15.000Z | OIandACM/OJ/LeetCode/first/medium-406-根据身高重建队列.cpp | ASC8384/MyCodeSnippets | aa74afa85672601bd25bf625590f26ac909b2042 | [
"CC0-1.0"
] | null | null | null | OIandACM/OJ/LeetCode/first/medium-406-根据身高重建队列.cpp | ASC8384/MyCodeSnippets | aa74afa85672601bd25bf625590f26ac909b2042 | [
"CC0-1.0"
] | 4 | 2019-08-16T12:00:41.000Z | 2019-11-29T12:01:17.000Z | /*
* @lc app=leetcode.cn id=406 lang=cpp
*
* [406] 根据身高重建队列
*
* https://leetcode-cn.com/problems/queue-reconstruction-by-height/description/
*
* algorithms
* Medium (64.22%)
* Likes: 290
* Dislikes: 0
* Total Accepted: 24.5K
* Total Submissions: 38.1K
* Testcase Example: '[[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]'
*
* 假设有打乱顺序的一群人站成一个队列。 每个人由一个整数对(h, k)表示,其中h是这个人的身高,k是排在这个人前面且身高大于或等于h的人数。
* 编写一个算法来重建这个队列。
*
* 注意:
* 总人数少于1100人。
*
* 示例
*
*
* 输入:
* [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
*
* 输出:
* [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
*
*
*/
// @lc code=start
class Solution {
public:
static bool cmp(vector<int> a, vector<int> b) {
if(a[0] == b[0])
return a[1] < b[1];
else
return a[0] > b[0];
}
vector<vector<int>> reconstructQueue(vector<vector<int>> &people) {
int ll = people.size();
if(ll < 2)
return people;
sort(people.begin(), people.end(), cmp);
list<vector<int>> a;
for(auto &i : people) {
auto iter = a.begin();
advance(iter, i[1]);
a.insert(iter, i);
}
return (vector<vector<int>>(a.begin(), a.end()));
}
};
// @lc code=end
| 19.344828 | 79 | 0.561497 | ASC8384 |
bf9bed6c3562413a9f578e2ce8d0efd59540ca5b | 1,132 | cpp | C++ | CHEFPRMS.cpp | Khush-Ramdev/codechef-solution | ecf57442efde8fbb03b55efdf761d7b1e0d04e80 | [
"MIT"
] | 5 | 2018-10-04T09:49:19.000Z | 2019-06-12T05:32:24.000Z | CHEFPRMS.cpp | Khush-Ramdev/codechef-solution | ecf57442efde8fbb03b55efdf761d7b1e0d04e80 | [
"MIT"
] | 5 | 2018-10-04T09:54:55.000Z | 2020-10-15T20:31:46.000Z | CHEFPRMS.cpp | Khush-Ramdev/codechef-solution | ecf57442efde8fbb03b55efdf761d7b1e0d04e80 | [
"MIT"
] | 38 | 2018-10-04T09:48:17.000Z | 2020-12-10T08:52:47.000Z | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
bool prime[202];
void isprime(ll n)
{ memset(prime,true,sizeof(prime));
prime[0]=false;
prime[1]=false;
for(ll i=2;i*i<=n;i++)
{
if(prime[i]==true)
{
for(ll p=i*2;p<=n;p+=i)
prime[p]=false;
}
}
}
bool primefactor(ll j)
{ll flag1=0,i;
for( i=1;i*i<=j;i++)
{
if((j%i==0)&&((j/i)!=i))
{
if(prime[i]&&prime[(j/i)])
{
flag1=1;
break;
}
}
}
if(flag1==1)
{
return true;
}
else
return false;
}
int main()
{ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll t;
cin>>t;
isprime(201);
while(t--)
{
ll n,j;
cin>>n;
ll flag=0;
for(j=2;j<=n/2;j++)
{
if(primefactor(j)&&primefactor(n-j))
{
flag=1;
}
}
if(flag==1)
cout<<"YES\n";
else
cout<<"NO"<<endl;
}
return 0;
}
| 14.512821 | 48 | 0.382509 | Khush-Ramdev |
bf9f980348503b6b26163a33c586bcbcd399f62e | 652 | hpp | C++ | irohad/main/iroha_status.hpp | Insafin/iroha | 5e3c3252b2a62fa887274bdf25547dc264c10c26 | [
"Apache-2.0"
] | null | null | null | irohad/main/iroha_status.hpp | Insafin/iroha | 5e3c3252b2a62fa887274bdf25547dc264c10c26 | [
"Apache-2.0"
] | null | null | null | irohad/main/iroha_status.hpp | Insafin/iroha | 5e3c3252b2a62fa887274bdf25547dc264c10c26 | [
"Apache-2.0"
] | 1 | 2022-03-11T10:28:21.000Z | 2022-03-11T10:28:21.000Z | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef IROHA_STATUS_HPP
#define IROHA_STATUS_HPP
#include <rapidjson/stringbuffer.h>
#include <cstdint>
#include <optional>
#include <string>
#include "consensus/round.hpp"
namespace iroha {
struct IrohaStatus {
std::optional<uint64_t> memory_consumption;
std::optional<consensus::Round> last_round;
std::optional<bool> is_syncing;
std::optional<bool> is_healthy;
};
struct IrohaStoredStatus {
IrohaStatus status;
rapidjson::StringBuffer serialized_status;
};
} // namespace iroha
#endif // IROHA_STATUS_HPP
| 19.757576 | 53 | 0.726994 | Insafin |
bfa04fb4013ddfe07f30f237c48d1cdd8a59cea7 | 1,508 | hpp | C++ | src/LibCraft/coreEngine/include/HP.hpp | leodlplq/IMACraft | 5fec1729238e7e428bd39543dfd1fad521e16047 | [
"MIT"
] | 1 | 2021-11-24T16:49:48.000Z | 2021-11-24T16:49:48.000Z | src/LibCraft/coreEngine/include/HP.hpp | leodlplq/IMACraft | 5fec1729238e7e428bd39543dfd1fad521e16047 | [
"MIT"
] | null | null | null | src/LibCraft/coreEngine/include/HP.hpp | leodlplq/IMACraft | 5fec1729238e7e428bd39543dfd1fad521e16047 | [
"MIT"
] | null | null | null | //
// Created by Adam on 13/12/2021.
//
#pragma once
#include <iostream>
#include "vector"
#include "LibCraft/renderEngine/include/Vertex.hpp"
#include "LibCraft/renderEngine/include/Cube.hpp"
#include "LibCraft/renderEngine/include/vbo.hpp"
#include "LibCraft/renderEngine/include/vao.hpp"
#include "LibCraft/renderEngine/include/ibo.hpp"
#include "LibCraft/renderEngine/include/Shader.hpp"
#include <glm/gtc/type_ptr.hpp>
#include "stb/stb_image.h"
#include "LibCraft/tools/include/filePath.hpp"
class HP {
public:
//CONSTRUCTORS & DESTRUCTORS;
HP();
~HP();
void drawHP(Shader& shader, int nbHp);
void genTexHP(std::string filePathHP);
inline int getVertexCountHP(){
return _vertices.size();
}
inline int getIndicesCountHP(){
return _indices.size();
}
inline GLuint* getIndicesHP() {
return &_indices[0];
}
inline Vertex* getDataPointerHP() {
return &_vertices[0];
}
private:
std::vector<Vertex> _vertices = {
Vertex(glm::vec3(-0.5, -0.5, 0.0), glm::vec3(1.0, 0.0, 0.0), glm::vec2(0.0, 0.0)),
Vertex(glm::vec3(0.5, -0.5, 0.0), glm::vec3(0.0, 1.0, 0.0), glm::vec2(1.0, 0.0)),
Vertex(glm::vec3(0.5, 0.5, 0.0), glm::vec3(0.0, 0.0, 1.0), glm::vec2(1.0, 1.0)),
Vertex(glm::vec3(-0.5, 0.5, 0.0), glm::vec3(1.0, 1.0, 1.0), glm::vec2(0.0, 1.0))
};
std::vector<GLuint> _indices = {0, 1, 2, 0, 2, 3};
vao _vao;
vbo _vbo;
ibo _ibo;
GLuint _texture;
};
| 28.45283 | 94 | 0.615385 | leodlplq |
bfa225823a119b760369311b30ffbc2824170b88 | 4,957 | cpp | C++ | GameRulesModules/GameRulesObjectiveVictoryConditionsIndividualScore.cpp | IvarJonsson/Project-Unknown | 4675b41bbb5e90135c7bf3aded2c2e262b50f351 | [
"BSL-1.0"
] | null | null | null | GameRulesModules/GameRulesObjectiveVictoryConditionsIndividualScore.cpp | IvarJonsson/Project-Unknown | 4675b41bbb5e90135c7bf3aded2c2e262b50f351 | [
"BSL-1.0"
] | null | null | null | GameRulesModules/GameRulesObjectiveVictoryConditionsIndividualScore.cpp | IvarJonsson/Project-Unknown | 4675b41bbb5e90135c7bf3aded2c2e262b50f351 | [
"BSL-1.0"
] | null | null | null | // Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved.
#include "StdAfx.h"
#include "Game.h"
#include "IGameRulesPlayerStatsModule.h"
#include "GameRulesObjectiveVictoryConditionsIndividualScore.h"
#include "GameRules.h"
#include "IGameRulesStateModule.h"
#include "IGameRulesObjectivesModule.h"
#include "GameRulesModules/IGameRulesRoundsModule.h"
#include "PersistantStats.h"
#include "UI/HUD/HUDEventWrapper.h"
#include "Audio/Announcer.h"
#include "Network/Lobby/GameLobby.h"
void CGameRulesObjectiveVictoryConditionsIndividualScore::OnEndGame(int teamId, EGameOverReason reason, ESVC_DrawResolution winningResolution, EntityId killedEntity, EntityId shooterEntity)
{
EGameOverType gameOverType = EGOT_Unknown;
if (gEnv->bServer)
{
IGameRulesRoundsModule *pRoundsModule = m_pGameRules->GetRoundsModule();
if (pRoundsModule)
{
pRoundsModule->OnEndGame(teamId, 0, reason);
if (!pRoundsModule->IsGameOver())
{
return;
}
}
EntityId localClient = gEnv->pGameFramework->GetClientActorId();
if ( shooterEntity == localClient && localClient != 0)
{
g_pGame->GetPersistantStats()->IncrementClientStats(EIPS_WinningKill);
}
if ( killedEntity == localClient && localClient != 0)
{
g_pGame->GetPersistantStats()->IncrementClientStats(EIPS_VictimOnFinalKillcam);
}
IGameRulesStateModule *pStateModule = m_pGameRules->GetStateModule();
if (pStateModule)
pStateModule->OnGameEnd();
IGameRulesPlayerStatsModule *pStatsModule = m_pGameRules->GetPlayerStatsModule();
if (pStatsModule)
{
pStatsModule->CalculateSkillRanking();
}
int team1Score = m_pGameRules->GetTeamsScore(1);
int team2Score = m_pGameRules->GetTeamsScore(2);
m_victoryParams = CGameRules::VictoryTeamParams(teamId, reason, team1Score, team2Score, winningResolution, m_drawResolutionData[ESVC_DrawResolution_level_1], m_drawResolutionData[ESVC_DrawResolution_level_2], m_winningVictim, m_winningAttacker);
m_winningVictim = 0;
m_winningAttacker = 0;
m_pGameRules->GetGameObject()->InvokeRMI(CGameRules::ClVictoryTeam(), m_victoryParams, eRMI_ToRemoteClients);
// have finished processing these winning stats now
m_winningAttacker=0;
m_winningVictim=0;
}
m_pGameRules->OnEndGame();
int highestPlayerScore = -1;
EntityId playerId = 0;
bool bDraw = true;
IGameRulesPlayerStatsModule* pPlayStatsMo = m_pGameRules->GetPlayerStatsModule();
if (pPlayStatsMo)
{
const int numStats = pPlayStatsMo->GetNumPlayerStats();
for (int i=0; i<numStats; i++)
{
const SGameRulesPlayerStat* s = pPlayStatsMo->GetNthPlayerStats(i);
if (s->flags & SGameRulesPlayerStat::PLYSTATFL_HASSPAWNEDTHISROUND)
{
if (s->points == highestPlayerScore)
{
bDraw = true;
playerId = 0;
}
else if (s->points > highestPlayerScore)
{
bDraw = false;
highestPlayerScore = s->points;
playerId = s->playerId;
}
}
}
}
if (gEnv->IsClient())
{
int clientScore = 0;
bool clientScoreIsTop = false;
const EntityId clientId = g_pGame->GetIGameFramework()->GetClientActorId();
if (pPlayStatsMo)
{
if (const SGameRulesPlayerStat* s = pPlayStatsMo->GetPlayerStats(clientId))
{
clientScore = s->points;
}
if (clientScore == highestPlayerScore)
{
clientScoreIsTop = true;
}
}
const bool localPlayerWon = (playerId == clientId);
if (!bDraw)
{
if (localPlayerWon)
{
CAudioSignalPlayer::JustPlay("MatchWon");
}
else
{
CAudioSignalPlayer::JustPlay("MatchLost");
}
}
else
{
CAudioSignalPlayer::JustPlay("MatchDraw");
}
// the server has already increased these stats in the server block above
if (!gEnv->bServer)
{
EntityId localClient = gEnv->pGameFramework->GetClientActorId();
if ( shooterEntity == localClient && localClient != 0)
{
g_pGame->GetPersistantStats()->IncrementClientStats(EIPS_WinningKill);
}
if ( killedEntity == localClient && localClient != 0)
{
g_pGame->GetPersistantStats()->IncrementClientStats(EIPS_VictimOnFinalKillcam);
}
}
if(playerId == 0) // overall the game was a Draw (at the top of the scoreboard)...
{
gameOverType = (clientScoreIsTop ? EGOT_Draw : EGOT_Lose); // ...but whether or not the local client considers the game a Draw or a Loss depends on whether they are one of the players who are drawn at the top
}
else
{
gameOverType = (localPlayerWon ? EGOT_Win : EGOT_Lose);
}
CRY_ASSERT(gameOverType != EGOT_Unknown);
EAnnouncementID announcementId = INVALID_ANNOUNCEMENT_ID;
GetGameOverAnnouncement(gameOverType, clientScore, highestPlayerScore, announcementId);
if (!m_pGameRules->GetRoundsModule())
{
// rounds will play the one shot themselves
CAudioSignalPlayer::JustPlay("RoundEndOneShot");
}
SHUDEventWrapper::OnGameEnd((int) playerId, clientScoreIsTop, reason, NULL, ESVC_DrawResolution_invalid, announcementId);
}
m_pGameRules->GameOver( gameOverType );
}
| 28.819767 | 247 | 0.731693 | IvarJonsson |
bfa837544c3033c23982fe16154f5f0dad9deb12 | 625 | cpp | C++ | Lydsy/P1588 [HNOI2002]营业额统计/data.cpp | Wycers/Codelib | 86d83787aa577b8f2d66b5410e73102411c45e46 | [
"MIT"
] | 22 | 2018-08-07T06:55:10.000Z | 2021-06-12T02:12:19.000Z | Lydsy/P1588 [HNOI2002]营业额统计/data.cpp | Wycers/Codelib | 86d83787aa577b8f2d66b5410e73102411c45e46 | [
"MIT"
] | 28 | 2020-03-04T23:47:22.000Z | 2022-02-26T18:50:00.000Z | Lydsy/P1588 [HNOI2002]营业额统计/data.cpp | Wycers/Codelib | 86d83787aa577b8f2d66b5410e73102411c45e46 | [
"MIT"
] | 4 | 2019-11-09T15:41:26.000Z | 2021-10-10T08:56:57.000Z | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#define Clr(x, t) memset(x,t,sizeof(x))
typedef long long ll;
using namespace std;
const int N = 1e5 + 10;
const int Inf = 0x3f3f3f3f;
int read()
{
int x = 0,f = 1;char ch = getchar();
while (ch < '0' || '9' < ch) {if (ch == '-') f = -1; ch = getchar();}
while ('0' <= ch && ch <= '9') x = x * 10 + ch - 48,ch = getchar();
return x * f;
}
//Struct
//Code
int n;
int main()
{
n = 32767;
printf("%d\n", n);
for (int i = 1; i <= n; ++i)
{
printf("%d\n", (rand() % 2 ? 1 : -1 ) * rand());
}
return 0;
}
| 17.857143 | 73 | 0.5232 | Wycers |
bfb4d6b6441adb106243b211ec8c6190c2ddf51e | 657 | cpp | C++ | fhq-server/src/utils/utils_static_analizing_text.cpp | MobyFS/fhq-server | aa2d8891b0c958ce74ae2a8bf2635c3683b368e0 | [
"MIT"
] | null | null | null | fhq-server/src/utils/utils_static_analizing_text.cpp | MobyFS/fhq-server | aa2d8891b0c958ce74ae2a8bf2635c3683b368e0 | [
"MIT"
] | null | null | null | fhq-server/src/utils/utils_static_analizing_text.cpp | MobyFS/fhq-server | aa2d8891b0c958ce74ae2a8bf2635c3683b368e0 | [
"MIT"
] | null | null | null | #include <utils/utils_static_analizing_text.h>
// #include <core/fallen.h>
#include <wsjcpp_core.h>
double UtilsStaticAnalizingText::calcWeightOfOneChar(int strLen) {
return 100.0/static_cast<double>(strLen);
}
std::map<char, double> UtilsStaticAnalizingText::calc(const std::string &text) {
std::map<char, double> map;
std::string str = text;
str = WsjcppCore::toLower(str);
int strLen = str.length();
double weightOfOneChar = calcWeightOfOneChar(strLen);
for (int i = 0; i < strLen; i++) {
map[str[i]] = 0.0;
}
for (int i = 0; i < strLen; i++) {
map[str[i]] += weightOfOneChar;
}
return map;
}
| 27.375 | 80 | 0.645358 | MobyFS |
bfb4e21289f3158c867588c70d0e27e5810d8e6a | 302 | cpp | C++ | src/main.cpp | MoeidHeidari/PANN | 62bd308c08185107e8803be5ab8f09ab0f7225bb | [
"Apache-2.0"
] | 2 | 2021-01-31T23:44:54.000Z | 2021-03-15T07:27:30.000Z | src/main.cpp | MoeidHeidari/PANN | 62bd308c08185107e8803be5ab8f09ab0f7225bb | [
"Apache-2.0"
] | null | null | null | src/main.cpp | MoeidHeidari/PANN | 62bd308c08185107e8803be5ab8f09ab0f7225bb | [
"Apache-2.0"
] | null | null | null |
#include <iostream>
#include <Foundation/Types/Types.hpp>
#include <Foundation/Strings/String.hpp>
using namespace PANN::TYPES;
int main(int, char**)
{
PANN_UInt8 x='B';
PANNString str;
str.print_a_string();
std::cout << "\nHello, world!"<<x<<std::endl;
return 0;
}
| 15.1 | 49 | 0.629139 | MoeidHeidari |