text
string
size
int64
token_count
int64
/* Copyright © 2017 Apple Inc. All rights reserved. * * Use of this source code is governed by a BSD-3-clause license that can * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause */ #ifndef TURI_TOOLKIT_FUNCTION_SPECIFICATION_HPP #define TURI_TOOLKIT_FUNCTION_SPECIFICATION_HPP #include <string> #include <functional> #include <model_server/lib/toolkit_function_response.hpp> #include <model_server/lib/toolkit_function_invocation.hpp> namespace turi { /** * \ingroup unity * Each toolkit is specified by filling in \ref toolkit_function_specification struct. * The contents of the struct describe user-facing documentation and default * options, as well as a callback to actual toolkit execution. */ struct toolkit_function_specification { /** * A short name used to identify this toolkit. For instance, * LDA, or PageRank. */ std::string name; /** * A list of required configurable parameters and their default values. */ variant_map_type default_options; /** * Toolkit properties. * The following keys are recognized: * - "arguments": value must a flex_list containing a list of * the argument names. * - "file": The file which the toolkit was loaded from * - "documentation": A documentation string */ std::map<std::string, flexible_type> description; /** * A pointer to the actual execution function. All parameters to the * execution are passed in the \ref toolkit_function_invocation struct. * Returns an std::pair<bool, options_map> with status results. * * \note this can be generated easily using toolkit_function_wrapper_impl::make_spec */ std::function<toolkit_function_response_type(toolkit_function_invocation&)> toolkit_execute_function; /** * A pointer to a simple version of the toolkit execution function which can be * executed natively without a toolkit_function_invocation. It will not have * some of the error management/reporting capabilities of the invocation object, * and does not have named parameters. But it is much simpler. */ std::function<variant_type(const std::vector<variant_type>& invoke)> native_execute_function; }; } // namespace turi #endif
2,240
656
/**************************** ** Contrôle de l’écran LCD ** ****************************/ #include <LiquidCrystal.h> #include "Lcd.h" #include "MorseCharacter.h" /* Initialisation de la librairie de l'écran LCD */ LiquidCrystal lcd(LCDRS, LCDENABLE, LCDD4, LCDD5, LCDD6, LCDD7); /* Fonction d'initialisation de l'écran LCD */ void initLcd(void) { lcd.begin(LCD_NUMCOLS, LCD_NUMROWS); // On définie le nombre de lignes et de colonnes de l'écran LCD lcd.print(MORSE_LINE); // On affiche le titre sur la 1ère ligne resetLcd(); // On réinitialise la 2ème ligne } /* Fonction de réinitialisation de la 2ème ligne l'écran LCD */ void resetLcd(void) { lcd.setCursor(0, 1); // On place le curseur au début de la 2ème ligne lcd.print(BLANK_LINE); // On affiche une ligne vide lcd.setCursor(0, 1); // On replace le curseur au début de la 2ème ligne } /* Fonction d'affichage d'un caractère sur l'écran LCD */ void displayCharacterOnLcd(char character) { static unsigned int cursorIndex = 0; // Postion horizontale if (character != UNDEFINED_CHAR) // Si le caractère n'est pas non trouvé { lcd.print(character); // On affiche le caractère ++cursorIndex; // On incrémente la position horizontale } if (cursorIndex == LCD_NUMCOLS) // Si la position horizontale est égale au nombre de colonne { resetLcd(); // On réinitialise la deuxième ligne cursorIndex = 0; // On réinitialise la position } }
1,431
526
//============================================================================ // // SSSS tt lll lll // SS SS tt ll ll // SS tttttt eeee ll ll aaaa // SSSS tt ee ee ll ll aa // SS tt eeeeee ll ll aaaaa -- "An Atari 2600 VCS Emulator" // SS SS tt ee ll ll aa aa // SSSS ttt eeeee llll llll aaaaa // // Copyright (c) 1995-2007 by Bradford W. Mott // // See the file "license" for information on usage and redistribution of // this file, and for a DISCLAIMER OF ALL WARRANTIES. // // $Id: TIASnd.cxx,v 1.6 2007/01/01 18:04:50 stephena Exp $ //============================================================================ #include "System.hxx" #include "TIASnd.hxx" // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TIASound::TIASound(Int32 outputFrequency, Int32 tiaFrequency, uInt32 channels) : myOutputFrequency(outputFrequency), myTIAFrequency(tiaFrequency), myChannels(channels), myOutputCounter(0), myVolumePercentage(100), myVolumeClip(128) { reset(); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TIASound::~TIASound() { } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void TIASound::reset() { myAUDC[0] = myAUDC[1] = myAUDF[0] = myAUDF[1] = myAUDV[0] = myAUDV[1] = 0; myP4[0] = myP5[0] = myP4[1] = myP5[1] = 1; myFreqDiv[0].set(0); myFreqDiv[1].set(0); myOutputCounter = 0; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void TIASound::outputFrequency(Int32 freq) { myOutputFrequency = freq; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void TIASound::tiaFrequency(Int32 freq) { myTIAFrequency = freq; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void TIASound::channels(uInt32 number) { myChannels = number == 2 ? 2 : 1; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void TIASound::clipVolume(bool clip) { myVolumeClip = clip ? 128 : 0; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void TIASound::set(uInt16 address, uInt8 value) { switch(address) { case 0x15: // AUDC0 myAUDC[0] = value & 0x0f; break; case 0x16: // AUDC1 myAUDC[1] = value & 0x0f; break; case 0x17: // AUDF0 myAUDF[0] = value & 0x1f; myFreqDiv[0].set(myAUDF[0]); break; case 0x18: // AUDF1 myAUDF[1] = value & 0x1f; myFreqDiv[1].set(myAUDF[1]); break; case 0x19: // AUDV0 myAUDV[0] = value & 0x0f; break; case 0x1a: // AUDV1 myAUDV[1] = value & 0x0f; break; default: break; } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - uInt8 TIASound::get(uInt16 address) { switch(address) { case 0x15: // AUDC0 return myAUDC[0]; case 0x16: // AUDC1 return myAUDC[1]; case 0x17: // AUDF0 return myAUDF[0]; case 0x18: // AUDF1 return myAUDF[1]; case 0x19: // AUDV0 return myAUDV[0]; case 0x1a: // AUDV1 return myAUDV[1]; default: return 0; } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void TIASound::volume(uInt32 percent) { if((percent >= 0) && (percent <= 100)) myVolumePercentage = percent; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void TIASound::process(uInt8* buffer, uInt32 samples) { Int32 v0 = ((myAUDV[0] << 2) * myVolumePercentage) / 100; Int32 v1 = ((myAUDV[1] << 2) * myVolumePercentage) / 100; // Loop until the sample buffer is full while(samples > 0) { // Process both sound channels for(uInt32 c = 0; c < 2; ++c) { // Update P4 & P5 registers for channel if freq divider outputs a pulse if((myFreqDiv[c].clock())) { switch(myAUDC[c]) { case 0x00: // Set to 1 { // Shift a 1 into the 4-bit register each clock myP4[c] = (myP4[c] << 1) | 0x01; break; } case 0x01: // 4 bit poly { // Clock P4 as a standard 4-bit LSFR taps at bits 3 & 2 myP4[c] = (myP4[c] & 0x0f) ? ((myP4[c] << 1) | (((myP4[c] & 0x08) ? 1 : 0) ^ ((myP4[c] & 0x04) ? 1 : 0))) : 1; break; } case 0x02: // div 31 -> 4 bit poly { // Clock P5 as a standard 5-bit LSFR taps at bits 4 & 2 myP5[c] = (myP5[c] & 0x1f) ? ((myP5[c] << 1) | (((myP5[c] & 0x10) ? 1 : 0) ^ ((myP5[c] & 0x04) ? 1 : 0))) : 1; // This does the divide-by 31 with length 13:18 if((myP5[c] & 0x0f) == 0x08) { // Clock P4 as a standard 4-bit LSFR taps at bits 3 & 2 myP4[c] = (myP4[c] & 0x0f) ? ((myP4[c] << 1) | (((myP4[c] & 0x08) ? 1 : 0) ^ ((myP4[c] & 0x04) ? 1 : 0))) : 1; } break; } case 0x03: // 5 bit poly -> 4 bit poly { // Clock P5 as a standard 5-bit LSFR taps at bits 4 & 2 myP5[c] = (myP5[c] & 0x1f) ? ((myP5[c] << 1) | (((myP5[c] & 0x10) ? 1 : 0) ^ ((myP5[c] & 0x04) ? 1 : 0))) : 1; // P5 clocks the 4 bit poly if(myP5[c] & 0x10) { // Clock P4 as a standard 4-bit LSFR taps at bits 3 & 2 myP4[c] = (myP4[c] & 0x0f) ? ((myP4[c] << 1) | (((myP4[c] & 0x08) ? 1 : 0) ^ ((myP4[c] & 0x04) ? 1 : 0))) : 1; } break; } case 0x04: // div 2 { // Clock P4 toggling the lower bit (divide by 2) myP4[c] = (myP4[c] << 1) | ((myP4[c] & 0x01) ? 0 : 1); break; } case 0x05: // div 2 { // Clock P4 toggling the lower bit (divide by 2) myP4[c] = (myP4[c] << 1) | ((myP4[c] & 0x01) ? 0 : 1); break; } case 0x06: // div 31 -> div 2 { // Clock P5 as a standard 5-bit LSFR taps at bits 4 & 2 myP5[c] = (myP5[c] & 0x1f) ? ((myP5[c] << 1) | (((myP5[c] & 0x10) ? 1 : 0) ^ ((myP5[c] & 0x04) ? 1 : 0))) : 1; // This does the divide-by 31 with length 13:18 if((myP5[c] & 0x0f) == 0x08) { // Clock P4 toggling the lower bit (divide by 2) myP4[c] = (myP4[c] << 1) | ((myP4[c] & 0x01) ? 0 : 1); } break; } case 0x07: // 5 bit poly -> div 2 { // Clock P5 as a standard 5-bit LSFR taps at bits 4 & 2 myP5[c] = (myP5[c] & 0x1f) ? ((myP5[c] << 1) | (((myP5[c] & 0x10) ? 1 : 0) ^ ((myP5[c] & 0x04) ? 1 : 0))) : 1; // P5 clocks the 4 bit register if(myP5[c] & 0x10) { // Clock P4 toggling the lower bit (divide by 2) myP4[c] = (myP4[c] << 1) | ((myP4[c] & 0x01) ? 0 : 1); } break; } case 0x08: // 9 bit poly { // Clock P5 & P4 as a standard 9-bit LSFR taps at 8 & 4 myP5[c] = ((myP5[c] & 0x1f) || (myP4[c] & 0x0f)) ? ((myP5[c] << 1) | (((myP4[c] & 0x08) ? 1 : 0) ^ ((myP5[c] & 0x10) ? 1 : 0))) : 1; myP4[c] = (myP4[c] << 1) | ((myP5[c] & 0x20) ? 1 : 0); break; } case 0x09: // 5 bit poly { // Clock P5 as a standard 5-bit LSFR taps at bits 4 & 2 myP5[c] = (myP5[c] & 0x1f) ? ((myP5[c] << 1) | (((myP5[c] & 0x10) ? 1 : 0) ^ ((myP5[c] & 0x04) ? 1 : 0))) : 1; // Clock value out of P5 into P4 with no modification myP4[c] = (myP4[c] << 1) | ((myP5[c] & 0x20) ? 1 : 0); break; } case 0x0a: // div 31 { // Clock P5 as a standard 5-bit LSFR taps at bits 4 & 2 myP5[c] = (myP5[c] & 0x1f) ? ((myP5[c] << 1) | (((myP5[c] & 0x10) ? 1 : 0) ^ ((myP5[c] & 0x04) ? 1 : 0))) : 1; // This does the divide-by 31 with length 13:18 if((myP5[c] & 0x0f) == 0x08) { // Feed bit 4 of P5 into P4 (this will toggle back and forth) myP4[c] = (myP4[c] << 1) | ((myP5[c] & 0x10) ? 1 : 0); } break; } case 0x0b: // Set last 4 bits to 1 { // A 1 is shifted into the 4-bit register each clock myP4[c] = (myP4[c] << 1) | 0x01; break; } case 0x0c: // div 6 { // Use 4-bit register to generate sequence 000111000111 myP4[c] = (~myP4[c] << 1) | ((!(!(myP4[c] & 4) && ((myP4[c] & 7)))) ? 0 : 1); break; } case 0x0d: // div 6 { // Use 4-bit register to generate sequence 000111000111 myP4[c] = (~myP4[c] << 1) | ((!(!(myP4[c] & 4) && ((myP4[c] & 7)))) ? 0 : 1); break; } case 0x0e: // div 31 -> div 6 { // Clock P5 as a standard 5-bit LSFR taps at bits 4 & 2 myP5[c] = (myP5[c] & 0x1f) ? ((myP5[c] << 1) | (((myP5[c] & 0x10) ? 1 : 0) ^ ((myP5[c] & 0x04) ? 1 : 0))) : 1; // This does the divide-by 31 with length 13:18 if((myP5[c] & 0x0f) == 0x08) { // Use 4-bit register to generate sequence 000111000111 myP4[c] = (~myP4[c] << 1) | ((!(!(myP4[c] & 4) && ((myP4[c] & 7)))) ? 0 : 1); } break; } case 0x0f: // poly 5 -> div 6 { // Clock P5 as a standard 5-bit LSFR taps at bits 4 & 2 myP5[c] = (myP5[c] & 0x1f) ? ((myP5[c] << 1) | (((myP5[c] & 0x10) ? 1 : 0) ^ ((myP5[c] & 0x04) ? 1 : 0))) : 1; // Use poly 5 to clock 4-bit div register if(myP5[c] & 0x10) { // Use 4-bit register to generate sequence 000111000111 myP4[c] = (~myP4[c] << 1) | ((!(!(myP4[c] & 4) && ((myP4[c] & 7)))) ? 0 : 1); } break; } } } } myOutputCounter += myOutputFrequency; if(myChannels == 1) { // Handle mono sample generation while((samples > 0) && (myOutputCounter >= myTIAFrequency)) { *(buffer++) = (((myP4[0] & 8) ? v0 : 0) + ((myP4[1] & 8) ? v1 : 0)) + myVolumeClip; myOutputCounter -= myTIAFrequency; samples--; } } else { // Handle stereo sample generation while((samples > 0) && (myOutputCounter >= myTIAFrequency)) { *(buffer++) = ((myP4[0] & 8) ? v0 : 0) + myVolumeClip; *(buffer++) = ((myP4[1] & 8) ? v1 : 0) + myVolumeClip; myOutputCounter -= myTIAFrequency; samples--; } } } }
11,463
5,122
// This file is part of the dune-xt-functions project: // https://github.com/dune-community/dune-xt-functions // Copyright 2009-2018 dune-xt-functions developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2018) // TiKeil (2018) // Tobias Leibner (2018) // // reserved. // (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_XT_FUNCTIONS_BASE_COMBINED_FUNCTIONS_HH #define DUNE_XT_FUNCTIONS_BASE_COMBINED_FUNCTIONS_HH #include <dune/xt/functions/base/combined-grid-functions.hh> #include <dune/xt/functions/interfaces/function.hh> namespace Dune { namespace XT { namespace Functions { namespace internal { /** * \brief Helper class defining types of combined functions, if available. * * \note Most likely you do not want to use this class directly, but Combined. */ template <class LeftType, class RightType, Combination comb> class SelectCombined { public: using D = typename LeftType::DomainFieldType; static const size_t d = LeftType::domain_dim; using R = typename LeftType::RangeFieldType; private: static_assert(std::is_same<typename RightType::DomainFieldType, D>::value, "Types do not match!"); static_assert(RightType::domain_dim == d, "Dimensions do not match!"); static_assert(std::is_same<typename RightType::RangeFieldType, R>::value, "Types do not match!"); template <class L, class R> class Choose { template <size_t rL, size_t rR, size_t rCL, size_t rcR, Combination cc, bool anything = true> class Dimension { static_assert(!anything, "No combination for these dimensions available!"); }; template <size_t r_in, size_t rC_in, bool anything> class Dimension<r_in, r_in, rC_in, rC_in, Combination::difference, anything> { public: static const size_t r = r_in; static const size_t rC = rC_in; }; template <size_t r_in, size_t rC_in, bool anything> class Dimension<r_in, r_in, rC_in, rC_in, Combination::sum, anything> { public: static const size_t r = r_in; static const size_t rC = rC_in; }; template <size_t r_in, size_t rC_in, bool anything> class Dimension<1, r_in, 1, rC_in, Combination::product, anything> { public: static const size_t r = r_in; static const size_t rC = rC_in; }; public: static const size_t r = Dimension<L::range_dim, R::range_dim, L::range_dim_cols, R::range_dim_cols, comb>::r; static const size_t rC = Dimension<L::range_dim, R::range_dim, L::range_dim_cols, R::range_dim_cols, comb>::rC; }; // class Choose public: static const size_t r = Choose<LeftType, RightType>::r; static const size_t rC = Choose<LeftType, RightType>::rC; using DomainType = typename FunctionInterface<d, r, rC, R>::DomainType; using RangeReturnType = typename RightType::RangeReturnType; using ScalarRangeReturnType = typename LeftType::RangeReturnType; using DerivativeRangeReturnType = typename FunctionInterface<d, r, rC, R>::DerivativeRangeReturnType; private: template <Combination cc, bool anything = true> class Call { static_assert(!anything, "Nothing available for these combinations!"); }; // class Call template <bool anything> class Call<Combination::difference, anything> { public: static std::string type() { return "difference"; } static size_t order(const size_t left_order, const size_t right_order) { return std::max(left_order, right_order); } static RangeReturnType evaluate(const LeftType& left_, const RightType& right_, const DomainType& point_in_global_coordinates, const Common::Parameter& param) { return left_.evaluate(point_in_global_coordinates, param) - right_.evaluate(point_in_global_coordinates, param); } static DerivativeRangeReturnType jacobian(const LeftType& left_, const RightType& right_, const DomainType& point_in_global_coordinates, const Common::Parameter& param) { return left_.jacobian(point_in_global_coordinates, param) - right_.jacobian(point_in_global_coordinates, param); } // ... jacobian(...) }; // class Call< ..., difference > template <bool anything> class Call<Combination::sum, anything> { public: static std::string type() { return "sum"; } static size_t order(const size_t left_order, const size_t right_order) { return std::max(left_order, right_order); } static RangeReturnType evaluate(const LeftType& left_, const RightType& right_, const DomainType& point_in_global_coordinates, const Common::Parameter& param) { return left_.evaluate(point_in_global_coordinates, param) + right_.evaluate(point_in_global_coordinates, param); } // ... evaluate(...) static DerivativeRangeReturnType jacobian(const LeftType& left_, const RightType& right_, const DomainType& point_in_global_coordinates, const Common::Parameter& param) { return left_.jacobian(point_in_global_coordinates, param) + right_.jacobian(point_in_global_coordinates, param); } // ... jacobian(...) }; // class Call< ..., sum > // left only scalar atm template <bool anything> class Call<Combination::product, anything> { public: static std::string type() { return "product"; } static size_t order(const size_t left_order, const size_t right_order) { return left_order + right_order; } static RangeReturnType evaluate(const LeftType& left_, const RightType& right_, const DomainType& point_in_global_coordinates, const Common::Parameter& param) { ScalarRangeReturnType left_eval = left_.evaluate(point_in_global_coordinates, param); RangeReturnType right_eval = right_.evaluate(point_in_global_coordinates, param); if (left_eval.size() != 1) DUNE_THROW(NotImplemented, "Only available for scalar left type!"); right_eval *= left_eval[0]; return right_eval; } // ... evaluate(...) static DerivativeRangeReturnType jacobian(const LeftType& /*left_*/, const RightType& /*right_*/, const DomainType& /*point_in_global_coordinates*/, const Common::Parameter& /*param*/) { DUNE_THROW(NotImplemented, "If you need this, implement it!"); return DerivativeRangeReturnType(); } }; // class Call< ..., product > public: static std::string type() { return Call<comb>::type(); } static size_t order(const size_t left_order, const size_t right_order) { return Call<comb>::order(left_order, right_order); } static RangeReturnType evaluate(const LeftType& left_, const RightType& right_, const DomainType& point_in_global_coordinates, const Common::Parameter& param) { return Call<comb>::evaluate(left_, right_, point_in_global_coordinates, param); } static DerivativeRangeReturnType jacobian(const LeftType& left_, const RightType& right_, const DomainType& point_in_global_coordinates, const Common::Parameter& param) { return Call<comb>::jacobian(left_, right_, point_in_global_coordinates, param); } }; // class SelectCombined /** * \brief Generic combined function. * * This class combines two given functions of type LeftType and RightType using the given combination * Combination. This class (and any derived class, like Difference, Sum or Product) can be used in two ways: * - You can pass references of the left and right operand to this class. This is done for instance when calling * operator+, operator- or operator* on any function deriving from FunctionInterface: \code using ConstantType = Functions::ConstantFunction< ..., double>; ConstantType one( ... ); ConstantType two( ... ); // the following code auto difference = one - two; // is equivalent to Difference< ConstantType, ConstantType > difference(one, two); // and internal::Combined< ConstantType, ConstantType, Combination::difference > difference(one, tow); \endcode * In this situation you are responsible to ensure that the arguments given are valid throughout the lifetime * of this class. The following will lead to a segfault: \code using ConstantType = Functions::ConstantFunction< ..., double >; Difference< ConstantType, ConstantType > stupid_difference() { ConstantType one( ... ); ConstantType two( ... ); return one - two; } \endcode * - You can pass shared_ptr of the left and right operands to this class. In this case the following is valid: \code using ConstantType = Functions::ConstantFunction< ..., double >; Difference< ConstantType, ConstantType > stupid_difference() { auto one = std::make_shared< ConstantType >(1); auto two = std::make_shared< ConstantType >(2); return Difference< ConstantType, ConstantType >(one, two) } \endcode * * \note Most likely you do not want to use this class diretly, but one of Difference, Sum or Product. */ template <class LeftType, class RightType, Combination comb> class CombinedFunction : public FunctionInterface<LeftType::domain_dim, SelectCombined<LeftType, RightType, comb>::r, SelectCombined<LeftType, RightType, comb>::rC, typename SelectCombined<LeftType, RightType, comb>::R> { using BaseType = FunctionInterface<LeftType::domain_dim, SelectCombined<LeftType, RightType, comb>::r, SelectCombined<LeftType, RightType, comb>::rC, typename SelectCombined<LeftType, RightType, comb>::R>; using ThisType = CombinedFunction<LeftType, RightType, comb>; using Select = SelectCombined<LeftType, RightType, comb>; using LeftStorageType = Common::ConstStorageProvider<LeftType>; using RightStorageType = Common::ConstStorageProvider<RightType>; public: CombinedFunction(const LeftType& left, const RightType& right, const std::string nm = "") : left_(Common::make_unique<LeftStorageType>(left)) , right_(Common::make_unique<RightStorageType>(right)) , name_(nm.empty() ? SelectCombined<LeftType, RightType, comb>::type() + " of '" + left.name() + "' and '" + right.name() + "'" : nm) {} CombinedFunction(const std::shared_ptr<const LeftType> left, const std::shared_ptr<const RightType> right, const std::string nm = "") : left_(Common::make_unique<LeftStorageType>(left)) , right_(Common::make_unique<RightStorageType>(right)) , name_(nm.empty() ? SelectCombined<LeftType, RightType, comb>::type() + " of '" + left_->access().name() + "' and '" + right_->access().name() + "'" : nm) {} CombinedFunction(ThisType&& source) = default; CombinedFunction(const ThisType& other) = delete; ThisType& operator=(const ThisType& other) = delete; ThisType& operator=(ThisType&& other) = delete; std::string name() const override final { return name_; } using typename BaseType::DerivativeRangeReturnType; using typename BaseType::DomainType; using typename BaseType::RangeReturnType; int order(const XT::Common::Parameter& param = {}) const override final { auto ret = Select::order(left_->access().order(param), right_->access().order(param)); assert(ret < std::numeric_limits<int>::max()); return static_cast<int>(ret); } RangeReturnType evaluate(const DomainType& point_in_global_coordinates, const Common::Parameter& param = {}) const override final { return Select::evaluate(left_->access(), right_->access(), point_in_global_coordinates, param); } DerivativeRangeReturnType jacobian(const DomainType& point_in_global_coordinates, const Common::Parameter& param = {}) const override final { return Select::jacobian(left_->access(), right_->access(), point_in_global_coordinates, param); } private: std::unique_ptr<const LeftStorageType> left_; std::unique_ptr<const RightStorageType> right_; const std::string name_; }; // class Combined } // namespace internal /** * \brief Function representing the difference between two functions. * * \see internal::Combined */ template <class MinuendType, class SubtrahendType> class DifferenceFunction : public internal::CombinedFunction<MinuendType, SubtrahendType, internal::Combination::difference> { using BaseType = internal::CombinedFunction<MinuendType, SubtrahendType, internal::Combination::difference>; public: template <class... Args> explicit DifferenceFunction(Args&&... args) : BaseType(std::forward<Args>(args)...) {} }; // class DifferenceFunction /** * \brief Function representing the sum of two functions. * * \see internal::Combined */ template <class LeftSummandType, class RightSummandType> class SumFunction : public internal::CombinedFunction<LeftSummandType, RightSummandType, internal::Combination::sum> { using BaseType = internal::CombinedFunction<LeftSummandType, RightSummandType, internal::Combination::sum>; public: template <class... Args> explicit SumFunction(Args&&... args) : BaseType(std::forward<Args>(args)...) {} }; // class SumFunction /** * \brief Function representing the product of two functions. * * \see internal::Combined */ template <class LeftSummandType, class RightSummandType> class ProductFunction : public internal::CombinedFunction<LeftSummandType, RightSummandType, internal::Combination::product> { using BaseType = internal::CombinedFunction<LeftSummandType, RightSummandType, internal::Combination::product>; public: template <class... Args> explicit ProductFunction(Args&&... args) : BaseType(std::forward<Args>(args)...) {} }; // class ProductFunction template <class T1, class T2, class... Args> std::shared_ptr<DifferenceFunction<T1, T2>> make_difference(const T1& left, const T2& right, Args&&... args) { return std::make_shared<DifferenceFunction<T1, T2>>(left, right, std::forward<Args>(args)...); } template <class T1, class T2, class... Args> std::shared_ptr<DifferenceFunction<T1, T2>> make_difference(std::shared_ptr<T1> left, std::shared_ptr<T2> right, Args&&... args) { return std::make_shared<DifferenceFunction<T1, T2>>(left, right, std::forward<Args>(args)...); } template <class T1, class T2, class... Args> std::shared_ptr<SumFunction<T1, T2>> make_sum(const T1& left, const T2& right, Args&&... args) { return std::make_shared<SumFunction<T1, T2>>(left, right, std::forward<Args>(args)...); } template <class T1, class T2, class... Args> std::shared_ptr<SumFunction<T1, T2>> make_sum(std::shared_ptr<T1> left, std::shared_ptr<T2> right, Args&&... args) { return std::make_shared<SumFunction<T1, T2>>(left, right, std::forward<Args>(args)...); } template <class T1, class T2, class... Args> std::shared_ptr<ProductFunction<T1, T2>> make_product(const T1& left, const T2& right, Args&&... args) { return std::make_shared<ProductFunction<T1, T2>>(left, right, std::forward<Args>(args)...); } template <class T1, class T2, class... Args> std::shared_ptr<ProductFunction<T1, T2>> make_product(std::shared_ptr<T1> left, std::shared_ptr<T2> right, Args&&... args) { return std::make_shared<ProductFunction<T1, T2>>(left, right, std::forward<Args>(args)...); } } // namespace Functions } // namespace XT } // namespace Dune #endif // DUNE_XT_FUNCTIONS_BASE_COMBINED_HH
16,624
5,011
//--------------------------------------------------------------------------- // E L E N A P r o j e c t: Win32 ELENA System Routines // // (C)2018-2020, by Alexei Rakov //--------------------------------------------------------------------------- #include "elena.h" // -------------------------------------------------------------------------- #include "elenamachine.h" #include <windows.h> using namespace _ELENA_; void SystemRoutineProvider :: InitCriticalStruct(CriticalStruct* header, pos_t criticalHandler) { pos_t previousHeader = 0; // ; set SEH handler / frame / stack pointers __asm { mov eax, header mov ecx, fs: [0] mov previousHeader, ecx mov fs : [0] , eax } header->previousStruct = previousHeader; header->handler = criticalHandler; } TLSEntry* SystemRoutineProvider :: GetTLSEntry(pos_t tlsIndex) { TLSEntry* entry = nullptr; // ; GCXT: assign tls entry __asm { mov ebx, tlsIndex mov ecx, fs: [2Ch] mov edx, [ecx + ebx * 4] mov entry, edx } return entry; } void SystemRoutineProvider :: InitTLSEntry(pos_t threadIndex, pos_t tlsIndex, ProgramHeader* frameHeader, pos_t* threadTable) { TLSEntry* entry = GetTLSEntry(tlsIndex); entry->tls_flags = 0; entry->tls_sync_event = ::CreateEvent(0, -1, 0, 0); entry->tls_et_current = &frameHeader->root_exception_struct; entry->tls_threadindex = threadIndex; threadTable[threadIndex] = (pos_t)entry; } pos_t SystemRoutineProvider :: NewHeap(int totalSize, int committedSize) { // reserve void* allocPtr = VirtualAlloc(nullptr, totalSize, MEM_RESERVE, PAGE_READWRITE); // allocate VirtualAlloc(allocPtr, committedSize, MEM_COMMIT, PAGE_READWRITE); return (pos_t)allocPtr; } void SystemRoutineProvider :: Exit(pos_t exitCode) { ::ExitProcess(exitCode); } void SystemRoutineProvider :: CloseThreadHandle(TLSEntry* entry, bool withExit, pos_t exitCode) { ::CloseHandle(entry->tls_sync_event); if (withExit) ::ExitThread(exitCode); }
2,088
706
// MIT Licensed (see LICENSE.md). #include "Precompiled.hpp" namespace Plasma { // Sound Attenuator LightningDefineType(SoundAttenuatorDisplay, builder, type) { } String SoundAttenuatorDisplay::GetName(HandleParam object) { SoundAttenuator* soundAtten = object.Get<SoundAttenuator*>(GetOptions::AssertOnNull); return BuildString("SoundAttenuator: ", soundAtten->Name); } String SoundAttenuatorDisplay::GetDebugText(HandleParam object) { return GetName(object); } String SoundAttenuationToString(const BoundType* meta, const byte* data) { SoundAttenuator* soundAtten = (SoundAttenuator*)data; return BuildString("SoundAttenuator: ", soundAtten->Name); } LightningDefineType(SoundAttenuator, builder, type) { PlasmaBindDocumented(); type->ToStringFunction = SoundAttenuationToString; LightningBindGetterSetterProperty(StartDistance); LightningBindGetterSetterProperty(StopDistance); LightningBindGetterSetterProperty(MinAttenuatedVolume)->Add(new EditorSlider(0.0f, 1.0f, 0.01f)); LightningBindGetterSetterProperty(UseLowPassFilter)->AddAttribute(PropertyAttributes::cInvalidatesObject); LightningBindGetterSetterProperty(LowPassStartDistance)->PlasmaFilterBool(mUseLowPassFilter); LightningBindGetterSetterProperty(LowPassCutoffFreq)->PlasmaFilterBool(mUseLowPassFilter); LightningBindGetterSetterProperty(FalloffCurveType)->AddAttribute(PropertyAttributes::cInvalidatesObject); LightningBindGetterSetterProperty(FalloffCurve) ->PlasmaFilterEquality(mFalloffCurveType, FalloffCurveType::Enum, FalloffCurveType::Custom); } SoundAttenuator::SoundAttenuator() : mStartDistance(1.0f), mStopDistance(70.0f), mMinAttenuatedVolume(0.0f), mFalloffCurveType(FalloffCurveType::Log), mCustomFalloffCurve(nullptr), mUseLowPassFilter(true), mLowPassStartDistance(20.0f), mLowPassCutoffFreq(1000.0f) { mResourceIconName = cAudioIcon; } SoundAttenuator::~SoundAttenuator() { // Delete any existing SoundAttenuatorNode objects for (AttenuatorListType::range nodes = mNodeList.All(); !nodes.Empty();) { SoundAttenuatorNode* node = &nodes.Front(); nodes.PopFront(); delete node; } } void SoundAttenuator::Serialize(Serializer& stream) { SerializeNameDefault(mStartDistance, 1.0f); SerializeNameDefault(mStopDistance, 70.0f); SerializeNameDefault(mMinAttenuatedVolume, 0.0f); SerializeNameDefault(mUseLowPassFilter, true); SerializeNameDefault(mLowPassStartDistance, 20.0f); SerializeNameDefault(mLowPassCutoffFreq, 1000.0f); SerializeNullableResourceNameDefault(mCustomFalloffCurve, CurveManager, nullptr); SerializeEnumNameDefault(FalloffCurveType, mFalloffCurveType, FalloffCurveType::Log); } void SoundAttenuator::Initialize() { if (mFalloffCurveType == FalloffCurveType::Custom && mCustomFalloffCurve) { UpdateCurve(nullptr); SampleCurve* curve = mCustomFalloffCurve; if (curve) ConnectThisTo(curve, Events::ObjectModified, UpdateCurve); } } void SoundAttenuator::Unload() { mCustomFalloffCurve = nullptr; } float SoundAttenuator::GetStartDistance() { return mStartDistance; } void SoundAttenuator::SetStartDistance(float value) { mStartDistance = Math::Clamp(value, 0.0f, mStopDistance); // Update the attenuation information on all existing nodes for (AttenuatorListType::range nodes = mNodeList.All(); !nodes.Empty(); nodes.PopFront()) nodes.Front().mNode->SetStartDistance(mStartDistance); } float SoundAttenuator::GetStopDistance() { return mStopDistance; } void SoundAttenuator::SetStopDistance(float value) { mStopDistance = Math::Max(value, mStartDistance); // Update the attenuation information on all existing nodes for (AttenuatorListType::range nodes = mNodeList.All(); !nodes.Empty(); nodes.PopFront()) nodes.Front().mNode->SetEndDistance(mStopDistance); } float SoundAttenuator::GetMinAttenuatedVolume() { return mMinAttenuatedVolume; } void SoundAttenuator::SetMinAttenuatedVolume(float value) { mMinAttenuatedVolume = Math::Clamp(value, 0.0f, AudioConstants::cMaxVolumeValue); // Update the attenuation information on all existing nodes for (AttenuatorListType::range nodes = mNodeList.All(); !nodes.Empty(); nodes.PopFront()) nodes.Front().mNode->SetMinimumVolume(mMinAttenuatedVolume); } SampleCurve* SoundAttenuator::GetFalloffCurve() { return mCustomFalloffCurve; } void SoundAttenuator::SetFalloffCurve(SampleCurve* newCurve) { SampleCurve* curve = mCustomFalloffCurve; if (curve) curve->GetDispatcher()->DisconnectEvent(Events::ObjectModified, this); mCustomFalloffCurve = newCurve; UpdateCurve(nullptr); curve = mCustomFalloffCurve; if (curve) { ConnectThisTo(curve, Events::ObjectModified, UpdateCurve); Array<Vec3> curveData; curve->GetCurve(curveData); // Send the custom curve data to all existing nodes for (AttenuatorListType::range nodes = mNodeList.All(); !nodes.Empty(); nodes.PopFront()) nodes.Front().mNode->SetCurveType(FalloffCurveType::Custom, &curveData); } else { // Set the custom curve data to null on all existing nodes for (AttenuatorListType::range nodes = mNodeList.All(); !nodes.Empty(); nodes.PopFront()) nodes.Front().mNode->SetCurveType(FalloffCurveType::Custom, nullptr); } } FalloffCurveType::Enum SoundAttenuator::GetFalloffCurveType() { return mFalloffCurveType; } void SoundAttenuator::SetFalloffCurveType(FalloffCurveType::Enum newtype) { mFalloffCurveType = newtype; if (newtype != FalloffCurveType::Custom) { // Set the curve type on all existing nodes for (AttenuatorListType::range nodes = mNodeList.All(); !nodes.Empty(); nodes.PopFront()) nodes.Front().mNode->SetCurveType(newtype, nullptr); } } bool SoundAttenuator::GetUseLowPassFilter() { return mUseLowPassFilter; } void SoundAttenuator::SetUseLowPassFilter(bool useFilter) { mUseLowPassFilter = useFilter; // Update all existing nodes for (AttenuatorListType::range nodes = mNodeList.All(); !nodes.Empty(); nodes.PopFront()) nodes.Front().mNode->SetUsingLowPass(useFilter); } float SoundAttenuator::GetLowPassStartDistance() { return mLowPassStartDistance; } void SoundAttenuator::SetLowPassStartDistance(float distance) { mLowPassStartDistance = Math::Max(distance, 0.0f); // Update all existing nodes for (AttenuatorListType::range nodes = mNodeList.All(); !nodes.Empty(); nodes.PopFront()) nodes.Front().mNode->SetLowPassDistance(distance); } float SoundAttenuator::GetLowPassCutoffFreq() { return mLowPassCutoffFreq; } void SoundAttenuator::SetLowPassCutoffFreq(float frequency) { mLowPassCutoffFreq = Math::Clamp(frequency, 0.0f, 20000.0f); // Update all existing nodes for (AttenuatorListType::range nodes = mNodeList.All(); !nodes.Empty(); nodes.PopFront()) nodes.Front().mNode->SetLowPassCutoffFreq(frequency); } void SoundAttenuator::UpdateCurve(Event* event) { // We don't ever use the fallback or default resources... just roll back to // 'none' SampleCurve* curve = mCustomFalloffCurve; if (curve) { CurveManager* manager = CurveManager::GetInstance(); String& name = curve->Name; if (name == manager->DefaultResourceName || name == manager->FallbackResourceName) mCustomFalloffCurve = nullptr; } } SoundAttenuatorNode* SoundAttenuator::GetAttenuationNode(StringParam name, unsigned ID) { SoundAttenuatorNode* node; // If using a custom curve, create the SoundAttenuatorNode with that curve if (mFalloffCurveType == FalloffCurveType::Custom && mCustomFalloffCurve) { Array<Vec3> curve; mCustomFalloffCurve->GetCurve(curve); node = new SoundAttenuatorNode(new AttenuatorNode( name, ID, Math::Vec3(0, 0, 0), mStartDistance, mStopDistance, mMinAttenuatedVolume, mFalloffCurveType, &curve)); } // Otherwise create it for the specified curve type else node = new SoundAttenuatorNode(new AttenuatorNode(name, ID, Math::Vec3(0, 0, 0), mStartDistance, mStopDistance, mMinAttenuatedVolume, mFalloffCurveType, nullptr)); node->mNode->SetUsingLowPass(mUseLowPassFilter); if (mUseLowPassFilter) { node->mNode->SetLowPassDistance(mLowPassStartDistance); node->mNode->SetLowPassCutoffFreq(mLowPassCutoffFreq); } mNodeList.PushBack(node); return node; } void SoundAttenuator::RemoveAttenuationNode(SoundAttenuatorNode* node) { mNodeList.Erase(node); delete node; } bool SoundAttenuator::HasInput() { // If any of the SoundAttenuatorNodes has input, return true forRange (SoundAttenuatorNode& node, mNodeList.All()) { if (node.mNode->GetHasInputs()) return true; } return false; } // Sound Attenuator Manager ImplementResourceManager(SoundAttenuatorManager, SoundAttenuator); SoundAttenuatorManager::SoundAttenuatorManager(BoundType* resourceType) : ResourceManager(resourceType) { AddLoader("SoundAttenuator", new TextDataFileLoader<SoundAttenuatorManager>()); DefaultResourceName = "DefaultNoAttenuation"; mCategory = "Sound"; mCanAddFile = true; mOpenFileFilters.PushBack(FileDialogFilter("*.SoundAttenuator.data")); mCanCreateNew = true; mCanDuplicate = true; mExtension = DataResourceExtension; } } // namespace Plasma
9,579
3,171
/* // Copyright (c) 2015 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. */ #include "sat-tid.h" #include "sat-log.h" #include <sstream> #include <map> #include <algorithm> namespace sat { using namespace std; typedef pair<pid_t /* thread id */, unsigned /* cpu */> unique_tid; namespace { bool adding = true; typedef map<unique_tid, pid_t> pid_map; pid_map pids; typedef map<unique_tid, tid_t> tid_map; tid_map tids; unique_tid make_unique(pid_t thread_id, unsigned cpu) { // only use the cpu # for thread 0 if (thread_id != 0) { cpu = 0; } return make_pair(thread_id, cpu); } void assign_tids() { SAT_LOG(1, "assigning tids\n"); tid_t tid_count = 0; for (auto& p : pids) { SAT_LOG(1, "%d => %u\n", p.first.first, tid_count); tids[p.first] = tid_count++; } } } void tid_add(pid_t pid, pid_t thread_id, unsigned cpu) { if (adding) { pids[make_unique(thread_id, cpu)] = pid; } else { fprintf(stderr, "WARNING: ADDING A THREAD AFTER ASSIGNING IDS\n"); } } bool tid_get(pid_t thread_id, unsigned cpu, tid_t& tid) { bool found = false; if (adding) { assign_tids(); adding = false; } auto t = tids.find(make_unique(thread_id, cpu)); if (t != tids.end()) { tid = t->second; found = true; } return found; } bool tid_get_pid(pid_t thread_id, unsigned cpu, pid_t& pid) { bool found; auto i = pids.find(make_unique(thread_id, cpu)); if (i == pids.end()) { SAT_LOG(0, "COULD NOT FIND PID FOR THREAD_ID %d\n", thread_id); found = false; } else { pid = i->second; found = true; SAT_LOG(0, "MAPPED THREAD_ID %d -> PID %d\n", thread_id, pid); } return found; } static tid_map::const_iterator tid_find(tid_t tid) { return find_if(tids.begin(), tids.end(), [tid](tid_map::const_reference t) { return t.second == tid; }); } bool tid_get_pid(tid_t tid, pid_t& pid) { bool found = false; const auto& t = tid_find(tid); if (t != tids.end()) { pid = pids[t->first]; found = true; SAT_LOG(1, "MAPPED TID %u -> PID %d\n", tid, pid); } else { SAT_LOG(0, "COULD NOT FIND PID FOR TID %d\n", tid); } return found; } bool tid_get_thread_id(tid_t tid, pid_t& thread_id) { bool found = false; const auto& t = tid_find(tid); if (t != tids.end()) { thread_id = t->first.first; found = true; SAT_LOG(0, "MAPPED TID %d -> THREAD_ID %d\n", tid, thread_id); } else { SAT_LOG(0, "COULD NOT FIND THREAD_ID FOR TID %d\n", tid); } return found; } bool tid_get_info(tid_t tid, pid_t& pid, pid_t& thread_id, unsigned& cpu) { bool found = false; const auto& t = tid_find(tid); if (t != tids.end()) { pid = pids[t->first]; thread_id = t->first.first; cpu = t->first.second; found = true; } else { SAT_LOG(0, "COULD NOT FIND THREAD_ID FOR TID %d\n", tid); } return found; } // tid, pid, thread_id, cpu void tid_iterate(std::function<bool(tid_t, pid_t, pid_t, unsigned)> callback) { for (auto& t : tids) { // tid, pid, thread_id, cpu if (!callback(t.second, pids[t.first], t.first.first, t.first.second)) { break; } } } pid_t tid_get_first_free_pid() { pid_t i; bool found = false; for (i=1; i<0x7FFFFFF0; i++) { found = false; auto it = pids.begin(); for (; it != pids.end(); it++) { //printf("tid_get_first_free_pid(): %d (%d)\n", it->second, i); if (it->second == i) { found = true; break; } } if (!found) return i; } return i; } } // namespace sat
4,503
1,657
/* * CX - C++ framework for general purpose development * * https://github.com/draede/cx * * Copyright (C) 2014 - 2021 draede - draede [at] outlook [dot] com * * Released under the MIT License. * * 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 "CX/precomp.hpp" #include "CX/Util/DateTime.hpp" #include "CX/Platform.hpp" #ifdef CX_OS_WINDOWS #include "CX/C/Platform/Windows/windows.h" #else #include <time.h> #include <sys/time.h> #endif namespace CX { namespace Util { Bool DateTime::IsLeapYear(UInt16 uYear) { return (uYear % 4 == 0 && uYear % 100 != 0) || (uYear % 400 == 0); } UInt8 DateTime::GetDaysInMonth(UInt16 uYear, UInt8 uMonth) { if (2 == uMonth) { if (IsLeapYear(uYear)) { return 29; } else { return 28; } } else if (4 == uMonth || 6 == uMonth || 9 == uMonth || 11 == uMonth) { return 30; } else { return 31; } } DateTime::DayOfWeek DateTime::GetDayOfWeekFromDate(UInt16 uYear, UInt8 uMonth, UInt8 uDay) { UInt32 y; UInt32 v; y = uYear; y -= uMonth <= 2; const UInt32 era = (y >= 0 ? y : y- 399) / 400; const UInt32 yoe = static_cast<UInt32>(y - era * 400); // [0, 399] const UInt32 doy = (153 * (uMonth + (uMonth > 2 ? -3 : 9)) + 2) / 5 + uDay - 1; // [0, 365] const UInt32 doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096] v = era * 146097 + static_cast<UInt32>(doe) - 719468; v *= SECONDS_PER_DAY; return GetDayOfWeekFromSeconds(v); } DateTime::DayOfWeek DateTime::GetDayOfWeekFromSeconds(UInt32 uSeconds) { return (DayOfWeek)((uSeconds / SECONDS_PER_DAY + 4) % 7); } DateTime::DayOfWeek DateTime::GetDayOfWeekFromMilliseconds(UInt64 uMilliseconds) { return GetDayOfWeekFromSeconds((UInt32)(uMilliseconds / 1000)); } DateTime::DayOfWeek DateTime::GetDayOfWeekFromDate() const { return GetDayOfWeekFromDate(uYear, uMonth, uDay); } void DateTime::FromSeconds(UInt32 uSeconds) { UInt64 cDays = uSeconds / SECONDS_PER_DAY; cDays += 719468; const UInt64 era = (cDays >= 0 ? cDays : cDays - 146096) / 146097; const UInt64 doe = static_cast<UInt64>(cDays - era * 146097); // [0, 146096] const UInt64 yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; // [0, 399] const UInt64 y = static_cast<UInt64>(yoe) + era * 400; const UInt64 doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365] const UInt64 mp = (5 * doy + 2) / 153; // [0, 11] const UInt64 d = doy - (153 * mp + 2)/5 + 1; // [1, 31] const UInt64 m = mp + (mp < 10 ? 3 : -9); // [1, 12] uYear = (UInt16)(y + (m <= 2)); uMonth = (UInt8)m; uDay = (UInt8)d; uSeconds %= SECONDS_PER_DAY; uHour = (UInt8)(uSeconds / SECONDS_PER_HOUR); uSeconds %= SECONDS_PER_HOUR; uMinute = (UInt8)(uSeconds / SECONDS_PER_MINUTE); uSeconds %= SECONDS_PER_MINUTE; uSecond = (UInt8)uSeconds; uMillisecond = 0; } UInt32 DateTime::ToSeconds() const { UInt32 y; UInt32 v; y = uYear; y -= uMonth <= 2; const UInt32 era = (y >= 0 ? y : y- 399) / 400; const UInt32 yoe = static_cast<UInt32>(y - era * 400); // [0, 399] const UInt32 doy = (153 * (uMonth + (uMonth > 2 ? -3 : 9)) + 2) / 5 + uDay - 1; // [0, 365] const UInt32 doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096] v = era * 146097 + static_cast<UInt32>(doe) - 719468; v *= SECONDS_PER_DAY; v += uHour * SECONDS_PER_HOUR; v += uMinute * SECONDS_PER_MINUTE; v += uSecond; return v; } void DateTime::FromMilliseconds(UInt64 uMilliseconds) { UInt64 cDays = uMilliseconds / MILLISECONDS_PER_DAY; cDays += 719468; const UInt64 era = (cDays >= 0 ? cDays : cDays - 146096) / 146097; const UInt64 doe = static_cast<UInt64>(cDays - era * 146097); // [0, 146096] const UInt64 yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; // [0, 399] const UInt64 y = static_cast<UInt64>(yoe) + era * 400; const UInt64 doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365] const UInt64 mp = (5 * doy + 2) / 153; // [0, 11] const UInt64 d = doy - (153 * mp + 2)/5 + 1; // [1, 31] const UInt64 m = mp + (mp < 10 ? 3 : -9); // [1, 12] uYear = (UInt16)(y + (m <= 2)); uMonth = (UInt8)m; uDay = (UInt8)d; uMilliseconds %= MILLISECONDS_PER_DAY; uHour = (UInt8)(uMilliseconds / MILLISECONDS_PER_HOUR); uMilliseconds %= MILLISECONDS_PER_HOUR; uMinute = (UInt8)(uMilliseconds / MILLISECONDS_PER_MINUTE); uMilliseconds %= MILLISECONDS_PER_MINUTE; uSecond = (UInt8)(uMilliseconds / MILLISECONDS_PER_SECOND); uMilliseconds %= MILLISECONDS_PER_SECOND; uMillisecond = (UInt16)uMilliseconds; } UInt64 DateTime::ToMilliseconds() const { UInt64 y; UInt64 v; y = uYear; y -= uMonth <= 2; const UInt64 era = (y >= 0 ? y : y- 399) / 400; const UInt64 yoe = static_cast<UInt64>(y - era * 400); // [0, 399] const UInt64 doy = (153 * ((UInt64)uMonth + ((UInt64)uMonth > 2 ? -3 : 9)) + 2) / 5 + (UInt64)uDay - 1;// [0, 365] const UInt64 doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096] v = era * 146097 + static_cast<UInt64>(doe) - 719468; v *= MILLISECONDS_PER_DAY; v += uHour * MILLISECONDS_PER_HOUR; v += uMinute * MILLISECONDS_PER_MINUTE; v += uSecond * MILLISECONDS_PER_SECOND; v += uMillisecond; return v; } void DateTime::Now() { #ifdef CX_OS_WINDOWS SYSTEMTIME st; ::GetLocalTime(&st); uYear = (UInt16)st.wYear; uMonth = (UInt8)st.wMonth; uDay = (UInt8)st.wDay; uHour = (UInt8)st.wHour; uMinute = (UInt8)st.wMinute; uSecond = (UInt8)st.wSecond; uMillisecond = (UInt16)st.wMilliseconds; #else struct tm *pTime; struct timeval tv; pTime = localtime(&tv.tv_sec); uYear = (UInt16)(pTime->tm_year + 1900); uMonth = (UInt8)(pTime->tm_mon + 1); uDay = (UInt8)(pTime->tm_mday); uHour = (UInt8)(pTime->tm_hour); uMinute = (UInt8)(pTime->tm_min); uSecond = (UInt8)(pTime->tm_sec); if (0 != gettimeofday(&tv, NULL)) { uMillisecond = (UInt16)(tv.tv_usec / 1000); } else { uMillisecond = 0; } #endif } }//namespace Util }//namespace CX
7,448
3,447
#include "Item.h" namespace Cta::Combat { }
46
23
//------------------------------------------------------------------------------ /* This file is part of MUSO: https://github.com/MUSO/MUSO Copyright (c) 2012-2017 MUSO Labs Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #include <MUSO/protocol/Feature.h> #include <MUSO/protocol/Quality.h> #include <MUSO/protocol/jss.h> #include <test/jtx.h> #include <test/jtx/PathSet.h> #include <test/jtx/WSClient.h> namespace MUSO { namespace test { class Offer_test : public beast::unit_test::suite { MUSOAmount reserve(jtx::Env& env, std::uint32_t count) { return env.current()->fees().accountReserve(count); } std::uint32_t lastClose(jtx::Env& env) { return env.current()->info().parentCloseTime.time_since_epoch().count(); } static auto MUSOMinusFee(jtx::Env const& env, std::int64_t MUSOAmount) -> jtx::PrettyAmount { using namespace jtx; auto feeDrops = env.current()->fees().base; return drops(dropsPerMUSO * MUSOAmount - feeDrops); } static auto ledgerEntryState( jtx::Env& env, jtx::Account const& acct_a, jtx::Account const& acct_b, std::string const& currency) { Json::Value jvParams; jvParams[jss::ledger_index] = "current"; jvParams[jss::MUSO_state][jss::currency] = currency; jvParams[jss::MUSO_state][jss::accounts] = Json::arrayValue; jvParams[jss::MUSO_state][jss::accounts].append(acct_a.human()); jvParams[jss::MUSO_state][jss::accounts].append(acct_b.human()); return env.rpc( "json", "ledger_entry", to_string(jvParams))[jss::result]; } static auto ledgerEntryRoot(jtx::Env& env, jtx::Account const& acct) { Json::Value jvParams; jvParams[jss::ledger_index] = "current"; jvParams[jss::account_root] = acct.human(); return env.rpc( "json", "ledger_entry", to_string(jvParams))[jss::result]; } static auto ledgerEntryOffer( jtx::Env& env, jtx::Account const& acct, std::uint32_t offer_seq) { Json::Value jvParams; jvParams[jss::offer][jss::account] = acct.human(); jvParams[jss::offer][jss::seq] = offer_seq; return env.rpc( "json", "ledger_entry", to_string(jvParams))[jss::result]; } static auto getBookOffers( jtx::Env& env, Issue const& taker_pays, Issue const& taker_gets) { Json::Value jvbp; jvbp[jss::ledger_index] = "current"; jvbp[jss::taker_pays][jss::currency] = to_string(taker_pays.currency); jvbp[jss::taker_pays][jss::issuer] = to_string(taker_pays.account); jvbp[jss::taker_gets][jss::currency] = to_string(taker_gets.currency); jvbp[jss::taker_gets][jss::issuer] = to_string(taker_gets.account); return env.rpc("json", "book_offers", to_string(jvbp))[jss::result]; } public: void testRmFundedOffer(FeatureBitset features) { testcase("Incorrect Removal of Funded Offers"); // We need at least two paths. One at good quality and one at bad // quality. The bad quality path needs two offer books in a row. // Each offer book should have two offers at the same quality, the // offers should be completely consumed, and the payment should // should require both offers to be satisfied. The first offer must // be "taker gets" MUSO. Old, broken would remove the first // "taker gets" MUSO offer, even though the offer is still funded and // not used for the payment. using namespace jtx; Env env{*this, features}; auto const gw = Account{"gateway"}; auto const USD = gw["USD"]; auto const BTC = gw["BTC"]; Account const alice{"alice"}; Account const bob{"bob"}; Account const carol{"carol"}; env.fund(MUSO(10000), alice, bob, carol, gw); env.trust(USD(1000), alice, bob, carol); env.trust(BTC(1000), alice, bob, carol); env(pay(gw, alice, BTC(1000))); env(pay(gw, carol, USD(1000))); env(pay(gw, carol, BTC(1000))); // Must be two offers at the same quality // "taker gets" must be MUSO // (Different amounts so I can distinguish the offers) env(offer(carol, BTC(49), MUSO(49))); env(offer(carol, BTC(51), MUSO(51))); // Offers for the poor quality path // Must be two offers at the same quality env(offer(carol, MUSO(50), USD(50))); env(offer(carol, MUSO(50), USD(50))); // Offers for the good quality path env(offer(carol, BTC(1), USD(100))); PathSet paths(Path(MUSO, USD), Path(USD)); env(pay(alice, bob, USD(100)), json(paths.json()), sendmax(BTC(1000)), txflags(tfPartialPayment)); env.require(balance(bob, USD(100))); BEAST_EXPECT( !isOffer(env, carol, BTC(1), USD(100)) && isOffer(env, carol, BTC(49), MUSO(49))); } void testCanceledOffer(FeatureBitset features) { testcase("Removing Canceled Offers"); using namespace jtx; Env env{*this, features}; auto const gw = Account{"gateway"}; auto const alice = Account{"alice"}; auto const USD = gw["USD"]; env.fund(MUSO(10000), alice, gw); env.close(); env.trust(USD(100), alice); env.close(); env(pay(gw, alice, USD(50))); env.close(); auto const offer1Seq = env.seq(alice); env(offer(alice, MUSO(500), USD(100)), require(offers(alice, 1))); env.close(); BEAST_EXPECT(isOffer(env, alice, MUSO(500), USD(100))); // cancel the offer above and replace it with a new offer auto const offer2Seq = env.seq(alice); env(offer(alice, MUSO(300), USD(100)), json(jss::OfferSequence, offer1Seq), require(offers(alice, 1))); env.close(); BEAST_EXPECT( isOffer(env, alice, MUSO(300), USD(100)) && !isOffer(env, alice, MUSO(500), USD(100))); // Test canceling non-existent offer. // auto const offer3Seq = env.seq (alice); env(offer(alice, MUSO(400), USD(200)), json(jss::OfferSequence, offer1Seq), require(offers(alice, 2))); env.close(); BEAST_EXPECT( isOffer(env, alice, MUSO(300), USD(100)) && isOffer(env, alice, MUSO(400), USD(200))); // Test cancellation now with OfferCancel tx auto const offer4Seq = env.seq(alice); env(offer(alice, MUSO(222), USD(111)), require(offers(alice, 3))); env.close(); BEAST_EXPECT(isOffer(env, alice, MUSO(222), USD(111))); { Json::Value cancelOffer; cancelOffer[jss::Account] = alice.human(); cancelOffer[jss::OfferSequence] = offer4Seq; cancelOffer[jss::TransactionType] = jss::OfferCancel; env(cancelOffer); } env.close(); BEAST_EXPECT(env.seq(alice) == offer4Seq + 2); BEAST_EXPECT(!isOffer(env, alice, MUSO(222), USD(111))); // Create an offer that both fails with a tecEXPIRED code and removes // an offer. Show that the attempt to remove the offer fails. env.require(offers(alice, 2)); // featureDepositPreauths changes the return code on an expired Offer. // Adapt to that. bool const featPreauth{features[featureDepositPreauth]}; env(offer(alice, MUSO(5), USD(2)), json(sfExpiration.fieldName, lastClose(env)), json(jss::OfferSequence, offer2Seq), ter(featPreauth ? TER{tecEXPIRED} : TER{tesSUCCESS})); env.close(); env.require(offers(alice, 2)); BEAST_EXPECT(isOffer(env, alice, MUSO(300), USD(100))); // offer2 BEAST_EXPECT(!isOffer(env, alice, MUSO(5), USD(2))); // expired } void testTinyPayment(FeatureBitset features) { testcase("Tiny payments"); // Regression test for tiny payments using namespace jtx; using namespace std::chrono_literals; auto const alice = Account{"alice"}; auto const bob = Account{"bob"}; auto const carol = Account{"carol"}; auto const gw = Account{"gw"}; auto const USD = gw["USD"]; auto const EUR = gw["EUR"]; Env env{*this, features}; env.fund(MUSO(10000), alice, bob, carol, gw); env.trust(USD(1000), alice, bob, carol); env.trust(EUR(1000), alice, bob, carol); env(pay(gw, alice, USD(100))); env(pay(gw, carol, EUR(100))); // Create more offers than the loop max count in DeliverNodeReverse // Note: the DeliverNodeReverse code has been removed; however since // this is a regression test the original test is being left as-is for // now. for (int i = 0; i < 101; ++i) env(offer(carol, USD(1), EUR(2))); env(pay(alice, bob, EUR(epsilon)), path(~EUR), sendmax(USD(100))); } void testMUSOTinyPayment(FeatureBitset features) { testcase("MUSO Tiny payments"); // Regression test for tiny MUSO payments // In some cases, when the payment code calculates // the amount of MUSO needed as input to an MUSO->iou offer // it would incorrectly round the amount to zero (even when // round-up was set to true). // The bug would cause funded offers to be incorrectly removed // because the code thought they were unfunded. // The conditions to trigger the bug are: // 1) When we calculate the amount of input MUSO needed for an offer // from MUSO->iou, the amount is less than 1 drop (after rounding // up the float representation). // 2) There is another offer in the same book with a quality // sufficiently bad that when calculating the input amount // needed the amount is not set to zero. using namespace jtx; using namespace std::chrono_literals; auto const alice = Account{"alice"}; auto const bob = Account{"bob"}; auto const carol = Account{"carol"}; auto const dan = Account{"dan"}; auto const erin = Account{"erin"}; auto const gw = Account{"gw"}; auto const USD = gw["USD"]; Env env{*this, features}; env.fund(MUSO(10000), alice, bob, carol, dan, erin, gw); env.trust(USD(1000), alice, bob, carol, dan, erin); env(pay(gw, carol, USD(0.99999))); env(pay(gw, dan, USD(1))); env(pay(gw, erin, USD(1))); // Carol doesn't quite have enough funds for this offer // The amount left after this offer is taken will cause // STAmount to incorrectly round to zero when the next offer // (at a good quality) is considered. (when the // stAmountCalcSwitchover2 patch is inactive) env(offer(carol, drops(1), USD(1))); // Offer at a quality poor enough so when the input MUSO is // calculated in the reverse pass, the amount is not zero. env(offer(dan, MUSO(100), USD(1))); env.close(); // This is the funded offer that will be incorrectly removed. // It is considered after the offer from carol, which leaves a // tiny amount left to pay. When calculating the amount of MUSO // needed for this offer, it will incorrectly compute zero in both // the forward and reverse passes (when the stAmountCalcSwitchover2 // is inactive.) env(offer(erin, drops(2), USD(2))); env(pay(alice, bob, USD(1)), path(~USD), sendmax(MUSO(102)), txflags(tfNoMUSOirect | tfPartialPayment)); env.require(offers(carol, 0), offers(dan, 1)); // offer was correctly consumed. There is still some // liquidity left on that offer. env.require(balance(erin, USD(0.99999)), offers(erin, 1)); } void testEnforceNoMUSO(FeatureBitset features) { testcase("Enforce No MUSO"); using namespace jtx; auto const gw = Account{"gateway"}; auto const USD = gw["USD"]; auto const BTC = gw["BTC"]; auto const EUR = gw["EUR"]; Account const alice{"alice"}; Account const bob{"bob"}; Account const carol{"carol"}; Account const dan{"dan"}; { // No MUSO with an implied account step after an offer Env env{*this, features}; auto const gw1 = Account{"gw1"}; auto const USD1 = gw1["USD"]; auto const gw2 = Account{"gw2"}; auto const USD2 = gw2["USD"]; env.fund(MUSO(10000), alice, noMUSO(bob), carol, dan, gw1, gw2); env.trust(USD1(1000), alice, carol, dan); env(trust(bob, USD1(1000), tfSetNoMUSO)); env.trust(USD2(1000), alice, carol, dan); env(trust(bob, USD2(1000), tfSetNoMUSO)); env(pay(gw1, dan, USD1(50))); env(pay(gw1, bob, USD1(50))); env(pay(gw2, bob, USD2(50))); env(offer(dan, MUSO(50), USD1(50))); env(pay(alice, carol, USD2(50)), path(~USD1, bob), sendmax(MUSO(50)), txflags(tfNoMUSOirect), ter(tecPATH_DRY)); } { // Make sure payment works with default flags Env env{*this, features}; auto const gw1 = Account{"gw1"}; auto const USD1 = gw1["USD"]; auto const gw2 = Account{"gw2"}; auto const USD2 = gw2["USD"]; env.fund(MUSO(10000), alice, bob, carol, dan, gw1, gw2); env.trust(USD1(1000), alice, bob, carol, dan); env.trust(USD2(1000), alice, bob, carol, dan); env(pay(gw1, dan, USD1(50))); env(pay(gw1, bob, USD1(50))); env(pay(gw2, bob, USD2(50))); env(offer(dan, MUSO(50), USD1(50))); env(pay(alice, carol, USD2(50)), path(~USD1, bob), sendmax(MUSO(50)), txflags(tfNoMUSOirect)); env.require(balance(alice, MUSOMinusFee(env, 10000 - 50))); env.require(balance(bob, USD1(100))); env.require(balance(bob, USD2(0))); env.require(balance(carol, USD2(50))); } } void testInsufficientReserve(FeatureBitset features) { testcase("Insufficient Reserve"); // If an account places an offer and its balance // *before* the transaction began isn't high enough // to meet the reserve *after* the transaction runs, // then no offer should go on the books but if the // offer partially or fully crossed the tx succeeds. using namespace jtx; auto const gw = Account{"gateway"}; auto const alice = Account{"alice"}; auto const bob = Account{"bob"}; auto const carol = Account{"carol"}; auto const USD = gw["USD"]; auto const usdOffer = USD(1000); auto const MUSOOffer = MUSO(1000); // No crossing: { Env env{*this, features}; env.fund(MUSO(1000000), gw); auto const f = env.current()->fees().base; auto const r = reserve(env, 0); env.fund(r + f, alice); env(trust(alice, usdOffer), ter(tesSUCCESS)); env(pay(gw, alice, usdOffer), ter(tesSUCCESS)); env(offer(alice, MUSOOffer, usdOffer), ter(tecINSUF_RESERVE_OFFER)); env.require(balance(alice, r - f), owners(alice, 1)); } // Partial cross: { Env env{*this, features}; env.fund(MUSO(1000000), gw); auto const f = env.current()->fees().base; auto const r = reserve(env, 0); auto const usdOffer2 = USD(500); auto const MUSOOffer2 = MUSO(500); env.fund(r + f + MUSOOffer, bob); env(offer(bob, usdOffer2, MUSOOffer2), ter(tesSUCCESS)); env.fund(r + f, alice); env(trust(alice, usdOffer), ter(tesSUCCESS)); env(pay(gw, alice, usdOffer), ter(tesSUCCESS)); env(offer(alice, MUSOOffer, usdOffer), ter(tesSUCCESS)); env.require( balance(alice, r - f + MUSOOffer2), balance(alice, usdOffer2), owners(alice, 1), balance(bob, r + MUSOOffer2), balance(bob, usdOffer2), owners(bob, 1)); } // Account has enough reserve as is, but not enough // if an offer were added. Attempt to sell IOUs to // buy MUSO. If it fully crosses, we succeed. { Env env{*this, features}; env.fund(MUSO(1000000), gw); auto const f = env.current()->fees().base; auto const r = reserve(env, 0); auto const usdOffer2 = USD(500); auto const MUSOOffer2 = MUSO(500); env.fund(r + f + MUSOOffer, bob, carol); env(offer(bob, usdOffer2, MUSOOffer2), ter(tesSUCCESS)); env(offer(carol, usdOffer, MUSOOffer), ter(tesSUCCESS)); env.fund(r + f, alice); env(trust(alice, usdOffer), ter(tesSUCCESS)); env(pay(gw, alice, usdOffer), ter(tesSUCCESS)); env(offer(alice, MUSOOffer, usdOffer), ter(tesSUCCESS)); env.require( balance(alice, r - f + MUSOOffer), balance(alice, USD(0)), owners(alice, 1), balance(bob, r + MUSOOffer2), balance(bob, usdOffer2), owners(bob, 1), balance(carol, r + MUSOOffer2), balance(carol, usdOffer2), owners(carol, 2)); } } // Helper function that returns the Offers on an account. static std::vector<std::shared_ptr<SLE const>> offersOnAccount(jtx::Env& env, jtx::Account account) { std::vector<std::shared_ptr<SLE const>> result; forEachItem( *env.current(), account, [&result](std::shared_ptr<SLE const> const& sle) { if (sle->getType() == ltOFFER) result.push_back(sle); }); return result; } void testFillModes(FeatureBitset features) { testcase("Fill Modes"); using namespace jtx; auto const startBalance = MUSO(1000000); auto const gw = Account{"gateway"}; auto const alice = Account{"alice"}; auto const bob = Account{"bob"}; auto const USD = gw["USD"]; // Fill or Kill - unless we fully cross, just charge a fee and don't // place the offer on the books. But also clean up expired offers // that are discovered along the way. // // fix1578 changes the return code. Verify expected behavior // without and with fix1578. for (auto const tweakedFeatures : {features - fix1578, features | fix1578}) { Env env{*this, tweakedFeatures}; auto const f = env.current()->fees().base; env.fund(startBalance, gw, alice, bob); // bob creates an offer that expires before the next ledger close. env(offer(bob, USD(500), MUSO(500)), json(sfExpiration.fieldName, lastClose(env) + 1), ter(tesSUCCESS)); // The offer expires (it's not removed yet). env.close(); env.require(owners(bob, 1), offers(bob, 1)); // bob creates the offer that will be crossed. env(offer(bob, USD(500), MUSO(500)), ter(tesSUCCESS)); env.close(); env.require(owners(bob, 2), offers(bob, 2)); env(trust(alice, USD(1000)), ter(tesSUCCESS)); env(pay(gw, alice, USD(1000)), ter(tesSUCCESS)); // Order that can't be filled but will remove bob's expired offer: { TER const killedCode{ tweakedFeatures[fix1578] ? TER{tecKILLED} : TER{tesSUCCESS}}; env(offer(alice, MUSO(1000), USD(1000)), txflags(tfFillOrKill), ter(killedCode)); } env.require( balance(alice, startBalance - (f * 2)), balance(alice, USD(1000)), owners(alice, 1), offers(alice, 0), balance(bob, startBalance - (f * 2)), balance(bob, USD(none)), owners(bob, 1), offers(bob, 1)); // Order that can be filled env(offer(alice, MUSO(500), USD(500)), txflags(tfFillOrKill), ter(tesSUCCESS)); env.require( balance(alice, startBalance - (f * 3) + MUSO(500)), balance(alice, USD(500)), owners(alice, 1), offers(alice, 0), balance(bob, startBalance - (f * 2) - MUSO(500)), balance(bob, USD(500)), owners(bob, 1), offers(bob, 0)); } // Immediate or Cancel - cross as much as possible // and add nothing on the books: { Env env{*this, features}; auto const f = env.current()->fees().base; env.fund(startBalance, gw, alice, bob); env(trust(alice, USD(1000)), ter(tesSUCCESS)); env(pay(gw, alice, USD(1000)), ter(tesSUCCESS)); // No cross: env(offer(alice, MUSO(1000), USD(1000)), txflags(tfImmediateOrCancel), ter(tesSUCCESS)); env.require( balance(alice, startBalance - f - f), balance(alice, USD(1000)), owners(alice, 1), offers(alice, 0)); // Partially cross: env(offer(bob, USD(50), MUSO(50)), ter(tesSUCCESS)); env(offer(alice, MUSO(1000), USD(1000)), txflags(tfImmediateOrCancel), ter(tesSUCCESS)); env.require( balance(alice, startBalance - f - f - f + MUSO(50)), balance(alice, USD(950)), owners(alice, 1), offers(alice, 0), balance(bob, startBalance - f - MUSO(50)), balance(bob, USD(50)), owners(bob, 1), offers(bob, 0)); // Fully cross: env(offer(bob, USD(50), MUSO(50)), ter(tesSUCCESS)); env(offer(alice, MUSO(50), USD(50)), txflags(tfImmediateOrCancel), ter(tesSUCCESS)); env.require( balance(alice, startBalance - f - f - f - f + MUSO(100)), balance(alice, USD(900)), owners(alice, 1), offers(alice, 0), balance(bob, startBalance - f - f - MUSO(100)), balance(bob, USD(100)), owners(bob, 1), offers(bob, 0)); } // tfPassive -- place the offer without crossing it. { Env env(*this, features); env.fund(startBalance, gw, alice, bob); env.close(); env(trust(bob, USD(1000))); env.close(); env(pay(gw, bob, USD(1000))); env.close(); env(offer(alice, USD(1000), MUSO(2000))); env.close(); auto const aliceOffers = offersOnAccount(env, alice); BEAST_EXPECT(aliceOffers.size() == 1); for (auto offerPtr : aliceOffers) { auto const& offer = *offerPtr; BEAST_EXPECT(offer[sfTakerGets] == MUSO(2000)); BEAST_EXPECT(offer[sfTakerPays] == USD(1000)); } // bob creates a passive offer that could cross alice's. // bob's offer should stay in the ledger. env(offer(bob, MUSO(2000), USD(1000), tfPassive)); env.close(); env.require(offers(alice, 1)); auto const bobOffers = offersOnAccount(env, bob); BEAST_EXPECT(bobOffers.size() == 1); for (auto offerPtr : bobOffers) { auto const& offer = *offerPtr; BEAST_EXPECT(offer[sfTakerGets] == USD(1000)); BEAST_EXPECT(offer[sfTakerPays] == MUSO(2000)); } // It should be possible for gw to cross both of those offers. env(offer(gw, MUSO(2000), USD(1000))); env.close(); env.require(offers(alice, 0)); env.require(offers(gw, 0)); env.require(offers(bob, 1)); env(offer(gw, USD(1000), MUSO(2000))); env.close(); env.require(offers(bob, 0)); env.require(offers(gw, 0)); } // tfPassive -- cross only offers of better quality. { Env env(*this, features); env.fund(startBalance, gw, "alice", "bob"); env.close(); env(trust("bob", USD(1000))); env.close(); env(pay(gw, "bob", USD(1000))); env(offer("alice", USD(500), MUSO(1001))); env.close(); env(offer("alice", USD(500), MUSO(1000))); env.close(); auto const aliceOffers = offersOnAccount(env, "alice"); BEAST_EXPECT(aliceOffers.size() == 2); // bob creates a passive offer. That offer should cross one // of alice's (the one with better quality) and leave alice's // other offer untouched. env(offer("bob", MUSO(2000), USD(1000), tfPassive)); env.close(); env.require(offers("alice", 1)); auto const bobOffers = offersOnAccount(env, "bob"); BEAST_EXPECT(bobOffers.size() == 1); for (auto offerPtr : bobOffers) { auto const& offer = *offerPtr; BEAST_EXPECT(offer[sfTakerGets] == USD(499.5)); BEAST_EXPECT(offer[sfTakerPays] == MUSO(999)); } } } void testMalformed(FeatureBitset features) { testcase("Malformed Detection"); using namespace jtx; auto const startBalance = MUSO(1000000); auto const gw = Account{"gateway"}; auto const alice = Account{"alice"}; auto const USD = gw["USD"]; Env env{*this, features}; env.fund(startBalance, gw, alice); // Order that has invalid flags env(offer(alice, USD(1000), MUSO(1000)), txflags(tfImmediateOrCancel + 1), ter(temINVALID_FLAG)); env.require( balance(alice, startBalance), owners(alice, 0), offers(alice, 0)); // Order with incompatible flags env(offer(alice, USD(1000), MUSO(1000)), txflags(tfImmediateOrCancel | tfFillOrKill), ter(temINVALID_FLAG)); env.require( balance(alice, startBalance), owners(alice, 0), offers(alice, 0)); // Sell and buy the same asset { // Alice tries an MUSO to MUSO order: env(offer(alice, MUSO(1000), MUSO(1000)), ter(temBAD_OFFER)); env.require(owners(alice, 0), offers(alice, 0)); // Alice tries an IOU to IOU order: env(trust(alice, USD(1000)), ter(tesSUCCESS)); env(pay(gw, alice, USD(1000)), ter(tesSUCCESS)); env(offer(alice, USD(1000), USD(1000)), ter(temREDUNDANT)); env.require(owners(alice, 1), offers(alice, 0)); } // Offers with negative amounts { env(offer(alice, -USD(1000), MUSO(1000)), ter(temBAD_OFFER)); env.require(owners(alice, 1), offers(alice, 0)); env(offer(alice, USD(1000), -MUSO(1000)), ter(temBAD_OFFER)); env.require(owners(alice, 1), offers(alice, 0)); } // Offer with a bad expiration { env(offer(alice, USD(1000), MUSO(1000)), json(sfExpiration.fieldName, std::uint32_t(0)), ter(temBAD_EXPIRATION)); env.require(owners(alice, 1), offers(alice, 0)); } // Offer with a bad offer sequence { env(offer(alice, USD(1000), MUSO(1000)), json(jss::OfferSequence, std::uint32_t(0)), ter(temBAD_SEQUENCE)); env.require(owners(alice, 1), offers(alice, 0)); } // Use MUSO as a currency code { auto const BAD = IOU(gw, badCurrency()); env(offer(alice, MUSO(1000), BAD(1000)), ter(temBAD_CURRENCY)); env.require(owners(alice, 1), offers(alice, 0)); } } void testExpiration(FeatureBitset features) { testcase("Offer Expiration"); using namespace jtx; auto const gw = Account{"gateway"}; auto const alice = Account{"alice"}; auto const bob = Account{"bob"}; auto const USD = gw["USD"]; auto const startBalance = MUSO(1000000); auto const usdOffer = USD(1000); auto const MUSOOffer = MUSO(1000); Env env{*this, features}; env.fund(startBalance, gw, alice, bob); env.close(); auto const f = env.current()->fees().base; env(trust(alice, usdOffer), ter(tesSUCCESS)); env(pay(gw, alice, usdOffer), ter(tesSUCCESS)); env.close(); env.require( balance(alice, startBalance - f), balance(alice, usdOffer), offers(alice, 0), owners(alice, 1)); // Place an offer that should have already expired. // The DepositPreauth amendment changes the return code; adapt to that. bool const featPreauth{features[featureDepositPreauth]}; env(offer(alice, MUSOOffer, usdOffer), json(sfExpiration.fieldName, lastClose(env)), ter(featPreauth ? TER{tecEXPIRED} : TER{tesSUCCESS})); env.require( balance(alice, startBalance - f - f), balance(alice, usdOffer), offers(alice, 0), owners(alice, 1)); env.close(); // Add an offer that expires before the next ledger close env(offer(alice, MUSOOffer, usdOffer), json(sfExpiration.fieldName, lastClose(env) + 1), ter(tesSUCCESS)); env.require( balance(alice, startBalance - f - f - f), balance(alice, usdOffer), offers(alice, 1), owners(alice, 2)); // The offer expires (it's not removed yet) env.close(); env.require( balance(alice, startBalance - f - f - f), balance(alice, usdOffer), offers(alice, 1), owners(alice, 2)); // Add offer - the expired offer is removed env(offer(bob, usdOffer, MUSOOffer), ter(tesSUCCESS)); env.require( balance(alice, startBalance - f - f - f), balance(alice, usdOffer), offers(alice, 0), owners(alice, 1), balance(bob, startBalance - f), balance(bob, USD(none)), offers(bob, 1), owners(bob, 1)); } void testUnfundedCross(FeatureBitset features) { testcase("Unfunded Crossing"); using namespace jtx; auto const gw = Account{"gateway"}; auto const USD = gw["USD"]; auto const usdOffer = USD(1000); auto const MUSOOffer = MUSO(1000); Env env{*this, features}; env.fund(MUSO(1000000), gw); // The fee that's charged for transactions auto const f = env.current()->fees().base; // Account is at the reserve, and will dip below once // fees are subtracted. env.fund(reserve(env, 0), "alice"); env(offer("alice", usdOffer, MUSOOffer), ter(tecUNFUNDED_OFFER)); env.require(balance("alice", reserve(env, 0) - f), owners("alice", 0)); // Account has just enough for the reserve and the // fee. env.fund(reserve(env, 0) + f, "bob"); env(offer("bob", usdOffer, MUSOOffer), ter(tecUNFUNDED_OFFER)); env.require(balance("bob", reserve(env, 0)), owners("bob", 0)); // Account has enough for the reserve, the fee and // the offer, and a bit more, but not enough for the // reserve after the offer is placed. env.fund(reserve(env, 0) + f + MUSO(1), "carol"); env(offer("carol", usdOffer, MUSOOffer), ter(tecINSUF_RESERVE_OFFER)); env.require( balance("carol", reserve(env, 0) + MUSO(1)), owners("carol", 0)); // Account has enough for the reserve plus one // offer, and the fee. env.fund(reserve(env, 1) + f, "dan"); env(offer("dan", usdOffer, MUSOOffer), ter(tesSUCCESS)); env.require(balance("dan", reserve(env, 1)), owners("dan", 1)); // Account has enough for the reserve plus one // offer, the fee and the entire offer amount. env.fund(reserve(env, 1) + f + MUSOOffer, "eve"); env(offer("eve", usdOffer, MUSOOffer), ter(tesSUCCESS)); env.require( balance("eve", reserve(env, 1) + MUSOOffer), owners("eve", 1)); } void testSelfCross(bool use_partner, FeatureBitset features) { testcase( std::string("Self-crossing") + (use_partner ? ", with partner account" : "")); using namespace jtx; auto const gw = Account{"gateway"}; auto const partner = Account{"partner"}; auto const USD = gw["USD"]; auto const BTC = gw["BTC"]; Env env{*this, features}; env.close(); env.fund(MUSO(10000), gw); if (use_partner) { env.fund(MUSO(10000), partner); env(trust(partner, USD(100))); env(trust(partner, BTC(500))); env(pay(gw, partner, USD(100))); env(pay(gw, partner, BTC(500))); } auto const& account_to_test = use_partner ? partner : gw; env.close(); env.require(offers(account_to_test, 0)); // PART 1: // we will make two offers that can be used to bridge BTC to USD // through MUSO env(offer(account_to_test, BTC(250), MUSO(1000))); env.require(offers(account_to_test, 1)); // validate that the book now shows a BTC for MUSO offer BEAST_EXPECT(isOffer(env, account_to_test, BTC(250), MUSO(1000))); auto const secondLegSeq = env.seq(account_to_test); env(offer(account_to_test, MUSO(1000), USD(50))); env.require(offers(account_to_test, 2)); // validate that the book also shows a MUSO for USD offer BEAST_EXPECT(isOffer(env, account_to_test, MUSO(1000), USD(50))); // now make an offer that will cross and auto-bridge, meaning // the outstanding offers will be taken leaving us with none env(offer(account_to_test, USD(50), BTC(250))); auto jrr = getBookOffers(env, USD, BTC); BEAST_EXPECT(jrr[jss::offers].isArray()); BEAST_EXPECT(jrr[jss::offers].size() == 0); jrr = getBookOffers(env, BTC, MUSO); BEAST_EXPECT(jrr[jss::offers].isArray()); BEAST_EXPECT(jrr[jss::offers].size() == 0); // NOTE : // At this point, all offers are expected to be consumed. // Alas, they are not - because of a bug in the Taker auto-bridging // implementation which is addressed by fixTakerDryOfferRemoval. // The pre-fixTakerDryOfferRemoval implementation (incorrect) leaves // an empty offer in the second leg of the bridge. Validate both the // old and the new behavior. { auto acctOffers = offersOnAccount(env, account_to_test); bool const noStaleOffers{ features[featureFlowCross] || features[fixTakerDryOfferRemoval]}; BEAST_EXPECT(acctOffers.size() == (noStaleOffers ? 0 : 1)); for (auto const& offerPtr : acctOffers) { auto const& offer = *offerPtr; BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER); BEAST_EXPECT(offer[sfTakerGets] == USD(0)); BEAST_EXPECT(offer[sfTakerPays] == MUSO(0)); } } // cancel that lingering second offer so that it doesn't interfere // with the next set of offers we test. this will not be needed once // the bridging bug is fixed Json::Value cancelOffer; cancelOffer[jss::Account] = account_to_test.human(); cancelOffer[jss::OfferSequence] = secondLegSeq; cancelOffer[jss::TransactionType] = jss::OfferCancel; env(cancelOffer); env.require(offers(account_to_test, 0)); // PART 2: // simple direct crossing BTC to USD and then USD to BTC which causes // the first offer to be replaced env(offer(account_to_test, BTC(250), USD(50))); env.require(offers(account_to_test, 1)); // validate that the book shows one BTC for USD offer and no USD for // BTC offers BEAST_EXPECT(isOffer(env, account_to_test, BTC(250), USD(50))); jrr = getBookOffers(env, USD, BTC); BEAST_EXPECT(jrr[jss::offers].isArray()); BEAST_EXPECT(jrr[jss::offers].size() == 0); // this second offer would self-cross directly, so it causes the first // offer by the same owner/taker to be removed env(offer(account_to_test, USD(50), BTC(250))); env.require(offers(account_to_test, 1)); // validate that we now have just the second offer...the first // was removed jrr = getBookOffers(env, BTC, USD); BEAST_EXPECT(jrr[jss::offers].isArray()); BEAST_EXPECT(jrr[jss::offers].size() == 0); BEAST_EXPECT(isOffer(env, account_to_test, USD(50), BTC(250))); } void testNegativeBalance(FeatureBitset features) { // This test creates an offer test for negative balance // with transfer fees and miniscule funds. testcase("Negative Balance"); using namespace jtx; Env env{*this, features}; auto const gw = Account{"gateway"}; auto const alice = Account{"alice"}; auto const bob = Account{"bob"}; auto const USD = gw["USD"]; auto const BTC = gw["BTC"]; // these *interesting* amounts were taken // from the original JS test that was ported here auto const gw_initial_balance = drops(1149999730); auto const alice_initial_balance = drops(499946999680); auto const bob_initial_balance = drops(10199999920); auto const small_amount = STAmount{bob["USD"].issue(), UINT64_C(2710505431213761), -33}; env.fund(gw_initial_balance, gw); env.fund(alice_initial_balance, alice); env.fund(bob_initial_balance, bob); env(rate(gw, 1.005)); env(trust(alice, USD(500))); env(trust(bob, USD(50))); env(trust(gw, alice["USD"](100))); env(pay(gw, alice, alice["USD"](50))); env(pay(gw, bob, small_amount)); env(offer(alice, USD(50), MUSO(150000))); // unfund the offer env(pay(alice, gw, USD(100))); // drop the trust line (set to 0) env(trust(gw, alice["USD"](0))); // verify balances auto jrr = ledgerEntryState(env, alice, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "50"); jrr = ledgerEntryState(env, bob, gw, "USD"); BEAST_EXPECT( jrr[jss::node][sfBalance.fieldName][jss::value] == "-2710505431213761e-33"); // create crossing offer env(offer(bob, MUSO(2000), USD(1))); // verify balances again. // // NOTE : // Here a difference in the rounding modes of our two offer crossing // algorithms becomes apparent. The old offer crossing would consume // small_amount and transfer no MUSO. The new offer crossing transfers // a single drop, rather than no drops. auto const crossingDelta = features[featureFlowCross] ? drops(1) : drops(0); jrr = ledgerEntryState(env, alice, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "50"); BEAST_EXPECT( env.balance(alice, MUSOIssue()) == alice_initial_balance - env.current()->fees().base * 3 - crossingDelta); jrr = ledgerEntryState(env, bob, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "0"); BEAST_EXPECT( env.balance(bob, MUSOIssue()) == bob_initial_balance - env.current()->fees().base * 2 + crossingDelta); } void testOfferCrossWithMUSO(bool reverse_order, FeatureBitset features) { testcase( std::string("Offer Crossing with MUSO, ") + (reverse_order ? "Reverse" : "Normal") + " order"); using namespace jtx; Env env{*this, features}; auto const gw = Account{"gateway"}; auto const alice = Account{"alice"}; auto const bob = Account{"bob"}; auto const USD = gw["USD"]; env.fund(MUSO(10000), gw, alice, bob); env(trust(alice, USD(1000))); env(trust(bob, USD(1000))); env(pay(gw, alice, alice["USD"](500))); if (reverse_order) env(offer(bob, USD(1), MUSO(4000))); env(offer(alice, MUSO(150000), USD(50))); if (!reverse_order) env(offer(bob, USD(1), MUSO(4000))); // Existing offer pays better than this wants. // Fully consume existing offer. // Pay 1 USD, get 4000 MUSO. auto jrr = ledgerEntryState(env, bob, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-1"); jrr = ledgerEntryRoot(env, bob); BEAST_EXPECT( jrr[jss::node][sfBalance.fieldName] == to_string((MUSO(10000) - MUSO(reverse_order ? 4000 : 3000) - env.current()->fees().base * 2) .MUSO())); jrr = ledgerEntryState(env, alice, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-499"); jrr = ledgerEntryRoot(env, alice); BEAST_EXPECT( jrr[jss::node][sfBalance.fieldName] == to_string((MUSO(10000) + MUSO(reverse_order ? 4000 : 3000) - env.current()->fees().base * 2) .MUSO())); } void testOfferCrossWithLimitOverride(FeatureBitset features) { testcase("Offer Crossing with Limit Override"); using namespace jtx; Env env{*this, features}; auto const gw = Account{"gateway"}; auto const alice = Account{"alice"}; auto const bob = Account{"bob"}; auto const USD = gw["USD"]; env.fund(MUSO(100000), gw, alice, bob); env(trust(alice, USD(1000))); env(pay(gw, alice, alice["USD"](500))); env(offer(alice, MUSO(150000), USD(50))); env(offer(bob, USD(1), MUSO(3000))); auto jrr = ledgerEntryState(env, bob, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-1"); jrr = ledgerEntryRoot(env, bob); BEAST_EXPECT( jrr[jss::node][sfBalance.fieldName] == to_string((MUSO(100000) - MUSO(3000) - env.current()->fees().base * 1) .MUSO())); jrr = ledgerEntryState(env, alice, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-499"); jrr = ledgerEntryRoot(env, alice); BEAST_EXPECT( jrr[jss::node][sfBalance.fieldName] == to_string((MUSO(100000) + MUSO(3000) - env.current()->fees().base * 2) .MUSO())); } void testOfferAcceptThenCancel(FeatureBitset features) { testcase("Offer Accept then Cancel."); using namespace jtx; Env env{*this, features}; auto const USD = env.master["USD"]; auto const nextOfferSeq = env.seq(env.master); env(offer(env.master, MUSO(500), USD(100))); env.close(); Json::Value cancelOffer; cancelOffer[jss::Account] = env.master.human(); cancelOffer[jss::OfferSequence] = nextOfferSeq; cancelOffer[jss::TransactionType] = jss::OfferCancel; env(cancelOffer); BEAST_EXPECT(env.seq(env.master) == nextOfferSeq + 2); // ledger_accept, call twice and verify no odd behavior env.close(); env.close(); BEAST_EXPECT(env.seq(env.master) == nextOfferSeq + 2); } void testOfferCancelPastAndFuture(FeatureBitset features) { testcase("Offer Cancel Past and Future Sequence."); using namespace jtx; Env env{*this, features}; auto const alice = Account{"alice"}; auto const nextOfferSeq = env.seq(env.master); env.fund(MUSO(10000), alice); Json::Value cancelOffer; cancelOffer[jss::Account] = env.master.human(); cancelOffer[jss::OfferSequence] = nextOfferSeq; cancelOffer[jss::TransactionType] = jss::OfferCancel; env(cancelOffer); cancelOffer[jss::OfferSequence] = env.seq(env.master); env(cancelOffer, ter(temBAD_SEQUENCE)); cancelOffer[jss::OfferSequence] = env.seq(env.master) + 1; env(cancelOffer, ter(temBAD_SEQUENCE)); env.close(); env.close(); } void testCurrencyConversionEntire(FeatureBitset features) { testcase("Currency Conversion: Entire Offer"); using namespace jtx; Env env{*this, features}; auto const gw = Account{"gateway"}; auto const alice = Account{"alice"}; auto const bob = Account{"bob"}; auto const USD = gw["USD"]; env.fund(MUSO(10000), gw, alice, bob); env.require(owners(bob, 0)); env(trust(alice, USD(100))); env(trust(bob, USD(1000))); env.require(owners(alice, 1), owners(bob, 1)); env(pay(gw, alice, alice["USD"](100))); auto const bobOfferSeq = env.seq(bob); env(offer(bob, USD(100), MUSO(500))); env.require(owners(alice, 1), owners(bob, 2)); auto jro = ledgerEntryOffer(env, bob, bobOfferSeq); BEAST_EXPECT( jro[jss::node][jss::TakerGets] == MUSO(500).value().getText()); BEAST_EXPECT( jro[jss::node][jss::TakerPays] == USD(100).value().getJson(JsonOptions::none)); env(pay(alice, alice, MUSO(500)), sendmax(USD(100))); auto jrr = ledgerEntryState(env, alice, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "0"); jrr = ledgerEntryRoot(env, alice); BEAST_EXPECT( jrr[jss::node][sfBalance.fieldName] == to_string((MUSO(10000) + MUSO(500) - env.current()->fees().base * 2) .MUSO())); jrr = ledgerEntryState(env, bob, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-100"); jro = ledgerEntryOffer(env, bob, bobOfferSeq); BEAST_EXPECT(jro[jss::error] == "entryNotFound"); env.require(owners(alice, 1), owners(bob, 1)); } void testCurrencyConversionIntoDebt(FeatureBitset features) { testcase("Currency Conversion: Offerer Into Debt"); using namespace jtx; Env env{*this, features}; auto const alice = Account{"alice"}; auto const bob = Account{"bob"}; auto const carol = Account{"carol"}; env.fund(MUSO(10000), alice, bob, carol); env(trust(alice, carol["EUR"](2000))); env(trust(bob, alice["USD"](100))); env(trust(carol, bob["EUR"](1000))); auto const bobOfferSeq = env.seq(bob); env(offer(bob, alice["USD"](50), carol["EUR"](200)), ter(tecUNFUNDED_OFFER)); env(offer(alice, carol["EUR"](200), alice["USD"](50))); auto jro = ledgerEntryOffer(env, bob, bobOfferSeq); BEAST_EXPECT(jro[jss::error] == "entryNotFound"); } void testCurrencyConversionInParts(FeatureBitset features) { testcase("Currency Conversion: In Parts"); using namespace jtx; Env env{*this, features}; auto const gw = Account{"gateway"}; auto const alice = Account{"alice"}; auto const bob = Account{"bob"}; auto const USD = gw["USD"]; env.fund(MUSO(10000), gw, alice, bob); env(trust(alice, USD(200))); env(trust(bob, USD(1000))); env(pay(gw, alice, alice["USD"](200))); auto const bobOfferSeq = env.seq(bob); env(offer(bob, USD(100), MUSO(500))); env(pay(alice, alice, MUSO(200)), sendmax(USD(100))); // The previous payment reduced the remaining offer amount by 200 MUSO auto jro = ledgerEntryOffer(env, bob, bobOfferSeq); BEAST_EXPECT( jro[jss::node][jss::TakerGets] == MUSO(300).value().getText()); BEAST_EXPECT( jro[jss::node][jss::TakerPays] == USD(60).value().getJson(JsonOptions::none)); // the balance between alice and gw is 160 USD..200 less the 40 taken // by the offer auto jrr = ledgerEntryState(env, alice, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-160"); // alice now has 200 more MUSO from the payment jrr = ledgerEntryRoot(env, alice); BEAST_EXPECT( jrr[jss::node][sfBalance.fieldName] == to_string((MUSO(10000) + MUSO(200) - env.current()->fees().base * 2) .MUSO())); // bob got 40 USD from partial consumption of the offer jrr = ledgerEntryState(env, bob, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-40"); // Alice converts USD to MUSO which should fail // due to PartialPayment. env(pay(alice, alice, MUSO(600)), sendmax(USD(100)), ter(tecPATH_PARTIAL)); // Alice converts USD to MUSO, should succeed because // we permit partial payment env(pay(alice, alice, MUSO(600)), sendmax(USD(100)), txflags(tfPartialPayment)); // Verify the offer was consumed jro = ledgerEntryOffer(env, bob, bobOfferSeq); BEAST_EXPECT(jro[jss::error] == "entryNotFound"); // verify balances look right after the partial payment // only 300 MUSO should be have been payed since that's all // that remained in the offer from bob. The alice balance is now // 100 USD because another 60 USD were transferred to bob in the second // payment jrr = ledgerEntryState(env, alice, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-100"); jrr = ledgerEntryRoot(env, alice); BEAST_EXPECT( jrr[jss::node][sfBalance.fieldName] == to_string((MUSO(10000) + MUSO(200) + MUSO(300) - env.current()->fees().base * 4) .MUSO())); // bob now has 100 USD - 40 from the first payment and 60 from the // second (partial) payment jrr = ledgerEntryState(env, bob, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-100"); } void testCrossCurrencyStartMUSO(FeatureBitset features) { testcase("Cross Currency Payment: Start with MUSO"); using namespace jtx; Env env{*this, features}; auto const gw = Account{"gateway"}; auto const alice = Account{"alice"}; auto const bob = Account{"bob"}; auto const carol = Account{"carol"}; auto const USD = gw["USD"]; env.fund(MUSO(10000), gw, alice, bob, carol); env(trust(carol, USD(1000))); env(trust(bob, USD(2000))); env(pay(gw, carol, carol["USD"](500))); auto const carolOfferSeq = env.seq(carol); env(offer(carol, MUSO(500), USD(50))); env(pay(alice, bob, USD(25)), sendmax(MUSO(333))); auto jrr = ledgerEntryState(env, bob, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-25"); jrr = ledgerEntryState(env, carol, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-475"); auto jro = ledgerEntryOffer(env, carol, carolOfferSeq); BEAST_EXPECT( jro[jss::node][jss::TakerGets] == USD(25).value().getJson(JsonOptions::none)); BEAST_EXPECT( jro[jss::node][jss::TakerPays] == MUSO(250).value().getText()); } void testCrossCurrencyEndMUSO(FeatureBitset features) { testcase("Cross Currency Payment: End with MUSO"); using namespace jtx; Env env{*this, features}; auto const gw = Account{"gateway"}; auto const alice = Account{"alice"}; auto const bob = Account{"bob"}; auto const carol = Account{"carol"}; auto const USD = gw["USD"]; env.fund(MUSO(10000), gw, alice, bob, carol); env(trust(alice, USD(1000))); env(trust(carol, USD(2000))); env(pay(gw, alice, alice["USD"](500))); auto const carolOfferSeq = env.seq(carol); env(offer(carol, USD(50), MUSO(500))); env(pay(alice, bob, MUSO(250)), sendmax(USD(333))); auto jrr = ledgerEntryState(env, alice, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-475"); jrr = ledgerEntryState(env, carol, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-25"); jrr = ledgerEntryRoot(env, bob); BEAST_EXPECT( jrr[jss::node][sfBalance.fieldName] == std::to_string( MUSO(10000).value().mantissa() + MUSO(250).value().mantissa())); auto jro = ledgerEntryOffer(env, carol, carolOfferSeq); BEAST_EXPECT( jro[jss::node][jss::TakerGets] == MUSO(250).value().getText()); BEAST_EXPECT( jro[jss::node][jss::TakerPays] == USD(25).value().getJson(JsonOptions::none)); } void testCrossCurrencyBridged(FeatureBitset features) { testcase("Cross Currency Payment: Bridged"); using namespace jtx; Env env{*this, features}; auto const gw1 = Account{"gateway_1"}; auto const gw2 = Account{"gateway_2"}; auto const alice = Account{"alice"}; auto const bob = Account{"bob"}; auto const carol = Account{"carol"}; auto const dan = Account{"dan"}; auto const USD = gw1["USD"]; auto const EUR = gw2["EUR"]; env.fund(MUSO(10000), gw1, gw2, alice, bob, carol, dan); env(trust(alice, USD(1000))); env(trust(bob, EUR(1000))); env(trust(carol, USD(1000))); env(trust(dan, EUR(1000))); env(pay(gw1, alice, alice["USD"](500))); env(pay(gw2, dan, dan["EUR"](400))); auto const carolOfferSeq = env.seq(carol); env(offer(carol, USD(50), MUSO(500))); auto const danOfferSeq = env.seq(dan); env(offer(dan, MUSO(500), EUR(50))); Json::Value jtp{Json::arrayValue}; jtp[0u][0u][jss::currency] = "MUSO"; env(pay(alice, bob, EUR(30)), json(jss::Paths, jtp), sendmax(USD(333))); auto jrr = ledgerEntryState(env, alice, gw1, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "470"); jrr = ledgerEntryState(env, bob, gw2, "EUR"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-30"); jrr = ledgerEntryState(env, carol, gw1, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-30"); jrr = ledgerEntryState(env, dan, gw2, "EUR"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-370"); auto jro = ledgerEntryOffer(env, carol, carolOfferSeq); BEAST_EXPECT( jro[jss::node][jss::TakerGets] == MUSO(200).value().getText()); BEAST_EXPECT( jro[jss::node][jss::TakerPays] == USD(20).value().getJson(JsonOptions::none)); jro = ledgerEntryOffer(env, dan, danOfferSeq); BEAST_EXPECT( jro[jss::node][jss::TakerGets] == gw2["EUR"](20).value().getJson(JsonOptions::none)); BEAST_EXPECT( jro[jss::node][jss::TakerPays] == MUSO(200).value().getText()); } void testBridgedSecondLegDry(FeatureBitset features) { // At least with Taker bridging, a sensitivity was identified if the // second leg goes dry before the first one. This test exercises that // case. testcase("Auto Bridged Second Leg Dry"); using namespace jtx; Env env(*this, features); Account const alice{"alice"}; Account const bob{"bob"}; Account const carol{"carol"}; Account const gw{"gateway"}; auto const USD = gw["USD"]; auto const EUR = gw["EUR"]; env.fund(MUSO(100000000), alice, bob, carol, gw); env.trust(USD(10), alice); env.close(); env(pay(gw, alice, USD(10))); env.trust(USD(10), carol); env.close(); env(pay(gw, carol, USD(3))); env(offer(alice, EUR(2), MUSO(1))); env(offer(alice, EUR(2), MUSO(1))); env(offer(alice, MUSO(1), USD(4))); env(offer(carol, MUSO(1), USD(3))); env.close(); // Bob offers to buy 10 USD for 10 EUR. // 1. He spends 2 EUR taking Alice's auto-bridged offers and // gets 4 USD for that. // 2. He spends another 2 EUR taking Alice's last EUR->MUSO offer and // Carol's MUSO-USD offer. He gets 3 USD for that. // The key for this test is that Alice's MUSO->USD leg goes dry before // Alice's EUR->MUSO. The MUSO->USD leg is the second leg which showed // some sensitivity. env.trust(EUR(10), bob); env.close(); env(pay(gw, bob, EUR(10))); env.close(); env(offer(bob, USD(10), EUR(10))); env.close(); env.require(balance(bob, USD(7))); env.require(balance(bob, EUR(6))); env.require(offers(bob, 1)); env.require(owners(bob, 3)); env.require(balance(alice, USD(6))); env.require(balance(alice, EUR(4))); env.require(offers(alice, 0)); env.require(owners(alice, 2)); env.require(balance(carol, USD(0))); env.require(balance(carol, EUR(none))); // If neither featureFlowCross nor fixTakerDryOfferRemoval are defined // then carol's offer will be left on the books, but with zero value. int const emptyOfferCount{ features[featureFlowCross] || features[fixTakerDryOfferRemoval] ? 0 : 1}; env.require(offers(carol, 0 + emptyOfferCount)); env.require(owners(carol, 1 + emptyOfferCount)); } void testOfferFeesConsumeFunds(FeatureBitset features) { testcase("Offer Fees Consume Funds"); using namespace jtx; Env env{*this, features}; auto const gw1 = Account{"gateway_1"}; auto const gw2 = Account{"gateway_2"}; auto const gw3 = Account{"gateway_3"}; auto const alice = Account{"alice"}; auto const bob = Account{"bob"}; auto const USD1 = gw1["USD"]; auto const USD2 = gw2["USD"]; auto const USD3 = gw3["USD"]; // Provide micro amounts to compensate for fees to make results round // nice. // reserve: Alice has 3 entries in the ledger, via trust lines // fees: // 1 for each trust limit == 3 (alice < mtgox/amazon/bitstamp) + // 1 for payment == 4 auto const starting_MUSO = MUSO(100) + env.current()->fees().accountReserve(3) + env.current()->fees().base * 4; env.fund(starting_MUSO, gw1, gw2, gw3, alice, bob); env(trust(alice, USD1(1000))); env(trust(alice, USD2(1000))); env(trust(alice, USD3(1000))); env(trust(bob, USD1(1000))); env(trust(bob, USD2(1000))); env(pay(gw1, bob, bob["USD"](500))); env(offer(bob, MUSO(200), USD1(200))); // Alice has 350 fees - a reserve of 50 = 250 reserve = 100 available. // Ask for more than available to prove reserve works. env(offer(alice, USD1(200), MUSO(200))); auto jrr = ledgerEntryState(env, alice, gw1, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "100"); jrr = ledgerEntryRoot(env, alice); BEAST_EXPECT( jrr[jss::node][sfBalance.fieldName] == MUSO(350).value().getText()); jrr = ledgerEntryState(env, bob, gw1, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-400"); } void testOfferCreateThenCross(FeatureBitset features) { testcase("Offer Create, then Cross"); using namespace jtx; Env env{*this, features}; auto const gw = Account{"gateway"}; auto const alice = Account{"alice"}; auto const bob = Account{"bob"}; auto const USD = gw["USD"]; env.fund(MUSO(10000), gw, alice, bob); env(rate(gw, 1.005)); env(trust(alice, USD(1000))); env(trust(bob, USD(1000))); env(trust(gw, alice["USD"](50))); env(pay(gw, bob, bob["USD"](1))); env(pay(alice, gw, USD(50))); env(trust(gw, alice["USD"](0))); env(offer(alice, USD(50), MUSO(150000))); env(offer(bob, MUSO(100), USD(0.1))); auto jrr = ledgerEntryState(env, alice, gw, "USD"); BEAST_EXPECT( jrr[jss::node][sfBalance.fieldName][jss::value] == "49.96666666666667"); jrr = ledgerEntryState(env, bob, gw, "USD"); BEAST_EXPECT( jrr[jss::node][sfBalance.fieldName][jss::value] == "-0.966500000033334"); } void testSellFlagBasic(FeatureBitset features) { testcase("Offer tfSell: Basic Sell"); using namespace jtx; Env env{*this, features}; auto const gw = Account{"gateway"}; auto const alice = Account{"alice"}; auto const bob = Account{"bob"}; auto const USD = gw["USD"]; auto const starting_MUSO = MUSO(100) + env.current()->fees().accountReserve(1) + env.current()->fees().base * 2; env.fund(starting_MUSO, gw, alice, bob); env(trust(alice, USD(1000))); env(trust(bob, USD(1000))); env(pay(gw, bob, bob["USD"](500))); env(offer(bob, MUSO(200), USD(200)), json(jss::Flags, tfSell)); // Alice has 350 + fees - a reserve of 50 = 250 reserve = 100 available. // Alice has 350 + fees - a reserve of 50 = 250 reserve = 100 available. // Ask for more than available to prove reserve works. env(offer(alice, USD(200), MUSO(200)), json(jss::Flags, tfSell)); auto jrr = ledgerEntryState(env, alice, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-100"); jrr = ledgerEntryRoot(env, alice); BEAST_EXPECT( jrr[jss::node][sfBalance.fieldName] == MUSO(250).value().getText()); jrr = ledgerEntryState(env, bob, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-400"); } void testSellFlagExceedLimit(FeatureBitset features) { testcase("Offer tfSell: 2x Sell Exceed Limit"); using namespace jtx; Env env{*this, features}; auto const gw = Account{"gateway"}; auto const alice = Account{"alice"}; auto const bob = Account{"bob"}; auto const USD = gw["USD"]; auto const starting_MUSO = MUSO(100) + env.current()->fees().accountReserve(1) + env.current()->fees().base * 2; env.fund(starting_MUSO, gw, alice, bob); env(trust(alice, USD(150))); env(trust(bob, USD(1000))); env(pay(gw, bob, bob["USD"](500))); env(offer(bob, MUSO(100), USD(200))); // Alice has 350 fees - a reserve of 50 = 250 reserve = 100 available. // Ask for more than available to prove reserve works. // Taker pays 100 USD for 100 MUSO. // Selling MUSO. // Will sell all 100 MUSO and get more USD than asked for. env(offer(alice, USD(100), MUSO(100)), json(jss::Flags, tfSell)); auto jrr = ledgerEntryState(env, alice, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-200"); jrr = ledgerEntryRoot(env, alice); BEAST_EXPECT( jrr[jss::node][sfBalance.fieldName] == MUSO(250).value().getText()); jrr = ledgerEntryState(env, bob, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-300"); } void testGatewayCrossCurrency(FeatureBitset features) { testcase("Client Issue #535: Gateway Cross Currency"); using namespace jtx; Env env{*this, features}; auto const gw = Account{"gateway"}; auto const alice = Account{"alice"}; auto const bob = Account{"bob"}; auto const XTS = gw["XTS"]; auto const XXX = gw["XXX"]; auto const starting_MUSO = MUSO(100.1) + env.current()->fees().accountReserve(1) + env.current()->fees().base * 2; env.fund(starting_MUSO, gw, alice, bob); env(trust(alice, XTS(1000))); env(trust(alice, XXX(1000))); env(trust(bob, XTS(1000))); env(trust(bob, XXX(1000))); env(pay(gw, alice, alice["XTS"](100))); env(pay(gw, alice, alice["XXX"](100))); env(pay(gw, bob, bob["XTS"](100))); env(pay(gw, bob, bob["XXX"](100))); env(offer(alice, XTS(100), XXX(100))); // WS client is used here because the RPC client could not // be convinced to pass the build_path argument auto wsc = makeWSClient(env.app().config()); Json::Value payment; payment[jss::secret] = toBase58(generateSeed("bob")); payment[jss::id] = env.seq(bob); payment[jss::build_path] = true; payment[jss::tx_json] = pay(bob, bob, bob["XXX"](1)); payment[jss::tx_json][jss::Sequence] = env.current() ->read(keylet::account(bob.id())) ->getFieldU32(sfSequence); payment[jss::tx_json][jss::Fee] = to_string(env.current()->fees().base); payment[jss::tx_json][jss::SendMax] = bob["XTS"](1.5).value().getJson(JsonOptions::none); auto jrr = wsc->invoke("submit", payment); BEAST_EXPECT(jrr[jss::status] == "success"); BEAST_EXPECT(jrr[jss::result][jss::engine_result] == "tesSUCCESS"); if (wsc->version() == 2) { BEAST_EXPECT( jrr.isMember(jss::jsonrpc) && jrr[jss::jsonrpc] == "2.0"); BEAST_EXPECT( jrr.isMember(jss::MUSOrpc) && jrr[jss::MUSOrpc] == "2.0"); BEAST_EXPECT(jrr.isMember(jss::id) && jrr[jss::id] == 5); } jrr = ledgerEntryState(env, alice, gw, "XTS"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-101"); jrr = ledgerEntryState(env, alice, gw, "XXX"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-99"); jrr = ledgerEntryState(env, bob, gw, "XTS"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-99"); jrr = ledgerEntryState(env, bob, gw, "XXX"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-101"); } // Helper function that validates a *defaulted* trustline: one that has // no unusual flags set and doesn't have high or low limits set. Such a // trustline may have an actual balance (it can be created automatically // if a user places an offer to acquire an IOU for which they don't have // a trust line defined). If the trustline is not defaulted then the tests // will not pass. void verifyDefaultTrustline( jtx::Env& env, jtx::Account const& account, jtx::PrettyAmount const& expectBalance) { auto const sleTrust = env.le(keylet::line(account.id(), expectBalance.value().issue())); BEAST_EXPECT(sleTrust); if (sleTrust) { Issue const issue = expectBalance.value().issue(); bool const accountLow = account.id() < issue.account; STAmount low{issue}; STAmount high{issue}; low.setIssuer(accountLow ? account.id() : issue.account); high.setIssuer(accountLow ? issue.account : account.id()); BEAST_EXPECT(sleTrust->getFieldAmount(sfLowLimit) == low); BEAST_EXPECT(sleTrust->getFieldAmount(sfHighLimit) == high); STAmount actualBalance{sleTrust->getFieldAmount(sfBalance)}; if (!accountLow) actualBalance.negate(); BEAST_EXPECT(actualBalance == expectBalance); } } void testPartialCross(FeatureBitset features) { // Test a number of different corner cases regarding adding a // possibly crossable offer to an account. The test is table // driven so it should be easy to add or remove tests. testcase("Partial Crossing"); using namespace jtx; auto const gw = Account("gateway"); auto const USD = gw["USD"]; Env env{*this, features}; env.fund(MUSO(10000000), gw); // The fee that's charged for transactions auto const f = env.current()->fees().base; // To keep things simple all offers are 1 : 1 for MUSO : USD. enum preTrustType { noPreTrust, gwPreTrust, acctPreTrust }; struct TestData { std::string account; // Account operated on STAmount fundMUSO; // Account funded with int bookAmount; // USD -> MUSO offer on the books preTrustType preTrust; // If true, pre-establish trust line int offerAmount; // Account offers this much MUSO -> USD TER tec; // Returned tec code STAmount spentMUSO; // Amount removed from fundMUSO PrettyAmount balanceUsd; // Balance on account end int offers; // Offers on account int owners; // Owners on account }; TestData const tests[]{ // acct fundMUSO bookAmt preTrust // offerAmt tec spentMUSO balanceUSD // offers owners {"ann", reserve(env, 0) + 0 * f, 1, noPreTrust, 1000, tecUNFUNDED_OFFER, f, USD(0), 0, 0}, // Account is at the reserve, and will dip below once fees are // subtracted. {"bev", reserve(env, 0) + 1 * f, 1, noPreTrust, 1000, tecUNFUNDED_OFFER, f, USD(0), 0, 0}, // Account has just enough for the reserve and the fee. {"cam", reserve(env, 0) + 2 * f, 0, noPreTrust, 1000, tecINSUF_RESERVE_OFFER, f, USD(0), 0, 0}, // Account has enough for the reserve, the fee and the offer, // and a bit more, but not enough for the reserve after the // offer is placed. {"deb", reserve(env, 0) + 2 * f, 1, noPreTrust, 1000, tesSUCCESS, 2 * f, USD(0.00001), 0, 1}, // Account has enough to buy a little USD then the offer runs // dry. {"eve", reserve(env, 1) + 0 * f, 0, noPreTrust, 1000, tesSUCCESS, f, USD(0), 1, 1}, // No offer to cross {"flo", reserve(env, 1) + 0 * f, 1, noPreTrust, 1000, tesSUCCESS, MUSO(1) + f, USD(1), 0, 1}, {"gay", reserve(env, 1) + 1 * f, 1000, noPreTrust, 1000, tesSUCCESS, MUSO(50) + f, USD(50), 0, 1}, {"hye", MUSO(1000) + 1 * f, 1000, noPreTrust, 1000, tesSUCCESS, MUSO(800) + f, USD(800), 0, 1}, {"ivy", MUSO(1) + reserve(env, 1) + 1 * f, 1, noPreTrust, 1000, tesSUCCESS, MUSO(1) + f, USD(1), 0, 1}, {"joy", MUSO(1) + reserve(env, 2) + 1 * f, 1, noPreTrust, 1000, tesSUCCESS, MUSO(1) + f, USD(1), 1, 2}, {"kim", MUSO(900) + reserve(env, 2) + 1 * f, 999, noPreTrust, 1000, tesSUCCESS, MUSO(999) + f, USD(999), 0, 1}, {"liz", MUSO(998) + reserve(env, 0) + 1 * f, 999, noPreTrust, 1000, tesSUCCESS, MUSO(998) + f, USD(998), 0, 1}, {"meg", MUSO(998) + reserve(env, 1) + 1 * f, 999, noPreTrust, 1000, tesSUCCESS, MUSO(999) + f, USD(999), 0, 1}, {"nia", MUSO(998) + reserve(env, 2) + 1 * f, 999, noPreTrust, 1000, tesSUCCESS, MUSO(999) + f, USD(999), 1, 2}, {"ova", MUSO(999) + reserve(env, 0) + 1 * f, 1000, noPreTrust, 1000, tesSUCCESS, MUSO(999) + f, USD(999), 0, 1}, {"pam", MUSO(999) + reserve(env, 1) + 1 * f, 1000, noPreTrust, 1000, tesSUCCESS, MUSO(1000) + f, USD(1000), 0, 1}, {"rae", MUSO(999) + reserve(env, 2) + 1 * f, 1000, noPreTrust, 1000, tesSUCCESS, MUSO(1000) + f, USD(1000), 0, 1}, {"sue", MUSO(1000) + reserve(env, 2) + 1 * f, 0, noPreTrust, 1000, tesSUCCESS, f, USD(0), 1, 1}, //---------------------Pre-established trust lines //----------------------------- {"abe", reserve(env, 0) + 0 * f, 1, gwPreTrust, 1000, tecUNFUNDED_OFFER, f, USD(0), 0, 0}, {"bud", reserve(env, 0) + 1 * f, 1, gwPreTrust, 1000, tecUNFUNDED_OFFER, f, USD(0), 0, 0}, {"che", reserve(env, 0) + 2 * f, 0, gwPreTrust, 1000, tecINSUF_RESERVE_OFFER, f, USD(0), 0, 0}, {"dan", reserve(env, 0) + 2 * f, 1, gwPreTrust, 1000, tesSUCCESS, 2 * f, USD(0.00001), 0, 0}, {"eli", MUSO(20) + reserve(env, 0) + 1 * f, 1000, gwPreTrust, 1000, tesSUCCESS, MUSO(20) + 1 * f, USD(20), 0, 0}, {"fyn", reserve(env, 1) + 0 * f, 0, gwPreTrust, 1000, tesSUCCESS, f, USD(0), 1, 1}, {"gar", reserve(env, 1) + 0 * f, 1, gwPreTrust, 1000, tesSUCCESS, MUSO(1) + f, USD(1), 1, 1}, {"hal", reserve(env, 1) + 1 * f, 1, gwPreTrust, 1000, tesSUCCESS, MUSO(1) + f, USD(1), 1, 1}, {"ned", reserve(env, 1) + 0 * f, 1, acctPreTrust, 1000, tecUNFUNDED_OFFER, 2 * f, USD(0), 0, 1}, {"ole", reserve(env, 1) + 1 * f, 1, acctPreTrust, 1000, tecUNFUNDED_OFFER, 2 * f, USD(0), 0, 1}, {"pat", reserve(env, 1) + 2 * f, 0, acctPreTrust, 1000, tecUNFUNDED_OFFER, 2 * f, USD(0), 0, 1}, {"quy", reserve(env, 1) + 2 * f, 1, acctPreTrust, 1000, tecUNFUNDED_OFFER, 2 * f, USD(0), 0, 1}, {"ron", reserve(env, 1) + 3 * f, 0, acctPreTrust, 1000, tecINSUF_RESERVE_OFFER, 2 * f, USD(0), 0, 1}, {"syd", reserve(env, 1) + 3 * f, 1, acctPreTrust, 1000, tesSUCCESS, 3 * f, USD(0.00001), 0, 1}, {"ted", MUSO(20) + reserve(env, 1) + 2 * f, 1000, acctPreTrust, 1000, tesSUCCESS, MUSO(20) + 2 * f, USD(20), 0, 1}, {"uli", reserve(env, 2) + 0 * f, 0, acctPreTrust, 1000, tecINSUF_RESERVE_OFFER, 2 * f, USD(0), 0, 1}, {"vic", reserve(env, 2) + 0 * f, 1, acctPreTrust, 1000, tesSUCCESS, MUSO(1) + 2 * f, USD(1), 0, 1}, {"wes", reserve(env, 2) + 1 * f, 0, acctPreTrust, 1000, tesSUCCESS, 2 * f, USD(0), 1, 2}, {"xan", reserve(env, 2) + 1 * f, 1, acctPreTrust, 1000, tesSUCCESS, MUSO(1) + 2 * f, USD(1), 1, 2}, }; for (auto const& t : tests) { auto const acct = Account(t.account); env.fund(t.fundMUSO, acct); env.close(); // Make sure gateway has no current offers. env.require(offers(gw, 0)); // The gateway optionally creates an offer that would be crossed. auto const book = t.bookAmount; if (book) env(offer(gw, MUSO(book), USD(book))); env.close(); std::uint32_t const gwOfferSeq = env.seq(gw) - 1; // Optionally pre-establish a trustline between gw and acct. if (t.preTrust == gwPreTrust) env(trust(gw, acct["USD"](1))); // Optionally pre-establish a trustline between acct and gw. // Note this is not really part of the test, so we expect there // to be enough MUSO reserve for acct to create the trust line. if (t.preTrust == acctPreTrust) env(trust(acct, USD(1))); env.close(); { // Acct creates an offer. This is the heart of the test. auto const acctOffer = t.offerAmount; env(offer(acct, USD(acctOffer), MUSO(acctOffer)), ter(t.tec)); env.close(); } std::uint32_t const acctOfferSeq = env.seq(acct) - 1; BEAST_EXPECT(env.balance(acct, USD.issue()) == t.balanceUsd); BEAST_EXPECT( env.balance(acct, MUSOIssue()) == t.fundMUSO - t.spentMUSO); env.require(offers(acct, t.offers)); env.require(owners(acct, t.owners)); auto acctOffers = offersOnAccount(env, acct); BEAST_EXPECT(acctOffers.size() == t.offers); if (acctOffers.size() && t.offers) { auto const& acctOffer = *(acctOffers.front()); auto const leftover = t.offerAmount - t.bookAmount; BEAST_EXPECT(acctOffer[sfTakerGets] == MUSO(leftover)); BEAST_EXPECT(acctOffer[sfTakerPays] == USD(leftover)); } if (t.preTrust == noPreTrust) { if (t.balanceUsd.value().signum()) { // Verify the correct contents of the trustline verifyDefaultTrustline(env, acct, t.balanceUsd); } else { // Verify that no trustline was created. auto const sleTrust = env.le(keylet::line(acct, USD.issue())); BEAST_EXPECT(!sleTrust); } } // Give the next loop a clean slate by canceling any left-overs // in the offers. env(offer_cancel(acct, acctOfferSeq)); env(offer_cancel(gw, gwOfferSeq)); env.close(); } } void testMUSODirectCross(FeatureBitset features) { testcase("MUSO Direct Crossing"); using namespace jtx; auto const gw = Account("gateway"); auto const alice = Account("alice"); auto const bob = Account("bob"); auto const USD = gw["USD"]; auto const usdOffer = USD(1000); auto const MUSOOffer = MUSO(1000); Env env{*this, features}; env.fund(MUSO(1000000), gw, bob); env.close(); // The fee that's charged for transactions. auto const fee = env.current()->fees().base; // alice's account has enough for the reserve, one trust line plus two // offers, and two fees. env.fund(reserve(env, 2) + fee * 2, alice); env.close(); env(trust(alice, usdOffer)); env.close(); env(pay(gw, alice, usdOffer)); env.close(); env.require(balance(alice, usdOffer), offers(alice, 0), offers(bob, 0)); // The scenario: // o alice has USD but wants MUSO. // o bob has MUSO but wants USD. auto const alicesMUSO = env.balance(alice); auto const bobsMUSO = env.balance(bob); env(offer(alice, MUSOOffer, usdOffer)); env.close(); env(offer(bob, usdOffer, MUSOOffer)); env.close(); env.require( balance(alice, USD(0)), balance(bob, usdOffer), balance(alice, alicesMUSO + MUSOOffer - fee), balance(bob, bobsMUSO - MUSOOffer - fee), offers(alice, 0), offers(bob, 0)); verifyDefaultTrustline(env, bob, usdOffer); // Make two more offers that leave one of the offers non-dry. env(offer(alice, USD(999), MUSO(999))); env(offer(bob, MUSOOffer, usdOffer)); env.close(); env.require(balance(alice, USD(999))); env.require(balance(bob, USD(1))); env.require(offers(alice, 0)); verifyDefaultTrustline(env, bob, USD(1)); { auto const bobsOffers = offersOnAccount(env, bob); BEAST_EXPECT(bobsOffers.size() == 1); auto const& bobsOffer = *(bobsOffers.front()); BEAST_EXPECT(bobsOffer[sfLedgerEntryType] == ltOFFER); BEAST_EXPECT(bobsOffer[sfTakerGets] == USD(1)); BEAST_EXPECT(bobsOffer[sfTakerPays] == MUSO(1)); } } void testDirectCross(FeatureBitset features) { testcase("Direct Crossing"); using namespace jtx; auto const gw = Account("gateway"); auto const alice = Account("alice"); auto const bob = Account("bob"); auto const USD = gw["USD"]; auto const EUR = gw["EUR"]; auto const usdOffer = USD(1000); auto const eurOffer = EUR(1000); Env env{*this, features}; env.fund(MUSO(1000000), gw); env.close(); // The fee that's charged for transactions. auto const fee = env.current()->fees().base; // Each account has enough for the reserve, two trust lines, one // offer, and two fees. env.fund(reserve(env, 3) + fee * 3, alice); env.fund(reserve(env, 3) + fee * 2, bob); env.close(); env(trust(alice, usdOffer)); env(trust(bob, eurOffer)); env.close(); env(pay(gw, alice, usdOffer)); env(pay(gw, bob, eurOffer)); env.close(); env.require(balance(alice, usdOffer), balance(bob, eurOffer)); // The scenario: // o alice has USD but wants EUR. // o bob has EUR but wants USD. env(offer(alice, eurOffer, usdOffer)); env(offer(bob, usdOffer, eurOffer)); env.close(); env.require( balance(alice, eurOffer), balance(bob, usdOffer), offers(alice, 0), offers(bob, 0)); // Alice's offer crossing created a default EUR trustline and // Bob's offer crossing created a default USD trustline: verifyDefaultTrustline(env, alice, eurOffer); verifyDefaultTrustline(env, bob, usdOffer); // Make two more offers that leave one of the offers non-dry. // Guarantee the order of application by putting a close() // between them. env(offer(bob, eurOffer, usdOffer)); env.close(); env(offer(alice, USD(999), eurOffer)); env.close(); env.require(offers(alice, 0)); env.require(offers(bob, 1)); env.require(balance(alice, USD(999))); env.require(balance(alice, EUR(1))); env.require(balance(bob, USD(1))); env.require(balance(bob, EUR(999))); { auto bobsOffers = offersOnAccount(env, bob); if (BEAST_EXPECT(bobsOffers.size() == 1)) { auto const& bobsOffer = *(bobsOffers.front()); BEAST_EXPECT(bobsOffer[sfTakerGets] == USD(1)); BEAST_EXPECT(bobsOffer[sfTakerPays] == EUR(1)); } } // alice makes one more offer that cleans out bob's offer. env(offer(alice, USD(1), EUR(1))); env.close(); env.require(balance(alice, USD(1000))); env.require(balance(alice, EUR(none))); env.require(balance(bob, USD(none))); env.require(balance(bob, EUR(1000))); env.require(offers(alice, 0)); env.require(offers(bob, 0)); // The two trustlines that were generated by offers should be gone. BEAST_EXPECT(!env.le(keylet::line(alice.id(), EUR.issue()))); BEAST_EXPECT(!env.le(keylet::line(bob.id(), USD.issue()))); // Make two more offers that leave one of the offers non-dry. We // need to properly sequence the transactions: env(offer(alice, EUR(999), usdOffer)); env.close(); env(offer(bob, usdOffer, eurOffer)); env.close(); env.require(offers(alice, 0)); env.require(offers(bob, 0)); env.require(balance(alice, USD(0))); env.require(balance(alice, EUR(999))); env.require(balance(bob, USD(1000))); env.require(balance(bob, EUR(1))); } void testBridgedCross(FeatureBitset features) { testcase("Bridged Crossing"); using namespace jtx; auto const gw = Account("gateway"); auto const alice = Account("alice"); auto const bob = Account("bob"); auto const carol = Account("carol"); auto const USD = gw["USD"]; auto const EUR = gw["EUR"]; auto const usdOffer = USD(1000); auto const eurOffer = EUR(1000); Env env{*this, features}; env.fund(MUSO(1000000), gw, alice, bob, carol); env.close(); env(trust(alice, usdOffer)); env(trust(carol, eurOffer)); env.close(); env(pay(gw, alice, usdOffer)); env(pay(gw, carol, eurOffer)); env.close(); // The scenario: // o alice has USD but wants XPR. // o bob has MUSO but wants EUR. // o carol has EUR but wants USD. // Note that carol's offer must come last. If carol's offer is placed // before bob's or alice's, then autobridging will not occur. env(offer(alice, MUSO(1000), usdOffer)); env(offer(bob, eurOffer, MUSO(1000))); auto const bobMUSOBalance = env.balance(bob); env.close(); // carol makes an offer that partially consumes alice and bob's offers. env(offer(carol, USD(400), EUR(400))); env.close(); env.require( balance(alice, USD(600)), balance(bob, EUR(400)), balance(carol, USD(400)), balance(bob, bobMUSOBalance - MUSO(400)), offers(carol, 0)); verifyDefaultTrustline(env, bob, EUR(400)); verifyDefaultTrustline(env, carol, USD(400)); { auto const alicesOffers = offersOnAccount(env, alice); BEAST_EXPECT(alicesOffers.size() == 1); auto const& alicesOffer = *(alicesOffers.front()); BEAST_EXPECT(alicesOffer[sfLedgerEntryType] == ltOFFER); BEAST_EXPECT(alicesOffer[sfTakerGets] == USD(600)); BEAST_EXPECT(alicesOffer[sfTakerPays] == MUSO(600)); } { auto const bobsOffers = offersOnAccount(env, bob); BEAST_EXPECT(bobsOffers.size() == 1); auto const& bobsOffer = *(bobsOffers.front()); BEAST_EXPECT(bobsOffer[sfLedgerEntryType] == ltOFFER); BEAST_EXPECT(bobsOffer[sfTakerGets] == MUSO(600)); BEAST_EXPECT(bobsOffer[sfTakerPays] == EUR(600)); } // carol makes an offer that exactly consumes alice and bob's offers. env(offer(carol, USD(600), EUR(600))); env.close(); env.require( balance(alice, USD(0)), balance(bob, eurOffer), balance(carol, usdOffer), balance(bob, bobMUSOBalance - MUSO(1000)), offers(bob, 0), offers(carol, 0)); verifyDefaultTrustline(env, bob, EUR(1000)); verifyDefaultTrustline(env, carol, USD(1000)); // In pre-flow code alice's offer is left empty in the ledger. auto const alicesOffers = offersOnAccount(env, alice); if (alicesOffers.size() != 0) { BEAST_EXPECT(alicesOffers.size() == 1); auto const& alicesOffer = *(alicesOffers.front()); BEAST_EXPECT(alicesOffer[sfLedgerEntryType] == ltOFFER); BEAST_EXPECT(alicesOffer[sfTakerGets] == USD(0)); BEAST_EXPECT(alicesOffer[sfTakerPays] == MUSO(0)); } } void testSellOffer(FeatureBitset features) { // Test a number of different corner cases regarding offer crossing // when the tfSell flag is set. The test is table driven so it // should be easy to add or remove tests. testcase("Sell Offer"); using namespace jtx; auto const gw = Account("gateway"); auto const USD = gw["USD"]; Env env{*this, features}; env.fund(MUSO(10000000), gw); // The fee that's charged for transactions auto const f = env.current()->fees().base; // To keep things simple all offers are 1 : 1 for MUSO : USD. enum preTrustType { noPreTrust, gwPreTrust, acctPreTrust }; struct TestData { std::string account; // Account operated on STAmount fundMUSO; // MUSO acct funded with STAmount fundUSD; // USD acct funded with STAmount gwGets; // gw's offer STAmount gwPays; // STAmount acctGets; // acct's offer STAmount acctPays; // TER tec; // Returned tec code STAmount spentMUSO; // Amount removed from fundMUSO STAmount finalUsd; // Final USD balance on acct int offers; // Offers on acct int owners; // Owners on acct STAmount takerGets; // Remainder of acct's offer STAmount takerPays; // // Constructor with takerGets/takerPays TestData( std::string&& account_, // Account operated on STAmount const& fundMUSO_, // MUSO acct funded with STAmount const& fundUSD_, // USD acct funded with STAmount const& gwGets_, // gw's offer STAmount const& gwPays_, // STAmount const& acctGets_, // acct's offer STAmount const& acctPays_, // TER tec_, // Returned tec code STAmount const& spentMUSO_, // Amount removed from fundMUSO STAmount const& finalUsd_, // Final USD balance on acct int offers_, // Offers on acct int owners_, // Owners on acct STAmount const& takerGets_, // Remainder of acct's offer STAmount const& takerPays_) // : account(std::move(account_)) , fundMUSO(fundMUSO_) , fundUSD(fundUSD_) , gwGets(gwGets_) , gwPays(gwPays_) , acctGets(acctGets_) , acctPays(acctPays_) , tec(tec_) , spentMUSO(spentMUSO_) , finalUsd(finalUsd_) , offers(offers_) , owners(owners_) , takerGets(takerGets_) , takerPays(takerPays_) { } // Constructor without takerGets/takerPays TestData( std::string&& account_, // Account operated on STAmount const& fundMUSO_, // MUSO acct funded with STAmount const& fundUSD_, // USD acct funded with STAmount const& gwGets_, // gw's offer STAmount const& gwPays_, // STAmount const& acctGets_, // acct's offer STAmount const& acctPays_, // TER tec_, // Returned tec code STAmount const& spentMUSO_, // Amount removed from fundMUSO STAmount const& finalUsd_, // Final USD balance on acct int offers_, // Offers on acct int owners_) // Owners on acct : TestData( std::move(account_), fundMUSO_, fundUSD_, gwGets_, gwPays_, acctGets_, acctPays_, tec_, spentMUSO_, finalUsd_, offers_, owners_, STAmount{0}, STAmount{0}) { } }; TestData const tests[]{ // acct pays MUSO // acct fundMUSO fundUSD gwGets gwPays // acctGets acctPays tec spentMUSO // finalUSD offers owners takerGets takerPays {"ann", MUSO(10) + reserve(env, 0) + 1 * f, USD(0), MUSO(10), USD(5), USD(10), MUSO(10), tecINSUF_RESERVE_OFFER, MUSO(0) + (1 * f), USD(0), 0, 0}, {"bev", MUSO(10) + reserve(env, 1) + 1 * f, USD(0), MUSO(10), USD(5), USD(10), MUSO(10), tesSUCCESS, MUSO(0) + (1 * f), USD(0), 1, 1, MUSO(10), USD(10)}, {"cam", MUSO(10) + reserve(env, 0) + 1 * f, USD(0), MUSO(10), USD(10), USD(10), MUSO(10), tesSUCCESS, MUSO(10) + (1 * f), USD(10), 0, 1}, {"deb", MUSO(10) + reserve(env, 0) + 1 * f, USD(0), MUSO(10), USD(20), USD(10), MUSO(10), tesSUCCESS, MUSO(10) + (1 * f), USD(20), 0, 1}, {"eve", MUSO(10) + reserve(env, 0) + 1 * f, USD(0), MUSO(10), USD(20), USD(5), MUSO(5), tesSUCCESS, MUSO(5) + (1 * f), USD(10), 0, 1}, {"flo", MUSO(10) + reserve(env, 0) + 1 * f, USD(0), MUSO(10), USD(20), USD(20), MUSO(20), tesSUCCESS, MUSO(10) + (1 * f), USD(20), 0, 1}, {"gay", MUSO(20) + reserve(env, 1) + 1 * f, USD(0), MUSO(10), USD(20), USD(20), MUSO(20), tesSUCCESS, MUSO(10) + (1 * f), USD(20), 0, 1}, {"hye", MUSO(20) + reserve(env, 2) + 1 * f, USD(0), MUSO(10), USD(20), USD(20), MUSO(20), tesSUCCESS, MUSO(10) + (1 * f), USD(20), 1, 2, MUSO(10), USD(10)}, // acct pays USD {"meg", reserve(env, 1) + 2 * f, USD(10), USD(10), MUSO(5), MUSO(10), USD(10), tecINSUF_RESERVE_OFFER, MUSO(0) + (2 * f), USD(10), 0, 1}, {"nia", reserve(env, 2) + 2 * f, USD(10), USD(10), MUSO(5), MUSO(10), USD(10), tesSUCCESS, MUSO(0) + (2 * f), USD(10), 1, 2, USD(10), MUSO(10)}, {"ova", reserve(env, 1) + 2 * f, USD(10), USD(10), MUSO(10), MUSO(10), USD(10), tesSUCCESS, MUSO(-10) + (2 * f), USD(0), 0, 1}, {"pam", reserve(env, 1) + 2 * f, USD(10), USD(10), MUSO(20), MUSO(10), USD(10), tesSUCCESS, MUSO(-20) + (2 * f), USD(0), 0, 1}, {"qui", reserve(env, 1) + 2 * f, USD(10), USD(20), MUSO(40), MUSO(10), USD(10), tesSUCCESS, MUSO(-20) + (2 * f), USD(0), 0, 1}, {"rae", reserve(env, 2) + 2 * f, USD(10), USD(5), MUSO(5), MUSO(10), USD(10), tesSUCCESS, MUSO(-5) + (2 * f), USD(5), 1, 2, USD(5), MUSO(5)}, {"sue", reserve(env, 2) + 2 * f, USD(10), USD(5), MUSO(10), MUSO(10), USD(10), tesSUCCESS, MUSO(-10) + (2 * f), USD(5), 1, 2, USD(5), MUSO(5)}, }; auto const zeroUsd = USD(0); for (auto const& t : tests) { // Make sure gateway has no current offers. env.require(offers(gw, 0)); auto const acct = Account(t.account); env.fund(t.fundMUSO, acct); env.close(); // Optionally give acct some USD. This is not part of the test, // so we assume that acct has sufficient USD to cover the reserve // on the trust line. if (t.fundUSD != zeroUsd) { env(trust(acct, t.fundUSD)); env.close(); env(pay(gw, acct, t.fundUSD)); env.close(); } env(offer(gw, t.gwGets, t.gwPays)); env.close(); std::uint32_t const gwOfferSeq = env.seq(gw) - 1; // Acct creates a tfSell offer. This is the heart of the test. env(offer(acct, t.acctGets, t.acctPays, tfSell), ter(t.tec)); env.close(); std::uint32_t const acctOfferSeq = env.seq(acct) - 1; // Check results BEAST_EXPECT(env.balance(acct, USD.issue()) == t.finalUsd); BEAST_EXPECT( env.balance(acct, MUSOIssue()) == t.fundMUSO - t.spentMUSO); env.require(offers(acct, t.offers)); env.require(owners(acct, t.owners)); if (t.offers) { auto const acctOffers = offersOnAccount(env, acct); if (acctOffers.size() > 0) { BEAST_EXPECT(acctOffers.size() == 1); auto const& acctOffer = *(acctOffers.front()); BEAST_EXPECT(acctOffer[sfLedgerEntryType] == ltOFFER); BEAST_EXPECT(acctOffer[sfTakerGets] == t.takerGets); BEAST_EXPECT(acctOffer[sfTakerPays] == t.takerPays); } } // Give the next loop a clean slate by canceling any left-overs // in the offers. env(offer_cancel(acct, acctOfferSeq)); env(offer_cancel(gw, gwOfferSeq)); env.close(); } } void testSellWithFillOrKill(FeatureBitset features) { // Test a number of different corner cases regarding offer crossing // when both the tfSell flag and tfFillOrKill flags are set. testcase("Combine tfSell with tfFillOrKill"); using namespace jtx; auto const gw = Account("gateway"); auto const alice = Account("alice"); auto const bob = Account("bob"); auto const USD = gw["USD"]; Env env{*this, features}; env.fund(MUSO(10000000), gw, alice, bob); // Code returned if an offer is killed. TER const killedCode{ features[fix1578] ? TER{tecKILLED} : TER{tesSUCCESS}}; // bob offers MUSO for USD. env(trust(bob, USD(200))); env.close(); env(pay(gw, bob, USD(100))); env.close(); env(offer(bob, MUSO(2000), USD(20))); env.close(); { // alice submits a tfSell | tfFillOrKill offer that does not cross. env(offer(alice, USD(21), MUSO(2100), tfSell | tfFillOrKill), ter(killedCode)); env.close(); env.require(balance(alice, USD(none))); env.require(offers(alice, 0)); env.require(balance(bob, USD(100))); } { // alice submits a tfSell | tfFillOrKill offer that crosses. // Even though tfSell is present it doesn't matter this time. env(offer(alice, USD(20), MUSO(2000), tfSell | tfFillOrKill)); env.close(); env.require(balance(alice, USD(20))); env.require(offers(alice, 0)); env.require(balance(bob, USD(80))); } { // alice submits a tfSell | tfFillOrKill offer that crosses and // returns more than was asked for (because of the tfSell flag). env(offer(bob, MUSO(2000), USD(20))); env.close(); env(offer(alice, USD(10), MUSO(1500), tfSell | tfFillOrKill)); env.close(); env.require(balance(alice, USD(35))); env.require(offers(alice, 0)); env.require(balance(bob, USD(65))); } { // alice submits a tfSell | tfFillOrKill offer that doesn't cross. // This would have succeeded with a regular tfSell, but the // fillOrKill prevents the transaction from crossing since not // all of the offer is consumed. // We're using bob's left-over offer for MUSO(500), USD(5) env(offer(alice, USD(1), MUSO(501), tfSell | tfFillOrKill), ter(killedCode)); env.close(); env.require(balance(alice, USD(35))); env.require(offers(alice, 0)); env.require(balance(bob, USD(65))); } { // Alice submits a tfSell | tfFillOrKill offer that finishes // off the remainder of bob's offer. // We're using bob's left-over offer for MUSO(500), USD(5) env(offer(alice, USD(1), MUSO(500), tfSell | tfFillOrKill)); env.close(); env.require(balance(alice, USD(40))); env.require(offers(alice, 0)); env.require(balance(bob, USD(60))); } } void testTransferRateOffer(FeatureBitset features) { testcase("Transfer Rate Offer"); using namespace jtx; auto const gw1 = Account("gateway1"); auto const USD = gw1["USD"]; Env env{*this, features}; // The fee that's charged for transactions. auto const fee = env.current()->fees().base; env.fund(MUSO(100000), gw1); env.close(); env(rate(gw1, 1.25)); { auto const ann = Account("ann"); auto const bob = Account("bob"); env.fund(MUSO(100) + reserve(env, 2) + (fee * 2), ann, bob); env.close(); env(trust(ann, USD(200))); env(trust(bob, USD(200))); env.close(); env(pay(gw1, bob, USD(125))); env.close(); // bob offers to sell USD(100) for MUSO. alice takes bob's offer. // Notice that although bob only offered USD(100), USD(125) was // removed from his account due to the gateway fee. // // A comparable payment would look like this: // env (pay (bob, alice, USD(100)), sendmax(USD(125))) env(offer(bob, MUSO(1), USD(100))); env.close(); env(offer(ann, USD(100), MUSO(1))); env.close(); env.require(balance(ann, USD(100))); env.require(balance(ann, MUSO(99) + reserve(env, 2))); env.require(offers(ann, 0)); env.require(balance(bob, USD(0))); env.require(balance(bob, MUSO(101) + reserve(env, 2))); env.require(offers(bob, 0)); } { // Reverse the order, so the offer in the books is to sell MUSO // in return for USD. Gateway rate should still apply identically. auto const che = Account("che"); auto const deb = Account("deb"); env.fund(MUSO(100) + reserve(env, 2) + (fee * 2), che, deb); env.close(); env(trust(che, USD(200))); env(trust(deb, USD(200))); env.close(); env(pay(gw1, deb, USD(125))); env.close(); env(offer(che, USD(100), MUSO(1))); env.close(); env(offer(deb, MUSO(1), USD(100))); env.close(); env.require(balance(che, USD(100))); env.require(balance(che, MUSO(99) + reserve(env, 2))); env.require(offers(che, 0)); env.require(balance(deb, USD(0))); env.require(balance(deb, MUSO(101) + reserve(env, 2))); env.require(offers(deb, 0)); } { auto const eve = Account("eve"); auto const fyn = Account("fyn"); env.fund(MUSO(20000) + (fee * 2), eve, fyn); env.close(); env(trust(eve, USD(1000))); env(trust(fyn, USD(1000))); env.close(); env(pay(gw1, eve, USD(100))); env(pay(gw1, fyn, USD(100))); env.close(); // This test verifies that the amount removed from an offer // accounts for the transfer fee that is removed from the // account but not from the remaining offer. env(offer(eve, USD(10), MUSO(4000))); env.close(); std::uint32_t const eveOfferSeq = env.seq(eve) - 1; env(offer(fyn, MUSO(2000), USD(5))); env.close(); env.require(balance(eve, USD(105))); env.require(balance(eve, MUSO(18000))); auto const evesOffers = offersOnAccount(env, eve); BEAST_EXPECT(evesOffers.size() == 1); if (evesOffers.size() != 0) { auto const& evesOffer = *(evesOffers.front()); BEAST_EXPECT(evesOffer[sfLedgerEntryType] == ltOFFER); BEAST_EXPECT(evesOffer[sfTakerGets] == MUSO(2000)); BEAST_EXPECT(evesOffer[sfTakerPays] == USD(5)); } env(offer_cancel(eve, eveOfferSeq)); // For later tests env.require(balance(fyn, USD(93.75))); env.require(balance(fyn, MUSO(22000))); env.require(offers(fyn, 0)); } // Start messing with two non-native currencies. auto const gw2 = Account("gateway2"); auto const EUR = gw2["EUR"]; env.fund(MUSO(100000), gw2); env.close(); env(rate(gw2, 1.5)); { // Remove MUSO from the equation. Give the two currencies two // different transfer rates so we can see both transfer rates // apply in the same transaction. auto const gay = Account("gay"); auto const hal = Account("hal"); env.fund(reserve(env, 3) + (fee * 3), gay, hal); env.close(); env(trust(gay, USD(200))); env(trust(gay, EUR(200))); env(trust(hal, USD(200))); env(trust(hal, EUR(200))); env.close(); env(pay(gw1, gay, USD(125))); env(pay(gw2, hal, EUR(150))); env.close(); env(offer(gay, EUR(100), USD(100))); env.close(); env(offer(hal, USD(100), EUR(100))); env.close(); env.require(balance(gay, USD(0))); env.require(balance(gay, EUR(100))); env.require(balance(gay, reserve(env, 3))); env.require(offers(gay, 0)); env.require(balance(hal, USD(100))); env.require(balance(hal, EUR(0))); env.require(balance(hal, reserve(env, 3))); env.require(offers(hal, 0)); } { // A trust line's QualityIn should not affect offer crossing. auto const ivy = Account("ivy"); auto const joe = Account("joe"); env.fund(reserve(env, 3) + (fee * 3), ivy, joe); env.close(); env(trust(ivy, USD(400)), qualityInPercent(90)); env(trust(ivy, EUR(400)), qualityInPercent(80)); env(trust(joe, USD(400)), qualityInPercent(70)); env(trust(joe, EUR(400)), qualityInPercent(60)); env.close(); env(pay(gw1, ivy, USD(270)), sendmax(USD(500))); env(pay(gw2, joe, EUR(150)), sendmax(EUR(300))); env.close(); env.require(balance(ivy, USD(300))); env.require(balance(joe, EUR(250))); env(offer(ivy, EUR(100), USD(200))); env.close(); env(offer(joe, USD(200), EUR(100))); env.close(); env.require(balance(ivy, USD(50))); env.require(balance(ivy, EUR(100))); env.require(balance(ivy, reserve(env, 3))); env.require(offers(ivy, 0)); env.require(balance(joe, USD(200))); env.require(balance(joe, EUR(100))); env.require(balance(joe, reserve(env, 3))); env.require(offers(joe, 0)); } { // A trust line's QualityOut should not affect offer crossing. auto const kim = Account("kim"); auto const K_BUX = kim["BUX"]; auto const lex = Account("lex"); auto const meg = Account("meg"); auto const ned = Account("ned"); auto const N_BUX = ned["BUX"]; // Verify trust line QualityOut affects payments. env.fund(reserve(env, 4) + (fee * 4), kim, lex, meg, ned); env.close(); env(trust(lex, K_BUX(400))); env(trust(lex, N_BUX(200)), qualityOutPercent(120)); env(trust(meg, N_BUX(100))); env.close(); env(pay(ned, lex, N_BUX(100))); env.close(); env.require(balance(lex, N_BUX(100))); env(pay(kim, meg, N_BUX(60)), path(lex, ned), sendmax(K_BUX(200))); env.close(); env.require(balance(kim, K_BUX(none))); env.require(balance(kim, N_BUX(none))); env.require(balance(lex, K_BUX(72))); env.require(balance(lex, N_BUX(40))); env.require(balance(meg, K_BUX(none))); env.require(balance(meg, N_BUX(60))); env.require(balance(ned, K_BUX(none))); env.require(balance(ned, N_BUX(none))); // Now verify that offer crossing is unaffected by QualityOut. env(offer(lex, K_BUX(30), N_BUX(30))); env.close(); env(offer(kim, N_BUX(30), K_BUX(30))); env.close(); env.require(balance(kim, K_BUX(none))); env.require(balance(kim, N_BUX(30))); env.require(balance(lex, K_BUX(102))); env.require(balance(lex, N_BUX(10))); env.require(balance(meg, K_BUX(none))); env.require(balance(meg, N_BUX(60))); env.require(balance(ned, K_BUX(-30))); env.require(balance(ned, N_BUX(none))); } { // Make sure things work right when we're auto-bridging as well. auto const ova = Account("ova"); auto const pat = Account("pat"); auto const qae = Account("qae"); env.fund(MUSO(2) + reserve(env, 3) + (fee * 3), ova, pat, qae); env.close(); // o ova has USD but wants XPR. // o pat has MUSO but wants EUR. // o qae has EUR but wants USD. env(trust(ova, USD(200))); env(trust(ova, EUR(200))); env(trust(pat, USD(200))); env(trust(pat, EUR(200))); env(trust(qae, USD(200))); env(trust(qae, EUR(200))); env.close(); env(pay(gw1, ova, USD(125))); env(pay(gw2, qae, EUR(150))); env.close(); env(offer(ova, MUSO(2), USD(100))); env(offer(pat, EUR(100), MUSO(2))); env.close(); env(offer(qae, USD(100), EUR(100))); env.close(); env.require(balance(ova, USD(0))); env.require(balance(ova, EUR(0))); env.require(balance(ova, MUSO(4) + reserve(env, 3))); // In pre-flow code ova's offer is left empty in the ledger. auto const ovasOffers = offersOnAccount(env, ova); if (ovasOffers.size() != 0) { BEAST_EXPECT(ovasOffers.size() == 1); auto const& ovasOffer = *(ovasOffers.front()); BEAST_EXPECT(ovasOffer[sfLedgerEntryType] == ltOFFER); BEAST_EXPECT(ovasOffer[sfTakerGets] == USD(0)); BEAST_EXPECT(ovasOffer[sfTakerPays] == MUSO(0)); } env.require(balance(pat, USD(0))); env.require(balance(pat, EUR(100))); env.require(balance(pat, MUSO(0) + reserve(env, 3))); env.require(offers(pat, 0)); env.require(balance(qae, USD(100))); env.require(balance(qae, EUR(0))); env.require(balance(qae, MUSO(2) + reserve(env, 3))); env.require(offers(qae, 0)); } } void testSelfCrossOffer1(FeatureBitset features) { // The following test verifies some correct but slightly surprising // behavior in offer crossing. The scenario: // // o An entity has created one or more offers. // o The entity creates another offer that can be directly crossed // (not autobridged) by the previously created offer(s). // o Rather than self crossing the offers, delete the old offer(s). // // See a more complete explanation in the comments for // BookOfferCrossingStep::limitSelfCrossQuality(). // // Note that, in this particular example, one offer causes several // crossable offers (worth considerably more than the new offer) // to be removed from the book. using namespace jtx; auto const gw = Account("gateway"); auto const USD = gw["USD"]; Env env{*this, features}; // The fee that's charged for transactions. auto const fee = env.current()->fees().base; auto const startBalance = MUSO(1000000); env.fund(startBalance + (fee * 4), gw); env.close(); env(offer(gw, USD(60), MUSO(600))); env.close(); env(offer(gw, USD(60), MUSO(600))); env.close(); env(offer(gw, USD(60), MUSO(600))); env.close(); env.require(owners(gw, 3)); env.require(balance(gw, startBalance + fee)); auto gwOffers = offersOnAccount(env, gw); BEAST_EXPECT(gwOffers.size() == 3); for (auto const& offerPtr : gwOffers) { auto const& offer = *offerPtr; BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER); BEAST_EXPECT(offer[sfTakerGets] == MUSO(600)); BEAST_EXPECT(offer[sfTakerPays] == USD(60)); } // Since this offer crosses the first offers, the previous offers // will be deleted and this offer will be put on the order book. env(offer(gw, MUSO(1000), USD(100))); env.close(); env.require(owners(gw, 1)); env.require(offers(gw, 1)); env.require(balance(gw, startBalance)); gwOffers = offersOnAccount(env, gw); BEAST_EXPECT(gwOffers.size() == 1); for (auto const& offerPtr : gwOffers) { auto const& offer = *offerPtr; BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER); BEAST_EXPECT(offer[sfTakerGets] == USD(100)); BEAST_EXPECT(offer[sfTakerPays] == MUSO(1000)); } } void testSelfCrossOffer2(FeatureBitset features) { using namespace jtx; auto const gw1 = Account("gateway1"); auto const gw2 = Account("gateway2"); auto const alice = Account("alice"); auto const USD = gw1["USD"]; auto const EUR = gw2["EUR"]; Env env{*this, features}; env.fund(MUSO(1000000), gw1, gw2); env.close(); // The fee that's charged for transactions. auto const f = env.current()->fees().base; // Test cases struct TestData { std::string acct; // Account operated on STAmount fundMUSO; // MUSO acct funded with STAmount fundUSD; // USD acct funded with STAmount fundEUR; // EUR acct funded with TER firstOfferTec; // tec code on first offer TER secondOfferTec; // tec code on second offer }; TestData const tests[]{ // acct fundMUSO fundUSD fundEUR firstOfferTec // secondOfferTec {"ann", reserve(env, 3) + f * 4, USD(1000), EUR(1000), tesSUCCESS, tesSUCCESS}, {"bev", reserve(env, 3) + f * 4, USD(1), EUR(1000), tesSUCCESS, tesSUCCESS}, {"cam", reserve(env, 3) + f * 4, USD(1000), EUR(1), tesSUCCESS, tesSUCCESS}, {"deb", reserve(env, 3) + f * 4, USD(0), EUR(1), tesSUCCESS, tecUNFUNDED_OFFER}, {"eve", reserve(env, 3) + f * 4, USD(1), EUR(0), tecUNFUNDED_OFFER, tesSUCCESS}, {"flo", reserve(env, 3) + 0, USD(1000), EUR(1000), tecINSUF_RESERVE_OFFER, tecINSUF_RESERVE_OFFER}, }; for (auto const& t : tests) { auto const acct = Account{t.acct}; env.fund(t.fundMUSO, acct); env.close(); env(trust(acct, USD(1000))); env(trust(acct, EUR(1000))); env.close(); if (t.fundUSD > USD(0)) env(pay(gw1, acct, t.fundUSD)); if (t.fundEUR > EUR(0)) env(pay(gw2, acct, t.fundEUR)); env.close(); env(offer(acct, USD(500), EUR(600)), ter(t.firstOfferTec)); env.close(); std::uint32_t const firstOfferSeq = env.seq(acct) - 1; int offerCount = t.firstOfferTec == tesSUCCESS ? 1 : 0; env.require(owners(acct, 2 + offerCount)); env.require(balance(acct, t.fundUSD)); env.require(balance(acct, t.fundEUR)); auto acctOffers = offersOnAccount(env, acct); BEAST_EXPECT(acctOffers.size() == offerCount); for (auto const& offerPtr : acctOffers) { auto const& offer = *offerPtr; BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER); BEAST_EXPECT(offer[sfTakerGets] == EUR(600)); BEAST_EXPECT(offer[sfTakerPays] == USD(500)); } env(offer(acct, EUR(600), USD(500)), ter(t.secondOfferTec)); env.close(); std::uint32_t const secondOfferSeq = env.seq(acct) - 1; offerCount = t.secondOfferTec == tesSUCCESS ? 1 : offerCount; env.require(owners(acct, 2 + offerCount)); env.require(balance(acct, t.fundUSD)); env.require(balance(acct, t.fundEUR)); acctOffers = offersOnAccount(env, acct); BEAST_EXPECT(acctOffers.size() == offerCount); for (auto const& offerPtr : acctOffers) { auto const& offer = *offerPtr; BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER); if (offer[sfSequence] == firstOfferSeq) { BEAST_EXPECT(offer[sfTakerGets] == EUR(600)); BEAST_EXPECT(offer[sfTakerPays] == USD(500)); } else { BEAST_EXPECT(offer[sfTakerGets] == USD(500)); BEAST_EXPECT(offer[sfTakerPays] == EUR(600)); } } // Remove any offers from acct for the next pass. env(offer_cancel(acct, firstOfferSeq)); env.close(); env(offer_cancel(acct, secondOfferSeq)); env.close(); } } void testSelfCrossOffer(FeatureBitset features) { testcase("Self Cross Offer"); testSelfCrossOffer1(features); testSelfCrossOffer2(features); } void testSelfIssueOffer(FeatureBitset features) { // Folks who issue their own currency have, in effect, as many // funds as they are trusted for. This test used to fail because // self-issuing was not properly checked. Verify that it works // correctly now. using namespace jtx; Env env{*this, features}; auto const alice = Account("alice"); auto const bob = Account("bob"); auto const USD = bob["USD"]; auto const f = env.current()->fees().base; env.fund(MUSO(50000) + f, alice, bob); env.close(); env(offer(alice, USD(5000), MUSO(50000))); env.close(); // This offer should take alice's offer up to Alice's reserve. env(offer(bob, MUSO(50000), USD(5000))); env.close(); // alice's offer should have been removed, since she's down to her // MUSO reserve. env.require(balance(alice, MUSO(250))); env.require(owners(alice, 1)); env.require(lines(alice, 1)); // However bob's offer should be in the ledger, since it was not // fully crossed. auto const bobOffers = offersOnAccount(env, bob); BEAST_EXPECT(bobOffers.size() == 1); for (auto const& offerPtr : bobOffers) { auto const& offer = *offerPtr; BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER); BEAST_EXPECT(offer[sfTakerGets] == USD(25)); BEAST_EXPECT(offer[sfTakerPays] == MUSO(250)); } } void testBadPathAssert(FeatureBitset features) { // At one point in the past this invalid path caused an assert. It // should not be possible for user-supplied data to cause an assert. // Make sure the assert is gone. testcase("Bad path assert"); using namespace jtx; // The problem was identified when featureOwnerPaysFee was enabled, // so make sure that gets included. Env env{*this, features | featureOwnerPaysFee}; // The fee that's charged for transactions. auto const fee = env.current()->fees().base; { // A trust line's QualityOut should not affect offer crossing. auto const ann = Account("ann"); auto const A_BUX = ann["BUX"]; auto const bob = Account("bob"); auto const cam = Account("cam"); auto const dan = Account("dan"); auto const D_BUX = dan["BUX"]; // Verify trust line QualityOut affects payments. env.fund(reserve(env, 4) + (fee * 4), ann, bob, cam, dan); env.close(); env(trust(bob, A_BUX(400))); env(trust(bob, D_BUX(200)), qualityOutPercent(120)); env(trust(cam, D_BUX(100))); env.close(); env(pay(dan, bob, D_BUX(100))); env.close(); env.require(balance(bob, D_BUX(100))); env(pay(ann, cam, D_BUX(60)), path(bob, dan), sendmax(A_BUX(200))); env.close(); env.require(balance(ann, A_BUX(none))); env.require(balance(ann, D_BUX(none))); env.require(balance(bob, A_BUX(72))); env.require(balance(bob, D_BUX(40))); env.require(balance(cam, A_BUX(none))); env.require(balance(cam, D_BUX(60))); env.require(balance(dan, A_BUX(none))); env.require(balance(dan, D_BUX(none))); env(offer(bob, A_BUX(30), D_BUX(30))); env.close(); env(trust(ann, D_BUX(100))); env.close(); // This payment caused the assert. env(pay(ann, ann, D_BUX(30)), path(A_BUX, D_BUX), sendmax(A_BUX(30)), ter(temBAD_PATH)); env.close(); env.require(balance(ann, A_BUX(none))); env.require(balance(ann, D_BUX(0))); env.require(balance(bob, A_BUX(72))); env.require(balance(bob, D_BUX(40))); env.require(balance(cam, A_BUX(none))); env.require(balance(cam, D_BUX(60))); env.require(balance(dan, A_BUX(0))); env.require(balance(dan, D_BUX(none))); } } void testDirectToDirectPath(FeatureBitset features) { // The offer crossing code expects that a DirectStep is always // preceded by a BookStep. In one instance the default path // was not matching that assumption. Here we recreate that case // so we can prove the bug stays fixed. testcase("Direct to Direct path"); using namespace jtx; Env env{*this, features}; auto const ann = Account("ann"); auto const bob = Account("bob"); auto const cam = Account("cam"); auto const A_BUX = ann["BUX"]; auto const B_BUX = bob["BUX"]; auto const fee = env.current()->fees().base; env.fund(reserve(env, 4) + (fee * 5), ann, bob, cam); env.close(); env(trust(ann, B_BUX(40))); env(trust(cam, A_BUX(40))); env(trust(cam, B_BUX(40))); env.close(); env(pay(ann, cam, A_BUX(35))); env(pay(bob, cam, B_BUX(35))); env(offer(bob, A_BUX(30), B_BUX(30))); env.close(); // cam puts an offer on the books that her upcoming offer could cross. // But this offer should be deleted, not crossed, by her upcoming // offer. env(offer(cam, A_BUX(29), B_BUX(30), tfPassive)); env.close(); env.require(balance(cam, A_BUX(35))); env.require(balance(cam, B_BUX(35))); env.require(offers(cam, 1)); // This offer caused the assert. env(offer(cam, B_BUX(30), A_BUX(30))); env.close(); env.require(balance(bob, A_BUX(30))); env.require(balance(cam, A_BUX(5))); env.require(balance(cam, B_BUX(65))); env.require(offers(cam, 0)); } void testSelfCrossLowQualityOffer(FeatureBitset features) { // The Flow offer crossing code used to assert if an offer was made // for more MUSO than the offering account held. This unit test // reproduces that failing case. testcase("Self crossing low quality offer"); using namespace jtx; Env env{*this, features}; auto const ann = Account("ann"); auto const gw = Account("gateway"); auto const BTC = gw["BTC"]; auto const fee = env.current()->fees().base; env.fund(reserve(env, 2) + drops(9999640) + (fee), ann); env.fund(reserve(env, 2) + (fee * 4), gw); env.close(); env(rate(gw, 1.002)); env(trust(ann, BTC(10))); env.close(); env(pay(gw, ann, BTC(2.856))); env.close(); env(offer(ann, drops(365611702030), BTC(5.713))); env.close(); // This offer caused the assert. env(offer(ann, BTC(0.687), drops(20000000000)), ter(tecINSUF_RESERVE_OFFER)); } void testOfferInScaling(FeatureBitset features) { // The Flow offer crossing code had a case where it was not rounding // the offer crossing correctly after a partial crossing. The // failing case was found on the network. Here we add the case to // the unit tests. testcase("Offer In Scaling"); using namespace jtx; Env env{*this, features}; auto const gw = Account("gateway"); auto const alice = Account("alice"); auto const bob = Account("bob"); auto const CNY = gw["CNY"]; auto const fee = env.current()->fees().base; env.fund(reserve(env, 2) + drops(400000000000) + (fee), alice, bob); env.fund(reserve(env, 2) + (fee * 4), gw); env.close(); env(trust(bob, CNY(500))); env.close(); env(pay(gw, bob, CNY(300))); env.close(); env(offer(bob, drops(5400000000), CNY(216.054))); env.close(); // This offer did not round result of partial crossing correctly. env(offer(alice, CNY(13562.0001), drops(339000000000))); env.close(); auto const aliceOffers = offersOnAccount(env, alice); BEAST_EXPECT(aliceOffers.size() == 1); for (auto const& offerPtr : aliceOffers) { auto const& offer = *offerPtr; BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER); BEAST_EXPECT(offer[sfTakerGets] == drops(333599446582)); BEAST_EXPECT(offer[sfTakerPays] == CNY(13345.9461)); } } void testOfferInScalingWithXferRate(FeatureBitset features) { // After adding the previous case, there were still failing rounding // cases in Flow offer crossing. This one was because the gateway // transfer rate was not being correctly handled. testcase("Offer In Scaling With Xfer Rate"); using namespace jtx; Env env{*this, features}; auto const gw = Account("gateway"); auto const alice = Account("alice"); auto const bob = Account("bob"); auto const BTC = gw["BTC"]; auto const JPY = gw["JPY"]; auto const fee = env.current()->fees().base; env.fund(reserve(env, 2) + drops(400000000000) + (fee), alice, bob); env.fund(reserve(env, 2) + (fee * 4), gw); env.close(); env(rate(gw, 1.002)); env(trust(alice, JPY(4000))); env(trust(bob, BTC(2))); env.close(); env(pay(gw, alice, JPY(3699.034802280317))); env(pay(gw, bob, BTC(1.156722559140311))); env.close(); env(offer(bob, JPY(1241.913390770747), BTC(0.01969825690469254))); env.close(); // This offer did not round result of partial crossing correctly. env(offer(alice, BTC(0.05507568706427876), JPY(3472.696773391072))); env.close(); auto const aliceOffers = offersOnAccount(env, alice); BEAST_EXPECT(aliceOffers.size() == 1); for (auto const& offerPtr : aliceOffers) { auto const& offer = *offerPtr; BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER); BEAST_EXPECT( offer[sfTakerGets] == STAmount(JPY.issue(), std::uint64_t(2230682446713524ul), -12)); BEAST_EXPECT(offer[sfTakerPays] == BTC(0.035378)); } } void testOfferThresholdWithReducedFunds(FeatureBitset features) { // Another instance where Flow offer crossing was not always // working right was if the Taker had fewer funds than the Offer // was offering. The basis for this test came off the network. testcase("Offer Threshold With Reduced Funds"); using namespace jtx; Env env{*this, features}; auto const gw1 = Account("gw1"); auto const gw2 = Account("gw2"); auto const alice = Account("alice"); auto const bob = Account("bob"); auto const USD = gw1["USD"]; auto const JPY = gw2["JPY"]; auto const fee = env.current()->fees().base; env.fund(reserve(env, 2) + drops(400000000000) + (fee), alice, bob); env.fund(reserve(env, 2) + (fee * 4), gw1, gw2); env.close(); env(rate(gw1, 1.002)); env(trust(alice, USD(1000))); env(trust(bob, JPY(100000))); env.close(); env( pay(gw1, alice, STAmount{USD.issue(), std::uint64_t(2185410179555600), -14})); env( pay(gw2, bob, STAmount{JPY.issue(), std::uint64_t(6351823459548956), -12})); env.close(); env(offer( bob, STAmount{USD.issue(), std::uint64_t(4371257532306000), -17}, STAmount{JPY.issue(), std::uint64_t(4573216636606000), -15})); env.close(); // This offer did not partially cross correctly. env(offer( alice, STAmount{JPY.issue(), std::uint64_t(2291181510070762), -12}, STAmount{USD.issue(), std::uint64_t(2190218999914694), -14})); env.close(); auto const aliceOffers = offersOnAccount(env, alice); BEAST_EXPECT(aliceOffers.size() == 1); for (auto const& offerPtr : aliceOffers) { auto const& offer = *offerPtr; BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER); BEAST_EXPECT( offer[sfTakerGets] == STAmount(USD.issue(), std::uint64_t(2185847305256635), -14)); BEAST_EXPECT( offer[sfTakerPays] == STAmount(JPY.issue(), std::uint64_t(2286608293434156), -12)); } } void testTinyOffer(FeatureBitset features) { testcase("Tiny Offer"); using namespace jtx; Env env{*this, features}; auto const gw = Account("gw"); auto const alice = Account("alice"); auto const bob = Account("bob"); auto const CNY = gw["CNY"]; auto const fee = env.current()->fees().base; auto const startMUSOBalance = drops(400000000000) + (fee * 2); env.fund(startMUSOBalance, gw, alice, bob); env.close(); env(trust(bob, CNY(100000))); env.close(); // Place alice's tiny offer in the book first. Let's see what happens // when a reasonable offer crosses it. STAmount const alicesCnyOffer{ CNY.issue(), std::uint64_t(4926000000000000), -23}; env(offer(alice, alicesCnyOffer, drops(1), tfPassive)); env.close(); // bob places an ordinary offer STAmount const bobsCnyStartBalance{ CNY.issue(), std::uint64_t(3767479960090235), -15}; env(pay(gw, bob, bobsCnyStartBalance)); env.close(); env(offer( bob, drops(203), STAmount{CNY.issue(), std::uint64_t(1000000000000000), -20})); env.close(); env.require(balance(alice, alicesCnyOffer)); env.require(balance(alice, startMUSOBalance - fee - drops(1))); env.require(balance(bob, bobsCnyStartBalance - alicesCnyOffer)); env.require(balance(bob, startMUSOBalance - (fee * 2) + drops(1))); } void testSelfPayXferFeeOffer(FeatureBitset features) { testcase("Self Pay Xfer Fee"); // The old offer crossing code does not charge a transfer fee // if alice pays alice. That's different from how payments work. // Payments always charge a transfer fee even if the money is staying // in the same hands. // // What's an example where alice pays alice? There are three actors: // gw, alice, and bob. // // 1. gw issues BTC and USD. qw charges a 0.2% transfer fee. // // 2. alice makes an offer to buy MUSO and sell USD. // 3. bob makes an offer to buy BTC and sell MUSO. // // 4. alice now makes an offer to sell BTC and buy USD. // // This last offer crosses using auto-bridging. // o alice's last offer sells BTC to... // o bob' offer which takes alice's BTC and sells MUSO to... // o alice's first offer which takes bob's MUSO and sells USD to... // o alice's last offer. // // So alice sells USD to herself. // // There are six cases that we need to test: // o alice crosses her own offer on the first leg (BTC). // o alice crosses her own offer on the second leg (USD). // o alice crosses her own offers on both legs. // All three cases need to be tested: // o In reverse (alice has enough BTC to cover her offer) and // o Forward (alice owns less BTC than is in her final offer. // // It turns out that two of the forward cases fail for a different // reason. They are therefore commented out here, But they are // revisited in the testSelfPayUnlimitedFunds() unit test. using namespace jtx; Env env{*this, features}; auto const gw = Account("gw"); auto const BTC = gw["BTC"]; auto const USD = gw["USD"]; auto const startMUSOBalance = MUSO(4000000); env.fund(startMUSOBalance, gw); env.close(); env(rate(gw, 1.25)); env.close(); // Test cases struct Actor { Account acct; int offers; // offers on account after crossing PrettyAmount MUSO; // final expected after crossing PrettyAmount btc; // final expected after crossing PrettyAmount usd; // final expected after crossing }; struct TestData { // The first three three integers give the *index* in actors // to assign each of the three roles. By using indices it is // easy for alice to own the offer in the first leg, the second // leg, or both. std::size_t self; std::size_t leg0; std::size_t leg1; PrettyAmount btcStart; std::vector<Actor> actors; }; TestData const tests[]{ // btcStart --------------------- actor[0] // --------------------- -------------------- actor[1] // ------------------- {0, 0, 1, BTC(20), {{"ann", 0, drops(3899999999960), BTC(20.0), USD(3000)}, {"abe", 0, drops(4099999999970), BTC(0), USD(750)}}}, // no BTC // xfer fee {0, 1, 0, BTC(20), {{"bev", 0, drops(4099999999960), BTC(7.5), USD(2000)}, {"bob", 0, drops(3899999999970), BTC(10), USD(0)}}}, // no USD // xfer fee {0, 0, 0, BTC(20), {{"cam", 0, drops(3999999999950), BTC(20.0), USD(2000)}}}, // no xfer fee // { 0, 0, 1, BTC( 5), { {"deb", 0, drops(3899999999960), BTC( 5.0), // USD(3000)}, {"dan", 0, drops(4099999999970), BTC( 0), USD(750)} } // }, // no BTC xfer fee {0, 1, 0, BTC(5), {{"eve", 1, drops(4039999999960), BTC(0.0), USD(2000)}, {"eli", 1, drops(3959999999970), BTC(4), USD(0)}}}, // no USD // xfer fee // { 0, 0, 0, BTC( 5), { {"flo", 0, drops(3999999999950), BTC( 5.0), // USD(2000)} } // } // no xfer fee }; for (auto const& t : tests) { Account const& self = t.actors[t.self].acct; Account const& leg0 = t.actors[t.leg0].acct; Account const& leg1 = t.actors[t.leg1].acct; for (auto const& actor : t.actors) { env.fund(MUSO(4000000), actor.acct); env.close(); env(trust(actor.acct, BTC(40))); env(trust(actor.acct, USD(8000))); env.close(); } env(pay(gw, self, t.btcStart)); env(pay(gw, self, USD(2000))); if (self.id() != leg1.id()) env(pay(gw, leg1, USD(2000))); env.close(); // Get the initial offers in place. Remember their sequences // so we can delete them later. env(offer(leg0, BTC(10), MUSO(100000), tfPassive)); env.close(); std::uint32_t const leg0OfferSeq = env.seq(leg0) - 1; env(offer(leg1, MUSO(100000), USD(1000), tfPassive)); env.close(); std::uint32_t const leg1OfferSeq = env.seq(leg1) - 1; // This is the offer that matters. env(offer(self, USD(1000), BTC(10))); env.close(); std::uint32_t const selfOfferSeq = env.seq(self) - 1; // Verify results. for (auto const& actor : t.actors) { // Sometimes Taker crossing gets lazy about deleting offers. // Treat an empty offer as though it is deleted. auto actorOffers = offersOnAccount(env, actor.acct); auto const offerCount = std::distance( actorOffers.begin(), std::remove_if( actorOffers.begin(), actorOffers.end(), [](std::shared_ptr<SLE const>& offer) { return (*offer)[sfTakerGets].signum() == 0; })); BEAST_EXPECT(offerCount == actor.offers); env.require(balance(actor.acct, actor.MUSO)); env.require(balance(actor.acct, actor.btc)); env.require(balance(actor.acct, actor.usd)); } // Remove any offers that might be left hanging around. They // could bollix up later loops. env(offer_cancel(leg0, leg0OfferSeq)); env.close(); env(offer_cancel(leg1, leg1OfferSeq)); env.close(); env(offer_cancel(self, selfOfferSeq)); env.close(); } } void testSelfPayUnlimitedFunds(FeatureBitset features) { testcase("Self Pay Unlimited Funds"); // The Taker offer crossing code recognized when Alice was paying // Alice the same denomination. In this case, as long as Alice // has a little bit of that denomination, it treats Alice as though // she has unlimited funds in that denomination. // // Huh? What kind of sense does that make? // // One way to think about it is to break a single payment into a // series of very small payments executed sequentially but very // quickly. Alice needs to pay herself 1 USD, but she only has // 0.01 USD. Alice says, "Hey Alice, let me pay you a penny." // Alice does this, taking the penny out of her pocket and then // putting it back in her pocket. Then she says, "Hey Alice, // I found another penny. I can pay you another penny." Repeat // these steps 100 times and Alice has paid herself 1 USD even though // she only owns 0.01 USD. // // That's all very nice, but the payment code does not support this // optimization. In part that's because the payment code can // operate on a whole batch of offers. As a matter of fact, it can // deal in two consecutive batches of offers. It would take a great // deal of sorting out to figure out which offers in the two batches // had the same owner and give them special processing. And, // honestly, it's a weird little corner case. // // So, since Flow offer crossing uses the payments engine, Flow // offer crossing no longer supports this optimization. // // The following test shows the difference in the behaviors between // Taker offer crossing and Flow offer crossing. using namespace jtx; Env env{*this, features}; auto const gw = Account("gw"); auto const BTC = gw["BTC"]; auto const USD = gw["USD"]; auto const startMUSOBalance = MUSO(4000000); env.fund(startMUSOBalance, gw); env.close(); env(rate(gw, 1.25)); env.close(); // Test cases struct Actor { Account acct; int offers; // offers on account after crossing PrettyAmount MUSO; // final expected after crossing PrettyAmount btc; // final expected after crossing PrettyAmount usd; // final expected after crossing }; struct TestData { // The first three three integers give the *index* in actors // to assign each of the three roles. By using indices it is // easy for alice to own the offer in the first leg, the second // leg, or both. std::size_t self; std::size_t leg0; std::size_t leg1; PrettyAmount btcStart; std::vector<Actor> actors; }; TestData const takerTests[]{ // btcStart ------------------- actor[0] // -------------------- ------------------- actor[1] // -------------------- {0, 0, 1, BTC(5), {{"deb", 0, drops(3899999999960), BTC(5), USD(3000)}, {"dan", 0, drops(4099999999970), BTC(0), USD(750)}}}, // no BTC // xfer fee {0, 0, 0, BTC(5), {{"flo", 0, drops(3999999999950), BTC(5), USD(2000)}}} // no xfer // fee }; TestData const flowTests[]{ // btcStart ------------------- actor[0] // -------------------- ------------------- actor[1] // -------------------- {0, 0, 1, BTC(5), {{"gay", 1, drops(3949999999960), BTC(5), USD(2500)}, {"gar", 1, drops(4049999999970), BTC(0), USD(1375)}}}, // no BTC xfer fee {0, 0, 0, BTC(5), {{"hye", 2, drops(3999999999950), BTC(5), USD(2000)}}} // no xfer // fee }; // Pick the right tests. auto const& tests = features[featureFlowCross] ? flowTests : takerTests; for (auto const& t : tests) { Account const& self = t.actors[t.self].acct; Account const& leg0 = t.actors[t.leg0].acct; Account const& leg1 = t.actors[t.leg1].acct; for (auto const& actor : t.actors) { env.fund(MUSO(4000000), actor.acct); env.close(); env(trust(actor.acct, BTC(40))); env(trust(actor.acct, USD(8000))); env.close(); } env(pay(gw, self, t.btcStart)); env(pay(gw, self, USD(2000))); if (self.id() != leg1.id()) env(pay(gw, leg1, USD(2000))); env.close(); // Get the initial offers in place. Remember their sequences // so we can delete them later. env(offer(leg0, BTC(10), MUSO(100000), tfPassive)); env.close(); std::uint32_t const leg0OfferSeq = env.seq(leg0) - 1; env(offer(leg1, MUSO(100000), USD(1000), tfPassive)); env.close(); std::uint32_t const leg1OfferSeq = env.seq(leg1) - 1; // This is the offer that matters. env(offer(self, USD(1000), BTC(10))); env.close(); std::uint32_t const selfOfferSeq = env.seq(self) - 1; // Verify results. for (auto const& actor : t.actors) { // Sometimes Taker offer crossing gets lazy about deleting // offers. Treat an empty offer as though it is deleted. auto actorOffers = offersOnAccount(env, actor.acct); auto const offerCount = std::distance( actorOffers.begin(), std::remove_if( actorOffers.begin(), actorOffers.end(), [](std::shared_ptr<SLE const>& offer) { return (*offer)[sfTakerGets].signum() == 0; })); BEAST_EXPECT(offerCount == actor.offers); env.require(balance(actor.acct, actor.MUSO)); env.require(balance(actor.acct, actor.btc)); env.require(balance(actor.acct, actor.usd)); } // Remove any offers that might be left hanging around. They // could bollix up later loops. env(offer_cancel(leg0, leg0OfferSeq)); env.close(); env(offer_cancel(leg1, leg1OfferSeq)); env.close(); env(offer_cancel(self, selfOfferSeq)); env.close(); } } void testRequireAuth(FeatureBitset features) { testcase("lsfRequireAuth"); using namespace jtx; Env env{*this, features}; auto const gw = Account("gw"); auto const alice = Account("alice"); auto const bob = Account("bob"); auto const gwUSD = gw["USD"]; auto const aliceUSD = alice["USD"]; auto const bobUSD = bob["USD"]; env.fund(MUSO(400000), gw, alice, bob); env.close(); // GW requires authorization for holders of its IOUs env(fset(gw, asfRequireAuth)); env.close(); // Properly set trust and have gw authorize bob and alice env(trust(gw, bobUSD(100)), txflags(tfSetfAuth)); env(trust(bob, gwUSD(100))); env(trust(gw, aliceUSD(100)), txflags(tfSetfAuth)); env(trust(alice, gwUSD(100))); // Alice is able to place the offer since the GW has authorized her env(offer(alice, gwUSD(40), MUSO(4000))); env.close(); env.require(offers(alice, 1)); env.require(balance(alice, gwUSD(0))); env(pay(gw, bob, gwUSD(50))); env.close(); env.require(balance(bob, gwUSD(50))); // Bob's offer should cross Alice's env(offer(bob, MUSO(4000), gwUSD(40))); env.close(); env.require(offers(alice, 0)); env.require(balance(alice, gwUSD(40))); env.require(offers(bob, 0)); env.require(balance(bob, gwUSD(10))); } void testMissingAuth(FeatureBitset features) { testcase("Missing Auth"); // 1. alice creates an offer to acquire USD/gw, an asset for which // she does not have a trust line. At some point in the future, // gw adds lsfRequireAuth. Then, later, alice's offer is crossed. // a. With Taker alice's unauthorized offer is consumed. // b. With FlowCross alice's offer is deleted, not consumed, // since alice is not authorized to hold USD/gw. // // 2. alice tries to create an offer for USD/gw, now that gw has // lsfRequireAuth set. This time the offer create fails because // alice is not authorized to hold USD/gw. // // 3. Next, gw creates a trust line to alice, but does not set // tfSetfAuth on that trust line. alice attempts to create an // offer and again fails. // // 4. Finally, gw sets tsfSetAuth on the trust line authorizing // alice to own USD/gw. At this point alice successfully // creates and crosses an offer for USD/gw. using namespace jtx; Env env{*this, features}; auto const gw = Account("gw"); auto const alice = Account("alice"); auto const bob = Account("bob"); auto const gwUSD = gw["USD"]; auto const aliceUSD = alice["USD"]; auto const bobUSD = bob["USD"]; env.fund(MUSO(400000), gw, alice, bob); env.close(); env(offer(alice, gwUSD(40), MUSO(4000))); env.close(); env.require(offers(alice, 1)); env.require(balance(alice, gwUSD(none))); env(fset(gw, asfRequireAuth)); env.close(); env(trust(gw, bobUSD(100)), txflags(tfSetfAuth)); env.close(); env(trust(bob, gwUSD(100))); env.close(); env(pay(gw, bob, gwUSD(50))); env.close(); env.require(balance(bob, gwUSD(50))); // gw now requires authorization and bob has gwUSD(50). Let's see if // bob can cross alice's offer. // // o With Taker bob's offer should cross alice's. // o With FlowCross bob's offer shouldn't cross and alice's // unauthorized offer should be deleted. env(offer(bob, MUSO(4000), gwUSD(40))); env.close(); std::uint32_t const bobOfferSeq = env.seq(bob) - 1; bool const flowCross = features[featureFlowCross]; env.require(offers(alice, 0)); if (flowCross) { // alice's unauthorized offer is deleted & bob's offer not crossed. env.require(balance(alice, gwUSD(none))); env.require(offers(bob, 1)); env.require(balance(bob, gwUSD(50))); } else { // alice's offer crosses bob's env.require(balance(alice, gwUSD(40))); env.require(offers(bob, 0)); env.require(balance(bob, gwUSD(10))); // The rest of the test verifies FlowCross behavior. return; } // See if alice can create an offer without authorization. alice // should not be able to create the offer and bob's offer should be // untouched. env(offer(alice, gwUSD(40), MUSO(4000)), ter(tecNO_LINE)); env.close(); env.require(offers(alice, 0)); env.require(balance(alice, gwUSD(none))); env.require(offers(bob, 1)); env.require(balance(bob, gwUSD(50))); // Set up a trust line for alice, but don't authorize it. alice // should still not be able to create an offer for USD/gw. env(trust(gw, aliceUSD(100))); env.close(); env(offer(alice, gwUSD(40), MUSO(4000)), ter(tecNO_AUTH)); env.close(); env.require(offers(alice, 0)); env.require(balance(alice, gwUSD(0))); env.require(offers(bob, 1)); env.require(balance(bob, gwUSD(50))); // Delete bob's offer so alice can create an offer without crossing. env(offer_cancel(bob, bobOfferSeq)); env.close(); env.require(offers(bob, 0)); // Finally, set up an authorized trust line for alice. Now alice's // offer should succeed. Note that, since this is an offer rather // than a payment, alice does not need to set a trust line limit. env(trust(gw, aliceUSD(100)), txflags(tfSetfAuth)); env.close(); env(offer(alice, gwUSD(40), MUSO(4000))); env.close(); env.require(offers(alice, 1)); // Now bob creates his offer again. alice's offer should cross. env(offer(bob, MUSO(4000), gwUSD(40))); env.close(); env.require(offers(alice, 0)); env.require(balance(alice, gwUSD(40))); env.require(offers(bob, 0)); env.require(balance(bob, gwUSD(10))); } void testRCSmoketest(FeatureBitset features) { testcase("MUSOConnect Smoketest payment flow"); using namespace jtx; Env env{*this, features}; // This test mimics the payment flow used in the MUSO Connect // smoke test. The players: // A USD gateway with hot and cold wallets // A EUR gateway with hot and cold walllets // A MM gateway that will provide offers from USD->EUR and EUR->USD // A path from hot US to cold EUR is found and then used to send // USD for EUR that goes through the market maker auto const hotUS = Account("hotUS"); auto const coldUS = Account("coldUS"); auto const hotEU = Account("hotEU"); auto const coldEU = Account("coldEU"); auto const mm = Account("mm"); auto const USD = coldUS["USD"]; auto const EUR = coldEU["EUR"]; env.fund(MUSO(100000), hotUS, coldUS, hotEU, coldEU, mm); env.close(); // Cold wallets require trust but will MUSO by default for (auto const& cold : {coldUS, coldEU}) { env(fset(cold, asfRequireAuth)); env(fset(cold, asfDefaultMUSO)); } env.close(); // Each hot wallet trusts the related cold wallet for a large amount env(trust(hotUS, USD(10000000)), txflags(tfSetNoMUSO)); env(trust(hotEU, EUR(10000000)), txflags(tfSetNoMUSO)); // Market maker trusts both cold wallets for a large amount env(trust(mm, USD(10000000)), txflags(tfSetNoMUSO)); env(trust(mm, EUR(10000000)), txflags(tfSetNoMUSO)); env.close(); // Gateways authorize the trustlines of hot and market maker env(trust(coldUS, USD(0), hotUS, tfSetfAuth)); env(trust(coldEU, EUR(0), hotEU, tfSetfAuth)); env(trust(coldUS, USD(0), mm, tfSetfAuth)); env(trust(coldEU, EUR(0), mm, tfSetfAuth)); env.close(); // Issue currency from cold wallets to hot and market maker env(pay(coldUS, hotUS, USD(5000000))); env(pay(coldEU, hotEU, EUR(5000000))); env(pay(coldUS, mm, USD(5000000))); env(pay(coldEU, mm, EUR(5000000))); env.close(); // MM places offers float const rate = 0.9f; // 0.9 USD = 1 EUR env(offer(mm, EUR(4000000 * rate), USD(4000000)), json(jss::Flags, tfSell)); float const reverseRate = 1.0f / rate * 1.00101f; env(offer(mm, USD(4000000 * reverseRate), EUR(4000000)), json(jss::Flags, tfSell)); env.close(); // There should be a path available from hot US to cold EUR { Json::Value jvParams; jvParams[jss::destination_account] = coldEU.human(); jvParams[jss::destination_amount][jss::issuer] = coldEU.human(); jvParams[jss::destination_amount][jss::currency] = "EUR"; jvParams[jss::destination_amount][jss::value] = 10; jvParams[jss::source_account] = hotUS.human(); Json::Value const jrr{env.rpc( "json", "MUSO_path_find", to_string(jvParams))[jss::result]}; BEAST_EXPECT(jrr[jss::status] == "success"); BEAST_EXPECT( jrr[jss::alternatives].isArray() && jrr[jss::alternatives].size() > 0); } // Send the payment using the found path. env(pay(hotUS, coldEU, EUR(10)), sendmax(USD(11.1223326))); } void testSelfAuth(FeatureBitset features) { testcase("Self Auth"); using namespace jtx; Env env{*this, features}; auto const gw = Account("gw"); auto const alice = Account("alice"); auto const gwUSD = gw["USD"]; auto const aliceUSD = alice["USD"]; env.fund(MUSO(400000), gw, alice); env.close(); // Test that gw can create an offer to buy gw's currency. env(offer(gw, gwUSD(40), MUSO(4000))); env.close(); std::uint32_t const gwOfferSeq = env.seq(gw) - 1; env.require(offers(gw, 1)); // Since gw has an offer out, gw should not be able to set RequireAuth. env(fset(gw, asfRequireAuth), ter(tecOWNERS)); env.close(); // Cancel gw's offer so we can set RequireAuth. env(offer_cancel(gw, gwOfferSeq)); env.close(); env.require(offers(gw, 0)); // gw now requires authorization for holders of its IOUs env(fset(gw, asfRequireAuth)); env.close(); // The test behaves differently with or without DepositPreauth. bool const preauth = features[featureDepositPreauth]; // Before DepositPreauth an account with lsfRequireAuth set could not // create an offer to buy their own currency. After DepositPreauth // they can. env(offer(gw, gwUSD(40), MUSO(4000)), ter(preauth ? TER{tesSUCCESS} : TER{tecNO_LINE})); env.close(); env.require(offers(gw, preauth ? 1 : 0)); if (!preauth) // The rest of the test verifies DepositPreauth behavior. return; // Set up an authorized trust line and pay alice gwUSD 50. env(trust(gw, aliceUSD(100)), txflags(tfSetfAuth)); env(trust(alice, gwUSD(100))); env.close(); env(pay(gw, alice, gwUSD(50))); env.close(); env.require(balance(alice, gwUSD(50))); // alice's offer should cross gw's env(offer(alice, MUSO(4000), gwUSD(40))); env.close(); env.require(offers(alice, 0)); env.require(balance(alice, gwUSD(10))); env.require(offers(gw, 0)); } void testDeletedOfferIssuer(FeatureBitset features) { // Show that an offer who's issuer has been deleted cannot be crossed. using namespace jtx; testcase("Deleted offer issuer"); auto trustLineExists = [](jtx::Env const& env, jtx::Account const& src, jtx::Account const& dst, Currency const& cur) -> bool { return bool(env.le(keylet::line(src, dst, cur))); }; Account const alice("alice"); Account const becky("becky"); Account const carol("carol"); Account const gw("gateway"); auto const USD = gw["USD"]; auto const BUX = alice["BUX"]; Env env{*this, features}; env.fund(MUSO(10000), alice, becky, carol, noMUSO(gw)); env.trust(USD(1000), becky); env(pay(gw, becky, USD(5))); env.close(); BEAST_EXPECT(trustLineExists(env, gw, becky, USD.currency)); // Make offers that produce USD and can be crossed two ways: // direct MUSO -> USD // direct BUX -> USD env(offer(becky, MUSO(2), USD(2)), txflags(tfPassive)); std::uint32_t const beckyBuxUsdSeq{env.seq(becky)}; env(offer(becky, BUX(3), USD(3)), txflags(tfPassive)); env.close(); // becky keeps the offers, but removes the trustline. env(pay(becky, gw, USD(5))); env.trust(USD(0), becky); env.close(); BEAST_EXPECT(!trustLineExists(env, gw, becky, USD.currency)); BEAST_EXPECT(isOffer(env, becky, MUSO(2), USD(2))); BEAST_EXPECT(isOffer(env, becky, BUX(3), USD(3))); // Delete gw's account. { // The ledger sequence needs to far enough ahead of the account // sequence before the account can be deleted. int const delta = [&env, &gw, openLedgerSeq = env.current()->seq()]() -> int { std::uint32_t const gwSeq{env.seq(gw)}; if (gwSeq + 255 > openLedgerSeq) return gwSeq - openLedgerSeq + 255; return 0; }(); for (int i = 0; i < delta; ++i) env.close(); // Account deletion has a high fee. Account for that. env(acctdelete(gw, alice), fee(drops(env.current()->fees().increment))); env.close(); // Verify that gw's account root is gone from the ledger. BEAST_EXPECT(!env.closed()->exists(keylet::account(gw.id()))); } // alice crosses becky's first offer. The offer create fails because // the USD issuer is not in the ledger. env(offer(alice, USD(2), MUSO(2)), ter(tecNO_ISSUER)); env.close(); env.require(offers(alice, 0)); BEAST_EXPECT(isOffer(env, becky, MUSO(2), USD(2))); BEAST_EXPECT(isOffer(env, becky, BUX(3), USD(3))); // alice crosses becky's second offer. Again, the offer create fails // because the USD issuer is not in the ledger. env(offer(alice, USD(3), BUX(3)), ter(tecNO_ISSUER)); env.require(offers(alice, 0)); BEAST_EXPECT(isOffer(env, becky, MUSO(2), USD(2))); BEAST_EXPECT(isOffer(env, becky, BUX(3), USD(3))); // Cancel becky's BUX -> USD offer so we can try auto-bridging. env(offer_cancel(becky, beckyBuxUsdSeq)); env.close(); BEAST_EXPECT(!isOffer(env, becky, BUX(3), USD(3))); // alice creates an offer that can be auto-bridged with becky's // remaining offer. env.trust(BUX(1000), carol); env(pay(alice, carol, BUX(2))); env(offer(alice, BUX(2), MUSO(2))); env.close(); // carol attempts the auto-bridge. Again, the offer create fails // because the USD issuer is not in the ledger. env(offer(carol, USD(2), BUX(2)), ter(tecNO_ISSUER)); env.close(); BEAST_EXPECT(isOffer(env, alice, BUX(2), MUSO(2))); BEAST_EXPECT(isOffer(env, becky, MUSO(2), USD(2))); } void testTickSize(FeatureBitset features) { testcase("Tick Size"); using namespace jtx; // Try to set tick size out of range { Env env{*this, features}; auto const gw = Account{"gateway"}; env.fund(MUSO(10000), gw); auto txn = noop(gw); txn[sfTickSize.fieldName] = Quality::minTickSize - 1; env(txn, ter(temBAD_TICK_SIZE)); txn[sfTickSize.fieldName] = Quality::minTickSize; env(txn); BEAST_EXPECT((*env.le(gw))[sfTickSize] == Quality::minTickSize); txn = noop(gw); txn[sfTickSize.fieldName] = Quality::maxTickSize; env(txn); BEAST_EXPECT(!env.le(gw)->isFieldPresent(sfTickSize)); txn = noop(gw); txn[sfTickSize.fieldName] = Quality::maxTickSize - 1; env(txn); BEAST_EXPECT((*env.le(gw))[sfTickSize] == Quality::maxTickSize - 1); txn = noop(gw); txn[sfTickSize.fieldName] = Quality::maxTickSize + 1; env(txn, ter(temBAD_TICK_SIZE)); txn[sfTickSize.fieldName] = 0; env(txn); BEAST_EXPECT(!env.le(gw)->isFieldPresent(sfTickSize)); } Env env{*this, features}; auto const gw = Account{"gateway"}; auto const alice = Account{"alice"}; auto const XTS = gw["XTS"]; auto const XXX = gw["XXX"]; env.fund(MUSO(10000), gw, alice); { // Gateway sets its tick size to 5 auto txn = noop(gw); txn[sfTickSize.fieldName] = 5; env(txn); BEAST_EXPECT((*env.le(gw))[sfTickSize] == 5); } env(trust(alice, XTS(1000))); env(trust(alice, XXX(1000))); env(pay(gw, alice, alice["XTS"](100))); env(pay(gw, alice, alice["XXX"](100))); env(offer(alice, XTS(10), XXX(30))); env(offer(alice, XTS(30), XXX(10))); env(offer(alice, XTS(10), XXX(30)), json(jss::Flags, tfSell)); env(offer(alice, XTS(30), XXX(10)), json(jss::Flags, tfSell)); std::map<std::uint32_t, std::pair<STAmount, STAmount>> offers; forEachItem( *env.current(), alice, [&](std::shared_ptr<SLE const> const& sle) { if (sle->getType() == ltOFFER) offers.emplace( (*sle)[sfSequence], std::make_pair( (*sle)[sfTakerPays], (*sle)[sfTakerGets])); }); // first offer auto it = offers.begin(); BEAST_EXPECT(it != offers.end()); BEAST_EXPECT( it->second.first == XTS(10) && it->second.second < XXX(30) && it->second.second > XXX(29.9994)); // second offer ++it; BEAST_EXPECT(it != offers.end()); BEAST_EXPECT( it->second.first == XTS(30) && it->second.second == XXX(10)); // third offer ++it; BEAST_EXPECT(it != offers.end()); BEAST_EXPECT( it->second.first == XTS(10.0002) && it->second.second == XXX(30)); // fourth offer // exact TakerPays is XTS(1/.033333) ++it; BEAST_EXPECT(it != offers.end()); BEAST_EXPECT( it->second.first == XTS(30) && it->second.second == XXX(10)); BEAST_EXPECT(++it == offers.end()); } // Helper function that returns offers on an account sorted by sequence. static std::vector<std::shared_ptr<SLE const>> sortedOffersOnAccount(jtx::Env& env, jtx::Account const& acct) { std::vector<std::shared_ptr<SLE const>> offers{ offersOnAccount(env, acct)}; std::sort( offers.begin(), offers.end(), [](std::shared_ptr<SLE const> const& rhs, std::shared_ptr<SLE const> const& lhs) { return (*rhs)[sfSequence] < (*lhs)[sfSequence]; }); return offers; } void testTicketOffer(FeatureBitset features) { testcase("Ticket Offers"); using namespace jtx; // Two goals for this test. // // o Verify that offers can be created using tickets. // // o Show that offers in the _same_ order book remain in // chronological order regardless of sequence/ticket numbers. Env env{*this, features}; auto const gw = Account{"gateway"}; auto const alice = Account{"alice"}; auto const bob = Account{"bob"}; auto const USD = gw["USD"]; env.fund(MUSO(10000), gw, alice, bob); env.close(); env(trust(alice, USD(1000))); env(trust(bob, USD(1000))); env.close(); env(pay(gw, alice, USD(200))); env.close(); // Create four offers from the same account with identical quality // so they go in the same order book. Each offer goes in a different // ledger so the chronology is clear. std::uint32_t const offerId_0{env.seq(alice)}; env(offer(alice, MUSO(50), USD(50))); env.close(); // Create two tickets. std::uint32_t const ticketSeq{env.seq(alice) + 1}; env(ticket::create(alice, 2)); env.close(); // Create another sequence-based offer. std::uint32_t const offerId_1{env.seq(alice)}; BEAST_EXPECT(offerId_1 == offerId_0 + 4); env(offer(alice, MUSO(50), USD(50))); env.close(); // Create two ticket based offers in reverse order. std::uint32_t const offerId_2{ticketSeq + 1}; env(offer(alice, MUSO(50), USD(50)), ticket::use(offerId_2)); env.close(); // Create the last offer. std::uint32_t const offerId_3{ticketSeq}; env(offer(alice, MUSO(50), USD(50)), ticket::use(offerId_3)); env.close(); // Verify that all of alice's offers are present. { auto offers = sortedOffersOnAccount(env, alice); BEAST_EXPECT(offers.size() == 4); BEAST_EXPECT(offers[0]->getFieldU32(sfSequence) == offerId_0); BEAST_EXPECT(offers[1]->getFieldU32(sfSequence) == offerId_3); BEAST_EXPECT(offers[2]->getFieldU32(sfSequence) == offerId_2); BEAST_EXPECT(offers[3]->getFieldU32(sfSequence) == offerId_1); env.require(balance(alice, USD(200))); env.require(owners(alice, 5)); } // Cross alice's first offer. env(offer(bob, USD(50), MUSO(50))); env.close(); // Verify that the first offer alice created was consumed. { auto offers = sortedOffersOnAccount(env, alice); BEAST_EXPECT(offers.size() == 3); BEAST_EXPECT(offers[0]->getFieldU32(sfSequence) == offerId_3); BEAST_EXPECT(offers[1]->getFieldU32(sfSequence) == offerId_2); BEAST_EXPECT(offers[2]->getFieldU32(sfSequence) == offerId_1); } // Cross alice's second offer. env(offer(bob, USD(50), MUSO(50))); env.close(); // Verify that the second offer alice created was consumed. { auto offers = sortedOffersOnAccount(env, alice); BEAST_EXPECT(offers.size() == 2); BEAST_EXPECT(offers[0]->getFieldU32(sfSequence) == offerId_3); BEAST_EXPECT(offers[1]->getFieldU32(sfSequence) == offerId_2); } // Cross alice's third offer. env(offer(bob, USD(50), MUSO(50))); env.close(); // Verify that the third offer alice created was consumed. { auto offers = sortedOffersOnAccount(env, alice); BEAST_EXPECT(offers.size() == 1); BEAST_EXPECT(offers[0]->getFieldU32(sfSequence) == offerId_3); } // Cross alice's last offer. env(offer(bob, USD(50), MUSO(50))); env.close(); // Verify that the third offer alice created was consumed. { auto offers = sortedOffersOnAccount(env, alice); BEAST_EXPECT(offers.size() == 0); } env.require(balance(alice, USD(0))); env.require(owners(alice, 1)); env.require(balance(bob, USD(200))); env.require(owners(bob, 1)); } void testTicketCancelOffer(FeatureBitset features) { testcase("Ticket Cancel Offers"); using namespace jtx; // Verify that offers created with or without tickets can be canceled // by transactions with or without tickets. Env env{*this, features}; auto const gw = Account{"gateway"}; auto const alice = Account{"alice"}; auto const USD = gw["USD"]; env.fund(MUSO(10000), gw, alice); env.close(); env(trust(alice, USD(1000))); env.close(); env.require(owners(alice, 1), tickets(alice, 0)); env(pay(gw, alice, USD(200))); env.close(); // Create the first of four offers using a sequence. std::uint32_t const offerSeqId_0{env.seq(alice)}; env(offer(alice, MUSO(50), USD(50))); env.close(); env.require(owners(alice, 2), tickets(alice, 0)); // Create four tickets. std::uint32_t const ticketSeq{env.seq(alice) + 1}; env(ticket::create(alice, 4)); env.close(); env.require(owners(alice, 6), tickets(alice, 4)); // Create the second (also sequence-based) offer. std::uint32_t const offerSeqId_1{env.seq(alice)}; BEAST_EXPECT(offerSeqId_1 == offerSeqId_0 + 6); env(offer(alice, MUSO(50), USD(50))); env.close(); // Create the third (ticket-based) offer. std::uint32_t const offerTixId_0{ticketSeq + 1}; env(offer(alice, MUSO(50), USD(50)), ticket::use(offerTixId_0)); env.close(); // Create the last offer. std::uint32_t const offerTixId_1{ticketSeq}; env(offer(alice, MUSO(50), USD(50)), ticket::use(offerTixId_1)); env.close(); // Verify that all of alice's offers are present. { auto offers = sortedOffersOnAccount(env, alice); BEAST_EXPECT(offers.size() == 4); BEAST_EXPECT(offers[0]->getFieldU32(sfSequence) == offerSeqId_0); BEAST_EXPECT(offers[1]->getFieldU32(sfSequence) == offerTixId_1); BEAST_EXPECT(offers[2]->getFieldU32(sfSequence) == offerTixId_0); BEAST_EXPECT(offers[3]->getFieldU32(sfSequence) == offerSeqId_1); env.require(balance(alice, USD(200))); env.require(owners(alice, 7)); } // Use a ticket to cancel an offer created with a sequence. env(offer_cancel(alice, offerSeqId_0), ticket::use(ticketSeq + 2)); env.close(); // Verify that offerSeqId_0 was canceled. { auto offers = sortedOffersOnAccount(env, alice); BEAST_EXPECT(offers.size() == 3); BEAST_EXPECT(offers[0]->getFieldU32(sfSequence) == offerTixId_1); BEAST_EXPECT(offers[1]->getFieldU32(sfSequence) == offerTixId_0); BEAST_EXPECT(offers[2]->getFieldU32(sfSequence) == offerSeqId_1); } // Use a ticket to cancel an offer created with a ticket. env(offer_cancel(alice, offerTixId_0), ticket::use(ticketSeq + 3)); env.close(); // Verify that offerTixId_0 was canceled. { auto offers = sortedOffersOnAccount(env, alice); BEAST_EXPECT(offers.size() == 2); BEAST_EXPECT(offers[0]->getFieldU32(sfSequence) == offerTixId_1); BEAST_EXPECT(offers[1]->getFieldU32(sfSequence) == offerSeqId_1); } // All of alice's tickets should now be used up. env.require(owners(alice, 3), tickets(alice, 0)); // Use a sequence to cancel an offer created with a ticket. env(offer_cancel(alice, offerTixId_1)); env.close(); // Verify that offerTixId_1 was canceled. { auto offers = sortedOffersOnAccount(env, alice); BEAST_EXPECT(offers.size() == 1); BEAST_EXPECT(offers[0]->getFieldU32(sfSequence) == offerSeqId_1); } // Use a sequence to cancel an offer created with a sequence. env(offer_cancel(alice, offerSeqId_1)); env.close(); // Verify that offerSeqId_1 was canceled. // All of alice's tickets should now be used up. env.require(owners(alice, 1), tickets(alice, 0), offers(alice, 0)); } void testFalseAssert() { // An assert was falsely triggering when computing rates for offers. // This unit test would trigger that assert (which has been removed). testcase("false assert"); using namespace jtx; Env env{*this}; auto const alice = Account("alice"); auto const USD = alice["USD"]; env.fund(MUSO(10000), alice); env.close(); env(offer(alice, MUSO(100000000000), USD(100000000))); pass(); } void testAll(FeatureBitset features) { testCanceledOffer(features); testRmFundedOffer(features); testTinyPayment(features); testMUSOTinyPayment(features); testEnforceNoMUSO(features); testInsufficientReserve(features); testFillModes(features); testMalformed(features); testExpiration(features); testUnfundedCross(features); testSelfCross(false, features); testSelfCross(true, features); testNegativeBalance(features); testOfferCrossWithMUSO(true, features); testOfferCrossWithMUSO(false, features); testOfferCrossWithLimitOverride(features); testOfferAcceptThenCancel(features); testOfferCancelPastAndFuture(features); testCurrencyConversionEntire(features); testCurrencyConversionIntoDebt(features); testCurrencyConversionInParts(features); testCrossCurrencyStartMUSO(features); testCrossCurrencyEndMUSO(features); testCrossCurrencyBridged(features); testBridgedSecondLegDry(features); testOfferFeesConsumeFunds(features); testOfferCreateThenCross(features); testSellFlagBasic(features); testSellFlagExceedLimit(features); testGatewayCrossCurrency(features); testPartialCross(features); testMUSODirectCross(features); testDirectCross(features); testBridgedCross(features); testSellOffer(features); testSellWithFillOrKill(features); testTransferRateOffer(features); testSelfCrossOffer(features); testSelfIssueOffer(features); testBadPathAssert(features); testDirectToDirectPath(features); testSelfCrossLowQualityOffer(features); testOfferInScaling(features); testOfferInScalingWithXferRate(features); testOfferThresholdWithReducedFunds(features); testTinyOffer(features); testSelfPayXferFeeOffer(features); testSelfPayUnlimitedFunds(features); testRequireAuth(features); testMissingAuth(features); testRCSmoketest(features); testSelfAuth(features); testDeletedOfferIssuer(features); testTickSize(features); testTicketOffer(features); testTicketCancelOffer(features); } void run() override { using namespace jtx; FeatureBitset const all{supported_amendments()}; FeatureBitset const flowCross{featureFlowCross}; FeatureBitset const takerDryOffer{fixTakerDryOfferRemoval}; testAll(all - takerDryOffer); testAll(all - flowCross - takerDryOffer); testAll(all - flowCross); testAll(all); testFalseAssert(); } }; class Offer_manual_test : public Offer_test { void run() override { using namespace jtx; FeatureBitset const all{supported_amendments()}; FeatureBitset const flowCross{featureFlowCross}; FeatureBitset const f1513{fix1513}; FeatureBitset const takerDryOffer{fixTakerDryOfferRemoval}; testAll(all - flowCross - f1513); testAll(all - flowCross); testAll(all - f1513); testAll(all); testAll(all - flowCross - takerDryOffer); } }; BEAST_DEFINE_TESTSUITE_PRIO(Offer, tx, MUSO, 4); BEAST_DEFINE_TESTSUITE_MANUAL_PRIO(Offer_manual, tx, MUSO, 20); } // namespace test } // namespace MUSO
189,202
65,579
/* * Copyright (c) 2016, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * This file implements the CoAP message generation and parsing. */ #include "coap_message.hpp" #include "coap/coap.hpp" #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/encoding.hpp" #include "common/instance.hpp" #include "common/random.hpp" namespace ot { namespace Coap { void Message::Init(void) { memset(&GetHelpData(), 0, sizeof(GetHelpData())); SetVersion(kVersion1); SetOffset(0); GetHelpData().mHeaderLength = kMinHeaderLength; SetLength(GetHelpData().mHeaderLength); } void Message::Init(Type aType, Code aCode) { Init(); SetType(aType); SetCode(aCode); } otError Message::Init(Type aType, Code aCode, const char *aUriPath) { otError error; Init(aType, aCode); SuccessOrExit(error = SetToken(kDefaultTokenLength)); SuccessOrExit(error = AppendUriPathOptions(aUriPath)); exit: return error; } void Message::Finish(void) { Write(0, GetOptionStart(), &GetHelpData().mHeader); } otError Message::AppendOption(uint16_t aNumber, uint16_t aLength, const void *aValue) { otError error = OT_ERROR_NONE; uint16_t optionDelta = aNumber - GetHelpData().mOptionLast; uint16_t optionLength; uint8_t buf[kMaxOptionHeaderSize] = {0}; uint8_t *cur = &buf[1]; // Assure that no option is inserted out of order. VerifyOrExit(aNumber >= GetHelpData().mOptionLast, error = OT_ERROR_INVALID_ARGS); // Calculate the total option size and check the buffers. optionLength = 1 + aLength; optionLength += optionDelta < kOption1ByteExtensionOffset ? 0 : (optionDelta < kOption2ByteExtensionOffset ? 1 : 2); optionLength += aLength < kOption1ByteExtensionOffset ? 0 : (aLength < kOption2ByteExtensionOffset ? 1 : 2); VerifyOrExit(GetLength() + optionLength < kMaxHeaderLength, error = OT_ERROR_NO_BUFS); // Insert option delta. if (optionDelta < kOption1ByteExtensionOffset) { *buf = (optionDelta << kOptionDeltaOffset) & kOptionDeltaMask; } else if (optionDelta < kOption2ByteExtensionOffset) { *buf |= kOption1ByteExtension << kOptionDeltaOffset; *cur++ = (optionDelta - kOption1ByteExtensionOffset) & 0xff; } else { *buf |= kOption2ByteExtension << kOptionDeltaOffset; optionDelta -= kOption2ByteExtensionOffset; *cur++ = optionDelta >> 8; *cur++ = optionDelta & 0xff; } // Insert option length. if (aLength < kOption1ByteExtensionOffset) { *buf |= aLength; } else if (aLength < kOption2ByteExtensionOffset) { *buf |= kOption1ByteExtension; *cur++ = (aLength - kOption1ByteExtensionOffset) & 0xff; } else { *buf |= kOption2ByteExtension; optionLength = aLength - kOption2ByteExtensionOffset; *cur++ = optionLength >> 8; *cur++ = optionLength & 0xff; } SuccessOrExit(error = Append(buf, static_cast<uint16_t>(cur - buf))); SuccessOrExit(error = Append(aValue, aLength)); GetHelpData().mOptionLast = aNumber; GetHelpData().mHeaderLength = GetLength(); exit: return error; } otError Message::AppendUintOption(uint16_t aNumber, uint32_t aValue) { uint16_t length = sizeof(aValue); uint8_t *value; aValue = Encoding::BigEndian::HostSwap32(aValue); value = reinterpret_cast<uint8_t *>(&aValue); // skip preceding zeros while (value[0] == 0 && length > 0) { value++; length--; } return AppendOption(aNumber, length, value); } otError Message::AppendStringOption(uint16_t aNumber, const char *aValue) { return AppendOption(aNumber, static_cast<uint16_t>(strlen(aValue)), aValue); } otError Message::AppendObserveOption(uint32_t aObserve) { return AppendUintOption(OT_COAP_OPTION_OBSERVE, aObserve & 0xFFFFFF); } otError Message::AppendUriPathOptions(const char *aUriPath) { otError error = OT_ERROR_NONE; const char *cur = aUriPath; const char *end; while ((end = strchr(cur, '/')) != NULL) { SuccessOrExit(error = AppendOption(OT_COAP_OPTION_URI_PATH, static_cast<uint16_t>(end - cur), cur)); cur = end + 1; } SuccessOrExit(error = AppendStringOption(OT_COAP_OPTION_URI_PATH, cur)); exit: return error; } otError Message::AppendProxyUriOption(const char *aProxyUri) { return AppendStringOption(OT_COAP_OPTION_PROXY_URI, aProxyUri); } otError Message::AppendContentFormatOption(otCoapOptionContentFormat aContentFormat) { return AppendUintOption(OT_COAP_OPTION_CONTENT_FORMAT, static_cast<uint32_t>(aContentFormat)); } otError Message::AppendMaxAgeOption(uint32_t aMaxAge) { return AppendUintOption(OT_COAP_OPTION_MAX_AGE, aMaxAge); } otError Message::AppendUriQueryOption(const char *aUriQuery) { return AppendStringOption(OT_COAP_OPTION_URI_QUERY, aUriQuery); } const otCoapOption *Message::GetFirstOption(void) { const otCoapOption *option = NULL; memset(&GetHelpData().mOption, 0, sizeof(GetHelpData().mOption)); VerifyOrExit(GetLength() - GetHelpData().mHeaderOffset >= GetOptionStart()); GetHelpData().mNextOptionOffset = GetHelpData().mHeaderOffset + GetOptionStart(); if (GetHelpData().mNextOptionOffset < GetLength()) { option = GetNextOption(); } exit: return option; } const otCoapOption *Message::GetNextOption(void) { otError error = OT_ERROR_NONE; uint16_t optionDelta; uint16_t optionLength; uint8_t buf[kMaxOptionHeaderSize]; uint8_t * cur = buf + 1; otCoapOption *rval = NULL; VerifyOrExit(GetHelpData().mNextOptionOffset < GetLength(), error = OT_ERROR_NOT_FOUND); Read(GetHelpData().mNextOptionOffset, sizeof(buf), buf); optionDelta = buf[0] >> 4; optionLength = buf[0] & 0xf; GetHelpData().mNextOptionOffset += sizeof(uint8_t); if (optionDelta < kOption1ByteExtension) { // do nothing } else if (optionDelta == kOption1ByteExtension) { optionDelta = kOption1ByteExtensionOffset + cur[0]; GetHelpData().mNextOptionOffset += sizeof(uint8_t); cur++; } else if (optionDelta == kOption2ByteExtension) { optionDelta = kOption2ByteExtensionOffset + static_cast<uint16_t>((cur[0] << 8) | cur[1]); GetHelpData().mNextOptionOffset += sizeof(uint16_t); cur += 2; } else { // RFC7252 (Section 3): // Reserved for payload marker. VerifyOrExit(optionLength == 0xf, error = OT_ERROR_PARSE); // The presence of a marker followed by a zero-length payload MUST be processed // as a message format error. VerifyOrExit(GetHelpData().mNextOptionOffset < GetLength(), error = OT_ERROR_PARSE); ExitNow(error = OT_ERROR_NOT_FOUND); } if (optionLength < kOption1ByteExtension) { // do nothing } else if (optionLength == kOption1ByteExtension) { optionLength = kOption1ByteExtensionOffset + cur[0]; GetHelpData().mNextOptionOffset += sizeof(uint8_t); } else if (optionLength == kOption2ByteExtension) { optionLength = kOption2ByteExtensionOffset + static_cast<uint16_t>((cur[0] << 8) | cur[1]); GetHelpData().mNextOptionOffset += sizeof(uint16_t); } else { ExitNow(error = OT_ERROR_PARSE); } VerifyOrExit(optionLength <= GetLength() - GetHelpData().mNextOptionOffset, error = OT_ERROR_PARSE); rval = &GetHelpData().mOption; rval->mNumber += optionDelta; rval->mLength = optionLength; GetHelpData().mNextOptionOffset += optionLength; exit: if (error == OT_ERROR_PARSE) { GetHelpData().mNextOptionOffset = 0; } return rval; } otError Message::GetOptionValue(void *aValue) const { otError error = OT_ERROR_NONE; const otCoapOption &option = GetHelpData().mOption; VerifyOrExit(GetHelpData().mNextOptionOffset > 0, error = OT_ERROR_NOT_FOUND); VerifyOrExit(Read(GetHelpData().mNextOptionOffset - option.mLength, option.mLength, aValue) == option.mLength, error = OT_ERROR_PARSE); exit: return error; } otError Message::SetPayloadMarker(void) { otError error = OT_ERROR_NONE; uint8_t marker = 0xff; VerifyOrExit(GetLength() < kMaxHeaderLength, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = Append(&marker, sizeof(marker))); GetHelpData().mHeaderLength = GetLength(); // Set offset to the start of payload. SetOffset(GetHelpData().mHeaderLength); exit: return error; } otError Message::ParseHeader(void) { otError error = OT_ERROR_NONE; assert(mBuffer.mHead.mInfo.mReserved >= sizeof(GetHelpData()) + static_cast<size_t>((reinterpret_cast<uint8_t *>(&GetHelpData()) - mBuffer.mHead.mData))); memset(&GetHelpData(), 0, sizeof(GetHelpData())); GetHelpData().mHeaderOffset = GetOffset(); Read(GetHelpData().mHeaderOffset, sizeof(GetHelpData().mHeader), &GetHelpData().mHeader); for (const otCoapOption *option = GetFirstOption(); option != NULL; option = GetNextOption()) { } VerifyOrExit(GetHelpData().mNextOptionOffset > 0, error = OT_ERROR_PARSE); GetHelpData().mHeaderLength = GetHelpData().mNextOptionOffset - GetHelpData().mHeaderOffset; MoveOffset(GetHelpData().mHeaderLength); exit: return error; } otError Message::SetToken(const uint8_t *aToken, uint8_t aTokenLength) { GetHelpData().mHeader.mVersionTypeToken = (GetHelpData().mHeader.mVersionTypeToken & ~kTokenLengthMask) | ((aTokenLength << kTokenLengthOffset) & kTokenLengthMask); memcpy(GetHelpData().mHeader.mToken, aToken, aTokenLength); GetHelpData().mHeaderLength += aTokenLength; return SetLength(GetHelpData().mHeaderLength); } otError Message::SetToken(uint8_t aTokenLength) { uint8_t token[kMaxTokenLength] = {0}; assert(aTokenLength <= sizeof(token)); Random::NonCrypto::FillBuffer(token, aTokenLength); return SetToken(token, aTokenLength); } otError Message::SetDefaultResponseHeader(const Message &aRequest) { Init(OT_COAP_TYPE_ACKNOWLEDGMENT, OT_COAP_CODE_CHANGED); SetMessageId(aRequest.GetMessageId()); return SetToken(aRequest.GetToken(), aRequest.GetTokenLength()); } Message *Message::Clone(uint16_t aLength) const { Message *message = static_cast<Message *>(ot::Message::Clone(aLength)); VerifyOrExit(message != NULL); memcpy(&message->GetHelpData(), &GetHelpData(), sizeof(GetHelpData())); exit: return message; } #if OPENTHREAD_CONFIG_COAP_API_ENABLE const char *Message::CodeToString(void) const { const char *codeString; switch (GetCode()) { case OT_COAP_CODE_INTERNAL_ERROR: codeString = "InternalError"; break; case OT_COAP_CODE_METHOD_NOT_ALLOWED: codeString = "MethodNotAllowed"; break; case OT_COAP_CODE_CONTENT: codeString = "Content"; break; case OT_COAP_CODE_EMPTY: codeString = "Empty"; break; case OT_COAP_CODE_GET: codeString = "Get"; break; case OT_COAP_CODE_POST: codeString = "Post"; break; case OT_COAP_CODE_PUT: codeString = "Put"; break; case OT_COAP_CODE_DELETE: codeString = "Delete"; break; case OT_COAP_CODE_NOT_FOUND: codeString = "NotFound"; break; case OT_COAP_CODE_UNSUPPORTED_FORMAT: codeString = "UnsupportedFormat"; break; case OT_COAP_CODE_RESPONSE_MIN: codeString = "ResponseMin"; break; case OT_COAP_CODE_CREATED: codeString = "Created"; break; case OT_COAP_CODE_DELETED: codeString = "Deleted"; break; case OT_COAP_CODE_VALID: codeString = "Valid"; break; case OT_COAP_CODE_CHANGED: codeString = "Changed"; break; case OT_COAP_CODE_BAD_REQUEST: codeString = "BadRequest"; break; case OT_COAP_CODE_UNAUTHORIZED: codeString = "Unauthorized"; break; case OT_COAP_CODE_BAD_OPTION: codeString = "BadOption"; break; case OT_COAP_CODE_FORBIDDEN: codeString = "Forbidden"; break; case OT_COAP_CODE_NOT_ACCEPTABLE: codeString = "NotAcceptable"; break; case OT_COAP_CODE_PRECONDITION_FAILED: codeString = "PreconditionFailed"; break; case OT_COAP_CODE_REQUEST_TOO_LARGE: codeString = "RequestTooLarge"; break; case OT_COAP_CODE_NOT_IMPLEMENTED: codeString = "NotImplemented"; break; case OT_COAP_CODE_BAD_GATEWAY: codeString = "BadGateway"; break; case OT_COAP_CODE_SERVICE_UNAVAILABLE: codeString = "ServiceUnavailable"; break; case OT_COAP_CODE_GATEWAY_TIMEOUT: codeString = "GatewayTimeout"; break; case OT_COAP_CODE_PROXY_NOT_SUPPORTED: codeString = "ProxyNotSupported"; break; default: codeString = "Unknown"; break; } return codeString; } #endif // OPENTHREAD_CONFIG_COAP_API_ENABLE } // namespace Coap } // namespace ot
14,885
5,040
/*******************************************************************\ Module: Author: Daniel Kroening, kroening@kroening.com \*******************************************************************/ #include "boolbv_width.h" #include <algorithm> #include <util/arith_tools.h> #include <util/invariant.h> #include <util/std_types.h> boolbv_widtht::boolbv_widtht(const namespacet &_ns):ns(_ns) { } boolbv_widtht::~boolbv_widtht() { } const boolbv_widtht::entryt &boolbv_widtht::get_entry(const typet &type) const { // check cache first std::pair<cachet::iterator, bool> cache_result= cache.insert(std::pair<typet, entryt>(type, entryt())); entryt &entry=cache_result.first->second; if(!cache_result.second) // found! return entry; entry.total_width=0; const irep_idt type_id=type.id(); if(type_id==ID_struct) { const struct_typet::componentst &components= to_struct_type(type).components(); std::size_t offset=0; entry.members.resize(components.size()); for(std::size_t i=0; i<entry.members.size(); i++) { std::size_t sub_width=operator()(components[i].type()); entry.members[i].offset=offset; entry.members[i].width=sub_width; offset+=sub_width; } entry.total_width=offset; } else if(type_id==ID_union) { const union_typet::componentst &components= to_union_type(type).components(); entry.members.resize(components.size()); std::size_t max_width=0; for(std::size_t i=0; i<entry.members.size(); i++) { std::size_t sub_width=operator()(components[i].type()); entry.members[i].width=sub_width; max_width=std::max(max_width, sub_width); } entry.total_width=max_width; } else if(type_id==ID_bool) entry.total_width=1; else if(type_id==ID_c_bool) { entry.total_width=to_c_bool_type(type).get_width(); assert(entry.total_width!=0); } else if(type_id==ID_signedbv) { entry.total_width=to_signedbv_type(type).get_width(); assert(entry.total_width!=0); } else if(type_id==ID_unsignedbv) { entry.total_width=to_unsignedbv_type(type).get_width(); assert(entry.total_width!=0); } else if(type_id==ID_floatbv) { entry.total_width=to_floatbv_type(type).get_width(); assert(entry.total_width!=0); } else if(type_id==ID_fixedbv) { entry.total_width=to_fixedbv_type(type).get_width(); assert(entry.total_width!=0); } else if(type_id==ID_bv) { entry.total_width=to_bv_type(type).get_width(); assert(entry.total_width!=0); } else if(type_id==ID_verilog_signedbv || type_id==ID_verilog_unsignedbv) { // we encode with two bits entry.total_width=type.get_unsigned_int(ID_width)*2; assert(entry.total_width!=0); } else if(type_id==ID_range) { mp_integer from=string2integer(type.get_string(ID_from)), to=string2integer(type.get_string(ID_to)); mp_integer size=to-from+1; if(size>=1) { entry.total_width=integer2unsigned(address_bits(size)); assert(entry.total_width!=0); } } else if(type_id==ID_array) { const array_typet &array_type=to_array_type(type); std::size_t sub_width=operator()(array_type.subtype()); mp_integer array_size; if(to_integer(array_type.size(), array_size)) { // we can still use the theory of arrays for this entry.total_width=0; } else { mp_integer total=array_size*sub_width; if(total>(1<<30)) // realistic limit throw "array too large for flattening"; entry.total_width=integer2unsigned(total); } } else if(type_id==ID_vector) { const vector_typet &vector_type=to_vector_type(type); std::size_t sub_width=operator()(vector_type.subtype()); mp_integer vector_size; if(to_integer(vector_type.size(), vector_size)) { // we can still use the theory of arrays for this entry.total_width=0; } else { mp_integer total=vector_size*sub_width; if(total>(1<<30)) // realistic limit throw "vector too large for flattening"; entry.total_width=integer2unsigned(vector_size*sub_width); } } else if(type_id==ID_complex) { std::size_t sub_width=operator()(type.subtype()); entry.total_width=integer2unsigned(2*sub_width); } else if(type_id==ID_code) { } else if(type_id==ID_enumeration) { // get number of necessary bits std::size_t size=to_enumeration_type(type).elements().size(); entry.total_width=integer2unsigned(address_bits(size)); assert(entry.total_width!=0); } else if(type_id==ID_c_enum) { // these have a subtype entry.total_width=type.subtype().get_unsigned_int(ID_width); assert(entry.total_width!=0); } else if(type_id==ID_incomplete_c_enum) { // no width } else if(type_id==ID_pointer) entry.total_width = type_checked_cast<pointer_typet>(type).get_width(); else if(type_id==ID_symbol) entry=get_entry(ns.follow(type)); else if(type_id==ID_struct_tag) entry=get_entry(ns.follow_tag(to_struct_tag_type(type))); else if(type_id==ID_union_tag) entry=get_entry(ns.follow_tag(to_union_tag_type(type))); else if(type_id==ID_c_enum_tag) entry=get_entry(ns.follow_tag(to_c_enum_tag_type(type))); else if(type_id==ID_c_bit_field) { entry.total_width=to_c_bit_field_type(type).get_width(); } else if(type_id==ID_string) entry.total_width=32; return entry; } const boolbv_widtht::membert &boolbv_widtht::get_member( const struct_typet &type, const irep_idt &member) const { std::size_t component_number=type.component_number(member); return get_entry(type).members[component_number]; }
5,706
2,144
#include "MathUtils.h" MathUtils::MathUtils() { } MathUtils::~MathUtils() { } double MathUtils::ToRadians(double degrees) { return (degrees * PI) / 180.0; } double MathUtils::ToDegrees(double radians) { return (radians * 180.0) / PI; } double MathUtils::PI = 3.14159265359;
277
129
/* Copyright 2016 CyberTech Labs 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 "tcpRobotSimulator/tcpRobotSimulator.h" #include <QtCore/QThread> #include <QtCore/QMetaObject> #include "connection.h" using namespace tcpRobotSimulator; TcpRobotSimulator::TcpRobotSimulator(int port) { if(!listen(QHostAddress::LocalHost, port)) { qErrnoWarning(errno, "Failed to open TCP port"); } } TcpRobotSimulator::~TcpRobotSimulator() { if (mConnectionThread) { mConnectionThread->quit(); mConnectionThread->wait(); mConnectionThread.reset(); } } void TcpRobotSimulator::incomingConnection(qintptr socketDescriptor) { mConnection = new Connection(Protocol::messageLength, Heartbeat::use, mConfigVersion); mConnectionThread.reset(new QThread()); mConnection->moveToThread(mConnectionThread.data()); connect(mConnectionThread.data(), &QThread::finished, mConnection, &QObject::deleteLater); connect(mConnection, &Connection::runProgramRequestReceivedSignal , this, &TcpRobotSimulator::runProgramRequestReceivedSignal, Qt::QueuedConnection); connect(mConnectionThread.data(), &QThread::started , mConnection, [this, socketDescriptor](){ mConnection->init(socketDescriptor); }); mConnectionThread->start(); } bool TcpRobotSimulator::runProgramRequestReceived() const { return mConnection && mConnection->runProgramRequestReceived(); } bool TcpRobotSimulator::configVersionRequestReceived() const { return mConnection && mConnection->configVersionRequestReceived(); } bool TcpRobotSimulator::versionRequestReceived() const { return mConnection && mConnection->versionRequestReceived(); } void TcpRobotSimulator::setConfigVersion(const QString &configVersion) { mConfigVersion = configVersion; }
2,245
682
#include "PostgreSQLReplicationHandler.h" #include <DataStreams/PostgreSQLSource.h> #include <Processors/QueryPipeline.h> #include <Processors/Executors/PullingPipelineExecutor.h> #include <Databases/PostgreSQL/fetchPostgreSQLTableStructure.h> #include <Storages/PostgreSQL/StorageMaterializedPostgreSQL.h> #include <Interpreters/InterpreterDropQuery.h> #include <Interpreters/InterpreterInsertQuery.h> #include <Interpreters/InterpreterRenameQuery.h> #include <Common/setThreadName.h> #include <Interpreters/Context.h> #include <DataStreams/copyData.h> namespace DB { static const auto RESCHEDULE_MS = 500; static const auto BACKOFF_TRESHOLD_MS = 10000; namespace ErrorCodes { extern const int LOGICAL_ERROR; extern const int BAD_ARGUMENTS; } PostgreSQLReplicationHandler::PostgreSQLReplicationHandler( const String & replication_identifier, const String & remote_database_name_, const String & current_database_name_, const postgres::ConnectionInfo & connection_info_, ContextPtr context_, bool is_attach_, const size_t max_block_size_, bool allow_automatic_update_, bool is_materialized_postgresql_database_, const String tables_list_) : log(&Poco::Logger::get("PostgreSQLReplicationHandler")) , context(context_) , is_attach(is_attach_) , remote_database_name(remote_database_name_) , current_database_name(current_database_name_) , connection_info(connection_info_) , max_block_size(max_block_size_) , allow_automatic_update(allow_automatic_update_) , is_materialized_postgresql_database(is_materialized_postgresql_database_) , tables_list(tables_list_) , connection(std::make_shared<postgres::Connection>(connection_info_)) , milliseconds_to_wait(RESCHEDULE_MS) { replication_slot = fmt::format("{}_ch_replication_slot", replication_identifier); publication_name = fmt::format("{}_ch_publication", replication_identifier); startup_task = context->getSchedulePool().createTask("PostgreSQLReplicaStartup", [this]{ waitConnectionAndStart(); }); consumer_task = context->getSchedulePool().createTask("PostgreSQLReplicaStartup", [this]{ consumerFunc(); }); } void PostgreSQLReplicationHandler::addStorage(const std::string & table_name, StorageMaterializedPostgreSQL * storage) { materialized_storages[table_name] = storage; } void PostgreSQLReplicationHandler::startup() { startup_task->activateAndSchedule(); } void PostgreSQLReplicationHandler::waitConnectionAndStart() { try { connection->connect(); /// Will throw pqxx::broken_connection if no connection at the moment startSynchronization(false); } catch (const pqxx::broken_connection & pqxx_error) { LOG_ERROR(log, "Unable to set up connection. Reconnection attempt will continue. Error message: {}", pqxx_error.what()); startup_task->scheduleAfter(RESCHEDULE_MS); } catch (...) { tryLogCurrentException(__PRETTY_FUNCTION__); } } void PostgreSQLReplicationHandler::shutdown() { stop_synchronization.store(true); startup_task->deactivate(); consumer_task->deactivate(); } void PostgreSQLReplicationHandler::startSynchronization(bool throw_on_error) { { pqxx::work tx(connection->getRef()); createPublicationIfNeeded(tx); tx.commit(); } postgres::Connection replication_connection(connection_info, /* replication */true); pqxx::nontransaction tx(replication_connection.getRef()); /// List of nested tables (table_name -> nested_storage), which is passed to replication consumer. std::unordered_map<String, StoragePtr> nested_storages; /// snapshot_name is initialized only if a new replication slot is created. /// start_lsn is initialized in two places: /// 1. if replication slot does not exist, start_lsn will be returned with its creation return parameters; /// 2. if replication slot already exist, start_lsn is read from pg_replication_slots as /// `confirmed_flush_lsn` - the address (LSN) up to which the logical slot's consumer has confirmed receiving data. /// Data older than this is not available anymore. /// TODO: more tests String snapshot_name, start_lsn; auto initial_sync = [&]() { createReplicationSlot(tx, start_lsn, snapshot_name); for (const auto & [table_name, storage] : materialized_storages) { try { nested_storages[table_name] = loadFromSnapshot(snapshot_name, table_name, storage->as <StorageMaterializedPostgreSQL>()); } catch (Exception & e) { e.addMessage("while loading table {}.{}", remote_database_name, table_name); tryLogCurrentException(__PRETTY_FUNCTION__); /// Throw in case of single MaterializedPostgreSQL storage, because initial setup is done immediately /// (unlike database engine where it is done in a separate thread). if (throw_on_error) throw; } } }; /// There is one replication slot for each replication handler. In case of MaterializedPostgreSQL database engine, /// there is one replication slot per database. Its lifetime must be equal to the lifetime of replication handler. /// Recreation of a replication slot imposes reloading of all tables. if (!isReplicationSlotExist(tx, start_lsn, /* temporary */false)) { initial_sync(); } /// Always drop replication slot if it is CREATE query and not ATTACH. else if (!is_attach || new_publication) { dropReplicationSlot(tx); initial_sync(); } /// Synchronization and initial load already took place - do not create any new tables, just fetch StoragePtr's /// and pass them to replication consumer. else { for (const auto & [table_name, storage] : materialized_storages) { auto * materialized_storage = storage->as <StorageMaterializedPostgreSQL>(); try { /// Try load nested table, set materialized table metadata. nested_storages[table_name] = materialized_storage->prepare(); } catch (Exception & e) { e.addMessage("while loading table {}.{}", remote_database_name, table_name); tryLogCurrentException(__PRETTY_FUNCTION__); if (throw_on_error) throw; } } LOG_TRACE(log, "Loaded {} tables", nested_storages.size()); } tx.commit(); /// Pass current connection to consumer. It is not std::moved implicitly, but a shared_ptr is passed. /// Consumer and replication handler are always executed one after another (not concurrently) and share the same connection. /// (Apart from the case, when shutdownFinal is called). /// Handler uses it only for loadFromSnapshot and shutdown methods. consumer = std::make_shared<MaterializedPostgreSQLConsumer>( context, connection, replication_slot, publication_name, start_lsn, max_block_size, allow_automatic_update, nested_storages); consumer_task->activateAndSchedule(); /// Do not rely anymore on saved storage pointers. materialized_storages.clear(); } StoragePtr PostgreSQLReplicationHandler::loadFromSnapshot(String & snapshot_name, const String & table_name, StorageMaterializedPostgreSQL * materialized_storage) { auto tx = std::make_shared<pqxx::ReplicationTransaction>(connection->getRef()); std::string query_str = fmt::format("SET TRANSACTION SNAPSHOT '{}'", snapshot_name); tx->exec(query_str); /// Load from snapshot, which will show table state before creation of replication slot. /// Already connected to needed database, no need to add it to query. query_str = fmt::format("SELECT * FROM {}", doubleQuoteString(table_name)); materialized_storage->createNestedIfNeeded(fetchTableStructure(*tx, table_name)); auto nested_storage = materialized_storage->getNested(); auto insert = std::make_shared<ASTInsertQuery>(); insert->table_id = nested_storage->getStorageID(); auto insert_context = materialized_storage->getNestedTableContext(); InterpreterInsertQuery interpreter(insert, insert_context); auto block_io = interpreter.execute(); const StorageInMemoryMetadata & storage_metadata = nested_storage->getInMemoryMetadata(); auto sample_block = storage_metadata.getSampleBlockNonMaterialized(); auto input = std::make_unique<PostgreSQLTransactionSource<pqxx::ReplicationTransaction>>(tx, query_str, sample_block, DEFAULT_BLOCK_SIZE); QueryPipeline pipeline; pipeline.init(Pipe(std::move(input))); assertBlocksHaveEqualStructure(pipeline.getHeader(), block_io.out->getHeader(), "postgresql replica load from snapshot"); PullingPipelineExecutor executor(pipeline); Block block; block_io.out->writePrefix(); while (executor.pull(block)) block_io.out->write(block); block_io.out->writeSuffix(); nested_storage = materialized_storage->prepare(); auto nested_table_id = nested_storage->getStorageID(); LOG_TRACE(log, "Loaded table {}.{} (uuid: {})", nested_table_id.database_name, nested_table_id.table_name, toString(nested_table_id.uuid)); return nested_storage; } void PostgreSQLReplicationHandler::consumerFunc() { std::vector<std::pair<Int32, String>> skipped_tables; bool schedule_now = consumer->consume(skipped_tables); if (!skipped_tables.empty()) { try { reloadFromSnapshot(skipped_tables); } catch (...) { tryLogCurrentException(__PRETTY_FUNCTION__); } } if (stop_synchronization) { LOG_TRACE(log, "Replication thread is stopped"); return; } if (schedule_now) { milliseconds_to_wait = RESCHEDULE_MS; consumer_task->schedule(); LOG_DEBUG(log, "Scheduling replication thread: now"); } else { consumer_task->scheduleAfter(milliseconds_to_wait); if (milliseconds_to_wait < BACKOFF_TRESHOLD_MS) milliseconds_to_wait *= 2; LOG_TRACE(log, "Scheduling replication thread: after {} ms", milliseconds_to_wait); } } bool PostgreSQLReplicationHandler::isPublicationExist(pqxx::work & tx) { std::string query_str = fmt::format("SELECT exists (SELECT 1 FROM pg_publication WHERE pubname = '{}')", publication_name); pqxx::result result{tx.exec(query_str)}; assert(!result.empty()); return result[0][0].as<std::string>() == "t"; } void PostgreSQLReplicationHandler::createPublicationIfNeeded(pqxx::work & tx) { auto publication_exists = isPublicationExist(tx); if (!is_attach && publication_exists) { /// This is a case for single Materialized storage. In case of database engine this check is done in advance. LOG_WARNING(log, "Publication {} already exists, but it is a CREATE query, not ATTACH. Publication will be dropped", publication_name); connection->execWithRetry([&](pqxx::nontransaction & tx_){ dropPublication(tx_); }); } if (!is_attach || !publication_exists) { if (tables_list.empty()) { for (const auto & storage_data : materialized_storages) { if (!tables_list.empty()) tables_list += ", "; tables_list += doubleQuoteString(storage_data.first); } } if (tables_list.empty()) throw Exception(ErrorCodes::LOGICAL_ERROR, "No table found to be replicated"); /// 'ONLY' means just a table, without descendants. std::string query_str = fmt::format("CREATE PUBLICATION {} FOR TABLE ONLY {}", publication_name, tables_list); try { tx.exec(query_str); LOG_TRACE(log, "Created publication {} with tables list: {}", publication_name, tables_list); new_publication = true; } catch (Exception & e) { e.addMessage("while creating pg_publication"); throw; } } else { LOG_TRACE(log, "Using existing publication ({}) version", publication_name); } } bool PostgreSQLReplicationHandler::isReplicationSlotExist(pqxx::nontransaction & tx, String & start_lsn, bool temporary) { String slot_name; if (temporary) slot_name = replication_slot + "_tmp"; else slot_name = replication_slot; String query_str = fmt::format("SELECT active, restart_lsn, confirmed_flush_lsn FROM pg_replication_slots WHERE slot_name = '{}'", slot_name); pqxx::result result{tx.exec(query_str)}; /// Replication slot does not exist if (result.empty()) return false; start_lsn = result[0][2].as<std::string>(); LOG_TRACE(log, "Replication slot {} already exists (active: {}). Restart lsn position: {}, confirmed flush lsn: {}", slot_name, result[0][0].as<bool>(), result[0][1].as<std::string>(), start_lsn); return true; } void PostgreSQLReplicationHandler::createReplicationSlot( pqxx::nontransaction & tx, String & start_lsn, String & snapshot_name, bool temporary) { String query_str, slot_name; if (temporary) slot_name = replication_slot + "_tmp"; else slot_name = replication_slot; query_str = fmt::format("CREATE_REPLICATION_SLOT {} LOGICAL pgoutput EXPORT_SNAPSHOT", slot_name); try { pqxx::result result{tx.exec(query_str)}; start_lsn = result[0][1].as<std::string>(); snapshot_name = result[0][2].as<std::string>(); LOG_TRACE(log, "Created replication slot: {}, start lsn: {}", replication_slot, start_lsn); } catch (Exception & e) { e.addMessage("while creating PostgreSQL replication slot {}", slot_name); throw; } } void PostgreSQLReplicationHandler::dropReplicationSlot(pqxx::nontransaction & tx, bool temporary) { std::string slot_name; if (temporary) slot_name = replication_slot + "_tmp"; else slot_name = replication_slot; std::string query_str = fmt::format("SELECT pg_drop_replication_slot('{}')", slot_name); tx.exec(query_str); LOG_TRACE(log, "Dropped replication slot: {}", slot_name); } void PostgreSQLReplicationHandler::dropPublication(pqxx::nontransaction & tx) { std::string query_str = fmt::format("DROP PUBLICATION IF EXISTS {}", publication_name); tx.exec(query_str); LOG_TRACE(log, "Dropped publication: {}", publication_name); } void PostgreSQLReplicationHandler::shutdownFinal() { try { shutdown(); connection->execWithRetry([&](pqxx::nontransaction & tx){ dropPublication(tx); }); String last_committed_lsn; connection->execWithRetry([&](pqxx::nontransaction & tx) { if (isReplicationSlotExist(tx, last_committed_lsn, /* temporary */false)) dropReplicationSlot(tx, /* temporary */false); }); connection->execWithRetry([&](pqxx::nontransaction & tx) { if (isReplicationSlotExist(tx, last_committed_lsn, /* temporary */true)) dropReplicationSlot(tx, /* temporary */true); }); } catch (Exception & e) { e.addMessage("while dropping replication slot: {}", replication_slot); LOG_ERROR(log, "Failed to drop replication slot: {}. It must be dropped manually.", replication_slot); throw; } } /// Used by MaterializedPostgreSQL database engine. NameSet PostgreSQLReplicationHandler::fetchRequiredTables(postgres::Connection & connection_) { pqxx::work tx(connection_.getRef()); NameSet result_tables; bool publication_exists_before_startup = isPublicationExist(tx); LOG_DEBUG(log, "Publication exists: {}, is attach: {}", publication_exists_before_startup, is_attach); Strings expected_tables; if (!tables_list.empty()) { splitInto<','>(expected_tables, tables_list); if (expected_tables.empty()) throw Exception(ErrorCodes::BAD_ARGUMENTS, "Cannot parse tables list: {}", tables_list); for (auto & table_name : expected_tables) boost::trim(table_name); } if (publication_exists_before_startup) { if (!is_attach) { LOG_WARNING(log, "Publication {} already exists, but it is a CREATE query, not ATTACH. Publication will be dropped", publication_name); connection->execWithRetry([&](pqxx::nontransaction & tx_){ dropPublication(tx_); }); } else { if (tables_list.empty()) { LOG_WARNING(log, "Publication {} already exists and tables list is empty. Assuming publication is correct.", publication_name); result_tables = fetchPostgreSQLTablesList(tx, postgres_schema); } /// Check tables list from publication is the same as expected tables list. /// If not - drop publication and return expected tables list. else { result_tables = fetchTablesFromPublication(tx); NameSet diff; std::set_symmetric_difference(expected_tables.begin(), expected_tables.end(), result_tables.begin(), result_tables.end(), std::inserter(diff, diff.begin())); if (!diff.empty()) { String diff_tables; for (const auto & table_name : diff) { if (!diff_tables.empty()) diff_tables += ", "; diff_tables += table_name; } LOG_WARNING(log, "Publication {} already exists, but specified tables list differs from publication tables list in tables: {}.", publication_name, diff_tables); connection->execWithRetry([&](pqxx::nontransaction & tx_){ dropPublication(tx_); }); } } } } if (result_tables.empty()) { if (!tables_list.empty()) { result_tables = NameSet(expected_tables.begin(), expected_tables.end()); } else { /// Fetch all tables list from database. Publication does not exist yet, which means /// that no replication took place. Publication will be created in /// startSynchronization method. result_tables = fetchPostgreSQLTablesList(tx, postgres_schema); } } tx.commit(); return result_tables; } NameSet PostgreSQLReplicationHandler::fetchTablesFromPublication(pqxx::work & tx) { std::string query = fmt::format("SELECT tablename FROM pg_publication_tables WHERE pubname = '{}'", publication_name); std::unordered_set<std::string> tables; for (auto table_name : tx.stream<std::string>(query)) tables.insert(std::get<0>(table_name)); return tables; } PostgreSQLTableStructurePtr PostgreSQLReplicationHandler::fetchTableStructure( pqxx::ReplicationTransaction & tx, const std::string & table_name) const { if (!is_materialized_postgresql_database) return nullptr; return std::make_unique<PostgreSQLTableStructure>(fetchPostgreSQLTableStructure(tx, table_name, true, true, true)); } void PostgreSQLReplicationHandler::reloadFromSnapshot(const std::vector<std::pair<Int32, String>> & relation_data) { /// If table schema has changed, the table stops consuming changes from replication stream. /// If `allow_automatic_update` is true, create a new table in the background, load new table schema /// and all data from scratch. Then execute REPLACE query. /// This is only allowed for MaterializedPostgreSQL database engine. try { postgres::Connection replication_connection(connection_info, /* replication */true); pqxx::nontransaction tx(replication_connection.getRef()); String snapshot_name, start_lsn; if (isReplicationSlotExist(tx, start_lsn, /* temporary */true)) dropReplicationSlot(tx, /* temporary */true); createReplicationSlot(tx, start_lsn, snapshot_name, /* temporary */true); for (const auto & [relation_id, table_name] : relation_data) { auto storage = DatabaseCatalog::instance().getTable(StorageID(current_database_name, table_name), context); auto * materialized_storage = storage->as <StorageMaterializedPostgreSQL>(); /// If for some reason this temporary table already exists - also drop it. auto temp_materialized_storage = materialized_storage->createTemporary(); /// This snapshot is valid up to the end of the transaction, which exported it. StoragePtr temp_nested_storage = loadFromSnapshot(snapshot_name, table_name, temp_materialized_storage->as <StorageMaterializedPostgreSQL>()); auto table_id = materialized_storage->getNestedStorageID(); auto temp_table_id = temp_nested_storage->getStorageID(); LOG_TRACE(log, "Starting background update of table {} with table {}", table_id.getNameForLogs(), temp_table_id.getNameForLogs()); auto ast_rename = std::make_shared<ASTRenameQuery>(); ASTRenameQuery::Element elem { ASTRenameQuery::Table{table_id.database_name, table_id.table_name}, ASTRenameQuery::Table{temp_table_id.database_name, temp_table_id.table_name} }; ast_rename->elements.push_back(std::move(elem)); ast_rename->exchange = true; auto nested_context = materialized_storage->getNestedTableContext(); try { auto materialized_table_lock = materialized_storage->lockForShare(String(), context->getSettingsRef().lock_acquire_timeout); InterpreterRenameQuery(ast_rename, nested_context).execute(); { auto nested_storage = DatabaseCatalog::instance().getTable(StorageID(table_id.database_name, table_id.table_name), nested_context); auto nested_table_lock = nested_storage->lockForShare(String(), context->getSettingsRef().lock_acquire_timeout); auto nested_table_id = nested_storage->getStorageID(); materialized_storage->setNestedStorageID(nested_table_id); nested_storage = materialized_storage->prepare(); auto nested_storage_metadata = nested_storage->getInMemoryMetadataPtr(); auto nested_sample_block = nested_storage_metadata->getSampleBlock(); LOG_TRACE(log, "Updated table {}. New structure: {}", nested_table_id.getNameForLogs(), nested_sample_block.dumpStructure()); auto materialized_storage_metadata = nested_storage->getInMemoryMetadataPtr(); auto materialized_sample_block = materialized_storage_metadata->getSampleBlock(); assertBlocksHaveEqualStructure(nested_sample_block, materialized_sample_block, "while reloading table in the background"); /// Pass pointer to new nested table into replication consumer, remove current table from skip list and set start lsn position. consumer->updateNested(table_name, nested_storage, relation_id, start_lsn); } LOG_DEBUG(log, "Dropping table {}", temp_table_id.getNameForLogs()); InterpreterDropQuery::executeDropQuery(ASTDropQuery::Kind::Drop, nested_context, nested_context, temp_table_id, true); } catch (...) { tryLogCurrentException(__PRETTY_FUNCTION__); } } dropReplicationSlot(tx, /* temporary */true); tx.commit(); } catch (...) { tryLogCurrentException(__PRETTY_FUNCTION__); } } }
24,729
6,887
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/device/usb/usb_service_mac.h" #include <CoreFoundation/CFBase.h> #include <CoreFoundation/CoreFoundation.h> #include <IOKit/IOCFPlugIn.h> #include <IOKit/IOReturn.h> #include <memory> #include <string> #include <utility> #include <vector> #include "base/mac/foundation_util.h" #include "base/mac/scoped_ioplugininterface.h" #include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" #include "components/device_event_log/device_event_log.h" #include "services/device/usb/usb_descriptors.h" #include "services/device/usb/usb_device_mac.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace device { namespace { // USB class codes are defined by the USB specification. // https://www.usb.org/defined-class-codes constexpr uint8_t kDeviceClassHub = 0x09; // These methods are similar to the ones used by HidServiceMac. // TODO(https://crbug.com/1104271): Move these methods into a shared utility // file. absl::optional<std::u16string> GetStringProperty(io_service_t service, CFStringRef key) { base::ScopedCFTypeRef<CFStringRef> ref(base::mac::CFCast<CFStringRef>( IORegistryEntryCreateCFProperty(service, key, kCFAllocatorDefault, 0))); if (!ref) return absl::nullopt; return base::SysCFStringRefToUTF16(ref); } absl::optional<uint16_t> GetUint16Property(io_service_t service, CFStringRef property) { base::ScopedCFTypeRef<CFNumberRef> cf_number( base::mac::CFCast<CFNumberRef>(IORegistryEntryCreateCFProperty( service, property, kCFAllocatorDefault, 0))); if (!cf_number) return absl::nullopt; if (CFGetTypeID(cf_number) != CFNumberGetTypeID()) return absl::nullopt; uint16_t value; if (!CFNumberGetValue((CFNumberRef)cf_number, kCFNumberSInt16Type, &value)) return absl::nullopt; return value; } absl::optional<uint8_t> GetUint8Property(io_service_t service, CFStringRef property) { base::ScopedCFTypeRef<CFNumberRef> cf_number( base::mac::CFCast<CFNumberRef>(IORegistryEntryCreateCFProperty( service, property, kCFAllocatorDefault, 0))); bool success = false; uint8_t value; if (cf_number) { if (CFGetTypeID(cf_number) == CFNumberGetTypeID()) { success = CFNumberGetValue((CFNumberRef)cf_number, kCFNumberSInt8Type, &value); } } if (success) return value; return absl::nullopt; } } // namespace UsbServiceMac::UsbServiceMac() { notify_port_.reset(IONotificationPortCreate(kIOMasterPortDefault)); CFRunLoopAddSource(CFRunLoopGetMain(), IONotificationPortGetRunLoopSource(notify_port_.get()), kCFRunLoopDefaultMode); IOReturn result = IOServiceAddMatchingNotification( notify_port_.get(), kIOFirstMatchNotification, IOServiceMatching(kIOUSBDeviceClassName), FirstMatchCallback, this, devices_added_iterator_.InitializeInto()); if (result != kIOReturnSuccess) { USB_LOG(ERROR) << "Failed to listen for device arrival: " << std::hex << result << "."; return; } // Drain |devices_added_iterator_| to arm the notification. AddDevices(); result = IOServiceAddMatchingNotification( notify_port_.get(), kIOTerminatedNotification, IOServiceMatching(kIOUSBDeviceClassName), TerminatedCallback, this, devices_removed_iterator_.InitializeInto()); if (result != kIOReturnSuccess) { USB_LOG(ERROR) << "Failed to listen for device removal: " << std::hex << result << "."; return; } // Drain |devices_removed_iterator_| to arm the notification. RemoveDevices(); } UsbServiceMac::~UsbServiceMac() = default; // static void UsbServiceMac::FirstMatchCallback(void* context, io_iterator_t iterator) { DCHECK_EQ(CFRunLoopGetMain(), CFRunLoopGetCurrent()); UsbServiceMac* service = reinterpret_cast<UsbServiceMac*>(context); DCHECK_EQ(service->devices_added_iterator_, iterator); service->AddDevices(); } // static void UsbServiceMac::TerminatedCallback(void* context, io_iterator_t iterator) { DCHECK_EQ(CFRunLoopGetMain(), CFRunLoopGetCurrent()); UsbServiceMac* service = reinterpret_cast<UsbServiceMac*>(context); DCHECK_EQ(service->devices_removed_iterator_, iterator); service->RemoveDevices(); } void UsbServiceMac::AddDevices() { base::mac::ScopedIOObject<io_service_t> device; while (device.reset(IOIteratorNext(devices_added_iterator_)), device) { AddDevice(device); } } void UsbServiceMac::AddDevice(io_service_t device) { base::mac::ScopedIOPluginInterface<IOCFPlugInInterface> plugin_interface; int32_t score; // This call fails sometimes due to a resource shortage. // TODO(richardmachado): Figure out what is causing this failure. IOReturn kr = IOCreatePlugInInterfaceForService( device, kIOUSBDeviceUserClientTypeID, kIOCFPlugInInterfaceID, plugin_interface.InitializeInto(), &score); if ((kr != kIOReturnSuccess) || !plugin_interface.get()) { USB_LOG(ERROR) << "Unable to create a plug-in: " << std::hex << kr << "."; return; } base::mac::ScopedIOPluginInterface<IOUSBDeviceInterface182> device_interface; kr = (*plugin_interface) ->QueryInterface( plugin_interface.get(), CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID), reinterpret_cast<LPVOID*>(device_interface.InitializeInto())); if (kr != kIOReturnSuccess || !device_interface) { USB_LOG(ERROR) << "Couldn’t create a device interface."; return; } uint8_t device_class; if ((*device_interface)->GetDeviceClass(device_interface, &device_class) != kIOReturnSuccess) { return; } // We don't want to enumerate hubs. if (device_class == kDeviceClassHub) return; uint16_t vendor_id; if ((*device_interface)->GetDeviceVendor(device_interface, &vendor_id) != kIOReturnSuccess) { return; } uint16_t product_id; if ((*device_interface)->GetDeviceProduct(device_interface, &product_id) != kIOReturnSuccess) { return; } uint8_t device_protocol; if ((*device_interface) ->GetDeviceProtocol(device_interface, &device_protocol) != kIOReturnSuccess) { return; } uint8_t device_subclass; if ((*device_interface) ->GetDeviceSubClass(device_interface, &device_subclass) != kIOReturnSuccess) { return; } uint16_t device_version; if ((*device_interface) ->GetDeviceReleaseNumber(device_interface, &device_version) != kIOReturnSuccess) { return; } uint32_t location_id; if ((*device_interface)->GetLocationID(device_interface, &location_id) != kIOReturnSuccess) { return; } uint64_t entry_id; if (IORegistryEntryGetRegistryEntryID(device, &entry_id) != kIOReturnSuccess) return; absl::optional<uint8_t> property_uint8 = GetUint8Property(device, CFSTR("PortNum")); if (!property_uint8.has_value()) return; uint8_t port_number = property_uint8.value(); absl::optional<uint16_t> property_uint16 = GetUint16Property(device, CFSTR("bcdUSB")); uint16_t usb_version; if (!property_uint16.has_value()) return; usb_version = property_uint16.value(); absl::optional<std::u16string> property_string16 = GetStringProperty(device, CFSTR(kUSBVendorString)); std::u16string manufacturer_string; if (property_string16.has_value()) manufacturer_string = property_string16.value(); property_string16 = GetStringProperty(device, CFSTR(kUSBSerialNumberString)); std::u16string serial_number_string; if (property_string16.has_value()) serial_number_string = property_string16.value(); property_string16 = GetStringProperty(device, CFSTR(kUSBProductString)); std::u16string product_string; if (property_string16.has_value()) product_string = property_string16.value(); uint8_t num_config; if ((*device_interface) ->GetNumberOfConfigurations(device_interface, &num_config) != kIOReturnSuccess) { return; } // Populate device descriptor with all necessary configuration info. auto descriptor = std::make_unique<UsbDeviceDescriptor>(); IOUSBConfigurationDescriptorPtr desc; for (uint8_t i = 0; i < num_config; i++) { if ((*device_interface) ->GetConfigurationDescriptorPtr(device_interface, i, &desc) != kIOReturnSuccess) { return; } if (!descriptor->Parse(base::make_span(reinterpret_cast<uint8_t*>(desc), desc->wTotalLength))) { return; } } descriptor->device_info->usb_version_major = usb_version >> 8; descriptor->device_info->usb_version_minor = usb_version >> 4 & 0xf; descriptor->device_info->usb_version_subminor = usb_version & 0xf; descriptor->device_info->class_code = device_class; descriptor->device_info->subclass_code = device_subclass; descriptor->device_info->protocol_code = device_protocol; descriptor->device_info->vendor_id = vendor_id; descriptor->device_info->product_id = product_id; descriptor->device_info->device_version_major = device_version >> 8; descriptor->device_info->device_version_minor = device_version >> 4 & 0xf; descriptor->device_info->device_version_subminor = device_version & 0xf; descriptor->device_info->manufacturer_name = manufacturer_string; descriptor->device_info->product_name = product_string; descriptor->device_info->serial_number = serial_number_string; descriptor->device_info->bus_number = location_id >> 24; descriptor->device_info->port_number = port_number; scoped_refptr<UsbDeviceMac> mac_device = new UsbDeviceMac(entry_id, std::move(descriptor->device_info)); device_map_[entry_id] = mac_device; devices()[mac_device->guid()] = mac_device; NotifyDeviceAdded(mac_device); } void UsbServiceMac::RemoveDevices() { base::mac::ScopedIOObject<io_service_t> device; while (device.reset(IOIteratorNext(devices_removed_iterator_)), device) { uint64_t entry_id; if (kIOReturnSuccess != IORegistryEntryGetRegistryEntryID(device, &entry_id)) { continue; } auto it = device_map_.find(entry_id); if (it == device_map_.end()) continue; auto mac_device = it->second; device_map_.erase(it); auto by_guid_it = devices().find(mac_device->guid()); devices().erase(by_guid_it); NotifyDeviceRemoved(mac_device); mac_device->OnDisconnect(); } } } // namespace device
10,709
3,600
#include <migraphx/gpu/device/gelu.hpp> #include <migraphx/gpu/device/nary.hpp> #include <migraphx/gpu/device/types.hpp> #include <cmath> namespace migraphx { inline namespace MIGRAPHX_INLINE_NS { namespace gpu { namespace device { // x * 0.5 * (1.0 + erf(x / sqrt(2.0))) template <class T> auto gelu_fn(T x) __device__ { return x * 0.5 * (1 + ::erf(x * M_SQRT1_2)); } // 0.5 * x * (1 + tanh(sqrt(2 / pi) * (x + 0.044715 * pow(x, 3)))) template <class T> auto gelu_fn_new(T x) __device__ { return 0.5 * x * (1 + tanh(sqrt(M_2_PI) * (x + 0.044715 * x * x * x))); } void gelu(hipStream_t stream, const argument& result, const argument& arg) { nary(stream, result, arg)([](auto x) __device__ { return gelu_fn(to_hip_type(x)); }); } void gelu_new(hipStream_t stream, const argument& result, const argument& arg) { nary(stream, result, arg)([](auto x) __device__ { return gelu_fn_new(to_hip_type(x)); }); } void add_gelu(hipStream_t stream, const argument& result, const argument& arg1, const argument& arg2) { nary(stream, result, arg1, arg2)([](auto x, auto y) __device__ { auto sum = to_hip_type(x + y); return gelu_fn(sum); }); } void add_gelu_new(hipStream_t stream, const argument& result, const argument& arg1, const argument& arg2) { nary(stream, result, arg1, arg2)([](auto x, auto y) __device__ { auto sum = to_hip_type(x + y); return gelu_fn(sum); }); } } // namespace device } // namespace gpu } // namespace MIGRAPHX_INLINE_NS } // namespace migraphx
1,627
641
#include "entity.hpp" #include "move.hpp" #include "field.hpp" #include "io.hpp" #include <fstream> Entity::Entity(int _displayChar) { setDisplayChar(_displayChar); position.setXY(0, 0); } Entity::~Entity() { } Position Entity::getPosition() { Position _pos; _pos.from(position); return _pos; } void Entity::setPosition(Position _pos) { position.from(_pos); } void Entity::display() { putCharAt(getDisplayChar(), getPosition()); } void Entity::hit(Direction dir) {} void Entity::clear() { Field <char> * wf = getWallField(); if (wf == nullptr) { return; } putCharAt(wf->getAt(getPosition()), getPosition()); } void Entity::setDisplayChar(int _displayChar) { displayChar = _displayChar; } int Entity::getDisplayChar() { return displayChar; } void Entity::move(Direction dir) { switch(dir) { case DIR_UP: case DIR_DOWN: case DIR_LEFT: case DIR_RIGHT: bool success = false; Position newPosition = getPossibleMovePosition(getPosition(), dir, success); if (success) { clear(); setPosition(newPosition); display(); } break; } }
1,086
428
#ifndef SHADER_LOADER_HPP #define SHADER_LOADER_HPP #include <map> #include <string> #include <glbinding/gl/enum.h> using namespace gl; namespace shader_loader { // compile shader unsigned shader(std::string const& file_path, GLenum shader_type); // create program from given list of stages unsigned program(std::map<GLenum, std::string> const&); } #endif
385
139
#include "GameStateMachine.h" #include <iostream> void GameStateMachine::pushState(GameState* pState){ m_gameStates.push_back(pState); m_gameStates.back()->onEnter(); } void GameStateMachine::popState(){ if(!m_gameStates.empty()){ if(m_gameStates.back()->onExit()){ delete m_gameStates.back(); m_gameStates.pop_back(); } } } void GameStateMachine::changeState(GameState* pState){ if(!m_gameStates.empty()){ if(m_gameStates.back()->getStateID() == pState->getStateID()){ return; } if(m_gameStates.back()->onExit()){ m_gameStates.pop_back(); } } m_gameStates.push_back(pState); m_gameStates.back()->onEnter(); } void GameStateMachine::update(){ if(!m_gameStates.empty() && m_gameStates.back()->can_update){ m_gameStates.back()->update(); } } void GameStateMachine::render(){ if(!m_gameStates.empty()){ m_gameStates.back()->render(); } }
884
368
#include "trie.hpp" #include <cassert> #include <iostream> #include <string> #include <vector> #include <sstream> int main() { std::string str[113] = {"Bold","Daring","Clever","Intelligent","Careful","Cautious","Boistrous","Serious","Lighthearted","Funny","Sly","Tricky","Lucky","Selfish","Caring","Benevolent","Peaceful","Pacifist","Brave","Cowardly","Fearsome","Intimidating","Scared","Angry","Vengeful","Sad","Avenging","Bombastic","Manipulative","Controlling","Demanding","Wasteful","Leader","Greedy","Violent","Psychotic","Weak","Masochistic","Fake","Thick Skinned","Questing","Trusting","Prophetic","Disgusting","Ignorant","Arrogant","Adept","Skilled","Masterful","Witty","Focused","Determined","Vigilant","Faithful","Predictable","Unpredictable","Magic","Skilled","Dasterdly","Devious","Duranged","Pious","Dangerous","Dashing","Dynamic","Dextrious","Indecent","Courageous","Empowered","Charming","Adventerous","Dumb","Creative","Intuative","Imaginative","Crazed","Paranoid","Insane","Optimistic","Willing","Commited","Innovative","Annoying","Untolerable","Apathetic","Apologetic","Pathetic","Polite","Emotional","Powerful","Doubtful","Friendly","Graceful","Generous","Saintly","Loving","Lovable","Likeable","Kind","Knowledgable","Nice","Positive","Persistent","Querying","Quick","Respectable","Righteous","Resilent","Speculative","Stealthy","Cunning","Wild","Wombo"}; trie<std::string> triehard; for(int i=0;i<113;i++) { triehard.insert(str[i]); } std::string in; std::cin>>in; auto candidates = triehard.complete(in); for(int i=0;i<candidates.size();i++){ std::cout<<*candidates[i]<<' '<<std::endl; } }
1,674
620
#include "../pch.h" #include "Shader.h" #include "GL/glew.h" #include "debug.h" ShaderProgramSource Shader::ParseShader(const std::string &filePath) { std::ifstream stream(filePath); enum class ShaderType { NONE = -1, VERTEX = 0, FRAGMENT = 1 }; std::stringstream ss[2]; std::string line; ShaderType type = ShaderType::NONE; while (getline(stream, line)) { if (line.find("#shader") != std::string::npos) { if (line.find("vertex") != std::string::npos) { type = ShaderType::VERTEX; } else if (line.find("fragment") != std::string::npos) { type = ShaderType::FRAGMENT; } } else { ss[(int)type] << line << '\n'; } } stream.close(); return {ss[0].str(), ss[1].str()}; } unsigned int Shader::CompileShader(unsigned int type, const std::string &source) { GLCall(unsigned int shader = glCreateShader(type)); const char* src = source.c_str(); GLCall(glShaderSource(shader, 1, &src, 0)); GLCall(glCompileShader(shader)); return shader; } Shader::Shader(const std::string &filePath) : m_Path(filePath) { ShaderProgramSource source = ParseShader(filePath); GLCall(m_RendererID = glCreateProgram()); unsigned int vs = CompileShader(GL_VERTEX_SHADER, source.VertexSource); unsigned int fs = CompileShader(GL_FRAGMENT_SHADER, source.FragmentSource); GLCall(glAttachShader(m_RendererID, vs)); GLCall(glAttachShader(m_RendererID, fs)); GLCall(glLinkProgram(m_RendererID)); GLCall(glValidateProgram(m_RendererID)); GLCall(glDeleteShader(vs)); GLCall(glDeleteShader(fs)); } Shader::~Shader() { GLCall(glDeleteProgram(m_RendererID)); } void Shader::bind() const { GLCall(glUseProgram(m_RendererID)); } void Shader::unbind() const { GLCall(glUseProgram(0)); } void Shader::setUniform4f(const std::string &name, float v0, float v1, float v2, float v3) { int location = getUniformLocation(name); if (location != -1) GLCall(glUniform4f(location, v0, v1, v2, v3)); } int Shader::getUniformLocation(const std::string &name) { if (cache.find(name) != cache.end()) return cache[name]; GLCall(cache[name] = glGetUniformLocation(m_RendererID, name.c_str())); return cache[name]; } void Shader::setUnifromMat4f(const std::string &name, const glm::mat4 &matrix) { int location = getUniformLocation(name); if (location != -1) GLCall(glUniformMatrix4fv(location, 1, GL_FALSE, &matrix[0][0])); } void Shader::setUniform1i(const std::string &name, int v0) { int location = getUniformLocation(name); if (location != -1) GLCall(glUniform1i(location, v0)); }
2,754
992
/* ----------------------------------------------------------------------------- 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-2022, 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. ------------------------------------------------------------------------------------------- */ /** \file SampleAdaptiveOffset.cpp \brief sample adaptive offset class */ #include "SampleAdaptiveOffset.h" #include "UnitTools.h" #include "UnitPartitioner.h" #include "CodingStructure.h" #include "dtrace_codingstruct.h" #include "dtrace_buffer.h" #include <string.h> #include <stdlib.h> #include <math.h> //! \ingroup CommonLib //! \{ namespace vvenc { void offsetBlock_core(const int channelBitDepth, const ClpRng& clpRng, int typeIdx, int* offset, int startIdx, const Pel* srcBlk, Pel* resBlk, ptrdiff_t srcStride, ptrdiff_t resStride, int width, int height, uint8_t availMask, std::vector<int8_t> &signLineBuf1, std::vector<int8_t> &signLineBuf2) { int x, y, startX, startY, endX, endY, edgeType; int firstLineStartX, firstLineEndX, lastLineStartX, lastLineEndX; int8_t signLeft, signRight, signDown; const Pel* srcLine = srcBlk; Pel* resLine = resBlk; switch (typeIdx) { case SAO_TYPE_EO_0: { offset += 2; startX = availMask&LeftAvail ? 0 : 1; endX = availMask&RightAvail ? width : (width - 1); for (y = 0; y < height; y++) { signLeft = (int8_t)sgn(srcLine[startX] - srcLine[startX - 1]); for (x = startX; x < endX; x++) { signRight = (int8_t)sgn(srcLine[x] - srcLine[x + 1]); edgeType = signRight + signLeft; signLeft = -signRight; resLine[x] = ClipPel<int>(srcLine[x] + offset[edgeType], clpRng); } srcLine += srcStride; resLine += resStride; } } break; case SAO_TYPE_EO_90: { offset += 2; int8_t *signUpLine = &signLineBuf1[0]; startY = availMask&AboveAvail ? 0 : 1; endY = availMask&BelowAvail ? height : height - 1; if (!(availMask&AboveAvail)) { srcLine += srcStride; resLine += resStride; } const Pel* srcLineAbove = srcLine - srcStride; for (x = 0; x < width; x++) { signUpLine[x] = (int8_t)sgn(srcLine[x] - srcLineAbove[x]); } const Pel* srcLineBelow; for (y = startY; y < endY; y++) { srcLineBelow = srcLine + srcStride; for (x = 0; x < width; x++) { signDown = (int8_t)sgn(srcLine[x] - srcLineBelow[x]); edgeType = signDown + signUpLine[x]; signUpLine[x] = -signDown; resLine[x] = ClipPel<int>(srcLine[x] + offset[edgeType], clpRng); } srcLine += srcStride; resLine += resStride; } } break; case SAO_TYPE_EO_135: { offset += 2; int8_t *signUpLine, *signDownLine, *signTmpLine; signUpLine = &signLineBuf1[0]; signDownLine = &signLineBuf2[0]; startX = availMask&LeftAvail ? 0 : 1; endX = availMask&RightAvail ? width : (width - 1); //prepare 2nd line's upper sign const Pel* srcLineBelow = srcLine + srcStride; for (x = startX; x < endX + 1; x++) { signUpLine[x] = (int8_t)sgn(srcLineBelow[x] - srcLine[x - 1]); } //1st line const Pel* srcLineAbove = srcLine - srcStride; firstLineStartX = availMask&AboveLeftAvail ? 0 : 1; firstLineEndX = availMask&AboveAvail ? endX : 1; for (x = firstLineStartX; x < firstLineEndX; x++) { edgeType = sgn(srcLine[x] - srcLineAbove[x - 1]) - signUpLine[x + 1]; resLine[x] = ClipPel<int>(srcLine[x] + offset[edgeType], clpRng); } srcLine += srcStride; resLine += resStride; //middle lines for (y = 1; y < height - 1; y++) { srcLineBelow = srcLine + srcStride; for (x = startX; x < endX; x++) { signDown = (int8_t)sgn(srcLine[x] - srcLineBelow[x + 1]); edgeType = signDown + signUpLine[x]; resLine[x] = ClipPel<int>(srcLine[x] + offset[edgeType], clpRng); signDownLine[x + 1] = -signDown; } signDownLine[startX] = (int8_t)sgn(srcLineBelow[startX] - srcLine[startX - 1]); signTmpLine = signUpLine; signUpLine = signDownLine; signDownLine = signTmpLine; srcLine += srcStride; resLine += resStride; } //last line srcLineBelow = srcLine + srcStride; lastLineStartX = availMask&BelowAvail ? startX : (width - 1); lastLineEndX = availMask&BelowRightAvail ? width : (width - 1); for (x = lastLineStartX; x < lastLineEndX; x++) { edgeType = sgn(srcLine[x] - srcLineBelow[x + 1]) + signUpLine[x]; resLine[x] = ClipPel<int>(srcLine[x] + offset[edgeType], clpRng); } } break; case SAO_TYPE_EO_45: { offset += 2; int8_t *signUpLine = &signLineBuf1[1]; startX = availMask&LeftAvail ? 0 : 1; endX = availMask&RightAvail ? width : (width - 1); //prepare 2nd line upper sign const Pel* srcLineBelow = srcLine + srcStride; for (x = startX - 1; x < endX; x++) { signUpLine[x] = (int8_t)sgn(srcLineBelow[x] - srcLine[x + 1]); } //first line const Pel* srcLineAbove = srcLine - srcStride; firstLineStartX = availMask&AboveAvail ? startX : (width - 1); firstLineEndX = availMask&AboveRightAvail ? width : (width - 1); for (x = firstLineStartX; x < firstLineEndX; x++) { edgeType = sgn(srcLine[x] - srcLineAbove[x + 1]) - signUpLine[x - 1]; resLine[x] = ClipPel<int>(srcLine[x] + offset[edgeType], clpRng); } srcLine += srcStride; resLine += resStride; //middle lines for (y = 1; y < height - 1; y++) { srcLineBelow = srcLine + srcStride; for (x = startX; x < endX; x++) { signDown = (int8_t)sgn(srcLine[x] - srcLineBelow[x - 1]); edgeType = signDown + signUpLine[x]; resLine[x] = ClipPel<int>(srcLine[x] + offset[edgeType], clpRng); signUpLine[x - 1] = -signDown; } signUpLine[endX - 1] = (int8_t)sgn(srcLineBelow[endX - 1] - srcLine[endX]); srcLine += srcStride; resLine += resStride; } //last line srcLineBelow = srcLine + srcStride; lastLineStartX = availMask&BelowLeftAvail ? 0 : 1; lastLineEndX = availMask&BelowAvail ? endX : 1; for (x = lastLineStartX; x < lastLineEndX; x++) { edgeType = sgn(srcLine[x] - srcLineBelow[x - 1]) + signUpLine[x]; resLine[x] = ClipPel<int>(srcLine[x] + offset[edgeType], clpRng); } } break; case SAO_TYPE_BO: { const int shiftBits = channelBitDepth - NUM_SAO_BO_CLASSES_LOG2; for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { resLine[x] = ClipPel<int>(srcLine[x] + offset[srcLine[x] >> shiftBits], clpRng); } srcLine += srcStride; resLine += resStride; } } break; default: { THROW("Not a supported SAO types\n"); } } } void SAOOffset::reset() { modeIdc = SAO_MODE_OFF; typeIdc = -1; typeAuxInfo = -1; ::memset(offset, 0, sizeof(int)* MAX_NUM_SAO_CLASSES); } void SAOBlkParam::reset() { for(int compIdx = 0; compIdx < MAX_NUM_COMP; compIdx++) { SAOOffsets[compIdx].reset(); } } SampleAdaptiveOffset::SampleAdaptiveOffset() { } SampleAdaptiveOffset::~SampleAdaptiveOffset() { m_signLineBuf1.clear(); m_signLineBuf2.clear(); } void SampleAdaptiveOffset::init( ChromaFormat format, uint32_t maxCUWidth, uint32_t maxCUHeight, uint32_t lumaBitShift, uint32_t chromaBitShift ) { offsetBlock = offsetBlock_core; #if ENABLE_SIMD_OPT_SAO && defined( TARGET_SIMD_X86 ) initSampleAdaptiveOffsetX86(); #endif //bit-depth related for(int compIdx = 0; compIdx < MAX_NUM_COMP; compIdx++) { m_offsetStepLog2 [compIdx] = isLuma(ComponentID(compIdx))? lumaBitShift : chromaBitShift; } m_numberOfComponents = getNumberValidComponents(format); size_t lineBufferSize = std::max( maxCUWidth, maxCUHeight ) + 1; if( m_signLineBuf1.size() < lineBufferSize ) { m_signLineBuf1.resize( lineBufferSize ); m_signLineBuf2.resize( lineBufferSize ); } } void SampleAdaptiveOffset::invertQuantOffsets(ComponentID compIdx, int typeIdc, int typeAuxInfo, int* dstOffsets, int* srcOffsets) { int codedOffset[MAX_NUM_SAO_CLASSES]; ::memcpy(codedOffset, srcOffsets, sizeof(int)*MAX_NUM_SAO_CLASSES); ::memset(dstOffsets, 0, sizeof(int)*MAX_NUM_SAO_CLASSES); if(typeIdc == SAO_TYPE_START_BO) { for(int i=0; i< 4; i++) { dstOffsets[(typeAuxInfo+ i)%NUM_SAO_BO_CLASSES] = codedOffset[(typeAuxInfo+ i)%NUM_SAO_BO_CLASSES]*(1<<m_offsetStepLog2[compIdx]); } } else //EO { for(int i=0; i< NUM_SAO_EO_CLASSES; i++) { dstOffsets[i] = codedOffset[i] *(1<<m_offsetStepLog2[compIdx]); } CHECK(dstOffsets[SAO_CLASS_EO_PLAIN] != 0, "EO offset is not '0'"); //keep EO plain offset as zero } } int SampleAdaptiveOffset::getMergeList(CodingStructure& cs, int ctuRsAddr, SAOBlkParam* blkParams, SAOBlkParam* mergeList[NUM_SAO_MERGE_TYPES]) { const PreCalcValues& pcv = *cs.pcv; int ctuX = ctuRsAddr % pcv.widthInCtus; int ctuY = ctuRsAddr / pcv.widthInCtus; const CodingUnit& cu = *cs.getCU(Position(ctuX*pcv.maxCUSize, ctuY*pcv.maxCUSize), CH_L, TREE_D); int mergedCTUPos; int numValidMergeCandidates = 0; for(int mergeType=0; mergeType< NUM_SAO_MERGE_TYPES; mergeType++) { SAOBlkParam* mergeCandidate = NULL; switch(mergeType) { case SAO_MERGE_ABOVE: { if(ctuY > 0) { mergedCTUPos = ctuRsAddr- pcv.widthInCtus; if(cs.getCURestricted(Position(ctuX*pcv.maxCUSize, (ctuY-1)*pcv.maxCUSize), cu, cu.chType)) { mergeCandidate = &(blkParams[mergedCTUPos]); } } } break; case SAO_MERGE_LEFT: { if(ctuX > 0) { mergedCTUPos = ctuRsAddr- 1; if(cs.getCURestricted(Position((ctuX-1)*pcv.maxCUSize, ctuY*pcv.maxCUSize), cu, cu.chType)) { mergeCandidate = &(blkParams[mergedCTUPos]); } } } break; default: { THROW("not a supported merge type"); } } mergeList[mergeType]=mergeCandidate; if (mergeCandidate != NULL) { numValidMergeCandidates++; } } return numValidMergeCandidates; } void SampleAdaptiveOffset::reconstructBlkSAOParam(SAOBlkParam& recParam, SAOBlkParam* mergeList[NUM_SAO_MERGE_TYPES]) { const int numberOfComponents = m_numberOfComponents; for(int compIdx = 0; compIdx < numberOfComponents; compIdx++) { const ComponentID component = ComponentID(compIdx); SAOOffset& offsetParam = recParam[component]; if(offsetParam.modeIdc == SAO_MODE_OFF) { continue; } switch(offsetParam.modeIdc) { case SAO_MODE_NEW: { invertQuantOffsets(component, offsetParam.typeIdc, offsetParam.typeAuxInfo, offsetParam.offset, offsetParam.offset); } break; case SAO_MODE_MERGE: { SAOBlkParam* mergeTarget = mergeList[offsetParam.typeIdc]; CHECK(mergeTarget == NULL, "Merge target does not exist"); offsetParam = (*mergeTarget)[component]; } break; default: { THROW("Not a supported mode"); } } } } void SampleAdaptiveOffset::xReconstructBlkSAOParams(CodingStructure& cs, SAOBlkParam* saoBlkParams) { for(uint32_t compIdx = 0; compIdx < MAX_NUM_COMP; compIdx++) { m_picSAOEnabled[compIdx] = false; } const uint32_t numberOfComponents = getNumberValidComponents(cs.pcv->chrFormat); for(int ctuRsAddr=0; ctuRsAddr< cs.pcv->sizeInCtus; ctuRsAddr++) { SAOBlkParam* mergeList[NUM_SAO_MERGE_TYPES] = { NULL }; getMergeList(cs, ctuRsAddr, saoBlkParams, mergeList); reconstructBlkSAOParam(saoBlkParams[ctuRsAddr], mergeList); for(uint32_t compIdx = 0; compIdx < numberOfComponents; compIdx++) { if(saoBlkParams[ctuRsAddr][compIdx].modeIdc != SAO_MODE_OFF) { m_picSAOEnabled[compIdx] = true; } } } } void SampleAdaptiveOffset::offsetCTU( const UnitArea& area, const CPelUnitBuf& src, PelUnitBuf& res, SAOBlkParam& saoblkParam, CodingStructure& cs) { const uint32_t numberOfComponents = getNumberValidComponents( area.chromaFormat ); bool bAllOff=true; for( uint32_t compIdx = 0; compIdx < numberOfComponents; compIdx++) { if (saoblkParam[compIdx].modeIdc != SAO_MODE_OFF) { bAllOff=false; } } if (bAllOff) { return; } uint8_t availMask; //block boundary availability deriveLoopFilterBoundaryAvailibility(cs, area.Y(), availMask); const size_t lineBufferSize = area.Y().width + 1; if (m_signLineBuf1.size() < lineBufferSize) { m_signLineBuf1.resize(lineBufferSize); m_signLineBuf2.resize(lineBufferSize); } for(int compIdx = 0; compIdx < numberOfComponents; compIdx++) { const ComponentID compID = ComponentID(compIdx); const CompArea& compArea = area.block(compID); SAOOffset& ctbOffset = saoblkParam[compIdx]; if(ctbOffset.modeIdc != SAO_MODE_OFF) { int srcStride = src.get(compID).stride; const Pel* srcBlk = src.get(compID).bufAt(compArea); int resStride = res.get(compID).stride; Pel* resBlk = res.get(compID).bufAt(compArea); offsetBlock( cs.sps->bitDepths[toChannelType(compID)], cs.slice->clpRngs[compID], ctbOffset.typeIdc, ctbOffset.offset, ctbOffset.typeAuxInfo , srcBlk, resBlk, srcStride, resStride, compArea.width, compArea.height, availMask , m_signLineBuf1, m_signLineBuf2 ); } } //compIdx } void SampleAdaptiveOffset::SAOProcess( CodingStructure& cs, SAOBlkParam* saoBlkParams ) { CHECK(!saoBlkParams, "No parameters present"); xReconstructBlkSAOParams(cs, saoBlkParams); const uint32_t numberOfComponents = getNumberValidComponents(cs.area.chromaFormat); bool bAllDisabled = true; for (uint32_t compIdx = 0; compIdx < numberOfComponents; compIdx++) { if (m_picSAOEnabled[compIdx]) { bAllDisabled = false; } } if (bAllDisabled) { return; } const PreCalcValues& pcv = *cs.pcv; Picture& pic = *cs.picture; PelUnitBuf recBuf = pic.getRecoBuf(); PelUnitBuf saoBuf = pic.getSaoBuf(); saoBuf.copyFrom( recBuf ); int ctuRsAddr = 0; for( uint32_t yPos = 0; yPos < pcv.lumaHeight; yPos += pcv.maxCUSize ) { const uint32_t height = (yPos + pcv.maxCUSize > pcv.lumaHeight) ? (pcv.lumaHeight - yPos) : pcv.maxCUSize; for( uint32_t xPos = 0; xPos < pcv.lumaWidth; xPos += pcv.maxCUSize ) { const uint32_t width = (xPos + pcv.maxCUSize > pcv.lumaWidth) ? (pcv.lumaWidth - xPos) : pcv.maxCUSize; const UnitArea area( cs.area.chromaFormat, Area(xPos , yPos, width, height) ); offsetCTU( area, saoBuf, recBuf, cs.picture->getSAO()[ctuRsAddr], cs); ctuRsAddr++; } } DTRACE_PIC_COMP(D_REC_CB_LUMA_SAO, cs, cs.getRecoBuf(), COMP_Y); DTRACE_PIC_COMP(D_REC_CB_CHROMA_SAO, cs, cs.getRecoBuf(), COMP_Cb); DTRACE_PIC_COMP(D_REC_CB_CHROMA_SAO, cs, cs.getRecoBuf(), COMP_Cr); } void SampleAdaptiveOffset::deriveLoopFilterBoundaryAvailibility(CodingStructure& cs, const Position& pos, uint8_t& availMask ) const { const int cuSize = cs.pcv->maxCUSize; const CodingUnit* cuCurr = cs.getCU(pos, CH_L, TREE_D); const CodingUnit* cuLeft = cs.getCU(pos.offset(-cuSize, 0), CH_L, TREE_D); const CodingUnit* cuRight = cs.getCU(pos.offset(cuSize, 0), CH_L, TREE_D); const CodingUnit* cuAbove = cs.getCU(pos.offset(0, -cuSize), CH_L, TREE_D); const CodingUnit* cuBelow = cs.getCU(pos.offset(0, cuSize), CH_L, TREE_D); const CodingUnit* cuAboveLeft = cs.getCU(pos.offset(-cuSize, -cuSize), CH_L, TREE_D); const CodingUnit* cuAboveRight = cs.getCU(pos.offset(cuSize, -cuSize), CH_L, TREE_D); const CodingUnit* cuBelowLeft = cs.getCU(pos.offset(-cuSize, cuSize), CH_L, TREE_D); const CodingUnit* cuBelowRight = cs.getCU(pos.offset(cuSize, cuSize), CH_L, TREE_D); availMask = 0; // check cross slice flags if( cs.pps->loopFilterAcrossSlicesEnabled ) { availMask |= (cuLeft != NULL) ? LeftAvail : 0; availMask |= (cuAbove != NULL) ? AboveAvail : 0; availMask |= (cuRight != NULL) ? RightAvail : 0; availMask |= (cuBelow != NULL) ? BelowAvail : 0; availMask |= (cuAboveLeft != NULL) ? AboveLeftAvail : 0; availMask |= (cuBelowRight != NULL) ? BelowRightAvail : 0; availMask |= (cuAboveRight != NULL) ? AboveRightAvail : 0; availMask |= (cuBelowLeft != NULL) ? BelowLeftAvail : 0; } else { availMask |= ((cuLeft != NULL) && CU::isSameSlice(*cuCurr, *cuLeft) ) ? LeftAvail : 0; availMask |= ((cuAbove != NULL) && CU::isSameSlice(*cuCurr, *cuAbove) ) ? AboveAvail : 0; availMask |= ((cuRight != NULL) && CU::isSameSlice(*cuCurr, *cuRight)) ? RightAvail : 0; availMask |= ((cuBelow != NULL) && CU::isSameSlice(*cuCurr, *cuBelow) ) ? BelowAvail : 0; availMask |= ((cuAboveLeft != NULL) && CU::isSameSlice(*cuCurr, *cuAboveLeft)) ? AboveLeftAvail : 0; availMask |= ((cuBelowRight != NULL) && CU::isSameSlice(*cuCurr, *cuBelowRight) ) ? BelowRightAvail : 0; availMask |= ((cuAboveRight != NULL) && CU::isSameSlice(*cuCurr, *cuAboveRight) ) ? AboveRightAvail : 0; availMask |= ( (cuBelowLeft != NULL) && CU::isSameSlice(*cuCurr, *cuBelowLeft) ) ? BelowLeftAvail : 0; } // check cross tile flags if (!cs.pps->loopFilterAcrossTilesEnabled) { uint8_t availMaskTile = 0; availMaskTile |= (availMask&LeftAvail && CU::isSameTile(*cuCurr, *cuLeft)) ? LeftAvail : 0; availMaskTile |= (availMask&AboveAvail && CU::isSameTile(*cuCurr, *cuAbove)) ? AboveAvail : 0; availMaskTile |= (availMask&RightAvail && CU::isSameTile(*cuCurr, *cuRight)) ? RightAvail : 0; availMaskTile |= (availMask&BelowAvail && CU::isSameTile(*cuCurr, *cuBelow)) ? BelowAvail : 0; availMaskTile |= (availMask&AboveLeftAvail && CU::isSameTile(*cuCurr, *cuAboveLeft)) ? AboveLeftAvail : 0; availMaskTile |= (availMask&AboveRightAvail &&CU::isSameTile(*cuCurr, *cuAboveRight)) ? AboveRightAvail : 0; availMaskTile |= (availMask&BelowLeftAvail && CU::isSameTile(*cuCurr, *cuBelowLeft)) ? BelowLeftAvail : 0; availMaskTile |= (availMask&BelowRightAvail && CU::isSameTile(*cuCurr, *cuBelowRight)) ? BelowRightAvail : 0; availMask = availMaskTile; } if (!cs.pps->getSubPicFromCU(*cuCurr).loopFilterAcrossSubPicEnabled) { THROW("no support"); } } } // namespace vvenc //! \}
20,622
8,198
/** * Copyright 2020 The Magma Authors. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. * * 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 "lte/gateway/c/session_manager/StatsPoller.hpp" #include <stdint.h> #include <chrono> #include <memory> #include <thread> #include "lte/gateway/c/session_manager/LocalEnforcer.hpp" #define COOKIE 0 #define COOKIE_MASK 0 namespace magma { void StatsPoller::start_loop( std::shared_ptr<magma::LocalEnforcer> local_enforcer, uint32_t loop_interval_seconds) { while (true) { local_enforcer->poll_stats_enforcer(COOKIE, COOKIE_MASK); std::this_thread::sleep_for(std::chrono::seconds(loop_interval_seconds)); } } } // namespace magma
1,068
360
// -*- mode: c++; c-basic-offset: 4 -*- /* * FlowStrip.{cc,hh} -- element FlowStrips bytes from front of packet * Robert Morris, Eddie Kohler * * Copyright (c) 1999-2000 Massachusetts Institute of Technology * * 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, subject to the conditions * listed in the Click LICENSE file. These conditions include: you must * preserve this copyright notice, and you cannot mention the copyright * holders in advertising related to the Software without their permission. * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This * notice is a summary of the Click LICENSE file; the license in that file is * legally binding. */ #include <click/config.h> #include <click/args.hh> #include <click/error.hh> #include <click/glue.hh> #include "flowstrip.hh" CLICK_DECLS FlowStrip::FlowStrip() { in_batch_mode = BATCH_MODE_NEEDED; } int FlowStrip::configure(Vector<String> &conf, ErrorHandler *errh) { return Args(conf, this, errh).read_mp("LENGTH", _nbytes).complete(); } PacketBatch * FlowStrip::simple_action_batch(PacketBatch *head) { Packet* current = head->first(); while (current != NULL) { current->pull(_nbytes); current = current->next(); } return head; } void FlowStrip::apply_offset(FlowNode* node, bool invert) { node->level()->add_offset(invert?-_nbytes:_nbytes); FlowNode::NodeIterator it = node->iterator(); FlowNodePtr* child; while ((child = it.next()) != 0) { if (child->ptr && child->is_node()) apply_offset(child->node,invert); } if (node->default_ptr()->ptr && node->default_ptr()->is_node()) apply_offset(node->default_ptr()->node,invert); } FlowNode* FlowStrip::get_table(int,Vector<FlowElement*> context) { context.push_back(this); FlowNode* root = FlowElementVisitor::get_downward_table(this, 0, context); if (root) apply_offset(root, false); return root; } FlowNode* FlowStrip::resolveContext(FlowType t, Vector<FlowElement*> contextStack) { if (contextStack.size() > 1) { FlowNode* n = contextStack[contextStack.size() - 2]->resolveContext(t, contextStack.sub(0,contextStack.size()-1)); if (n) { apply_offset(n, true); return n; } } return FlowElement::resolveContext(t,contextStack); } CLICK_ENDDECLS ELEMENT_REQUIRES(flow) EXPORT_ELEMENT(FlowStrip) ELEMENT_MT_SAFE(FlowStrip)
2,516
860
#include <iostream> #include <conio.h> using namespace std; int main() { struct node{ int info; node *left,*right; }*ptr,*start,*last,*save; int c=1,i=0,data,item; start=last=NULL; while(c<4 && c>0){ cout<<"1.Insert\n2.Deletion\n3.Link List\n"; cin>>c; switch(c){ case 1: cout<<"Enter Data\n"; cin>>data; ptr=new node; ptr->info=data; ptr->left=last; ptr->right=NULL; if(start==NULL){ start=last=ptr; } else{ last->right=ptr; last=ptr; } break; case 2: if(start==NULL){ cout<<"Underflow\n"; } else{ cout<<"Enter Item to be Deleted\n"; cin>>item; ptr=start; while(ptr!=NULL){ if(ptr->info==item){ i++; if(ptr==start){ start->left=NULL; start=start->right; } else{ ptr->left->right=ptr->right; ptr->right->left=ptr->left; } delete ptr; cout<<"Item Deleted\n"; } ptr=ptr->right; } if(i==0){ cout<<"Item Does not exist\n"; } i=0; } break; case 3: ptr=start; while(ptr!=NULL){ cout<<ptr->info<<"->"; ptr=ptr->right; } cout<<"\n"; break; default: cout<<"Wrong Choice\nExiting...\n"; } } getch(); return 0; }
1,194
648
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include <stdint.h> #include "beatsaber-hook/shared/utils/byref.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Threading::Tasks namespace System::Threading::Tasks { // Forward declaring type: Task class Task; } // Forward declaring namespace: System::Threading namespace System::Threading { // Forward declaring type: CancellationToken struct CancellationToken; } // Completed forward declares // Type namespace: BGNet.Core namespace BGNet::Core { // Forward declaring type: ITimeProvider class ITimeProvider; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::BGNet::Core::ITimeProvider); DEFINE_IL2CPP_ARG_TYPE(::BGNet::Core::ITimeProvider*, "BGNet.Core", "ITimeProvider"); // Type namespace: BGNet.Core namespace BGNet::Core { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: BGNet.Core.ITimeProvider // [TokenAttribute] Offset: FFFFFFFF class ITimeProvider { public: // public System.Int64 GetTimeMs() // Offset: 0xFFFFFFFFFFFFFFFF int64_t GetTimeMs(); // public System.Threading.Tasks.Task DelayMs(System.Int32 millis, System.Threading.CancellationToken cancellationToken) // Offset: 0xFFFFFFFFFFFFFFFF ::System::Threading::Tasks::Task* DelayMs(int millis, ::System::Threading::CancellationToken cancellationToken); }; // BGNet.Core.ITimeProvider #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: BGNet::Core::ITimeProvider::GetTimeMs // Il2CppName: GetTimeMs template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int64_t (BGNet::Core::ITimeProvider::*)()>(&BGNet::Core::ITimeProvider::GetTimeMs)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(BGNet::Core::ITimeProvider*), "GetTimeMs", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: BGNet::Core::ITimeProvider::DelayMs // Il2CppName: DelayMs template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Threading::Tasks::Task* (BGNet::Core::ITimeProvider::*)(int, ::System::Threading::CancellationToken)>(&BGNet::Core::ITimeProvider::DelayMs)> { static const MethodInfo* get() { static auto* millis = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* cancellationToken = &::il2cpp_utils::GetClassFromName("System.Threading", "CancellationToken")->byval_arg; return ::il2cpp_utils::FindMethod(classof(BGNet::Core::ITimeProvider*), "DelayMs", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{millis, cancellationToken}); } };
2,868
974
#include <cmath> #include "amr-wind/incflo.H" #include "amr-wind/core/Physics.H" #include "amr-wind/core/field_ops.H" #include "amr-wind/equation_systems/PDEBase.H" #include "amr-wind/turbulence/TurbulenceModel.H" #include "amr-wind/utilities/console_io.H" #include "amr-wind/utilities/PostProcessing.H" #include "amr-wind/core/field_ops.H" using namespace amrex; void incflo::pre_advance_stage1() { BL_PROFILE("amr-wind::incflo::pre_advance_stage1"); // Compute time step size bool explicit_diffusion = (m_diff_type == DiffusionType::Explicit); ComputeDt(explicit_diffusion); } void incflo::pre_advance_stage2() { BL_PROFILE("amr-wind::incflo::pre_advance_stage2"); for (auto& pp : m_sim.physics()) pp->pre_advance_work(); } /** Advance simulation state by one timestep * * Performs the following actions at a given timestep * - Compute \f$\Delta t\f$ * - Advance all computational fields to new timestate in preparation for time * integration * - Call pre-advance work for all registered physics modules * - For Godunov scheme, advance to new time state * - For MOL scheme, call predictor corrector steps * - Perform any post-advance work * * Much of the heavy-lifting is done by incflo::ApplyPredictor and * incflo::ApplyCorrector. Please refer to the documentation of those methods * for detailed information on the various equations being solved. * * \callgraph */ void incflo::advance() { BL_PROFILE("amr-wind::incflo::Advance"); m_sim.pde_manager().advance_states(); ApplyPredictor(); if (!m_use_godunov) ApplyCorrector(); } // Apply predictor step // // For Godunov, this completes the timestep. For MOL, this is the first part of // the predictor/corrector within a timestep. // // <ol> // <li> Use u = vel_old to compute // // \code{.cpp} // conv_u = - u grad u // conv_r = - div( u rho ) // conv_t = - div( u trac ) // eta_old = visosity at m_time.current_time() // if (m_diff_type == DiffusionType::Explicit) // divtau _old = div( eta ( (grad u) + (grad u)^T ) ) / rho^n // rhs = u + dt * ( conv + divtau_old ) // else // divtau_old = 0.0 // rhs = u + dt * conv // // eta = eta at new_time // \endcode // // <li> Add explicit forcing term i.e. gravity + lagged pressure gradient // // \code{.cpp} // rhs += dt * ( g - grad(p + p0) / rho^nph ) // \endcode // // Note that in order to add the pressure gradient terms divided by rho, // we convert the velocity to momentum before adding and then convert them // back. // // <li> A. If (m_diff_type == DiffusionType::Implicit) // solve implicit diffusion equation for u* // // \code{.cpp} // ( 1 - dt / rho^nph * div ( eta grad ) ) u* = u^n + dt * conv_u // + dt * ( g - grad(p + p0) / // rho^nph ) // \endcode // // B. If (m_diff_type == DiffusionType::Crank-Nicolson) // solve semi-implicit diffusion equation for u* // // \code{.cpp} // ( 1 - (dt/2) / rho^nph * div ( eta_old grad ) ) u* = u^n + // dt * conv_u + (dt/2) / rho * div (eta_old grad) u^n // + dt * ( g - grad(p + p0) / rho^nph ) // \endcode // // <li> Apply projection (see incflo::ApplyProjection) // // Add pressure gradient term back to u*: // // \code{.cpp} // u** = u* + dt * grad p / rho^nph // \endcode // // Solve Poisson equation for phi: // // \code{.cpp} // div( grad(phi) / rho^nph ) = div( u** ) // \endcode // // Update pressure: // // p = phi / dt // // Update velocity, now divergence free // // vel = u** - dt * grad p / rho^nph // </ol> // // It is assumed that the ghost cels of the old data have been filled and // the old and new data are the same in valid region. // /** Apply predictor step * * For Godunov, this completes the timestep. For MOL, this is the first part of * the predictor/corrector within a timestep. * * <ol> * <li> Solve transport equation for momentum and scalars * * \f{align} * \left[1 - \kappa \frac{\Delta t}{\rho^{n+1/2}} \nabla \cdot \left( \mu * \nabla \right)\right] u^{*} &= u^n - \Delta t (u \cdot \nabla) u + (1 - * \kappa) \frac{\Delta t}{\rho^n} \nabla \cdot \left( \mu^{n} \nabla\right) * u^{n} + \frac{\Delta t}{\rho^{n+1/2}} \left( S_u - \nabla(p + p_0)\right) \\ * \f} * * where * \f{align} * \kappa = \begin{cases} * 0 & \text{Explicit} \\ * 0.5 & \text{Crank-Nicholson} \\ * 1 & \text{Implicit} * \end{cases} * \f} * * <li> \ref incflo::ApplyProjection "Apply projection" * </ol> */ void incflo::ApplyPredictor(bool incremental_projection) { BL_PROFILE("amr-wind::incflo::ApplyPredictor"); // We use the new time value for things computed on the "*" state Real new_time = m_time.new_time(); if (m_verbose > 2) PrintMaxValues("before predictor step"); if (m_use_godunov) amr_wind::io::print_mlmg_header("Godunov:"); else amr_wind::io::print_mlmg_header("Predictor:"); auto& icns_fields = icns().fields(); auto& velocity_new = icns_fields.field; auto& velocity_old = velocity_new.state(amr_wind::FieldState::Old); auto& density_new = density(); auto& density_old = density_new.state(amr_wind::FieldState::Old); auto& density_nph = density_new.state(amr_wind::FieldState::NPH); // ************************************************************************************* // Compute viscosity / diffusive coefficients // ************************************************************************************* m_sim.turbulence_model().update_turbulent_viscosity( amr_wind::FieldState::Old); icns().compute_mueff(amr_wind::FieldState::Old); for (auto& eqns : scalar_eqns()) eqns->compute_mueff(amr_wind::FieldState::Old); // ************************************************************************************* // Define the forcing terms to use in the Godunov prediction // ************************************************************************************* if (m_use_godunov) { icns().compute_source_term(amr_wind::FieldState::Old); for (auto& seqn : scalar_eqns()) { seqn->compute_source_term(amr_wind::FieldState::Old); } } // ************************************************************************************* // Compute explicit viscous term // ************************************************************************************* if (need_divtau()) { // Reuse existing buffer to avoid creating new multifabs amr_wind::field_ops::copy( velocity_new, velocity_old, 0, 0, velocity_new.num_comp(), 1); icns().compute_diffusion_term(amr_wind::FieldState::Old); if (m_use_godunov) { auto& velocity_forces = icns_fields.src_term; // only the old states are used in predictor auto& divtau = m_use_godunov ? icns_fields.diff_term : icns_fields.diff_term.state(amr_wind::FieldState::Old); amr_wind::field_ops::add( velocity_forces, divtau, 0, 0, AMREX_SPACEDIM, 0); } } // ************************************************************************************* // Compute explicit diffusive terms // ************************************************************************************* if (need_divtau()) { for (auto& eqn : scalar_eqns()) { auto& field = eqn->fields().field; // Reuse existing buffer to avoid creating new multifabs amr_wind::field_ops::copy( field, field.state(amr_wind::FieldState::Old), 0, 0, field.num_comp(), 1); eqn->compute_diffusion_term(amr_wind::FieldState::Old); if (m_use_godunov) amr_wind::field_ops::add( eqn->fields().src_term, eqn->fields().diff_term, 0, 0, field.num_comp(), 0); } } if (m_use_godunov) { const int nghost_force = 1; IntVect ng(nghost_force); icns().fields().src_term.fillpatch(m_time.current_time(), ng); for (auto& eqn : scalar_eqns()) { eqn->fields().src_term.fillpatch(m_time.current_time(), ng); } } // ************************************************************************************* // if ( m_use_godunov) Compute the explicit advective terms // R_u^(n+1/2), R_s^(n+1/2) and R_t^(n+1/2) // if (!m_use_godunov) Compute the explicit advective terms // R_u^n , R_s^n and R_t^n // ************************************************************************************* icns().compute_advection_term(amr_wind::FieldState::Old); for (auto& seqn : scalar_eqns()) { seqn->compute_advection_term(amr_wind::FieldState::Old); } // ************************************************************************************* // Update density first // ************************************************************************************* if (m_constant_density) { amr_wind::field_ops::copy(density_nph, density_old, 0, 0, 1, 1); } // Perform scalar update one at a time. This is to allow an updated density // at `n+1/2` to be computed before other scalars use it when computing // their source terms. for (auto& eqn : scalar_eqns()) { // Compute (recompute for Godunov) the scalar forcing terms eqn->compute_source_term(amr_wind::FieldState::NPH); // Update the scalar (if explicit), or the RHS for implicit/CN eqn->compute_predictor_rhs(m_diff_type); auto& field = eqn->fields().field; if (m_diff_type != DiffusionType::Explicit) { amrex::Real dt_diff = (m_diff_type == DiffusionType::Implicit) ? m_time.deltaT() : 0.5 * m_time.deltaT(); // Solve diffusion eqn. and update of the scalar field eqn->solve(dt_diff); // Post-processing actions after a PDE solve } eqn->post_solve_actions(); // Update scalar at n+1/2 amr_wind::field_ops::lincomb( field.state(amr_wind::FieldState::NPH), 0.5, field.state(amr_wind::FieldState::Old), 0, 0.5, field, 0, 0, field.num_comp(), 1); } // ************************************************************************************* // Define (or if use_godunov, re-define) the forcing terms, without the // viscous terms // and using the half-time density // ************************************************************************************* icns().compute_source_term(amr_wind::FieldState::New); // ************************************************************************************* // Update the velocity // ************************************************************************************* icns().compute_predictor_rhs(m_diff_type); // ************************************************************************************* // Solve diffusion equation for u* but using eta_old at old time // ************************************************************************************* if (m_diff_type == DiffusionType::Crank_Nicolson || m_diff_type == DiffusionType::Implicit) { Real dt_diff = (m_diff_type == DiffusionType::Implicit) ? m_time.deltaT() : 0.5 * m_time.deltaT(); icns().solve(dt_diff); } icns().post_solve_actions(); // ************************************************************************************ // // Project velocity field, update pressure // // ************************************************************************************ ApplyProjection( (density_nph).vec_const_ptrs(), new_time, m_time.deltaT(), incremental_projection); } // // Apply corrector: // // Output variables from the predictor are labelled _pred // // 1. Use u = vel_pred to compute // // conv_u = - u grad u // conv_r = - u grad rho // conv_t = - u grad trac // eta = viscosity // divtau = div( eta ( (grad u) + (grad u)^T ) ) / rho // // conv_u = 0.5 (conv_u + conv_u_pred) // conv_r = 0.5 (conv_r + conv_r_pred) // conv_t = 0.5 (conv_t + conv_t_pred) // if (m_diff_type == DiffusionType::Explicit) // divtau = divtau at new_time using (*) state // else // divtau = 0.0 // eta = eta at new_time // // rhs = u + dt * ( conv + divtau ) // // 2. Add explicit forcing term i.e. gravity + lagged pressure gradient // // rhs += dt * ( g - grad(p + p0) / rho ) // // Note that in order to add the pressure gradient terms divided by rho, // we convert the velocity to momentum before adding and then convert them // back. // // 3. A. If (m_diff_type == DiffusionType::Implicit) // solve implicit diffusion equation for u* // // ( 1 - dt / rho * div ( eta grad ) ) u* = u^n + dt * conv_u // + dt * ( g - grad(p + p0) / // rho ) // // B. If (m_diff_type == DiffusionType::Crank-Nicolson) // solve semi-implicit diffusion equation for u* // // ( 1 - (dt/2) / rho * div ( eta grad ) ) u* = u^n + dt * conv_u + (dt/2) / // rho * div (eta_old grad) u^n // + dt * ( g - grad(p + // p0) / rho ) // // 4. Apply projection // // Add pressure gradient term back to u*: // // u** = u* + dt * grad p / rho // // Solve Poisson equation for phi: // // div( grad(phi) / rho ) = div( u** ) // // Update pressure: // // p = phi / dt // // Update velocity, now divergence free // // vel = u** - dt * grad p / rho // /** Corrector step for MOL scheme * * <ol> * <li> Solve transport equation for momentum and scalars * * \f{align} * \left[1 - \kappa \frac{\Delta t}{\rho} \nabla \cdot \left( \mu * \nabla \right)\right] u^{*} &= u^n - \Delta t C_u + (1 - \kappa) * \frac{\Delta t}{\rho} \nabla \cdot \left( \mu \nabla\right) u^{n} + * \frac{\Delta t}{\rho} \left( S_u - \nabla(p + p_0)\right) \\ \f} * * where * \f{align} * \kappa = \begin{cases} * 0 & \text{Explicit} \\ * 0.5 & \text{Crank-Nicholson} \\ * 1 & \text{Implicit} * \end{cases} * \f} * * <li> \ref incflo::ApplyProjection "Apply projection" * </ol> */ void incflo::ApplyCorrector() { BL_PROFILE("amr-wind::incflo::ApplyCorrector"); // We use the new time value for things computed on the "*" state Real new_time = m_time.new_time(); if (m_verbose > 2) PrintMaxValues("before corrector step"); amr_wind::io::print_mlmg_header("Corrector:"); auto& density_new = density(); auto& density_old = density_new.state(amr_wind::FieldState::Old); auto& density_nph = density_new.state(amr_wind::FieldState::NPH); // ************************************************************************************* // Compute the explicit "new" advective terms R_u^(n+1,*), R_r^(n+1,*) and // R_t^(n+1,*) We only reach the corrector if !m_use_godunov which means we // don't use the forces in constructing the advection term // ************************************************************************************* icns().compute_advection_term(amr_wind::FieldState::New); for (auto& seqn : scalar_eqns()) { seqn->compute_advection_term(amr_wind::FieldState::New); } // ************************************************************************************* // Compute viscosity / diffusive coefficients // ************************************************************************************* m_sim.turbulence_model().update_turbulent_viscosity( amr_wind::FieldState::New); icns().compute_mueff(amr_wind::FieldState::New); for (auto& eqns : scalar_eqns()) eqns->compute_mueff(amr_wind::FieldState::New); // Here we create divtau of the (n+1,*) state that was computed in the // predictor; // we use this laps only if DiffusionType::Explicit if (m_diff_type == DiffusionType::Explicit) { icns().compute_diffusion_term(amr_wind::FieldState::New); for (auto& eqns : scalar_eqns()) { eqns->compute_diffusion_term(amr_wind::FieldState::New); } } // ************************************************************************************* // Update density first // ************************************************************************************* if (m_constant_density) { amr_wind::field_ops::copy(density_nph, density_old, 0, 0, 1, 1); } // Perform scalar update one at a time. This is to allow an updated density // at `n+1/2` to be computed before other scalars use it when computing // their source terms. for (auto& eqn : scalar_eqns()) { // Compute (recompute for Godunov) the scalar forcing terms // Note this is (rho * scalar) and not just scalar eqn->compute_source_term(amr_wind::FieldState::New); // Update (note that dtdt already has rho in it) // (rho trac)^new = (rho trac)^old + dt * ( // div(rho trac u) + div (mu grad trac) + rho * f_t eqn->compute_corrector_rhs(m_diff_type); auto& field = eqn->fields().field; if (m_diff_type != DiffusionType::Explicit) { amrex::Real dt_diff = (m_diff_type == DiffusionType::Implicit) ? m_time.deltaT() : 0.5 * m_time.deltaT(); // Solve diffusion eqn. and update of the scalar field eqn->solve(dt_diff); } eqn->post_solve_actions(); // Update scalar at n+1/2 amr_wind::field_ops::lincomb( field.state(amr_wind::FieldState::NPH), 0.5, field.state(amr_wind::FieldState::Old), 0, 0.5, field, 0, 0, field.num_comp(), 1); } // ************************************************************************************* // Define the forcing terms to use in the final update (using half-time // density) // ************************************************************************************* icns().compute_source_term(amr_wind::FieldState::New); // ************************************************************************************* // Update velocity // ************************************************************************************* icns().compute_corrector_rhs(m_diff_type); // ************************************************************************************* // // Solve diffusion equation for u* at t^{n+1} but using eta at predicted new // time // // ************************************************************************************* if (m_diff_type == DiffusionType::Crank_Nicolson || m_diff_type == DiffusionType::Implicit) { Real dt_diff = (m_diff_type == DiffusionType::Implicit) ? m_time.deltaT() : 0.5 * m_time.deltaT(); icns().solve(dt_diff); } icns().post_solve_actions(); // ************************************************************************************* // Project velocity field, update pressure // ************************************************************************************* bool incremental = false; ApplyProjection( (density_nph).vec_const_ptrs(), new_time, m_time.deltaT(), incremental); }
20,048
6,308
//----------------------------------*-C++-*----------------------------------// /*! * \file c4/test/tstglobal_containers.cc * \author Kent Budge * \date Mon Mar 24 09:41:04 2008 * \note Copyright (C) 2008-2019 Triad National Security, LLC. * All rights reserved. */ //---------------------------------------------------------------------------// #include "c4/ParallelUnitTest.hh" #include "c4/global_containers.i.hh" #include "ds++/Release.hh" #include "ds++/Soft_Equivalence.hh" #include <cmath> #include <set> using namespace std; using namespace rtt_dsxx; using namespace rtt_c4; //---------------------------------------------------------------------------// // TESTS //---------------------------------------------------------------------------// #ifdef C4_MPI void tstglobal_containers(UnitTest &ut) { unsigned const pid = rtt_c4::node(); unsigned const number_of_processors = rtt_c4::nodes(); { set<unsigned> local_set; local_set.insert(pid); local_set.insert(number_of_processors + pid); global_merge(local_set); if (local_set.size() == 2 * number_of_processors) PASSMSG("Correct number of global elements"); else FAILMSG("NOT correct number of global elements"); for (unsigned p = 0; p < number_of_processors; ++p) { if (local_set.count(p) != 1 || local_set.count(number_of_processors + p) != 1) { FAILMSG("WRONG element in set"); } } } { map<unsigned, double> local_map; local_map[pid] = pid; local_map[number_of_processors + pid] = 2 * pid; global_merge(local_map); if (local_map.size() == 2 * number_of_processors) PASSMSG("Correct number of global elements"); else FAILMSG("NOT correct number of global elements"); for (unsigned p = 0; p < number_of_processors; ++p) { if (local_map.count(p) != 1 || local_map.count(number_of_processors + p) != 1) { FAILMSG("WRONG element in map"); } if (!rtt_dsxx::soft_equiv(local_map[p], static_cast<double>(p)) || !rtt_dsxx::soft_equiv(local_map[number_of_processors + p], static_cast<double>(2 * p))) { FAILMSG("WRONG element value in map"); } } } { map<unsigned, bool> local_map; local_map[pid] = false; local_map[number_of_processors + pid] = true; global_merge(local_map); if (local_map.size() == 2 * number_of_processors) PASSMSG("Correct number of global elements"); else FAILMSG("NOT correct number of global elements"); for (unsigned p = 0; p < number_of_processors; ++p) { if (local_map.count(p) != 1 || local_map.count(number_of_processors + p) != 1) { FAILMSG("WRONG element in map"); } if (local_map[p] != false || local_map[number_of_processors + p] != true) { FAILMSG("WRONG element value in map"); } } } } #endif // C4_MPI //---------------------------------------------------------------------------// int main(int argc, char *argv[]) { rtt_c4::ParallelUnitTest ut(argc, argv, release); try { #ifdef C4_MPI tstglobal_containers(ut); #else PASSMSG("Test inactive for scalar"); #endif // C4_MPI } catch (exception &err) { cout << "ERROR: While testing tstglobal_containers, " << err.what() << endl; ut.numFails++; } catch (...) { cout << "ERROR: While testing tstglobal_containers, " << "An unknown exception was thrown." << endl; ut.numFails++; } return ut.numFails; } //---------------------------------------------------------------------------// // end of tstglobal_containers.cc //---------------------------------------------------------------------------//
3,741
1,248
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2020 - Raw Material Software Limited JUCE is an open source library subject to commercial or open-source licensing. By using JUCE, you agree to the terms of both the JUCE 6 End-User License Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020). End User License Agreement: www.juce.com/juce-6-licence Privacy Policy: www.juce.com/juce-privacy-policy Or: You may also use this code under the terms of the GPL v3 (see www.gnu.org/licenses). JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ namespace juce { namespace build_tools { String EntitlementOptions::getEntitlementsFileContent() const { String content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n" "<plist version=\"1.0\">\n" "<dict>\n"; const auto entitlements = getEntitlements(); for (auto& key : entitlements.getAllKeys()) content += "\t<key>" + key + "</key>\n\t" + entitlements[key] + "\n"; return content + "</dict>\n</plist>\n"; } StringPairArray EntitlementOptions::getEntitlements() const { StringPairArray entitlements; if (isiOS) { if (isAudioPluginProject && shouldEnableIAA) entitlements.set ("inter-app-audio", "<true/>"); if (isiCloudPermissionsEnabled) { entitlements.set ("com.apple.developer.icloud-container-identifiers", "<array>\n" " <string>iCloud.$(CFBundleIdentifier)</string>\n" " </array>"); entitlements.set ("com.apple.developer.icloud-services", "<array>\n" " <string>CloudDocuments</string>\n" " </array>"); entitlements.set ("com.apple.developer.ubiquity-container-identifiers", "<array>\n" " <string>iCloud.$(CFBundleIdentifier)</string>\n" " </array>"); } } if (isPushNotificationsEnabled) entitlements.set (isiOS ? "aps-environment" : "com.apple.developer.aps-environment", "<string>development</string>"); if (isAppGroupsEnabled) { auto appGroups = StringArray::fromTokens (appGroupIdString, ";", {}); auto groups = String ("<array>"); for (auto group : appGroups) groups += "\n\t\t<string>" + group.trim() + "</string>"; groups += "\n\t</array>"; entitlements.set ("com.apple.security.application-groups", groups); } if (isHardenedRuntimeEnabled) for (auto& option : hardenedRuntimeOptions) entitlements.set (option, "<true/>"); if (isAppSandboxEnabled || (! isiOS && isAudioPluginProject && type == ProjectType::Target::AudioUnitv3PlugIn)) { entitlements.set ("com.apple.security.app-sandbox", "<true/>"); if (isAppSandboxInhertianceEnabled) { // no other sandbox options can be specified if sandbox inheritance is enabled! jassert (appSandboxOptions.isEmpty()); entitlements.set ("com.apple.security.inherit", "<true/>"); } if (isAppSandboxEnabled) for (auto& option : appSandboxOptions) entitlements.set (option, "<true/>"); } if (isNetworkingMulticastEnabled) entitlements.set ("com.apple.developer.networking.multicast", "<true/>"); return entitlements; } } }
4,311
1,242
//======================================================================= // Copyright 1997, 1998, 1999, 2000 University of Notre Dame. // Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek // // This file is part of the Boost Graph Library // // You should have received a copy of the License Agreement for the // Boost Graph Library along with the software; see the file LICENSE. // If not, contact Office of Research, University of Notre Dame, Notre // Dame, IN 46556. // // Permission to modify the code and to distribute modified code is // granted, provided the text of this NOTICE is retained, a notice that // the code was modified is included with the above COPYRIGHT NOTICE and // with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE // file is distributed with the modified code. // // LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. // By way of example, but not limitation, Licensor MAKES NO // REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY // PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS // OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS // OR OTHER RIGHTS. //======================================================================= #include <boost/config.hpp> #include <iostream> // for std::cout #include <utility> // for std::pair #include <algorithm> // for std::for_each #include <boost/utility.hpp> // for boost::tie #include <boost/graph/graph_traits.hpp> // for boost::graph_traits #include <boost/graph/adjacency_list.hpp> #include <boost/graph/graphviz.hpp> using namespace boost; template <class Graph> struct exercise_vertex { exercise_vertex(Graph& g_) : g(g_) { } typedef typename graph_traits<Graph>::vertex_descriptor Vertex; void operator()(const Vertex& v) const { using namespace boost; typename property_map<Graph, vertex_index_t>::type vertex_id = get(vertex_index, g); std::cout << "vertex: " << get(vertex_id, v) << std::endl; // Write out the outgoing edges std::cout << "\tout-edges: "; typename graph_traits<Graph>::out_edge_iterator out_i, out_end; typename graph_traits<Graph>::edge_descriptor e; for (tie(out_i, out_end) = out_edges(v, g); out_i != out_end; ++out_i) { e = *out_i; Vertex src = source(e, g), targ = target(e, g); std::cout << "(" << get(vertex_id, src) << "," << get(vertex_id, targ) << ") "; } std::cout << std::endl; // Write out the incoming edges std::cout << "\tin-edges: "; typename graph_traits<Graph>::in_edge_iterator in_i, in_end; for (tie(in_i, in_end) = in_edges(v, g); in_i != in_end; ++in_i) { e = *in_i; Vertex src = source(e, g), targ = target(e, g); std::cout << "(" << get(vertex_id, src) << "," << get(vertex_id, targ) << ") "; } std::cout << std::endl; // Write out all adjacent vertices std::cout << "\tadjacent vertices: "; typename graph_traits<Graph>::adjacency_iterator ai, ai_end; for (tie(ai,ai_end) = adjacent_vertices(v, g); ai != ai_end; ++ai) std::cout << get(vertex_id, *ai) << " "; std::cout << std::endl; } Graph& g; }; int main(int,char*[]) { // create a typedef for the Graph type typedef adjacency_list<vecS, vecS, bidirectionalS, no_property, property<edge_weight_t, float> > Graph; // Make convenient labels for the vertices enum { A, B, C, D, E, N }; const int num_vertices = N; const char* name = "ABCDE"; // writing out the edges in the graph typedef std::pair<int,int> Edge; Edge edge_array[] = { Edge(A,B), Edge(A,D), Edge(C,A), Edge(D,C), Edge(C,E), Edge(B,D), Edge(D,E), }; const int num_edges = sizeof(edge_array)/sizeof(edge_array[0]); // average transmission delay (in milliseconds) for each connection float transmission_delay[] = { 1.2, 4.5, 2.6, 0.4, 5.2, 1.8, 3.3, 9.1 }; // declare a graph object, adding the edges and edge properties #if defined(BOOST_MSVC) && BOOST_MSVC <= 1300 // VC++ can't handle the iterator constructor Graph g(num_vertices); property_map<Graph, edge_weight_t>::type weightmap = get(edge_weight, g); for (std::size_t j = 0; j < num_edges; ++j) { graph_traits<Graph>::edge_descriptor e; bool inserted; tie(e, inserted) = add_edge(edge_array[j].first, edge_array[j].second, g); weightmap[e] = transmission_delay[j]; } #else Graph g(edge_array, edge_array + num_edges, transmission_delay, num_vertices); #endif boost::property_map<Graph, vertex_index_t>::type vertex_id = get(vertex_index, g); boost::property_map<Graph, edge_weight_t>::type trans_delay = get(edge_weight, g); std::cout << "vertices(g) = "; typedef graph_traits<Graph>::vertex_iterator vertex_iter; std::pair<vertex_iter, vertex_iter> vp; for (vp = vertices(g); vp.first != vp.second; ++vp.first) std::cout << name[get(vertex_id, *vp.first)] << " "; std::cout << std::endl; std::cout << "edges(g) = "; graph_traits<Graph>::edge_iterator ei, ei_end; for (tie(ei,ei_end) = edges(g); ei != ei_end; ++ei) std::cout << "(" << name[get(vertex_id, source(*ei, g))] << "," << name[get(vertex_id, target(*ei, g))] << ") "; std::cout << std::endl; std::for_each(vertices(g).first, vertices(g).second, exercise_vertex<Graph>(g)); std::map<std::string,std::string> graph_attr, vertex_attr, edge_attr; graph_attr["size"] = "3,3"; graph_attr["rankdir"] = "LR"; graph_attr["ratio"] = "fill"; vertex_attr["shape"] = "circle"; boost::write_graphviz(std::cout, g, make_label_writer(name), make_label_writer(trans_delay), make_graph_attributes_writer(graph_attr, vertex_attr, edge_attr)); return 0; }
5,990
2,128
/* Returns: - pointer to the last unprocessed character (a scalar fallback should check the rest); - nullptr if an error was detected. */ const char32_t* avx2_validate_utf32le(const char32_t* input, size_t size) { const char32_t* end = input + size; const __m256i standardmax = _mm256_set1_epi32(0x10ffff); const __m256i offset = _mm256_set1_epi32(0xffff2000); const __m256i standardoffsetmax = _mm256_set1_epi32(0xfffff7ff); __m256i currentmax = _mm256_setzero_si256(); __m256i currentoffsetmax = _mm256_setzero_si256(); while (input + 8 < end) { const __m256i in = _mm256_loadu_si256((__m256i *)input); currentmax = _mm256_max_epu32(in,currentmax); currentoffsetmax = _mm256_max_epu32(_mm256_add_epi32(in, offset), currentoffsetmax); input += 8; } __m256i is_zero = _mm256_xor_si256(_mm256_max_epu32(currentmax, standardmax), standardmax); if(_mm256_testz_si256(is_zero, is_zero) == 0) { return nullptr; } is_zero = _mm256_xor_si256(_mm256_max_epu32(currentoffsetmax, standardoffsetmax), standardoffsetmax); if(_mm256_testz_si256(is_zero, is_zero) == 0) { return nullptr; } return input; }
1,209
535
// Copyright (c) 2017 Intel Corporation // // 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 "mfx_trace_utils.h" #include <sstream> #include <iomanip> #ifdef MFX_TRACE_ENABLE #include "vm_sys_info.h" #if defined(ANDROID) #include "snprintf_s.h" #endif extern "C" { #include <stdlib.h> /*------------------------------------------------------------------------------*/ FILE* mfx_trace_open_conf_file(const char* name) { FILE* file = NULL; char file_name[MAX_PATH] = {0}; #if defined(ANDROID) const char* home = "/data/data/com.intel.vtune/mediasdk"; #else const char* home = getenv("HOME"); #endif if (home) { snprintf_s_ss(file_name, MAX_PATH-1, "%s/.%s", getenv("HOME"), name); file = fopen(file_name, "r"); } else { snprintf_s_ss(file_name, MAX_PATH-1, "%s/%s", MFX_TRACE_CONFIG_PATH, name); file = fopen(file_name, "r"); } return file; } /*------------------------------------------------------------------------------*/ mfxTraceU32 mfx_trace_get_value_pos(FILE* file, const char* pName, char* line, mfxTraceU32 line_size, char** value_pos) { char *str = NULL, *p = NULL; mfxTraceU32 n = 0; bool bFound = false; if (!file || ! pName || !value_pos) return 1; while (NULL != (str = fgets(line, line_size-1, file))) { n = strnlen_s(str, line_size-1); if ((n > 0) && (str[n-1] == '\n')) str[n-1] = '\0'; for(; strchr(" \t", *str) && (*str); str++); n = strnlen_s(pName, 256); if (!strncmp(str, pName, n)) { str += n; if (!strchr(" =\t", *str)) continue; for(; strchr(" =\t", *str) && (*str); str++); bFound = true; *value_pos = str; break; } } return (bFound)? 0: 1; } /*------------------------------------------------------------------------------*/ mfxTraceU32 mfx_trace_get_conf_dword(FILE* file, const char* pName, mfxTraceU32* pValue) { char line[MAX_PATH] = {0}, *value_pos = NULL; if (!mfx_trace_get_value_pos(file, pName, line, sizeof(line), &value_pos)) { if (!strncmp(value_pos, "0x", 2)) { value_pos += 2; std::stringstream ss(value_pos); std::string s; ss >> std::setw(8) >> s; std::stringstream(s) >> std::hex >> *pValue; } else { *pValue = atoi(value_pos); } return 0; } return 1; } mfxTraceU32 mfx_trace_get_conf_string(FILE* file, const char* pName, mfxTraceChar* pValue, mfxTraceU32 cValueMaxSize) { char line[MAX_PATH] = {0}, *value_pos = NULL; if (!mfx_trace_get_value_pos(file, pName, line, sizeof(line), &value_pos)) { strncpy(pValue, value_pos, cValueMaxSize-1); return 0; } return 1; } } // extern "C" #endif // #ifdef MFX_TRACE_ENABLE
4,201
1,446
#include <iostream> #include <algorithm> #include <cstdio> #define maxN 102 #define maxA 20002 typedef int maxn, maxa; maxn n, lim_n; bool f[maxA][maxN]; maxa a[maxN], lim_t, sum, res; void Prepare() { std::cin >> n; for (maxn i = 0; i < n; i++) std::cin >> a[i], sum += a[i]; lim_t = sum / 2, lim_n = n / 2 + (n & 1); //std::cout << lim_t << ' ' << lim_n << '\n'; } void Process() { for (maxn i = 0; i < n; i++) { f[a[i]][1] = 1; for (maxn j = 2; j <= i + 1 && j <= lim_n; j++) { for (maxa t = a[i]; t <= lim_t; t++) { f[t][j] |= f[t - a[i]][j - 1]; //if (f[t][j]) std::cout << a[i] << ' ' << j << ' ' << t << ' ' << f[t][j] << '\n'; } } } if (n == 1) lim_t = a[0]; while (!f[lim_t][lim_n] && !f[lim_t][lim_n - (n & 1)]) --lim_t; std::cout << std::min(sum - lim_t, lim_t) << ' ' << std::max(lim_t, sum - lim_t); } int main() { freopen("chiaqua.inp", "r", stdin); freopen("chiaqua.out", "w", stdout); std::ios_base::sync_with_stdio(0); std::cin.tie(0); Prepare(); Process(); }
1,022
537
/* * 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. */ /*! * \file expr_functor.cc */ #include <tvm/tir/expr_functor.h> #include "functor_common.h" namespace tvm { namespace tir { void ExprVisitor::VisitExpr_(const VarNode* op) {} void ExprVisitor::VisitExpr_(const SizeVarNode* op) { this->VisitExpr_(static_cast<const VarNode*>(op)); } void ExprVisitor::VisitExpr_(const AnyNode* op) {} void ExprVisitor::VisitExpr_(const LoadNode* op) { LOG(FATAL) << "Unexpected use of deprecated LoadNode. Please use BufferLoadNode instead."; } void ExprVisitor::VisitExpr_(const BufferLoadNode* op) { VisitArray(op->indices, [this](const PrimExpr& e) { this->VisitExpr(e); }); } void ExprVisitor::VisitExpr_(const ProducerLoadNode* op) { VisitArray(op->indices, [this](const PrimExpr& e) { this->VisitExpr(e); }); } void ExprVisitor::VisitExpr_(const LetNode* op) { this->VisitExpr(op->value); this->VisitExpr(op->body); } void ExprVisitor::VisitExpr_(const CallNode* op) { VisitArray(op->args, [this](const PrimExpr& e) { this->VisitExpr(e); }); } #define DEFINE_BINOP_VISIT_(OP) \ void ExprVisitor::VisitExpr_(const OP* op) { \ this->VisitExpr(op->a); \ this->VisitExpr(op->b); \ } DEFINE_BINOP_VISIT_(AddNode); DEFINE_BINOP_VISIT_(SubNode); DEFINE_BINOP_VISIT_(MulNode); DEFINE_BINOP_VISIT_(DivNode); DEFINE_BINOP_VISIT_(ModNode); DEFINE_BINOP_VISIT_(FloorDivNode); DEFINE_BINOP_VISIT_(FloorModNode); DEFINE_BINOP_VISIT_(MinNode); DEFINE_BINOP_VISIT_(MaxNode); DEFINE_BINOP_VISIT_(EQNode); DEFINE_BINOP_VISIT_(NENode); DEFINE_BINOP_VISIT_(LTNode); DEFINE_BINOP_VISIT_(LENode); DEFINE_BINOP_VISIT_(GTNode); DEFINE_BINOP_VISIT_(GENode); DEFINE_BINOP_VISIT_(AndNode); DEFINE_BINOP_VISIT_(OrNode); void ExprVisitor::VisitExpr_(const IntImmNode* op) {} void ExprVisitor::VisitExpr_(const FloatImmNode* op) {} void ExprVisitor::VisitExpr_(const StringImmNode* op) {} void ExprVisitor::VisitExpr_(const ReduceNode* op) { VisitArray(op->axis, [this](const IterVar& r) { this->VisitExpr(r->dom->min); this->VisitExpr(r->dom->extent); }); VisitArray(op->source, [this](const PrimExpr& e) { this->VisitExpr(e); }); if (!op->init.empty()) { VisitArray(op->init, [this](const PrimExpr& e) { this->VisitExpr(e); }); } this->VisitExpr(op->condition); } void ExprVisitor::VisitExpr_(const CastNode* op) { this->VisitExpr(op->value); } void ExprVisitor::VisitExpr_(const NotNode* op) { this->VisitExpr(op->a); } void ExprVisitor::VisitExpr_(const SelectNode* op) { this->VisitExpr(op->condition); this->VisitExpr(op->true_value); this->VisitExpr(op->false_value); } void ExprVisitor::VisitExpr_(const RampNode* op) { this->VisitExpr(op->base); this->VisitExpr(op->stride); } void ExprVisitor::VisitExpr_(const ShuffleNode* op) { VisitArray(op->indices, [this](const PrimExpr& e) { this->VisitExpr(e); }); VisitArray(op->vectors, [this](const PrimExpr& e) { this->VisitExpr(e); }); } void ExprVisitor::VisitExpr_(const BroadcastNode* op) { this->VisitExpr(op->value); } PrimExpr ExprMutator::VisitExpr_(const VarNode* op) { return GetRef<PrimExpr>(op); } PrimExpr ExprMutator::VisitExpr_(const SizeVarNode* op) { return this->VisitExpr_(static_cast<const VarNode*>(op)); } PrimExpr ExprMutator::VisitExpr_(const AnyNode* op) { return GetRef<PrimExpr>(op); } PrimExpr ExprMutator::VisitExpr_(const LoadNode* op) { LOG(FATAL) << "Unexpected use of deprecated LoadNode. Please use BufferLoadNode instead."; return PrimExpr(); } PrimExpr ExprMutator::VisitExpr_(const BufferLoadNode* op) { auto fmutate = [this](const PrimExpr& e) { return this->VisitExpr(e); }; Array<PrimExpr> indices = MutateArray(op->indices, fmutate); if (indices.same_as(op->indices)) { return GetRef<PrimExpr>(op); } else { return BufferLoad(op->buffer, indices); } } PrimExpr ExprMutator::VisitExpr_(const ProducerLoadNode* op) { auto fmutate = [this](const PrimExpr& e) { return this->VisitExpr(e); }; Array<PrimExpr> indices = MutateArray(op->indices, fmutate); if (indices.same_as(op->indices)) { return GetRef<PrimExpr>(op); } else { return ProducerLoad(op->producer, indices); } } PrimExpr ExprMutator::VisitExpr_(const LetNode* op) { PrimExpr value = this->VisitExpr(op->value); PrimExpr body = this->VisitExpr(op->body); if (value.same_as(op->value) && body.same_as(op->body)) { return GetRef<PrimExpr>(op); } else { return Let(op->var, value, body); } } PrimExpr ExprMutator::VisitExpr_(const CallNode* op) { auto fmutate = [this](const PrimExpr& e) { return this->VisitExpr(e); }; Array<PrimExpr> args = MutateArray(op->args, fmutate); if (args.same_as(op->args)) { return GetRef<PrimExpr>(op); } else { return Call(op->dtype, op->op, args); } } #define DEFINE_OP_RETURN_SELF_EXPR_MUTATE_(OP) \ PrimExpr ExprMutator::VisitExpr_(const OP* op) { return GetRef<PrimExpr>(op); } DEFINE_OP_RETURN_SELF_EXPR_MUTATE_(IntImmNode) DEFINE_OP_RETURN_SELF_EXPR_MUTATE_(FloatImmNode) DEFINE_OP_RETURN_SELF_EXPR_MUTATE_(StringImmNode) #define DEFINE_BIOP_EXPR_MUTATE_(OP) \ PrimExpr ExprMutator::VisitExpr_(const OP##Node* op) { \ PrimExpr a = this->VisitExpr(op->a); \ PrimExpr b = this->VisitExpr(op->b); \ if (a.same_as(op->a) && b.same_as(op->b)) { \ return GetRef<PrimExpr>(op); \ } else { \ return OP(a, b); \ } \ } DEFINE_BIOP_EXPR_MUTATE_(Add); DEFINE_BIOP_EXPR_MUTATE_(Sub); DEFINE_BIOP_EXPR_MUTATE_(Mul); DEFINE_BIOP_EXPR_MUTATE_(Div); DEFINE_BIOP_EXPR_MUTATE_(Mod); DEFINE_BIOP_EXPR_MUTATE_(FloorDiv); DEFINE_BIOP_EXPR_MUTATE_(FloorMod); DEFINE_BIOP_EXPR_MUTATE_(Min); DEFINE_BIOP_EXPR_MUTATE_(Max); DEFINE_BIOP_EXPR_MUTATE_(EQ); DEFINE_BIOP_EXPR_MUTATE_(NE); DEFINE_BIOP_EXPR_MUTATE_(LT); DEFINE_BIOP_EXPR_MUTATE_(LE); DEFINE_BIOP_EXPR_MUTATE_(GT); DEFINE_BIOP_EXPR_MUTATE_(GE); DEFINE_BIOP_EXPR_MUTATE_(And); DEFINE_BIOP_EXPR_MUTATE_(Or); PrimExpr ExprMutator::VisitExpr_(const ReduceNode* op) { auto fitervar = [this](const IterVar& v) { Range r = v->dom; PrimExpr min = this->VisitExpr(r->min); PrimExpr extent = this->VisitExpr(r->extent); if (min.same_as(r->min) && extent.same_as(r->extent)) { return v; } else { return IterVar(Range::FromMinExtent(min, extent), v->var, v->iter_type, v->thread_tag); } }; Array<IterVar> axis = MutateArray(op->axis, fitervar); auto fexpr = [this](const PrimExpr& e) { return this->VisitExpr(e); }; Array<PrimExpr> source = MutateArray(op->source, fexpr); Array<PrimExpr> init = MutateArray(op->init, fexpr); PrimExpr condition = this->VisitExpr(op->condition); if (axis.same_as(op->axis) && source.same_as(op->source) && condition.same_as(op->condition) && init.same_as(op->init)) { return GetRef<PrimExpr>(op); } else { return Reduce(op->combiner, source, axis, condition, op->value_index, init); } } PrimExpr ExprMutator::VisitExpr_(const CastNode* op) { PrimExpr value = this->VisitExpr(op->value); if (value.same_as(op->value)) { return GetRef<PrimExpr>(op); } else { return Cast(op->dtype, value); } } PrimExpr ExprMutator::VisitExpr_(const NotNode* op) { PrimExpr a = this->VisitExpr(op->a); if (a.same_as(op->a)) { return GetRef<PrimExpr>(op); } else { return Not(a); } } PrimExpr ExprMutator::VisitExpr_(const SelectNode* op) { PrimExpr condition = this->VisitExpr(op->condition); PrimExpr true_value = this->VisitExpr(op->true_value); PrimExpr false_value = this->VisitExpr(op->false_value); if (condition.same_as(op->condition) && true_value.same_as(op->true_value) && false_value.same_as(op->false_value)) { return GetRef<PrimExpr>(op); } else { return Select(condition, true_value, false_value); } } PrimExpr ExprMutator::VisitExpr_(const RampNode* op) { PrimExpr base = this->VisitExpr(op->base); PrimExpr stride = this->VisitExpr(op->stride); if (base.same_as(op->base) && stride.same_as(op->stride)) { return GetRef<PrimExpr>(op); } else { return Ramp(base, stride, op->lanes); } } PrimExpr ExprMutator::VisitExpr_(const BroadcastNode* op) { PrimExpr value = this->VisitExpr(op->value); if (value.same_as(op->value)) { return GetRef<PrimExpr>(op); } else { return Broadcast(value, op->lanes); } } PrimExpr ExprMutator::VisitExpr_(const ShuffleNode* op) { auto fexpr = [this](const PrimExpr& e) { return this->VisitExpr(e); }; auto vectors = MutateArray(op->vectors, fexpr); if (vectors.same_as(op->vectors)) { return GetRef<PrimExpr>(op); } else { return Shuffle(vectors, op->indices); } } } // namespace tir } // namespace tvm
9,663
3,651
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <vector> #include "single_layer_tests/logical.hpp" #include "common_test_utils/test_constants.hpp" using namespace LayerTestsDefinitions; using namespace LayerTestsDefinitions::LogicalParams; namespace { std::map<std::vector<size_t>, std::vector<std::vector<size_t >>> inputShapes = { {{1}, {{1}, {17}, {1, 1}, {2, 18}, {1, 1, 2}, {2, 2, 3}, {1, 1, 2, 3}}}, {{5}, {{1}, {1, 1}, {2, 5}, {1, 1, 1}, {2, 2, 5}}}, {{2, 200}, {{1}, {200}, {1, 200}, {2, 200}, {2, 2, 200}}}, {{1, 3, 20}, {{20}, {2, 1, 1}}}, {{2, 17, 3, 4}, {{4}, {1, 3, 4}, {2, 1, 3, 4}}}, {{2, 1, 1, 3, 1}, {{1}, {1, 3, 4}, {2, 1, 3, 4}, {1, 1, 1, 1, 1}}}, }; std::map<std::vector<size_t>, std::vector<std::vector<size_t >>> inputShapesNot = { {{1}, {}}, {{5}, {}}, {{2, 200}, {}}, {{1, 3, 20}, {}}, {{2, 17, 3, 4}, {}}, {{2, 1, 1, 3, 1}, {}}, }; std::vector<InferenceEngine::Precision> inputsPrecisions = { InferenceEngine::Precision::BOOL, }; std::vector<ngraph::helpers::LogicalTypes> logicalOpTypes = { ngraph::helpers::LogicalTypes::LOGICAL_AND, ngraph::helpers::LogicalTypes::LOGICAL_OR, ngraph::helpers::LogicalTypes::LOGICAL_XOR, }; std::vector<ngraph::helpers::InputLayerType> secondInputTypes = { ngraph::helpers::InputLayerType::CONSTANT, ngraph::helpers::InputLayerType::PARAMETER, }; std::vector<InferenceEngine::Precision> netPrecisions = { InferenceEngine::Precision::FP32, }; std::map<std::string, std::string> additional_config = {}; const auto LogicalTestParams = ::testing::Combine( ::testing::ValuesIn(LogicalLayerTest::combineShapes(inputShapes)), ::testing::ValuesIn(logicalOpTypes), ::testing::ValuesIn(secondInputTypes), ::testing::ValuesIn(netPrecisions), ::testing::ValuesIn(inputsPrecisions), ::testing::Values(InferenceEngine::Precision::UNSPECIFIED), ::testing::Values(InferenceEngine::Layout::ANY), ::testing::Values(InferenceEngine::Layout::ANY), ::testing::Values(CommonTestUtils::DEVICE_GPU), ::testing::Values(additional_config)); const auto LogicalTestParamsNot = ::testing::Combine( ::testing::ValuesIn(LogicalLayerTest::combineShapes(inputShapesNot)), ::testing::Values(ngraph::helpers::LogicalTypes::LOGICAL_NOT), ::testing::Values(ngraph::helpers::InputLayerType::CONSTANT), ::testing::ValuesIn(netPrecisions), ::testing::ValuesIn(inputsPrecisions), ::testing::Values(InferenceEngine::Precision::UNSPECIFIED), ::testing::Values(InferenceEngine::Layout::ANY), ::testing::Values(InferenceEngine::Layout::ANY), ::testing::Values(CommonTestUtils::DEVICE_GPU), ::testing::Values(additional_config)); INSTANTIATE_TEST_CASE_P(smoke_CompareWithRefs, LogicalLayerTest, LogicalTestParams, LogicalLayerTest::getTestCaseName); INSTANTIATE_TEST_CASE_P(smoke_CompareWithRefsNot, LogicalLayerTest, LogicalTestParamsNot, LogicalLayerTest::getTestCaseName); } // namespace
3,181
1,193
# /* Copyright (C) 2001 # * Housemarque Oy # * http://www.housemarque.com # * # * Distributed under the Boost Software License, Version 1.0. (See # * accompanying file LICENSE_1_0.txt or copy at # * http://www.boost.org/LICENSE_1_0.txt) # */ # # /* Revised by Paul Mensonides (2002) */ # # /* See http://www.boost.org for most recent version. */ # # ifndef MSGPACK_PREPROCESSOR_CONTROL_DETAIL_MSVC_WHILE_HPP # define MSGPACK_PREPROCESSOR_CONTROL_DETAIL_MSVC_WHILE_HPP # # include "../../if.hpp" # include "../../../tuple/eat.hpp" # # define MSGPACK_PP_WHILE_1(p, o, s) MSGPACK_PP_IF(p(2, s), MSGPACK_PP_WHILE_2, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(2, s)) # define MSGPACK_PP_WHILE_2(p, o, s) MSGPACK_PP_IF(p(3, s), MSGPACK_PP_WHILE_3, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(3, s)) # define MSGPACK_PP_WHILE_3(p, o, s) MSGPACK_PP_IF(p(4, s), MSGPACK_PP_WHILE_4, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(4, s)) # define MSGPACK_PP_WHILE_4(p, o, s) MSGPACK_PP_IF(p(5, s), MSGPACK_PP_WHILE_5, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(5, s)) # define MSGPACK_PP_WHILE_5(p, o, s) MSGPACK_PP_IF(p(6, s), MSGPACK_PP_WHILE_6, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(6, s)) # define MSGPACK_PP_WHILE_6(p, o, s) MSGPACK_PP_IF(p(7, s), MSGPACK_PP_WHILE_7, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(7, s)) # define MSGPACK_PP_WHILE_7(p, o, s) MSGPACK_PP_IF(p(8, s), MSGPACK_PP_WHILE_8, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(8, s)) # define MSGPACK_PP_WHILE_8(p, o, s) MSGPACK_PP_IF(p(9, s), MSGPACK_PP_WHILE_9, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(9, s)) # define MSGPACK_PP_WHILE_9(p, o, s) MSGPACK_PP_IF(p(10, s), MSGPACK_PP_WHILE_10, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(10, s)) # define MSGPACK_PP_WHILE_10(p, o, s) MSGPACK_PP_IF(p(11, s), MSGPACK_PP_WHILE_11, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(11, s)) # define MSGPACK_PP_WHILE_11(p, o, s) MSGPACK_PP_IF(p(12, s), MSGPACK_PP_WHILE_12, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(12, s)) # define MSGPACK_PP_WHILE_12(p, o, s) MSGPACK_PP_IF(p(13, s), MSGPACK_PP_WHILE_13, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(13, s)) # define MSGPACK_PP_WHILE_13(p, o, s) MSGPACK_PP_IF(p(14, s), MSGPACK_PP_WHILE_14, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(14, s)) # define MSGPACK_PP_WHILE_14(p, o, s) MSGPACK_PP_IF(p(15, s), MSGPACK_PP_WHILE_15, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(15, s)) # define MSGPACK_PP_WHILE_15(p, o, s) MSGPACK_PP_IF(p(16, s), MSGPACK_PP_WHILE_16, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(16, s)) # define MSGPACK_PP_WHILE_16(p, o, s) MSGPACK_PP_IF(p(17, s), MSGPACK_PP_WHILE_17, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(17, s)) # define MSGPACK_PP_WHILE_17(p, o, s) MSGPACK_PP_IF(p(18, s), MSGPACK_PP_WHILE_18, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(18, s)) # define MSGPACK_PP_WHILE_18(p, o, s) MSGPACK_PP_IF(p(19, s), MSGPACK_PP_WHILE_19, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(19, s)) # define MSGPACK_PP_WHILE_19(p, o, s) MSGPACK_PP_IF(p(20, s), MSGPACK_PP_WHILE_20, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(20, s)) # define MSGPACK_PP_WHILE_20(p, o, s) MSGPACK_PP_IF(p(21, s), MSGPACK_PP_WHILE_21, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(21, s)) # define MSGPACK_PP_WHILE_21(p, o, s) MSGPACK_PP_IF(p(22, s), MSGPACK_PP_WHILE_22, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(22, s)) # define MSGPACK_PP_WHILE_22(p, o, s) MSGPACK_PP_IF(p(23, s), MSGPACK_PP_WHILE_23, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(23, s)) # define MSGPACK_PP_WHILE_23(p, o, s) MSGPACK_PP_IF(p(24, s), MSGPACK_PP_WHILE_24, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(24, s)) # define MSGPACK_PP_WHILE_24(p, o, s) MSGPACK_PP_IF(p(25, s), MSGPACK_PP_WHILE_25, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(25, s)) # define MSGPACK_PP_WHILE_25(p, o, s) MSGPACK_PP_IF(p(26, s), MSGPACK_PP_WHILE_26, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(26, s)) # define MSGPACK_PP_WHILE_26(p, o, s) MSGPACK_PP_IF(p(27, s), MSGPACK_PP_WHILE_27, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(27, s)) # define MSGPACK_PP_WHILE_27(p, o, s) MSGPACK_PP_IF(p(28, s), MSGPACK_PP_WHILE_28, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(28, s)) # define MSGPACK_PP_WHILE_28(p, o, s) MSGPACK_PP_IF(p(29, s), MSGPACK_PP_WHILE_29, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(29, s)) # define MSGPACK_PP_WHILE_29(p, o, s) MSGPACK_PP_IF(p(30, s), MSGPACK_PP_WHILE_30, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(30, s)) # define MSGPACK_PP_WHILE_30(p, o, s) MSGPACK_PP_IF(p(31, s), MSGPACK_PP_WHILE_31, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(31, s)) # define MSGPACK_PP_WHILE_31(p, o, s) MSGPACK_PP_IF(p(32, s), MSGPACK_PP_WHILE_32, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(32, s)) # define MSGPACK_PP_WHILE_32(p, o, s) MSGPACK_PP_IF(p(33, s), MSGPACK_PP_WHILE_33, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(33, s)) # define MSGPACK_PP_WHILE_33(p, o, s) MSGPACK_PP_IF(p(34, s), MSGPACK_PP_WHILE_34, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(34, s)) # define MSGPACK_PP_WHILE_34(p, o, s) MSGPACK_PP_IF(p(35, s), MSGPACK_PP_WHILE_35, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(35, s)) # define MSGPACK_PP_WHILE_35(p, o, s) MSGPACK_PP_IF(p(36, s), MSGPACK_PP_WHILE_36, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(36, s)) # define MSGPACK_PP_WHILE_36(p, o, s) MSGPACK_PP_IF(p(37, s), MSGPACK_PP_WHILE_37, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(37, s)) # define MSGPACK_PP_WHILE_37(p, o, s) MSGPACK_PP_IF(p(38, s), MSGPACK_PP_WHILE_38, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(38, s)) # define MSGPACK_PP_WHILE_38(p, o, s) MSGPACK_PP_IF(p(39, s), MSGPACK_PP_WHILE_39, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(39, s)) # define MSGPACK_PP_WHILE_39(p, o, s) MSGPACK_PP_IF(p(40, s), MSGPACK_PP_WHILE_40, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(40, s)) # define MSGPACK_PP_WHILE_40(p, o, s) MSGPACK_PP_IF(p(41, s), MSGPACK_PP_WHILE_41, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(41, s)) # define MSGPACK_PP_WHILE_41(p, o, s) MSGPACK_PP_IF(p(42, s), MSGPACK_PP_WHILE_42, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(42, s)) # define MSGPACK_PP_WHILE_42(p, o, s) MSGPACK_PP_IF(p(43, s), MSGPACK_PP_WHILE_43, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(43, s)) # define MSGPACK_PP_WHILE_43(p, o, s) MSGPACK_PP_IF(p(44, s), MSGPACK_PP_WHILE_44, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(44, s)) # define MSGPACK_PP_WHILE_44(p, o, s) MSGPACK_PP_IF(p(45, s), MSGPACK_PP_WHILE_45, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(45, s)) # define MSGPACK_PP_WHILE_45(p, o, s) MSGPACK_PP_IF(p(46, s), MSGPACK_PP_WHILE_46, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(46, s)) # define MSGPACK_PP_WHILE_46(p, o, s) MSGPACK_PP_IF(p(47, s), MSGPACK_PP_WHILE_47, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(47, s)) # define MSGPACK_PP_WHILE_47(p, o, s) MSGPACK_PP_IF(p(48, s), MSGPACK_PP_WHILE_48, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(48, s)) # define MSGPACK_PP_WHILE_48(p, o, s) MSGPACK_PP_IF(p(49, s), MSGPACK_PP_WHILE_49, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(49, s)) # define MSGPACK_PP_WHILE_49(p, o, s) MSGPACK_PP_IF(p(50, s), MSGPACK_PP_WHILE_50, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(50, s)) # define MSGPACK_PP_WHILE_50(p, o, s) MSGPACK_PP_IF(p(51, s), MSGPACK_PP_WHILE_51, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(51, s)) # define MSGPACK_PP_WHILE_51(p, o, s) MSGPACK_PP_IF(p(52, s), MSGPACK_PP_WHILE_52, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(52, s)) # define MSGPACK_PP_WHILE_52(p, o, s) MSGPACK_PP_IF(p(53, s), MSGPACK_PP_WHILE_53, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(53, s)) # define MSGPACK_PP_WHILE_53(p, o, s) MSGPACK_PP_IF(p(54, s), MSGPACK_PP_WHILE_54, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(54, s)) # define MSGPACK_PP_WHILE_54(p, o, s) MSGPACK_PP_IF(p(55, s), MSGPACK_PP_WHILE_55, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(55, s)) # define MSGPACK_PP_WHILE_55(p, o, s) MSGPACK_PP_IF(p(56, s), MSGPACK_PP_WHILE_56, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(56, s)) # define MSGPACK_PP_WHILE_56(p, o, s) MSGPACK_PP_IF(p(57, s), MSGPACK_PP_WHILE_57, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(57, s)) # define MSGPACK_PP_WHILE_57(p, o, s) MSGPACK_PP_IF(p(58, s), MSGPACK_PP_WHILE_58, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(58, s)) # define MSGPACK_PP_WHILE_58(p, o, s) MSGPACK_PP_IF(p(59, s), MSGPACK_PP_WHILE_59, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(59, s)) # define MSGPACK_PP_WHILE_59(p, o, s) MSGPACK_PP_IF(p(60, s), MSGPACK_PP_WHILE_60, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(60, s)) # define MSGPACK_PP_WHILE_60(p, o, s) MSGPACK_PP_IF(p(61, s), MSGPACK_PP_WHILE_61, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(61, s)) # define MSGPACK_PP_WHILE_61(p, o, s) MSGPACK_PP_IF(p(62, s), MSGPACK_PP_WHILE_62, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(62, s)) # define MSGPACK_PP_WHILE_62(p, o, s) MSGPACK_PP_IF(p(63, s), MSGPACK_PP_WHILE_63, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(63, s)) # define MSGPACK_PP_WHILE_63(p, o, s) MSGPACK_PP_IF(p(64, s), MSGPACK_PP_WHILE_64, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(64, s)) # define MSGPACK_PP_WHILE_64(p, o, s) MSGPACK_PP_IF(p(65, s), MSGPACK_PP_WHILE_65, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(65, s)) # define MSGPACK_PP_WHILE_65(p, o, s) MSGPACK_PP_IF(p(66, s), MSGPACK_PP_WHILE_66, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(66, s)) # define MSGPACK_PP_WHILE_66(p, o, s) MSGPACK_PP_IF(p(67, s), MSGPACK_PP_WHILE_67, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(67, s)) # define MSGPACK_PP_WHILE_67(p, o, s) MSGPACK_PP_IF(p(68, s), MSGPACK_PP_WHILE_68, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(68, s)) # define MSGPACK_PP_WHILE_68(p, o, s) MSGPACK_PP_IF(p(69, s), MSGPACK_PP_WHILE_69, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(69, s)) # define MSGPACK_PP_WHILE_69(p, o, s) MSGPACK_PP_IF(p(70, s), MSGPACK_PP_WHILE_70, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(70, s)) # define MSGPACK_PP_WHILE_70(p, o, s) MSGPACK_PP_IF(p(71, s), MSGPACK_PP_WHILE_71, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(71, s)) # define MSGPACK_PP_WHILE_71(p, o, s) MSGPACK_PP_IF(p(72, s), MSGPACK_PP_WHILE_72, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(72, s)) # define MSGPACK_PP_WHILE_72(p, o, s) MSGPACK_PP_IF(p(73, s), MSGPACK_PP_WHILE_73, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(73, s)) # define MSGPACK_PP_WHILE_73(p, o, s) MSGPACK_PP_IF(p(74, s), MSGPACK_PP_WHILE_74, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(74, s)) # define MSGPACK_PP_WHILE_74(p, o, s) MSGPACK_PP_IF(p(75, s), MSGPACK_PP_WHILE_75, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(75, s)) # define MSGPACK_PP_WHILE_75(p, o, s) MSGPACK_PP_IF(p(76, s), MSGPACK_PP_WHILE_76, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(76, s)) # define MSGPACK_PP_WHILE_76(p, o, s) MSGPACK_PP_IF(p(77, s), MSGPACK_PP_WHILE_77, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(77, s)) # define MSGPACK_PP_WHILE_77(p, o, s) MSGPACK_PP_IF(p(78, s), MSGPACK_PP_WHILE_78, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(78, s)) # define MSGPACK_PP_WHILE_78(p, o, s) MSGPACK_PP_IF(p(79, s), MSGPACK_PP_WHILE_79, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(79, s)) # define MSGPACK_PP_WHILE_79(p, o, s) MSGPACK_PP_IF(p(80, s), MSGPACK_PP_WHILE_80, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(80, s)) # define MSGPACK_PP_WHILE_80(p, o, s) MSGPACK_PP_IF(p(81, s), MSGPACK_PP_WHILE_81, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(81, s)) # define MSGPACK_PP_WHILE_81(p, o, s) MSGPACK_PP_IF(p(82, s), MSGPACK_PP_WHILE_82, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(82, s)) # define MSGPACK_PP_WHILE_82(p, o, s) MSGPACK_PP_IF(p(83, s), MSGPACK_PP_WHILE_83, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(83, s)) # define MSGPACK_PP_WHILE_83(p, o, s) MSGPACK_PP_IF(p(84, s), MSGPACK_PP_WHILE_84, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(84, s)) # define MSGPACK_PP_WHILE_84(p, o, s) MSGPACK_PP_IF(p(85, s), MSGPACK_PP_WHILE_85, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(85, s)) # define MSGPACK_PP_WHILE_85(p, o, s) MSGPACK_PP_IF(p(86, s), MSGPACK_PP_WHILE_86, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(86, s)) # define MSGPACK_PP_WHILE_86(p, o, s) MSGPACK_PP_IF(p(87, s), MSGPACK_PP_WHILE_87, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(87, s)) # define MSGPACK_PP_WHILE_87(p, o, s) MSGPACK_PP_IF(p(88, s), MSGPACK_PP_WHILE_88, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(88, s)) # define MSGPACK_PP_WHILE_88(p, o, s) MSGPACK_PP_IF(p(89, s), MSGPACK_PP_WHILE_89, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(89, s)) # define MSGPACK_PP_WHILE_89(p, o, s) MSGPACK_PP_IF(p(90, s), MSGPACK_PP_WHILE_90, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(90, s)) # define MSGPACK_PP_WHILE_90(p, o, s) MSGPACK_PP_IF(p(91, s), MSGPACK_PP_WHILE_91, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(91, s)) # define MSGPACK_PP_WHILE_91(p, o, s) MSGPACK_PP_IF(p(92, s), MSGPACK_PP_WHILE_92, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(92, s)) # define MSGPACK_PP_WHILE_92(p, o, s) MSGPACK_PP_IF(p(93, s), MSGPACK_PP_WHILE_93, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(93, s)) # define MSGPACK_PP_WHILE_93(p, o, s) MSGPACK_PP_IF(p(94, s), MSGPACK_PP_WHILE_94, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(94, s)) # define MSGPACK_PP_WHILE_94(p, o, s) MSGPACK_PP_IF(p(95, s), MSGPACK_PP_WHILE_95, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(95, s)) # define MSGPACK_PP_WHILE_95(p, o, s) MSGPACK_PP_IF(p(96, s), MSGPACK_PP_WHILE_96, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(96, s)) # define MSGPACK_PP_WHILE_96(p, o, s) MSGPACK_PP_IF(p(97, s), MSGPACK_PP_WHILE_97, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(97, s)) # define MSGPACK_PP_WHILE_97(p, o, s) MSGPACK_PP_IF(p(98, s), MSGPACK_PP_WHILE_98, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(98, s)) # define MSGPACK_PP_WHILE_98(p, o, s) MSGPACK_PP_IF(p(99, s), MSGPACK_PP_WHILE_99, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(99, s)) # define MSGPACK_PP_WHILE_99(p, o, s) MSGPACK_PP_IF(p(100, s), MSGPACK_PP_WHILE_100, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(100, s)) # define MSGPACK_PP_WHILE_100(p, o, s) MSGPACK_PP_IF(p(101, s), MSGPACK_PP_WHILE_101, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(101, s)) # define MSGPACK_PP_WHILE_101(p, o, s) MSGPACK_PP_IF(p(102, s), MSGPACK_PP_WHILE_102, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(102, s)) # define MSGPACK_PP_WHILE_102(p, o, s) MSGPACK_PP_IF(p(103, s), MSGPACK_PP_WHILE_103, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(103, s)) # define MSGPACK_PP_WHILE_103(p, o, s) MSGPACK_PP_IF(p(104, s), MSGPACK_PP_WHILE_104, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(104, s)) # define MSGPACK_PP_WHILE_104(p, o, s) MSGPACK_PP_IF(p(105, s), MSGPACK_PP_WHILE_105, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(105, s)) # define MSGPACK_PP_WHILE_105(p, o, s) MSGPACK_PP_IF(p(106, s), MSGPACK_PP_WHILE_106, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(106, s)) # define MSGPACK_PP_WHILE_106(p, o, s) MSGPACK_PP_IF(p(107, s), MSGPACK_PP_WHILE_107, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(107, s)) # define MSGPACK_PP_WHILE_107(p, o, s) MSGPACK_PP_IF(p(108, s), MSGPACK_PP_WHILE_108, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(108, s)) # define MSGPACK_PP_WHILE_108(p, o, s) MSGPACK_PP_IF(p(109, s), MSGPACK_PP_WHILE_109, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(109, s)) # define MSGPACK_PP_WHILE_109(p, o, s) MSGPACK_PP_IF(p(110, s), MSGPACK_PP_WHILE_110, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(110, s)) # define MSGPACK_PP_WHILE_110(p, o, s) MSGPACK_PP_IF(p(111, s), MSGPACK_PP_WHILE_111, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(111, s)) # define MSGPACK_PP_WHILE_111(p, o, s) MSGPACK_PP_IF(p(112, s), MSGPACK_PP_WHILE_112, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(112, s)) # define MSGPACK_PP_WHILE_112(p, o, s) MSGPACK_PP_IF(p(113, s), MSGPACK_PP_WHILE_113, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(113, s)) # define MSGPACK_PP_WHILE_113(p, o, s) MSGPACK_PP_IF(p(114, s), MSGPACK_PP_WHILE_114, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(114, s)) # define MSGPACK_PP_WHILE_114(p, o, s) MSGPACK_PP_IF(p(115, s), MSGPACK_PP_WHILE_115, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(115, s)) # define MSGPACK_PP_WHILE_115(p, o, s) MSGPACK_PP_IF(p(116, s), MSGPACK_PP_WHILE_116, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(116, s)) # define MSGPACK_PP_WHILE_116(p, o, s) MSGPACK_PP_IF(p(117, s), MSGPACK_PP_WHILE_117, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(117, s)) # define MSGPACK_PP_WHILE_117(p, o, s) MSGPACK_PP_IF(p(118, s), MSGPACK_PP_WHILE_118, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(118, s)) # define MSGPACK_PP_WHILE_118(p, o, s) MSGPACK_PP_IF(p(119, s), MSGPACK_PP_WHILE_119, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(119, s)) # define MSGPACK_PP_WHILE_119(p, o, s) MSGPACK_PP_IF(p(120, s), MSGPACK_PP_WHILE_120, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(120, s)) # define MSGPACK_PP_WHILE_120(p, o, s) MSGPACK_PP_IF(p(121, s), MSGPACK_PP_WHILE_121, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(121, s)) # define MSGPACK_PP_WHILE_121(p, o, s) MSGPACK_PP_IF(p(122, s), MSGPACK_PP_WHILE_122, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(122, s)) # define MSGPACK_PP_WHILE_122(p, o, s) MSGPACK_PP_IF(p(123, s), MSGPACK_PP_WHILE_123, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(123, s)) # define MSGPACK_PP_WHILE_123(p, o, s) MSGPACK_PP_IF(p(124, s), MSGPACK_PP_WHILE_124, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(124, s)) # define MSGPACK_PP_WHILE_124(p, o, s) MSGPACK_PP_IF(p(125, s), MSGPACK_PP_WHILE_125, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(125, s)) # define MSGPACK_PP_WHILE_125(p, o, s) MSGPACK_PP_IF(p(126, s), MSGPACK_PP_WHILE_126, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(126, s)) # define MSGPACK_PP_WHILE_126(p, o, s) MSGPACK_PP_IF(p(127, s), MSGPACK_PP_WHILE_127, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(127, s)) # define MSGPACK_PP_WHILE_127(p, o, s) MSGPACK_PP_IF(p(128, s), MSGPACK_PP_WHILE_128, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(128, s)) # define MSGPACK_PP_WHILE_128(p, o, s) MSGPACK_PP_IF(p(129, s), MSGPACK_PP_WHILE_129, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(129, s)) # define MSGPACK_PP_WHILE_129(p, o, s) MSGPACK_PP_IF(p(130, s), MSGPACK_PP_WHILE_130, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(130, s)) # define MSGPACK_PP_WHILE_130(p, o, s) MSGPACK_PP_IF(p(131, s), MSGPACK_PP_WHILE_131, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(131, s)) # define MSGPACK_PP_WHILE_131(p, o, s) MSGPACK_PP_IF(p(132, s), MSGPACK_PP_WHILE_132, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(132, s)) # define MSGPACK_PP_WHILE_132(p, o, s) MSGPACK_PP_IF(p(133, s), MSGPACK_PP_WHILE_133, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(133, s)) # define MSGPACK_PP_WHILE_133(p, o, s) MSGPACK_PP_IF(p(134, s), MSGPACK_PP_WHILE_134, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(134, s)) # define MSGPACK_PP_WHILE_134(p, o, s) MSGPACK_PP_IF(p(135, s), MSGPACK_PP_WHILE_135, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(135, s)) # define MSGPACK_PP_WHILE_135(p, o, s) MSGPACK_PP_IF(p(136, s), MSGPACK_PP_WHILE_136, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(136, s)) # define MSGPACK_PP_WHILE_136(p, o, s) MSGPACK_PP_IF(p(137, s), MSGPACK_PP_WHILE_137, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(137, s)) # define MSGPACK_PP_WHILE_137(p, o, s) MSGPACK_PP_IF(p(138, s), MSGPACK_PP_WHILE_138, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(138, s)) # define MSGPACK_PP_WHILE_138(p, o, s) MSGPACK_PP_IF(p(139, s), MSGPACK_PP_WHILE_139, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(139, s)) # define MSGPACK_PP_WHILE_139(p, o, s) MSGPACK_PP_IF(p(140, s), MSGPACK_PP_WHILE_140, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(140, s)) # define MSGPACK_PP_WHILE_140(p, o, s) MSGPACK_PP_IF(p(141, s), MSGPACK_PP_WHILE_141, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(141, s)) # define MSGPACK_PP_WHILE_141(p, o, s) MSGPACK_PP_IF(p(142, s), MSGPACK_PP_WHILE_142, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(142, s)) # define MSGPACK_PP_WHILE_142(p, o, s) MSGPACK_PP_IF(p(143, s), MSGPACK_PP_WHILE_143, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(143, s)) # define MSGPACK_PP_WHILE_143(p, o, s) MSGPACK_PP_IF(p(144, s), MSGPACK_PP_WHILE_144, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(144, s)) # define MSGPACK_PP_WHILE_144(p, o, s) MSGPACK_PP_IF(p(145, s), MSGPACK_PP_WHILE_145, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(145, s)) # define MSGPACK_PP_WHILE_145(p, o, s) MSGPACK_PP_IF(p(146, s), MSGPACK_PP_WHILE_146, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(146, s)) # define MSGPACK_PP_WHILE_146(p, o, s) MSGPACK_PP_IF(p(147, s), MSGPACK_PP_WHILE_147, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(147, s)) # define MSGPACK_PP_WHILE_147(p, o, s) MSGPACK_PP_IF(p(148, s), MSGPACK_PP_WHILE_148, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(148, s)) # define MSGPACK_PP_WHILE_148(p, o, s) MSGPACK_PP_IF(p(149, s), MSGPACK_PP_WHILE_149, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(149, s)) # define MSGPACK_PP_WHILE_149(p, o, s) MSGPACK_PP_IF(p(150, s), MSGPACK_PP_WHILE_150, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(150, s)) # define MSGPACK_PP_WHILE_150(p, o, s) MSGPACK_PP_IF(p(151, s), MSGPACK_PP_WHILE_151, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(151, s)) # define MSGPACK_PP_WHILE_151(p, o, s) MSGPACK_PP_IF(p(152, s), MSGPACK_PP_WHILE_152, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(152, s)) # define MSGPACK_PP_WHILE_152(p, o, s) MSGPACK_PP_IF(p(153, s), MSGPACK_PP_WHILE_153, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(153, s)) # define MSGPACK_PP_WHILE_153(p, o, s) MSGPACK_PP_IF(p(154, s), MSGPACK_PP_WHILE_154, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(154, s)) # define MSGPACK_PP_WHILE_154(p, o, s) MSGPACK_PP_IF(p(155, s), MSGPACK_PP_WHILE_155, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(155, s)) # define MSGPACK_PP_WHILE_155(p, o, s) MSGPACK_PP_IF(p(156, s), MSGPACK_PP_WHILE_156, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(156, s)) # define MSGPACK_PP_WHILE_156(p, o, s) MSGPACK_PP_IF(p(157, s), MSGPACK_PP_WHILE_157, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(157, s)) # define MSGPACK_PP_WHILE_157(p, o, s) MSGPACK_PP_IF(p(158, s), MSGPACK_PP_WHILE_158, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(158, s)) # define MSGPACK_PP_WHILE_158(p, o, s) MSGPACK_PP_IF(p(159, s), MSGPACK_PP_WHILE_159, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(159, s)) # define MSGPACK_PP_WHILE_159(p, o, s) MSGPACK_PP_IF(p(160, s), MSGPACK_PP_WHILE_160, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(160, s)) # define MSGPACK_PP_WHILE_160(p, o, s) MSGPACK_PP_IF(p(161, s), MSGPACK_PP_WHILE_161, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(161, s)) # define MSGPACK_PP_WHILE_161(p, o, s) MSGPACK_PP_IF(p(162, s), MSGPACK_PP_WHILE_162, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(162, s)) # define MSGPACK_PP_WHILE_162(p, o, s) MSGPACK_PP_IF(p(163, s), MSGPACK_PP_WHILE_163, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(163, s)) # define MSGPACK_PP_WHILE_163(p, o, s) MSGPACK_PP_IF(p(164, s), MSGPACK_PP_WHILE_164, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(164, s)) # define MSGPACK_PP_WHILE_164(p, o, s) MSGPACK_PP_IF(p(165, s), MSGPACK_PP_WHILE_165, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(165, s)) # define MSGPACK_PP_WHILE_165(p, o, s) MSGPACK_PP_IF(p(166, s), MSGPACK_PP_WHILE_166, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(166, s)) # define MSGPACK_PP_WHILE_166(p, o, s) MSGPACK_PP_IF(p(167, s), MSGPACK_PP_WHILE_167, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(167, s)) # define MSGPACK_PP_WHILE_167(p, o, s) MSGPACK_PP_IF(p(168, s), MSGPACK_PP_WHILE_168, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(168, s)) # define MSGPACK_PP_WHILE_168(p, o, s) MSGPACK_PP_IF(p(169, s), MSGPACK_PP_WHILE_169, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(169, s)) # define MSGPACK_PP_WHILE_169(p, o, s) MSGPACK_PP_IF(p(170, s), MSGPACK_PP_WHILE_170, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(170, s)) # define MSGPACK_PP_WHILE_170(p, o, s) MSGPACK_PP_IF(p(171, s), MSGPACK_PP_WHILE_171, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(171, s)) # define MSGPACK_PP_WHILE_171(p, o, s) MSGPACK_PP_IF(p(172, s), MSGPACK_PP_WHILE_172, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(172, s)) # define MSGPACK_PP_WHILE_172(p, o, s) MSGPACK_PP_IF(p(173, s), MSGPACK_PP_WHILE_173, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(173, s)) # define MSGPACK_PP_WHILE_173(p, o, s) MSGPACK_PP_IF(p(174, s), MSGPACK_PP_WHILE_174, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(174, s)) # define MSGPACK_PP_WHILE_174(p, o, s) MSGPACK_PP_IF(p(175, s), MSGPACK_PP_WHILE_175, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(175, s)) # define MSGPACK_PP_WHILE_175(p, o, s) MSGPACK_PP_IF(p(176, s), MSGPACK_PP_WHILE_176, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(176, s)) # define MSGPACK_PP_WHILE_176(p, o, s) MSGPACK_PP_IF(p(177, s), MSGPACK_PP_WHILE_177, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(177, s)) # define MSGPACK_PP_WHILE_177(p, o, s) MSGPACK_PP_IF(p(178, s), MSGPACK_PP_WHILE_178, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(178, s)) # define MSGPACK_PP_WHILE_178(p, o, s) MSGPACK_PP_IF(p(179, s), MSGPACK_PP_WHILE_179, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(179, s)) # define MSGPACK_PP_WHILE_179(p, o, s) MSGPACK_PP_IF(p(180, s), MSGPACK_PP_WHILE_180, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(180, s)) # define MSGPACK_PP_WHILE_180(p, o, s) MSGPACK_PP_IF(p(181, s), MSGPACK_PP_WHILE_181, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(181, s)) # define MSGPACK_PP_WHILE_181(p, o, s) MSGPACK_PP_IF(p(182, s), MSGPACK_PP_WHILE_182, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(182, s)) # define MSGPACK_PP_WHILE_182(p, o, s) MSGPACK_PP_IF(p(183, s), MSGPACK_PP_WHILE_183, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(183, s)) # define MSGPACK_PP_WHILE_183(p, o, s) MSGPACK_PP_IF(p(184, s), MSGPACK_PP_WHILE_184, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(184, s)) # define MSGPACK_PP_WHILE_184(p, o, s) MSGPACK_PP_IF(p(185, s), MSGPACK_PP_WHILE_185, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(185, s)) # define MSGPACK_PP_WHILE_185(p, o, s) MSGPACK_PP_IF(p(186, s), MSGPACK_PP_WHILE_186, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(186, s)) # define MSGPACK_PP_WHILE_186(p, o, s) MSGPACK_PP_IF(p(187, s), MSGPACK_PP_WHILE_187, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(187, s)) # define MSGPACK_PP_WHILE_187(p, o, s) MSGPACK_PP_IF(p(188, s), MSGPACK_PP_WHILE_188, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(188, s)) # define MSGPACK_PP_WHILE_188(p, o, s) MSGPACK_PP_IF(p(189, s), MSGPACK_PP_WHILE_189, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(189, s)) # define MSGPACK_PP_WHILE_189(p, o, s) MSGPACK_PP_IF(p(190, s), MSGPACK_PP_WHILE_190, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(190, s)) # define MSGPACK_PP_WHILE_190(p, o, s) MSGPACK_PP_IF(p(191, s), MSGPACK_PP_WHILE_191, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(191, s)) # define MSGPACK_PP_WHILE_191(p, o, s) MSGPACK_PP_IF(p(192, s), MSGPACK_PP_WHILE_192, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(192, s)) # define MSGPACK_PP_WHILE_192(p, o, s) MSGPACK_PP_IF(p(193, s), MSGPACK_PP_WHILE_193, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(193, s)) # define MSGPACK_PP_WHILE_193(p, o, s) MSGPACK_PP_IF(p(194, s), MSGPACK_PP_WHILE_194, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(194, s)) # define MSGPACK_PP_WHILE_194(p, o, s) MSGPACK_PP_IF(p(195, s), MSGPACK_PP_WHILE_195, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(195, s)) # define MSGPACK_PP_WHILE_195(p, o, s) MSGPACK_PP_IF(p(196, s), MSGPACK_PP_WHILE_196, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(196, s)) # define MSGPACK_PP_WHILE_196(p, o, s) MSGPACK_PP_IF(p(197, s), MSGPACK_PP_WHILE_197, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(197, s)) # define MSGPACK_PP_WHILE_197(p, o, s) MSGPACK_PP_IF(p(198, s), MSGPACK_PP_WHILE_198, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(198, s)) # define MSGPACK_PP_WHILE_198(p, o, s) MSGPACK_PP_IF(p(199, s), MSGPACK_PP_WHILE_199, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(199, s)) # define MSGPACK_PP_WHILE_199(p, o, s) MSGPACK_PP_IF(p(200, s), MSGPACK_PP_WHILE_200, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(200, s)) # define MSGPACK_PP_WHILE_200(p, o, s) MSGPACK_PP_IF(p(201, s), MSGPACK_PP_WHILE_201, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(201, s)) # define MSGPACK_PP_WHILE_201(p, o, s) MSGPACK_PP_IF(p(202, s), MSGPACK_PP_WHILE_202, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(202, s)) # define MSGPACK_PP_WHILE_202(p, o, s) MSGPACK_PP_IF(p(203, s), MSGPACK_PP_WHILE_203, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(203, s)) # define MSGPACK_PP_WHILE_203(p, o, s) MSGPACK_PP_IF(p(204, s), MSGPACK_PP_WHILE_204, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(204, s)) # define MSGPACK_PP_WHILE_204(p, o, s) MSGPACK_PP_IF(p(205, s), MSGPACK_PP_WHILE_205, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(205, s)) # define MSGPACK_PP_WHILE_205(p, o, s) MSGPACK_PP_IF(p(206, s), MSGPACK_PP_WHILE_206, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(206, s)) # define MSGPACK_PP_WHILE_206(p, o, s) MSGPACK_PP_IF(p(207, s), MSGPACK_PP_WHILE_207, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(207, s)) # define MSGPACK_PP_WHILE_207(p, o, s) MSGPACK_PP_IF(p(208, s), MSGPACK_PP_WHILE_208, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(208, s)) # define MSGPACK_PP_WHILE_208(p, o, s) MSGPACK_PP_IF(p(209, s), MSGPACK_PP_WHILE_209, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(209, s)) # define MSGPACK_PP_WHILE_209(p, o, s) MSGPACK_PP_IF(p(210, s), MSGPACK_PP_WHILE_210, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(210, s)) # define MSGPACK_PP_WHILE_210(p, o, s) MSGPACK_PP_IF(p(211, s), MSGPACK_PP_WHILE_211, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(211, s)) # define MSGPACK_PP_WHILE_211(p, o, s) MSGPACK_PP_IF(p(212, s), MSGPACK_PP_WHILE_212, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(212, s)) # define MSGPACK_PP_WHILE_212(p, o, s) MSGPACK_PP_IF(p(213, s), MSGPACK_PP_WHILE_213, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(213, s)) # define MSGPACK_PP_WHILE_213(p, o, s) MSGPACK_PP_IF(p(214, s), MSGPACK_PP_WHILE_214, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(214, s)) # define MSGPACK_PP_WHILE_214(p, o, s) MSGPACK_PP_IF(p(215, s), MSGPACK_PP_WHILE_215, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(215, s)) # define MSGPACK_PP_WHILE_215(p, o, s) MSGPACK_PP_IF(p(216, s), MSGPACK_PP_WHILE_216, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(216, s)) # define MSGPACK_PP_WHILE_216(p, o, s) MSGPACK_PP_IF(p(217, s), MSGPACK_PP_WHILE_217, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(217, s)) # define MSGPACK_PP_WHILE_217(p, o, s) MSGPACK_PP_IF(p(218, s), MSGPACK_PP_WHILE_218, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(218, s)) # define MSGPACK_PP_WHILE_218(p, o, s) MSGPACK_PP_IF(p(219, s), MSGPACK_PP_WHILE_219, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(219, s)) # define MSGPACK_PP_WHILE_219(p, o, s) MSGPACK_PP_IF(p(220, s), MSGPACK_PP_WHILE_220, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(220, s)) # define MSGPACK_PP_WHILE_220(p, o, s) MSGPACK_PP_IF(p(221, s), MSGPACK_PP_WHILE_221, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(221, s)) # define MSGPACK_PP_WHILE_221(p, o, s) MSGPACK_PP_IF(p(222, s), MSGPACK_PP_WHILE_222, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(222, s)) # define MSGPACK_PP_WHILE_222(p, o, s) MSGPACK_PP_IF(p(223, s), MSGPACK_PP_WHILE_223, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(223, s)) # define MSGPACK_PP_WHILE_223(p, o, s) MSGPACK_PP_IF(p(224, s), MSGPACK_PP_WHILE_224, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(224, s)) # define MSGPACK_PP_WHILE_224(p, o, s) MSGPACK_PP_IF(p(225, s), MSGPACK_PP_WHILE_225, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(225, s)) # define MSGPACK_PP_WHILE_225(p, o, s) MSGPACK_PP_IF(p(226, s), MSGPACK_PP_WHILE_226, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(226, s)) # define MSGPACK_PP_WHILE_226(p, o, s) MSGPACK_PP_IF(p(227, s), MSGPACK_PP_WHILE_227, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(227, s)) # define MSGPACK_PP_WHILE_227(p, o, s) MSGPACK_PP_IF(p(228, s), MSGPACK_PP_WHILE_228, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(228, s)) # define MSGPACK_PP_WHILE_228(p, o, s) MSGPACK_PP_IF(p(229, s), MSGPACK_PP_WHILE_229, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(229, s)) # define MSGPACK_PP_WHILE_229(p, o, s) MSGPACK_PP_IF(p(230, s), MSGPACK_PP_WHILE_230, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(230, s)) # define MSGPACK_PP_WHILE_230(p, o, s) MSGPACK_PP_IF(p(231, s), MSGPACK_PP_WHILE_231, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(231, s)) # define MSGPACK_PP_WHILE_231(p, o, s) MSGPACK_PP_IF(p(232, s), MSGPACK_PP_WHILE_232, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(232, s)) # define MSGPACK_PP_WHILE_232(p, o, s) MSGPACK_PP_IF(p(233, s), MSGPACK_PP_WHILE_233, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(233, s)) # define MSGPACK_PP_WHILE_233(p, o, s) MSGPACK_PP_IF(p(234, s), MSGPACK_PP_WHILE_234, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(234, s)) # define MSGPACK_PP_WHILE_234(p, o, s) MSGPACK_PP_IF(p(235, s), MSGPACK_PP_WHILE_235, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(235, s)) # define MSGPACK_PP_WHILE_235(p, o, s) MSGPACK_PP_IF(p(236, s), MSGPACK_PP_WHILE_236, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(236, s)) # define MSGPACK_PP_WHILE_236(p, o, s) MSGPACK_PP_IF(p(237, s), MSGPACK_PP_WHILE_237, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(237, s)) # define MSGPACK_PP_WHILE_237(p, o, s) MSGPACK_PP_IF(p(238, s), MSGPACK_PP_WHILE_238, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(238, s)) # define MSGPACK_PP_WHILE_238(p, o, s) MSGPACK_PP_IF(p(239, s), MSGPACK_PP_WHILE_239, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(239, s)) # define MSGPACK_PP_WHILE_239(p, o, s) MSGPACK_PP_IF(p(240, s), MSGPACK_PP_WHILE_240, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(240, s)) # define MSGPACK_PP_WHILE_240(p, o, s) MSGPACK_PP_IF(p(241, s), MSGPACK_PP_WHILE_241, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(241, s)) # define MSGPACK_PP_WHILE_241(p, o, s) MSGPACK_PP_IF(p(242, s), MSGPACK_PP_WHILE_242, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(242, s)) # define MSGPACK_PP_WHILE_242(p, o, s) MSGPACK_PP_IF(p(243, s), MSGPACK_PP_WHILE_243, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(243, s)) # define MSGPACK_PP_WHILE_243(p, o, s) MSGPACK_PP_IF(p(244, s), MSGPACK_PP_WHILE_244, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(244, s)) # define MSGPACK_PP_WHILE_244(p, o, s) MSGPACK_PP_IF(p(245, s), MSGPACK_PP_WHILE_245, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(245, s)) # define MSGPACK_PP_WHILE_245(p, o, s) MSGPACK_PP_IF(p(246, s), MSGPACK_PP_WHILE_246, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(246, s)) # define MSGPACK_PP_WHILE_246(p, o, s) MSGPACK_PP_IF(p(247, s), MSGPACK_PP_WHILE_247, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(247, s)) # define MSGPACK_PP_WHILE_247(p, o, s) MSGPACK_PP_IF(p(248, s), MSGPACK_PP_WHILE_248, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(248, s)) # define MSGPACK_PP_WHILE_248(p, o, s) MSGPACK_PP_IF(p(249, s), MSGPACK_PP_WHILE_249, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(249, s)) # define MSGPACK_PP_WHILE_249(p, o, s) MSGPACK_PP_IF(p(250, s), MSGPACK_PP_WHILE_250, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(250, s)) # define MSGPACK_PP_WHILE_250(p, o, s) MSGPACK_PP_IF(p(251, s), MSGPACK_PP_WHILE_251, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(251, s)) # define MSGPACK_PP_WHILE_251(p, o, s) MSGPACK_PP_IF(p(252, s), MSGPACK_PP_WHILE_252, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(252, s)) # define MSGPACK_PP_WHILE_252(p, o, s) MSGPACK_PP_IF(p(253, s), MSGPACK_PP_WHILE_253, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(253, s)) # define MSGPACK_PP_WHILE_253(p, o, s) MSGPACK_PP_IF(p(254, s), MSGPACK_PP_WHILE_254, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(254, s)) # define MSGPACK_PP_WHILE_254(p, o, s) MSGPACK_PP_IF(p(255, s), MSGPACK_PP_WHILE_255, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(255, s)) # define MSGPACK_PP_WHILE_255(p, o, s) MSGPACK_PP_IF(p(256, s), MSGPACK_PP_WHILE_256, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(256, s)) # define MSGPACK_PP_WHILE_256(p, o, s) MSGPACK_PP_IF(p(257, s), MSGPACK_PP_WHILE_257, s MSGPACK_PP_TUPLE_EAT_3)(p, o, o(257, s)) # # endif
33,147
20,554
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/shadow_types.h" #include "ui/base/class_property.h" namespace wm { DEFINE_UI_CLASS_PROPERTY_KEY(int, kShadowElevationKey, kShadowElevationDefault) void SetShadowElevation(aura::Window* window, int elevation) { window->SetProperty(kShadowElevationKey, elevation); } int GetDefaultShadowElevationForWindow(const aura::Window* window) { switch (window->type()) { case aura::client::WINDOW_TYPE_NORMAL: return kShadowElevationInactiveWindow; case aura::client::WINDOW_TYPE_MENU: case aura::client::WINDOW_TYPE_TOOLTIP: return kShadowElevationMenuOrTooltip; default: return kShadowElevationNone; } } int GetShadowElevationConvertDefault(const aura::Window* window) { int elevation = window->GetProperty(kShadowElevationKey); return elevation == kShadowElevationDefault ? GetDefaultShadowElevationForWindow(window) : elevation; } } // namespace wm
1,113
390
/// @author Владимир Керимов #pragma once #include <exception/exception_holder.hpp> #include <data/stacktrace> namespace data { } // sine qua non
163
62
#include "cardencoding.h" #include "sorting_merging.h" #include <cmath> using namespace PBLib; using namespace std; CardEncoding::CardIncData::~CardIncData() { } CardEncoding::CardIncData::CardIncData(vector< Lit >& outlits) : outlits(outlits) {} void CardEncoding::CardIncData::encodeNewGeq(int64_t newGeq, ClauseDatabase& formula, AuxVarManager& auxVars, vector< int32_t > conditionals) { formula.addConditionals(conditionals); if (outlits.size() < newGeq) formula.addUnsat(); else if (newGeq > 0) formula.addClause(outlits[newGeq - 1]); // setting newGeq to true forcing the sum to be at least equal newGeq for (int i = 0; i < conditionals.size(); ++i) formula.getConditionals().pop_back(); } void CardEncoding::CardIncData::encodeNewLeq(int64_t newLeq, ClauseDatabase& formula, AuxVarManager& auxVars, vector< int32_t > conditionals) { formula.addConditionals(conditionals); if (outlits.size() > newLeq) formula.addClause(-outlits[newLeq]); // setting newLeq + 1 to false forcing the sum to be less equal newLeq for (int i = 0; i < conditionals.size(); ++i) formula.getConditionals().pop_back(); } int64_t CardEncoding::encodingValue(const shared_ptr< IncSimplePBConstraint >& pbconstraint) { int n = pbconstraint->getN(); int64_t num_clauses_approx = (n * pow(ceil(log2(n)),2)); return valueFunction(num_clauses_approx, num_clauses_approx); } int64_t CardEncoding::encodingValue(const SimplePBConstraint& pbconstraint) { int n = pbconstraint.getN(); int64_t num_clauses_approx = (n * pow(ceil(log2(n)),2)); if (num_clauses_approx > config->MAX_CLAUSES_PER_CONSTRAINT) return valueFunction(num_clauses_approx, num_clauses_approx); CountingClauseDatabase formula(config); AuxVarManager auxvars(1000000); encode(pbconstraint, formula, auxvars); return valueFunction(formula.getNumberOfClauses(), auxvars.getBiggestReturnedAuxVar() - 1000000); } void CardEncoding::encode(const shared_ptr<IncSimplePBConstraint> & pbconstraint, ClauseDatabase& formula, AuxVarManager& auxvars) { if (config->print_used_encodings) cout << "c encode incremental with card" << endl; vector<int32_t> input, output; int64_t leq = pbconstraint->getLeq(); for (auto l : pbconstraint->getWeightedLiterals()) input.push_back(l.lit); if (pbconstraint->getComparator() == BOTH) Sorting::sort(leq+1, input, formula, auxvars, output, Sorting::BOTH); else Sorting::sort(leq+1, input, formula, auxvars, output, Sorting::INPUT_TO_OUTPUT); formula.addConditionals(pbconstraint->getConditionals()); if (output.size() > leq) // if not, the constraint is always satisfiable (initially) formula.addClause(-output[leq]); // setting k + 1 to false forcing the sum to be less equal k if (pbconstraint->getComparator() == BOTH) { if (output.size() < pbconstraint->getGeq()) formula.addUnsat(); else for (int i = 0; i < pbconstraint->getGeq(); ++i) formula.addClause(output[i]); } for (int i = 0; i < pbconstraint->getConditionals().size(); ++i) formula.getConditionals().pop_back(); pbconstraint->setIncrementalData(make_shared<CardIncData>(output)); } void CardEncoding::encode(const SimplePBConstraint& pbconstraint, ClauseDatabase & formula, AuxVarManager & auxvars) { if (config->print_used_encodings) cout << "c encode with card" << endl; vector<int32_t> input, output; int64_t leq = pbconstraint.getLeq(); if (pbconstraint.getComparator() == LEQ && leq > (pbconstraint.getN() / 2) ) { int64_t geq = pbconstraint.getN() - leq; // we treat this as geq constraint for (auto l : pbconstraint.getWeightedLiterals()) input.push_back(-l.lit); // negate everything Sorting::sort(geq, input, formula, auxvars, output, Sorting::OUTPUT_TO_INPUT); formula.addConditionals(pbconstraint.getConditionals()); for (int i = 0; i < geq; ++i) formula.addClause(output[i]); for (int i = 0; i < pbconstraint.getConditionals().size(); ++i) formula.getConditionals().pop_back(); return; } for (auto l : pbconstraint.getWeightedLiterals()) input.push_back(l.lit); if (pbconstraint.getComparator() == BOTH) Sorting::sort(leq+1, input, formula, auxvars, output, Sorting::BOTH); else Sorting::sort(leq+1, input, formula, auxvars, output, Sorting::INPUT_TO_OUTPUT); assert(output.size() > leq); formula.addConditionals(pbconstraint.getConditionals()); formula.addClause(-output[leq]); // setting k + 1 to false forcing the sum to be less equal k if (pbconstraint.getComparator() == BOTH) { for (int i = 0; i < pbconstraint.getGeq(); ++i) formula.addClause(output[i]); } for (int i = 0; i < pbconstraint.getConditionals().size(); ++i) formula.getConditionals().pop_back(); } CardEncoding::CardEncoding(PBConfig& config) : Encoder(config) { } CardEncoding::~CardEncoding() { }
5,010
1,812
// GAMBIT: Global and Modular BSM Inference Tool // ********************************************* /// \file /// /// Square grid sampler. /// /// ********************************************* /// /// Authors (add name and date if you modify): // /// \author Gregory Martinez /// (gregory.david.martinez@gmail.com) /// \date 2013 August /// /// ********************************************* #ifdef WITH_MPI #include "mpi.h" #endif #include <vector> #include <string> #include <cmath> #include <iostream> #include <map> #include <sstream> #include "gambit/ScannerBit/scanner_plugin.hpp" scanner_plugin(square_grid, version(1, 0, 0)) { int plugin_main() { int rank, numtasks; int N = std::abs(get_inifile_value<int>("grid_pts", 2)); if (N == 0) N = 1; int ma = get_dimension(); #ifdef WITH_MPI MPI_Comm_size(MPI_COMM_WORLD, &numtasks); MPI_Comm_rank(MPI_COMM_WORLD, &rank); #else numtasks = 1; rank = 0; #endif like_ptr LogLike = get_purpose(get_inifile_value<std::string>("like")); std::vector<double> vec(ma, 0.0); for (int i = rank, end = std::pow(N, ma); i < end; i+=numtasks) { int n = i; for (int j = 0; j < ma; j++) { if (N == 1) vec[j] = 0.5; else vec[j] = double(n%N)/double(N-1); n /= N; } LogLike(vec); } return 0; } }
1,558
547
/* * Blocks.cpp * RVO2 Library * * Copyright 2008 University of North Carolina at Chapel Hill * * 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. * * Please send all bug reports to <geom@cs.unc.edu>. * * The authors may be contacted via: * * Jur van den Berg, Stephen J. Guy, Jamie Snape, Ming C. Lin, Dinesh Manocha * Dept. of Computer Science * 201 S. Columbia St. * Frederick P. Brooks, Jr. Computer Science Bldg. * Chapel Hill, N.C. 27599-3175 * United States of America * * <http://gamma.cs.unc.edu/RVO2/> */ /* * Example file showing a demo with 100 agents split in four groups initially * positioned in four corners of the environment. Each agent attempts to move to * other side of the environment through a narrow passage generated by four * obstacles. There is no roadmap to guide the agents around the obstacles. */ #ifndef RVO_OUTPUT_TIME_AND_POSITIONS #define RVO_OUTPUT_TIME_AND_POSITIONS 1 #endif #ifndef RVO_SEED_RANDOM_NUMBER_GENERATOR #define RVO_SEED_RANDOM_NUMBER_GENERATOR 1 #endif #include <cmath> #include <cstdlib> #include <vector> #if RVO_OUTPUT_TIME_AND_POSITIONS #include <iostream> #endif #if RVO_SEED_RANDOM_NUMBER_GENERATOR #include <ctime> #endif #if _OPENMP #include <omp.h> #endif #include <RVO.h> #ifndef M_PI const float M_PI = 3.14159265358979323846f; #endif #include <fstream> #include <sstream> int curGoalId[12] = {1,1,1,1,1,1,1,1,1,1,1,1}; std::vector<std::vector<RVO::Vector2>> goalsList; std::vector<RVO::Vector2> goals; std::vector<std::vector<RVO::Vector2>> trajs; void initGoalsList() { std::string filename = "/home/malintha/Desktop/scp/rvo2-2.0.2/RVO2/examples/goals/goalsList.txt"; std::ifstream infile(filename); int x, y, z; std::vector<RVO::Vector2> goals_t; while(infile >> x >> y >> z) { if (x == 0 && y == 0 && z == 0) { goalsList.push_back(goals_t); goals_t.clear(); } else { RVO::Vector2 v(x,y); goals_t.push_back(v); } } } void setupScenario(RVO::RVOSimulator *sim) { #if RVO_SEED_RANDOM_NUMBER_GENERATOR std::srand(static_cast<unsigned int>(std::time(NULL))); #endif sim->setTimeStep(0.01f); sim->setAgentDefaults(4.0f, 5, 5.0f, 5.0f, 0.3f, 3.0f); // goals list initGoalsList(); std::cout<<"## goalsVec: "<<goalsList.size()<<" "<<goalsList[0].size()<<std::endl; /* * Add robots */ sim->addAgent(RVO::Vector2(4,8)); goals.push_back(goalsList[0][1]); sim->addAgent(RVO::Vector2(5,8)); goals.push_back(goalsList[1][1]); sim->addAgent(RVO::Vector2(6,8)); goals.push_back(goalsList[2][1]); sim->addAgent(RVO::Vector2(4,7)); goals.push_back(goalsList[3][1]); sim->addAgent(RVO::Vector2(5,7)); goals.push_back(goalsList[4][1]); sim->addAgent(RVO::Vector2(6,7)); goals.push_back(goalsList[5][1]); // sim->addAgent(RVO::Vector2(4,6)); // goals.push_back(goalsList[6][1]); // sim->addAgent(RVO::Vector2(5,6)); // goals.push_back(goalsList[7][1]); // sim->addAgent(RVO::Vector2(6,6)); // goals.push_back(goalsList[8][1]); // sim->addAgent(RVO::Vector2(4,5)); // goals.push_back(goalsList[9][1]); // sim->addAgent(RVO::Vector2(5,5)); // goals.push_back(goalsList[10][1]); // sim->addAgent(RVO::Vector2(6,5)); // goals.push_back(goalsList[11][1]); // init empty trajs for(int i=0;i<6;i++) { std::vector<RVO::Vector2> traj; trajs.push_back(traj); } /* * Add (polygonal) obstacles, specifying their vertices in counterclockwise * order. */ std::vector<RVO::Vector2> obstacle1, obstacle2, obstacle3, obstacle4; // obstacle1.push_back(RVO::Vector2(-10.0f, 40.0f)); // obstacle1.push_back(RVO::Vector2(-40.0f, 40.0f)); // obstacle1.push_back(RVO::Vector2(-40.0f, 10.0f)); // obstacle1.push_back(RVO::Vector2(-10.0f, 10.0f)); // obstacle2.push_back(RVO::Vector2(10.0f, 40.0f)); // obstacle2.push_back(RVO::Vector2(10.0f, 10.0f)); // obstacle2.push_back(RVO::Vector2(40.0f, 10.0f)); // obstacle2.push_back(RVO::Vector2(40.0f, 40.0f)); // obstacle3.push_back(RVO::Vector2(10.0f, -40.0f)); // obstacle3.push_back(RVO::Vector2(40.0f, -40.0f)); // obstacle3.push_back(RVO::Vector2(40.0f, -10.0f)); // obstacle3.push_back(RVO::Vector2(10.0f, -10.0f)); // obstacle4.push_back(RVO::Vector2(-10.0f, -40.0f)); // obstacle4.push_back(RVO::Vector2(-10.0f, -10.0f)); // obstacle4.push_back(RVO::Vector2(-40.0f, -10.0f)); // obstacle4.push_back(RVO::Vector2(-40.0f, -40.0f)); // sim->addObstacle(obstacle1); // sim->addObstacle(obstacle2); // sim->addObstacle(obstacle3); // sim->addObstacle(obstacle4); /* Process the obstacles so that they are accounted for in the simulation. */ // sim->processObstacles(); } #if RVO_OUTPUT_TIME_AND_POSITIONS void updateVisualization(RVO::RVOSimulator *sim) { /* Output the current global time. */ std::cout << sim->getGlobalTime(); /* Output the current position of all the agents. */ for (size_t i = 0; i < sim->getNumAgents(); ++i) { std::cout << " " << sim->getAgentPosition(i); trajs[i].push_back(sim->getAgentPosition(i)); } std::cout << std::endl; } #endif void setPreferredVelocities(RVO::RVOSimulator *sim) { /* * Set the preferred velocity to be a vector of unit magnitude (speed) in the * direction of the goal. */ #ifdef _OPENMP #pragma omp parallel for #endif for (int i = 0; i < static_cast<int>(sim->getNumAgents()); ++i) { RVO::Vector2 goalVector = goals[i] - sim->getAgentPosition(i); if (std::sqrt(RVO::absSq(goalVector)) > 0.5f) { goalVector = RVO::normalize(goalVector); } sim->setAgentPrefVelocity(i, goalVector); /* * Perturb a little to avoid deadlocks due to perfect symmetry. */ float angle = std::rand() * 2.0f * M_PI / RAND_MAX; float dist = std::rand() * 0.0001f / RAND_MAX; sim->setAgentPrefVelocity(i, sim->getAgentPrefVelocity(i) + dist * RVO::Vector2(std::cos(angle), std::sin(angle))); } } /* Check if all agents have reached their goals. */ bool reachedGoal(RVO::RVOSimulator *sim) { bool reached = true; int nGoals = 5; for (size_t i = 0; i < sim->getNumAgents(); ++i) { if (std::sqrt(RVO::absSq(sim->getAgentPosition(i) - goals[i]) > 0.05)) { reached = reached * false; } else { int curGoal = curGoalId[i]; if(curGoalId[i] < nGoals-1) { goals[i] = goalsList[i][++curGoal]; curGoalId[i] = curGoal; // std::cout<<"## curr: "<<sim->getAgentPosition(i)<<" "<<goals[i]<<i<<std::endl; } else if(curGoal == nGoals - 1) { // std::cout<<"reached goal"<<std::endl; reached = reached * true; } } } return reached; } void storeTrajs() { for(int i=0; i<trajs.size();i++) { std::cout << "Writing trajs "<<i << std::endl; std::stringstream ss; ss << "/home/malintha/Desktop/scp/rvo2-2.0.2/RVO2/examples/trajectories/pos_" << i << ".txt"; std::ofstream ofs(ss.str(), std::ofstream::trunc); for(int j=0;j<trajs[i].size();j++) { ofs << trajs[i][j].x() << " " <<trajs[i][j].y() << " " << "4"<<std::endl; } ofs.close(); } } int main() { /* Create a new simulator instance. */ RVO::RVOSimulator *sim = new RVO::RVOSimulator(); // /* Set up the scenario. */ setupScenario(sim); /* Perform (and manipulate) the simulation. */ do { #if RVO_OUTPUT_TIME_AND_POSITIONS updateVisualization(sim); #endif setPreferredVelocities(sim); sim->doStep(); } while (!reachedGoal(sim)); storeTrajs(); delete sim; return 0; }
7,830
3,425
// ***************************************************************************************** // // File description: // // Author: Joao Costa // Purpose: Defines a DOM user handler to cleanup user added node information // // ***************************************************************************************** #ifndef OSAPI_XML_HANDLER_HH_ #define OSAPI_XML_HANDLER_HH_ // ***************************************************************************************** // // Section: Import headers // // ***************************************************************************************** // Import Xerces C++ headers #include "xercesc/dom/DOM.hpp" // ***************************************************************************************** // // Section: API declaration // // ***************************************************************************************** namespace osapi { namespace xml { class dataHandler : xercesc::DOMUserDataHandler { public: /// @brief class destructor dataHandler() {} void handle( DOMOperationType operation, const XMLCh * const key, void * data, const xercesc::DOMNode * src, xercesc::DOMNode * dest ); }; } // End of namespace "xml" } // End of namespace "osapi" #endif /* OSAPI_XML_HANDLER_HH_ */
1,278
325
// Copyright (c) Csaba Molnar & Daniel Butum. All Rights Reserved. #include "SoCharacterSheet.h" #include "SoIMortalTypes.h" #include "Basic/Helpers/SoStaticHelper.h" #include "SaveFiles/SoWorldState.h" //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Sets default values for this component's properties USoCharacterSheet::USoCharacterSheet() { // Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features // off to improve performance if you don't need them. // bWantsBeginPlay = false; PrimaryComponentTick.bCanEverTick = false; bWantsInitializeComponent = true; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void USoCharacterSheet::InitializeComponent() { Super::InitializeComponent(); CurrentHealthPoints = GetMaxHealth(); } #if WITH_EDITOR //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void USoCharacterSheet::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) { Super::PostEditChangeProperty(PropertyChangedEvent); CurrentHealthPoints = MaxHealthPoints; } #endif //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void USoCharacterSheet::RestoreHealth() { CurrentHealthPoints = GetMaxHealth(); OnHealthChanged.Broadcast(CurrentHealthPoints, CurrentHealthPoints); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void USoCharacterSheet::SetMaxHealth(float NewValue, bool bModifyCurrent) { MaxHealthPoints = NewValue; const float Max = GetMaxHealth(); if (bModifyCurrent) CurrentHealthPoints = Max; OnHealthChanged.Broadcast(CurrentHealthPoints, Max); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool USoCharacterSheet::SetHealth(float NewValue) { const float Max = GetMaxHealth(); CurrentHealthPoints = FMath::Clamp(NewValue, 0.0f, Max); OnHealthChanged.Broadcast(CurrentHealthPoints, Max); return CurrentHealthPoints > 0.0f; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void USoCharacterSheet::IncreaseHealth(float Delta) { const float Max = GetMaxHealth(); CurrentHealthPoints = FMath::Clamp(CurrentHealthPoints + Delta, 0.0f, Max); OnHealthChanged.Broadcast(CurrentHealthPoints, Max); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void USoCharacterSheet::AddBonusHealth(const FSoDmg& BonusHealthAmount) { BonusHealth += BonusHealthAmount; OnBonusHealthChanged.Broadcast(BonusHealth); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void USoCharacterSheet::ClearBonusHealth() { BonusHealth.SetToZero(); OnBonusHealthChanged.Broadcast(BonusHealth); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// FSoDmg USoCharacterSheet::AddRes(const FSoDmg& Res) { FSoDmg Applied = Res; if (Resistance.Physical + Res.Physical > 1.0f) Applied.Physical = 1.0f - Resistance.Physical; if (Resistance.Magical + Res.Magical > 1.0f) Applied.Magical = 1.0f - Resistance.Magical; Resistance.Physical = FMath::Clamp(Resistance.Physical + Res.Physical, 0.0f, 1.0f); Resistance.Magical = FMath::Clamp(Resistance.Magical + Res.Magical, 0.0f, 1.0f); return Applied; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void USoCharacterSheet::RemoveRes(const FSoDmg& Res) { Resistance.Physical = FMath::Clamp(Resistance.Physical - Res.Physical, 0.0f, 1.0f); Resistance.Magical = FMath::Clamp(Resistance.Magical - Res.Magical, 0.0f, 1.0f); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool USoCharacterSheet::ApplyDmg(const FSoDmg& Damage) { FSoDmg AppliedDmg = Damage * (Resistance.OneMinus()); const float Sum = AppliedDmg.Sum(); if (Sum > KINDA_SMALL_NUMBER) { OnDmg.Broadcast(AppliedDmg); bool bBonusBlocked = false; if (AppliedDmg.HasPhysical() && BonusHealth.HasPhysical()) { const float PreBonusHealth = BonusHealth.Physical; BonusHealth.Physical = FMath::Max(BonusHealth.Physical - AppliedDmg.Physical, 0.0f); AppliedDmg.Physical = FMath::Max(AppliedDmg.Physical - PreBonusHealth, 0.0f); bBonusBlocked = true; } if (AppliedDmg.HasMagical() && BonusHealth.HasMagical()) { const float PreBonusHealth = BonusHealth.Magical; BonusHealth.Magical = FMath::Max(BonusHealth.Magical - AppliedDmg.Magical, 0.0f); AppliedDmg.Magical = FMath::Max(AppliedDmg.Magical - PreBonusHealth, 0.0f); bBonusBlocked = true; } if (bBonusBlocked) OnBonusHealthChanged.Broadcast(BonusHealth); OnDmgApplied.Broadcast(AppliedDmg); const float PostBonusSum = AppliedDmg.Sum(); if (PostBonusSum > KINDA_SMALL_NUMBER) { const bool bAlive = CurrentHealthPoints > PostBonusSum; CurrentHealthPoints = FMath::Clamp(CurrentHealthPoints - PostBonusSum, 0.0f, GetMaxHealth()); if (!bAlive) { OnPreDeath.Broadcast(); return CurrentHealthPoints > KINDA_SMALL_NUMBER; } } } return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// FSoDmg USoCharacterSheet::GetReducedDmg(const FSoDmg& Damage) { return Damage * (Resistance.OneMinus()); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float USoCharacterSheet::GetMaxHealth() const { switch (FSoWorldState::Get().GetGameDifficulty()) { case ESoDifficulty::Sane: return MaxHealthPoints * SaneHPMultiplier; case ESoDifficulty::Insane: return MaxHealthPoints * InsaneHPMultiplier; case ESoDifficulty::Intended: default: return MaxHealthPoints; } }
6,245
1,953
/** * @file BayesianBlocks.cxx * @brief Implementation of BB algorithm for event, binned and point * measurement data. * * @author J. Chiang * * $Header: /nfs/slac/g/glast/ground/cvs/BayesianBlocks/src/BayesianBlocks.cxx,v 1.1.1.1 2011/09/03 00:55:59 jchiang Exp $ */ #include <cmath> #include <iostream> #include <numeric> #include <stdexcept> #include "BayesianBlocks/BayesianBlocks.h" namespace { void computePartialSums(const std::vector<double> & x, std::deque<double> & partialSums) { partialSums.resize(x.size()); std::partial_sum(x.begin(), x.end(), partialSums.begin()); partialSums.push_front(0); } } BayesianBlocks:: BayesianBlocks(const std::vector<double> & arrival_times, double tstart, double tstop) : m_point_mode(false), m_binned(false), m_tstart(tstart), m_tstop(tstop), m_cellSizes(arrival_times.size(), 0), m_cellContent(arrival_times.size(), 1.), m_blockCost(new BlockCostEvent(*this)) { generateCells(arrival_times); } BayesianBlocks:: BayesianBlocks(double tstart, const std::vector<double> & bin_content, const std::vector<double> & bin_sizes) : m_point_mode(false), m_binned(true), m_tstart(tstart), m_cellSizes(bin_sizes), m_cellContent(bin_content), m_blockCost(new BlockCostEvent(*this)) { cellPartialSums(); } BayesianBlocks:: BayesianBlocks(const std::vector<double> & xx, const std::vector<double> & yy, const std::vector<double> & dy) : m_point_mode(true), m_binned(false), m_tstart((3*xx[0] - xx[1])/2.), m_tstop((3*xx[xx.size()-1] - xx[xx.size()-2])/2.), m_cellSizes(xx.size(), 0), m_cellContent(yy), m_cellErrors(dy), m_blockCost(new BlockCostPoint(*this)) { generateCells(xx); } void BayesianBlocks:: globalOpt(double ncp_prior, std::vector<double> & xvals, std::vector<double> & yvals) const { std::vector<double> opt; std::vector<size_t> last; opt.push_back(blockCost(0, 0) - ncp_prior); last.push_back(0); size_t npts(m_cellContent.size()); for (size_t nn(1); nn < npts; nn++) { double max_opt(blockCost(0, nn) - ncp_prior); size_t jmax(0); for (size_t j(1); j < nn+1; j++) { double my_opt(opt[j-1] + blockCost(j, nn) - ncp_prior); if (my_opt > max_opt) { max_opt = my_opt; jmax = j; } } opt.push_back(max_opt); last.push_back(jmax); } std::deque<size_t> changePoints; size_t indx(last.back()); while (indx > 0) { changePoints.push_front(indx); indx = last[indx-1]; } changePoints.push_front(0); changePoints.push_back(npts); // for (size_t i(0); i < changePoints.size(); i++) { // std::cout << changePoints[i] << " "; // } // std::cout << std::endl; lightCurve(changePoints, xvals, yvals); } double BayesianBlocks::blockSize(size_t imin, size_t imax) const { return m_cellSizePartialSums[imax+1] - m_cellSizePartialSums[imin]; } double BayesianBlocks::blockContent(size_t imin, size_t imax) const { return m_cellContentPartialSums[imax+1] - m_cellContentPartialSums[imin]; } void BayesianBlocks::setCellSizes(const std::vector<double> & cellSizes) { if (cellSizes.size() != m_cellSizes.size()) { throw std::runtime_error("The number of scale factors does not equal " "the number of cells."); } m_cellSizes = cellSizes; ::computePartialSums(m_cellSizes, m_cellSizePartialSums); } void BayesianBlocks::lightCurve(const std::deque<size_t> & changePoints, std::vector<double> & xx, std::vector<double> & yy) const { xx.clear(); yy.clear(); for (size_t i(0); i < changePoints.size() - 1; i++) { size_t imin(changePoints[i]); size_t imax(changePoints[i+1]); xx.push_back(m_tstart + m_unscaledCellSizePartialSums[imin]); xx.push_back(m_tstart + m_unscaledCellSizePartialSums[imax]); double yval(0); if (m_point_mode) { std::vector<double> weights; weights.reserve(imax - imin); double sum_wts(0); for (size_t ii(imin); ii < imax; ii++) { weights.push_back(1./m_cellErrors[ii]/m_cellErrors[ii]); sum_wts += weights.back(); yval += weights.back()*m_cellContent[ii]; } yval /= sum_wts; } else { double unscaled_block_size = m_unscaledCellSizePartialSums[imax] - m_unscaledCellSizePartialSums[imin]; yval = blockContent(imin, imax-1)/unscaled_block_size; } yy.push_back(yval); yy.push_back(yval); } } void BayesianBlocks:: generateCells(const std::vector<double> & arrival_times) { size_t npts(arrival_times.size()); m_cellSizes[0] = (arrival_times[1] + arrival_times[0])/2. - m_tstart; for (size_t i(1); i < npts-1; i++) { m_cellSizes[i] = (arrival_times[i+1] - arrival_times[i-1])/2.; } m_cellSizes[npts-1] = m_tstop - (arrival_times[npts-1] + arrival_times[npts-2])/2.; cellPartialSums(); } void BayesianBlocks::cellPartialSums() { ::computePartialSums(m_cellSizes, m_unscaledCellSizePartialSums); ::computePartialSums(m_cellSizes, m_cellSizePartialSums); ::computePartialSums(m_cellContent, m_cellContentPartialSums); } double BayesianBlocks:: BlockCostEvent::operator()(size_t imin, size_t imax) const { double block_size(m_bbObject.blockSize(imin, imax)); double block_content(m_bbObject.blockContent(imin, imax)); if (block_content == 0) { return 0; } double cost = block_content*(std::log(block_content/block_size) - 1.); return cost; } double BayesianBlocks:: BlockCostPoint::operator()(size_t imin, size_t imax) const { std::vector<double> weights; weights.reserve(imax - imin); double sum_wts(0); const std::vector<double> & cellErrors(m_bbObject.cellErrors()); for (size_t i(imin); i < imax+1; i++) { weights.push_back(1./cellErrors[i]/cellErrors[i]); sum_wts += weights.back(); } double sum_wts_yy(0); double sigx2(0); size_t j(0); const std::vector<double> & cellContent(m_bbObject.cellContent()); for (size_t i(imin); i < imax+1; i++, j++) { weights[j] /= sum_wts; sum_wts_yy += weights[j]*cellContent[i]; sigx2 += weights[j]*cellContent[i]*cellContent[i]; } sigx2 -= sum_wts_yy*sum_wts_yy; return -sigx2/2.*sum_wts; } double BayesianBlocks::ncp_prior(double nevents, double fp_frac) { double value = 4. - std::log(fp_frac/(0.0136*std::pow(nevents, 0.478))); return value; }
6,747
2,574
// Copyright (c) 2011 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 "app/sql/connection.h" #include "app/sql/statement.h" #include "app/sql/transaction.h" #include "base/file_util.h" #include "base/memory/scoped_temp_dir.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/sqlite/sqlite3.h" class SQLTransactionTest : public testing::Test { public: SQLTransactionTest() {} void SetUp() { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); ASSERT_TRUE(db_.Open( temp_dir_.path().AppendASCII("SQLTransactionTest.db"))); ASSERT_TRUE(db().Execute("CREATE TABLE foo (a, b)")); } void TearDown() { db_.Close(); } sql::Connection& db() { return db_; } // Returns the number of rows in table "foo". int CountFoo() { sql::Statement count(db().GetUniqueStatement("SELECT count(*) FROM foo")); count.Step(); return count.ColumnInt(0); } private: ScopedTempDir temp_dir_; sql::Connection db_; }; TEST_F(SQLTransactionTest, Commit) { { sql::Transaction t(&db()); EXPECT_FALSE(t.is_open()); EXPECT_TRUE(t.Begin()); EXPECT_TRUE(t.is_open()); EXPECT_TRUE(db().Execute("INSERT INTO foo (a, b) VALUES (1, 2)")); t.Commit(); EXPECT_FALSE(t.is_open()); } EXPECT_EQ(1, CountFoo()); } TEST_F(SQLTransactionTest, Rollback) { // Test some basic initialization, and that rollback runs when you exit the // scope. { sql::Transaction t(&db()); EXPECT_FALSE(t.is_open()); EXPECT_TRUE(t.Begin()); EXPECT_TRUE(t.is_open()); EXPECT_TRUE(db().Execute("INSERT INTO foo (a, b) VALUES (1, 2)")); } // Nothing should have been committed since it was implicitly rolled back. EXPECT_EQ(0, CountFoo()); // Test explicit rollback. sql::Transaction t2(&db()); EXPECT_FALSE(t2.is_open()); EXPECT_TRUE(t2.Begin()); EXPECT_TRUE(db().Execute("INSERT INTO foo (a, b) VALUES (1, 2)")); t2.Rollback(); EXPECT_FALSE(t2.is_open()); // Nothing should have been committed since it was explicitly rolled back. EXPECT_EQ(0, CountFoo()); } // Rolling back any part of a transaction should roll back all of them. TEST_F(SQLTransactionTest, NestedRollback) { EXPECT_EQ(0, db().transaction_nesting()); // Outermost transaction. { sql::Transaction outer(&db()); EXPECT_TRUE(outer.Begin()); EXPECT_EQ(1, db().transaction_nesting()); // The first inner one gets committed. { sql::Transaction inner1(&db()); EXPECT_TRUE(inner1.Begin()); EXPECT_TRUE(db().Execute("INSERT INTO foo (a, b) VALUES (1, 2)")); EXPECT_EQ(2, db().transaction_nesting()); inner1.Commit(); EXPECT_EQ(1, db().transaction_nesting()); } // One row should have gotten inserted. EXPECT_EQ(1, CountFoo()); // The second inner one gets rolled back. { sql::Transaction inner2(&db()); EXPECT_TRUE(inner2.Begin()); EXPECT_TRUE(db().Execute("INSERT INTO foo (a, b) VALUES (1, 2)")); EXPECT_EQ(2, db().transaction_nesting()); inner2.Rollback(); EXPECT_EQ(1, db().transaction_nesting()); } // A third inner one will fail in Begin since one has already been rolled // back. EXPECT_EQ(1, db().transaction_nesting()); { sql::Transaction inner3(&db()); EXPECT_FALSE(inner3.Begin()); EXPECT_EQ(1, db().transaction_nesting()); } } EXPECT_EQ(0, db().transaction_nesting()); EXPECT_EQ(0, CountFoo()); }
3,554
1,261
#pragma once #include <vector> #include <glm/glm.hpp> namespace AGE { class DepthMapHandle; class DepthMap { public: void init(std::size_t width, std::size_t height, std::size_t mipmalLevel); bool testPixel(uint32_t pixelDepth, std::size_t x, std::size_t y) const; bool testBox(uint32_t pixelDepth, glm::uvec2 min, glm::uvec2 max) const; glm::mat4 getMV() const; std::size_t getMipmapWidth() const; std::size_t getMipmapHeight() const; private: std::vector<uint32_t> _buffer; std::size_t _width; std::size_t _height; std::size_t _mimpapLevel; std::size_t _mipmapWidth; std::size_t _mipmapHeight; glm::mat4 _mv; friend class DepthMapHandle; }; }
681
304
// Copyright 2014 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 "ui/gl/gl_image_ref_counted_memory.h" #include <stddef.h> #include "base/check.h" #include "base/memory/ref_counted_memory.h" #include "base/trace_event/memory_allocator_dump.h" #include "base/trace_event/memory_dump_manager.h" #include "base/trace_event/process_memory_dump.h" #include "ui/gfx/buffer_format_util.h" namespace gl { GLImageRefCountedMemory::GLImageRefCountedMemory(const gfx::Size& size) : GLImageMemory(size) {} GLImageRefCountedMemory::~GLImageRefCountedMemory() {} bool GLImageRefCountedMemory::Initialize( base::RefCountedMemory* ref_counted_memory, gfx::BufferFormat format) { if (!GLImageMemory::Initialize( ref_counted_memory->front(), format, gfx::RowSizeForBufferFormat(GetSize().width(), format, 0))) { return false; } DCHECK(!ref_counted_memory_.get()); ref_counted_memory_ = ref_counted_memory; return true; } void GLImageRefCountedMemory::OnMemoryDump( base::trace_event::ProcessMemoryDump* pmd, uint64_t process_tracing_id, const std::string& dump_name) { // Log size 0 if |ref_counted_memory_| has been released. size_t size_in_bytes = ref_counted_memory_ ? ref_counted_memory_->size() : 0; // Dump under "/private_memory", as the base class may also dump to // "/texture_memory". base::trace_event::MemoryAllocatorDump* dump = pmd->CreateAllocatorDump(dump_name + "/private_memory"); dump->AddScalar(base::trace_event::MemoryAllocatorDump::kNameSize, base::trace_event::MemoryAllocatorDump::kUnitsBytes, static_cast<uint64_t>(size_in_bytes)); pmd->AddSuballocation(dump->guid(), base::trace_event::MemoryDumpManager::GetInstance() ->system_allocator_pool_name()); } } // namespace gl
1,969
673
#include <Support/Threading/ThreadPool.h> namespace jf{ namespace threading{ ThreadPoolWorker::ThreadPoolWorker(ThreadPool* owner, ThreadContext* threadContext) : owner(owner) , threadContext(threadContext) , terminate(false) , nextWorker(nullptr) , job(nullptr){ thread.run(this); } ThreadPoolWorker::~ThreadPoolWorker(){ terminate = true; synchronized(monitor){ monitor.notifyAll(); } thread.join(); } void ThreadPoolWorker::run(){ contextUserdata = threadContext->initializeCurrentThread(); while ( !terminate ){ ThreadPoolJob* job = this->job.read(); if ( job ){ this->job.write(nullptr); while ( job ){ job->run(); job = owner->pullJob(this); } } synchronized(monitor){ if ( !terminate ){ monitor.wait(); } } } threadContext->destroyCurrentThread(contextUserdata); } void ThreadPoolWorker::runJob(ThreadPoolJob* job){ this->job.write(job); synchronized(monitor){ monitor.notifyAll(); } } ThreadPool::ThreadPool(ThreadContext* threadContext, size_t threadsCount) : threadContext(threadContext) , workers(nullptr) , jobs(nullptr) , runningThreads(0){ for ( size_t i = 0; i < threadsCount; i++ ){ createWorker(); } } ThreadPool::~ThreadPool(){ join(); ThreadPoolWorker* firstWorker; do{ firstWorker = workers.read(); }while ( workers.compareAndSwap(firstWorker, nullptr) != firstWorker ); while ( firstWorker ){ ThreadPoolWorker* nextWorker = firstWorker->nextWorker; delete firstWorker; firstWorker = nextWorker; } } void ThreadPool::addJob(ThreadPoolJob* job){ ThreadPoolWorker* freeWorker; { acquire_lock(workerLock); freeWorker = workers.read(); if ( !freeWorker ){ job->nextJob = jobs.read(); jobs.write(job); synchronized(jobDoneMonitor){ jobDoneMonitor.notifyAll(); } return; } workers.write(freeWorker->nextWorker); runningThreads.increment(); } freeWorker->runJob(job); } ThreadPoolJob* ThreadPool::pullJob(ThreadPoolWorker* worker){ ThreadPoolJob* job; { acquire_lock(workerLock); job = jobs.read(); if ( !job ){ worker->nextWorker = workers.read(); workers.write(worker); if ( !runningThreads.decrement() ){ synchronized(jobDoneMonitor){ jobDoneMonitor.notifyAll(); } } return nullptr; } jobs.write(job->nextJob); } return job; } void ThreadPool::join(){ while ( true ){ ThreadPoolJob* job = nullptr; synchronized(jobDoneMonitor){ { acquire_lock(workerLock); job = jobs.read(); if ( job ){ jobs.write(job->nextJob); } } if ( job ){ goto performJob; } if ( runningThreads.read() == 0 ){ return; } jobDoneMonitor.wait(); } performJob: if ( job ){ job->run(); job = nullptr; } } } void ThreadPool::createWorker(){ ThreadPoolWorker* newWorker = new ThreadPoolWorker(this, threadContext); do{ newWorker->nextWorker = workers.read(); }while ( workers.compareAndSwap(newWorker->nextWorker, newWorker) != newWorker->nextWorker ); } } }
3,268
1,421
// Copyright 2013 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 "content/renderer/media/webmediaplayer_ms.h" #include <limits> #include "base/bind.h" #include "base/callback.h" #include "base/message_loop/message_loop.h" #include "base/metrics/histogram.h" #include "cc/layers/video_layer.h" #include "content/renderer/media/media_stream_audio_renderer.h" #include "content/renderer/media/media_stream_client.h" #include "content/renderer/media/video_frame_provider.h" #include "content/renderer/media/webmediaplayer_delegate.h" #include "content/renderer/media/webmediaplayer_util.h" #include "content/renderer/render_frame_impl.h" #include "media/base/media_log.h" #include "media/base/video_frame.h" #include "third_party/WebKit/public/platform/WebMediaPlayerClient.h" #include "third_party/WebKit/public/platform/WebRect.h" #include "third_party/WebKit/public/platform/WebSize.h" #include "third_party/WebKit/public/platform/WebURL.h" #include "third_party/WebKit/public/web/WebFrame.h" #include "third_party/WebKit/public/web/WebView.h" #include "webkit/renderer/compositor_bindings/web_layer_impl.h" using blink::WebCanvas; using blink::WebMediaPlayer; using blink::WebRect; using blink::WebSize; namespace content { WebMediaPlayerMS::WebMediaPlayerMS( blink::WebFrame* frame, blink::WebMediaPlayerClient* client, base::WeakPtr<WebMediaPlayerDelegate> delegate, MediaStreamClient* media_stream_client, media::MediaLog* media_log) : frame_(frame), network_state_(WebMediaPlayer::NetworkStateEmpty), ready_state_(WebMediaPlayer::ReadyStateHaveNothing), buffered_(static_cast<size_t>(1)), client_(client), delegate_(delegate), media_stream_client_(media_stream_client), paused_(true), current_frame_used_(false), pending_repaint_(false), video_frame_provider_client_(NULL), received_first_frame_(false), sequence_started_(false), total_frame_count_(0), dropped_frame_count_(0), media_log_(media_log) { DVLOG(1) << "WebMediaPlayerMS::ctor"; DCHECK(media_stream_client); media_log_->AddEvent( media_log_->CreateEvent(media::MediaLogEvent::WEBMEDIAPLAYER_CREATED)); } WebMediaPlayerMS::~WebMediaPlayerMS() { DVLOG(1) << "WebMediaPlayerMS::dtor"; DCHECK(thread_checker_.CalledOnValidThread()); SetVideoFrameProviderClient(NULL); GetClient()->setWebLayer(NULL); if (video_frame_provider_.get()) video_frame_provider_->Stop(); if (audio_renderer_.get()) audio_renderer_->Stop(); media_log_->AddEvent( media_log_->CreateEvent(media::MediaLogEvent::WEBMEDIAPLAYER_DESTROYED)); if (delegate_.get()) delegate_->PlayerGone(this); } void WebMediaPlayerMS::load(LoadType load_type, const blink::WebURL& url, CORSMode cors_mode) { DVLOG(1) << "WebMediaPlayerMS::load"; DCHECK(thread_checker_.CalledOnValidThread()); // TODO(acolwell): Change this to DCHECK_EQ(load_type, // LoadTypeMediaStream) once Blink-side changes land. DCHECK_NE(load_type, LoadTypeMediaSource); GURL gurl(url); setVolume(GetClient()->volume()); SetNetworkState(WebMediaPlayer::NetworkStateLoading); SetReadyState(WebMediaPlayer::ReadyStateHaveNothing); media_log_->AddEvent(media_log_->CreateLoadEvent(url.spec())); // Check if this url is media stream. video_frame_provider_ = media_stream_client_->GetVideoFrameProvider( url, base::Bind(&WebMediaPlayerMS::OnSourceError, AsWeakPtr()), base::Bind(&WebMediaPlayerMS::OnFrameAvailable, AsWeakPtr())); audio_renderer_ = media_stream_client_->GetAudioRenderer( url, RenderFrame::FromWebFrame(frame_)->GetRoutingID()); if (video_frame_provider_.get() || audio_renderer_.get()) { GetClient()->setOpaque(true); if (audio_renderer_.get()) audio_renderer_->Start(); if (video_frame_provider_.get()) { video_frame_provider_->Start(); } else { // This is audio-only mode. DCHECK(audio_renderer_.get()); SetReadyState(WebMediaPlayer::ReadyStateHaveMetadata); SetReadyState(WebMediaPlayer::ReadyStateHaveEnoughData); } } else { SetNetworkState(WebMediaPlayer::NetworkStateNetworkError); } } void WebMediaPlayerMS::play() { DVLOG(1) << "WebMediaPlayerMS::play"; DCHECK(thread_checker_.CalledOnValidThread()); if (paused_) { if (video_frame_provider_.get()) video_frame_provider_->Play(); if (audio_renderer_.get()) audio_renderer_->Play(); if (delegate_.get()) delegate_->DidPlay(this); } paused_ = false; media_log_->AddEvent(media_log_->CreateEvent(media::MediaLogEvent::PLAY)); } void WebMediaPlayerMS::pause() { DVLOG(1) << "WebMediaPlayerMS::pause"; DCHECK(thread_checker_.CalledOnValidThread()); if (video_frame_provider_.get()) video_frame_provider_->Pause(); if (!paused_) { if (audio_renderer_.get()) audio_renderer_->Pause(); if (delegate_.get()) delegate_->DidPause(this); } paused_ = true; media_log_->AddEvent(media_log_->CreateEvent(media::MediaLogEvent::PAUSE)); } bool WebMediaPlayerMS::supportsSave() const { DCHECK(thread_checker_.CalledOnValidThread()); return false; } void WebMediaPlayerMS::seek(double seconds) { DCHECK(thread_checker_.CalledOnValidThread()); } void WebMediaPlayerMS::setRate(double rate) { DCHECK(thread_checker_.CalledOnValidThread()); } void WebMediaPlayerMS::setVolume(double volume) { DCHECK(thread_checker_.CalledOnValidThread()); if (!audio_renderer_.get()) return; DVLOG(1) << "WebMediaPlayerMS::setVolume(volume=" << volume << ")"; audio_renderer_->SetVolume(volume); } void WebMediaPlayerMS::setPreload(WebMediaPlayer::Preload preload) { DCHECK(thread_checker_.CalledOnValidThread()); } bool WebMediaPlayerMS::hasVideo() const { DCHECK(thread_checker_.CalledOnValidThread()); return (video_frame_provider_.get() != NULL); } bool WebMediaPlayerMS::hasAudio() const { DCHECK(thread_checker_.CalledOnValidThread()); return (audio_renderer_.get() != NULL); } blink::WebSize WebMediaPlayerMS::naturalSize() const { DCHECK(thread_checker_.CalledOnValidThread()); gfx::Size size; if (current_frame_.get()) size = current_frame_->natural_size(); DVLOG(3) << "WebMediaPlayerMS::naturalSize, " << size.ToString(); return blink::WebSize(size); } bool WebMediaPlayerMS::paused() const { DCHECK(thread_checker_.CalledOnValidThread()); return paused_; } bool WebMediaPlayerMS::seeking() const { DCHECK(thread_checker_.CalledOnValidThread()); return false; } double WebMediaPlayerMS::duration() const { DCHECK(thread_checker_.CalledOnValidThread()); return std::numeric_limits<double>::infinity(); } double WebMediaPlayerMS::currentTime() const { DCHECK(thread_checker_.CalledOnValidThread()); if (current_frame_.get()) { return current_frame_->GetTimestamp().InSecondsF(); } else if (audio_renderer_.get()) { return audio_renderer_->GetCurrentRenderTime().InSecondsF(); } return 0.0; } WebMediaPlayer::NetworkState WebMediaPlayerMS::networkState() const { DCHECK(thread_checker_.CalledOnValidThread()); DVLOG(1) << "WebMediaPlayerMS::networkState, state:" << network_state_; return network_state_; } WebMediaPlayer::ReadyState WebMediaPlayerMS::readyState() const { DCHECK(thread_checker_.CalledOnValidThread()); DVLOG(1) << "WebMediaPlayerMS::readyState, state:" << ready_state_; return ready_state_; } const blink::WebTimeRanges& WebMediaPlayerMS::buffered() { DCHECK(thread_checker_.CalledOnValidThread()); return buffered_; } double WebMediaPlayerMS::maxTimeSeekable() const { DCHECK(thread_checker_.CalledOnValidThread()); return 0.0; } bool WebMediaPlayerMS::didLoadingProgress() const { DCHECK(thread_checker_.CalledOnValidThread()); return true; } void WebMediaPlayerMS::paint(WebCanvas* canvas, const WebRect& rect, unsigned char alpha) { DVLOG(3) << "WebMediaPlayerMS::paint"; DCHECK(thread_checker_.CalledOnValidThread()); gfx::RectF dest_rect(rect.x, rect.y, rect.width, rect.height); video_renderer_.Paint(current_frame_.get(), canvas, dest_rect, alpha); { base::AutoLock auto_lock(current_frame_lock_); if (current_frame_.get()) current_frame_used_ = true; } } bool WebMediaPlayerMS::hasSingleSecurityOrigin() const { DCHECK(thread_checker_.CalledOnValidThread()); return true; } bool WebMediaPlayerMS::didPassCORSAccessCheck() const { DCHECK(thread_checker_.CalledOnValidThread()); return true; } double WebMediaPlayerMS::mediaTimeForTimeValue(double timeValue) const { return ConvertSecondsToTimestamp(timeValue).InSecondsF(); } unsigned WebMediaPlayerMS::decodedFrameCount() const { DCHECK(thread_checker_.CalledOnValidThread()); DVLOG(1) << "WebMediaPlayerMS::decodedFrameCount, " << total_frame_count_; return total_frame_count_; } unsigned WebMediaPlayerMS::droppedFrameCount() const { DCHECK(thread_checker_.CalledOnValidThread()); DVLOG(1) << "WebMediaPlayerMS::droppedFrameCount, " << dropped_frame_count_; return dropped_frame_count_; } unsigned WebMediaPlayerMS::audioDecodedByteCount() const { DCHECK(thread_checker_.CalledOnValidThread()); NOTIMPLEMENTED(); return 0; } unsigned WebMediaPlayerMS::videoDecodedByteCount() const { DCHECK(thread_checker_.CalledOnValidThread()); NOTIMPLEMENTED(); return 0; } void WebMediaPlayerMS::SetVideoFrameProviderClient( cc::VideoFrameProvider::Client* client) { // This is called from both the main renderer thread and the compositor // thread (when the main thread is blocked). if (video_frame_provider_client_) video_frame_provider_client_->StopUsingProvider(); video_frame_provider_client_ = client; } scoped_refptr<media::VideoFrame> WebMediaPlayerMS::GetCurrentFrame() { DVLOG(3) << "WebMediaPlayerMS::GetCurrentFrame"; base::AutoLock auto_lock(current_frame_lock_); DCHECK(!pending_repaint_); if (!current_frame_.get()) return NULL; pending_repaint_ = true; current_frame_used_ = true; return current_frame_; } void WebMediaPlayerMS::PutCurrentFrame( const scoped_refptr<media::VideoFrame>& frame) { DVLOG(3) << "WebMediaPlayerMS::PutCurrentFrame"; DCHECK(pending_repaint_); pending_repaint_ = false; } void WebMediaPlayerMS::OnFrameAvailable( const scoped_refptr<media::VideoFrame>& frame) { DVLOG(3) << "WebMediaPlayerMS::OnFrameAvailable"; DCHECK(thread_checker_.CalledOnValidThread()); ++total_frame_count_; if (!received_first_frame_) { received_first_frame_ = true; { base::AutoLock auto_lock(current_frame_lock_); DCHECK(!current_frame_used_); current_frame_ = frame; } SetReadyState(WebMediaPlayer::ReadyStateHaveMetadata); SetReadyState(WebMediaPlayer::ReadyStateHaveEnoughData); GetClient()->sizeChanged(); if (video_frame_provider_.get() && GetClient()->needsWebLayerForVideo()) { video_weblayer_.reset( new webkit::WebLayerImpl(cc::VideoLayer::Create(this))); GetClient()->setWebLayer(video_weblayer_.get()); } } // Do not update |current_frame_| when paused. if (paused_) return; if (!sequence_started_) { sequence_started_ = true; start_time_ = frame->GetTimestamp(); } bool size_changed = !current_frame_.get() || current_frame_->natural_size() != frame->natural_size(); { base::AutoLock auto_lock(current_frame_lock_); if (!current_frame_used_ && current_frame_.get()) ++dropped_frame_count_; current_frame_ = frame; current_frame_->SetTimestamp(frame->GetTimestamp() - start_time_); current_frame_used_ = false; } if (size_changed) GetClient()->sizeChanged(); GetClient()->repaint(); } void WebMediaPlayerMS::RepaintInternal() { DVLOG(1) << "WebMediaPlayerMS::RepaintInternal"; DCHECK(thread_checker_.CalledOnValidThread()); GetClient()->repaint(); } void WebMediaPlayerMS::OnSourceError() { DVLOG(1) << "WebMediaPlayerMS::OnSourceError"; DCHECK(thread_checker_.CalledOnValidThread()); SetNetworkState(WebMediaPlayer::NetworkStateFormatError); RepaintInternal(); } void WebMediaPlayerMS::SetNetworkState(WebMediaPlayer::NetworkState state) { DCHECK(thread_checker_.CalledOnValidThread()); network_state_ = state; // Always notify to ensure client has the latest value. GetClient()->networkStateChanged(); } void WebMediaPlayerMS::SetReadyState(WebMediaPlayer::ReadyState state) { DCHECK(thread_checker_.CalledOnValidThread()); ready_state_ = state; // Always notify to ensure client has the latest value. GetClient()->readyStateChanged(); } blink::WebMediaPlayerClient* WebMediaPlayerMS::GetClient() { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(client_); return client_; } } // namespace content
12,994
4,303
/* * Copyright (c) 2017 Jason Waataja * * 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 "config.h" #include "removeactioneditor.h" #include <assert.h> namespace dfm { RemoveActionEditor::RemoveActionEditor( Gtk::Window& parent, RemoveAction* action) : Gtk::Dialog("Edit Remove Action", parent, true), action(action) { assert(action != nullptr); pathLabel.set_text("Path:"); get_content_area()->add(pathLabel); pathEntry.set_placeholder_text("Path"); pathEntry.set_text(action->getFilePath()); get_content_area()->add(pathEntry); show_all_children(); add_button("Ok", Gtk::RESPONSE_OK); add_button("Cancel", Gtk::RESPONSE_CANCEL); signal_response().connect( sigc::mem_fun(*this, &RemoveActionEditor::onResponse)); } void RemoveActionEditor::onResponse(int responseId) { if (responseId != Gtk::RESPONSE_OK) return; std::string filePath = pathEntry.get_text(); if (filePath.length() > 0) action->setFilePath(filePath); } } /* namespace dfm */
2,075
684
#include "convert.h"
21
9
#include <gecode/string.hh> #include <gecode/driver.hh> using namespace Gecode; using namespace String; class StringOptions : public Options { public: int N; string SQL; StringOptions(const char* s, int n): Options(s), N(n) { this->c_d(1); switch (n) { case 11: SQL = "A=B=C = B=C"; break; case 12: SQL = "+;+*=!'*I =*I"; break; case 100: SQL = "LXA.U22=H-= W+QOA<)!@K?4L@3L)=V%$))<XI>+P>)AP&435Z@2)P6TSE)Y8 =)P6TSE)Y8H!"; break; case 200: SQL = "7*C).CYGU.UW ?>DC +<<(PMUD%C@SA34G,1V9H7WG,.JK(0#U$H-N>G4LRHSEL:JKU!4D6?F,<!)E=R> Y>3D0W61&AEDAI1+,(-5;QL*4D30JV;J'S#K.YA'EP,X?HO.Z(7DN7(X*U4)B)PZL:5@?/O78<U=HO.Z(7DN7(X*U4)B)PZL:5@?/O78<U7@Q'<=:,0$?!"; break; case 250: SQL = "XB%DQ:QQDX57@NG$XU8PKU1GTYU,K$:3JA=6@V-WD;)RM@&2D,W3M> F:S2:M.49UHKC58KD#=UW8ZFRZJAFN;)B9?6@-ZVO;1#YOJTI) 7XH6&@QZ$AXRJ-=XC,IEM)F@+WO:R&*:S64GN(%Q'ULJ@S?497.9?#Y@?425'*@,-7>=7<M' ; &CWJ8#O94:584L#F'1UZ28T@B+'%ZA?72F96/(@=%UIIOL3EL-W<%V.ZTSW.B2:U%UD6U"; break; case 300: SQL = ")%L>/4T/L(5V-$:1V'(XEB-O5SPDK =&)YT%R,6W0UD<K)4L58?#X9L4D0(8@1>A)<=AR2W*)'ZO +:+8HZNS=#XM*E2?7?C:T9$W7#;*R8$@9>:0N4SU2,XCI9+HCB%W#6>NVL7S+T!1<&2.1JFO5GVMB&N:&J-ZMQN1@G,670 ACG'%I),05T'$ ='%I),05T'$C$'62/C$F+1'GO"; break; case 400: SQL = "NR-7A365%&I.+E*H2>),$/HM/?BRLJM-D'OEXDF&OX6$FNA0,ZY7YLE@<=P>9,GI&359MMK:58CYV)Q,##0?C#<(M:2SJ&P+D=:9E,@+C.U=>+4(Z)LA81.K7X:.TW4;#=AMXQDVK<9Q=T&E8??J;&LQ0/Z?IB/<')UU.,?FE = 7A365%&I.+E*H2>),$/HM/?BRLJM-D'OEXDF&OX6$FNA0,ZY7YLE@<=P>9,GI&359MMK:58CYV)Q,##0?C#<(M:2SJ&P+D=:9E,@+C.U=>+4(Z)LA81.K7X:.TW4;#=AMXQDVK<9Q=T&E8??J;&LQ0/Z?IB/<')UU.,?FEU"; break; case 500: SQL = "V3EZKXFXQFVMVZNHVRIOI0YP5WHVETOZXTWUQ47HMIKQ8OAWMDMG1HLGVXTJK8GZBLVXP1BQXEE06GUVXLMSR1A7HKQLQBEZGVQ3T1SLM3VS8CPTCQG6KLUEDBFE9CNAJHDZEUNGTV68TVWDBGJNGKJCEKG4FQA0GI3252PAKIKSLNZZZ23AOJBS9CHDHUVRZRNVRTJABKEWQISEG36QSGIKKLFQT047VZNBR2FFI = ID1QI0NNTKDJXOSSZJZRZNM4JFLZJMW8PB860MGTF74JOUN0QTDZEDZLCUWCTE7J8OCDP2GSWF1NCWCT6XA1VWFNXZFVHDOXN7RCQ8F4KWGY6XRFQXLNNDTIGNNUUYXHOEZVY5PIP0UFQOPQHJQPVEOROORLQLPNRL4VXVHZM4K1V3KOVBP9UI2LAET9ZIB8WRFI3RESY3MXFF397VQBNY7FOQR9Q061SXKMNVVLEQFNTTCTWC0UQWNKDVTRMHUAFDO5UKV"; break; case 1000: SQL = "H4,$;)4$GJUE&TB&8@LRR0ENI(84;U/X.L)A)LH08W4PV@9KBL LNB.V78OQC1<VD4JU-A3;R/*P<A-ETP7.1:>PB;6+?-BW0J@SY1O6&QXI/9BV)JGB#HY@8;2V8R2SWS=&XWB=3QJ(Q>37'YW(JK3UZ5PALY+/@S8M> $@#A+?BKA'+7MO*'$OAUH-P7GL5%?G?4/-M#A>R%WPAYQT8 ?%S$N7&K<4=&4T7CFT7HS<51EUD7 #CE>=MBV'<(&AJ<=YA@)B.6)-6Y0'L<Q8PQ)J2%&*=Y,2Z8HBJL:R2FYB(3AB==1%?IZVK8N1%$65<0E&LC?J@SAO7KNZ+4Q=V5YOU$N'MQ)OXJ(YQ.S >@4;?(1DE5T0$UVJ2G=KB<+UF<E;4W&'@*50D(H8+P&0-G;ZUJWGAN13.RKKPN'VH?PU?G;@($2:0=&ZT ;3VS1IUPEC+$$A%(A$TUD$5&'QGKS(W,=DKPXS8FAYYQP 26/4'Q=7)4HX(A%3B5T'NYHOQHEF4SN3&SZT?VN=>2A.-OSCQ(XKHFB%.9KU<-2:,:B'XSG8Z@NW-X;B<R5F(FD7+EAA97S'%#=.G0Y73/Z2WMBUS.=:H>QH,(/D9PRHVD 76.%==J0D/AOV7/,B')R*@;&2$K.1G9+TOR.J'VQX-UGH+>'J$<=0ZB#F.I-#9?<>QJOV57<B50(<(X Q+%O@%3F:97=3J1H(MI?3MFUJ*M+ &LS AK6K/3:KRYL@C1@:A+AU,-UM*#;X1NJZ<(1$M4X BNXD7F?U'<7;*AW$FJQJY/ 6S4K&RY;66M'I2>(P82:D(PE@)CMW -=9)$EKCMVM;5NIU#S/OO8)FK +'1..FIV6)V4LLD--YY<T*NE?T3VR$CF,>7I;51EG@LWJ=GP%=L$ .JJKKAY:I F1+*8+6-80FJ1-6 B=#P4;3F+E'@7?WD8>C@C2BR?$3=:HIRJ9'=L2J=:Q140X<Y>:Y:QDP@PKD><V20KZG@="; break; case 2500: SQL = "V9KVM5KVGS2TZJHPUWV81VCIIBOZMKEQPCMN4UJ9RESI18AWJQNIYFSLXOBH3DIOKU51SAQO1TILW2TSWXRH89AWKHJATNWF0GHRVYCDGZXRGSDVVZ5MX3KSBWGFBCDAIOV6KWVTXCKAVE1BAK28TYFLQC2BAEU7OOFGL9ZTHLZ94PFYIYS3WZMK29Q6YSM7KRO2ZSJ8RSRWUAUKTYMWTKFLAZYDS79GZAUILTMKOWRBNTWS7FOYQ1KXZ2WXGX0MYRQXMGLJEUY37PI9QBI4FVCEROTTPFKVZPNGUAGDEQYQ4C8A7ER7LFLYD29VL2LFB6UJCBNRXR5HL4YUZB0BYYKDASEBH5NHGAQNLH6YHMOBYXX8CIMUMFYKWWOQPBLP6IUOEW6JMCOKYZ5RDWH0T7ZVN4OWRWJTRMUV4XXP52RVRCX7XTGVGO8ZMPQYQY76GXT7XOBFUJ75ZDPQNTVBSYTJE72WWLK26E2WLJ12GSEGAI1UVLWJ75WWQRSVEGSIWKFC9MSZF58HELOOJK7POW6QR1HWSPXN8PR0W6BCISHH5SAJF0R1PGMEXEWWHIOW426VVCBGGFFN1EO7NAJOABIPYZH5SOXCZNGQBLYLKX3ROMM6QHVTG7PAEGW8JRPZFADRRGH3XPOMBT0OFTXEIHO83UWXWLMG0EZOHV6GLMEZPKXEL8JC4CB2GPC6FUWCX2PRGRNUVZWVMSKZQLKVV9EMVCEELCBFACL0HHMJLOT4YYSKP9RRB3QCIBJXEMHHV2GJI6LJCLMEQLYTLZBN1J2QDCPQTSKR26BSUYPUEJ1LBWOIBQRJK6VVRGLWQNBYWDQBMUBNO5VRZTWVINSBEOMQPMCPVGRI0NTYVWLOZBSXTCAEMORKFM3A0MUVRKFR2BPIAGPBNT77HZQ29YV5QLNBSJNALGBPVS0KBT1SCBBA5FJJJKEJLRCBEAUFHAHIW71B7N1WLZ2KAWVUQIKEYDTBTSTJAQIWVNXLLUGJZIT4XEGP59EP71HJ3VIRYCV8YJFARUF8FKNB2GE9NVIUH8T4ALPCUKNXWHLTQZYJKXAFVQTFS9KANHRTRKYGP6GQWERGGUQTKZFM52XQWGAMRTHTYASDL90L4UJZ9LEUJWAKBZ6CZLOFQ2X6LNBQBVCLENKKQ2ZSWET9GRSEN4DYIMJGARJHWLX2PVJMQS3AVPJAKPUJCUU6C5WLO50NKPKXRCLXHHTM1RDJIAGL6RGZZR1ALLJPJFU6EUNUYKOB6MHNZGWCVZ6YGFXT41SYWMMXEHZO6K6V7PVSQAAQEJT6NSJYNUEPNI0SM3GVIDU8UVKKUX2E696GYNCWWWMVECGEOXQW5HTVDQHQ4RQYCTEL6LOHCMKFFAVWN4GJKOSOQ6FELYKY5L0RTGJAUSATBE4RWUJIRHMSQUBCUUDUALEOH7HMXGQ9LSVIUAXEINVPF1KLRTRJGGO2NUMLXESXCMMWGCYKZT18OULWA5PABC3ZLRXXNXRATAKHOJ7T=TVFVMCOAB7DDQCRC5IWREGQRWF8PCGWPJ1ZT8IRAFAWSYVDAOLVH42AHBQZ8ZSB2OQXJTCPP3346WSYLUBY8JORSNGFAZYMCMFFC8KTHWRJRWXZA3TP5O75Z6UOSGNV7ZH8PFZBO126GSC9WP9CNC16NZROVRYUZQVOMCUWGATXZJDYIYW7NIHJ1QWALK1SHQLRQ6ONMW4FJBQ17ZKWARJ03YTUNJMSR1JHZIXYQKBDPILPYAHHS7GWAQZAUJVT7RAUHULIG9ZICA6NCWCMFFHWBQFG9EIJFJWPYMO7HCFA15P8ZJWZJV1CHJXBPXRIBLXYBZ0SMGK9REMMUQVI1AUE8GVFHGJ6Q72ISK2HLH2HPX6K2AM7FR2BO1PMTV5RYAA8U1HSTWEKB9UPONNKGLWM8XU2B4TOJ7CLFHZ5XNJ7OI4IOBWKY0O3LWB4B87QHGV1BOVWZFWFU7XPNZCVDYCPSDEAILW0EXYEAJF386ZMSH5OJNSPPYSZ2139YTE5IKENRY43PX43O37Z5UTOAI5LV9EOG3HLRTTMNUZO7X4O2S63SAQ0SIDIMFVZJ2GU23Z1LU1MRSUQV4MRJOVZ3PQISVFCG1JP5ICM8DG8CSDPBQWRNUYJPSK8IMZANGKY1UIC5BM5NWTDEHRZUVNCLESKM25SMKPCFVKBJXZOZRRNEKL7GEADMKEG7CPAI0LLZCCIMDLIUZNMUXUHWVPCYWAGG9TYZWSI82XGCI4AKC22EB4FZN7OJABHQKANLQZNNWL9SVIMADPM2P3ZEORYDUHEZWSXXZEIXWRCBNFJKQPYRG13SCNORA8TZJ15NHOVFJDWS61KTJ3S5KWRTTYTUJCMANRR6ODJW05QUFNMIMN5HHKECOP3DCQ4LTLPKTFM8XGPCFRCJ7IMSHX5TSFMPEYRCZILGLI5JHJNJSMQYCX0VJCLRMCNGI9LBLHMRUTSZV7V5T6TWVUCYE6LTQVLRKCJSUTJSRHF"; break; case 5000: SQL = "3UK8&Q0XB,%2&HCA()G8C&&DQSD44/,GO?-EKWXSV6,J1Z@*XQM&-I<28RB&U?,*QV/CPIEGX4;37%5&,J0T9ZFV2K=L5=M):K7#ZYAO;X@QJ)?M'L0:OE.;54&%AIGSE==K0:-H'/QI95MU?%,5G MG7T,F#CFO6E=:(H6W4TR&<POJ%,D:GPNEH131F1(,2U'FK+8S-/OYJ:'(=?J:DUENZ(4SGW/5(>-20 #TI,AE84;E1P0$) 7SWO2MI(5H4GWZ>SL+ZV6(=D@?QU(STUM+P%)</ .)1T-L%8I*I3HM/SY)#8 QWX:+J1@G)XX0V?W(Z8J8U(03DA7WWZ1;11R%2L+R)JO=R<QLOL*$<:YQ1KGK*:(<(M<Z$X=2MRES3$GV2/>S,E1.,S08.W68GAO75,YAUR%A1(HQ/Z:/ND.%7IG,?=L7V&$'V9)9+=B#/:5&NPOKGTP&:4DW*J,&:>(*R>(),YRQ+R39;.(84AY&-MRW#D0#5FI4NDTI@&$,33)>,VS/UV:<<G6NXTIZ5P9,/=QI#80-TN<-7BMZW(@ OC&F;:;Y(P;.4XT;7M$=1J)D'R>>609(*N<)#H(K%WZ,W<*+=/7LQIWB4AX(7539=Q&&JY;960E'729 ,7L,E*+WYL/+)#2E*ER3-S,S-E?-;%W4<6O:'-&IMYK:SUG)2%U9LYM)=%O7S4):JA4?,+UOQ?GL0+ ?<UX7 GJP5Q XWZRD/<*71&1N$=7W*OJN=FDRM2>8G/,WL3NE0O,RTTG#Q)?R#6-HF7EXOK 5AI*/M/D=>J>QR5+?F81CJ7Z@X?*R39%7F4,*U'BIC#(#)10%ZT4T9'(HG4OJ.Q.&LNL?8VDHA02/C 9;LO%$FU*.W/(RHU$3W'6-.SO<OT:C@HFYHU2('=QP54Q;=Q%U;U0 KA2U#2U1U)- +$$2:K)GH;OQ66:?IEH8O2P*9/Z-P=CNBZ()210C+I6=?:;UG3:.+)I*LPH+5.ZOWG *H3QX$Q0R%UEI N:RT$&'199ZE'KE/3$V+3Y I(9W5>G>NRY+D(()Z4KSCAFAPQ$@GP8$ZHPZXW6GYC,P?2J@BU+.ADWQG#Y3+832V1N+ ).B:98#H>)C:Y KTS<T?+M.6;+8D2,G:::?)R:=.%2VH$%&5J57-+CI<659B##7L D2GV26E,;G0H0D/3@VK=:7IC#IJ@294PF%==VCDY ,'#7;#C*X@.U8M@5D>K&;@?F88#@AA'DMKU*:KX(D* :3<N)?SCA=56M+@TO$>B@B13FFX0-D#C0@S,:D?*/RJ(%?+QB(PI14Z@<SHG>J/?:DCDCYBOFHS-W2,B<VQ%X;18EDU3W C<G*$B-+>2,BGEVK+E90? '2EJMRZ#QB8D%GO 0(/YVE)IS LM3*G4#' 1B(F$<LA F3CAU5%:SRV#,B+Z XZM0=(?5+B2J0%UJXFZM)&6@82ZMCQ/QO<H7K.7P?#'J1AZ'WZCBC,A.YUXR#/D+0*=D CDPEHSWL47Y+2;%=NGZ.$SCE*C0L:K/&M?RJNV3C.Y2.Z##+1#0* WI 375*WCQC2';S06O&T7MH6@DO .I>X.ZAHP9>P=B#2C<5NFOR<*9F;27*:6,?JIK=,CA5'4KV3Q?,62,8=PSNNKVCK6WN,<$A2S=ERG2U62.&IMYLAVB<$N*E:2>853V$BV(4>0W$I*?>P=>6.A1-KG0<)?MY3Q8+3OC)TL7),J7-@,7*<LT7%W4HV'4DD.F%FY 9@>U(A@%A*I=&2>HO@GVZ7KP.$0J-I'I@B G+A0P@QA<GF*# 'Y#F.,AZV>$CVP+(ZQ/6$Z+8CEI+(FIP;V9&Z:,F)YV'LJ/XL=G>.D.OSW5'#+,8N48KX>GFWO Y3.%O$##LN7@VT@<2QE*YNYZ+IX3<B &Q8;P6;U;101:4<: M*1=A?6FFU@ANC38'(,1/5EAR/ ?W7J%<?%9<56H&8K$&MAX$W< F?$&Y5?,MB+P/S&3W9'8%,+;B#KS31RMZ6.CF1N'=FC0U1EGC(D@5Y+&+I7;.)=3=2GAD,Q)EOU8N4B&P5.$.YYKF>F)B'8#<83DKG<?-5)#&77N4-ITWN9Z<BXMW6T2N#Y9WMA+XFCY @R'S0%I(*7V%WWLAZ/V;N;E>):%U:QOW3; VP4>OMWK$6AP:'RGCIZ&3(NRRI$?SO/D=LDV0J43WB7VB5))W*C*5<'=:0G3VI69=GG=J(9*U=H=%I(>%6$4E$ZPQQ,,?:B*Y.1$88ZXO:+4L1PM2('RGR9*J0'.*MGM$G CV.ZS-MB:PF-..X/KEG@V*B?WC,=<Z'NT EPYH0 -PBTE)KOZU*8H&7=MLRO7&#YC2&3N2=AB0KYVRPA=<%W0@LH6C,-W$JQ<WAGXWE-*=E(X-W?-39(=P-TLWDE*Y+3B'#X8TCP76JVJJN,BLCZCFWBXC'U&K&B3A(2)#AY,POA>NEG@EI/2:>S$ G<BRND;.$/J.;HUK/HGTLN%Y9:=S5TR-,P%) 'EJ7(30/6W'%:/;/WZ@3-Z.14VU=I@2#5RT&+GN>P#EA ('QEOMD,C1UHL$C,JR,N$@<=(CANG-W/&G/C78G6%L9$0V<+<=/XPT5A1@Z/8H- -9:6I:GS97%QK7>>/K6RW:LA7TRW33ZS1 ':HSK)RV06147?FJ?96-%HYK40>%ZHI4SW9/=#C>OF5F-O$#=X3W/,N8OU)K6?E%A>$<GUZJ'G?LE?;E6E#*J9,8BZMMB2,B6,29'<W>?*MT*XWN7PXPH<B%S<K--F?/'C@->N.()94*MQ,UYSZPQV/<7#.Y* Z:O7D<J08PZ&M/H&&N'R0- Z5F;:<Q;FF42#N@U@0-$TA X9LC#:,A;FJ$;B3E5R<:?'*V.'J?9LQ$GS(-*( MJ)ZT2BB8CS*FR%O5TQ- ?9&T/(U4(F?33FP,.G46737?#I$(8 >/ FREYN93IHL<5;L3D'&?TIPPYQ0?MK(R-/3'LDJ1R*%(-+SHL'% <K?:HF9U1QMD/C6%RGUQPSH-4)7;$0)B>&YPPR8+8U.TJ3',W78##&GU==E#UTS<%#%PAW,HGF7IEE( U L-F-+6V#2=TR#=LRI,2=@TZFN$+-L5HPF.6DQAG)MFF/H, NT2L>4;91QK##5*J;)@;&##J64%2J<FF=&A+YRN0Y5=,3#UW(S@R-L6UIFDDI.( :D.Q3KBRR(5BX(?66V'()>U@%=:+-0HORXE>FBU@?'$');->3Q*>&27;;@YBC9-LJ( J5*T,#C1'6,7X%.DN=6MQV8$669NKGW?Y5BWFWF1&9GQ*G;<$FBP6GJA2X;NFQ&:G6#;1GCMMQ8RAOLV%2M1C>0E*7*:Z:+B5Y.J7QBD6*7S3+D&T8NX=G(ERZ7Z-+1>JVL0L4 BMD?.VDTEV*L4'GFED2VYC%G*U.,XM@>41>K0#G%V93C<S;;=S&YBG#+01NRY(+A->XPE%5?AD7, ,GJ5L32U1BQJMAM$45Y6D?1/*3D=>:( 2.WM>37KNRX0>5>K.RQ$6.TLYUZMQ=%:16VRP+-:S GD*HKEC1U7FS=9?G9H%&:IE?PWJJV'<VC3<&P467>6T$TP(@/8H&<&2ML%IN9*EA4DJ3T39G>:36R'4;5'8OJZ+F*SR?C&F -<EC5=ST$R9*;J3,&J 8>:E.@+Y+FVMID#*((K@JE#X526WD/)S&7;-UTI+Q:+YOMFEKHU4RD8P9=SB=#Q,QY$;D4$+ZISO?Q=5/*GX>.;M''1.$'2 :HE'< );E35;+H1;-VHHM:)58/G&0(,L$&&HX#&1(+P:NL'&UA8,G@CA6XNT<VM+'TG224MJ=DOR'R/%*:<=(HR+ZJ%F1$-?S<O9AKR.89<Z,*72,N 78@>);OGD1B,NA3#8@A/'8CS&A9TW55W8+8<YE87;G8O@AB**44%6T7@8/95$B5&% 0#UVJ0?(;V+EVI.'X/F12L5DN:>#H/A(W:T$3T(8D+B199(MD/WD=0)(9HA%;KBJ)V<:@$H/*FOW,)=F* &?TO0ZY,>@'45G,2K:%WO=<'RRV'M;<SKRLER/?4 6M/=@(D+V8-L+V=.&3KT4I%=6?K':AEP' 8ZFR9KID9&XAB&$-BIN3Z;7C9CS+4BJ(F8N>UX@&G1VZ1 ,Q'2U(Y=O5WM#*88YRLRFX:>;VU%2/LV.>)?(-CG=S>=C:9R&' %H4YX>$8=W3O7WEREQPW9#?@Q/+PHV*1$I7DNO@+.XL<N&I.;@/ $:.OFO@EN:M7LWH)8C1SU4O?W-N8<M5F<2JUO&TF4USFA$N=5JASBDZ-**J8'AZR/$$0P18,F#%<-%AT3#WD=%76*S:6P'B.P:<'IT:(151H#GW-DK%'MWF.G/(U10)DI3;0; L)C#C9&%&1#YFXOY2U SUO'6*C M9G5F2(-EP-XI)AY#@DP>PR; M*IHZF6J+9: <>DSGBNE%().%O<9&*B-I#N@<@MY:3,.?4(%QVFL7K+&'I YHL)UFDF,:V&R@=S*'/Q?LG=>.57+')024F:U8RFGHI,JV&9M12DN4S.46KYV9Z?ZF:MD$HTAIE=G=4O@+O<.J9P*D#GHFX19O=$U8(-0.4(2A+UOG6J<55.R$;/8JFM7;LGOMB>?. UA,794U1V;XK1=/340.;I<8=33D0T$++5.;6+%<Y8F.AYKBS)UA8$CT%LB8JL:R#)GZ E@JB85YN3D@/DNI+'=SK;QGFA-;J5H'04TKN@<,7#X.06;OXK 9UL7+&3VP&6P#B-@P>N9&X.U.8UQHVH()#,/1%B8FS2V=2<K:1?:B/?D1NDV1NB(?Q(?X3#',<CDG?SHZ4OU::>G:K5T')Q%<$PB(.;NIF@9(Z0Y7+6C;M52MDCYH=LI4<VI%'8UMQU$XP1CF0UYQ9D@KCK<OT4W9?S1X)*P +#<=CFA90'U*C*T989AUAE7%<ZJR#=3UE >I0@L<FY<3/Y/JDV?&18MXB X9DFG(1:W8F0RW+DX&G,2=:UFSD"; break; case 10000: SQL = ")X:49N-*?,17A,KG(5'N1CL=)$:(.>@)AD>H;QAJ#CK2AG;HG#3.YR,04<Q@$,7;&V5+<@7+;?3N+39#@9Z9UTOY;3?O3Y+.)S#1IMW+JC0Z6H+)X-J7N9E1/=0U;VR88A.V6A XM>.8R7MD&6>#-PR,;#B%6=<SKET(<XBVNXK.RF2B%OBJ?&2-:L36S>.&TG<Q=+@0JC3R?%L)V;2<3RK*R5Y9?2J,MEE<F&5%C;$=<SA@1+$33.?'77DZU4&GP#PR :K)QPV=8.Y+,-#)KH9.3L>OWH.G-XB;/W30H2@$71G,(B#M*10F1M.1%AO=AO.7ZG?#KARZ%M&E1G=<I9;TCAWPN9,X0H#O#>DCWCA4 .#,WO,2P&*S3-M-K67+& $5*OB,X0JV#31*H5-A)/*;JUY5:)0,83X+23%KL+I*6KV&YT<98BH6)(WFD-73NB$'RVQ$&,8.:/&QSQLV>ABC#>&X/=>ORF:WM+=OV,$W1,F5<#I3RH5G$;LVUUXN;B(9R4R&9;;@T/%#.ATWW8'XFJMBI2E N4DD4)Y+K5O)HAWTP3ZJ(?/1>#3Q)')0TD:L'TB(%PLZ07*4*PTYKA+PSN%94P0I:H-/14J?1;PX.1$;>IN8,2<B6&>6HYQHXIA@&W ;3@;=1%EB<(DQHB>+<P5-,:9:JKAN@OSL#KM1*0'>.8/+B$P/0 PMG1QYB6Q$* 5*S'-DKY59:P)(3/4H.)@CZ5@WK@X>*>>),'+N'YSG@(-LY;:23?Z.NKVL9#Q*0*H(C@S8L%>IAFOY/DE(KY*+(?%,Z'F>WT T AJAR/N GD2 1$RD?0Y5.Z5G+D'00WWD1F?E8<+YI#M)%;';@, VC.EYJ?'I=,&#>)891@U6<7>DUN=( '*.@C(=2X,R)5NI1IUMAOBG7KH:F8XV?W.?R/EAY&L/>;5Q'T9:YP ?4/#IXN9>*;F;(UPVZX8A$'QP7BA5:P+70))L>7(<13T12>>/,D-*V:=M2GP3Q$D6) A0E1* T&G=&M5SB0CJ3LNJ3U#8@PWS1MV:XL>*S/0)S?W8W 'YZM,:SAGZ/7,''8JUIN8<$?V %3S08#9,Y?AQ.OW8F<3 ?KTE/N88A;->&O<HWFR/CK6J03#UFX+@H%S;YF,$SURV@0 F90O/DO.=/':%N0<H5G@'SM=JNOU7RX>=*A1T*UB=D5J;7Z3BR2BTL'%80, ;O2,S=AC01N7F?6+1%H/)>F>QEYWS8RAB%AWL#=Q9WJCNXRH?TN+1:M $L:ALT 7F+@UG=Z ><2G%&<XVJ0*K# 6F(J0$UBG8*WL#-7@1G&<6KKQ-4/,2M.K0<ITJDAS-EE'UEM*MXKDW>&BO'8)$RXT 4K$*B48Y%/18#=S7.X+Q'S:>OO//M5((,V&RJYA'-.?UYS8$.QG-GQJJ@,XS/V7+&Q,Z7/EK4>E-E34%C@PR1Y/B:'TQ4#/T-FGP)QZ7DS=5,UQ7S-<# 7I(T8<M<*07C=,7%B5,S# <JV)8Z:EL&ADCK,.9D-6421*V=JX/O'2R7,==74&RT2GL3Y+ZE7(1S)XWEB)*,Y1U?;B8OT0 B659N5Y FURD;:WPH#/*L89X%BH>0NC64/ SZVUO0NU>*ZTTDXYT2@+B>O4.C:RC7F3,30?5-7W1/@'7 Y1,/YI8T6U,DR7::D5RJF2<GX;&R0WA:PB$G?9@%-O8U5;JG@V2426?4& JIJO*SHI=%+ET I/# M;?D1.>B*R(GSD/; LJ@W<ELB7'-$H PEX4Q'$D@DJ(2:E>('1(CV6$SJ9H.9-WY(E1MMO#X0V9>CD<DMA,=O':L7</W7<R98)2: E(F9W-CETB/+E'3E9K14'Q?X/,AE%A0X/RATK1/;E#BIH/;2)?2*WF2:6O'90KN%:0J&2H7QPA ESK&&709T7>/WU;0;39Z3SLQ#0PP%CC0HW.':CA*/*CG&#Y'<EB,K4T#)@+QJ;Q:Q/>'%Z- 00H=@AY)H%QP$.9;6Q'LK1K1U<C@AA$XJ?ED$(09#(DCO.I+=T8G.@5ZB+?0WSE',%R3JB/V <083W,-*JVCO#8$Q,T<7O:>M+GLB@SIVJ>Q%$.R=UR11/CCVPFM<5X$ :TB7&A>/:*5R7 8O)+$3-N?7+R .-F/T1NHR':U'+%%1WZ6P.8?PM+R X<&)4&6QW<H9EC#,SA<6NJ4PV<CJ4M;,X#L*R@N5?<L7B=<&SE@OT8NB<:?@U0FGE4>' K;-3&3Y$X4+00'V<7 ?B.-C@MHW3C5X>//#W4KO1SWL7T3WUX=>A3N,%;R2PBW*W8JO+:L1%SW&(HX;@ 57KFGK,UFZ551*MY7D03C*5?WG'98W4MVR:$)+()EG7)@I%NQ)Y RO5X1O&ZBU$>ZCOI ; >%U*UZM,RIQ)$L917F,SRO<#9E#:+K)+YN.5S6C0'7BI)%J/AZ(=N>A #EAK+9KR.C$, PXKY&VX1PX6949N(JUUPT=8V(4,,E ?0;I3I# 8QY6VZ;IL$/#CJKT?V$ 6Y=W<J#7#VE9%6 3V<OL4K6Y0<D%J$#/O;DKW;=C#1(LJI'@W<>BIA.8%<Z846.U5&#00PGQSGNJ<+6QZTW:;<S(>6OL+5A2'**=$X<GM3I&NV$*5DE?0Z+2?:/5%E='$,RSYAAL.#C9CI%0&I4B4250M23(X?8):YVD,,6;2*?X4M$SEMYL#60Z:AA*MMU*P1DB8/'W'%7;L$;KW77,-CN*,.7UO@<GXRG>O@ZW'TOFDU <C>>*&T>XCQOB5WVC71=MWE*BLV%#@',P5<E@JF=7LO0QX#=CI0Y6,LL8%&9:T>Q.%,O -RN96B*/CN8<NOIXO89X:Y600Y>BN;CC#P<V=8BU$I2K@OCJKMC1XTS*J>%KDGNTPWMJV?9/FXG6A&&JA#G.T?YV#N/05(*#I-2&4319,F9N@E,W1OOLU@.A:N)3Z8<C9/-ZA28-S7-S0*C DU6OOF6A6 >MI<D/)@Q=Z&X?.ZS& AW.HM2(0U83VF5:0U7-6L(3>S%H7G4W'AIU%QN /@Q*:>4WK65PZ(,#O-->E<+728*OLJ%G>8+>R.9-94@M)K*-HZ*1K0(,=OWT&0'$Y(<%Q#UR*UW#M.$=+E**6O$8NT/ED<Z@-%%J;(47?IL'0X>GQ%>D);J;6VC6>YZ I(=8'MX0)4Y9<Z+I,(/ J$FH4%5O@HPI<ME4:OC%QDKT=O&7#/JR 1TN(4RMI+PEF.3U(37+R)V3BKM;#/+5P<QHA*QCFH)54NS<3.93.W?H)1$$;?@LE%89=M(23)'ED%Q 8W#2O$160..0<U6OYIOXJ'#<LLDD7)TA.MK-K%PJDIAO?#IOW)M/D1%$2HG#,#RW0Z0Z$$SWT=DGT8*,%OV333L4ZA1LT=5Y;/BP% V%Y%1%E0)X+IQ@9(K<AU13DPP@>>M=Q?V9+?L90M,UPCQ,IW@%>2UA&(TRZRVI)<Y3#%X /-4Z@7VA2E8O-,)N<5#1G@+:CS=JP?OTJ-X9W%Z6)D8@V=KC37GGXI0UWMM#9XU;ZL'NE#-&8'7=HJ<KP+UNEX;E>P9,#3>OF*:3IXD@ON4 QJ0BF/ )<@M40S/+NYOG:-65#*QYDDJFB& ?8I%DV6VO.ILDKH1F&QV?&>K0R-HNL<<;CKP2;.'GGPUG6S>QZNY6DDNX43MENN(P2%@.NAKUDSQ+X(4H-2<@0NF3-8&P*=X.TCZS+%I>(<NI' YJ%SDE68X 7H64GX8#44MH?:X6MZ/ADJ7&PT,TM9:>&Q(AFU@SR#8-1DQW=JV?4F+PP?0Q=?#R*F:#QS6J,7W%H,?OL(5G1H77FRXW5$Q,:IEN4WE2H5V,%Y,5CI%M9@(/G@YV LRC>XTZ/VQR1XGAZ'Q9E' 8V$I9Q+5-%RKUVKZUO%/ $F@?9/YC$'.'>LZ5YR1I9<T@%F* BJAQ35SCHL@4RX<N(%4CPHC9&:QEXU,>N(LN*I@*9.81)A7E4LR7?::#2R5XN@0>=2C=0H3N1REZ?@+CAZA:Y8?FN;QH=V3/$K>,Y1+#G;T@7.+V$-X>Q8QD/391A#4.,XE1&7/PJKU5&HC7XKPO'QZ.' .$XFM4TH%>'IE(?32B&0@9XU3+N5Q HZ=**@V'&HZM39X1,>Q(M#B2W')7N ZKZIH#6Z+GFDDO%ZB.K0ZCZ'7X+VQJ>;GVI8O>T3U5$WPGUTL&YQH>MIU7 :WZ)EF' /BLIN9G(DI3(D+N%)=X<KBS93>MN /1DPFH-(KNZ%K)<O;%333M3 WZU>L?JRJD,2GB-;(+6:G TK?,6G4B7%=)'KR5S9V9SD<IP/TB)6=W()KYZ7 &ZGDR=;TA8BW?64'90SC#NZ8U,-UD75V$E$XX-2W.7Q#L%QAEA*R/1PVL$=A:U,S+6J HT$*AI? YYM+F5NT0 8NPIB3<2W/'Q*$B=67UADI1 (BR*@H(Q>1A:$;95&HVD1$5P<W.)RH#DCSK-LHJ)8)I<W0$B/<R5-DGMT0BM+,Y<$6(9Z@IEX,&CLQ>,2#R=V+TT*&V7;--B<==.,3;#W8OC?Y'/$T,BR(27CKJN-V$-%EQ>T6VFL)/4#8YSI+LFYDTLS=4*) R):,AX(YDY/676XRM?88VLE-/O/N6&-%#/6:#S,E9%:N59$$3OW6XTQQ K:93XOYE-K08$*>HR=-33394WOGK<1LW/;$5BC:=/;O.:I3G P2<F<NG)DW:HK&?(UL)UHD:F=<.WH&+EWM+VUOJJ74D<52B479L-M/$NZS3%0A>0)+D+5<TCKZK0);A93BK61(&XMRG8)&:90CUV.+O1U3RYPT0HARQ$DHNTT.7R9Q'ZWJQ$5&%0W3E1%(6WR.4+;4(XS3YAG(OE$T;#M9XY' FLG#2 Q<(13:J<%N6D;I&<QX4X(:>=@;+V%G#W0A+L9$HP.C2UR9WPM*T+=&OCKY6L6>Q8&PG2FL*B 8$7-:F?1'I,D6L%?0H8UG$EH @ :D+(TP7/<?A?SEDVI% 2L%SCH*-Y'0N0,-*>S>XK3Q-&'(37A0(%T0$IE5 <YF*O-CSAI?(84M6$8('1PCS%Z:'QDG6).9Q6,BPQOU$JP'#'ESH#08H.3.A&T-Y6T8=#VI2..KT)M)X'1VYR@ <:7R41@R.12@$5ET,/4&U9/QS?QPF>$LQ(F+X/<M>VK(,P5Q:0TY?F;D8CS&3;++W0*/T2'0-<,DD-N$'XNB;?$'%-:2#HD>#$1 8;QUUMPN12IV<FB<:=XG-8'SCI%*NR;I;:NF*#-.0X /--@4SP'G=>0AY<GPAF=WFRN8=;-BK<6AX$2+CE%LHO,>QNJG)L:GWJ;@DH-9) NW=L$?FA=BV)O+.U8N-W91T?*Y#)H&1IV9;X57A&06;QYX5?$*H2K(X;V) *K2LE1BLD58@SO'AVYJXHQBTLAN=Z;?J3MN<T.MJN(H#4A&5@6*I/J'>U/7Y&/WD6G$-$;FQF*9%7R=#=Z8'PYP)BW<MFV%O ,O5%BPS++B4E24-XH *-+?Y97<' 9U8I9MF*4&&V#WI6#.FU+YMW/:E?6KPB9:E?KG;A7T51MZ8DO*>HM8WT.TRYQ=C5C)57$;;%Y9CSQDM@)3(>.9X&W&;AXZ5.8CWT49=-Q%MOY28NCHS=YP>*-P7OZ8I7QJII%BI+17*#>Z@X2FWGCF>LA=KTAG'>1-JIO-BF6G7:7'3=MDR;U7L<05R$/GBAT+0G>8B?%JY4'=&KJP6MK78,+TJ7VSQYQDV.FE+FO@HO;V$=I+EMI-E,Y9Q0EF6Y<&.NBC<X9?RQ N5.E-3#;UQAKDI=W#&FC2#/@IYS$KK2,KS):QBKNGM=JSC$GZ:M=>5(?C6K0)/OEA8P6>QP#Z,L-)M1Q3,U%RP?'V+SW#L1,/M2 26(2 K5/U#O>0L(GI@/:<:-Y?>X?%%8E&4$>K@AH9AWX/$Q525 NZ0F>XF'X<G&X'U<XHQLNNQYG#P*MIUVFN#H$2)G>P>ZIQH>6##LJ1XR$F8 ,1)J00O9II9&T9-GE?5:)DI'Q><6'CQ0*.PO527)@U*ANQTQ=?9TZ <VY?-('VB6LU6U9NJCCKY=D6>;;9:W0NM9GZ1-0&/#Z1/(X5WPX1'P3AWNO7O-/5=FK5INFO<F74<KYRZCXGZ'#C8UO@F,63$TVM(?RPDY8)/Y*32,.G+V8),Y'22R,X?'G28WH>GY9?%M-6Y6')?'G31,TUR%WD%O4DTZO->F;WLL8('187/9AZG;DP@D>&9:SXO$F:3*,)H?R'7BI)PJ%3XE9&( @54W&;SB-K'AK&J3?>.=3E#R2#2T5:LTV?R3*R.RWC:9S5F%9#HY+EB95Z*CD1;)4B >(Y<KZ;Z:6>ZE:) 1N2X0=-4R3(1/4Z5+P(6&Z+((LI=&B( S;I+GJ1PRZLI&V*FH, )<D9L-/-(TR6,F3IF1=LFA1$=J 7)'P(OYX.6PG)JQ%GL#Q6K*O5<H0-2Y?# ?B1WT9%S/@IAXSPHLG0.HX;1KCSJMJ.V<7EF,'QUP$>1@>%0NFDFTFF U0X#2M:6.I&,T4MN$&G&*7&2YZ @.?3.1B?4VU)>RX'(Y TM9#B-.UALZIFSD@6KS?-9WLB@SY8/RK5F>B@$P>-'B$LAB:($3DWZ3R5;03EQ1#OT9>:)88(Y-HCWLVEG:E'<Q5TQZ@DAIIA3T&EB68C.@99XR&VRYSR=6@JLK0(+P%N31T9OH,N<8#A P=XS5;'I,EW:)BY'N4:UOW3P$Q3NC3C#?U2'#I#O>$%.X$Z+1:+-Y9C<(-F7YBU'A>XB?:P-KPI,*XA0.LFE3 U3EG,/.(5/&-VS@+:R=56M>MG-%RFEU8 3DF#FF?S;GKX,VB;5&RCQS=ULT,M<.GK%7/#X@;D;O0=P;0<VA+O>D;8G.M *.MR>,5'GQESI&R@8+;Q?WZ$R&05FC$RAIK1,TD@ GD.1ID3YM<K#;KV ?:P&8J*WLD1?W8LF(I..HZOWL,)A3YP?D-3I5?JFT,Z(=/%4RH%.,&Q<'-U+16D)=IGX@:.:;B;L5 *R,LV(=7UKB%>$;LZ<-UTA($,JCNC7%5#9%2 O.#MF&4Z'=L9:T'9M%52XN%S@WJO2H(;J9<LR:'I(J7D V:X,L>,#TU%@LZ9UC&T%45;I6N1+ETNFRY=K.W847HZ>A<3,598-W0CEVH, XJA:>-N/.LG2Y<F==2B1=<=B$<V.D2N7F-JE#U*@X=F6B 88O+G6%5?8D.$J8K)C(7P/.*(UR(?S-+-DG6F5(3@A Q%B8PZL=.V+AC:52X&? .>P+IA./8WXV@LF6FYLV7<<V'7ACS)1G*P*.TEZ'@ QUU RNVRAFTFTW>2,+6OW$H=T'&%Y?DR-'LE>0C0$BG'9-NNW*0YZT;91M7@M @11F&R1Y7Y?2')B B/6LTD41WB&QZO1-A?+V+00N#=K+T3;QXLZRK? %-#%=#=FSQ37OO-%SJSSTE7SC2E1K8<*.5.TK97)SZLGM?,V-T&.QA<>.&D$;,RA@',HVZCD<)658'3>KEZ$-P,S7Y 00;7X@CYPXBNCV3.($'YX1/VSI?1?-9@@KX@=42'@ 1(*KQ?/G'BJNJ4 'S2XEOLD<N6-H-Q7ZOS:+$>94-<D2NY/Y,;J6#@U<9S:)43<G8'<A6MUPSFP'I$(2ZMWVF>0B@#LA&S3ZU=;8A9@BT/N3&7XSL*7V7CCBI+8L20T/UMM@KA7;Q(JD?@K,I(8SSQ1/WE<.& R+1D2T:YH9B?7IC M&B@(4ZAYFOJXMBRWCI(IDJB055L9&6,++GCIDP&TN9'DX%TC$5/,Y246H*@K9N#Z+RG $&L7.K7@SY.-/3S6?9,SA8L%J@O*X)W+*20-@QA2@H+BWH7(H4-S /U9QFUZ;KCK-QJF&$+M$ZES@YEM;4KU7609YU3$XI%$I+<YEKY1QW;Q&2Y.)R>$;R'MG4H>8AE6P<ZB8-S&J'>62:F:QBE'':WMT9HU,VBKXP9(RV#'JOY) #:S8>KV/A9NVZZW&RA<-#E$WY2Z9?.H5P%#7BO?<=.=+W67 V>J1E?A(X'?=1;'207R68P$Z6 9+$/)5AIUW)C-7>++JD?MBW.P;W*Z,%>VLOIO/R(&=48Z0D04.0Y?T1**S(6*+76E$)#%@7V>>KM:O0=7WQ0,TI&DN85K6TQW@3JMR3<F473Z8$?#-8@/&MLEZS(D(O:?/9%G:-7?AR%ZPWHGW6F0ERF4)PFDIV'*>@RV3T>NOK)E@ ).V&YTK&V7HWJYTWX&L><.T:U>D4W E>41B56Z@*SN(*H&4:>&6@F<#U(KI4DI7UY2#<BHDD1@JK&UN),M(D&2-$4(RHR@T?LTPX-1@',*ECUHLN6;:96:TY/JJ&GRD,WEMROIC23,1)0I:5O4+MNO>Y$#U/IF3TG9/F@H6(SW#>?7DL4+IOM.X(D6K#UY;DPRS@H7NO.#Z3R283#,4P<6''.P6%$>P ,Z0%8::3NE0*G:92V?)4':P,@3684G'SH=-C%&%-'+%EUGHD3ZR+(J$ ?WH9$S(EXXC/G709SHA6+FMB,5*H(IHU42);U;:U+U>@<U#3+WM<$W70.>Z)XO61$%J:?/BA/AH&WX0EKV'<DK<,M2JVCBYK*#>G:BUQX%:;6ECOT&@ 3/>#XF./F/LR'.I)Y;J8?X$4UCL!?NH?<12G(WF1R(B/6R AF $JZHI8@#Y(BVUQ+*0W:<A@SX@/HRH$9;P%D8VG-P< 3ZE75)4A0;8=*-<&((. HN'/O1W?=9V*05:5I4T92)I:C#2+70TIV('&0,>A,S=@5/<)DU9I#+SX;N 6$L :?<T)1;T)EV7>7ML@C1>/6JEE2 GP8Z8#@6G08E J'FN(D6 %8-GKSU(,4$X+SH5D+K=;2;',MXP8XQ7+N-PM A7A#8>3S5<M KVFB%7*/JH,FVK0T4IL(4:J0E1:21ZB?D3XQ=6;T:FRWT!?FZ>Q*N6M'>LGB'2%8U:>.(K>I>%(:Q>Q5@)PQW?=M8=7L(8X*XT/>SB2EMAYM#,UYQFU2O7.02.5PEZ2.&(+P@*Z>WY'8 MYXKQIP.DAA.Z8=>TQ?%W55 H-DE4-4Y1?$R.N=2#G0492)VIEVN&?R?<3HS=/J+7R.XN!? WZ:LI35P$EI1M1#;WSIYM:Z1<*Z+QADS=KV4'4'+U''</=FX4U$ S'U+IX+0KK,Q/$YL*QC<Y<WL/352J1(?W#&NZAMG.3*/V%%4PZ8ZWEW;-FD1#'JKP8'EK#3I$OM%=QWY.-*5'.LN5.JKJ(XUN+M$ABU1.1,=7-@BRJ5#5W&9@P#SJ P5#*N10JD=ZDLBZ;6D/2/'<5C&Q#CQV3ZW-)=ZKJ61,'83Z%6(:P=XD/4 A NA#'U>1;;FB?1D3KD;S24>7.>?691'=YTCV//G<&,BR?'/*$XI+J:G;' BL#$36K*(KDJ8D'UI+2QGKS;TZX%GR@'>=WJH)EP;-ZVR.?HL<94INMTF3>Q8?:OD,H9I%4WN,($TH</:TJHTRV94X-JZPTE0P*G>FJ9.W9L47VIW03*T-M3W?V@B#MRR=Z3%3=65E2)*1>GK,C%*.FZ5F3VA2I1 GG$3 MLO67=GB*5PXLH)*7#KI0 3TJ0KN>B/(:,I4?C=%,RFRU/+,DPNLKS.;2<X3$=C6/EN&Y1 ?/R;@7='U%+ZBSO/+JT#+6AZ20IGSKS%+Y3.Y7A#-AS$<?.F;,L &YH.?()'5GP3L730XK0:#;+2?GY/A3L?9$'2PNZELRWX>SYJ@N8JE'+K$BOT:@9PC-4K W$%#OEJ+<&/3+V7.GTFUT;F*SJ/DEUDVFX7Y?D)+2U(6;5IN/TU. (&6<0&LC,K3W%H/-GNU0$)H*+<$Q*SL0YI91QU.%VRB5#7O8C<IY Y@>6.88%O8M@Z#>%2N T>U@Y2/@19V?Z8NRZNUQ.EGE8M.JXT*).=@/F#ED37=0*(,FUN;X2F<N+9<N2<Y6$)30<I.7FNMF6M4DW1>Q%6KYF1M$<EV.%(WPSZWZF-:/PP"; break; default: throw -1; }} }; class Benchmark : public Script { IntVarArray int_vars; StringVarArray str_vars; public: static bool sat; Benchmark(Benchmark& s): Script(s) { int_vars.update(*this, s.int_vars); str_vars.update(*this, s.str_vars); } virtual Space* copy() { return new Benchmark(*this); } Benchmark(const StringOptions& so): Script(so) { // constraint str_len(expr) > 0; // constraint blank1 = str_pow(" ", n); // constraint blank2 = str_pow(" ", m); // constraint sql = // pref ++ expr ++ blank1 ++ "=" ++ blank2 ++ expr ++ suff // Variables. StringVar pref(*this, 0, so.N); StringVar suff(*this, 0, so.N); StringVar expr(*this, 0, so.N); StringVar blank1(*this, 0, so.N); StringVar blank2(*this, 0, so.N); StringVar pref_expr(*this, 0, so.N); StringVar blank_expr(*this, 0, so.N); StringVar lhs(*this, 0, so.N); StringVar rhs(*this, 0, so.N); StringVar eq (*this, 0, so.N); StringVarArgs sva; sva << pref << suff << expr << blank1 << blank2 << pref_expr << blank_expr << lhs << rhs << eq; str_vars = StringVarArray(*this, sva); IntVar n(*this, 0, so.N); IntVar m(*this, 0, so.N); IntVar l(*this, 0, so.N); IntVarArgs iva; iva << n << m << l; int_vars = IntVarArray(*this, iva); // Constraints. length(*this, expr, l); length(*this, blank1, n); length(*this, blank2, m); rel(*this, l > 0); NSBlocks v({NSBlock(NSIntSet(' '), 0, so.N)}); // NSBlocks w({NSBlock(NSIntSet(33, 90), 0, so.N)}); // rel(*this, expr, STRT_DOM, w); rel(*this, blank1, STRT_DOM, v, 0, so.N); rel(*this, blank2, STRT_DOM, v, 0, so.N); rel(*this, pref, expr, STRT_CAT, pref_expr); rel(*this, pref_expr, blank1, STRT_CAT, lhs); rel(*this, lhs, StringVar(*this, "="), STRT_CAT, eq); rel(*this, blank2, expr, STRT_CAT, blank_expr); rel(*this, blank_expr, suff, STRT_CAT, rhs); rel(*this, eq, rhs, STRT_CAT, StringVar(*this, so.SQL)); // Branching. lenblockmin_lllm(*this, str_vars); // sizemin_llul(*this, str_vars); } virtual void print(std::ostream& os) const { sat = true; for (int i = 0; i < int_vars.size(); ++i) if (int_vars[i].assigned()) os << "int_var[" << i << "] = " << int_vars[i].val() << "\n"; else os << "int_var[" << i << "] = " << int_vars[i] << "\n"; for (int i = 0; i < 5; ++i) if (str_vars[i].assigned()) os << "string_var[" << i << "] = \"" << str_vars[i].val() << "\"\n"; else os << "string_var[" << i << "] = \"" << str_vars[i] << "\"\n"; os << "----------\n"; } }; bool Benchmark::sat = false; int main(int argc, char* argv[]) { int n = atoi(argv[1]); StringOptions opt((string("*** sql ") + argv[1] + string(" ***")).c_str(), n); opt.solutions(1); Script::run<Benchmark, DFS, StringOptions>(opt); switch (n) { case 250: case 1000: case 5000: assert (!Benchmark::sat); break; default: assert (Benchmark::sat); } return 0; }
24,063
18,677
#include "preamble.h" #if MODEL == 5 #include <stdlib.h> #include <math.h> #include <string.h> #include "filzbach.h" void pause(){PAUSE} /************************************************************/ /* function headers */ /************************************************************/ void fake_data(); void read_data(); void setup_parameters(); void fit_model(); void final_output(); /************************************************************/ void fake_data() { /* use this to create fake data to test your analysis, before you try real data */ /* how many data? */ int numdata = 999; /* how many species? */ int numsp = 10; /* generate random means. */ /* do we get these parameters back out again? */ table_create("trueparams"); table_addcolumn("trueparams","spid"); table_addcolumn("trueparams","lambda"); for(int ss = 0; ss < numsp; ss++) { table_writevalue("trueparams", "spid", ss, ss); table_writevalue("trueparams", "lambda", ss, 1.0+random(0.0,9.0)); } table_create("fakedata"); table_addcolumn("fakedata","spid"); table_addcolumn("fakedata","count"); for(int ii = 0; ii < numdata; ii++) { /* generate random species */ int spp = random_integer(0,numsp-1); /* draw random value for y from poisson distribution with appropriate mean and sdev */ double true_lambda = table_getvalue("trueparams", "lambda", spp); int y = poisson_draw(true_lambda); /* write to fake data table */ table_writevalue("fakedata", "spid", ii, spp); table_writevalue("fakedata", "count", ii, y); } table_output("fakedata","./workspace/eg05_poisson_multispp_fakedata.txt"); table_output("trueparams","./workspace/eg05_poisson_multispp_trueparams.txt"); return; } /************************************************************/ void read_data() { table_read("mydata","./workspace/eg05_poisson_multispp_fakedata.txt",2); PAUSE return; } /************************************************************/ void setup_parameters() { /* first, figure out what is the number of species */ int numdata = table_numrows("mydata"); int numsp = (int)table_getcolumnmax("mydata","spid") + 1; /* each line defines one new parameter for our model */ parameter_create_vector("lambda", 0.0010, 200.0, 100.0, 1, 0, 1, numsp); /* set parameters for the hierarchical distribution? */ parameter_create("lambda_mean",0.0010,200.0,100.0,1,0,1); parameter_create("lambda_sdev",0.0010,2.0,0.20,1,0,1); parameter_showall(); PAUSE return; } /************************************************************/ void likelihood() { /* writes the log-likelihood given current parameter values */ /* set sum over log-likelihood to zero */ set_metr_ltotnew(0.0); set_metr_number_ok(0); /* get model parameters from list held by metropolis header */ /* loop over data */ int numdata = table_numrows("mydata"); int numsp = 0; for(int ii = 0; ii < numdata; ii++) { /* get observed count and species id */ int count = (int)table_getvalue("mydata","count",ii); int spp = (int)table_getvalue("mydata","spid",ii); if (spp > numsp) numsp = spp; /* get parameter for this species */ double prob1 = poisson_density(count, cv("lambda",spp)); inc_metr_ltotnew(log(prob1)); inc_metr_number_ok(1); } numsp += 1; /* loop over parameters for hierarhical modelling */ double grandmean = cv("lambda_mean"); double grandsdev = cv("lambda_sdev"); for(int spp = 0; spp < numsp; spp++) { /* get param value for this species */ double mean = cv("lambda",spp); /* calc prob1 */ double prob1 = normal_density(log(mean),log(grandmean),grandsdev); inc_metr_ltotnew(log(prob1)); } return; } /************************************************/ void final_output() { /* create link to file */ char fname[100]; /* create file name for output -- outp is the 'path' */ get_filzbach_path(fname, 100); /* now your bit to add to the path */ strcat(fname,"_my_output.txt"); /* print internal table out to file with name taken from above */ table_output("mydata",fname); return; } /* ************************************************* */ /* The control function that calls everything else. */ /* ************************************************* */ int main() { atexit(pause); // set the likelihood function pointer pfn_likelihood = &likelihood; initialize_filzbach(); name_analysis("eg05_poisson_multispp_00"); fake_data(); // either fake data (to test routine) or read data (to do for real) read_data(); setup_parameters(); //set_chains(3); runmcmc(5000, 5000, 5000, 5000); final_output(); } #endif
4,618
1,630
/* * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights * reserved. * Copyright (C) 2008, 2009, 2010, 2011 Google Inc. All rights reserved. * Copyright (C) 2011 Igalia S.L. * Copyright (C) 2011 Motorola Mobility. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. 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 "core/editing/serializers/StyledMarkupSerializer.h" #include "core/css/StylePropertySet.h" #include "core/dom/Document.h" #include "core/dom/Element.h" #include "core/dom/Text.h" #include "core/dom/shadow/ElementShadow.h" #include "core/editing/EditingStyle.h" #include "core/editing/EditingUtilities.h" #include "core/editing/VisibleSelection.h" #include "core/editing/VisibleUnits.h" #include "core/editing/serializers/Serialization.h" #include "core/html/HTMLBodyElement.h" #include "core/html/HTMLElement.h" #include "wtf/text/StringBuilder.h" namespace blink { namespace { template <typename Strategy> TextOffset toTextOffset(const PositionTemplate<Strategy>& position) { if (position.isNull()) return TextOffset(); if (!position.computeContainerNode()->isTextNode()) return TextOffset(); return TextOffset(toText(position.computeContainerNode()), position.offsetInContainerNode()); } template <typename EditingStrategy> static bool handleSelectionBoundary(const Node&); template <> bool handleSelectionBoundary<EditingStrategy>(const Node&) { return false; } template <> bool handleSelectionBoundary<EditingInFlatTreeStrategy>(const Node& node) { if (!node.isElementNode()) return false; ElementShadow* shadow = toElement(node).shadow(); if (!shadow) return false; return shadow->youngestShadowRoot().type() == ShadowRootType::UserAgent; } } // namespace using namespace HTMLNames; template <typename Strategy> class StyledMarkupTraverser { WTF_MAKE_NONCOPYABLE(StyledMarkupTraverser); STACK_ALLOCATED(); public: StyledMarkupTraverser(); StyledMarkupTraverser(StyledMarkupAccumulator*, Node*); Node* traverse(Node*, Node*); void wrapWithNode(ContainerNode&, EditingStyle*); EditingStyle* createInlineStyleIfNeeded(Node&); private: bool shouldAnnotate() const; bool shouldConvertBlocksToInlines() const; void appendStartMarkup(Node&); void appendEndMarkup(Node&); EditingStyle* createInlineStyle(Element&); bool needsInlineStyle(const Element&); bool shouldApplyWrappingStyle(const Node&) const; StyledMarkupAccumulator* m_accumulator; Member<Node> m_lastClosed; Member<EditingStyle> m_wrappingStyle; }; template <typename Strategy> bool StyledMarkupTraverser<Strategy>::shouldAnnotate() const { return m_accumulator->shouldAnnotate(); } template <typename Strategy> bool StyledMarkupTraverser<Strategy>::shouldConvertBlocksToInlines() const { return m_accumulator->shouldConvertBlocksToInlines(); } template <typename Strategy> StyledMarkupSerializer<Strategy>::StyledMarkupSerializer( EAbsoluteURLs shouldResolveURLs, EAnnotateForInterchange shouldAnnotate, const PositionTemplate<Strategy>& start, const PositionTemplate<Strategy>& end, Node* highestNodeToBeSerialized, ConvertBlocksToInlines convertBlocksToInlines) : m_start(start), m_end(end), m_shouldResolveURLs(shouldResolveURLs), m_shouldAnnotate(shouldAnnotate), m_highestNodeToBeSerialized(highestNodeToBeSerialized), m_convertBlocksToInlines(convertBlocksToInlines), m_lastClosed(highestNodeToBeSerialized) {} template <typename Strategy> static bool needInterchangeNewlineAfter( const VisiblePositionTemplate<Strategy>& v) { const VisiblePositionTemplate<Strategy> next = nextPositionOf(v); Node* upstreamNode = mostBackwardCaretPosition(next.deepEquivalent()).anchorNode(); Node* downstreamNode = mostForwardCaretPosition(v.deepEquivalent()).anchorNode(); // Add an interchange newline if a paragraph break is selected and a br won't // already be added to the markup to represent it. return isEndOfParagraph(v) && isStartOfParagraph(next) && !(isHTMLBRElement(*upstreamNode) && upstreamNode == downstreamNode); } template <typename Strategy> static bool needInterchangeNewlineAt( const VisiblePositionTemplate<Strategy>& v) { return needInterchangeNewlineAfter(previousPositionOf(v)); } template <typename Strategy> static bool areSameRanges(Node* node, const PositionTemplate<Strategy>& startPosition, const PositionTemplate<Strategy>& endPosition) { DCHECK(node); const EphemeralRange range = createVisibleSelection( SelectionInDOMTree::Builder().selectAllChildren(*node).build()) .toNormalizedEphemeralRange(); return toPositionInDOMTree(startPosition) == range.startPosition() && toPositionInDOMTree(endPosition) == range.endPosition(); } static EditingStyle* styleFromMatchedRulesAndInlineDecl( const HTMLElement* element) { EditingStyle* style = EditingStyle::create(element->inlineStyle()); // FIXME: Having to const_cast here is ugly, but it is quite a bit of work to // untangle the non-const-ness of styleFromMatchedRulesForElement. style->mergeStyleFromRules(const_cast<HTMLElement*>(element)); return style; } template <typename Strategy> String StyledMarkupSerializer<Strategy>::createMarkup() { StyledMarkupAccumulator markupAccumulator( m_shouldResolveURLs, toTextOffset(m_start.parentAnchoredEquivalent()), toTextOffset(m_end.parentAnchoredEquivalent()), m_start.document(), m_shouldAnnotate, m_convertBlocksToInlines); Node* pastEnd = m_end.nodeAsRangePastLastNode(); Node* firstNode = m_start.nodeAsRangeFirstNode(); const VisiblePositionTemplate<Strategy> visibleStart = createVisiblePosition(m_start); const VisiblePositionTemplate<Strategy> visibleEnd = createVisiblePosition(m_end); if (shouldAnnotate() && needInterchangeNewlineAfter(visibleStart)) { markupAccumulator.appendInterchangeNewline(); if (visibleStart.deepEquivalent() == previousPositionOf(visibleEnd).deepEquivalent()) return markupAccumulator.takeResults(); firstNode = nextPositionOf(visibleStart).deepEquivalent().anchorNode(); if (pastEnd && PositionTemplate<Strategy>::beforeNode(firstNode).compareTo( PositionTemplate<Strategy>::beforeNode(pastEnd)) >= 0) { // This condition hits in editing/pasteboard/copy-display-none.html. return markupAccumulator.takeResults(); } } // If there is no the highest node in the selected nodes, |m_lastClosed| can // be #text when its parent is a formatting tag. In this case, #text is // wrapped by <span> tag, but this text should be wrapped by the formatting // tag. See http://crbug.com/634482 bool shouldAppendParentTag = false; if (!m_lastClosed) { m_lastClosed = StyledMarkupTraverser<Strategy>().traverse(firstNode, pastEnd); if (m_lastClosed && m_lastClosed->isTextNode() && isPresentationalHTMLElement(m_lastClosed->parentNode())) { m_lastClosed = m_lastClosed->parentElement(); shouldAppendParentTag = true; } } StyledMarkupTraverser<Strategy> traverser(&markupAccumulator, m_lastClosed); Node* lastClosed = traverser.traverse(firstNode, pastEnd); if (m_highestNodeToBeSerialized && lastClosed) { // TODO(hajimehoshi): This is calculated at createMarkupInternal too. Node* commonAncestor = Strategy::commonAncestor( *m_start.computeContainerNode(), *m_end.computeContainerNode()); DCHECK(commonAncestor); HTMLBodyElement* body = toHTMLBodyElement(enclosingElementWithTag( Position::firstPositionInNode(commonAncestor), bodyTag)); HTMLBodyElement* fullySelectedRoot = nullptr; // FIXME: Do this for all fully selected blocks, not just the body. if (body && areSameRanges(body, m_start, m_end)) fullySelectedRoot = body; // Also include all of the ancestors of lastClosed up to this special // ancestor. // FIXME: What is ancestor? for (ContainerNode* ancestor = Strategy::parent(*lastClosed); ancestor; ancestor = Strategy::parent(*ancestor)) { if (ancestor == fullySelectedRoot && !markupAccumulator.shouldConvertBlocksToInlines()) { EditingStyle* fullySelectedRootStyle = styleFromMatchedRulesAndInlineDecl(fullySelectedRoot); // Bring the background attribute over, but not as an attribute because // a background attribute on a div appears to have no effect. if ((!fullySelectedRootStyle || !fullySelectedRootStyle->style() || !fullySelectedRootStyle->style()->getPropertyCSSValue( CSSPropertyBackgroundImage)) && fullySelectedRoot->hasAttribute(backgroundAttr)) fullySelectedRootStyle->style()->setProperty( CSSPropertyBackgroundImage, "url('" + fullySelectedRoot->getAttribute(backgroundAttr) + "')"); if (fullySelectedRootStyle->style()) { // Reset the CSS properties to avoid an assertion error in // addStyleMarkup(). This assertion is caused at least when we select // all text of a <body> element whose 'text-decoration' property is // "inherit", and copy it. if (!propertyMissingOrEqualToNone(fullySelectedRootStyle->style(), CSSPropertyTextDecoration)) fullySelectedRootStyle->style()->setProperty( CSSPropertyTextDecoration, CSSValueNone); if (!propertyMissingOrEqualToNone( fullySelectedRootStyle->style(), CSSPropertyWebkitTextDecorationsInEffect)) fullySelectedRootStyle->style()->setProperty( CSSPropertyWebkitTextDecorationsInEffect, CSSValueNone); markupAccumulator.wrapWithStyleNode(fullySelectedRootStyle->style()); } } else { EditingStyle* style = traverser.createInlineStyleIfNeeded(*ancestor); // Since this node and all the other ancestors are not in the selection // we want styles that affect the exterior of the node not to be not // included. If the node is not fully selected by the range, then we // don't want to keep styles that affect its relationship to the nodes // around it only the ones that affect it and the nodes within it. if (style && style->style()) style->style()->removeProperty(CSSPropertyFloat); traverser.wrapWithNode(*ancestor, style); } if (ancestor == m_highestNodeToBeSerialized) break; } } else if (shouldAppendParentTag) { EditingStyle* style = traverser.createInlineStyleIfNeeded(*m_lastClosed); traverser.wrapWithNode(*toContainerNode(m_lastClosed), style); } // FIXME: The interchange newline should be placed in the block that it's in, // not after all of the content, unconditionally. if (shouldAnnotate() && needInterchangeNewlineAt(visibleEnd)) markupAccumulator.appendInterchangeNewline(); return markupAccumulator.takeResults(); } template <typename Strategy> StyledMarkupTraverser<Strategy>::StyledMarkupTraverser() : StyledMarkupTraverser(nullptr, nullptr) {} template <typename Strategy> StyledMarkupTraverser<Strategy>::StyledMarkupTraverser( StyledMarkupAccumulator* accumulator, Node* lastClosed) : m_accumulator(accumulator), m_lastClosed(lastClosed), m_wrappingStyle(nullptr) { if (!m_accumulator) { DCHECK_EQ(m_lastClosed, static_cast<decltype(m_lastClosed)>(nullptr)); return; } if (!m_lastClosed) return; ContainerNode* parent = Strategy::parent(*m_lastClosed); if (!parent) return; if (shouldAnnotate()) { m_wrappingStyle = EditingStyle::wrappingStyleForAnnotatedSerialization(parent); return; } m_wrappingStyle = EditingStyle::wrappingStyleForSerialization(parent); } template <typename Strategy> Node* StyledMarkupTraverser<Strategy>::traverse(Node* startNode, Node* pastEnd) { HeapVector<Member<ContainerNode>> ancestorsToClose; Node* next; Node* lastClosed = nullptr; for (Node* n = startNode; n && n != pastEnd; n = next) { // If |n| is a selection boundary such as <input>, traverse the child // nodes in the DOM tree instead of the flat tree. if (handleSelectionBoundary<Strategy>(*n)) { lastClosed = StyledMarkupTraverser<EditingStrategy>(m_accumulator, m_lastClosed.get()) .traverse(n, EditingStrategy::nextSkippingChildren(*n)); next = EditingInFlatTreeStrategy::nextSkippingChildren(*n); } else { next = Strategy::next(*n); if (isEnclosingBlock(n) && canHaveChildrenForEditing(n) && next == pastEnd) { // Don't write out empty block containers that aren't fully selected. continue; } if (!n->layoutObject() && !enclosingElementWithTag(firstPositionInOrBeforeNode(n), selectTag)) { next = Strategy::nextSkippingChildren(*n); // Don't skip over pastEnd. if (pastEnd && Strategy::isDescendantOf(*pastEnd, *n)) next = pastEnd; } else { // Add the node to the markup if we're not skipping the descendants appendStartMarkup(*n); // If node has no children, close the tag now. if (Strategy::hasChildren(*n)) { ancestorsToClose.push_back(toContainerNode(n)); continue; } appendEndMarkup(*n); lastClosed = n; } } // If we didn't insert open tag and there's no more siblings or we're at the // end of the traversal, take care of ancestors. // FIXME: What happens if we just inserted open tag and reached the end? if (Strategy::nextSibling(*n) && next != pastEnd) continue; // Close up the ancestors. while (!ancestorsToClose.isEmpty()) { ContainerNode* ancestor = ancestorsToClose.back(); DCHECK(ancestor); if (next && next != pastEnd && Strategy::isDescendantOf(*next, *ancestor)) break; // Not at the end of the range, close ancestors up to sibling of next // node. appendEndMarkup(*ancestor); lastClosed = ancestor; ancestorsToClose.pop_back(); } // Surround the currently accumulated markup with markup for ancestors we // never opened as we leave the subtree(s) rooted at those ancestors. ContainerNode* nextParent = next ? Strategy::parent(*next) : nullptr; if (next == pastEnd || n == nextParent) continue; DCHECK(n); Node* lastAncestorClosedOrSelf = (lastClosed && Strategy::isDescendantOf(*n, *lastClosed)) ? lastClosed : n; for (ContainerNode* parent = Strategy::parent(*lastAncestorClosedOrSelf); parent && parent != nextParent; parent = Strategy::parent(*parent)) { // All ancestors that aren't in the ancestorsToClose list should either be // a) unrendered: if (!parent->layoutObject()) continue; // or b) ancestors that we never encountered during a pre-order traversal // starting at startNode: DCHECK(startNode); DCHECK(Strategy::isDescendantOf(*startNode, *parent)); EditingStyle* style = createInlineStyleIfNeeded(*parent); wrapWithNode(*parent, style); lastClosed = parent; } } return lastClosed; } template <typename Strategy> bool StyledMarkupTraverser<Strategy>::needsInlineStyle(const Element& element) { if (!element.isHTMLElement()) return false; if (shouldAnnotate()) return true; return shouldConvertBlocksToInlines() && isEnclosingBlock(&element); } template <typename Strategy> void StyledMarkupTraverser<Strategy>::wrapWithNode(ContainerNode& node, EditingStyle* style) { if (!m_accumulator) return; StringBuilder markup; if (node.isDocumentNode()) { MarkupFormatter::appendXMLDeclaration(markup, toDocument(node)); m_accumulator->pushMarkup(markup.toString()); return; } if (!node.isElementNode()) return; Element& element = toElement(node); if (shouldApplyWrappingStyle(element) || needsInlineStyle(element)) m_accumulator->appendElementWithInlineStyle(markup, element, style); else m_accumulator->appendElement(markup, element); m_accumulator->pushMarkup(markup.toString()); m_accumulator->appendEndTag(toElement(node)); } template <typename Strategy> EditingStyle* StyledMarkupTraverser<Strategy>::createInlineStyleIfNeeded( Node& node) { if (!m_accumulator) return nullptr; if (!node.isElementNode()) return nullptr; EditingStyle* inlineStyle = createInlineStyle(toElement(node)); if (shouldConvertBlocksToInlines() && isEnclosingBlock(&node)) inlineStyle->forceInline(); return inlineStyle; } template <typename Strategy> void StyledMarkupTraverser<Strategy>::appendStartMarkup(Node& node) { if (!m_accumulator) return; switch (node.getNodeType()) { case Node::kTextNode: { Text& text = toText(node); if (text.parentElement() && isHTMLTextAreaElement(text.parentElement())) { m_accumulator->appendText(text); break; } EditingStyle* inlineStyle = nullptr; if (shouldApplyWrappingStyle(text)) { inlineStyle = m_wrappingStyle->copy(); // FIXME: <rdar://problem/5371536> Style rules that match pasted content // can change its appearance. // Make sure spans are inline style in paste side e.g. span { display: // block }. inlineStyle->forceInline(); // FIXME: Should this be included in forceInline? inlineStyle->style()->setProperty(CSSPropertyFloat, CSSValueNone); } m_accumulator->appendTextWithInlineStyle(text, inlineStyle); break; } case Node::kElementNode: { Element& element = toElement(node); if ((element.isHTMLElement() && shouldAnnotate()) || shouldApplyWrappingStyle(element)) { EditingStyle* inlineStyle = createInlineStyle(element); m_accumulator->appendElementWithInlineStyle(element, inlineStyle); break; } m_accumulator->appendElement(element); break; } default: m_accumulator->appendStartMarkup(node); break; } } template <typename Strategy> void StyledMarkupTraverser<Strategy>::appendEndMarkup(Node& node) { if (!m_accumulator || !node.isElementNode()) return; m_accumulator->appendEndTag(toElement(node)); } template <typename Strategy> bool StyledMarkupTraverser<Strategy>::shouldApplyWrappingStyle( const Node& node) const { return m_lastClosed && Strategy::parent(*m_lastClosed) == Strategy::parent(node) && m_wrappingStyle && m_wrappingStyle->style(); } template <typename Strategy> EditingStyle* StyledMarkupTraverser<Strategy>::createInlineStyle( Element& element) { EditingStyle* inlineStyle = nullptr; if (shouldApplyWrappingStyle(element)) { inlineStyle = m_wrappingStyle->copy(); inlineStyle->removePropertiesInElementDefaultStyle(&element); inlineStyle->removeStyleConflictingWithStyleOfElement(&element); } else { inlineStyle = EditingStyle::create(); } if (element.isStyledElement() && element.inlineStyle()) inlineStyle->overrideWithStyle(element.inlineStyle()); if (element.isHTMLElement() && shouldAnnotate()) inlineStyle->mergeStyleFromRulesForSerialization(&toHTMLElement(element)); return inlineStyle; } template class StyledMarkupSerializer<EditingStrategy>; template class StyledMarkupSerializer<EditingInFlatTreeStrategy>; } // namespace blink
21,031
6,375
// -*- C++ -*- //===------------------------------ span ---------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===---------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03, c++11, c++14, c++17 // <span> // template<class Container> // constexpr span(Container& cont); // template<class Container> // constexpr span(const Container& cont); // // Remarks: These constructors shall not participate in overload resolution unless: // — Container is not a specialization of span, // — Container is not a specialization of array, // — is_array_v<Container> is false, // — data(cont) and size(cont) are both well-formed, and // — remove_pointer_t<decltype(data(cont))>(*)[] is convertible to ElementType(*)[]. // #include <span> #include <cassert> #include <list> #include <forward_list> #include <deque> #include "test_macros.h" // Look ma - I'm a container! template <typename T> struct IsAContainer { constexpr IsAContainer() : v_{} {} constexpr size_t size() const {return 1;} constexpr T *data() {return &v_;} constexpr const T *data() const {return &v_;} constexpr const T *getV() const {return &v_;} // for checking T v_; }; template <typename T> struct NotAContainerNoData { size_t size() const {return 0;} }; template <typename T> struct NotAContainerNoSize { const T *data() const {return nullptr;} }; template <typename T> struct NotAContainerPrivate { private: size_t size() const {return 0;} const T *data() const {return nullptr;} }; int main () { // Missing size and/or data { std::span<int> s1{IsAContainer<int>()}; // expected-error {{no matching constructor for initialization of 'std::span<int>'}} std::span<int, 0> s2{IsAContainer<int>()}; // expected-error {{no matching constructor for initialization of 'std::span<int, 0>'}} std::span<int> s3{NotAContainerNoData<int>()}; // expected-error {{no matching constructor for initialization of 'std::span<int>'}} std::span<int, 0> s4{NotAContainerNoData<int>()}; // expected-error {{no matching constructor for initialization of 'std::span<int, 0>'}} std::span<int> s5{NotAContainerNoSize<int>()}; // expected-error {{no matching constructor for initialization of 'std::span<int>'}} std::span<int, 0> s6{NotAContainerNoSize<int>()}; // expected-error {{no matching constructor for initialization of 'std::span<int, 0>'}} std::span<int> s7{NotAContainerPrivate<int>()}; // expected-error {{no matching constructor for initialization of 'std::span<int>'}} std::span<int, 0> s8{NotAContainerPrivate<int>()}; // expected-error {{no matching constructor for initialization of 'std::span<int, 0>'}} // Again with the standard containers std::span<int> s11{std::deque<int>()}; // expected-error {{no matching constructor for initialization of 'std::span<int>'}} std::span<int, 0> s12{std::deque<int>()}; // expected-error {{no matching constructor for initialization of 'std::span<int, 0>'}} std::span<int> s13{std::list<int>()}; // expected-error {{no matching constructor for initialization of 'std::span<int>'}} std::span<int, 0> s14{std::list<int>()}; // expected-error {{no matching constructor for initialization of 'std::span<int, 0>'}} std::span<int> s15{std::forward_list<int>()}; // expected-error {{no matching constructor for initialization of 'std::span<int>'}} std::span<int, 0> s16{std::forward_list<int>()}; // expected-error {{no matching constructor for initialization of 'std::span<int, 0>'}} } // Not the same type { std::span<float> s1{IsAContainer<int>()}; // expected-error {{no matching constructor for initialization of 'std::span<float>'}} std::span<float, 0> s2{IsAContainer<int>()}; // expected-error {{no matching constructor for initialization of 'std::span<float, 0>'}} } // CV wrong (dynamically sized) { std::span< int> s1{IsAContainer<const int>()}; // expected-error {{no matching constructor for initialization of 'std::span<int>'}} std::span< int> s2{IsAContainer< volatile int>()}; // expected-error {{no matching constructor for initialization of 'std::span<int>'}} std::span< int> s3{IsAContainer<const volatile int>()}; // expected-error {{no matching constructor for initialization of 'std::span<int>'}} std::span<const int> s4{IsAContainer< volatile int>()}; // expected-error {{no matching constructor for initialization of 'std::span<const int>'}} std::span<const int> s5{IsAContainer<const volatile int>()}; // expected-error {{no matching constructor for initialization of 'std::span<const int>'}} std::span< volatile int> s6{IsAContainer<const int>()}; // expected-error {{no matching constructor for initialization of 'std::span<volatile int>'}} std::span< volatile int> s7{IsAContainer<const volatile int>()}; // expected-error {{no matching constructor for initialization of 'std::span<volatile int>'}} } // CV wrong (statically sized) { std::span< int,1> s1{IsAContainer<const int>()}; // expected-error {{no matching constructor for initialization of 'std::span<int, 1>'}} std::span< int,1> s2{IsAContainer< volatile int>()}; // expected-error {{no matching constructor for initialization of 'std::span<int, 1>'}} std::span< int,1> s3{IsAContainer<const volatile int>()}; // expected-error {{no matching constructor for initialization of 'std::span<int, 1>'}} std::span<const int,1> s4{IsAContainer< volatile int>()}; // expected-error {{no matching constructor for initialization of 'std::span<const int, 1>'}} std::span<const int,1> s5{IsAContainer<const volatile int>()}; // expected-error {{no matching constructor for initialization of 'std::span<const int, 1>'}} std::span< volatile int,1> s6{IsAContainer<const int>()}; // expected-error {{no matching constructor for initialization of 'std::span<volatile int, 1>'}} std::span< volatile int,1> s7{IsAContainer<const volatile int>()}; // expected-error {{no matching constructor for initialization of 'std::span<volatile int, 1>'}} } }
6,580
1,951
/** * Copyright 2019-2022 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "minddata/dataset/engine/datasetops/map_op/map_op.h" #include <algorithm> #include <cstring> #include <memory> #include <vector> #include "minddata/dataset/callback/callback_param.h" #include "minddata/dataset/core/config_manager.h" #include "minddata/dataset/include/dataset/constants.h" #include "minddata/dataset/core/global_context.h" #include "minddata/dataset/engine/datasetops/map_op/cpu_map_job.h" #include "minddata/dataset/kernels/tensor_op.h" #include "minddata/dataset/util/log_adapter.h" #include "minddata/dataset/util/task_manager.h" namespace mindspore { namespace dataset { // Constructor of MapOp MapOp::MapOp(const std::vector<std::string> &in_col_names, const std::vector<std::string> &out_col_names, std::vector<std::shared_ptr<TensorOp>> tensor_funcs, int32_t num_workers, int32_t op_connector_size) : ParallelOp(num_workers, op_connector_size), tfuncs_(std::move(tensor_funcs)), in_columns_(in_col_names), out_columns_(out_col_names), python_mp_(nullptr) { // Set connector size via config. // If caller didn't specify the out_col_names, assume they are same as the in_columns. if (out_columns_.empty() || out_columns_[0].empty()) { out_columns_ = in_columns_; } } // A print method typically used for debugging void MapOp::Print(std::ostream &out, bool show_all) const { if (!show_all) { // Call the super class for displaying any common 1-liner info ParallelOp::Print(out, show_all); // Then show any custom derived-internal 1-liner info for this op out << "\n"; } else { // Call the super class for displaying any common detailed info ParallelOp::Print(out, show_all); // Then show any custom derived-internal stuff out << "\nInput column names:"; for (size_t i = 0; i < in_columns_.size(); i++) { out << " " << in_columns_[i]; } out << "\n TensorOps:"; for (size_t i = 0; i < tfuncs_.size(); i++) { out << " " << *(tfuncs_[i].get()); } out << "\n\n"; } } // A helper function that fetch worker map job from local queues and extract the data and map job list Status MapOp::FetchNextWork(uint32_t worker_id, TensorRow *row, std::vector<std::shared_ptr<MapJob>> *job_list) { std::unique_ptr<MapWorkerJob> worker_job; // Fetch the next worker job and TensorRow RETURN_IF_NOT_OK(worker_in_queues_[worker_id]->PopFront(&worker_job)); // Extract the TensorRow and job list from the map worker job. *row = std::move(worker_job->tensor_row); *job_list = std::move(worker_job->jobs); return Status::OK(); } Status MapOp::GenerateWorkerJob(const std::unique_ptr<MapWorkerJob> *worker_job) { std::shared_ptr<MapJob> map_job = nullptr; MapTargetDevice prev_target = MapTargetDevice::kCpu; for (size_t i = 0; i < tfuncs_.size(); i++) { // Currently we only have CPU as the device target // In the future, we will have heuristic or control from user to select target device MapTargetDevice target_device = MapTargetDevice::kCpu; // If there is no existing map_job, we will create one. // map_job could be nullptr when we are at the first tensor op or when the target device of the prev op // is different with that of the current op. if (map_job == nullptr) { map_job = std::make_shared<CpuMapJob>(); } RETURN_IF_NOT_OK(map_job->AddOperation(tfuncs_[i])); // Push map_job into worker_job if one of the two conditions is true: // 1) It is the last tensor operation in tfuncs_ // 2) The the target device of the current tensor operation is different with previous one if ((i + 1 == tfuncs_.size()) || ((i != 0) && (prev_target != target_device))) { (*worker_job)->jobs.push_back(std::move(map_job)); } prev_target = target_device; } return Status::OK(); } // This class functor will provide the master loop that drives the logic for performing the work Status MapOp::operator()() { RETURN_IF_NOT_OK(RegisterAndLaunchThreads()); // init callback RETURN_IF_NOT_OK(callback_manager_.Init(this)); // Synchronize with TaskManager TaskManager::FindMe()->Post(); int64_t ep_step = 0, total_step = 0; RETURN_IF_NOT_OK(callback_manager_.Begin(CallbackParam(0, ep_step, total_step))); child_iterator_ = std::make_unique<ChildIterator>(this, 0, 0); TensorRow new_row; RETURN_IF_NOT_OK(child_iterator_->FetchNextTensorRow(&new_row)); while (!new_row.eof()) { if (op_current_repeats_ % GetOpNumRepeatsPerEpoch() == 0) { ep_step = 0; RETURN_IF_NOT_OK(callback_manager_.EpochBegin(CallbackParam(op_current_epochs_ + 1, ep_step, total_step))); } while (!new_row.eoe()) { ep_step++; total_step++; // Create an empty map worker job to be populated by a TensorRow and map jobs RETURN_IF_NOT_OK(callback_manager_.StepBegin(CallbackParam(op_current_epochs_ + 1, ep_step, total_step))); std::unique_ptr<MapWorkerJob> worker_job = std::make_unique<MapWorkerJob>(std::move(new_row)); // Populate map worker job for a worker to execute RETURN_IF_NOT_OK(GenerateWorkerJob(&worker_job)); // Push map worker job to the corresponding worker's queue RETURN_IF_NOT_OK(worker_in_queues_[NextWorkerID()]->Add(std::move(worker_job))); RETURN_IF_NOT_OK(child_iterator_->FetchNextTensorRow(&new_row)); } // Propagate the eoe row to worker std::unique_ptr<MapWorkerJob> worker_job = std::make_unique<MapWorkerJob>(std::move(new_row)); RETURN_IF_NOT_OK(worker_in_queues_[NextWorkerID()]->Add(std::move(worker_job))); UpdateRepeatAndEpochCounter(); RETURN_IF_NOT_OK(child_iterator_->FetchNextTensorRow(&new_row)); } // End() is commented out because it might never be called due to the lack of EOF when EpochCtrl is -1 // Handle eof logic, this code might never be reached if epoch_ctrl = -1. std::unique_ptr<MapWorkerJob> worker_job = std::make_unique<MapWorkerJob>(std::move(new_row)); RETURN_IF_NOT_OK(worker_in_queues_[NextWorkerID()]->Add(std::move(worker_job))); // Quit all workers, this code might never be reached if EpochCtrl is -1. for (int32_t wkr_id = 0; wkr_id < num_workers_; wkr_id++) { RETURN_IF_NOT_OK(SendQuitFlagToWorker(NextWorkerID())); } return Status::OK(); } // Private function for worker/thread to loop continuously. It comprises the main // logic of MapOp: getting the data from previous Op, validating user specified column names, // applying a list of TensorOps to each of the data, process the results and then // pushing them back to MapOp's output Connector to be fetched by the next Op. Status MapOp::WorkerEntry(int32_t worker_id) { // Handshake with TaskManager that thread creation is successful. TaskManager::FindMe()->Post(); TensorRow in_row; std::vector<std::shared_ptr<MapJob>> job_list; // Fetch next data row and map job list RETURN_IF_NOT_OK(FetchNextWork(worker_id, &in_row, &job_list)); // Now that init work is done, drop into the main fetching loop. // Map op does not use child iterator, and it needs to manually handle eoe and eof's itself // rather than use the base-class defaults. while (true) { // Handle special logic where row carries a ctrl flag. if (in_row.Flags() != TensorRow::kFlagNone) { if (in_row.quit()) { break; } RETURN_IF_NOT_OK(worker_out_queues_[worker_id]->EmplaceBack(std::move(in_row))); } else { CHECK_FAIL_RETURN_UNEXPECTED(in_row.size() != 0, "[Internal ERROR] MapOp got an empty TensorRow."); TensorRow out_row; // Perform the compute function of TensorOp(s) and store the result in new_tensor_table. RETURN_IF_NOT_OK(WorkerCompute(in_row, &out_row, job_list)); // Push the row onto the connector for next operator to consume. RETURN_IF_NOT_OK(worker_out_queues_[worker_id]->EmplaceBack(std::move(out_row))); } // Fetch next data row and map job list RETURN_IF_NOT_OK(FetchNextWork(worker_id, &in_row, &job_list)); } return Status::OK(); } Status MapOp::WorkerCompute(const TensorRow &in_row, TensorRow *out_row, const std::vector<std::shared_ptr<MapJob>> &job_list) { int32_t num_cols = in_row.size(); std::vector<TensorRow> job_input_table; std::vector<TensorRow> original_table; TensorRow to_process; // Prepare the data that we need from in_row // to_process : A vector of Tensors only holding cols in input_columns. // From the current row, select the Tensor that need to be passed to TensorOp (void)std::transform(to_process_indices_.begin(), to_process_indices_.end(), std::back_inserter(to_process), [&in_row](const auto &it) { return std::move(in_row[it]); }); to_process.setId(in_row.getId()); std::vector<std::string> cur_row_path = in_row.getPath(); if (cur_row_path.size() > 0) { std::vector<std::string> to_process_path; (void)std::transform(to_process_indices_.begin(), to_process_indices_.end(), std::back_inserter(to_process_path), [&cur_row_path](const auto &it) { return cur_row_path[it]; }); to_process.setPath(to_process_path); } job_input_table.push_back(std::move(to_process)); original_table.push_back(std::move(in_row)); // Variable to keep the result after executing the job. std::vector<TensorRow> result_table; // Executing the list of jobs. for (size_t i = 0; i < job_list.size(); i++) { RETURN_IF_INTERRUPTED(); // Execute MapWorkerJob. RETURN_IF_NOT_OK(job_list[i]->Run(job_input_table, &result_table)); // Assign the processed data as an input for the next job processing, except for the last TensorOp in the list. if (i + 1 < job_list.size()) { job_input_table = std::move(result_table); } } // Sanity check a row in result_table if (!result_table.empty() && out_columns_.size() != result_table[0].size()) { RETURN_STATUS_UNEXPECTED( "Invalid columns, the number of columns returned in 'map' operations should match " "the number of 'output_columns', but got the number of columns returned in 'map' operations: " + std::to_string(result_table[0].size()) + ", the number of 'output_columns': " + std::to_string(out_columns_.size()) + "."); } // Merging the data processed by job (result_table) with the data that are not used. if (in_columns_.size() == out_columns_.size()) { // Place the processed tensor back into the original index of the input tensor for (size_t i = 0; i < result_table[0].size(); i++) { original_table[0][to_process_indices_[i]] = std::move(result_table[0][i]); } *out_row = std::move(original_table[0]); } else { // Append the data in the original table that we did not use to the end of each row in result_table. for (int32_t i = 0; i < num_cols; i++) { if (keep_input_columns_[i]) { result_table[0].push_back(std::move(original_table[0][i])); } } *out_row = std::move(result_table[0]); } return Status::OK(); } Status MapOp::ComputeColMap() { // If the map has not been set up yet in the base class, then set it up if (column_name_id_map_.empty()) { std::unordered_map<std::string, int32_t> current_name_id_map = child_[0]->column_name_id_map(); // Initialize private variables RETURN_IF_NOT_OK(InitPrivateVariable(&current_name_id_map)); // Create the final column name to index mapping in the base class field CreateFinalColMap(&current_name_id_map); MS_LOG(DEBUG) << "Column name map for map op is: " << this->ColumnNameMapAsString(); } else { MS_LOG(WARNING) << "Column name map is already set!"; } return Status::OK(); } // Validating if each of the input_columns exists in the col_name_id_map. Status MapOp::ValidateInColumns(const std::unordered_map<std::string, int32_t> &col_name_id_map) { for (const auto &inCol : in_columns_) { bool found = col_name_id_map.find(inCol) != col_name_id_map.end(); if (!found) { std::string err_msg = "Invalid parameter, input column name: " + inCol + " doesn't exist in the dataset columns."; RETURN_STATUS_UNEXPECTED(err_msg); } } return Status::OK(); } Status MapOp::InitPrivateVariable(std::unordered_map<std::string, int32_t> *col_name_id_map) { // If input_columns is empty(), The col at index-0 will be picked. if (in_columns_.empty()) { auto itr = std::find_if(col_name_id_map->begin(), col_name_id_map->end(), [](const auto &it) { return it.second == 0; }); CHECK_FAIL_RETURN_UNEXPECTED(itr != col_name_id_map->end(), "[Internal ERROR] Column name id map doesn't have id 0"); MS_LOG(INFO) << "Input columns empty for map op, will apply to the first column in the current table."; in_columns_.push_back(itr->first); // If caller didn't specify the out_col_names, assume they are same as the input_columns. // This was done in the constructor, but if input columns was empty to start we have to redo it here. if (out_columns_.empty() || out_columns_[0].empty()) { out_columns_ = in_columns_; } } // Before we continue, issue a sanity check to make sure the input columns from user and the incoming // columns from child are correct RETURN_IF_NOT_OK(this->ValidateInColumns(*col_name_id_map)); // Initialize keep_input_columns, true means to keep the column. keep_input_columns_.resize(col_name_id_map->size(), true); for (const auto &col_name : in_columns_) { int32_t missed = (*col_name_id_map)[col_name]; keep_input_columns_[missed] = false; } // initialize to_process_indices. for (const auto &col_name : in_columns_) { to_process_indices_.push_back((*col_name_id_map)[col_name]); } return Status::OK(); } // Create the final column name to index mapping and get indices of the columns this mapop does not use. void MapOp::CreateFinalColMap(std::unordered_map<std::string, int32_t> *col_name_id_map) { std::unordered_map<std::string, int32_t> final_col_name_id_map; size_t num_cols = col_name_id_map->size(); std::vector<int32_t> new_ids(num_cols); if (in_columns_.size() == out_columns_.size()) { for (size_t i = 0; i < in_columns_.size(); i++) { int32_t loc = (*col_name_id_map)[in_columns_[i]]; (void)col_name_id_map->erase(in_columns_[i]); (*col_name_id_map)[out_columns_[i]] = loc; } // Set the base class final column id map result column_name_id_map_ = *col_name_id_map; } else { int32_t fill_idx = 0; // First columns of the tables are occupied by the output columns from tensorOp. for (const auto &col_name : out_columns_) { final_col_name_id_map[col_name] = fill_idx++; } // Creating new_ids mapping for the columns we keep. for (size_t i = 0; i < num_cols; i++) { if (keep_input_columns_[i]) { new_ids[i] = fill_idx++; } } // Iterating through the old mapping to update the final mapping for the columns we kept. std::string name; for (const auto &pair : *col_name_id_map) { name = pair.first; int32_t old_id = pair.second; if (keep_input_columns_[old_id]) { final_col_name_id_map[name] = new_ids[old_id]; } } // Set the base class final column id map result column_name_id_map_ = final_col_name_id_map; } } Status MapOp::SendWaitFlagToWorker(int32_t worker_id) { TensorRow wait_row(TensorRow::kFlagWait); RETURN_IF_NOT_OK(worker_in_queues_[worker_id]->Add(std::make_unique<MapWorkerJob>(wait_row))); return Status::OK(); } Status MapOp::SendQuitFlagToWorker(int32_t worker_id) { TensorRow quit_flag(TensorRow::kFlagQuit); RETURN_IF_NOT_OK(worker_in_queues_[worker_id]->Add(std::make_unique<MapWorkerJob>(quit_flag))); return Status::OK(); } Status MapOp::AddNewWorkers(int32_t num_new_workers) { RETURN_IF_NOT_OK(ParallelOp::AddNewWorkers(num_new_workers)); if (python_mp_ != nullptr) { CHECK_FAIL_RETURN_UNEXPECTED(num_new_workers > 0, "Number of workers added should be greater than 0."); python_mp_->AddNewWorkers(num_new_workers); } return Status::OK(); } Status MapOp::RemoveWorkers(int32_t num_workers) { RETURN_IF_NOT_OK(ParallelOp::RemoveWorkers(num_workers)); if (python_mp_ != nullptr) { CHECK_FAIL_RETURN_UNEXPECTED(num_workers > 0, "Number of workers removed should be greater than 0."); python_mp_->RemoveWorkers(num_workers); } return Status::OK(); } void MapOp::SetPythonMp(std::shared_ptr<PythonMultiprocessingRuntime> python_mp) { python_mp_ = std::move(python_mp); } Status MapOp::Launch() { // launch python multiprocessing. This will create the MP pool and shared memory if needed. if (python_mp_) { MS_LOG(DEBUG) << "Launch Python Multiprocessing for MapOp:" << id(); python_mp_->Launch(id()); } return DatasetOp::Launch(); } std::vector<int32_t> MapOp::GetMPWorkerPIDs() const { if (python_mp_ != nullptr) { return python_mp_->GetPIDs(); } return DatasetOp::GetMPWorkerPIDs(); } } // namespace dataset } // namespace mindspore
17,653
6,043
#include "trace.h" /*********************************************************************** * NAME : Trace() * * DESCRIPTION : Constructor for the Trace object. * * ********************************************************************/ Trace::Trace() { /* initialize all of the boolean parameters */ allocInputPos_ = false; setModelParams_ = false; allocModelParams_ = false; setBounds_ = false; setTraceConfig_ = false; allocAlpha_ = false; setAlpha_ = false; allocHalpha_ = false; allocHalpha3D_ = false; setHalpha_ = false; allocTrace_ = false; setTrace_ = false; allocNstep_ = false; allocMP_ = false; allocDist_ = false; setDist_ = false; allocRnorm_ = false; setRnorm_ = false; allocFootprints_ = false; allocEqFP_ = false; allocEndpoints_ = false; setFootprints_ = false; allocR_ = false; allocZmso_ = false; /* default trace parameters */ SetTraceCFG(); } /*********************************************************************** * NAME : ~Trace() * * DESCRIPTION : Destructor for the Trace object. * * ********************************************************************/ Trace::~Trace() { /* check for each allocated variable and delete it*/ int i, j, k = 0; /* starting positions */ if (allocInputPos_) { delete[] x0_; delete[] y0_; delete[] z0_; } /* parameters */ if (allocModelParams_) { delete[] Rsm_; delete[] t1_; delete[] t2_; } /* traces */ if (allocMP_) { delete[] inMP_; } if (allocTrace_) { for (i=0;i<n_;i++) { delete[] x_[i]; delete[] y_[i]; delete[] z_[i]; delete[] bx_[i]; delete[] by_[i]; delete[] bz_[i]; } delete[] x_; delete[] y_; delete[] z_; delete[] bx_; delete[] by_; delete[] bz_; } if (allocZmso_) { for (i=0;i<n_;i++) { delete[] zmso_[i]; } delete[] zmso_; } /* nstep */ if (allocNstep_) { delete[] nstep_; } /* field line footprints */ if (allocFootprints_) { for (i=0;i<n_;i++) { delete[] FP_[i]; } delete[] FP_; } /* field line distance */ if (allocDist_) { for (i=0;i<n_;i++) { delete[] S_[i]; } delete[] S_; } /* radial distance */ if (allocR_) { for (i=0;i<n_;i++) { delete[] Rmsm_[i]; delete[] Rmso_[i]; } delete[] Rmsm_; delete[] Rmso_; } /* r norm distance */ if (allocRnorm_) { for (i=0;i<n_;i++) { delete[] Rnorm_[i]; } delete[] Rnorm_; } /* h alpha*/ if (allocAlpha_) { delete[] alpha0_; delete[] alpha1_; } if (allocHalpha_) { delete[] Halpha_; } if (allocHalpha3D_) { for (i=0;i<n_;i++) { for (j=0;j<nalpha_;j++) { delete[] Halpha3D_[i][j]; } delete[] Halpha3D_[i]; } delete[] Halpha3D_; } /* footprint/endpoints */ if (allocEndpoints_) { delete[] xfn_; delete[] yfn_; delete[] zfn_; delete[] xfs_; delete[] yfs_; delete[] zfs_; delete[] xfnc_; delete[] yfnc_; delete[] zfnc_; delete[] xfsc_; delete[] yfsc_; delete[] zfsc_; delete[] xfnv_; delete[] yfnv_; delete[] zfnv_; delete[] xfsv_; delete[] yfsv_; delete[] zfsv_; delete[] xfnvc_; delete[] yfnvc_; delete[] zfnvc_; delete[] xfsvc_; delete[] yfsvc_; delete[] zfsvc_; } if (allocEqFP_) { delete[] xfe_; delete[] yfe_; delete[] zfe_; } } /*********************************************************************** * NAME : void Trace::InputPos(n,x,y,z) * * DESCRIPTION : Input the starting positions of each trace. * * INPUTS : * int n Number of traces. * double x x-MSM coordinate of starting points. * double y y-MSM coordinate of starting points. * double z z-MSM coordinate of starting points. * * ********************************************************************/ void Trace::InputPos( int n, double *x, double *y, double *z) { /* check that we have not already done this */ if (allocInputPos_) { printf("Input positions already set, ignoring...\n"); return; } /* allocate the memory to store the input coords */ n_ = n; x0_ = new double[n]; y0_ = new double[n]; z0_ = new double[n]; /* convert the coordinates to GSM */ int i; for (i=0;i<n_;i++) { x0_[i] = x[i]; y0_[i] = y[i]; z0_[i] = z[i]; } /* set the flag so we know to delete again once the object is deleted */ allocInputPos_ = true; } /*********************************************************************** * NAME : void Trace::SetModelParams(Rsm,t1,t2) * * DESCRIPTION : Set the model parameters (KT14) for each trace. * * INPUTS : * double *Rsm Array of subsolar standof distances (Rm). * double *t1 Tail disk magnitudes. * double *t2 Quasi-harris sheet magnitudes. * * ********************************************************************/ void Trace::SetModelParams(double *Rsm, double *t1, double *t2) { /* set the pointers to parameters provided externally */ Rsm_ = Rsm; t1_ = t1; t2_ = t2; /* set the flags to say that we have the parameters, but they don't * need to be deleted */ setModelParams_ = true; allocModelParams_ = false; } /*********************************************************************** * NAME : void Trace::SetModelParams(Rsun,DistIndex) * * DESCRIPTION : Set model parameters (KT17) for each trace. * * INPUTS : * double *Rsun Distance from the Sun (AU). * double *DistIndex Anderson et al 2013 disturbance index (0-97). * * ********************************************************************/ void Trace::SetModelParams(double *Rsun, double *DistIndex) { /* allocate parameters*/ Rsm_ = new double[n_]; t1_ = new double[n_]; t2_ = new double[n_]; /* convert from KT17 to KT14 */ int i; for (i=0;i<n_;i++) { KT14Params(Rsun[i],DistIndex[i],&Rsm_[i],&t1_[i],&t2_[i]); } /* set the flags to say that we have the parameters, and that they * need to be deleted */ setModelParams_ = true; allocModelParams_ = true; } /*********************************************************************** * NAME : Trace::SetTraceBounds(MP,TailX,EndSurface) * * DESCRIPTION : Tell trace routine where to stop tracing. * * INPUTS : * bool MP If true, then the trace will stop if the MP is * encountered. * double TailX x-coordinate at which to stop tracing in the tail, * positive values will be ignored and tracing will * continue until MaxLen_. * int EndSurface Surface on which to end the field trace: * 1 - Stop at the planetary surface * 2 - Stop at the planetary core (0.832 Rm). * 3 - Stop at dipole at 1 Rm * 4 - Stop at dipole at 0.832 Rm (core radius) * 5 - Stop at northern surface, southern dipole at * 1 Rm (virtual surface). * 6 - Stop at northern core and southern dipole at * 0.832 Rm. * * * ********************************************************************/ void Trace::SetTraceBounds(bool MP, double TailX, int EndSurface) { BoundMP_ = true; BoundTail_ = TailX; BoundSurface_ = EndSurface; /* set the function pointers */ if (MP) { ctfMP_ = &ContTraceMP; } else { ctfMP_ = &ContTraceMPDummy; } if (TailX < 0) { ctfTX_ = &ContTraceTail; } else { ctfTX_ = &ContTraceTailDummy; } if (EndSurface == 1) { ctfSC_ = &ContTraceSurface1; } else if (EndSurface == 2) { ctfSC_ = &ContTraceSurface2; } else if (EndSurface == 3) { ctfSC_ = &ContTraceSurface3; } else if (EndSurface == 4) { ctfSC_ = &ContTraceSurface4; } else if (EndSurface == 5) { ctfSC_ = &ContTraceSurface5; } else { ctfSC_ = &ContTraceSurface6; } setBounds_ = true; } /*********************************************************************** * NAME : Trace::SetTraceBounds() * * DESCRIPTION : Tell trace routine where to stop tracing. (defaults) * * ********************************************************************/ void Trace::SetTraceBounds() { SetTraceBounds(true,-10.0,6); } /*********************************************************************** * NAME : void Trace::SetTraceConfig(MaxLen,MaxStep,InitStep,MinStep, * ErrMax,Delta,Verbose,TraceDir) * * DESCRIPTION : Sets a bunch of parameters for the trace. * * INPUTS : * int MaxLen Maximum length of each trace. * double MaxStep Maximum step size (Rm) * double InitStep Initial step size (Rm) * double MinStep Minimum step size (Rm) * double ErrMax Maximum error. * double Delta Distance between adjacent field lines (Rm) to be * used int he calculation of h_alpha. * bool Verbose Display tracing progress. * int TraceDir Direction in which to trace: * 0 - trace in both directions * 1 - along the field (towards north) * -1 - opposite to the field (towards south) * * ********************************************************************/ void Trace::SetTraceCFG(int MaxLen, double MaxStep, double InitStep, double MinStep, double ErrMax, double Delta, bool Verbose, int TraceDir) { /* set all of the params */ MaxLen_ = MaxLen; MaxStep_ = MaxStep; MinStep_ = MinStep; InitStep_ = InitStep; Verbose_ = Verbose; TraceDir_ = TraceDir; ErrMax_ = ErrMax; Delta_ = Delta; setTraceConfig_ = true; } /*********************************************************************** * NAME : void Trace::SetTraceConfig() * * DESCRIPTION : Sets a bunch of parameters for the trace. * * ********************************************************************/ void Trace::SetTraceCFG() { /* set default params */ MaxLen_ = 1000; MaxStep_ = 0.05; InitStep_ = 0.01; MinStep_ = 0.001; Verbose_ = false; TraceDir_ = 0; ErrMax_ = 0.0001; Delta_ = 0.05; setTraceConfig_ = true; } /*********************************************************************** * NAME : void Trace::SetAlpha(nalpha,alpha) * * DESCRIPTION : Set the alpha (polarization angles) to calculate * h_alpha at. * * INPUTS : * int nalpha The number of alpha values. * double *alpha Array of alphas (degrees) 0 = toroidal. * * OUPUTS : * * ********************************************************************/ void Trace::SetAlpha(int nalpha, double *alpha) { /*NOTE: for each alpha, there will be two traces - one for the * supplied value and one for alpha + 180 */ /* set the alpha pointer */ nalpha_ = nalpha; if (nalpha > 0) { alpha0_ = new double[nalpha_]; alpha1_ = new double[nalpha_]; allocAlpha_ = true; double dtor = M_PI/180.0; int i; for (i=0;i<nalpha;i++) { alpha0_[i] = alpha[i]*dtor; alpha1_[i] = fmod(alpha[i]*dtor + M_PI,2*M_PI); } } setAlpha_ = true; } /*********************************************************************** * NAME : bool Trace::ContinueTrace(x,y,z,zmso,rmsm,rmso) * * DESCRIPTION : Tells tracing routines whether to continue or not. * * INPUTS : * double x current x-coordinate. * double y current y-coordinate. * double z current z-coordinate. * * OUPUTS : * double *zmso z + 0.196 * double *rmsm radial coordinate in MSM * double *rmso radial coordinate in MSO * * RETURNS : * bool cont true if it wants to continue tracing. * * ********************************************************************/ bool Trace::ContinueTrace( double x, double y, double z, double *zmso, double *rmsm, double *rmso) { /* calculate zsmo, rmsm and rmso */ zmso[0] = z + 0.196; double rho2 = x*x + y*y; rmsm[0] = sqrt(rho2 + z*z); rmso[0] = sqrt(rho2 + zmso[0]*zmso[0]); /* check if we're within MP, Tail and outside surface */ bool goodMP, goodTX, goodSC; goodMP = ctfMP_(x,y,z,ktmodel.Rsm_); goodTX = ctfTX_(x,BoundTail_); goodSC = ctfSC_(z,rmsm[0],rmso[0]); return (goodMP && goodTX && goodSC); } /*********************************************************************** * NAME : void Trace::Step(x0,y0,z0,step,x,y,z,zmso,rmsm,rmso,Bx,By,Bz) * * DESCRIPTION : Take a single step using the Runge-Kutta-Merson algorithm. * * INPUTS : * double x0 Starting x-position * double y0 Starting y-position * double z0 Starting z-position * * OUPUTS : * double *step Step size. * double *x New x-position * double *y New y-position * double *z New z-position * double *zmso New z-position MSO * double *rmsm Radial coordinate (MSM) * double *rmso Radial coordinate (MSO) * double *Bx x-component of magnetic field. * double *By y-component of magnetic field. * double *Bz z-component of magnetic field. * * ********************************************************************/ void Trace::Step( double x0, double y0, double z0, double *step, double *x, double *y, double *z, double *zmso, double *rmsm, double *rmso, double *Bx, double *By, double *Bz) { /* based on the STEP_08 function from GEOPACK */ double rx1,ry1,rz1; double rx2,ry2,rz2; double rx3,ry3,rz3; double rx4,ry4,rz4; double rx5,ry5,rz5; double x1,y1,z1; double x2,y2,z2; double x3,y3,z3; double x4,y4,z4; double step3; double Err; double xn, yn, zn, zmson, Rn, Rmson; bool cont; bool adjstep = false; bool repeat = true; while (repeat) { /* this bit repeats until we get a desired step size */ step3 = step[0]/3.0; StepVector(x0,y0,z0,step3,&rx1,&ry1,&rz1); x1 = x0 + rx1; y1 = y0 + ry1; z1 = z0 + rz1; StepVector(x1,y1,z1,step3,&rx2,&ry2,&rz2); x2 = x0 + 0.5*(rx1 + rx2); y2 = y0 + 0.5*(ry1 + ry2); z2 = z0 + 0.5*(rz1 + rz2); StepVector(x2,y2,z2,step3,&rx3,&ry3,&rz3); x3 = x0 + 0.375*(rx1 + 3*rx3); y3 = y0 + 0.375*(ry1 + 3*ry3); z3 = z0 + 0.375*(rz1 + 3*rz3); StepVector(x3,y3,z3,step3,&rx4,&ry4,&rz4); x4 = x0 + 1.5*(rx1 - 3*rx3 + 4*rx4); y4 = y0 + 1.5*(ry1 - 3*ry3 + 4*ry4); z4 = z0 + 1.5*(rz1 - 3*rz3 + 4*rz4); StepVector(x4,y4,z4,step3,&rx5,&ry5,&rz5); Err = fabs(rx1 - 4.5*rx3 + 4*rx4 - 0.5*rx5); Err += fabs(ry1 - 4.5*ry3 + 4*ry4 - 0.5*ry5); Err += fabs(rz1 - 4.5*rz3 + 4*rz4 - 0.5*rz5); /* check that the next position is good */ xn = x0 + 0.5*(rx1 + 4*rx4 + rx5); yn = y0 + 0.5*(ry1 + 4*ry4 + ry5); zn = z0 + 0.5*(rz1 + 4*rz4 + rz5); cont = ContinueTrace(xn,yn,zn,&zmson,&Rn,&Rmson); if ((!cont) && (fabs(step[0]) > MinStep_)) { step[0] = 0.5*step[0]; if (fabs(step[0]) < MinStep_) { step[0] = (step[0]/fabs(step[0]))*MinStep_; } adjstep = true; } else if (!cont) { step[0] = (step[0]/fabs(step[0]))*MinStep_; repeat = false; } if (cont) { if ((Err <= ErrMax_) && (fabs(step[0]) <= MaxStep_)) { repeat = false; } else { if (Err > ErrMax_) { if (fabs(step[0]) > MinStep_) { step[0] = step[0]*0.5; } else { repeat = false; } } if (fabs(step[0]) > MaxStep_) { step[0] = (step[0]/fabs(step[0]))*MaxStep_; } } if ((Err < 0.04*ErrMax_) && (fabs(step[0]) < (MaxStep_/1.5))) { step[0] = 1.5*step[0]; } } } x[0] = xn; y[0] = yn; z[0] = zn; zmso[0] = zmson; rmsm[0] = Rn; rmso[0] = Rmson; ktmodel.Field(x[0],y[0],z[0],Bx,By,Bz); } /*********************************************************************** * NAME : void Trace::ReverseElements(n,x) * * DESCRIPTION : Reverse the elements of an array. * * INPUTS : * int n number of elements to be reversed. * double *x array to be reversed. * * ********************************************************************/ void Trace::ReverseElements(int n, double *x) { int i; double tmp; for (i=0;i<(n/2);i++) { tmp = x[i]; x[i] = x[n-i-1]; x[n-i-1] = tmp; } } /*********************************************************************** * NAME : void Trace::StepVector(x,y,z,step3,rx,ry,rz) * * DESCRIPTION : Calculate the vector of a given step. * * INPUTS : * double x x-position * double y y-position * double z z-position * double step3 1/3 of the step size * * OUPUTS : * double *rx output unit vector * double *ry output unit vector * double *rz output unit vector * * ********************************************************************/ void Trace::StepVector( double x, double y, double z, double step3, double *rx, double *ry, double *rz) { /* based on the RHAND_08 function from GEOPACK */ double bx, by, bz, s3bm; ktmodel.Field(x,y,z,&bx,&by,&bz); s3bm = step3/sqrt(bx*bx + by*by + bz*bz); /* this is a unit vector scaled by 1/3 of the step size */ rx[0] = s3bm*bx; ry[0] = s3bm*by; rz[0] = s3bm*bz; } /*********************************************************************** * NAME : void Trace::RKMTrace(x0,y0,z0,nstep,x,y,z,zmso,rmsm,rmso, * Bx,By,Bz) * * DESCRIPTION : Perform the trace along the magnetic field line using * Runge-Kutta-Merson algorithm. * * INPUTS : * double x0 starting x-position * double y0 starting y-position * double z0 starting z-position * * OUPUTS : * int *nstep Number of steps taken + 1 (actually the number * of elements in each output trace. * double *x Trace position * double *y Trace position * double *z Trace position * double *zmso Trace z MSO coordinate. * double *Rmsm MSM radial coordinate * double *Rmso MSO radial coordinate * double *Bx Trace field vector * double *By Trace field vector * double *Bz Trace field vector * * ********************************************************************/ void Trace::RKMTrace( double x0, double y0, double z0, int *nstep, double *x, double *y, double *z, double *zmso, double *Rmsm, double *Rmso, double *Bx, double *By, double *Bz) { /* intialize the trace */ nstep[0] = 1; x[0] = x0; y[0] = y0; z[0] = z0; ktmodel.Field(x0,y0,z0,&Bx[0],&By[0],&Bz[0]); double step; bool cont = ContinueTrace(x[0],y[0],z[0],&zmso[0],&Rmsm[0],&Rmso[0]); /* trace in one direction */ if ((TraceDir_ == -1) || (TraceDir_ == 0)) { /* This will trace in the opposite of the field direction, * towards the southern hemisphere*/ step = -InitStep_; while ((cont) && (nstep[0] < (MaxLen_/2 - 1))) { Step( x[nstep[0]-1],y[nstep[0]-1],z[nstep[0]-1],&step, &x[nstep[0]],&y[nstep[0]],&z[nstep[0]], &zmso[nstep[0]],&Rmsm[nstep[0]],&Rmso[nstep[0]], &Bx[nstep[0]],&By[nstep[0]],&Bz[nstep[0]]); cont = ContinueTrace(x[nstep[0]],y[nstep[0]],z[nstep[0]], &zmso[nstep[0]],&Rmsm[nstep[0]],&Rmso[nstep[0]]); nstep[0]++; } } /* reverse the elements of the trace */ ReverseElements(nstep[0],x); ReverseElements(nstep[0],y); ReverseElements(nstep[0],z); ReverseElements(nstep[0],zmso); ReverseElements(nstep[0],Bx); ReverseElements(nstep[0],By); ReverseElements(nstep[0],Bz); ReverseElements(nstep[0],Rmsm); ReverseElements(nstep[0],Rmso); /* trace in the opposite direction */ cont = ContinueTrace(x[nstep[0]-1],y[nstep[0]-1],z[nstep[0]-1], &zmso[nstep[0]-1],&Rmsm[nstep[0]-1],&Rmso[nstep[0]-1]); if ((TraceDir_ == 1) || (TraceDir_ == 0)) { /* hopefully this will go in the direction fo the field vectors * towards the northern hemisphere */ step = InitStep_; while ((cont) && (nstep[0] < (MaxLen_ - 1))) { Step( x[nstep[0]-1],y[nstep[0]-1],z[nstep[0]-1],&step, &x[nstep[0]],&y[nstep[0]],&z[nstep[0]], &zmso[nstep[0]],&Rmsm[nstep[0]],&Rmso[nstep[0]], &Bx[nstep[0]],&By[nstep[0]],&Bz[nstep[0]]); cont = ContinueTrace(x[nstep[0]],y[nstep[0]],z[nstep[0]], &zmso[nstep[0]],&Rmsm[nstep[0]],&Rmso[nstep[0]]); nstep[0]++; } } } /*********************************************************************** * NAME : Trace Trace::TracePostion(i,x,y,z) * * DESCRIPTION : Return a trace object for a position near to an * existing trace. * * INPUTS : * int i Index of existing trace. * double x x-coordinate near to existing trace * double y y-coordinate near to existing trace * double z z-coordinate near to existing trace * * RETURNS : * Trace T Trace object instance. * * ********************************************************************/ Trace Trace::TracePosition(int i, double x, double y, double z) { /* return a new trace object at the supplied position using the * parameters at time i */ Trace T; /* input position and time - I am pretty certain that the midpoints * of the field lines are stored in SM coords */ T.InputPos(1,&x,&y,&z); /* set the model up */ T.SetTraceBounds(BoundMP_,BoundTail_,BoundSurface_); T.SetModelParams(&Rsm_[i],&t1_[i],&t2_[i]); T.SetTraceCFG(MaxLen_,MaxStep_,InitStep_,MinStep_,ErrMax_,Delta_,false,0); /* run the trace */ T.TraceField(); /* calculate S*/ T.CalculateTraceDist(); return T; } /*********************************************************************** * NAME : void Trace::_CalculateTraceHalpha(i,j,halpha) * * DESCRIPTION : Calculates the h_alphas along a given trace and alpha. * * INPUTS : * int i Trace index * int j Alpha index * * OUPUTS : * double *halpha h_alpha along this field line. * * ********************************************************************/ void Trace::_CalculateTraceHalpha( int i, int j, double *halpha) { /* some variables needed */ double xe0,ye0,ze0,xe1,ye1,ze1; int k; /* get the trace starting points first */ _CalculateHalphaStartPoints(i,j,&xe0,&ye0,&ze0,&xe1,&ye1,&ze1); /* do two traces */ Trace T0 = TracePosition(i,xe0,ye0,ze0); Trace T1 = TracePosition(i,xe1,ye1,ze1); /* the traces above may only have 0 steps - in which case we can * just fill halpha with nans and leave the function */ if ((T0.nstep_[0] == 0) | (T1.nstep_[0] == 0)) { for (k=0;k<nstep_[i];k++) { halpha[k] = NAN; } return; } /* get the closest points to each step of the original trace*/ double *xc0 = new double[nstep_[i]]; double *yc0 = new double[nstep_[i]]; double *zc0 = new double[nstep_[i]]; double *xc1 = new double[nstep_[i]]; double *yc1 = new double[nstep_[i]]; double *zc1 = new double[nstep_[i]]; interptraceClosestPos( nstep_[i],x_[i],y_[i],z_[i], bx_[i],by_[i],bz_[i], T0.nstep_[0],T0.x_[0],T0.y_[0],T0.z_[0],T0.S_[0], T1.nstep_[0],T1.x_[0],T1.y_[0],T1.z_[0],T1.S_[0], xc0,yc0,zc0,xc1,yc1,zc1); /* calculate distances and then halpha */ double d, dx, dy, dz, h0, h1; for (k=0;k<nstep_[i];k++) { dx = x_[i][k] - xc0[k]; dy = y_[i][k] - yc0[k]; dz = z_[i][k] - zc0[k]; d = sqrt(dx*dx + dy*dy + dz*dz); h0 = d/Delta_; dx = x_[i][k] - xc1[k]; dy = y_[i][k] - yc1[k]; dz = z_[i][k] - zc1[k]; d = sqrt(dx*dx + dy*dy + dz*dz); h1 = d/Delta_; halpha[k] = 0.5*(h0 + h1); } /* free up memory */ delete[] xc0; delete[] yc0; delete[] zc0; delete[] xc1; delete[] yc1; delete[] zc1; } /*********************************************************************** * NAME : void Trace::_CalculateHalpha() * * DESCRIPTION : Loop through all traces and their alpha values to * calculate h_alpha. * * ********************************************************************/ void Trace::_CalculateHalpha() { /* loop through each trace and alpha combination */ int i, j, k, I, J; for (i=0;i<n_;i++) { I = i*(nalpha_*MaxLen_); if (isfinite(FP_[i][12])) { for (j=0;j<nalpha_;j++) { J = j*MaxLen_; _CalculateTraceHalpha(i,j,Halpha3D_[i][j]); for (k=0;k<MaxLen_;k++) { Halpha_[I + J + k] = Halpha3D_[i][j][k]; } } } } setHalpha_ = true; } /*********************************************************************** * NAME : bool Trace::_CheckHalpha() * * DESCRIPTION : Checks that the object is set up correctly before it * attempts to calculate h_alpha. * * RETURNS : * bool true if it is ready. * * ********************************************************************/ bool Trace::_CheckHalpha() { if ((!allocAlpha_) || (!setAlpha_)) { printf("Run the 'SetAlpha()' function prior to calculating h_alpha\n"); return false; } if (nalpha_ <= 0) { printf("1 or more values of alpha must be provided to calculate h_alpha\n"); return false; } if (setHalpha_) { printf("H alpha already calculated\n"); return false; } return true; } /*********************************************************************** * NAME : void Trace::CalculateHalpha() * * DESCRIPTION : Calculate the h_alpha for all traces. * * * ********************************************************************/ void Trace::CalculateHalpha() { if (!_CheckHalpha()) { return; } /* allocate both 1D and 3D arrays */ Halpha_ = new double[n_*nalpha_*MaxLen_]; Halpha3D_ = new double**[n_]; int i, j; for (i=0;i<n_;i++) { Halpha3D_[i] = new double*[nalpha_]; for (j=0;j<nalpha_;j++) { Halpha3D_[i][j] = new double[MaxLen_]; } } allocHalpha_ = true; allocHalpha3D_ = true; _CalculateHalpha(); } /*********************************************************************** * NAME : void Trace::CalculateHalpha() * * DESCRIPTION : Calculate the h_alpha for all traces. * * OUPUTS : * double *halpha 1-D array containing all trace h_alphas * * ********************************************************************/ void Trace::CalculateHalpha(double *halpha) { if (!_CheckHalpha()) { return; } /* allocate 3D array and use pointer for 1D */ Halpha_ = halpha; Halpha3D_ = new double**[n_]; int i, j; for (i=0;i<n_;i++) { Halpha3D_[i] = new double*[nalpha_]; for (j=0;j<nalpha_;j++) { Halpha3D_[i][j] = new double[MaxLen_]; } } allocHalpha3D_ = true; _CalculateHalpha(); } /*********************************************************************** * NAME : void Trace::CalculateHalpha() * * DESCRIPTION : Calculate the h_alpha for all traces. * * OUPUTS : * double ***hapha3d 3D array containing all of the h_alphas * * ********************************************************************/ void Trace::CalculateHalpha(double ***halpha3d) { if (!_CheckHalpha()) { return; } /* allocate 1D and use pointer for 3D array */ Halpha_ = new double[n_*nalpha_*MaxLen_]; Halpha3D_ = halpha3d; allocHalpha_ = true; _CalculateHalpha(); } /*********************************************************************** * NAME : void Trace::CalculateHalpha() * * DESCRIPTION : Calculate the h_alpha for all traces. * * OUPUTS : * double *halpha 1-D array containing all trace h_alphas * double ***hapha3d 3D array containing all of the h_alphas * * ********************************************************************/ void Trace::CalculateHalpha(double *halpha, double ***halpha3d) { if (!_CheckHalpha()) { return; } /* use pointer for both 1D and 3D arrays */ Halpha_ = halpha; Halpha3D_ = halpha3d; _CalculateHalpha(); } /*********************************************************************** * NAME : void Trace::_CalculateHalphaStartPoints(i,j,xe0,ye0,ze0,xe1,ye1,ze1) * * DESCRIPTION : Calcualte the starting points for two adjacent traces * to one original trace (one it 180 degrees around from the other) * in order to calculate h_alpha. * * INPUTS : * int i Trace index * int j Alpha index * * OUPUTS : * double *xe0 Starting position for adjacent field line 0 * double *ye0 Starting position for adjacent field line 0 * double *ze0 Starting position for adjacent field line 0 * double *xe1 Starting position for adjacent field line 1 * double *ye1 Starting position for adjacent field line 1 * double *ze1 Starting position for adjacent field line 1 * * ********************************************************************/ void Trace::_CalculateHalphaStartPoints(int i, int j, double *xe0, double *ye0, double *ze0, double *xe1, double *ye1, double *ze1) { /* calculate the tracing start points for each alpha */ double dt, dp, beta, dx, dy; /* dt and dp are the toroidal and poloidal components of Delta */ dt = Delta_*cos(alpha0_[j]); // alpha = 0.0 is toroidal dp = Delta_*sin(alpha0_[j]); /* rotate based on the local time */ beta = atan2(-xfe_[i],-yfe_[i]); dy = dp*cos(beta) - dt*sin(beta); dx = dp*sin(beta) + dt*cos(beta); /* set the start points of the new field lines */ xe0[0] = xfe_[i] + dx; ye0[0] = yfe_[i] + dy; ze0[0] = zfe_[i]; xe1[0] = xfe_[i] - dx; ye1[0] = yfe_[i] - dy; ze1[0] = zfe_[i]; } /*********************************************************************** * NAME : void Trace::_AllocTrace() * * DESCRIPTION : Allocates arrays to store trace positions and fields * * ********************************************************************/ void Trace::_AllocTrace() { x_ = new double*[n_]; y_ = new double*[n_]; z_ = new double*[n_]; bx_ = new double*[n_]; by_ = new double*[n_]; bz_ = new double*[n_]; int i; for (i=0;i<n_;i++) { x_[i] = new double[MaxLen_]; y_[i] = new double[MaxLen_]; z_[i] = new double[MaxLen_]; bx_[i] = new double[MaxLen_]; by_[i] = new double[MaxLen_]; bz_[i] = new double[MaxLen_]; } allocTrace_ = true; } /*********************************************************************** * NAME : void Trace::_AllocTraceR() * * DESCRIPTION : Allocates Rmsm and Rmso arrays. * * ********************************************************************/ void Trace::_AllocTraceR() { Rmsm_ = new double*[n_]; Rmso_ = new double*[n_]; int i; for (i=0;i<n_;i++) { Rmsm_[i] = new double[MaxLen_]; Rmso_[i] = new double[MaxLen_]; } allocR_ = true; } /*********************************************************************** * NAME : void Trace::_AllocZmso() * 1 * DESCRIPTION : Allocates array to store zmso. * * ********************************************************************/ void Trace::_AllocZmso() { zmso_ = new double*[n_]; int i; for (i=0;i<n_;i++) { zmso_[i] = new double[MaxLen_]; } allocZmso_ = true; } /*********************************************************************** * NAME : void Trace::TraceField(nstep,x,y,z,Rmsm,Rmso,bx,by,bz) * * DESCRIPTION : Trace the field lines. * * OUTPUTS : * int *nstep Number of trace steps * double **x Trace positions * double **y Trace positions * double **z Trace positions * double **Rmsm Trace radial coordinates (MSM) * double **Rmso Trace radial coordinates (MSO) * double **Bx Trace field * double **By Trace field * double **Bz Trace field * * ********************************************************************/ void Trace::TraceField( int *nstep, double **x, double **y, double **z, double **Rmsm, double **Rmso, double **bx, double **by, double **bz) { /* link the pointers within the object to those supplied by this * function */ nstep_ = nstep; x_ = x; y_ = y; z_ = z; bx_ = bx; by_ = by; bz_ = bz; Rmsm_ = Rmsm; Rmso_ = Rmso; _AllocZmso(); /* call the tracing code */ _TraceField(); } /*********************************************************************** * NAME : void Trace::TraceField(nstep,x,y,z,bx,by,bz) * * DESCRIPTION : Trace the field lines. * * OUPUTS : * int *nstep Number of trace steps * double **x Trace positions * double **y Trace positions * double **z Trace positions * double **Bx Trace field * double **By Trace field * double **Bz Trace field * * ********************************************************************/ void Trace::TraceField( int *nstep, double **x, double **y, double **z, double **bx, double **by, double **bz) { /* link the pointers within the object to those supplied by this * function */ nstep_ = nstep; x_ = x; y_ = y; z_ = z; bx_ = bx; by_ = by; bz_ = bz; _AllocTraceR(); _AllocZmso(); /* call the tracing code */ _TraceField(); } /*********************************************************************** * NAME : void Trace::TraceField(nstep) * * DESCRIPTION : Trace the field lines. * * OUPUTS : * int *nstep Number of trace steps * * ********************************************************************/ void Trace::TraceField( int *nstep) { /* link the pointers within the object to those supplied by this * function */ nstep_ = nstep; _AllocTrace(); _AllocTraceR(); _AllocZmso(); /* call the tracing code */ _TraceField(); } /*********************************************************************** * NAME : void Trace::TraceField() * * DESCRIPTION : Trace the field lines. * * ********************************************************************/ void Trace::TraceField() { /* no pointers provided: allocate them*/ if (!allocNstep_) { nstep_ = new int[n_]; allocNstep_ = true; } _AllocTrace(); _AllocTraceR(); _AllocZmso(); /* call the tracing code */ _TraceField(); } /*********************************************************************** * NAME : void Trace::_TraceField() * * DESCRIPTION : Run the field traces. * * ********************************************************************/ void Trace::_TraceField() { /* this function actually calls the tracing routines */ /* check this hasn't already been done */ if (setTrace_) { printf("Attempted to trace twice? not happening mate...\n"); return; } /* check we have input positions */ if (!allocInputPos_) { printf("Need InputPos() before trace\n"); return; } /* check that we have model parameters */ if (!setModelParams_) { printf("Run SetModelParams() before tracing\n"); return; } /* check if all of the starting points are within the MP */ inMP_ = new bool[n_]; allocMP_ = true; int i; for (i=0;i<n_;i++) { inMP_[i] = WithinMP(x0_[i],y0_[i],z0_[i],Rsm_[i]); } for (i=0;i<n_;i++) { if (Verbose_) { printf("\rTracing field line %d of %d (%6.2f)%%",i+1,n_,((float) (i+1)*100.0)/n_); } if (inMP_[i]) { /* set current trace parameters */ ktmodel.SetParams(Rsm_[i],t1_[i],t2_[i]); /* perform trace */ RKMTrace( x0_[i],y0_[i],z0_[i],&nstep_[i], x_[i],y_[i],z_[i], zmso_[i],Rmsm_[i],Rmso_[i], bx_[i],by_[i],bz_[i]); } else { /*fill with NaN*/ nstep_[i] = 0; } } if (Verbose_) { printf("\n"); } setTrace_ = true; } /*********************************************************************** * NAME : void Trace::CalculateTraceDist() * * DESCRIPTION : Calculate the distances along each field line. * * ********************************************************************/ void Trace::CalculateTraceDist() { int i; S_ = new double*[n_]; for (i=0;i<n_;i++) { S_[i] = new double[MaxLen_]; } allocDist_ = true; _CalculateTraceDist(); } /*********************************************************************** * NAME : void Trace::CalculateTraceDist(S) * * DESCRIPTION : Calculate the distances along each field line. * * OUPUTS : * double **S Distance along each field line. * * ********************************************************************/ void Trace::CalculateTraceDist(double **S) { S_ = S; _CalculateTraceDist(); } /*********************************************************************** * NAME : void Trace_CalcualteTraceDist() * * DESCRIPTION : Calcualtes the distance along all field lines. * * ********************************************************************/ void Trace::_CalculateTraceDist() { int i, j; double dx, dy, dz; for (i=0;i<n_;i++) { S_[i][0] = 0.0; for (j=1;j<nstep_[i];j++) { dx = x_[i][j] - x_[i][j-1]; dy = y_[i][j] - y_[i][j-1]; dz = z_[i][j] - z_[i][j-1]; S_[i][j] = S_[i][j-1] + sqrt(dx*dx + dy*dy + dz*dz); } } setDist_ = true; } /*********************************************************************** * NAME : void Trace::CalculateTraceRnorm() * * DESCRIPTION : Calcualtes the Rnorm value along each trace. * * ********************************************************************/ void Trace::CalculateTraceRnorm() { int i; Rnorm_ = new double*[n_]; for (i=0;i<n_;i++) { Rnorm_[i] = new double[MaxLen_]; } allocRnorm_ = true; _CalculateTraceRnorm(); } /*********************************************************************** * NAME : void Trace::CalculateTraceRnorm(Rnorm) * * DESCRIPTION : Calcualtes the Rnorm value along each trace. * * OUPUTS : * double **Rnorm Rnorm along each trace. * * ********************************************************************/ void Trace::CalculateTraceRnorm(double **Rnorm) { Rnorm_ = Rnorm; _CalculateTraceRnorm(); } /*********************************************************************** * NAME : void Trace::_CalculateTraceRnorm() * * DESCRIPTION : Calcualtes Rnorm values for all traces. * * ********************************************************************/ void Trace::_CalculateTraceRnorm() { int i, j; for (i=0;i<n_;i++) { for (j=0;j<nstep_[i];j++) { /* need footprints and R done first */ FieldLineRnorm(nstep_[i],Rmsm_[i],FP_[i][16],Rnorm_[i]); } } setRnorm_ = true; } /*********************************************************************** * NAME : void Trace::CalculateTraceFP() * * DESCRIPTION : Works out where all of the footprints are for each * trace. * * * ********************************************************************/ void Trace::CalculateTraceFP() { int i; FP_ = new double*[n_]; for (i=0;i<n_;i++) { FP_[i] = new double[18]; } allocFootprints_ = true; _CalculateTraceFP(); } /*********************************************************************** * NAME : void Trace::CalculateTraceFP() * * DESCRIPTION : Works out where all of the footprints are for each * trace. * * OUPUTS : * double **FP Output footprint coords, shape (n,18), where n * is the number of traces and the elements in the * 2nd dimension correspond to the following * footprints: * 0: North planetary latitude * 1: North planetary local time * 2: South planetary latitude * 3: South planetary local time * 4: North core latitude * 5: North core local time * 6: South core latitude * 7: South core local time * 8: North dipole R=1 latitude * 9: North dipole R=1 local time * 10: South dipole R=1 latitude * 11: South dipole R=1 local time * 12: North dipole R=0.832 latitude * 13: North dipole R=0.832 local time * 14: South dipole R=0.832 latitude * 15: South dipole R=0.832 local time * 16: L-shell * 17: Equatorial footprint magnetic local time. * * NOTE: core is assumed to be a sphere at * Rmso = 0.832 Rm and the dipole footprints * are footprints on a sphere centered on the * dipole rather than the planet itself. * * * ********************************************************************/ void Trace::CalculateTraceFP(double **FP) { FP_ = FP; _CalculateTraceFP(); } /*********************************************************************** * NAME : void Trace::_CalculateTraceFP() * * DESCRIPTION : Calculates all footprints for each trace. * * ********************************************************************/ void Trace::_CalculateTraceFP() { /* before running this we should check that the following functions * have been called: * 1. TraceField() * 2. CalcualteTraceDist() */ if (!setTrace_) { printf("Call TraceField() before calculating footprints\n"); return; } if (!setDist_) { printf("Call CalcualteTraceDist() before calculating footprints\n"); return; } /* allocate the endpoints */ xfn_ = new double[n_]; yfn_ = new double[n_]; zfn_ = new double[n_]; xfs_ = new double[n_]; yfs_ = new double[n_]; zfs_ = new double[n_]; xfnc_ = new double[n_]; yfnc_ = new double[n_]; zfnc_ = new double[n_]; xfsc_ = new double[n_]; yfsc_ = new double[n_]; zfsc_ = new double[n_]; xfnv_ = new double[n_]; yfnv_ = new double[n_]; zfnv_ = new double[n_]; xfsv_ = new double[n_]; yfsv_ = new double[n_]; zfsv_ = new double[n_]; xfnvc_ = new double[n_]; yfnvc_ = new double[n_]; zfnvc_ = new double[n_]; xfsvc_ = new double[n_]; yfsvc_ = new double[n_]; zfsvc_ = new double[n_]; allocEndpoints_ = true; xfe_ = new double[n_]; yfe_ = new double[n_]; zfe_ = new double[n_]; allocEqFP_ = true; int i, j; for (i=0;i<n_;i++) { _SingleTraceFP(i); } /* calculate the lats/ locals times for each footprint */ _FPCoords(); setFootprints_ = true; } /*********************************************************************** * NAME : void Trace::FPCoords() * * DESCRIPTION : Converts Cartesian footprint positions to latitude, * local times and L shell. * * ********************************************************************/ void Trace::_FPCoords() { int i; for (i=0;i<n_;i++) { /* surface */ LatLT(xfn_[i],yfn_[i],zfn_[i],&FP_[i][0],&FP_[i][1]); LatLT(xfs_[i],yfs_[i],zfs_[i],&FP_[i][2],&FP_[i][3]); /* core */ LatLT(xfnc_[i],yfnc_[i],zfnc_[i],&FP_[i][4],&FP_[i][5]); LatLT(xfsc_[i],yfsc_[i],zfsc_[i],&FP_[i][6],&FP_[i][7]); /* dipole R = 1 */ LatLT(xfnv_[i],yfnv_[i],zfnv_[i],&FP_[i][8],&FP_[i][9]); LatLT(xfsv_[i],yfsv_[i],zfsv_[i],&FP_[i][10],&FP_[i][11]); /* dipole R = 0.832 */ LatLT(xfnvc_[i],yfnvc_[i],zfnvc_[i],&FP_[i][12],&FP_[i][13]); LatLT(xfsvc_[i],yfsvc_[i],zfsvc_[i],&FP_[i][14],&FP_[i][15]); /* equatorial */ LshellMLT(xfe_[i],yfe_[i],zfe_[i],&FP_[i][16],&FP_[i][17]); } } /*********************************************************************** * NAME : void Trace::_InterpPos(xi,yi,zi,s,t,target,xo,yo,zo) * * DESCRIPTION : Attempt to work out a position along a trace which * corresponds to some target value along a target array (t) using * linear interpolation. * * e.g. For the northern footprint on the planet, we provide * the two positions surrounding Rmso = 1, their corresponding * trace distances (s), target arrays (R) and target value (R=1): * _InterpPos(xi,yi,zi,s,R,1.0,xo,yo,zo) * * It works out what trace distance corresponds to t == target * first, then uses interpolation to work out what x,y,z * corresponds to that same distance. * * * INPUTS : * double *xi Position along trace around target. * double *yi Position along trace around target. * double *zi Position along trace around target. * double *s distance along field line around target. * double *t target array. * double *target target values (~between t[0] and t[1]) * * OUPUTS : * double *x0 Output position * double *y0 Output position * double *z0 Output position * * ********************************************************************/ void Trace::_InterpPos( double *xi, double *yi, double *zi, double *s, double *t, double target, double *xo, double *yo, double *zo) { /* calculate the gradients wrt to t and s */ double s_targ, ds; double m, mx, my, mz; double c, cx, cy, cz; ds = (s[1] - s[0]); m = ds/(t[1] - t[0]); c = s[0] - m*t[0]; mx = (xi[1] - xi[0])/ds; cx = xi[0] - mx*s[0]; my = (yi[1] - yi[0])/ds; cy = yi[0] - my*s[0]; mz = (zi[1] - zi[0])/ds; cz = zi[0] - mz*s[0]; /* this is the distance along the field line where our target * array (t) crosses the target value (target) */ s_targ = c + target*m; /* calculate target crossing footprints */ xo[0] = cx + mx*s_targ; yo[0] = cy + my*s_targ; zo[0] = cz + mz*s_targ; } /*********************************************************************** * NAME : void Trace::_SingleTraceFP(I) * * DESCRIPTION : Calculate the footprints for a trace. * * INPUTS : * int I Trace index. * * ******************************************!**************************/ void Trace::_SingleTraceFP( int I) { int i; int eq_ind = -1; int n_ind = -1; int s_ind = -1; int nv_ind = -1; int sv_ind = -1; int nc_ind = -1; int sc_ind = -1; int nvc_ind = -1; int svc_ind = -1; /* check inMP */ if ((inMP_[I]) && (nstep_[I] > 1)) { /* check if there's an equator crossing */ for (i=0;i<nstep_[I]-1;i++) { if ((z_[I][i+1] >= 0) && (z_[I][i] < 0)) { eq_ind = i; break; } } /* southern footprints */ for (i=0;i<nstep_[I]-1;i++) { /* check that we're still in the south */ if ((Rmsm_[I][i+1] < Rmsm_[I][i]) || (Rmsm_[I][i] >= 2.0)) { break; } /* find where we cross Rmso == 1.0 */ if ((Rmso_[I][i] <= 1.0) && (Rmso_[I][i+1] > 1.0)) { s_ind = i; } /* find where we cross Rmso == 0.832 */ if ((Rmso_[I][i] <= 0.832) && (Rmso_[I][i+1] > 0.832)) { sc_ind = i; } /* find where we cross Rmsm == 1.0 */ if ((Rmsm_[I][i] <= 1.0) && (Rmsm_[I][i+1] > 1.0)) { sv_ind = i; } /* find where we cross Rmsm == 0.832 */ if ((Rmsm_[I][i] <= 0.832) && (Rmsm_[I][i+1] > 0.832)) { svc_ind = i; } } /* northern footprints */ for (i=nstep_[I]-2;i>=0;i--) { /* check that we're still in the south */ if ((Rmsm_[I][i+1] > Rmsm_[I][i]) || (Rmsm_[I][i] >= 2.0)) { break; } /* find where we cross Rmso == 1.0 */ if ((Rmso_[I][i] > 1.0) && (Rmso_[I][i+1] <= 1.0)) { n_ind = i; } /* find where we cross Rmso == 0.832 */ if ((Rmso_[I][i] > 0.832) && (Rmso_[I][i+1] <= 0.832)) { nc_ind = i; } /* find where we cross Rmsm == 1.0 */ if ((Rmsm_[I][i] > 1.0) && (Rmsm_[I][i+1] <= 1.0)) { nv_ind = i; } /* find where we cross Rmsm == 0.832 */ if ((Rmsm_[I][i] > 0.832) && (Rmsm_[I][i+1] <= 0.832)) { nvc_ind = i; } } } /* set equatorial footprint */ if (eq_ind >= 0) { /* interpolate for the point where z = 0*/ _InterpPos( &x_[I][eq_ind],&y_[I][eq_ind],&z_[I][eq_ind], &S_[I][eq_ind],&z_[I][eq_ind],0.0, &xfe_[I],&yfe_[I],&zfe_[I]); } else { xfe_[I] = NAN; yfe_[I] = NAN; zfe_[I] = NAN; } /* northern surface */ if (n_ind >= 0) { _InterpPos( &x_[I][n_ind],&y_[I][n_ind],&zmso_[I][n_ind], &S_[I][n_ind],&Rmso_[I][n_ind],1.0, &xfn_[I],&yfn_[I],&zfn_[I]); } else { xfn_[I] = NAN; yfn_[I] = NAN; zfn_[I] = NAN; } /* southern surface */ if (s_ind >= 0) { _InterpPos( &x_[I][s_ind],&y_[I][s_ind],&zmso_[I][s_ind], &S_[I][s_ind],&Rmso_[I][s_ind],1.0, &xfs_[I],&yfs_[I],&zfs_[I]); } else { xfs_[I] = NAN; yfs_[I] = NAN; zfs_[I] = NAN; } /* northern core */ if (nc_ind >= 0) { _InterpPos( &x_[I][nc_ind],&y_[I][nc_ind],&zmso_[I][nc_ind], &S_[I][nc_ind],&Rmso_[I][nc_ind],0.832, &xfnc_[I],&yfnc_[I],&zfnc_[I]); } else { xfnc_[I] = NAN; yfnc_[I] = NAN; zfnc_[I] = NAN; } /* southern core */ if (sc_ind >= 0) { _InterpPos( &x_[I][sc_ind],&y_[I][sc_ind],&zmso_[I][sc_ind], &S_[I][sc_ind],&Rmso_[I][sc_ind],0.832, &xfsc_[I],&yfsc_[I],&zfsc_[I]); } else { xfsc_[I] = NAN; yfsc_[I] = NAN; zfsc_[I] = NAN; } /* northern dipole surface */ if (nv_ind >= 0) { _InterpPos( &x_[I][nv_ind],&y_[I][nv_ind],&z_[I][nv_ind], &S_[I][nv_ind],&Rmsm_[I][nv_ind],1.0, &xfnv_[I],&yfnv_[I],&zfnv_[I]); } else { xfnv_[I] = NAN; yfnv_[I] = NAN; zfnv_[I] = NAN; } /* southern dipole surface */ if (sv_ind >= 0) { _InterpPos( &x_[I][sv_ind],&y_[I][sv_ind],&z_[I][sv_ind], &S_[I][sv_ind],&Rmsm_[I][sv_ind],1.0, &xfsv_[I],&yfsv_[I],&zfsv_[I]); } else { xfsv_[I] = NAN; yfsv_[I] = NAN; zfsv_[I] = NAN; } /* northern dipole core */ if (nvc_ind >= 0) { _InterpPos( &x_[I][nvc_ind],&y_[I][nvc_ind],&z_[I][nvc_ind], &S_[I][nvc_ind],&Rmsm_[I][nvc_ind],0.832, &xfnvc_[I],&yfnvc_[I],&zfnvc_[I]); } else { xfnvc_[I] = NAN; yfnvc_[I] = NAN; zfnvc_[I] = NAN; } /* southern dipole core */ if (svc_ind >= 0) { _InterpPos( &x_[I][svc_ind],&y_[I][svc_ind],&z_[I][svc_ind], &S_[I][svc_ind],&Rmsm_[I][svc_ind],0.832, &xfsvc_[I],&yfsvc_[I],&zfsvc_[I]); } else { xfsvc_[I] = NAN; yfsvc_[I] = NAN; zfsvc_[I] = NAN; } } /*********************************************************************** * NAME : void Trace::GetTrace(x,y,z) * * DESCRIPTION : Get trace positions. * * OUPUTS : * double **x Positions along traces. * double **y Positions along traces. * double **z Positions along traces. * * ********************************************************************/ void Trace::GetTrace(double **x,double **y, double **z) { /* copy GSM position into output arrays*/ int i, j; for (i=0;i<n_;i++) { for (j=0;j<nstep_[i];j++) { x[i][j] = x_[i][j]; y[i][j] = y_[i][j]; z[i][j] = z_[i][j]; } } } /*********************************************************************** * NAME : void Trace::GetTrace(x,y,z) * * DESCRIPTION : Get trace positions and field vectors. * * OUPUTS : * double **x Positions along traces. * double **y Positions along traces. * double **z Positions along traces. * double **Bx Field along traces * double **By Field along traces * double **Bz Field along traces * * ********************************************************************/ void Trace::GetTrace( double **x,double **y, double **z, double **Bx,double **By, double **Bz) { /* copy GSM field into output arrays*/ int i, j; for (i=0;i<n_;i++) { for (j=0;j<nstep_[i];j++) { Bx[i][j] = bx_[i][j]; By[i][j] = by_[i][j]; Bz[i][j] = bz_[i][j]; } } /* get the position */ GetTrace(x,y,z); } /*********************************************************************** * NAME : void Trace::GetTraceDist(S) * * DESCRIPTION : Get the distance along the field traces. * * OUPUTS : * double **S Trace distance. * * ********************************************************************/ void Trace::GetTraceDist(double **S) { int i, j; for (i=0;i<n_;i++) { for (j=0;j<nstep_[i];j++) { S[i][j] = S_[i][j]; } } } /*********************************************************************** * NAME : void Trace::GetTraceRmsm(Rmsm) * * DESCRIPTION : Get the radial coodinate along each trace (MSM) * * OUPUTS : * double **Rmsm radial coordinates (MSM) * * ********************************************************************/ void Trace::GetTraceRmsm(double **Rmsm) { int i, j; for (i=0;i<n_;i++) { for (j=0;j<nstep_[i];j++) { Rmsm[i][j] = Rmsm_[i][j]; } } } /*********************************************************************** * NAME : void Trace::GetTraceRmso(Rmso) * * DESCRIPTION : Get the radial coodinate along each trace (MSO) * * OUPUTS : * double **Rmso radial coordinates (MSO) * * ********************************************************************/ void Trace::GetTraceRmso(double **Rmso) { int i, j; for (i=0;i<n_;i++) { for (j=0;j<nstep_[i];j++) { Rmso[i][j] = Rmso_[i][j]; } } } /*********************************************************************** * NAME : void Trace::GetTraceRnorm(Rnorm) * * DESCRIPTION : Get the Rnorms for each trace. * * OUPUTS : * double **Rnorm Array of Rnorms. * * ********************************************************************/ void Trace::GetTraceRnorm(double **Rnorm) { int i, j; for (i=0;i<n_;i++) { for (j=0;j<nstep_[i];j++) { Rnorm[i][j] = Rnorm_[i][j]; } } } /*********************************************************************** * NAME : void Trace::GetTraceFootprints(FP) * * DESCRIPTION : Get the trace footprints for all traces. * * OUPUTS : * double **FP Output footprint coords, shape (n,18), where n * is the number of traces and the elements in the * 2nd dimension correspond to the following * footprints: * 0: North planetary latitude * 1: North planetary local time * 2: South planetary latitude * 3: South planetary local time * 4: North core latitude * 5: North core local time * 6: South core latitude * 7: South core local time * 8: North dipole R=1 latitude * 9: North dipole R=1 local time * 10: South dipole R=1 latitude * 11: South dipole R=1 local time * 12: North dipole R=0.832 latitude * 13: North dipole R=0.832 local time * 14: South dipole R=0.832 latitude * 15: South dipole R=0.832 local time * 16: L-shell * 17: Equatorial footprint magnetic local time. * * NOTE: core is assumed to be a sphere at * Rmso = 0.832 Rm and the dipole footprints * are footprints on a sphere centered on the * dipole rather than the planet itself. * * ********************************************************************/ void Trace::GetTraceFootprints(double **FP) { int i, j; for (i=0;i<n_;i++) { for (j=0;j<15;j++) { FP[i][j] = FP_[i][j]; } } } /*********************************************************************** * NAME : void Trace::GetTraceNstep(nstep) * * DESCRIPTION : Get the number of steps in each trace. * * OUPUTS : * int *nstep Number of steps in each trace. * * ********************************************************************/ void Trace::GetTraceNstep(int *nstep) { int i; for (i=0;i<n_;i++) { nstep[i] = nstep_[i]; } }
53,040
22,751
#include <QApplication> #include <QQmlApplicationEngine> #include "fileio.h" #include "clipboard.h" #include "library.h" #include <qqml.h> #include <QResource> #include <QQmlContext> #include <QVariant> #include <QDebug> struct GraphblocksContext { graphblocks::Library m_lib; }; GraphblocksContext* initializeGraphBlocks() { // Note: this is not 1 to 1 qmlContext <-> Library <-> gbContext! Use other mechanism with global object for qmlcontext. The gb is always connected with a specific qml context. Q_INIT_RESOURCE(graphblocks); //QResource::registerResource("qml.rcc"); GraphblocksContext* ctx = new GraphblocksContext(); qmlRegisterType<graphblocks::FileIO, 1>("FileIO", 1, 0, "FileIO"); qmlRegisterSingletonType<graphblocks::Clipboard>("Clipboard", 1, 0, "Clipboard", &graphblocks::Clipboard::qmlInstance); qmlRegisterSingletonType<graphblocks::Library>("Library", 1, 0, "Library", &graphblocks::Library::qmlInstance); return new GraphblocksContext(); } void addGraphBlocksLibrary(QQmlEngine *ctx, const QString &libname, const QString &folder) { graphblocks::Library *lib = graphblocks::Library::getInstance( ctx ); if( !lib ) { qDebug() << "Library manager not avaliable"; return; } lib->addLibrary(libname, folder); } void shutdownGraphBlocks(GraphblocksContext *ctx) { delete ctx; }
1,374
463
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ #include "IntStream.h" #include "atn/OrderedATNConfigSet.h" #include "Token.h" #include "LexerNoViableAltException.h" #include "atn/RuleStopState.h" #include "atn/RuleTransition.h" #include "atn/SingletonPredictionContext.h" #include "atn/PredicateTransition.h" #include "atn/ActionTransition.h" #include "atn/TokensStartState.h" #include "misc/Interval.h" #include "dfa/DFA.h" #include "Lexer.h" #include "dfa/DFAState.h" #include "atn/LexerATNConfig.h" #include "atn/LexerActionExecutor.h" #include "atn/EmptyPredictionContext.h" #include "atn/LexerATNSimulator.h" #define DEBUG_ATN 0 #define DEBUG_DFA 0 using namespace antlr4; using namespace antlr4::atn; using namespace antlrcpp; // Removed by TGAY 10/2020 (now defined in header) // Fixes 'undefined reference to `antlr4::atn::LexerATNSimulator::SimState::~SimState()' on Windows // LexerATNSimulator::SimState::~SimState() { } void LexerATNSimulator::SimState::reset() { index = INVALID_INDEX; line = 0; charPos = INVALID_INDEX; dfaState = nullptr; // Don't delete. It's just a reference. } void LexerATNSimulator::SimState::InitializeInstanceFields() { index = INVALID_INDEX; line = 0; charPos = INVALID_INDEX; } int LexerATNSimulator::match_calls = 0; LexerATNSimulator::LexerATNSimulator(const ATN &atn, std::vector<dfa::DFA> &decisionToDFA, PredictionContextCache &sharedContextCache) : LexerATNSimulator(nullptr, atn, decisionToDFA, sharedContextCache) { } LexerATNSimulator::LexerATNSimulator(Lexer *recog, const ATN &atn, std::vector<dfa::DFA> &decisionToDFA, PredictionContextCache &sharedContextCache) : ATNSimulator(atn, sharedContextCache), _recog(recog), _decisionToDFA(decisionToDFA) { InitializeInstanceFields(); } void LexerATNSimulator::copyState(LexerATNSimulator *simulator) { _charPositionInLine = simulator->_charPositionInLine; _line = simulator->_line; _mode = simulator->_mode; _startIndex = simulator->_startIndex; } size_t LexerATNSimulator::match(CharStream *input, size_t mode) { match_calls++; _mode = mode; ssize_t mark = input->mark(); auto onExit = finally([input, mark] { input->release(mark); }); _startIndex = input->index(); _prevAccept.reset(); const dfa::DFA &dfa = _decisionToDFA[mode]; if (dfa.s0 == nullptr) { return matchATN(input); } else { return execATN(input, dfa.s0); } } void LexerATNSimulator::reset() { _prevAccept.reset(); _startIndex = 0; _line = 1; _charPositionInLine = 0; _mode = Lexer::DEFAULT_MODE; } void LexerATNSimulator::clearDFA() { size_t size = _decisionToDFA.size(); _decisionToDFA.clear(); for (size_t d = 0; d < size; ++d) { _decisionToDFA.emplace_back(atn.getDecisionState(d), d); } } size_t LexerATNSimulator::matchATN(CharStream *input) { ATNState *startState = atn.modeToStartState[_mode]; std::unique_ptr<ATNConfigSet> s0_closure = computeStartState(input, startState); bool suppressEdge = s0_closure->hasSemanticContext; s0_closure->hasSemanticContext = false; dfa::DFAState *next = addDFAState(s0_closure.release()); if (!suppressEdge) { _decisionToDFA[_mode].s0 = next; } size_t predict = execATN(input, next); return predict; } size_t LexerATNSimulator::execATN(CharStream *input, dfa::DFAState *ds0) { if (ds0->isAcceptState) { // allow zero-length tokens // ml: in Java code this method uses 3 params. The first is a member var of the class anyway (_prevAccept), so why pass it here? captureSimState(input, ds0); } size_t t = input->LA(1); dfa::DFAState *s = ds0; // s is current/from DFA state while (true) { // while more work // As we move src->trg, src->trg, we keep track of the previous trg to // avoid looking up the DFA state again, which is expensive. // If the previous target was already part of the DFA, we might // be able to avoid doing a reach operation upon t. If s!=null, // it means that semantic predicates didn't prevent us from // creating a DFA state. Once we know s!=null, we check to see if // the DFA state has an edge already for t. If so, we can just reuse // it's configuration set; there's no point in re-computing it. // This is kind of like doing DFA simulation within the ATN // simulation because DFA simulation is really just a way to avoid // computing reach/closure sets. Technically, once we know that // we have a previously added DFA state, we could jump over to // the DFA simulator. But, that would mean popping back and forth // a lot and making things more complicated algorithmically. // This optimization makes a lot of sense for loops within DFA. // A character will take us back to an existing DFA state // that already has lots of edges out of it. e.g., .* in comments. dfa::DFAState *target = getExistingTargetState(s, t); if (target == nullptr) { target = computeTargetState(input, s, t); } if (target == ERROR.get()) { break; } // If this is a consumable input element, make sure to consume before // capturing the accept state so the input index, line, and char // position accurately reflect the state of the interpreter at the // end of the token. if (t != Token::EOF) { consume(input); } if (target->isAcceptState) { captureSimState(input, target); if (t == Token::EOF) { break; } } t = input->LA(1); s = target; // flip; current DFA target becomes new src/from state } return failOrAccept(input, s->configs.get(), t); } dfa::DFAState *LexerATNSimulator::getExistingTargetState(dfa::DFAState *s, size_t t) { dfa::DFAState* retval = nullptr; _edgeLock.readLock(); if (t <= MAX_DFA_EDGE) { auto iterator = s->edges.find(t - MIN_DFA_EDGE); #if DEBUG_ATN == 1 if (iterator != s->edges.end()) { std::cout << std::string("reuse state ") << s->stateNumber << std::string(" edge to ") << iterator->second->stateNumber << std::endl; } #endif if (iterator != s->edges.end()) retval = iterator->second; } _edgeLock.readUnlock(); return retval; } dfa::DFAState *LexerATNSimulator::computeTargetState(CharStream *input, dfa::DFAState *s, size_t t) { OrderedATNConfigSet *reach = new OrderedATNConfigSet(); /* mem-check: deleted on error or managed by new DFA state. */ // if we don't find an existing DFA state // Fill reach starting from closure, following t transitions getReachableConfigSet(input, s->configs.get(), reach, t); if (reach->isEmpty()) { // we got nowhere on t from s if (!reach->hasSemanticContext) { // we got nowhere on t, don't throw out this knowledge; it'd // cause a failover from DFA later. delete reach; addDFAEdge(s, t, ERROR.get()); } // stop when we can't match any more char return ERROR.get(); } // Add an edge from s to target DFA found/created for reach return addDFAEdge(s, t, reach); } size_t LexerATNSimulator::failOrAccept(CharStream *input, ATNConfigSet *reach, size_t t) { if (_prevAccept.dfaState != nullptr) { Ref<LexerActionExecutor> lexerActionExecutor = _prevAccept.dfaState->lexerActionExecutor; accept(input, lexerActionExecutor, _startIndex, _prevAccept.index, _prevAccept.line, _prevAccept.charPos); return _prevAccept.dfaState->prediction; } else { // if no accept and EOF is first char, return EOF if (t == Token::EOF && input->index() == _startIndex) { return Token::EOF; } throw LexerNoViableAltException(_recog, input, _startIndex, reach); } } void LexerATNSimulator::getReachableConfigSet(CharStream *input, ATNConfigSet *closure_, ATNConfigSet *reach, size_t t) { // this is used to skip processing for configs which have a lower priority // than a config that already reached an accept state for the same rule size_t skipAlt = ATN::INVALID_ALT_NUMBER; for (auto c : closure_->configs) { bool currentAltReachedAcceptState = c->alt == skipAlt; if (currentAltReachedAcceptState && (std::static_pointer_cast<LexerATNConfig>(c))->hasPassedThroughNonGreedyDecision()) { continue; } #if DEBUG_ATN == 1 std::cout << "testing " << getTokenName((int)t) << " at " << c->toString(true) << std::endl; #endif size_t n = c->state->transitions.size(); for (size_t ti = 0; ti < n; ti++) { // for each transition Transition *trans = c->state->transitions[ti]; ATNState *target = getReachableTarget(trans, (int)t); if (target != nullptr) { Ref<LexerActionExecutor> lexerActionExecutor = std::static_pointer_cast<LexerATNConfig>(c)->getLexerActionExecutor(); if (lexerActionExecutor != nullptr) { lexerActionExecutor = lexerActionExecutor->fixOffsetBeforeMatch((int)input->index() - (int)_startIndex); } bool treatEofAsEpsilon = t == Token::EOF; Ref<LexerATNConfig> config = std::make_shared<LexerATNConfig>(std::static_pointer_cast<LexerATNConfig>(c), target, lexerActionExecutor); if (closure(input, config, reach, currentAltReachedAcceptState, true, treatEofAsEpsilon)) { // any remaining configs for this alt have a lower priority than // the one that just reached an accept state. skipAlt = c->alt; break; } } } } } void LexerATNSimulator::accept(CharStream *input, const Ref<LexerActionExecutor> &lexerActionExecutor, size_t /*startIndex*/, size_t index, size_t line, size_t charPos) { #if DEBUG_ATN == 1 std::cout << "ACTION "; std::cout << toString(lexerActionExecutor) << std::endl; #endif // seek to after last char in token input->seek(index); _line = line; _charPositionInLine = (int)charPos; if (lexerActionExecutor != nullptr && _recog != nullptr) { lexerActionExecutor->execute(_recog, input, _startIndex); } } atn::ATNState *LexerATNSimulator::getReachableTarget(Transition *trans, size_t t) { if (trans->matches(t, Lexer::MIN_CHAR_VALUE, Lexer::MAX_CHAR_VALUE)) { return trans->target; } return nullptr; } std::unique_ptr<ATNConfigSet> LexerATNSimulator::computeStartState(CharStream *input, ATNState *p) { Ref<PredictionContext> initialContext = PredictionContext::EMPTY; // ml: the purpose of this assignment is unclear std::unique_ptr<ATNConfigSet> configs(new OrderedATNConfigSet()); for (size_t i = 0; i < p->transitions.size(); i++) { ATNState *target = p->transitions[i]->target; Ref<LexerATNConfig> c = std::make_shared<LexerATNConfig>(target, (int)(i + 1), initialContext); closure(input, c, configs.get(), false, false, false); } return configs; } bool LexerATNSimulator::closure(CharStream *input, const Ref<LexerATNConfig> &config, ATNConfigSet *configs, bool currentAltReachedAcceptState, bool speculative, bool treatEofAsEpsilon) { #if DEBUG_ATN == 1 std::cout << "closure(" << config->toString(true) << ")" << std::endl; #endif if (is<RuleStopState *>(config->state)) { #if DEBUG_ATN == 1 if (_recog != nullptr) { std::cout << "closure at " << _recog->getRuleNames()[config->state->ruleIndex] << " rule stop " << config << std::endl; } else { std::cout << "closure at rule stop " << config << std::endl; } #endif if (config->context == nullptr || config->context->hasEmptyPath()) { if (config->context == nullptr || config->context->isEmpty()) { configs->add(config); return true; } else { configs->add(std::make_shared<LexerATNConfig>(config, config->state, PredictionContext::EMPTY)); currentAltReachedAcceptState = true; } } if (config->context != nullptr && !config->context->isEmpty()) { for (size_t i = 0; i < config->context->size(); i++) { if (config->context->getReturnState(i) != PredictionContext::EMPTY_RETURN_STATE) { std::weak_ptr<PredictionContext> newContext = config->context->getParent(i); // "pop" return state ATNState *returnState = atn.states[config->context->getReturnState(i)]; Ref<LexerATNConfig> c = std::make_shared<LexerATNConfig>(config, returnState, newContext.lock()); currentAltReachedAcceptState = closure(input, c, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon); } } } return currentAltReachedAcceptState; } // optimization if (!config->state->epsilonOnlyTransitions) { if (!currentAltReachedAcceptState || !config->hasPassedThroughNonGreedyDecision()) { configs->add(config); } } ATNState *p = config->state; for (size_t i = 0; i < p->transitions.size(); i++) { Transition *t = p->transitions[i]; Ref<LexerATNConfig> c = getEpsilonTarget(input, config, t, configs, speculative, treatEofAsEpsilon); if (c != nullptr) { currentAltReachedAcceptState = closure(input, c, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon); } } return currentAltReachedAcceptState; } Ref<LexerATNConfig> LexerATNSimulator::getEpsilonTarget(CharStream *input, const Ref<LexerATNConfig> &config, Transition *t, ATNConfigSet *configs, bool speculative, bool treatEofAsEpsilon) { Ref<LexerATNConfig> c = nullptr; switch (t->getSerializationType()) { case Transition::RULE: { RuleTransition *ruleTransition = static_cast<RuleTransition*>(t); Ref<PredictionContext> newContext = SingletonPredictionContext::create(config->context, ruleTransition->followState->stateNumber); c = std::make_shared<LexerATNConfig>(config, t->target, newContext); break; } case Transition::PRECEDENCE: throw UnsupportedOperationException("Precedence predicates are not supported in lexers."); case Transition::PREDICATE: { /* Track traversing semantic predicates. If we traverse, we cannot add a DFA state for this "reach" computation because the DFA would not test the predicate again in the future. Rather than creating collections of semantic predicates like v3 and testing them on prediction, v4 will test them on the fly all the time using the ATN not the DFA. This is slower but semantically it's not used that often. One of the key elements to this predicate mechanism is not adding DFA states that see predicates immediately afterwards in the ATN. For example, a : ID {p1}? | ID {p2}? ; should create the start state for rule 'a' (to save start state competition), but should not create target of ID state. The collection of ATN states the following ID references includes states reached by traversing predicates. Since this is when we test them, we cannot cash the DFA state target of ID. */ PredicateTransition *pt = static_cast<PredicateTransition*>(t); #if DEBUG_ATN == 1 std::cout << "EVAL rule " << pt->ruleIndex << ":" << pt->predIndex << std::endl; #endif configs->hasSemanticContext = true; if (evaluatePredicate(input, pt->ruleIndex, pt->predIndex, speculative)) { c = std::make_shared<LexerATNConfig>(config, t->target); } break; } case Transition::ACTION: if (config->context == nullptr|| config->context->hasEmptyPath()) { // execute actions anywhere in the start rule for a token. // // TODO: if the entry rule is invoked recursively, some // actions may be executed during the recursive call. The // problem can appear when hasEmptyPath() is true but // isEmpty() is false. In this case, the config needs to be // split into two contexts - one with just the empty path // and another with everything but the empty path. // Unfortunately, the current algorithm does not allow // getEpsilonTarget to return two configurations, so // additional modifications are needed before we can support // the split operation. Ref<LexerActionExecutor> lexerActionExecutor = LexerActionExecutor::append(config->getLexerActionExecutor(), atn.lexerActions[static_cast<ActionTransition *>(t)->actionIndex]); c = std::make_shared<LexerATNConfig>(config, t->target, lexerActionExecutor); break; } else { // ignore actions in referenced rules c = std::make_shared<LexerATNConfig>(config, t->target); break; } case Transition::EPSILON: c = std::make_shared<LexerATNConfig>(config, t->target); break; case Transition::ATOM: case Transition::RANGE: case Transition::SET: if (treatEofAsEpsilon) { if (t->matches(Token::EOF, Lexer::MIN_CHAR_VALUE, Lexer::MAX_CHAR_VALUE)) { c = std::make_shared<LexerATNConfig>(config, t->target); break; } } break; default: // To silence the compiler. Other transition types are not used here. break; } return c; } bool LexerATNSimulator::evaluatePredicate(CharStream *input, size_t ruleIndex, size_t predIndex, bool speculative) { // assume true if no recognizer was provided if (_recog == nullptr) { return true; } if (!speculative) { return _recog->sempred(nullptr, ruleIndex, predIndex); } size_t savedCharPositionInLine = _charPositionInLine; size_t savedLine = _line; size_t index = input->index(); ssize_t marker = input->mark(); auto onExit = finally([this, input, savedCharPositionInLine, savedLine, index, marker] { _charPositionInLine = savedCharPositionInLine; _line = savedLine; input->seek(index); input->release(marker); }); consume(input); return _recog->sempred(nullptr, ruleIndex, predIndex); } void LexerATNSimulator::captureSimState(CharStream *input, dfa::DFAState *dfaState) { _prevAccept.index = input->index(); _prevAccept.line = _line; _prevAccept.charPos = _charPositionInLine; _prevAccept.dfaState = dfaState; } dfa::DFAState *LexerATNSimulator::addDFAEdge(dfa::DFAState *from, size_t t, ATNConfigSet *q) { /* leading to this call, ATNConfigSet.hasSemanticContext is used as a * marker indicating dynamic predicate evaluation makes this edge * dependent on the specific input sequence, so the static edge in the * DFA should be omitted. The target DFAState is still created since * execATN has the ability to resynchronize with the DFA state cache * following the predicate evaluation step. * * TJP notes: next time through the DFA, we see a pred again and eval. * If that gets us to a previously created (but dangling) DFA * state, we can continue in pure DFA mode from there. */ bool suppressEdge = q->hasSemanticContext; q->hasSemanticContext = false; dfa::DFAState *to = addDFAState(q); if (suppressEdge) { return to; } addDFAEdge(from, t, to); return to; } void LexerATNSimulator::addDFAEdge(dfa::DFAState *p, size_t t, dfa::DFAState *q) { if (/*t < MIN_DFA_EDGE ||*/ t > MAX_DFA_EDGE) { // MIN_DFA_EDGE is 0 // Only track edges within the DFA bounds return; } _edgeLock.writeLock(); p->edges[t - MIN_DFA_EDGE] = q; // connect _edgeLock.writeUnlock(); } dfa::DFAState *LexerATNSimulator::addDFAState(ATNConfigSet *configs) { /* the lexer evaluates predicates on-the-fly; by this point configs * should not contain any configurations with unevaluated predicates. */ assert(!configs->hasSemanticContext); dfa::DFAState *proposed = new dfa::DFAState(std::unique_ptr<ATNConfigSet>(configs)); /* mem-check: managed by the DFA or deleted below */ Ref<ATNConfig> firstConfigWithRuleStopState = nullptr; for (auto &c : configs->configs) { if (is<RuleStopState *>(c->state)) { firstConfigWithRuleStopState = c; break; } } if (firstConfigWithRuleStopState != nullptr) { proposed->isAcceptState = true; proposed->lexerActionExecutor = std::dynamic_pointer_cast<LexerATNConfig>(firstConfigWithRuleStopState)->getLexerActionExecutor(); proposed->prediction = atn.ruleToTokenType[firstConfigWithRuleStopState->state->ruleIndex]; } dfa::DFA &dfa = _decisionToDFA[_mode]; _stateLock.writeLock(); if (!dfa.states.empty()) { auto iterator = dfa.states.find(proposed); if (iterator != dfa.states.end()) { delete proposed; _stateLock.writeUnlock(); return *iterator; } } proposed->stateNumber = (int)dfa.states.size(); proposed->configs->setReadonly(true); dfa.states.insert(proposed); _stateLock.writeUnlock(); return proposed; } dfa::DFA& LexerATNSimulator::getDFA(size_t mode) { return _decisionToDFA[mode]; } std::string LexerATNSimulator::getText(CharStream *input) { // index is first lookahead char, don't include. return input->getText(misc::Interval(_startIndex, input->index() - 1)); } size_t LexerATNSimulator::getLine() const { return _line; } void LexerATNSimulator::setLine(size_t line) { _line = line; } size_t LexerATNSimulator::getCharPositionInLine() { return _charPositionInLine; } void LexerATNSimulator::setCharPositionInLine(size_t charPositionInLine) { _charPositionInLine = charPositionInLine; } void LexerATNSimulator::consume(CharStream *input) { size_t curChar = input->LA(1); if (curChar == '\n') { _line++; _charPositionInLine = 0; } else { _charPositionInLine++; } input->consume(); } std::string LexerATNSimulator::getTokenName(size_t t) { if (t == Token::EOF) { return "EOF"; } return std::string("'") + static_cast<char>(t) + std::string("'"); } void LexerATNSimulator::InitializeInstanceFields() { _startIndex = 0; _line = 1; _charPositionInLine = 0; _mode = antlr4::Lexer::DEFAULT_MODE; }
21,966
7,261
// Copyright Take Vos 2020-2021. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) #include "window_traffic_lights_widget.hpp" #include "../GUI/gui_window.hpp" #include "../GFX/pipeline_SDF_device_shared.hpp" #include "../text/font_book.hpp" #include <cmath> #include <typeinfo> namespace tt::inline v1 { window_traffic_lights_widget::window_traffic_lights_widget(gui_window &window, widget *parent) noexcept : super(window, parent) {} widget_constraints const &window_traffic_lights_widget::set_constraints() noexcept { _layout = {}; if (theme().operating_system == operating_system::windows) { ttlet size = extent2{theme().toolbar_decoration_button_width * 3.0f, theme().toolbar_height}; return _constraints = {size, size, size}; } else if (theme().operating_system == operating_system::macos) { ttlet size = extent2{DIAMETER * 3.0f + 2.0f * MARGIN + 2.0f * SPACING, DIAMETER + 2.0f * MARGIN}; return _constraints = {size, size, size}; } else { tt_no_default(); } } void window_traffic_lights_widget::set_layout(widget_layout const &layout) noexcept { if (compare_store(_layout, layout)) { auto extent = layout.size; if (extent.height() > theme().toolbar_height * 1.2f) { extent = extent2{extent.width(), theme().toolbar_height}; } auto y = layout.height() - extent.height(); if (theme().operating_system == operating_system::windows) { closeRectangle = aarectangle{point2(extent.width() * 2.0f / 3.0f, y), extent2{extent.width() * 1.0f / 3.0f, extent.height()}}; maximizeRectangle = aarectangle{point2(extent.width() * 1.0f / 3.0f, y), extent2{extent.width() * 1.0f / 3.0f, extent.height()}}; minimizeRectangle = aarectangle{point2(0.0f, y), extent2{extent.width() * 1.0f / 3.0f, extent.height()}}; } else if (theme().operating_system == operating_system::macos) { closeRectangle = aarectangle{point2(MARGIN, extent.height() / 2.0f - RADIUS), extent2{DIAMETER, DIAMETER}}; minimizeRectangle = aarectangle{point2(MARGIN + DIAMETER + SPACING, extent.height() / 2.0f - RADIUS), extent2{DIAMETER, DIAMETER}}; maximizeRectangle = aarectangle{ point2(MARGIN + DIAMETER + SPACING + DIAMETER + SPACING, extent.height() / 2.0f - RADIUS), extent2{DIAMETER, DIAMETER}}; } else { tt_no_default(); } closeWindowGlyph = font_book().find_glyph(ttauri_icon::CloseWindow); minimizeWindowGlyph = font_book().find_glyph(ttauri_icon::MinimizeWindow); if (theme().operating_system == operating_system::windows) { maximizeWindowGlyph = font_book().find_glyph(ttauri_icon::MaximizeWindowMS); restoreWindowGlyph = font_book().find_glyph(ttauri_icon::RestoreWindowMS); } else if (theme().operating_system == operating_system::macos) { maximizeWindowGlyph = font_book().find_glyph(ttauri_icon::MaximizeWindowMacOS); restoreWindowGlyph = font_book().find_glyph(ttauri_icon::RestoreWindowMacOS); } else { tt_no_default(); } ttlet closeWindowGlyphBB = closeWindowGlyph.get_bounding_box(); ttlet minimizeWindowGlyphBB = minimizeWindowGlyph.get_bounding_box(); ttlet maximizeWindowGlyphBB = maximizeWindowGlyph.get_bounding_box(); ttlet restoreWindowGlyphBB = restoreWindowGlyph.get_bounding_box(); ttlet glyph_size = theme().operating_system == operating_system::macos ? 5.0f : theme().icon_size; closeWindowGlyphRectangle = align(closeRectangle, closeWindowGlyphBB * glyph_size, alignment::middle_center()); minimizeWindowGlyphRectangle = align(minimizeRectangle, minimizeWindowGlyphBB * glyph_size, alignment::middle_center()); maximizeWindowGlyphRectangle = align(maximizeRectangle, maximizeWindowGlyphBB * glyph_size, alignment::middle_center()); restoreWindowGlyphRectangle = align(maximizeRectangle, restoreWindowGlyphBB * glyph_size, alignment::middle_center()); } } void window_traffic_lights_widget::drawMacOS(draw_context const &drawContext) noexcept { auto context = drawContext; ttlet close_circle_color = (not active() and not hover) ? color(0.246f, 0.246f, 0.246f) : pressedClose ? color(1.0f, 0.242f, 0.212f) : color(1.0f, 0.1f, 0.082f); context.draw_box(layout(), closeRectangle, close_circle_color, corner_radii{RADIUS}); ttlet minimize_circle_color = (not active() and not hover) ? color(0.246f, 0.246f, 0.246f) : pressedMinimize ? color(1.0f, 0.847f, 0.093f) : color(0.784f, 0.521f, 0.021f); context.draw_box(layout(), minimizeRectangle, minimize_circle_color, corner_radii{RADIUS}); ttlet maximize_circle_color = (not active() and not hover) ? color(0.246f, 0.246f, 0.246f) : pressedMaximize ? color(0.223f, 0.863f, 0.1f) : color(0.082f, 0.533f, 0.024f); context.draw_box(layout(), maximizeRectangle, maximize_circle_color, corner_radii{RADIUS}); if (hover) { context.draw_glyph(layout(), translate_z(0.1f) * closeWindowGlyphRectangle, color{0.319f, 0.0f, 0.0f}, closeWindowGlyph); context.draw_glyph( layout(), translate_z(0.1f) * minimizeWindowGlyphRectangle, color{0.212f, 0.1f, 0.0f}, minimizeWindowGlyph); if (window.size_state == gui_window_size::maximized) { context.draw_glyph( layout(), translate_z(0.1f) * restoreWindowGlyphRectangle, color{0.0f, 0.133f, 0.0f}, restoreWindowGlyph); } else { context.draw_glyph( layout(), translate_z(0.1f) * maximizeWindowGlyphRectangle, color{0.0f, 0.133f, 0.0f}, maximizeWindowGlyph); } } } void window_traffic_lights_widget::drawWindows(draw_context const &drawContext) noexcept { auto context = drawContext; if (pressedClose) { context.draw_box(layout(), closeRectangle, color{1.0f, 0.0f, 0.0f}); } else if (hoverClose) { context.draw_box(layout(), closeRectangle, color{0.5f, 0.0f, 0.0f}); } else { context.draw_box(layout(), closeRectangle, theme().color(theme_color::fill, semantic_layer)); } if (pressedMinimize) { context.draw_box(layout(), minimizeRectangle, theme().color(theme_color::fill, semantic_layer + 2)); } else if (hoverMinimize) { context.draw_box(layout(), minimizeRectangle, theme().color(theme_color::fill, semantic_layer + 1)); } else { context.draw_box(layout(), minimizeRectangle, theme().color(theme_color::fill, semantic_layer)); } if (pressedMaximize) { context.draw_box(layout(), maximizeRectangle, theme().color(theme_color::fill, semantic_layer + 2)); } else if (hoverMaximize) { context.draw_box(layout(), maximizeRectangle, theme().color(theme_color::fill, semantic_layer + 1)); } else { context.draw_box(layout(), maximizeRectangle, theme().color(theme_color::fill, semantic_layer)); } ttlet glyph_color = active() ? label_color() : foreground_color(); context.draw_glyph(layout(), translate_z(0.1f) * closeWindowGlyphRectangle, glyph_color, closeWindowGlyph); context.draw_glyph(layout(), translate_z(0.1f) * minimizeWindowGlyphRectangle, glyph_color, minimizeWindowGlyph); if (window.size_state == gui_window_size::maximized) { context.draw_glyph(layout(), translate_z(0.1f) * restoreWindowGlyphRectangle, glyph_color, restoreWindowGlyph); } else { context.draw_glyph(layout(), translate_z(0.1f) * maximizeWindowGlyphRectangle, glyph_color, maximizeWindowGlyph); } } void window_traffic_lights_widget::draw(draw_context const &context) noexcept { if (visible and overlaps(context, layout())) { if (theme().operating_system == operating_system::macos) { drawMacOS(context); } else if (theme().operating_system == operating_system::windows) { drawWindows(context); } else { tt_no_default(); } } } bool window_traffic_lights_widget::handle_event(mouse_event const &event) noexcept { tt_axiom(is_gui_thread()); auto handled = super::handle_event(event); // Check the hover states of each button. auto stateHasChanged = false; stateHasChanged |= compare_store(hoverClose, closeRectangle.contains(event.position)); stateHasChanged |= compare_store(hoverMinimize, minimizeRectangle.contains(event.position)); stateHasChanged |= compare_store(hoverMaximize, maximizeRectangle.contains(event.position)); if (stateHasChanged) { request_redraw(); } if (event.cause.leftButton) { handled = true; switch (event.type) { using enum mouse_event::Type; case ButtonUp: if (pressedClose && hoverClose) { window.close_window(); } if (pressedMinimize && hoverMinimize) { window.minimize_window(); } if (pressedMaximize && hoverMaximize) { switch (window.size_state) { case gui_window_size::normal: window.maximize_window(); break; case gui_window_size::maximized: window.normalize_window(); break; default: tt_no_default(); } } request_redraw(); pressedClose = false; pressedMinimize = false; pressedMaximize = false; break; case ButtonDown: request_redraw(); pressedClose = hoverClose; pressedMinimize = hoverMinimize; pressedMaximize = hoverMaximize; break; } } return handled; } hitbox window_traffic_lights_widget::hitbox_test(point3 position) const noexcept { tt_axiom(is_gui_thread()); if (visible and enabled and layout().contains(position) and (closeRectangle.contains(position) or minimizeRectangle.contains(position) or maximizeRectangle.contains(position))) { return hitbox{this, position, hitbox::Type::Button}; } else { return {}; } } } // namespace tt::inline v1
10,628
3,495
#include "reply.hpp" using namespace Moove; Reply func() { return Reply(); } int main() { Reply reply; reply = func(); return 0; }
139
62
// Tablacus Total Commander Listr Plugin Wrapper (C)2018 Gaku // MIT Lisence // Visual C++ 2017 Express Edition // 32-bit Visual Studio 2015 - Windows XP (v140_xp) // 64-bit Visual Studio 2017 (v141) // https://tablacus.github.io/ #include "twlx.h" // Global Variables: const TCHAR g_szProgid[] = TEXT("Tablacus.TotalCommanderLSPlugin"); const TCHAR g_szClsid[] = TEXT("{E160213A-4E9E-44f3-BD39-8297499608B6}"); HINSTANCE g_hinstDll = NULL; LONG g_lLocks = 0; CteBase *g_pBase = NULL; std::vector <CteWO *> g_ppObject; IDispatch *g_pdispArrayProc = NULL; IDispatch *g_pdispProgressProc = NULL; IDispatch *g_pdispLogProc = NULL; IDispatch *g_pdispRequestProc = NULL; IDispatch *g_pdispCryptProc = NULL; std::unordered_map<std::wstring, DISPID> g_umBASE = { { L"Open", 0x60010000 }, { L"Close", 0x6001000C }, }; std::unordered_map<std::wstring, DISPID> g_umWO = { { L"ListLoad", 0x60010001 }, { L"ListLoadNext", 0x60010002 }, { L"ListCloseWindow", 0x60010003 }, { L"ListSetDefaultParams", 0x60010004 }, { L"ListGetPreviewBitmap", 0x60010005 }, { L"ListGetDetectString", 0x60010006 }, { L"IsUnicode", 0x6001FFFF }, }; // Unit VOID SafeRelease(PVOID ppObj) { try { IUnknown **ppunk = static_cast<IUnknown **>(ppObj); if (*ppunk) { (*ppunk)->Release(); *ppunk = NULL; } } catch (...) { } } VOID teGetProcAddress(HMODULE hModule, LPSTR lpName, FARPROC *lpfnA, FARPROC *lpfnW) { *lpfnA = GetProcAddress(hModule, lpName); if (lpfnW) { char pszProcName[80]; strcpy_s(pszProcName, 80, lpName); strcat_s(pszProcName, 80, "W"); *lpfnW = GetProcAddress(hModule, (LPCSTR)pszProcName); } } void LockModule(BOOL bLock) { if (bLock) { InterlockedIncrement(&g_lLocks); } else { InterlockedDecrement(&g_lLocks); } } HRESULT ShowRegError(LSTATUS ls) { LPTSTR lpBuffer = NULL; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, ls, LANG_USER_DEFAULT, (LPTSTR)&lpBuffer, 0, NULL); MessageBox(NULL, lpBuffer, TEXT(PRODUCTNAME), MB_ICONHAND | MB_OK); LocalFree(lpBuffer); return HRESULT_FROM_WIN32(ls); } LSTATUS CreateRegistryKey(HKEY hKeyRoot, LPTSTR lpszKey, LPTSTR lpszValue, LPTSTR lpszData) { HKEY hKey; LSTATUS lr; DWORD dwSize; lr = RegCreateKeyEx(hKeyRoot, lpszKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, NULL); if (lr == ERROR_SUCCESS) { if (lpszData != NULL) { dwSize = (lstrlen(lpszData) + 1) * sizeof(TCHAR); } else { dwSize = 0; } lr = RegSetValueEx(hKey, lpszValue, 0, REG_SZ, (LPBYTE)lpszData, dwSize); RegCloseKey(hKey); } return lr; } BSTR GetLPWSTRFromVariant(VARIANT *pv) { if (pv->vt == (VT_VARIANT | VT_BYREF)) { return GetLPWSTRFromVariant(pv->pvarVal); } switch (pv->vt) { case VT_BSTR: case VT_LPWSTR: return pv->bstrVal; default: return NULL; }//end_switch } int GetIntFromVariant(VARIANT *pv) { if (pv) { if (pv->vt == (VT_VARIANT | VT_BYREF)) { return GetIntFromVariant(pv->pvarVal); } if (pv->vt == VT_I4) { return pv->lVal; } if (pv->vt == VT_UI4) { return pv->ulVal; } if (pv->vt == VT_R8) { return (int)(LONGLONG)pv->dblVal; } VARIANT vo; VariantInit(&vo); if SUCCEEDED(VariantChangeType(&vo, pv, 0, VT_I4)) { return vo.lVal; } if SUCCEEDED(VariantChangeType(&vo, pv, 0, VT_UI4)) { return vo.ulVal; } if SUCCEEDED(VariantChangeType(&vo, pv, 0, VT_I8)) { return (int)vo.llVal; } } return 0; } int GetIntFromVariantClear(VARIANT *pv) { int i = GetIntFromVariant(pv); VariantClear(pv); return i; } #ifdef _WIN64 BOOL teStartsText(LPWSTR pszSub, LPCWSTR pszFile) { BOOL bResult = pszFile ? TRUE : FALSE; WCHAR wc; while (bResult && (wc = *pszSub++)) { bResult = towlower(wc) == towlower(*pszFile++); } return bResult; } BOOL teVarIsNumber(VARIANT *pv) { return pv->vt == VT_I4 || pv->vt == VT_R8 || pv->vt == (VT_ARRAY | VT_I4) || (pv->vt == VT_BSTR && ::SysStringLen(pv->bstrVal) == 18 && teStartsText(L"0x", pv->bstrVal)); } LONGLONG GetLLFromVariant(VARIANT *pv) { if (pv) { if (pv->vt == (VT_VARIANT | VT_BYREF)) { return GetLLFromVariant(pv->pvarVal); } if (pv->vt == VT_I4) { return pv->lVal; } if (pv->vt == VT_R8) { return (LONGLONG)pv->dblVal; } if (pv->vt == (VT_ARRAY | VT_I4)) { LONGLONG ll = 0; PVOID pvData; if (::SafeArrayAccessData(pv->parray, &pvData) == S_OK) { ::CopyMemory(&ll, pvData, sizeof(LONGLONG)); ::SafeArrayUnaccessData(pv->parray); return ll; } } if (teVarIsNumber(pv)) { LONGLONG ll = 0; if (swscanf_s(pv->bstrVal, L"0x%016llx", &ll) > 0) { return ll; } } VARIANT vo; VariantInit(&vo); if SUCCEEDED(VariantChangeType(&vo, pv, 0, VT_I8)) { return vo.llVal; } } return 0; } #endif VOID teSetBool(VARIANT *pv, BOOL b) { if (pv) { pv->boolVal = b ? VARIANT_TRUE : VARIANT_FALSE; pv->vt = VT_BOOL; } } VOID teSysFreeString(BSTR *pbs) { if (*pbs) { ::SysFreeString(*pbs); *pbs = NULL; } } VOID teSetLong(VARIANT *pv, LONG i) { if (pv) { pv->lVal = i; pv->vt = VT_I4; } } VOID teSetLL(VARIANT *pv, LONGLONG ll) { if (pv) { pv->lVal = static_cast<int>(ll); if (ll == static_cast<LONGLONG>(pv->lVal)) { pv->vt = VT_I4; return; } pv->dblVal = static_cast<DOUBLE>(ll); if (ll == static_cast<LONGLONG>(pv->dblVal)) { pv->vt = VT_R8; return; } pv->bstrVal = ::SysAllocStringLen(NULL, 18); swprintf_s(pv->bstrVal, 19, L"0x%016llx", ll); pv->vt = VT_BSTR; } } BOOL teSetObject(VARIANT *pv, PVOID pObj) { if (pObj) { try { IUnknown *punk = static_cast<IUnknown *>(pObj); if SUCCEEDED(punk->QueryInterface(IID_PPV_ARGS(&pv->pdispVal))) { pv->vt = VT_DISPATCH; return true; } if SUCCEEDED(punk->QueryInterface(IID_PPV_ARGS(&pv->punkVal))) { pv->vt = VT_UNKNOWN; return true; } } catch (...) {} } return false; } BOOL teSetObjectRelease(VARIANT *pv, PVOID pObj) { if (pObj) { try { IUnknown *punk = static_cast<IUnknown *>(pObj); if (pv) { if SUCCEEDED(punk->QueryInterface(IID_PPV_ARGS(&pv->pdispVal))) { pv->vt = VT_DISPATCH; SafeRelease(&punk); return true; } if SUCCEEDED(punk->QueryInterface(IID_PPV_ARGS(&pv->punkVal))) { pv->vt = VT_UNKNOWN; SafeRelease(&punk); return true; } } SafeRelease(&punk); } catch (...) {} } return false; } VOID teSetSZA(VARIANT *pv, LPCSTR lpstr, int nCP) { if (pv) { int nLenW = MultiByteToWideChar(nCP, 0, lpstr, -1, NULL, NULL); if (nLenW) { pv->bstrVal = ::SysAllocStringLen(NULL, nLenW - 1); pv->bstrVal[0] = NULL; MultiByteToWideChar(nCP, 0, (LPCSTR)lpstr, -1, pv->bstrVal, nLenW); } else { pv->bstrVal = NULL; } pv->vt = VT_BSTR; } } VOID teSetSZ(VARIANT *pv, LPCWSTR lpstr) { if (pv) { pv->bstrVal = ::SysAllocString(lpstr); pv->vt = VT_BSTR; } } VOID teSetBSTR(VARIANT *pv, BSTR bs, int nLen) { if (pv) { pv->vt = VT_BSTR; if (bs) { if (nLen < 0) { nLen = lstrlen(bs); } if (::SysStringLen(bs) == nLen) { pv->bstrVal = bs; return; } } pv->bstrVal = SysAllocStringLen(bs, nLen); teSysFreeString(&bs); } } BOOL FindUnknown(VARIANT *pv, IUnknown **ppunk) { if (pv) { if (pv->vt == VT_DISPATCH || pv->vt == VT_UNKNOWN) { *ppunk = pv->punkVal; return *ppunk != NULL; } if (pv->vt == (VT_VARIANT | VT_BYREF)) { return FindUnknown(pv->pvarVal, ppunk); } if (pv->vt == (VT_DISPATCH | VT_BYREF) || pv->vt == (VT_UNKNOWN | VT_BYREF)) { *ppunk = *pv->ppunkVal; return *ppunk != NULL; } } *ppunk = NULL; return false; } HRESULT tePutProperty0(IUnknown *punk, LPOLESTR sz, VARIANT *pv, DWORD grfdex) { HRESULT hr = E_FAIL; DISPID dispid, putid; DISPPARAMS dispparams; IDispatchEx *pdex; if SUCCEEDED(punk->QueryInterface(IID_PPV_ARGS(&pdex))) { BSTR bs = ::SysAllocString(sz); hr = pdex->GetDispID(bs, grfdex, &dispid); if SUCCEEDED(hr) { putid = DISPID_PROPERTYPUT; dispparams.rgvarg = pv; dispparams.rgdispidNamedArgs = &putid; dispparams.cArgs = 1; dispparams.cNamedArgs = 1; hr = pdex->InvokeEx(dispid, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYPUTREF, &dispparams, NULL, NULL, NULL); } ::SysFreeString(bs); SafeRelease(&pdex); } return hr; } HRESULT tePutProperty(IUnknown *punk, LPOLESTR sz, VARIANT *pv) { return tePutProperty0(punk, sz, pv, fdexNameEnsure); } // VARIANT Clean-up of an array VOID teClearVariantArgs(int nArgs, VARIANTARG *pvArgs) { if (pvArgs && nArgs > 0) { for (int i = nArgs ; i-- > 0;){ VariantClear(&pvArgs[i]); } delete[] pvArgs; pvArgs = NULL; } } HRESULT Invoke5(IDispatch *pdisp, DISPID dispid, WORD wFlags, VARIANT *pvResult, int nArgs, VARIANTARG *pvArgs) { HRESULT hr; // DISPPARAMS DISPPARAMS dispParams; dispParams.rgvarg = pvArgs; dispParams.cArgs = abs(nArgs); DISPID dispidName = DISPID_PROPERTYPUT; if (wFlags & DISPATCH_PROPERTYPUT) { dispParams.cNamedArgs = 1; dispParams.rgdispidNamedArgs = &dispidName; } else { dispParams.rgdispidNamedArgs = NULL; dispParams.cNamedArgs = 0; } try { hr = pdisp->Invoke(dispid, IID_NULL, LOCALE_USER_DEFAULT, wFlags, &dispParams, pvResult, NULL, NULL); } catch (...) { hr = E_FAIL; } teClearVariantArgs(nArgs, pvArgs); return hr; } HRESULT Invoke4(IDispatch *pdisp, VARIANT *pvResult, int nArgs, VARIANTARG *pvArgs) { return Invoke5(pdisp, DISPID_VALUE, DISPATCH_METHOD, pvResult, nArgs, pvArgs); } VARIANTARG* GetNewVARIANT(int n) { VARIANT *pv = new VARIANTARG[n]; while (n--) { VariantInit(&pv[n]); } return pv; } int twlx_Proc(IDispatch *pdisp, char *Name, WCHAR *NameW, int n) { if (pdisp) { VARIANT vResult; VariantInit(&vResult); VARIANTARG *pv = GetNewVARIANT(2); if (NameW) { teSetSZ(&pv[1], NameW); } else if (Name) { teSetSZA(&pv[1], Name, CP_ACP); } teSetLong(&pv[0], n); if SUCCEEDED(Invoke4(pdisp, &vResult, 2, pv)) { return GetIntFromVariantClear(&vResult); } } return 1; } BOOL GetDispatch(VARIANT *pv, IDispatch **ppdisp) { IUnknown *punk; if (FindUnknown(pv, &punk)) { return SUCCEEDED(punk->QueryInterface(IID_PPV_ARGS(ppdisp))); } return false; } HRESULT teGetProperty(IDispatch *pdisp, LPOLESTR sz, VARIANT *pv) { DISPID dispid; HRESULT hr = pdisp->GetIDsOfNames(IID_NULL, &sz, 1, LOCALE_USER_DEFAULT, &dispid); if (hr == S_OK) { hr = Invoke5(pdisp, dispid, DISPATCH_PROPERTYGET, pv, 0, NULL); } return hr; } VOID teVariantChangeType(__out VARIANTARG * pvargDest, __in const VARIANTARG * pvarSrc, __in VARTYPE vt) { VariantInit(pvargDest); if FAILED(VariantChangeType(pvargDest, pvarSrc, 0, vt)) { pvargDest->llVal = 0; } } LPSTR teWide2Ansi(LPWSTR lpW, int nLenW, int nCP) { int nLenA = WideCharToMultiByte(nCP, 0, (LPCWSTR)lpW, nLenW, NULL, 0, NULL, NULL); BSTR bs = ::SysAllocStringByteLen(NULL, nLenA); WideCharToMultiByte(nCP, 0, (LPCWSTR)lpW, nLenW, (LPSTR)bs, nLenA, NULL, NULL); return (LPSTR)bs; } VOID teFreeAnsiString(LPSTR *lplpA) { ::SysFreeString((BSTR)*lplpA); *lplpA = NULL; } BSTR teGetMemoryFromVariant(VARIANT *pv, BOOL *pbDelete, LONG_PTR *pLen) { if (pv->vt == (VT_VARIANT | VT_BYREF)) { return teGetMemoryFromVariant(pv->pvarVal, pbDelete, pLen); } BSTR pMemory = NULL; *pbDelete = FALSE; if (pLen) { if (pv->vt == VT_BSTR || pv->vt == VT_LPWSTR) { return pv->bstrVal; } } IUnknown *punk; if (FindUnknown(pv, &punk)) { IStream *pStream; if SUCCEEDED(punk->QueryInterface(IID_PPV_ARGS(&pStream))) { ULARGE_INTEGER uliSize; if (pLen) { LARGE_INTEGER liOffset; liOffset.QuadPart = 0; pStream->Seek(liOffset, STREAM_SEEK_END, &uliSize); pStream->Seek(liOffset, STREAM_SEEK_SET, NULL); } else { uliSize.QuadPart = BUFF_SIZE; } pMemory = ::SysAllocStringByteLen(NULL, uliSize.LowPart > BUFF_SIZE ? uliSize.LowPart : BUFF_SIZE); if (pMemory) { if (uliSize.LowPart < BUFF_SIZE) { ::ZeroMemory(pMemory, BUFF_SIZE); } *pbDelete = TRUE; ULONG cbRead; pStream->Read(pMemory, uliSize.LowPart, &cbRead); if (pLen) { *pLen = cbRead; } } pStream->Release(); } } else if (pv->vt == (VT_ARRAY | VT_I1) || pv->vt == (VT_ARRAY | VT_UI1) || pv->vt == (VT_ARRAY | VT_I1 | VT_BYREF) || pv->vt == (VT_ARRAY | VT_UI1 | VT_BYREF)) { LONG lUBound, lLBound, nSize; SAFEARRAY *psa = (pv->vt & VT_BYREF) ? pv->pparray[0] : pv->parray; PVOID pvData; if (::SafeArrayAccessData(psa, &pvData) == S_OK) { SafeArrayGetUBound(psa, 1, &lUBound); SafeArrayGetLBound(psa, 1, &lLBound); nSize = lUBound - lLBound + 1; pMemory = ::SysAllocStringByteLen(NULL, nSize > BUFF_SIZE ? nSize : BUFF_SIZE); if (pMemory) { if (nSize < BUFF_SIZE) { ::ZeroMemory(pMemory, BUFF_SIZE); } ::CopyMemory(pMemory, pvData, nSize); if (pLen) { *pLen = nSize; } *pbDelete = TRUE; } ::SafeArrayUnaccessData(psa); } return pMemory; } else if (!pLen) { return (BSTR)GetPtrFromVariant(pv); } return pMemory; } HRESULT teExecMethod(IDispatch *pdisp, LPOLESTR sz, VARIANT *pvResult, int nArg, VARIANTARG *pvArgs) { DISPID dispid; HRESULT hr = pdisp->GetIDsOfNames(IID_NULL, &sz, 1, LOCALE_USER_DEFAULT, &dispid); if (hr == S_OK) { return Invoke5(pdisp, dispid, DISPATCH_METHOD, pvResult, nArg, pvArgs); } teClearVariantArgs(nArg, pvArgs); return hr; } // Initialize & Finalize BOOL WINAPI DllMain(HINSTANCE hinstDll, DWORD dwReason, LPVOID lpReserved) { switch (dwReason) { case DLL_PROCESS_ATTACH: g_pBase = new CteBase(); g_hinstDll = hinstDll; break; case DLL_PROCESS_DETACH: for (size_t i = g_ppObject.size(); i--;) { g_ppObject[i]->Close(); SafeRelease(&g_ppObject[i]); } SafeRelease(&g_pBase); SafeRelease(&g_pdispProgressProc); SafeRelease(&g_pdispLogProc); SafeRelease(&g_pdispRequestProc); break; } return TRUE; } // DLL Export STDAPI DllCanUnloadNow(void) { return g_lLocks == 0 ? S_OK : S_FALSE; } STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv) { static CteClassFactory serverFactory; CLSID clsid; HRESULT hr = CLASS_E_CLASSNOTAVAILABLE; *ppv = NULL; CLSIDFromString(g_szClsid, &clsid); if (IsEqualCLSID(rclsid, clsid)) { hr = serverFactory.QueryInterface(riid, ppv); } return hr; } STDAPI DllRegisterServer(void) { TCHAR szModulePath[MAX_PATH]; TCHAR szKey[256]; wsprintf(szKey, TEXT("CLSID\\%s"), g_szClsid); LSTATUS lr = CreateRegistryKey(HKEY_CLASSES_ROOT, szKey, NULL, const_cast<LPTSTR>(g_szProgid)); if (lr != ERROR_SUCCESS) { return ShowRegError(lr); } GetModuleFileName(g_hinstDll, szModulePath, sizeof(szModulePath) / sizeof(TCHAR)); wsprintf(szKey, TEXT("CLSID\\%s\\InprocServer32"), g_szClsid); lr = CreateRegistryKey(HKEY_CLASSES_ROOT, szKey, NULL, szModulePath); if (lr != ERROR_SUCCESS) { return ShowRegError(lr); } lr = CreateRegistryKey(HKEY_CLASSES_ROOT, szKey, TEXT("ThreadingModel"), TEXT("Apartment")); if (lr != ERROR_SUCCESS) { return ShowRegError(lr); } wsprintf(szKey, TEXT("CLSID\\%s\\ProgID"), g_szClsid); lr = CreateRegistryKey(HKEY_CLASSES_ROOT, szKey, NULL, const_cast<LPTSTR>(g_szProgid)); if (lr != ERROR_SUCCESS) { return ShowRegError(lr); } lr = CreateRegistryKey(HKEY_CLASSES_ROOT, const_cast<LPTSTR>(g_szProgid), NULL, TEXT(PRODUCTNAME)); if (lr != ERROR_SUCCESS) { return ShowRegError(lr); } wsprintf(szKey, TEXT("%s\\CLSID"), g_szProgid); lr = CreateRegistryKey(HKEY_CLASSES_ROOT, szKey, NULL, const_cast<LPTSTR>(g_szClsid)); if (lr != ERROR_SUCCESS) { return ShowRegError(lr); } return S_OK; } STDAPI DllUnregisterServer(void) { TCHAR szKey[64]; wsprintf(szKey, TEXT("CLSID\\%s"), g_szClsid); LSTATUS ls = SHDeleteKey(HKEY_CLASSES_ROOT, szKey); if (ls == ERROR_SUCCESS) { ls = SHDeleteKey(HKEY_CLASSES_ROOT, g_szProgid); if (ls == ERROR_SUCCESS) { return S_OK; } } return ShowRegError(ls); } //CteWO CteWO::CteWO(HMODULE hDll, LPWSTR lpLib) { m_cRef = 1; m_hDll = hDll; m_bsLib = ::SysAllocString(lpLib); teGetProcAddress(m_hDll, "ListLoad", (FARPROC *)&m_ListLoad, (FARPROC *)&m_ListLoadW); teGetProcAddress(m_hDll, "ListLoadNext", (FARPROC *)&m_ListLoadNext, (FARPROC *)&m_ListLoadNextW); teGetProcAddress(m_hDll, "ListCloseWindow", (FARPROC *)&m_ListCloseWindow, NULL); teGetProcAddress(m_hDll, "ListSetDefaultParam", (FARPROC *)&m_ListSetDefaultParam, NULL); teGetProcAddress(m_hDll, "ListGetPreviewBitmap", (FARPROC *)&m_ListGetPreviewBitmap, (FARPROC *)&m_ListGetPreviewBitmapW); teGetProcAddress(m_hDll, "ListGetDetectString", (FARPROC *)&m_ListGetDetectString, NULL); } CteWO::~CteWO() { Close(); for (size_t i = g_ppObject.size(); i--;) { if (this == g_ppObject[i]) { g_ppObject.erase(g_ppObject.begin() + i); break; } } } VOID CteWO::Close() { if (m_hDll) { FreeLibrary(m_hDll); m_hDll = NULL; } m_ListLoad = NULL; m_ListLoadW = NULL; m_ListLoadNext = NULL; m_ListLoadNextW = NULL; m_ListCloseWindow = NULL; m_ListSetDefaultParam = NULL; m_ListGetPreviewBitmap = NULL; m_ListGetPreviewBitmapW = NULL; m_ListGetDetectString = NULL; } STDMETHODIMP CteWO::QueryInterface(REFIID riid, void **ppvObject) { static const QITAB qit[] = { QITABENT(CteWO, IDispatch), { 0 }, }; return QISearch(this, qit, riid, ppvObject); } STDMETHODIMP_(ULONG) CteWO::AddRef() { return ::InterlockedIncrement(&m_cRef); } STDMETHODIMP_(ULONG) CteWO::Release() { if (::InterlockedDecrement(&m_cRef) == 0) { delete this; return 0; } return m_cRef; } STDMETHODIMP CteWO::GetTypeInfoCount(UINT *pctinfo) { *pctinfo = 0; return S_OK; } STDMETHODIMP CteWO::GetTypeInfo(UINT iTInfo, LCID lcid, ITypeInfo **ppTInfo) { return E_NOTIMPL; } STDMETHODIMP CteWO::GetIDsOfNames(REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId) { auto itr = g_umWO.find(*rgszNames); if (itr != g_umWO.end()) { *rgDispId = itr->second; return S_OK; } #ifdef _DEBUG OutputDebugStringA("GetIDsOfNames:"); OutputDebugString(rgszNames[0]); OutputDebugStringA("\n"); #endif return DISP_E_UNKNOWNNAME; } STDMETHODIMP CteWO::Invoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr) { int nArg = pDispParams ? pDispParams->cArgs - 1 : -1; try { switch (dispIdMember) { //ListLoad case 0x60010001: if (nArg >= 2) { HWND hwndList = NULL; HWND hwndParent = (HWND)GetPtrFromVariant(&pDispParams->rgvarg[nArg]); LPWSTR lpPath = GetLPWSTRFromVariant(&pDispParams->rgvarg[nArg - 1]); int ShowFlags = GetPtrFromVariant(&pDispParams->rgvarg[nArg - 2]); if (m_ListLoadW) { hwndList = m_ListLoadW(hwndParent, lpPath, ShowFlags); } else if (m_ListLoad) { LPSTR lpPathA = teWide2Ansi(lpPath, -1, CP_ACP); hwndList = m_ListLoad(hwndParent, lpPathA, ShowFlags); teFreeAnsiString(&lpPathA); } teSetPtr(pVarResult, hwndList); } else if (wFlags == DISPATCH_PROPERTYGET) { if (m_ListLoadW || m_ListLoad) { teSetObjectRelease(pVarResult, new CteDispatch(this, 0, dispIdMember)); } } return S_OK; //ListLoadNext case 0x60010002: if (nArg >= 3) { int iResult = 0; HWND hwndParent = (HWND)GetPtrFromVariant(&pDispParams->rgvarg[nArg]); HWND hwndList = (HWND)GetPtrFromVariant(&pDispParams->rgvarg[nArg - 1]); LPWSTR lpPath = GetLPWSTRFromVariant(&pDispParams->rgvarg[nArg - 2]); int ShowFlags = GetPtrFromVariant(&pDispParams->rgvarg[nArg - 3]); if (m_ListLoadNextW) { iResult = m_ListLoadNextW(hwndParent, hwndList, lpPath, ShowFlags); } else if (m_ListLoadNext) { LPSTR lpPathA = teWide2Ansi(lpPath, -1, CP_ACP); iResult = m_ListLoadNext(hwndParent, hwndList, lpPathA, ShowFlags); teFreeAnsiString(&lpPathA); } teSetLong(pVarResult, iResult); } else if (wFlags == DISPATCH_PROPERTYGET) { if (m_ListLoadNextW || m_ListLoadNext) { teSetObjectRelease(pVarResult, new CteDispatch(this, 0, dispIdMember)); } } return S_OK; //ListCloseWindow case 0x60010003: if (nArg >= 0) { HWND hwndList = (HWND)GetPtrFromVariant(&pDispParams->rgvarg[nArg]); if (m_ListCloseWindow) { m_ListCloseWindow(hwndList); } } else if (wFlags == DISPATCH_PROPERTYGET) { if (pVarResult, m_ListCloseWindow != NULL) { teSetObjectRelease(pVarResult, new CteDispatch(this, 0, dispIdMember)); } } return S_OK; //ListSetDefaultParams case 0x60010004: if (nArg >= 0 && m_ListSetDefaultParam) { ListDefaultParamStruct dps = { sizeof(ListDefaultParamStruct), 10, 2 }; LPWSTR lpPath = GetLPWSTRFromVariant(&pDispParams->rgvarg[nArg]); if (lpPath) { WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)lpPath, -1, dps.DefaultIniName, MAX_PATH, NULL, NULL); } m_ListSetDefaultParam(&dps); } else if (wFlags == DISPATCH_PROPERTYGET) { if (m_ListSetDefaultParam) { teSetObjectRelease(pVarResult, new CteDispatch(this, 0, dispIdMember)); } } return S_OK; //ListGetPreviewBitmap case 0x60010005: if (nArg >= 3) { HBITMAP hbm = NULL; BOOL bDelete = FALSE; LPWSTR lpPath = GetLPWSTRFromVariant(&pDispParams->rgvarg[nArg]); int width = GetPtrFromVariant(&pDispParams->rgvarg[nArg - 1]); int height = GetPtrFromVariant(&pDispParams->rgvarg[nArg - 2]); LONG_PTR len = nArg >= 4 ? GetPtrFromVariant(&pDispParams->rgvarg[nArg - 4]) : 0; BSTR lpBuf = teGetMemoryFromVariant(&pDispParams->rgvarg[nArg - 3], &bDelete, &len); if (m_ListGetPreviewBitmapW) { hbm = m_ListGetPreviewBitmapW(lpPath, width, height, (char *)lpBuf, len); } else if (m_ListGetPreviewBitmap) { LPSTR lpPathA = teWide2Ansi(lpPath, -1, CP_ACP); hbm = m_ListGetPreviewBitmap(lpPathA, width, height, (char *)lpBuf, len); teFreeAnsiString(&lpPathA); } if (bDelete) { teSysFreeString(&lpBuf); } teSetPtr(pVarResult, hbm); } else if (wFlags == DISPATCH_PROPERTYGET) { if (m_ListGetPreviewBitmapW || m_ListGetPreviewBitmap) { teSetObjectRelease(pVarResult, new CteDispatch(this, 0, dispIdMember)); } } return S_OK; //ListGetDetectString case 0x60010006: if (wFlags & DISPATCH_METHOD) { char pszDetectString[BUFF_SIZE]; pszDetectString[0] = NULL; if (m_ListGetDetectString) { m_ListGetDetectString(pszDetectString, sizeof(pszDetectString)); } teSetSZA(pVarResult, pszDetectString, CP_ACP); } else if (wFlags == DISPATCH_PROPERTYGET) { if (m_ListGetDetectString) { teSetObjectRelease(pVarResult, new CteDispatch(this, 0, dispIdMember)); } } return S_OK; //IsUnicode case 0x6001FFFF: teSetBool(pVarResult, m_ListLoadW != NULL); return S_OK; //this case DISPID_VALUE: if (pVarResult) { teSetObject(pVarResult, this); } return S_OK; }//end_switch } catch (...) { return DISP_E_EXCEPTION; } return DISP_E_MEMBERNOTFOUND; } //CteBase CteBase::CteBase() { m_cRef = 1; } CteBase::~CteBase() { } STDMETHODIMP CteBase::QueryInterface(REFIID riid, void **ppvObject) { static const QITAB qit[] = { QITABENT(CteBase, IDispatch), { 0 }, }; return QISearch(this, qit, riid, ppvObject); } STDMETHODIMP_(ULONG) CteBase::AddRef() { return ::InterlockedIncrement(&m_cRef); } STDMETHODIMP_(ULONG) CteBase::Release() { if (::InterlockedDecrement(&m_cRef) == 0) { delete this; return 0; } return m_cRef; } STDMETHODIMP CteBase::GetTypeInfoCount(UINT *pctinfo) { *pctinfo = 0; return S_OK; } STDMETHODIMP CteBase::GetTypeInfo(UINT iTInfo, LCID lcid, ITypeInfo **ppTInfo) { return E_NOTIMPL; } STDMETHODIMP CteBase::GetIDsOfNames(REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId) { auto itr = g_umBASE.find(*rgszNames); if (itr != g_umBASE.end()) { *rgDispId = itr->second; return S_OK; } #ifdef _DEBUG OutputDebugStringA("GetIDsOfNames:"); OutputDebugString(rgszNames[0]); OutputDebugStringA("\n"); #endif return DISP_E_UNKNOWNNAME; } STDMETHODIMP CteBase::Invoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr) { int nArg = pDispParams ? pDispParams->cArgs - 1 : -1; HRESULT hr = S_OK; if (wFlags == DISPATCH_PROPERTYGET && dispIdMember >= TE_METHOD) { teSetObjectRelease(pVarResult, new CteDispatch(this, 0, dispIdMember)); return S_OK; } switch (dispIdMember) { //Open case 0x60010000: if (nArg >= 0) { LPWSTR lpLib = GetLPWSTRFromVariant(&pDispParams->rgvarg[nArg]); CteWO *pItem; for (size_t i = g_ppObject.size(); i--;) { pItem = g_ppObject[i]; if (pItem) { if (lstrcmpi(lpLib, pItem->m_bsLib) == 0) { teSetObject(pVarResult, pItem); return S_OK; } } } HMODULE hDll = LoadLibrary(lpLib); if (hDll) { pItem = new CteWO(hDll, lpLib); g_ppObject.push_back(pItem); teSetObjectRelease(pVarResult, pItem); } } return S_OK; //Close case 0x6001000C: if (nArg >= 0) { LPWSTR lpLib = GetLPWSTRFromVariant(&pDispParams->rgvarg[nArg]); for (size_t i = g_ppObject.size(); i--;) { if (g_ppObject[i]) { if (lstrcmpi(lpLib, g_ppObject[i]->m_bsLib) == 0) { g_ppObject[i]->Close(); SafeRelease(&g_ppObject[i]); break; } } } } return S_OK; //this case DISPID_VALUE: if (pVarResult) { teSetObject(pVarResult, this); } return S_OK; }//end_switch return DISP_E_MEMBERNOTFOUND; } // CteClassFactory STDMETHODIMP CteClassFactory::QueryInterface(REFIID riid, void **ppvObject) { static const QITAB qit[] = { QITABENT(CteClassFactory, IClassFactory), { 0 }, }; return QISearch(this, qit, riid, ppvObject); } STDMETHODIMP_(ULONG) CteClassFactory::AddRef() { LockModule(TRUE); return 2; } STDMETHODIMP_(ULONG) CteClassFactory::Release() { LockModule(FALSE); return 1; } STDMETHODIMP CteClassFactory::CreateInstance(IUnknown *pUnkOuter, REFIID riid, void **ppvObject) { *ppvObject = NULL; if (pUnkOuter != NULL) { return CLASS_E_NOAGGREGATION; } return g_pBase->QueryInterface(riid, ppvObject); } STDMETHODIMP CteClassFactory::LockServer(BOOL fLock) { LockModule(fLock); return S_OK; } //CteDispatch CteDispatch::CteDispatch(IDispatch *pDispatch, int nMode, DISPID dispId) { m_cRef = 1; pDispatch->QueryInterface(IID_PPV_ARGS(&m_pDispatch)); m_dispIdMember = dispId; } CteDispatch::~CteDispatch() { Clear(); } VOID CteDispatch::Clear() { SafeRelease(&m_pDispatch); } STDMETHODIMP CteDispatch::QueryInterface(REFIID riid, void **ppvObject) { static const QITAB qit[] = { QITABENT(CteDispatch, IDispatch), { 0 }, }; return QISearch(this, qit, riid, ppvObject); } STDMETHODIMP_(ULONG) CteDispatch::AddRef() { return ::InterlockedIncrement(&m_cRef); } STDMETHODIMP_(ULONG) CteDispatch::Release() { if (::InterlockedDecrement(&m_cRef) == 0) { delete this; return 0; } return m_cRef; } STDMETHODIMP CteDispatch::GetTypeInfoCount(UINT *pctinfo) { *pctinfo = 0; return S_OK; } STDMETHODIMP CteDispatch::GetTypeInfo(UINT iTInfo, LCID lcid, ITypeInfo **ppTInfo) { return E_NOTIMPL; } STDMETHODIMP CteDispatch::GetIDsOfNames(REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId) { return DISP_E_UNKNOWNNAME; } STDMETHODIMP CteDispatch::Invoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr) { try { if (pVarResult) { VariantInit(pVarResult); } if (wFlags & DISPATCH_METHOD) { return m_pDispatch->Invoke(m_dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr); } teSetObject(pVarResult, this); return S_OK; } catch (...) {} return DISP_E_MEMBERNOTFOUND; }
27,795
13,914
#include "config.h" #include "environment.h" #include "logging.h" #include "locks.h" #include <faabric/util/network.h> namespace faabric::util { SystemConfig &getSystemConfig() { static SystemConfig conf; return conf; } SystemConfig::SystemConfig() { this->initialise(); } void SystemConfig::initialise() { // System hostType = getEnvVar("HOST_TYPE", "default"); functionStorage = getEnvVar("FUNCTION_STORAGE", "local"); fileserverUrl = getEnvVar("FILESERVER_URL", ""); serialisation = getEnvVar("SERIALISATION", "json"); cgroupMode = getEnvVar("CGROUP_MODE", "on"); netNsMode = getEnvVar("NETNS_MODE", "off"); logLevel = getEnvVar("LOG_LEVEL", "info"); pythonPreload = getEnvVar("PYTHON_PRELOAD", "off"); captureStdout = getEnvVar("CAPTURE_STDOUT", "off"); stateMode = getEnvVar("STATE_MODE", "inmemory"); wasmVm = getEnvVar("WASM_VM", "wavm"); // Redis redisStateHost = getEnvVar("REDIS_STATE_HOST", "localhost"); redisQueueHost = getEnvVar("REDIS_QUEUE_HOST", "localhost"); redisPort = getEnvVar("REDIS_PORT", "6379"); // Scheduling noScheduler = this->getSystemConfIntParam("NO_SCHEDULER", "0"); maxNodes = this->getSystemConfIntParam("MAX_NODES", "5"); maxInFlightRatio = this->getSystemConfIntParam("MAX_IN_FLIGHT_RATIO", "1"); maxNodesPerFunction = this->getSystemConfIntParam("MAX_NODES_PER_FUNCTION", "5"); // Threading threadMode = getEnvVar("THREAD_MODE", "local"); ompThreadPoolSize = this->getSystemConfIntParam("OMP_THREAD_POOL_SIZE", "0"); // Worker-related timeouts (all in seconds) globalMessageTimeout = this->getSystemConfIntParam("GLOBAL_MESSAGE_TIMEOUT", "60000"); boundTimeout = this->getSystemConfIntParam("BOUND_TIMEOUT", "30000"); unboundTimeout = this->getSystemConfIntParam("UNBOUND_TIMEOUT", "300000"); chainedCallTimeout = this->getSystemConfIntParam("CHAINED_CALL_TIMEOUT", "300000"); // Filesystem storage functionDir = getEnvVar("FUNC_DIR", "/usr/local/code/faasm/wasm"); objectFileDir = getEnvVar("OBJ_DIR", "/usr/local/faasm/object"); runtimeFilesDir = getEnvVar("RUNTIME_FILES_DIR", "/usr/local/faasm/runtime_root"); sharedFilesDir = getEnvVar("SHARED_FILES_DIR", "/usr/local/faasm/shared"); sharedFilesStorageDir = getEnvVar("SHARED_FILES_STORAGE_DIR", "/usr/local/faasm/shared_store"); // MPI defaultMpiWorldSize = this->getSystemConfIntParam("DEFAULT_MPI_WORLD_SIZE", "5"); // Endpoint endpointInterface = getEnvVar("ENDPOINT_INTERFACE", ""); endpointHost = getEnvVar("ENDPOINT_HOST", ""); endpointPort = this->getSystemConfIntParam("ENDPOINT_PORT", "8080"); endpointNumThreads = this->getSystemConfIntParam("ENDPOINT_NUM_THREADS", "4"); if (endpointHost.empty()) { // Get the IP for this host endpointHost = faabric::util::getPrimaryIPForThisHost(endpointInterface); } } int SystemConfig::getSystemConfIntParam(const char *name, const char *defaultValue) { int value = stoi(getEnvVar(name, defaultValue)); return value; }; void SystemConfig::reset() { this->initialise(); } void SystemConfig::print() { const std::shared_ptr<spdlog::logger> &logger = getLogger(); logger->info("--- System ---"); logger->info("HOST_TYPE {}", hostType); logger->info("FUNCTION_STORAGE {}", functionStorage); logger->info("FILESERVER_URL {}", fileserverUrl); logger->info("SERIALISATION {}", serialisation); logger->info("CGROUP_MODE {}", cgroupMode); logger->info("NETNS_MODE {}", netNsMode); logger->info("LOG_LEVEL {}", logLevel); logger->info("PYTHON_PRELOAD {}", pythonPreload); logger->info("CAPTURE_STDOUT {}", captureStdout); logger->info("STATE_MODE {}", stateMode); logger->info("WASM_VM {}", wasmVm); logger->info("--- Redis ---"); logger->info("REDIS_STATE_HOST {}", redisStateHost); logger->info("REDIS_QUEUE_HOST {}", redisQueueHost); logger->info("REDIS_PORT {}", redisPort); logger->info("--- Scheduling ---"); logger->info("NO_SCHEDULER {}", noScheduler); logger->info("MAX_NODES {}", maxNodes); logger->info("MAX_IN_FLIGHT_RATIO {}", maxInFlightRatio); logger->info("MAX_NODES_PER_FUNCTION {}", maxNodesPerFunction); logger->info("--- Threading ---"); logger->info("THREAD_MODE {}", threadMode); logger->info("OMP_THREAD_POOL_SIZE {}", ompThreadPoolSize); logger->info("--- Timeouts ---"); logger->info("GLOBAL_MESSAGE_TIMEOUT {}", globalMessageTimeout); logger->info("BOUND_TIMEOUT {}", boundTimeout); logger->info("UNBOUND_TIMEOUT {}", unboundTimeout); logger->info("CHAINED_CALL_TIMEOUT {}", chainedCallTimeout); logger->info("--- Storage ---"); logger->info("FUNC_DIR {}", functionDir); logger->info("OBJ_DIR {}", objectFileDir); logger->info("RUNTIME_FILES_DIR {}", runtimeFilesDir); logger->info("SHARED_FILES_DIR {}", sharedFilesDir); logger->info("SHARED_FILES_STORAGE_DIR {}", sharedFilesStorageDir); logger->info("--- MPI ---"); logger->info("DEFAULT_MPI_WORLD_SIZE {}", defaultMpiWorldSize); logger->info("--- Endpoint ---"); logger->info("ENDPOINT_INTERFACE {}", endpointInterface); logger->info("ENDPOINT_HOST {}", endpointHost); logger->info("ENDPOINT_PORT {}", endpointPort); logger->info("ENDPOINT_NUM_THREADS {}", endpointNumThreads); } }
6,215
1,898
//---------------------------------------------------------------------------// // Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com> // // Distributed under the Boost Software License, Version 1.0 // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // // See http://boostorg.github.com/compute for more information. //---------------------------------------------------------------------------// #ifndef BOOST_COMPUTE_ALGORITHM_REVERSE_HPP #define BOOST_COMPUTE_ALGORITHM_REVERSE_HPP #include <boost/compute/system.hpp> #include <boost/compute/command_queue.hpp> #include <boost/compute/detail/meta_kernel.hpp> #include <boost/compute/detail/iterator_range_size.hpp> namespace boost { namespace compute { namespace detail { template<class Iterator> struct reverse_kernel : public meta_kernel { reverse_kernel(Iterator first, Iterator last) : meta_kernel("reverse") { typedef typename std::iterator_traits<Iterator>::value_type value_type; // store size of the range m_size = detail::iterator_range_size(first, last); add_set_arg<const cl_uint>("size", static_cast<const cl_uint>(m_size)); *this << decl<cl_uint>("i") << " = get_global_id(0);\n" << decl<cl_uint>("j") << " = size - get_global_id(0) - 1;\n" << decl<value_type>("tmp") << "=" << first[var<cl_uint>("i")] << ";\n" << first[var<cl_uint>("i")] << "=" << first[var<cl_uint>("j")] << ";\n" << first[var<cl_uint>("j")] << "= tmp;\n"; } void exec(command_queue &queue) { exec_1d(queue, 0, m_size / 2); } size_t m_size; }; } // end detail namespace /// Reverses the elements in the range [\p first, \p last). /// /// Space complexity: \Omega(1) /// /// \see reverse_copy() template<class Iterator> inline void reverse(Iterator first, Iterator last, command_queue &queue = system::default_queue()) { size_t count = detail::iterator_range_size(first, last); if(count < 2){ return; } detail::reverse_kernel<Iterator> kernel(first, last); kernel.exec(queue); } } // end compute namespace } // end boost namespace #endif // BOOST_COMPUTE_ALGORITHM_REVERSE_HPP
2,356
794
// Copyright 1996-2021 Cyberbotics 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. #ifndef WB_JOINT_PARAMETERS_HPP #define WB_JOINT_PARAMETERS_HPP #include "WbBaseNode.hpp" #include "WbSFDouble.hpp" #include "WbSFVector3.hpp" class WbJointParameters : public WbBaseNode { Q_OBJECT public: explicit WbJointParameters(const QString &modelName, WbTokenizer *tokenizer = NULL); explicit WbJointParameters(WbTokenizer *tokenizer = NULL); WbJointParameters(const WbJointParameters &other); explicit WbJointParameters(const WbNode &other); virtual ~WbJointParameters(); int nodeType() const override { return WB_NODE_JOINT_PARAMETERS; } void preFinalize() override; void postFinalize() override; double position() const { return mPosition->value(); } double maxStop() const { return mMaxStop->value(); } double minStop() const { return mMinStop->value(); } double springConstant() const { return mSpringConstant->value(); } double dampingConstant() const { return mDampingConstant->value(); } double staticFriction() const { return mStaticFriction->value(); } const WbVector3 axis() const { return mAxis ? mAxis->value() : WbVector3(); } void setPosition(double p) { mPosition->setValue(p); } void setPositionFromOde(double p) { mPosition->setValueFromOde(p); } bool clampPosition(double &p) const; signals: void positionChanged(); void minAndMaxStopChanged(double min, double max); void springAndDampingConstantsChanged(); void axisChanged(); protected: WbSFVector3 *mAxis; // axis default value redefined in a derived classes bool exportNodeHeader(WbVrmlWriter &writer) const override; private: WbJointParameters &operator=(const WbJointParameters &); // non copyable WbNode *clone() const override { return new WbJointParameters(*this); } void init(); // fields WbSFDouble *mPosition; WbSFDouble *mMinStop; WbSFDouble *mMaxStop; WbSFDouble *mSpringConstant; WbSFDouble *mDampingConstant; WbSFDouble *mStaticFriction; private slots: void updateMinAndMaxStop(); void updateSpringConstant(); void updateDampingConstant(); void updateStaticFriction(); virtual void updateAxis(); }; #endif
2,692
868
#include <bits/stdc++.h> using namespace std; #define MAX 5 class Queue { public: int items[MAX]; int front; int rear; Queue() { front = -1; rear = -1; }; void enQueue(int val) { if(isFull()) { cout << "Queue is Full" << endl; return; } if(front == -1) { front = 0; } rear = (rear + 1) % MAX; items[rear] = val; } int deQueue() { if(isEmpty()) { cout << "Queue is Empty"; exit(0); } int element = items[front]; if(front == rear) { front = -1; rear = -1; } else { // Queue has only one element // so we are resetting the queue front = (front + 1) % MAX; } return element; } bool isFull() { if (front == 0 && rear == MAX - 1) return true; if (front == rear + 1) return true; return false; } bool isEmpty() { return front == -1 ? true : false; } void display() { int i; if (isEmpty()) { cout << endl << "Empty Queue" << endl; } else { cout << "Front -> " << front; cout << endl << "Items -> "; for (i = front; i != rear; i = (i + 1) % MAX) { cout << items[i] << " "; } cout << items[i]; cout << endl << "Rear -> " << rear; } } }; int main() { Queue *q = new Queue(); q->enQueue(1); q->enQueue(2); q->enQueue(3); q->enQueue(4); q->enQueue(5); q->display(); return 0; }
1,530
557
//****************************************************************** // // Copyright 2016 Samsung Electronics All Rights Reserved. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= #include <gtest/gtest.h> #include <atomic> #include <functional> #include <condition_variable> #include <mutex> #include <chrono> #include "NSProviderInterface.h" #include "NSConsumerSimulator.h" #include "NSUnittestUtil.h" #include "NSCommon.h" namespace { std::atomic_bool g_isStartedStack(false); /// Reasonable timeout is set to 1000 ms in unsecured mode unsigned int g_timeout = 1000; #ifdef SECURED g_timeout = 2 * g_timeout #endif std::chrono::milliseconds g_waitForResponse(g_timeout); std::condition_variable responseProviderSub; std::mutex responseProviderSubLock; std::condition_variable responseProviderSync; std::mutex responseProviderSyncLock; std::condition_variable responseConsumerMessage; std::mutex responseConsumerMessageLock; std::condition_variable responseConsumerSync; std::mutex responseConsumerSyncLock; NSConsumerSimulator g_consumerSimul; char * g_consumerID = NULL; char g_title[100]; char g_body[100]; char g_sourceName[100]; int expectedMsgId; int expectedSyncType = NS_SYNC_READ; static FILE* server_open(const char * path, const char * mode) { if (0 == strcmp(path, OC_SECURITY_DB_DAT_FILE_NAME)) { std::string file_name = "./oic_svr_db_ns.dat"; #ifndef LOCAL_RUNNING file_name = "./service/notification/unittest/oic_svr_db_ns.dat"; #endif return fopen(file_name.c_str(), mode); } else { return fopen(path, mode); } } } class TestWithMock: public testing::Test { protected: virtual ~TestWithMock() noexcept(noexcept(std::declval<Test>().~Test())) { } virtual void TearDown() { } }; class NotificationProviderTest : public TestWithMock { public: NotificationProviderTest() = default; ~NotificationProviderTest() = default; static void NSRequestedSubscribeCallback(NSConsumer * consumer) { if (g_consumerID) { free(g_consumerID); } g_consumerID = strdup(consumer->consumerId); responseProviderSub.notify_all(); } static void NSSyncCallback(NSSyncInfo * sync) { expectedSyncType = sync->state; expectedMsgId = sync->messageId; free(sync); responseProviderSync.notify_all(); } static void NSMessageCallbackFromConsumer( const int & id, const std::string &, const std::string &, const std::string &) { expectedMsgId = id; responseConsumerMessage.notify_all(); } static void NSSyncCallbackFromConsumer(const int type, const int syncId) { expectedSyncType = type; expectedMsgId = syncId; responseConsumerSync.notify_all(); } protected: void SetUp() { TestWithMock::SetUp(); if (g_isStartedStack == false) { static OCPersistentStorage gps {server_open, fread, fwrite, fclose, unlink }; OC::PlatformConfig cfg { OC::ServiceType::InProc, OC::ModeType::Both, "0.0.0.0", 0, OC::QualityOfService::HighQos, &gps }; OC::OCPlatform::Configure(cfg); try { OC::OCPlatform::stopPresence(); } catch (...) { } g_isStartedStack = true; strncpy(g_title, "Title", strlen("Title")); strncpy(g_body, "ContentText", strlen("ContentText")); strncpy(g_sourceName, "OIC", strlen("OIC")); } } void TearDown() { TestWithMock::TearDown(); } }; TEST_F(NotificationProviderTest, StartProviderPositiveWithNSPolicyTrue) { NSProviderConfig config; config.subRequestCallback = NSRequestedSubscribeCallback; config.syncInfoCallback = NSSyncCallback; config.subControllability = true; config.userInfo = strdup("user1"); config.resourceSecurity = false; NSResult ret = NSStartProvider(config); EXPECT_EQ(ret, NS_OK); free(config.userInfo); config.userInfo = NULL; } TEST_F(NotificationProviderTest, StopProviderPositive) { NSResult ret = NSStopProvider(); EXPECT_EQ(ret, NS_OK); } TEST_F(NotificationProviderTest, StartProviderPositiveWithNSPolicyFalse) { NSProviderConfig config; config.subRequestCallback = NSRequestedSubscribeCallback; config.syncInfoCallback = NSSyncCallback; config.subControllability = false; config.userInfo = NULL; config.resourceSecurity = false; NSResult ret = NSStartProvider(config); g_consumerSimul.findProvider(); NSStopProvider(); EXPECT_EQ(ret, NS_OK); } TEST_F(NotificationProviderTest, ExpectCallbackWhenReceiveSubscribeRequestWithAccepterProvider) { NSProviderConfig config; config.subRequestCallback = NSRequestedSubscribeCallback; config.syncInfoCallback = NSSyncCallback; config.subControllability = true; config.userInfo = NULL; config.resourceSecurity = false; NSStartProvider(config); g_consumerSimul.setCallback(NSMessageCallbackFromConsumer, NSSyncCallbackFromConsumer); g_consumerSimul.findProvider(); // maximum waiting time for subscription is 1.5 sec. // usually maximum time is 1 sec. (g_waitForResponse = 1 sec.) unsigned int timeout = g_timeout * 1.5; #ifdef SECURED timemout = 2 * timemout; #endif std::chrono::milliseconds waitForSubscription(timemout); std::unique_lock< std::mutex > lock{ responseProviderSubLock }; responseProviderSub.wait_for(lock, waitForSubscription); ASSERT_NE(nullptr, g_consumerID) << "error: discovery failure"; } TEST_F(NotificationProviderTest, NeverCallNotifyOnConsumerByAcceptIsFalse) { int msgID; ASSERT_NE(nullptr, g_consumerID) << "error: discovery failure"; NSAcceptSubscription(g_consumerID, false); NSMessage * msg = NSCreateMessage(); if(msg) { msgID = (int)msg->messageId; msg->title = g_title; msg->contentText = g_body; msg->sourceName = g_sourceName; NSSendMessage(msg); std::unique_lock< std::mutex > lock{ responseConsumerMessageLock }; responseConsumerMessage.wait_for(lock, g_waitForResponse); EXPECT_NE(expectedMsgId, msgID); NSAcceptSubscription(g_consumerID, true); responseConsumerMessage.wait_for(lock, g_waitForResponse); } else { EXPECT_EQ(expectedMsgId, msgID); } free(msg); } TEST_F(NotificationProviderTest, ExpectCallNotifyOnConsumerByAcceptIsTrue) { int msgID; ASSERT_NE(nullptr, g_consumerID) << "error: discovery failure"; NSMessage * msg = NSCreateMessage(); if(msg) { msgID = (int)msg->messageId; msg->title = g_title; msg->contentText = g_body; msg->sourceName = g_sourceName; NSSendMessage(msg); std::unique_lock< std::mutex > lock{ responseConsumerMessageLock }; responseConsumerMessage.wait_for(lock, g_waitForResponse); EXPECT_EQ(expectedMsgId, msgID); } free(msg); } TEST_F(NotificationProviderTest, ExpectCallbackSyncOnReadToConsumer) { int id; int type = NS_SYNC_READ; ASSERT_NE(nullptr, g_consumerID) << "error: discovery failure"; NSMessage * msg = NSCreateMessage(); if(msg) { id = (int)msg->messageId; msg->title = g_title; msg->contentText = g_body; msg->sourceName = g_sourceName; NSProviderSendSyncInfo(msg->messageId, NS_SYNC_READ); std::unique_lock< std::mutex > lock{ responseConsumerSyncLock }; responseConsumerSync.wait_for(lock, g_waitForResponse); EXPECT_EQ(expectedMsgId, id); EXPECT_EQ(expectedSyncType, type); } free(msg); } TEST_F(NotificationProviderTest, ExpectCallbackSyncOnReadFromConsumer) { int id; int type = NS_SYNC_READ; ASSERT_NE(nullptr, g_consumerID) << "error: discovery failure"; NSMessage * msg = NSCreateMessage(); if(msg) { id = (int)msg->messageId; msg->title = g_title; msg->contentText = g_body; msg->sourceName = g_sourceName; g_consumerSimul.syncToProvider(type, id, msg->providerId); std::unique_lock< std::mutex > lock{ responseProviderSyncLock }; responseProviderSync.wait_for(lock, g_waitForResponse); EXPECT_EQ(expectedMsgId, id); EXPECT_EQ(expectedSyncType, type); } free(msg); } TEST_F(NotificationProviderTest, ExpectEqualAddedTopicsAndRegisteredTopics) { std::string str("TEST1"); std::string str2("TEST2"); NSProviderRegisterTopic(str.c_str()); NSProviderRegisterTopic(str2.c_str()); bool isSame = true; NSTopicLL * topics = NSProviderGetTopics(); if(!topics) { isSame = false; } else { NSTopicLL * iter = topics; std::string compStr(iter->topicName); std::string compStr2(iter->next->topicName); if(str.compare(compStr) == 0 && str2.compare(compStr2) == 0) { isSame = true; } } removeTopics(topics); NSProviderUnregisterTopic(str.c_str()); NSProviderUnregisterTopic(str2.c_str()); EXPECT_EQ(isSame, true); } TEST_F(NotificationProviderTest, ExpectEqualUnregisteredTopicsAndRegisteredTopics) { std::string str("TEST1"); std::string str2("TEST2"); NSProviderRegisterTopic(str.c_str()); NSProviderRegisterTopic(str2.c_str()); NSProviderUnregisterTopic(str2.c_str()); bool isSame = true; NSTopicLL * topics = NSProviderGetTopics(); if(!topics) { isSame = false; } else { NSTopicLL * iter = topics; std::string compStr(iter->topicName); if(str.compare(compStr) == 0) { isSame = true; } } removeTopics(topics); NSProviderUnregisterTopic(str.c_str()); EXPECT_EQ(isSame, true); } TEST_F(NotificationProviderTest, ExpectEqualSetConsumerTopicsAndGetConsumerTopics) { std::string str("TEST1"); std::string str2("TEST2"); NSProviderRegisterTopic(str.c_str()); NSProviderRegisterTopic(str2.c_str()); NSProviderSetConsumerTopic(g_consumerID, str.c_str()); bool isSame = false; NSTopicLL * topics = NSProviderGetConsumerTopics(g_consumerID); if(!topics) { isSame = false; } else { NSTopicLL * firstData = topics; NSTopicLL * secondData = firstData->next; if(str.compare(firstData->topicName) == 0 && str2.compare(secondData->topicName) == 0 && ((int)firstData->state) == 1 && ((int)secondData->state) == 0) { isSame = true; } } removeTopics(topics); NSProviderUnregisterTopic(str.c_str()); NSProviderUnregisterTopic(str2.c_str()); EXPECT_EQ(isSame, true); } TEST_F(NotificationProviderTest, ExpectEqualUnSetConsumerTopicsAndGetConsumerTopics) { std::string str("TEST1"); std::string str2("TEST2"); NSProviderRegisterTopic(str.c_str()); NSProviderRegisterTopic(str2.c_str()); NSProviderSetConsumerTopic(g_consumerID, str.c_str()); NSProviderSetConsumerTopic(g_consumerID, str2.c_str()); NSProviderUnsetConsumerTopic(g_consumerID, str.c_str()); bool isSame = false; ASSERT_NE(nullptr, g_consumerID) << "error: discovery failure"; NSTopicLL * topics = NSProviderGetConsumerTopics(g_consumerID); if(!topics) { isSame = false; } else { NSTopicLL * firstData = topics; NSTopicLL * secondData = firstData->next; if(str.compare(firstData->topicName) == 0 && str2.compare(secondData->topicName) == 0 && ((int)firstData->state) == 0 && ((int)secondData->state) == 1) { isSame = true; } } removeTopics(topics); NSProviderUnregisterTopic(str.c_str()); NSProviderUnregisterTopic(str2.c_str()); EXPECT_EQ(isSame, true); } TEST_F(NotificationProviderTest, ExpectFailAcceptSubscription) { NSResult result; result = NS_SUCCESS; result = NSAcceptSubscription(NULL, true); result = NSAcceptSubscription("\0", true); EXPECT_EQ(result, NS_FAIL); } TEST_F(NotificationProviderTest, ExpectFailSendMessage) { NSResult result; result = NS_SUCCESS; result = NSSendMessage(NULL); EXPECT_EQ(result, NS_FAIL); } TEST_F(NotificationProviderTest, ExpectFailRegisterTopic) { NSResult result; result = NS_SUCCESS; result = NSProviderRegisterTopic(NULL); result = NSProviderRegisterTopic("\0"); EXPECT_EQ(result, NS_FAIL); } TEST_F(NotificationProviderTest, ExpectFailUnregisterTopic) { NSResult result; result = NS_SUCCESS; result = NSProviderUnregisterTopic(NULL); result = NSProviderUnregisterTopic("\0"); EXPECT_EQ(result, NS_FAIL); } TEST_F(NotificationProviderTest, ExpectFailGetConsumerTopics) { NSTopicLL topic; NSTopicLL * topicLL = &topic; topicLL = NSProviderGetConsumerTopics(NULL); topicLL = NSProviderGetConsumerTopics("\0"); EXPECT_EQ(topicLL, (NSTopicLL *)NULL); } TEST_F(NotificationProviderTest, ExpectFailSetConsumerTopics) { NSResult result; result = NS_SUCCESS; result = NSProviderSetConsumerTopic(NULL, NULL); result = NSProviderSetConsumerTopic(NULL, "\0"); result = NSProviderSetConsumerTopic("\0", NULL); result = NSProviderSetConsumerTopic("\0", "\0"); result = NSProviderSetConsumerTopic("abc", NULL); result = NSProviderSetConsumerTopic(NULL, "abc"); result = NSProviderSetConsumerTopic("abc", "\0"); result = NSProviderSetConsumerTopic("\0", "abc"); EXPECT_EQ(result, NS_FAIL); } TEST_F(NotificationProviderTest, ExpectFailUnsetConsumerTopics) { NSResult result; result = NS_SUCCESS; result = NSProviderUnsetConsumerTopic(NULL, NULL); result = NSProviderUnsetConsumerTopic(NULL, "\0"); result = NSProviderUnsetConsumerTopic("\0", NULL); result = NSProviderUnsetConsumerTopic("\0", "\0"); result = NSProviderUnsetConsumerTopic("abc", NULL); result = NSProviderUnsetConsumerTopic(NULL, "abc"); result = NSProviderUnsetConsumerTopic("abc", "\0"); result = NSProviderUnsetConsumerTopic("\0", "abc"); EXPECT_EQ(result, NS_FAIL); } TEST_F(NotificationProviderTest, CancelObserves) { bool ret = g_consumerSimul.cancelObserves(); std::chrono::milliseconds waitForTerminate(g_timemout); std::this_thread::sleep_for(waitForTerminate); EXPECT_EQ(ret, true); }
15,455
5,098
/***********************************************************/ /* File: objectdetection-contours-video.cpp */ /* Author: Travis Bueter */ /* Desc: This file tests the use of identifying objects */ /* based on their contours of a video feed. */ /* Based on a tutorial from the OpenCV website. */ /***********************************************************/ #include <opencv2/opencv.hpp> #include <highgui.h> #include <iostream> #include <stdlib.h> #include <stdio.h> #include <ctime> /* time */ #include <string> #include <math.h> //#include "opencv2/imgcodecs.hpp" using namespace cv; using namespace std; int main() { Mat img, edges, out, modi; //Set up camera VideoCapture cap(0); // open the video camera no. 0 while(!cap.isOpened()) // if not success, exit program { cout << "error cannot read from the camera" << endl; } while(1) { bool bSuccess = cap.read(img); // read a new frame from video if (!bSuccess) //if not success, break loop { cout << "Cannot read a frame from video stream" << endl; break; } //converting the original image into grayscale Mat imgGrayScale = Mat(img.size(), 8, 1); cvtColor(img,imgGrayScale,CV_BGR2GRAY); //Attempted to use for smoothing spots in the image //GaussianBlur(imgGrayScale,imgGrayScale,Size(7,7),1.5,1.5); //thresholding the grayscale image to get better results threshold(imgGrayScale,imgGrayScale,128,255,CV_THRESH_BINARY); vector< vector<Point> > contours; vector<Vec4i> hierarchy; //finding all contours in the image findContours(imgGrayScale, contours, hierarchy, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, Point(0,0)); vector< vector<Point> > contours_poly(contours.size()); //iterating through each contour for(int i = 0; i < contours.size(); i++) { //obtain a sequence of points of the countour approxPolyDP(Mat(contours[i]), contours_poly[i], arcLength(contours[i],true)*0.02, true); //if there are 3 vertices in the contour(It should be a triangle) vector<Point> result = contours_poly[i]; if(result.size() == 3) { //drawing lines around the triangle for(int j = 0; j < result.size()-1; j++) { line(img, result[j], result[j+1], cvScalar(255,0,0),4); } line(img, result[result.size()-1], result[0], cvScalar(255,0,0),4); } if(result.size() == 4) { //drawing lines around the triangle for(int j = 0; j < result.size()-1; j++) { line(img, result[j], result[j+1], cvScalar(0,255,0),4); } line(img, result[result.size()-1], result[0], cvScalar(0,255,0),4); } if(result.size() == 5) { //drawing lines around the triangle for(int j = 0; j < result.size()-1; j++) { line(img, result[j], result[j+1], cvScalar(0,0,255),4); } line(img, result[result.size()-1], result[0], cvScalar(0,0,255),4); } if(result.size() == 6) { //drawing lines around the triangle for(int j = 0; j < result.size()-1; j++) { line(img, result[j], result[j+1], cvScalar(255,0,127),4); } line(img, result[result.size()-1], result[0], cvScalar(255,0,127),4); } if(result.size() == 10) { //drawing lines around the triangle for(int j = 0; j < result.size()-1; j++) { line(img, result[j], result[j+1], cvScalar(0,255,255),4); } line(img, result[result.size()-1], result[0], cvScalar(0,255,255),4); } } namedWindow("MyVideo",CV_WINDOW_AUTOSIZE); imshow("MyVideo", img); if (waitKey(30) == 27)// 'Esc' key { cout << "Esc key is pressed by user." << endl; break; } } cap.release(); return 0; }
4,112
1,609
#include <profiling.hpp> #include <fstream> namespace llarp { bool RouterProfile::BEncode(llarp_buffer_t* buf) const { if(!bencode_start_dict(buf)) return false; if(!BEncodeWriteDictInt("g", connectGoodCount, buf)) return false; if(!BEncodeWriteDictInt("p", pathSuccessCount, buf)) return false; if(!BEncodeWriteDictInt("s", pathFailCount, buf)) return false; if(!BEncodeWriteDictInt("t", connectTimeoutCount, buf)) return false; if(!BEncodeWriteDictInt("u", lastUpdated, buf)) return false; if(!BEncodeWriteDictInt("v", version, buf)) return false; return bencode_end(buf); } bool RouterProfile::DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* buf) { bool read = false; if(!BEncodeMaybeReadDictInt("g", connectGoodCount, read, k, buf)) return false; if(!BEncodeMaybeReadDictInt("t", connectTimeoutCount, read, k, buf)) return false; if(!BEncodeMaybeReadDictInt("u", lastUpdated, read, k, buf)) return false; if(!BEncodeMaybeReadDictInt("v", version, read, k, buf)) return false; if(!BEncodeMaybeReadDictInt("s", pathFailCount, read, k, buf)) return false; if(!BEncodeMaybeReadDictInt("p", pathSuccessCount, read, k, buf)) return false; return read; } void RouterProfile::Decay() { connectGoodCount /= 2; connectTimeoutCount /= 2; pathSuccessCount /= 2; pathFailCount /= 2; lastUpdated = llarp::time_now_ms(); } void RouterProfile::Tick() { // 5 minutes static constexpr llarp_time_t updateInterval = DEFAULT_PATH_LIFETIME / 2; auto now = llarp::time_now_ms(); if(lastUpdated < now && now - lastUpdated > updateInterval) { Decay(); } } bool RouterProfile::IsGood(uint64_t chances) const { if(connectTimeoutCount > chances) return connectTimeoutCount <= connectGoodCount && (pathSuccessCount * chances) >= pathFailCount; else return (pathSuccessCount * chances) >= pathFailCount; } bool Profiling::IsBad(const RouterID& r, uint64_t chances) { lock_t lock(&m_ProfilesMutex); auto itr = m_Profiles.find(r); if(itr == m_Profiles.end()) return false; return !itr->second.IsGood(chances); } void Profiling::Tick() { lock_t lock(&m_ProfilesMutex); std::for_each(m_Profiles.begin(), m_Profiles.end(), [](auto& item) { item.second.Tick(); }); } void Profiling::MarkTimeout(const RouterID& r) { lock_t lock(&m_ProfilesMutex); m_Profiles[r].connectTimeoutCount += 1; m_Profiles[r].lastUpdated = llarp::time_now_ms(); } void Profiling::MarkSuccess(const RouterID& r) { lock_t lock(&m_ProfilesMutex); m_Profiles[r].connectGoodCount += 1; m_Profiles[r].lastUpdated = llarp::time_now_ms(); } void Profiling::ClearProfile(const RouterID& r) { lock_t lock(&m_ProfilesMutex); m_Profiles.erase(r); } void Profiling::MarkPathFail(path::Path* p) { lock_t lock(&m_ProfilesMutex); for(const auto& hop : p->hops) { // TODO: also mark bad? m_Profiles[hop.rc.pubkey].pathFailCount += 1; m_Profiles[hop.rc.pubkey].lastUpdated = llarp::time_now_ms(); } } void Profiling::MarkPathSuccess(path::Path* p) { lock_t lock(&m_ProfilesMutex); const auto sz = p->hops.size(); for(const auto& hop : p->hops) { m_Profiles[hop.rc.pubkey].pathSuccessCount += sz; m_Profiles[hop.rc.pubkey].lastUpdated = llarp::time_now_ms(); } } bool Profiling::Save(const char* fname) { absl::ReaderMutexLock lock(&m_ProfilesMutex); size_t sz = (m_Profiles.size() * (RouterProfile::MaxSize + 32 + 8)) + 8; std::vector< byte_t > tmp(sz, 0); llarp_buffer_t buf(tmp); auto res = BEncodeNoLock(&buf); if(res) { buf.sz = buf.cur - buf.base; std::ofstream f; f.open(fname); if(f.is_open()) { f.write((char*)buf.base, buf.sz); m_LastSave = llarp::time_now_ms(); } } return res; } bool Profiling::BEncode(llarp_buffer_t* buf) const { absl::ReaderMutexLock lock(&m_ProfilesMutex); return BEncodeNoLock(buf); } bool Profiling::BEncodeNoLock(llarp_buffer_t* buf) const { if(!bencode_start_dict(buf)) return false; auto itr = m_Profiles.begin(); while(itr != m_Profiles.end()) { if(!itr->first.BEncode(buf)) return false; if(!itr->second.BEncode(buf)) return false; ++itr; } return bencode_end(buf); } bool Profiling::DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* buf) { if(k.sz != 32) return false; RouterProfile profile; if(!profile.BDecode(buf)) return false; RouterID pk = k.base; return m_Profiles.emplace(pk, profile).second; } bool Profiling::Load(const char* fname) { lock_t lock(&m_ProfilesMutex); m_Profiles.clear(); if(!BDecodeReadFile(fname, *this)) { llarp::LogWarn("failed to load router profiles from ", fname); return false; } return true; } bool Profiling::ShouldSave(llarp_time_t now) const { auto dlt = now - m_LastSave; return dlt > 60000; } } // namespace llarp
5,330
2,013
/* -*-c++-*- */ /* osgEarth - Dynamic map generation toolkit for OpenSceneGraph * Copyright 2008-2010 Pelican Mapping * http://osgearth.org * * osgEarth is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #include "Common" #include "AMRGeometry" #include <osg/State> #include <osg/Uniform> #include <osgEarth/Notify> #define LC "[AMRGeometry] " // -------------------------------------------------------------------------- #include "AMRShaders.h" // -------------------------------------------------------------------------- AMRTriangle::AMRTriangle() { _stateSet = new osg::StateSet(); // should this be INT_SAMPLER_2D? _stateSet->getOrCreateUniform( "tex0", osg::Uniform::INT )->set( 0 ); } #define SET_UNIFORM(X,Y,Z) \ _stateSet->getOrCreateUniform( X , Y )->set( Z ) AMRTriangle::AMRTriangle(const MeshNode& n0, const osg::Vec2& t0, const MeshNode& n1, const osg::Vec2& t1, const MeshNode& n2, const osg::Vec2& t2) : _node0(n0), _node1(n1), _node2(n2) { _stateSet = new osg::StateSet(); // should this be INT_SAMPLER_2D? SET_UNIFORM( "tex0", osg::Uniform::INT, 0 ); SET_UNIFORM( "c0", osg::Uniform::FLOAT_VEC3, _node0._geodeticCoord ); SET_UNIFORM( "c1", osg::Uniform::FLOAT_VEC3, _node1._geodeticCoord ); SET_UNIFORM( "c2", osg::Uniform::FLOAT_VEC3, _node2._geodeticCoord ); SET_UNIFORM( "v0", osg::Uniform::FLOAT_VEC3, _node0._vertex ); SET_UNIFORM( "v1", osg::Uniform::FLOAT_VEC3, _node1._vertex ); SET_UNIFORM( "v2", osg::Uniform::FLOAT_VEC3, _node2._vertex ); SET_UNIFORM( "t0", osg::Uniform::FLOAT_VEC2, t0 ); SET_UNIFORM( "t1", osg::Uniform::FLOAT_VEC2, t1 ); SET_UNIFORM( "t2", osg::Uniform::FLOAT_VEC2, t2 ); SET_UNIFORM( "n0", osg::Uniform::FLOAT_VEC3, _node0._normal ); SET_UNIFORM( "n1", osg::Uniform::FLOAT_VEC3, _node1._normal ); SET_UNIFORM( "n2", osg::Uniform::FLOAT_VEC3, _node2._normal ); SET_UNIFORM( "r0", osg::Uniform::FLOAT_VEC4, _node0._geodeticRot.asVec4() ); SET_UNIFORM( "r1", osg::Uniform::FLOAT_VEC4, _node1._geodeticRot.asVec4() ); SET_UNIFORM( "r2", osg::Uniform::FLOAT_VEC4, _node2._geodeticRot.asVec4() ); } void AMRTriangle::expand( osg::BoundingBox& box ) { box.expandBy( _node0._vertex ); box.expandBy( _node1._vertex ); box.expandBy( _node2._vertex ); } // -------------------------------------------------------------------------- AMRDrawable::AMRDrawable() { _stateSet = new osg::StateSet(); } // -------------------------------------------------------------------------- AMRGeometry::AMRGeometry() { initShaders(); initPatterns(); //this->setBound( osg::BoundingBox(-1e10, -1e10, -1e10, 1e10, 1e10, 1e10) ); } AMRGeometry::AMRGeometry( const AMRGeometry& rhs, const osg::CopyOp& op ) : osg::Drawable( rhs, op ) //osg::Geometry( rhs, op ) { //todo setInitialBound( osg::BoundingBox(-1e10, -1e10, -1e10, 1e10, 1e10, 1e10) ); } osg::BoundingBox AMRGeometry::computeBound() const { osg::BoundingBox box; for( AMRDrawableList::const_iterator i = _drawList.begin(); i != _drawList.end(); ++i ) { const AMRTriangleList& prims = i->get()->_triangles; for( AMRTriangleList::const_iterator j = prims.begin(); j != prims.end(); ++j ) { j->get()->expand( box ); } } return box; } void AMRGeometry::clearDrawList() { if ( _drawList.size() > 0 ) { _drawList.clear(); dirtyBound(); } } void AMRGeometry::setDrawList( const AMRDrawableList& drawList ) { _drawList = drawList; dirtyBound(); } void AMRGeometry::initShaders() { // initialize the shader program. _program = new osg::Program(); _program->setName( "AMRGeometry" ); osg::Shader* vertexShader = new osg::Shader( osg::Shader::VERTEX, //std::string( source_vertShaderMain_flatMethod ) std::string( source_vertShaderMain_geocentricMethod ) + std::string( source_geodeticToXYZ ) + std::string( source_rotVecToGeodetic ) //std::string( source_vertShaderMain_latLonMethod ) //std::string( source_vertShaderMain_slerpMethod ) ); vertexShader->setName( "AMR Vert Shader" ); _program->addShader( vertexShader ); osg::Shader* fragmentShader = new osg::Shader( osg::Shader::FRAGMENT, std::string( source_fragShaderMain ) ); fragmentShader->setName( "AMR Frag Shader" ); _program->addShader( fragmentShader ); // the shader program: this->getOrCreateStateSet()->setAttribute( _program.get(), osg::StateAttribute::ON ); } static void toBarycentric(const osg::Vec3& p1, const osg::Vec3& p2, const osg::Vec3& p3, const osg::Vec3& in, osg::Vec3& outVert, osg::Vec2& outTex ) { //from: http://forums.cgsociety.org/archive/index.php/t-275372.html osg::Vec3 v1 = in - p1, v2 = in - p2, v3 = in - p3; double area1 = 0.5 * (v2 ^ v3).length(), area2 = 0.5 * (v1 ^ v3).length(), area3 = 0.5 * (v1 ^ v2).length(); double fullArea = area1 + area2 + area3; double u = area1/fullArea; double v = area2/fullArea; double w = area3/fullArea; outVert.set( u, v, w ); // tex coords osg::Vec2 t1( p1.x(), p1.y() ); osg::Vec2 t2( p2.x(), p2.y() ); osg::Vec2 t3( p3.x(), p3.y() ); outTex = t1*w + t2*v + t3*u; } void AMRGeometry::initPatterns() { _numPatternVerts = 0; _numPatternElements = 0; _numPatternStrips = 0; _numPatternTriangles = 0; this->setUseVertexBufferObjects( true ); this->setUseDisplayList( false ); _patternVBO = new osg::VertexBufferObject(); _verts = new osg::Vec3Array(); _verts->setVertexBufferObject( _patternVBO.get() ); _texCoords = new osg::Vec2Array(); _texCoords->setVertexBufferObject( _patternVBO.get() ); // build a right-triangle pattern. (0,0) is the lower-left (90d), // (0,1) is the lower right (45d) and (1,0) is the upper-left (45d) osg::Vec3f p1(0,0,0), p2(0,1,0), p3(1,0,0); for( int r=AMR_PATCH_ROWS-1; r >=0; --r ) { int cols = AMR_PATCH_ROWS-r; //OE_INFO << "ROW " << r << std::endl; for( int c=0; c<cols; ++c ) { osg::Vec3 point( (float)c/(float)(AMR_PATCH_ROWS-1), (float)r/(float)(AMR_PATCH_ROWS-1), 0 ); osg::Vec3 baryVert; osg::Vec2 baryTex; toBarycentric( p1, p2, p3, point, baryVert, baryTex ); _verts->push_back( baryVert ); _texCoords->push_back( baryTex ); } } _numPatternVerts = _verts->size(); unsigned short off = 0; unsigned short rowptr = off; _patternEBO = new osg::ElementBufferObject(); for( int r=1; r<AMR_PATCH_ROWS; ++r ) { rowptr += r; osg::DrawElementsUShort* e = new osg::DrawElementsUShort( GL_TRIANGLE_STRIP ); e->setElementBufferObject( _patternEBO.get() ); for( int c=0; c<=r; ++c ) { e->push_back( rowptr + c ); if ( c < r ) e->push_back( rowptr + c - r ); } OE_INFO << std::endl; _pattern.push_back( e ); _numPatternStrips++; _numPatternElements += e->size(); _numPatternTriangles += (e->size()-1)/2; } OE_INFO << LC << "Pattern: " << std::dec << "verts=" << _numPatternVerts << ", strips=" << _numPatternStrips << ", tris=" << _numPatternTriangles << ", elements=" << _numPatternElements << std::endl; } static int s_numTemplates = 0; void AMRGeometry::drawImplementation( osg::RenderInfo& renderInfo ) const { osg::State& state = *renderInfo.getState(); // bind the VBO: state.setVertexPointer( _verts.get() ); // bind the texture coordinate arrrays: state.setTexCoordPointer( 0, _texCoords.get() ); // this will enable the amr geometry's stateset (and activate the Program) state.pushStateSet( this->getStateSet() ); //state.pushStateSet(0L); //_program->apply( state ); int numTemplates = 0; for( AMRDrawableList::const_iterator i = _drawList.begin(); i != _drawList.end(); ++i ) { const AMRDrawable* drawable = i->get(); // apply the drawable's state changes: state.pushStateSet( drawable->_stateSet.get() ); for( AMRTriangleList::const_iterator j = drawable->_triangles.begin(); j != drawable->_triangles.end(); ++j ) { const AMRTriangle* dtemplate = j->get(); // apply the primitive's state changes: state.apply( dtemplate->_stateSet.get() ); // render the pattern (a collection of primitive sets) for( Pattern::const_iterator p = _pattern.begin(); p != _pattern.end(); ++p ) { p->get()->draw( state, true ); } numTemplates++; } state.popStateSet(); } if ( s_numTemplates != numTemplates ) { s_numTemplates = numTemplates; OE_INFO << LC << std::dec << "templates=" << numTemplates << ", verts=" << numTemplates*_numPatternVerts << ", strips=" << numTemplates*_numPatternStrips << ", tris=" << numTemplates*_numPatternTriangles << ", elements=" << numTemplates*_numPatternElements << std::endl; } // unbind the buffer objects. state.unbindVertexBufferObject(); state.unbindElementBufferObject(); // undo the program. state.popStateSet(); }
10,259
3,784
// The MIT License (MIT) // // Copyright (c) 2017-2018 Alexander Kurbatov #include "Unit.h" #include "core/API.h" #include "core/Helpers.h" #include "Hub.h" bp::Unit::Unit(sc2::UNIT_TYPEID who_builds_, sc2::UNIT_TYPEID required_addon_): m_who_builds(who_builds_), m_required_addon(required_addon_) { } bool bp::Unit::CanBeBuilt(const Order* order_) { if (m_required_addon == sc2::UNIT_TYPEID::INVALID) { return gHub->GetFreeBuildingProductionAssignee(order_, m_who_builds) != nullptr; } else { return gHub->GetFreeBuildingProductionAssignee(order_, m_who_builds, m_required_addon) != nullptr; } } bool bp::Unit::Build(Order* order_) { bool buildingAssignationSucceeded; if (m_required_addon == sc2::UNIT_TYPEID::INVALID) { buildingAssignationSucceeded = gHub->AssignBuildingProduction(order_, m_who_builds); } else { buildingAssignationSucceeded = gHub->AssignBuildingProduction(order_, m_who_builds, m_required_addon); } if (buildingAssignationSucceeded) { gAPI->action().Build(*order_); return true; } return false; }
1,115
419
/* * Copyright 2002-2021 oZ/acy (名賀月晃嗣) * Redistribution and use in source and binary forms, * with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE 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. * */ /* * @file jpegout.cpp * @author oZ/acy * @brief JPEG保存クラスの實裝 * * @date 2018.12.23 修正 * */ #include <cstdio> #include "jpegio.h" extern "C" { #include <jpeglib.h> #include <jerror.h> } #include <themis/exception.h> namespace polymnia { namespace private_ { void jpegErrorSetup_(jpeg_error_mgr& jerr); } } namespace { // 多重定義(オーバーロード)によつてfopen、_wfopenを切り替へる inline std::FILE* openfile(const char* path) { using namespace std; return fopen(path, "wb"); } inline std::FILE* openfile(const wchar_t* path) { using namespace std; return _wfopen(path, L"wb"); } }//end of namespace NONAME bool polymnia::JpegSaver::save( const polymnia::Picture* pct, const std::filesystem::path& path) { using namespace std; FILE *outfile = openfile(path.c_str()); if (!outfile) return false; struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; cinfo.err = jpeg_std_error(&jerr); polymnia::private_::jpegErrorSetup_(jerr); try { jpeg_create_compress(&cinfo); jpeg_stdio_dest(&cinfo, outfile); cinfo.image_width = pct->width(); cinfo.image_height = pct->height(); cinfo.input_components = 3; cinfo.in_color_space = JCS_RGB; jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, quality, TRUE); if (prog) jpeg_simple_progression(&cinfo); jpeg_start_compress(&cinfo, TRUE); JSAMPROW buf[1]; const polymnia::RgbColor* srcbuf = pct->buffer(); int o = pct->offset(); int j = 0; while(cinfo.next_scanline < cinfo.image_height) { buf[0] = (JSAMPROW)&srcbuf[j]; jpeg_write_scanlines(&cinfo, buf, 1); j += o; } jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo); fclose(outfile); return true; } catch(themis::Exception& exp) { jpeg_destroy_compress(&cinfo); fclose(outfile); return false; } } //eof
3,383
1,373
/* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "itkMacro.h" #include <iostream> #include <fstream> #include <string> #include "otbImage.h" #include "otbVectorImage.h" #include "otbImageFileReader.h" template<class InternalType> int otbVectorImageComplexGenericTest(int itkNotUsed(argc), char* argv[]) { typedef std::complex<InternalType> PixelType; typedef otb::VectorImage<PixelType, 2> ImageType; typedef otb::ImageFileReader<ImageType> ReaderType; typename ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(argv[1]); reader->UpdateOutputInformation(); std::cout << reader->GetOutput()->GetNumberOfComponentsPerPixel() << std::endl; otb::ImageIOBase::Pointer io = reader->GetImageIO(); std::cout << io << std::endl; reader->Update(); typename ImageType::IndexType index; index[0]=0; index[1]=0; typename ImageType::PixelType pixel = reader->GetOutput()->GetPixel(index); std::cout << pixel << std::endl; //Test value if ((pixel[0] != PixelType(0, 1)) || (pixel[1] != PixelType(20000, 20001))) { std::cout << "Found " << pixel[0] << " should be " << PixelType(0, 1) << std::endl; std::cout << "Found " << pixel[1] << " should be " << PixelType(20000, 20001) << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } int otbVectorImageComplexFloatTest(int argc, char* argv[]) { return otbVectorImageComplexGenericTest<float>(argc, argv); } int otbVectorImageComplexDoubleTest(int argc, char* argv[]) { return otbVectorImageComplexGenericTest<double>(argc, argv); } template<class InternalType> int otbImageComplexGenericTest(int itkNotUsed(argc), char* argv[]) { typedef std::complex<InternalType> PixelType; typedef otb::Image<PixelType, 2> ImageType; typedef otb::ImageFileReader<ImageType> ReaderType; typename ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(argv[1]); reader->UpdateOutputInformation(); std::cout << reader->GetOutput()->GetNumberOfComponentsPerPixel() << std::endl; otb::ImageIOBase::Pointer io = reader->GetImageIO(); std::cout << io << std::endl; reader->Update(); typename ImageType::IndexType index; index[0]=0; index[1]=0; typename ImageType::PixelType pixel = reader->GetOutput()->GetPixel(index); std::cout << pixel << std::endl; //Test value if (pixel != PixelType(0, 1)) { std::cout << "Found " << pixel << " should be " << PixelType(0, 1) << std::endl; return EXIT_FAILURE; } //Test other pixel index[0]=10; index[1]=10; pixel = reader->GetOutput()->GetPixel(index); std::cout << pixel << std::endl; if (pixel != PixelType(1010, 1011)) { std::cout << "Found " << pixel << " should be " << PixelType(1010, 1011) << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } int otbImageComplexFloatTest(int argc, char* argv[]) { return otbImageComplexGenericTest<float>(argc, argv); } int otbImageComplexDoubleTest(int argc, char* argv[]) { return otbImageComplexGenericTest<double>(argc, argv); } template<class InternalType> int otbVectorImageComplexIntoRealGenericTest(int itkNotUsed(argc), char* argv[]) { typedef InternalType PixelType; typedef otb::VectorImage<PixelType, 2> ImageType; typedef otb::ImageFileReader<ImageType> ReaderType; typename ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(argv[1]); reader->UpdateOutputInformation(); std::cout << reader->GetOutput()->GetNumberOfComponentsPerPixel() << std::endl; otb::ImageIOBase::Pointer io = reader->GetImageIO(); std::cout << io << std::endl; reader->Update(); typename ImageType::IndexType index; index[0]=0; index[1]=0; typename ImageType::PixelType pixel = reader->GetOutput()->GetPixel(index); std::cout << pixel << std::endl; //Test value if (reader->GetOutput()->GetNumberOfComponentsPerPixel() != 4) { std::cout << reader->GetOutput()->GetNumberOfComponentsPerPixel() << " bands instead of 4" << std::endl; return EXIT_FAILURE; } if ((pixel[0] != 0) || (pixel[1] != 1) || (pixel[2] != 20000) || (pixel[3] != 20001)) { std::cout << "Found " << pixel[0] << " should be " << 0 << std::endl; std::cout << "Found " << pixel[1] << " should be " << 1 << std::endl; std::cout << "Found " << pixel[2] << " should be " << 20000 << std::endl; std::cout << "Found " << pixel[3] << " should be " << 20001 << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } int otbVectorImageComplexIntoRealFloatTest(int argc, char* argv[]) { return otbVectorImageComplexIntoRealGenericTest<float>(argc, argv); } int otbVectorImageComplexIntoRealDoubleTest(int argc, char* argv[]) { return otbVectorImageComplexIntoRealGenericTest<double>(argc, argv); }
5,473
1,937
// DALICLOCK.CPP // Implements the actual drawing of the melting numbers // Earle F. Philhower, III <earle@ziplabel.com> // Most of this code was adapted from xdaliclock by Jamie Zawinski <jwz@jwz.org> // // His copyright message is included below: /* xscreensaver, Copyright (c) 1992, 1997 Jamie Zawinski <jwz@jwz.org> * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation. No representations are made about the suitability of this * software for any purpose. It is provided "as is" without express or * implied warranty. */ #include "stdafx.h" #include "WDaliClock.h" #include "daliclock.h" #undef MAX #undef MIN #define MAX(a, b) ((a)>(b)?(a):(b)) #define MIN(a, b) ((a)<(b)?(a):(b)) typedef struct raw_numer { unsigned char *bits; int width, height; } raw_number; #include "numbers0\zero0.xbm" #include "numbers0\one0.xbm" #include "numbers0\two0.xbm" #include "numbers0\three0.xbm" #include "numbers0\four0.xbm" #include "numbers0\five0.xbm" #include "numbers0\six0.xbm" #include "numbers0\seven0.xbm" #include "numbers0\eight0.xbm" #include "numbers0\nine0.xbm" #include "numbers0\colon0.xbm" #include "numbers0\slash0.xbm" static raw_number numbers_0 [] = { { zero0_bits, zero0_width, zero0_height }, { one0_bits, one0_width, one0_height }, { two0_bits, two0_width, two0_height }, { three0_bits, three0_width, three0_height }, { four0_bits, four0_width, four0_height }, { five0_bits, five0_width, five0_height }, { six0_bits, six0_width, six0_height }, { seven0_bits, seven0_width, seven0_height }, { eight0_bits, eight0_width, eight0_height }, { nine0_bits, nine0_width, nine0_height }, { colon0_bits, colon0_width, colon0_height }, { slash0_bits, slash0_width, slash0_height }, { 0, } }; #include "numbers1\zero1.xbm" #include "numbers1\one1.xbm" #include "numbers1\two1.xbm" #include "numbers1\three1.xbm" #include "numbers1\four1.xbm" #include "numbers1\five1.xbm" #include "numbers1\six1.xbm" #include "numbers1\seven1.xbm" #include "numbers1\eight1.xbm" #include "numbers1\nine1.xbm" #include "numbers1\colon1.xbm" #include "numbers1\slash1.xbm" static raw_number numbers_1 [] = { { zero1_bits, zero1_width, zero1_height }, { one1_bits, one1_width, one1_height }, { two1_bits, two1_width, two1_height }, { three1_bits, three1_width, three1_height }, { four1_bits, four1_width, four1_height }, { five1_bits, five1_width, five1_height }, { six1_bits, six1_width, six1_height }, { seven1_bits, seven1_width, seven1_height }, { eight1_bits, eight1_width, eight1_height }, { nine1_bits, nine1_width, nine1_height }, { colon1_bits, colon1_width, colon1_height }, { slash1_bits, slash1_width, slash1_height }, { 0, } }; #include "numbers2\zero2.xbm" #include "numbers2\one2.xbm" #include "numbers2\two2.xbm" #include "numbers2\three2.xbm" #include "numbers2\four2.xbm" #include "numbers2\five2.xbm" #include "numbers2\six2.xbm" #include "numbers2\seven2.xbm" #include "numbers2\eight2.xbm" #include "numbers2\nine2.xbm" #include "numbers2\colon2.xbm" #include "numbers2\slash2.xbm" static raw_number numbers_2 [] = { { zero2_bits, zero2_width, zero2_height }, { one2_bits, one2_width, one2_height }, { two2_bits, two2_width, two2_height }, { three2_bits, three2_width, three2_height }, { four2_bits, four2_width, four2_height }, { five2_bits, five2_width, five2_height }, { six2_bits, six2_width, six2_height }, { seven2_bits, seven2_width, seven2_height }, { eight2_bits, eight2_width, eight2_height }, { nine2_bits, nine2_width, nine2_height }, { colon2_bits, colon2_width, colon2_height }, { slash2_bits, slash2_width, slash2_height }, { 0, } }; #include "numbers3\zero3.xbm" #include "numbers3\one3.xbm" #include "numbers3\two3.xbm" #include "numbers3\three3.xbm" #include "numbers3\four3.xbm" #include "numbers3\five3.xbm" #include "numbers3\six3.xbm" #include "numbers3\seven3.xbm" #include "numbers3\eight3.xbm" #include "numbers3\nine3.xbm" #include "numbers3\colon3.xbm" #include "numbers3\slash3.xbm" static raw_number numbers_3 [] = { { zero3_bits, zero3_width, zero3_height }, { one3_bits, one3_width, one3_height }, { two3_bits, two3_width, two3_height }, { three3_bits, three3_width, three3_height }, { four3_bits, four3_width, four3_height }, { five3_bits, five3_width, five3_height }, { six3_bits, six3_width, six3_height }, { seven3_bits, seven3_width, seven3_height }, { eight3_bits, eight3_width, eight3_height }, { nine3_bits, nine3_width, nine3_height }, { colon3_bits, colon3_width, colon3_height }, { slash3_bits, slash3_width, slash3_height }, { 0, } }; COLORREF hsv_to_rgb (int h, double s, double v) { double H, S, V, R, G, B; double p1, p2, p3; double f; int i; int r, g, b; if (s < 0) s = 0; if (v < 0) v = 0; if (s > 1) s = 1; if (v > 1) v = 1; S = s; V = v; H = (h % 360) / 60.0; i = (int)H; f = H - i; p1 = V * (1 - S); p2 = V * (1 - (S * f)); p3 = V * (1 - (S * (1 - f))); if (i == 0) { R = V; G = p3; B = p1; } else if (i == 1) { R = p2; G = V; B = p1; } else if (i == 2) { R = p1; G = V; B = p3; } else if (i == 3) { R = p1; G = p2; B = V; } else if (i == 4) { R = p3; G = p1; B = V; } else { R = V; G = p1; B = p2; } r = (int)(R * 255.0); g = (int)(G * 255.0); b = (int)(B * 255.0); return RGB(r,g,b); } typedef short unsigned int POS; #define MAX_SEGS_PER_LINE 20 typedef struct scanline { POS left[MAX_SEGS_PER_LINE]; POS right[MAX_SEGS_PER_LINE]; } scanline; typedef struct frame { scanline scanlines[1]; /* scanlines are contiguous here */ } frame; inline int getbit(raw_number *num, int x, int y) { int ret; ret = (!! ((num->bits) [((y) * ((num->width+7) >> 3)) + ((x) >> 3)] & (1 << ((x) & 7)))); return ret; } static frame *image_to_frame(raw_number *image) { register int y, x; struct frame *frame; int width = image->width; int height = image->height; POS *left, *right; int maxsegments = 0; frame = (struct frame *) malloc (sizeof (struct frame) + (sizeof (struct scanline) * (height - 1))); for (y = 0; y < height; y++) { int seg, end; x = 0; left = frame->scanlines[y].left; right = frame->scanlines[y].right; for (seg = 0; seg < MAX_SEGS_PER_LINE; seg++) left [seg] = right [seg] = width / 2; for (seg = 0; seg < MAX_SEGS_PER_LINE; seg++) { for (; x < width; x++) if (getbit(image, x, y)) break; if (x == width) break; left [seg] = x; for (; x < width; x++) if (! getbit(image, x, y)) break; right [seg] = x; } for (; x < width; x++) if (getbit(image, x, y)) { exit (-1); } /* If there were any segments on this line, then replicate the last one out to the end of the line. If it's blank, leave it alone, meaning it will be a 0-pixel-wide line down the middle. */ end = seg; if (end > 0) for (; seg < MAX_SEGS_PER_LINE; seg++) { left [seg] = left [end-1]; right [seg] = right [end-1]; } if (end > maxsegments) maxsegments = end; } return frame; } static frame *base_frames [12]; static frame *clear_frame; int character_width, character_height; int colon_char_width; static void load_builtin_font(raw_number *nums) { int i; character_width = character_height = 0; for (i = 0; i < 12; i++) { raw_number *number = &nums [i]; character_width = MAX (character_width, number->width); character_height = MAX (character_height, number->height); if (base_frames[i]) free(base_frames[i]); base_frames [i] = image_to_frame (number); } colon_char_width = MAX (nums [10].width, nums [11].width); } void initialize_digits(int fontno) { raw_number *numbers; switch(fontno) { case 1: numbers=numbers_1; break; case 2: numbers=numbers_2; break; case 3: numbers=numbers_3; break; default: numbers=numbers_0; break; } load_builtin_font (numbers ); if (clear_frame) free(clear_frame); clear_frame = (struct frame *) malloc (sizeof (struct frame) + (sizeof (struct scanline) * (character_height - 1))); } static void set_current_scanlines (frame *into_frame, frame *from_frame) { register int i; for (i = 0; i < character_height; i++) into_frame->scanlines [i] = from_frame->scanlines [i]; } static void one_step (frame *current_frame, frame *target_frame, int tick) { register scanline *line = &current_frame->scanlines [0]; register scanline *target = &target_frame->scanlines [0]; register int i = 0, x; for (i = 0; i < character_height; i++) { #define STEP(field) (line->field += ((int) (target->field - line->field)) / tick) for (x = 0; x < MAX_SEGS_PER_LINE; x++) { STEP (left [x]); STEP (right [x]); } line++; target++; } } static void draw_frame(HDC hdc, frame *frame, int x_off, int y_off, int width) { register int y, x; for (y = 0; y < character_height; y++) { SelectObject(hdc, back); MoveToEx(hdc, x_off, y_off+y, NULL); LineTo(hdc, x_off+width, y_off+y); SelectObject(hdc, fore); struct scanline *line = &frame->scanlines [y]; for (x = 0; x < MAX_SEGS_PER_LINE; x++) { if (line->left[x] == line->right[x] || (x > 0 && line->left[x] == line->left[x-1] && line->right[x] == line->right[x-1])) continue; MoveToEx(hdc, x_off+line->left[x], y_off+y, NULL); LineTo(hdc, x_off+line->right[x], y_off+y); } } } int DrawColon(HDC hdc, int x, int y) { draw_frame(hdc, base_frames[10], x, y,colon_char_width ); return colon_char_width; } void DrawSpace(HDC hdc, int x, int y) { int i; SelectObject(hdc, back); for (i = 0; i < character_height; i++) { MoveToEx(hdc, x , y + i, NULL); LineTo(hdc, x+character_width, y + i); } } void DrawStage(HDC hdc, int x, int y, int start, int end, int count) { set_current_scanlines(clear_frame, base_frames[start]); if (count<10) for (int j=10; j>=count; j--) one_step(clear_frame, base_frames[end], 10-count); draw_frame(hdc, clear_frame, x, y, character_width); } void cycle_colors () { static int hue_tick=0; if (!trans) bc = hsv_to_rgb (hue_tick, 1.0, 1.0); else bc=RGB(255,255,255); fc = hsv_to_rgb ((hue_tick + 180) % 360, 1.0, 1.0); hue_tick = (hue_tick+1) % 360; DeleteObject(fore); DeleteObject(back); back=CreatePen(0,0,bc); fore=CreatePen(0,0,fc); }
10,773
4,683
// Mono Native Fixture // Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // Namespace: System.Security.Permissions // Name: FileDialogPermission // C++ Typed Name: mscorlib::System::Security::Permissions::FileDialogPermission #include <gtest/gtest.h> #include <mscorlib/System/Security/Permissions/mscorlib_System_Security_Permissions_FileDialogPermission.h> #include <mscorlib/System/Security/mscorlib_System_Security_SecurityElement.h> #include <mscorlib/System/mscorlib_System_String.h> #include <mscorlib/System/mscorlib_System_Type.h> namespace mscorlib { namespace System { namespace Security { namespace Permissions { //Constructors Tests //FileDialogPermission(mscorlib::System::Security::Permissions::PermissionState::__ENUM__ state) TEST(mscorlib_System_Security_Permissions_FileDialogPermission_Fixture,Constructor_1) { } //FileDialogPermission(mscorlib::System::Security::Permissions::FileDialogPermissionAccess::__ENUM__ access) TEST(mscorlib_System_Security_Permissions_FileDialogPermission_Fixture,Constructor_2) { } //Public Methods Tests // Method Copy // Signature: TEST(mscorlib_System_Security_Permissions_FileDialogPermission_Fixture,Copy_Test) { } // Method FromXml // Signature: mscorlib::System::Security::SecurityElement esd TEST(mscorlib_System_Security_Permissions_FileDialogPermission_Fixture,FromXml_Test) { } // Method Intersect // Signature: mscorlib::System::Security::IPermission target TEST(mscorlib_System_Security_Permissions_FileDialogPermission_Fixture,Intersect_Test) { } // Method IsSubsetOf // Signature: mscorlib::System::Security::IPermission target TEST(mscorlib_System_Security_Permissions_FileDialogPermission_Fixture,IsSubsetOf_Test) { } // Method IsUnrestricted // Signature: TEST(mscorlib_System_Security_Permissions_FileDialogPermission_Fixture,IsUnrestricted_Test) { } // Method ToXml // Signature: TEST(mscorlib_System_Security_Permissions_FileDialogPermission_Fixture,ToXml_Test) { } // Method Union // Signature: mscorlib::System::Security::IPermission target TEST(mscorlib_System_Security_Permissions_FileDialogPermission_Fixture,Union_Test) { } //Public Properties Tests // Property Access // Return Type: mscorlib::System::Security::Permissions::FileDialogPermissionAccess::__ENUM__ // Property Get Method TEST(mscorlib_System_Security_Permissions_FileDialogPermission_Fixture,get_Access_Test) { } // Property Access // Return Type: mscorlib::System::Security::Permissions::FileDialogPermissionAccess::__ENUM__ // Property Set Method TEST(mscorlib_System_Security_Permissions_FileDialogPermission_Fixture,set_Access_Test) { } } } } }
3,081
1,299
//by Hanchuan Peng //2006-2011 #include "convert_type2uint8.h" #include <stdio.h> bool convert_type2uint8_3dimg_1dpt(void * &img, V3DLONG * sz, int datatype) { if (!img || !sz) { fprintf(stderr, "The input to convert_type2uint8_3dimg_1dpt() are invalid [%s][%d].\n", __FILE__, __LINE__); return false; } if (datatype!=2 && datatype!=4) { fprintf(stderr, "This function convert_type2uint8_3dimg_1dpt() is designed to convert 16 bit and single-precision-float only.\n", __FILE__, __LINE__); return false; } if (sz[0]<1 || sz[1]<1 || sz[2]<1 || sz[3]<1 || sz[0]>2048 || sz[1]>2048 || sz[2]>1024 || sz[3]>10) { fprintf(stderr, "Input image size is not valid or too large [%s][%d] sz[0,1,2,3]=[%ld, %ld, %ld, %ld].\n", __FILE__, __LINE__, sz[0], sz[1], sz[2], sz[3]); return false; } V3DLONG totalunits = sz[0] * sz[1] * sz[2] * sz[3]; unsigned char * outimg = new unsigned char [totalunits]; if (!outimg) { fprintf(stderr, "Fail to allocate memory. [%s][%d].\n", __FILE__, __LINE__); return false; } if (datatype==2) { unsigned short int * tmpimg = (unsigned short int *)img; for (V3DLONG i=0;i<totalunits;i++) { outimg[i] = (unsigned char)(tmpimg[i]>>4); } } else { float * tmpimg = (float *)img; for (V3DLONG i=0;i<totalunits;i++) { outimg[i] = (unsigned char)(tmpimg[i]*255); } } //copy to output data delete [] ((unsigned char *)img); img = outimg; return true; }
1,442
685
#include <gainput/gainput.h> #include <gainput/GainputDebugRenderer.h> #include "GainputInputDeviceKeyboardImpl.h" #include "GainputKeyboardKeyNames.h" #include <gainput/GainputInputDeltaState.h> #include <gainput/GainputHelpers.h> #include <gainput/GainputLog.h> #if defined(GAINPUT_PLATFORM_LINUX) #include "GainputInputDeviceKeyboardLinux.h" #include "GainputInputDeviceKeyboardEvdev.h" #elif defined(GAINPUT_PLATFORM_WIN) #include "GainputInputDeviceKeyboardWin.h" #include "GainputInputDeviceKeyboardWinRaw.h" #elif defined(GAINPUT_PLATFORM_ANDROID) #include "GainputInputDeviceKeyboardAndroid.h" #elif defined(GAINPUT_PLATFORM_MAC) #include "GainputInputDeviceKeyboardMac.h" #endif #include "GainputInputDeviceKeyboardNull.h" namespace gainput { InputDeviceKeyboard::InputDeviceKeyboard(InputManager& manager, DeviceId device, unsigned index, DeviceVariant variant) : InputDevice(manager, device, index == InputDevice::AutoIndex ? manager.GetDeviceCountByType(DT_KEYBOARD): index), impl_(0), keyNames_(manager_.GetAllocator()) { state_ = manager.GetAllocator().New<InputState>(manager.GetAllocator(), KeyCount_); GAINPUT_ASSERT(state_); previousState_ = manager.GetAllocator().New<InputState>(manager.GetAllocator(), KeyCount_); GAINPUT_ASSERT(previousState_); #if defined(GAINPUT_PLATFORM_LINUX) if (variant == DV_STANDARD) { impl_ = manager.GetAllocator().New<InputDeviceKeyboardImplLinux>(manager, *this, *state_, *previousState_); } else if (variant == DV_RAW) { impl_ = manager.GetAllocator().New<InputDeviceKeyboardImplEvdev>(manager, *this, *state_, *previousState_); } #elif defined(GAINPUT_PLATFORM_WIN) if (variant == DV_STANDARD) { impl_ = manager.GetAllocator().New<InputDeviceKeyboardImplWin>(manager, *this, *state_, *previousState_); } else if (variant == DV_RAW) { impl_ = manager.GetAllocator().New<InputDeviceKeyboardImplWinRaw>(manager, *this, *state_, *previousState_); } #elif defined(GAINPUT_PLATFORM_ANDROID) impl_ = manager.GetAllocator().New<InputDeviceKeyboardImplAndroid>(manager, *this, *state_, *previousState_); #elif defined(GAINPUT_PLATFORM_MAC) impl_ = manager.GetAllocator().New<InputDeviceKeyboardImplMac>(manager, *this, *state_, *previousState_); #endif if (!impl_) { impl_ = manager.GetAllocator().New<InputDeviceKeyboardImplNull>(manager, device); } GAINPUT_ASSERT(impl_); GetKeyboardKeyNames(keyNames_); } InputDeviceKeyboard::~InputDeviceKeyboard() { manager_.GetAllocator().Delete(state_); manager_.GetAllocator().Delete(previousState_); manager_.GetAllocator().Delete(impl_); } void InputDeviceKeyboard::InternalUpdate(InputDeltaState* delta) { impl_->Update(delta); if ((manager_.IsDebugRenderingEnabled() || IsDebugRenderingEnabled()) && manager_.GetDebugRenderer()) { DebugRenderer* debugRenderer = manager_.GetDebugRenderer(); InputState* state = GetInputState(); char buf[64]; const float x = 0.2f; float y = 0.2f; for (int i = 0; i < KeyCount_; ++i) { if (state->GetBool(i)) { GetButtonName(i, buf, 64); debugRenderer->DrawText(x, y, buf); y += 0.025f; } } } } InputDevice::DeviceState InputDeviceKeyboard::InternalGetState() const { return impl_->GetState(); } InputDevice::DeviceVariant InputDeviceKeyboard::GetVariant() const { return impl_->GetVariant(); } size_t InputDeviceKeyboard::GetAnyButtonDown(DeviceButtonSpec* outButtons, size_t maxButtonCount) const { GAINPUT_ASSERT(outButtons); GAINPUT_ASSERT(maxButtonCount > 0); return CheckAllButtonsDown(outButtons, maxButtonCount, 0, KeyCount_); } size_t InputDeviceKeyboard::GetButtonName(DeviceButtonId deviceButton, char* buffer, size_t bufferLength) const { GAINPUT_ASSERT(IsValidButtonId(deviceButton)); GAINPUT_ASSERT(buffer); GAINPUT_ASSERT(bufferLength > 0); HashMap<Key, const char*>::const_iterator it = keyNames_.find(Key(deviceButton)); if (it == keyNames_.end()) { return 0; } strncpy_s(buffer, bufferLength, it->second, bufferLength); buffer[bufferLength-1] = 0; const size_t nameLen = strlen(it->second); return nameLen >= bufferLength ? bufferLength : nameLen+1; } ButtonType InputDeviceKeyboard::GetButtonType(DeviceButtonId deviceButton) const { GAINPUT_ASSERT(IsValidButtonId(deviceButton)); return BT_BOOL; } DeviceButtonId InputDeviceKeyboard::GetButtonByName(const char* name) const { GAINPUT_ASSERT(name); for (HashMap<Key, const char*>::const_iterator it = keyNames_.begin(); it != keyNames_.end(); ++it) { if (strcmp(name, it->second) == 0) { return it->first; } } return InvalidDeviceButtonId; } InputState* InputDeviceKeyboard::GetNextInputState() { return impl_->GetNextInputState(); } bool InputDeviceKeyboard::IsTextInputEnabled() const { return impl_->IsTextInputEnabled(); } void InputDeviceKeyboard::SetTextInputEnabled(bool enabled) { impl_->SetTextInputEnabled(enabled); } char InputDeviceKeyboard::GetNextCharacter() { return impl_->GetNextCharacter(); } }
4,962
1,827
#include "MccMethodNameChecker.h" #include "MccInvalidMethodNameError.h" #include "MccFunctionDeclaration.h" #include "MccRobot.h" MccMethodNameChecker::MccMethodNameChecker(void) { } MccMethodNameChecker::~MccMethodNameChecker(void) { } void MccMethodNameChecker::detect(MccFunctionDeclaration *fun) { string func_name = fun->get_decl_name(); int pos = func_name.find("label"); if (pos == 0) { for (int i = 5, len = func_name.length(); i < len; ++i) { if (func_name[i] <= '0' || func_name[i] >= '9') { return; } } MccInvalidMethodNameError *error = new MccInvalidMethodNameError(func_name); error->m_line_no = fun->get_lineno(); m_error_list.push_back(error); } }
695
292
//===--- swift-api-digester.cpp - API change detector ---------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // swift-api-digester is a test utility to detect source-breaking API changes // during the evolution of a Swift library. The tool works on two phases: // (1) dumping library contents as a JSON file, and (2) comparing two JSON // files textually to report interesting changes. // // During phase (1), the api-digester looks up every declarations inside // a module and outputs a singly-rooted tree that encloses interesting // details of the API level. // // During phase (2), api-digester applies structure-information comparison // algorithms on two given singly root trees, trying to figure out, as // precise as possible, the branches/leaves in the trees that differ from // each other. Further analysis decides whether the changed leaves/branches // can be reflected as source-breaking changes for API users. If they are, // the output of api-digester will include such changes. #include "swift/Frontend/PrintingDiagnosticConsumer.h" #include "swift/Frontend/SerializedDiagnosticConsumer.h" #include "swift/AST/DiagnosticsModuleDiffer.h" #include "swift/IDE/APIDigesterData.h" #include <functional> #include "ModuleAnalyzerNodes.h" #include "ModuleDiagsConsumer.h" using namespace swift; using namespace ide; using namespace api; namespace { enum class ActionType { None, DumpSDK, MigratorGen, DiagnoseSDKs, // The following two are for testing purposes DeserializeDiffItems, DeserializeSDK, GenerateNameCorrectionTemplate, FindUsr, GenerateEmptyBaseline, }; } // end anonymous namespace namespace options { static llvm::cl::OptionCategory Category("swift-api-digester Options"); static llvm::cl::opt<bool> IncludeAllModules("include-all", llvm::cl::desc("Include all modules from the SDK"), llvm::cl::cat(Category)); static llvm::cl::list<std::string> ModuleNames("module", llvm::cl::ZeroOrMore, llvm::cl::desc("Names of modules"), llvm::cl::cat(Category)); static llvm::cl::opt<std::string> ModuleList("module-list-file", llvm::cl::desc("File containing a new-line separated list of modules"), llvm::cl::cat(Category)); static llvm::cl::opt<std::string> ProtReqWhiteList("protocol-requirement-white-list", llvm::cl::desc("File containing a new-line separated list of protocol names"), llvm::cl::cat(Category)); static llvm::cl::opt<std::string> OutputFile("o", llvm::cl::desc("Output file"), llvm::cl::cat(Category)); static llvm::cl::opt<std::string> OutputDir("output-dir", llvm::cl::desc("Directory path to where we dump the generated Json files"), llvm::cl::cat(Category)); static llvm::cl::opt<std::string> SDK("sdk", llvm::cl::desc("path to the SDK to build against"), llvm::cl::cat(Category)); static llvm::cl::opt<std::string> BaselineSDK("bsdk", llvm::cl::desc("path to the baseline SDK to import frameworks"), llvm::cl::cat(Category)); static llvm::cl::opt<std::string> Triple("target", llvm::cl::desc("target triple"), llvm::cl::cat(Category)); static llvm::cl::opt<std::string> ModuleCachePath("module-cache-path", llvm::cl::desc("Clang module cache path"), llvm::cl::cat(Category)); static llvm::cl::opt<std::string> ResourceDir("resource-dir", llvm::cl::desc("The directory that holds the compiler resource files"), llvm::cl::cat(Category)); static llvm::cl::list<std::string> FrameworkPaths("F", llvm::cl::desc("add a directory to the framework search path"), llvm::cl::cat(Category)); static llvm::cl::list<std::string> BaselineFrameworkPaths("BF", llvm::cl::desc("add a directory to the baseline framework search path"), llvm::cl::cat(Category)); static llvm::cl::list<std::string> BaselineModuleInputPaths("BI", llvm::cl::desc("add a module for baseline input"), llvm::cl::cat(Category)); static llvm::cl::list<std::string> ModuleInputPaths("I", llvm::cl::desc("add a module for input"), llvm::cl::cat(Category)); static llvm::cl::list<std::string> CCSystemFrameworkPaths("iframework", llvm::cl::desc("add a directory to the clang importer system framework search path"), llvm::cl::cat(Category)); static llvm::cl::opt<bool> AbortOnModuleLoadFailure("abort-on-module-fail", llvm::cl::desc("Abort if a module failed to load"), llvm::cl::cat(Category)); static llvm::cl::opt<bool> Verbose("v", llvm::cl::desc("Verbose"), llvm::cl::cat(Category)); static llvm::cl::opt<bool> DebugMapping("debug-mapping", llvm::cl::desc("Dumping information for debug purposes"), llvm::cl::cat(Category)); static llvm::cl::opt<bool> Abi("abi", llvm::cl::desc("Dumping ABI interface"), llvm::cl::init(false), llvm::cl::cat(Category)); static llvm::cl::opt<bool> SwiftOnly("swift-only", llvm::cl::desc("Only include APIs defined from Swift source"), llvm::cl::init(false), llvm::cl::cat(Category)); static llvm::cl::opt<bool> DisableOSChecks("disable-os-checks", llvm::cl::desc("Skip OS related diagnostics"), llvm::cl::init(false), llvm::cl::cat(Category)); static llvm::cl::opt<bool> PrintModule("print-module", llvm::cl::desc("Print module names in diagnostics"), llvm::cl::cat(Category)); static llvm::cl::opt<ActionType> Action(llvm::cl::desc("Mode:"), llvm::cl::init(ActionType::None), llvm::cl::cat(Category), llvm::cl::values( clEnumValN(ActionType::DumpSDK, "dump-sdk", "Dump SDK content to JSON file"), clEnumValN(ActionType::MigratorGen, "generate-migration-script", "Compare SDK content in JSON file and generate migration script"), clEnumValN(ActionType::DiagnoseSDKs, "diagnose-sdk", "Diagnose SDK content in JSON file"), clEnumValN(ActionType::DeserializeDiffItems, "deserialize-diff", "Deserialize diff items in a JSON file"), clEnumValN(ActionType::DeserializeSDK, "deserialize-sdk", "Deserialize sdk digester in a JSON file"), clEnumValN(ActionType::FindUsr, "find-usr", "Find USR for decls by given condition"), clEnumValN(ActionType::GenerateNameCorrectionTemplate, "generate-name-correction", "Generate name correction template"), clEnumValN(ActionType::GenerateEmptyBaseline, "generate-empty-baseline", "Generate an empty baseline"))); static llvm::cl::list<std::string> SDKJsonPaths("input-paths", llvm::cl::desc("The SDK contents under comparison"), llvm::cl::cat(Category)); static llvm::cl::list<std::string> ApisPrintUsrs("api-usrs", llvm::cl::desc("The name of APIs to print their usrs, " "e.g. Type::Function"), llvm::cl::cat(Category)); static llvm::cl::opt<std::string> IgnoreRemovedDeclUSRs("ignored-usrs", llvm::cl::desc("the file containing USRs of removed decls " "that the digester should ignore"), llvm::cl::cat(Category)); static llvm::cl::opt<std::string> SwiftVersion("swift-version", llvm::cl::desc("The Swift compiler version to invoke"), llvm::cl::cat(Category)); static llvm::cl::opt<bool> OutputInJson("json", llvm::cl::desc("Print output in JSON format."), llvm::cl::cat(Category)); static llvm::cl::opt<bool> AvoidLocation("avoid-location", llvm::cl::desc("Avoid serializing the file paths of SDK nodes."), llvm::cl::cat(Category)); static llvm::cl::opt<bool> AvoidToolArgs("avoid-tool-args", llvm::cl::desc("Avoid serializing the arguments for invoking the tool."), llvm::cl::cat(Category)); static llvm::cl::opt<std::string> LocationFilter("location", llvm::cl::desc("Filter nodes with the given location."), llvm::cl::cat(Category)); static llvm::cl::opt<bool> CompilerStyleDiags("compiler-style-diags", llvm::cl::desc("Print compiler style diagnostics to stderr."), llvm::cl::cat(Category)); static llvm::cl::opt<bool> Migrator("migrator", llvm::cl::desc("Dump Json suitable for generating migration script"), llvm::cl::cat(Category)); static llvm::cl::list<std::string> PreferInterfaceForModules("use-interface-for-module", llvm::cl::ZeroOrMore, llvm::cl::desc("Prefer loading these modules via interface"), llvm::cl::cat(Category)); static llvm::cl::opt<std::string> BaselineFilePath("baseline-path", llvm::cl::desc("The path to the Json file that we should use as the baseline"), llvm::cl::cat(Category)); static llvm::cl::opt<std::string> BaselineDirPath("baseline-dir", llvm::cl::desc("The path to a directory containing baseline files: macos.json, iphoneos.json, appletvos.json, watchos.json, and iosmac.json"), llvm::cl::cat(Category)); static llvm::cl::opt<bool> UseEmptyBaseline("empty-baseline", llvm::cl::desc("Use empty baseline for diagnostics"), llvm::cl::cat(Category)); static llvm::cl::opt<std::string> SerializedDiagPath("serialize-diagnostics-path", llvm::cl::desc("Serialize diagnostics to a path"), llvm::cl::cat(Category)); } // namespace options namespace { using swift::ide::api::KnownProtocolKind; // A node matcher will traverse two trees of SDKNode and find matched nodes struct NodeMatcher { virtual void match() = 0; virtual ~NodeMatcher() = default; }; // During the matching phase, any matched node will be reported using this API. // For update Node left = {Node before change} Right = {Node after change}; // For added Node left = {NilNode} Right = {Node after change}; // For removed Node left = {Node before change} Right = {NilNode} struct MatchedNodeListener { virtual void foundMatch(NodePtr Left, NodePtr Right, NodeMatchReason Reason) = 0; virtual ~MatchedNodeListener() = default; }; template<typename T> bool contains(std::vector<T*> &container, T *instance) { return std::find(container.begin(), container.end(), instance) != container.end(); } template<typename T> bool contains(ArrayRef<T> container, T instance) { return std::find(container.begin(), container.end(), instance) != container.end(); } static void singleMatch(SDKNode* Left, SDKNode *Right, MatchedNodeListener &Listener) { // Both null, be forgiving. if (!Left && !Right) return; // If both are valid and identical to each other, we don't need to match them. if (Left && Right && *Left == *Right) return; if (!Left || !Right) Listener.foundMatch(Left, Right, Left ? NodeMatchReason::Removed : NodeMatchReason::Added); else Listener.foundMatch(Left, Right, NodeMatchReason::Sequential); } // Given two NodeVector, this matches SDKNode by the order of their appearance // in the respective NodeVector. We use this in the order-sensitive cases, such // as parameters in a function decl. class SequentialNodeMatcher : public NodeMatcher { ArrayRef<SDKNode*> Left; ArrayRef<SDKNode*> Right; MatchedNodeListener &Listener; public: SequentialNodeMatcher(ArrayRef<SDKNode*> Left, ArrayRef<SDKNode*> Right, MatchedNodeListener &Listener) : Left(Left), Right(Right), Listener(Listener) {} void match() override { for (unsigned long i = 0; i < std::max(Left.size(), Right.size()); i ++) { auto L = i < Left.size() ? Left[i] : nullptr; auto R = i < Right.size() ? Right[i] : nullptr; singleMatch(L, R, Listener); } } }; struct NodeMatch { NodePtr Left; NodePtr Right; }; class BestMatchMatcher : public NodeMatcher { NodeVector &Left; NodeVector &Right; llvm::function_ref<bool(NodePtr, NodePtr)> CanMatch; llvm::function_ref<bool(NodeMatch, NodeMatch)> IsFirstMatchBetter; NodeMatchReason Reason; MatchedNodeListener &Listener; llvm::SmallPtrSet<NodePtr, 16> MatchedRight; bool internalCanMatch(NodePtr L, NodePtr R) { return MatchedRight.count(R) == 0 && CanMatch(L, R); } Optional<NodePtr> findBestMatch(NodePtr Pin, NodeVector& Candidates) { Optional<NodePtr> Best; for (auto Can : Candidates) { if (!internalCanMatch(Pin, Can)) continue; if (!Best.hasValue() || IsFirstMatchBetter({Pin, Can}, {Pin, Best.getValue()})) Best = Can; } return Best; } public: BestMatchMatcher(NodeVector &Left, NodeVector &Right, llvm::function_ref<bool(NodePtr, NodePtr)> CanMatch, llvm::function_ref<bool(NodeMatch, NodeMatch)> IsFirstMatchBetter, NodeMatchReason Reason, MatchedNodeListener &Listener) : Left(Left), Right(Right), CanMatch(CanMatch), IsFirstMatchBetter(IsFirstMatchBetter), Reason(Reason), Listener(Listener){} void match() override { for (auto L : Left) { if (auto Best = findBestMatch(L, Right)) { MatchedRight.insert(Best.getValue()); Listener.foundMatch(L, Best.getValue(), Reason); } } } }; class RemovedAddedNodeMatcher : public NodeMatcher, public MatchedNodeListener { NodeVector &Removed; NodeVector &Added; MatchedNodeListener &Listener; NodeVector RemovedMatched; NodeVector AddedMatched; void handleUnmatch(NodeVector &Matched, NodeVector &All, bool Left) { for (auto A : All) { if (contains(Matched, A)) continue; if (Left) Listener.foundMatch(A, nullptr, NodeMatchReason::Removed); else Listener.foundMatch(nullptr, A, NodeMatchReason::Added); } } bool detectFuncToProperty(SDKNode *R, SDKNode *A) { if (R->getKind() == SDKNodeKind::DeclFunction) { if (A->getKind() == SDKNodeKind::DeclVar) { if (A->getName().compare_lower(R->getName()) == 0) { R->annotate(NodeAnnotation::GetterToProperty); } else if (R->getName().startswith("get") && R->getName().substr(3).compare_lower(A->getName()) == 0) { R->annotate(NodeAnnotation::GetterToProperty); } else if (R->getName().startswith("set") && R->getName().substr(3).compare_lower(A->getName()) == 0) { R->annotate(NodeAnnotation::SetterToProperty); } else { return false; } R->annotate(NodeAnnotation::PropertyName, A->getPrintedName()); foundMatch(R, A, NodeMatchReason::FuncToProperty); return true; } } return false; } static bool isAnonymousEnum(SDKNodeDecl *N) { return N->getKind() == SDKNodeKind::DeclVar && N->getUsr().startswith("c:@Ea@"); } static bool isNominalEnum(SDKNodeDecl *N) { return N->getKind() == SDKNodeKind::DeclType && N->getUsr().startswith("c:@E@"); } static Optional<StringRef> getLastPartOfUsr(SDKNodeDecl *N) { auto LastPartIndex = N->getUsr().find_last_of('@'); if (LastPartIndex == StringRef::npos) return None; return N->getUsr().substr(LastPartIndex + 1); } bool detectTypeAliasChange(SDKNodeDecl *R, SDKNodeDecl *A) { if (R->getPrintedName() != A->getPrintedName()) return false; if (R->getKind() == SDKNodeKind::DeclType && A->getKind() == SDKNodeKind::DeclTypeAlias) { foundMatch(R, A, NodeMatchReason::TypeToTypeAlias); return true; } else { return false; } } bool detectModernizeEnum(SDKNodeDecl *R, SDKNodeDecl *A) { if (!isAnonymousEnum(R) || !isNominalEnum(A)) return false; auto LastPartOfR = getLastPartOfUsr(R); if (!LastPartOfR) return false; for (auto Child : A->getChildren()) { if (auto VC = dyn_cast<SDKNodeDeclVar>(Child)) { auto LastPartOfA = getLastPartOfUsr(VC); if (LastPartOfA && LastPartOfR.getValue() == LastPartOfA.getValue()) { std::string FullName = (llvm::Twine(A->getName()) + "." + Child->getName()).str(); R->annotate(NodeAnnotation::ModernizeEnum, R->getSDKContext().buffer(FullName)); foundMatch(R, A, NodeMatchReason::ModernizeEnum); return true; } } } return false; } bool detectSameAnonymousEnum(SDKNodeDecl *R, SDKNodeDecl *A) { if (!isAnonymousEnum(R) || !isAnonymousEnum(A)) return false; auto LastR = getLastPartOfUsr(R); auto LastA = getLastPartOfUsr(A); if (LastR && LastA && LastR.getValue() == LastA.getValue()) { foundMatch(R, A, NodeMatchReason::Name); return true; } return false; } static bool isNameTooSimple(StringRef N) { static std::vector<std::string> SimpleNames = {"unit", "data", "log", "coding", "url", "name", "date", "datecomponents", "notification", "urlrequest", "personnamecomponents", "measurement", "dateinterval", "indexset"}; return std::find(SimpleNames.begin(), SimpleNames.end(), N) != SimpleNames.end(); } static bool isSimilarName(StringRef L, StringRef R) { auto LL = L.lower(); auto RR = R.lower(); if (isNameTooSimple(LL) || isNameTooSimple(RR)) return false; if (((StringRef)LL).startswith(RR) || ((StringRef)RR).startswith(LL)) return true; if (((StringRef)LL).startswith((llvm::Twine("ns") + RR).str()) || ((StringRef)RR).startswith((llvm::Twine("ns") + LL).str())) return true; if (((StringRef)LL).endswith(RR) || ((StringRef)RR).endswith(LL)) return true; return false; } /// Whether two decls of different decl kinds can be considered as rename. static bool isDeclKindCrossable(DeclKind DK1, DeclKind DK2, bool First) { if (DK1 == DK2) return true; if (DK1 == DeclKind::Var && DK2 == DeclKind::EnumElement) return true; return First && isDeclKindCrossable(DK2, DK1, false); } static bool isRename(NodePtr L, NodePtr R) { if (L->getKind() != R->getKind()) return false; if (isa<SDKNodeDeclConstructor>(L)) return false; if (auto LD = dyn_cast<SDKNodeDecl>(L)) { auto *RD = R->getAs<SDKNodeDecl>(); return isDeclKindCrossable(LD->getDeclKind(), RD->getDeclKind(), true) && isSimilarName(LD->getName(), RD->getName()); } return false; } static bool isBetterMatch(NodeMatch Match1, NodeMatch Match2) { assert(Match1.Left == Match2.Left); auto Left = Match1.Left; auto *M1Right = Match1.Right->getAs<SDKNodeDecl>(); auto *M2Right = Match2.Right->getAs<SDKNodeDecl>(); // Consider non-deprecated nodes better matches. auto Dep1 = M1Right->isDeprecated(); auto Dep2 = M2Right->isDeprecated(); if (Dep1 ^ Dep2) { return Dep2; } // If two names are identical, measure whose printed names is closer. if (M1Right->getName() == M2Right->getName()) { return M1Right->getPrintedName().edit_distance(Left->getPrintedName()) < M2Right->getPrintedName().edit_distance(Left->getPrintedName()); } #define DIST(A, B) (std::max(A, B) - std::min(A, B)) return DIST(Left->getName().size(), Match1.Right->getName().size()) < DIST(Left->getName().size(), Match2.Right->getName().size()); #undef DIST } void foundMatch(NodePtr R, NodePtr A, NodeMatchReason Reason) override { Listener.foundMatch(R, A, Reason); RemovedMatched.push_back(R); AddedMatched.push_back(A); } public: RemovedAddedNodeMatcher(NodeVector &Removed, NodeVector &Added, MatchedNodeListener &Listener) : Removed(Removed), Added(Added), Listener(Listener) {} void match() override { auto IsDecl = [](NodePtr P) { return isa<SDKNodeDecl>(P); }; for (auto R : SDKNodeVectorViewer(Removed, IsDecl)) { for (auto A : SDKNodeVectorViewer(Added, IsDecl)) { auto RD = R->getAs<SDKNodeDecl>(); auto AD = A->getAs<SDKNodeDecl>(); if (detectFuncToProperty(RD, AD) || detectModernizeEnum(RD, AD) || detectSameAnonymousEnum(RD, AD) || detectTypeAliasChange(RD, AD)) { break; } } } // Rename detection starts. NodeVector RenameLeft; NodeVector RenameRight; for (auto Remain : Removed) { if (!contains(RemovedMatched, Remain)) RenameLeft.push_back(Remain); } for (auto Remain : Added) { if (!contains(AddedMatched, Remain)) RenameRight.push_back(Remain); } BestMatchMatcher RenameMatcher(RenameLeft, RenameRight, isRename, isBetterMatch, NodeMatchReason::Name, *this); RenameMatcher.match(); // Rename detection ends. handleUnmatch(RemovedMatched, Removed, true); handleUnmatch(AddedMatched, Added, false); } }; // Given two NodeVector, this matches SDKNode by the their names; only Nodes with // the identical names will be matched. We use this in name-sensitive but // order-insensitive cases, such as matching types in a module. class SameNameNodeMatcher : public NodeMatcher { ArrayRef<SDKNode*> Left; ArrayRef<SDKNode*> Right; MatchedNodeListener &Listener; enum class NameMatchKind { USR, PrintedName, PrintedNameAndUSR, }; static bool isUSRSame(SDKNode *L, SDKNode *R) { auto *LD = dyn_cast<SDKNodeDecl>(L); auto *RD = dyn_cast<SDKNodeDecl>(R); if (!LD || !RD) return false; return LD->getUsr() == RD->getUsr(); } // Given two SDK nodes, figure out the reason for why they have the same name. Optional<NameMatchKind> getNameMatchKind(SDKNode *L, SDKNode *R) { if (L->getKind() != R->getKind()) return None; auto NameEqual = L->getPrintedName() == R->getPrintedName(); auto UsrEqual = isUSRSame(L, R); if (NameEqual && UsrEqual) return NameMatchKind::PrintedNameAndUSR; else if (NameEqual) return NameMatchKind::PrintedName; else if (UsrEqual) return NameMatchKind::USR; else return None; } struct NameMatchCandidate { SDKNode *Node; NameMatchKind Kind; }; // Get the priority for the favored name match kind. Favored name match kind // locats before less favored ones. ArrayRef<NameMatchKind> getNameMatchKindPriority(SDKNodeKind Kind) { if (Kind == SDKNodeKind::DeclFunction) { static NameMatchKind FuncPriority[] = { NameMatchKind::PrintedNameAndUSR, NameMatchKind::USR, NameMatchKind::PrintedName }; return FuncPriority; } else { static NameMatchKind OtherPriority[] = { NameMatchKind::PrintedNameAndUSR, NameMatchKind::PrintedName, NameMatchKind::USR }; return OtherPriority; } } // Given a list and a priority, find the best matched candidate SDK node. SDKNode* findBestNameMatch(ArrayRef<NameMatchCandidate> Candidates, ArrayRef<NameMatchKind> Kinds) { for (auto Kind : Kinds) for (auto &Can : Candidates) if (Kind == Can.Kind) return Can.Node; return nullptr; } public: SameNameNodeMatcher(ArrayRef<SDKNode*> Left, ArrayRef<SDKNode*> Right, MatchedNodeListener &Listener) : Left(Left), Right(Right), Listener(Listener) {} void match() override ; }; void SameNameNodeMatcher::match() { NodeVector MatchedRight; NodeVector Removed; NodeVector Added; for (auto *LN : Left) { // This collects all the candidates that can match with LN. std::vector<NameMatchCandidate> Candidates; for (auto *RN : Right) { // If RN has matched before, ignore it. if (contains(MatchedRight, RN)) continue; // If LN and RN have the same name for some reason, keep track of RN. if (auto Kind = getNameMatchKind(LN, RN)) Candidates.push_back({RN, Kind.getValue()}); } // Try to find the best match among all the candidates by the priority name // match kind list. if (auto Match = findBestNameMatch(Candidates, getNameMatchKindPriority(LN->getKind()))) { Listener.foundMatch(LN, Match, NodeMatchReason::Name); MatchedRight.push_back(Match); } else { Removed.push_back(LN); } } for (auto &R : Right) { if (!contains(MatchedRight, R)) { Added.push_back(R); } } RemovedAddedNodeMatcher RAMatcher(Removed, Added, Listener); RAMatcher.match(); } // The recursive version of sequential matcher. We do not only match two vectors // of NodePtr but also their descendents. class SequentialRecursiveMatcher : public NodeMatcher { NodePtr &Left; NodePtr &Right; MatchedNodeListener &Listener; void matchInternal(NodePtr L, NodePtr R) { Listener.foundMatch(L, R, NodeMatchReason::Sequential); if (!L || !R) return; for (unsigned I = 0; I < std::max(L->getChildrenCount(), R->getChildrenCount()); ++ I) { auto Left = I < L->getChildrenCount() ? L->childAt(I) : nullptr; auto Right = I < R->getChildrenCount() ? R->childAt(I): nullptr; matchInternal(Left, Right); } } public: SequentialRecursiveMatcher(NodePtr &Left, NodePtr &Right, MatchedNodeListener &Listener) : Left(Left), Right(Right), Listener(Listener) {} void match() override { matchInternal(Left, Right); } }; // This is the interface of all passes on the given trees rooted at Left and Right. class SDKTreeDiffPass { public: virtual void pass(NodePtr Left, NodePtr Right) = 0; virtual ~SDKTreeDiffPass() {} }; static void detectRename(SDKNode *L, SDKNode *R) { if (L->getKind() == R->getKind() && isa<SDKNodeDecl>(L) && L->getPrintedName() != R->getPrintedName()) { L->annotate(NodeAnnotation::Rename); L->annotate(NodeAnnotation::RenameOldName, L->getPrintedName()); L->annotate(NodeAnnotation::RenameNewName, R->getPrintedName()); } } static bool isOwnershipEquivalent(ReferenceOwnership Left, ReferenceOwnership Right) { if (Left == Right) return true; if (Left == ReferenceOwnership::Unowned && Right == ReferenceOwnership::Weak) return true; if (Left == ReferenceOwnership::Weak && Right == ReferenceOwnership::Unowned) return true; return false; } }// End of anonymous namespace void swift::ide::api::SDKNodeDeclType::diagnose(SDKNode *Right) { SDKNodeDecl::diagnose(Right); auto *R = dyn_cast<SDKNodeDeclType>(Right); if (!R) return; auto Loc = R->getLoc(); if (getDeclKind() != R->getDeclKind()) { emitDiag(Loc, diag::decl_kind_changed, getDeclKindStr(R->getDeclKind())); return; } assert(getDeclKind() == R->getDeclKind()); auto DKind = getDeclKind(); switch (DKind) { case DeclKind::Class: { auto LSuperClass = getSuperClassName(); auto RSuperClass = R->getSuperClassName(); if (!LSuperClass.empty() && LSuperClass != RSuperClass) { if (RSuperClass.empty()) { emitDiag(Loc, diag::super_class_removed, LSuperClass); } else if (!contains(R->getClassInheritanceChain(), LSuperClass)) { emitDiag(Loc, diag::super_class_changed, LSuperClass, RSuperClass); } } // Check for @_hasMissingDesignatedInitializers and // @_inheritsConvenienceInitializers changes. if (isOpen() && R->isOpen()) { // It's not safe to add new, invisible designated inits to open // classes. if (!hasMissingDesignatedInitializers() && R->hasMissingDesignatedInitializers()) R->emitDiag(R->getLoc(), diag::added_invisible_designated_init); } // It's not safe to stop inheriting convenience inits, it changes // the set of initializers that are available. if (inheritsConvenienceInitializers() && !R->inheritsConvenienceInitializers()) R->emitDiag(R->getLoc(), diag::not_inheriting_convenience_inits); break; } default: break; } } void swift::ide::api::SDKNodeDeclAbstractFunc::diagnose(SDKNode *Right) { SDKNodeDecl::diagnose(Right); auto *R = dyn_cast<SDKNodeDeclAbstractFunc>(Right); if (!R) return; auto Loc = R->getLoc(); if (!isThrowing() && R->isThrowing()) { emitDiag(Loc, diag::decl_new_attr, Ctx.buffer("throwing")); } if (Ctx.checkingABI()) { if (reqNewWitnessTableEntry() != R->reqNewWitnessTableEntry()) { emitDiag(Loc, diag::decl_new_witness_table_entry, reqNewWitnessTableEntry()); } } } void swift::ide::api::SDKNodeDeclFunction::diagnose(SDKNode *Right) { SDKNodeDeclAbstractFunc::diagnose(Right); auto *R = dyn_cast<SDKNodeDeclFunction>(Right); if (!R) return; auto Loc = R->getLoc(); if (getSelfAccessKind() != R->getSelfAccessKind()) { emitDiag(Loc, diag::func_self_access_change, getSelfAccessKind(), R->getSelfAccessKind()); } if (Ctx.checkingABI()) { if (hasFixedBinaryOrder() != R->hasFixedBinaryOrder()) { emitDiag(Loc, diag::func_has_fixed_order_change, hasFixedBinaryOrder()); } } } static StringRef getAttrName(DeclAttrKind Kind) { switch (Kind) { #define DECL_ATTR(NAME, CLASS, ...) \ case DAK_##CLASS: \ return DeclAttribute::isDeclModifier(DAK_##CLASS) ? #NAME : "@"#NAME; #include "swift/AST/Attr.def" case DAK_Count: llvm_unreachable("unrecognized attribute kind."); } llvm_unreachable("covered switch"); } static bool shouldDiagnoseAddingAttribute(SDKNodeDecl *D, DeclAttrKind Kind) { return true; } static bool shouldDiagnoseRemovingAttribute(SDKNodeDecl *D, DeclAttrKind Kind) { return true; } void swift::ide::api::SDKNodeDecl::diagnose(SDKNode *Right) { SDKNode::diagnose(Right); auto *RD = dyn_cast<SDKNodeDecl>(Right); if (!RD) return; detectRename(this, RD); auto Loc = RD->getLoc(); if (isOpen() && !RD->isOpen()) { emitDiag(Loc, diag::no_longer_open); } // Diagnose static attribute change. if (isStatic() ^ RD->isStatic()) { emitDiag(Loc, diag::decl_new_attr, Ctx.buffer(isStatic() ? "not static" : "static")); } // Diagnose ownership change. if (!isOwnershipEquivalent(getReferenceOwnership(), RD->getReferenceOwnership())) { auto getOwnershipDescription = [&](swift::ReferenceOwnership O) { if (O == ReferenceOwnership::Strong) return Ctx.buffer("strong"); return keywordOf(O); }; emitDiag(Loc, diag::decl_attr_change, getOwnershipDescription(getReferenceOwnership()), getOwnershipDescription(RD->getReferenceOwnership())); } // Diagnose generic signature change if (getGenericSignature() != RD->getGenericSignature()) { // Prefer sugared signature in diagnostics to be more user-friendly. if (Ctx.commonVersionAtLeast(2) && getSugaredGenericSignature() != RD->getSugaredGenericSignature()) { emitDiag(Loc, diag::generic_sig_change, getSugaredGenericSignature(), RD->getSugaredGenericSignature()); } else { emitDiag(Loc, diag::generic_sig_change, getGenericSignature(), RD->getGenericSignature()); } } // ObjC name changes are considered breakage if (getObjCName() != RD->getObjCName()) { if (Ctx.commonVersionAtLeast(4)) { emitDiag(Loc, diag::objc_name_change, getObjCName(), RD->getObjCName()); } } if (isOptional() != RD->isOptional()) { if (Ctx.checkingABI()) { // Both adding/removing optional is ABI-breaking. emitDiag(Loc, diag::optional_req_changed, isOptional()); } else if (isOptional()) { // Removing optional is source-breaking. emitDiag(Loc, diag::optional_req_changed, isOptional()); } } // Diagnose removing attributes. for (auto Kind: getDeclAttributes()) { if (!RD->hasDeclAttribute(Kind)) { if ((Ctx.checkingABI() ? DeclAttribute::isRemovingBreakingABI(Kind) : DeclAttribute::isRemovingBreakingAPI(Kind)) && shouldDiagnoseRemovingAttribute(this, Kind)) { emitDiag(Loc, diag::decl_new_attr, Ctx.buffer((llvm::Twine("without ") + getAttrName(Kind)).str())); } } } // Diagnose adding attributes. for (auto Kind: RD->getDeclAttributes()) { if (!hasDeclAttribute(Kind)) { if ((Ctx.checkingABI() ? DeclAttribute::isAddingBreakingABI(Kind) : DeclAttribute::isAddingBreakingAPI(Kind)) && shouldDiagnoseAddingAttribute(this, Kind)) { emitDiag(Loc, diag::decl_new_attr, Ctx.buffer((llvm::Twine("with ") + getAttrName(Kind)).str())); } } } if (Ctx.checkingABI()) { if (hasFixedBinaryOrder() && RD->hasFixedBinaryOrder() && getFixedBinaryOrder() != RD->getFixedBinaryOrder()) { emitDiag(Loc, diag::decl_reorder, getFixedBinaryOrder(), RD->getFixedBinaryOrder()); } } } void swift::ide::api::SDKNodeDeclOperator::diagnose(SDKNode *Right) { SDKNodeDecl::diagnose(Right); auto *RO = dyn_cast<SDKNodeDeclOperator>(Right); if (!RO) return; auto Loc = RO->getLoc(); if (getDeclKind() != RO->getDeclKind()) { emitDiag(Loc, diag::decl_kind_changed, getDeclKindStr(RO->getDeclKind())); } } void swift::ide::api::SDKNodeDeclVar::diagnose(SDKNode *Right) { SDKNodeDecl::diagnose(Right); auto *RV = dyn_cast<SDKNodeDeclVar>(Right); if (!RV) return; auto Loc = RV->getLoc(); if (Ctx.checkingABI()) { if (hasFixedBinaryOrder() != RV->hasFixedBinaryOrder()) { emitDiag(Loc, diag::var_has_fixed_order_change, hasFixedBinaryOrder()); } } } static bool shouldDiagnoseType(SDKNodeType *T) { return T->isTopLevelType(); } void swift::ide::api::SDKNodeType::diagnose(SDKNode *Right) { SDKNode::diagnose(Right); auto *RT = dyn_cast<SDKNodeType>(Right); if (!RT || !shouldDiagnoseType(this)) return; assert(isTopLevelType()); // Diagnose type witness changes when diagnosing ABI breakages. if (auto *Wit = dyn_cast<SDKNodeTypeWitness>(getParent())) { auto *Conform = Wit->getParent()->getAs<SDKNodeConformance>(); if (Ctx.checkingABI() && getPrintedName() != RT->getPrintedName()) { auto *LD = Conform->getNominalTypeDecl(); LD->emitDiag(SourceLoc(), diag::type_witness_change, Wit->getWitnessedTypeName(), getPrintedName(), RT->getPrintedName()); } return; } StringRef Descriptor = getTypeRoleDescription(); assert(isa<SDKNodeDecl>(getParent())); auto LParent = cast<SDKNodeDecl>(getParent()); assert(LParent->getKind() == RT->getParent()->getAs<SDKNodeDecl>()->getKind()); auto Loc = RT->getParent()->getAs<SDKNodeDecl>()->getLoc(); if (getPrintedName() != RT->getPrintedName()) { LParent->emitDiag(Loc, diag::decl_type_change, Descriptor, getPrintedName(), RT->getPrintedName()); } if (hasDefaultArgument() && !RT->hasDefaultArgument()) { LParent->emitDiag(Loc, diag::default_arg_removed, Descriptor); } if (getParamValueOwnership() != RT->getParamValueOwnership()) { LParent->emitDiag(Loc, diag::param_ownership_change, getTypeRoleDescription(), getParamValueOwnership(), RT->getParamValueOwnership()); } } void swift::ide::api::SDKNodeTypeFunc::diagnose(SDKNode *Right) { SDKNodeType::diagnose(Right); auto *RT = dyn_cast<SDKNodeTypeFunc>(Right); if (!RT || !shouldDiagnoseType(this)) return; assert(isTopLevelType()); auto Loc = RT->getParent()->getAs<SDKNodeDecl>()->getLoc(); if (Ctx.checkingABI() && isEscaping() != RT->isEscaping()) { getParent()->getAs<SDKNodeDecl>()->emitDiag(Loc, diag::func_type_escaping_changed, getTypeRoleDescription(), isEscaping()); } } namespace { // This is first pass on two given SDKNode trees. This pass removes the common part // of two versions of SDK, leaving only the changed part. class PrunePass : public MatchedNodeListener, public SDKTreeDiffPass { static void removeCommon(NodeVector &Left, NodeVector &Right) { NodeVector LeftMinusRight, RightMinusLeft; nodeSetDifference(Left, Right, LeftMinusRight, RightMinusLeft); Left = LeftMinusRight; Right = RightMinusLeft; } static void removeCommonChildren(NodePtr Left, NodePtr Right) { removeCommon(Left->getChildren(), Right->getChildren()); } SDKContext &Ctx; UpdatedNodesMap &UpdateMap; llvm::StringSet<> ProtocolReqWhitelist; SDKNodeRoot *LeftRoot; SDKNodeRoot *RightRoot; static void printSpaces(llvm::raw_ostream &OS, SDKNode *N) { assert(N); StringRef Space = " "; // Accessor doesn't have parent. if (auto *AC = dyn_cast<SDKNodeDeclAccessor>(N)) { OS << Space; printSpaces(OS, AC->getStorage()); return; } for (auto P = N; !isa<SDKNodeRoot>(P); P = P->getParent()) OS << Space; } static void debugMatch(SDKNode *Left, SDKNode *Right, NodeMatchReason Reason, llvm::raw_ostream &OS) { if (Left && !isa<SDKNodeDecl>(Left)) return; if (Right && !isa<SDKNodeDecl>(Right)) return; StringRef Arrow = " <--------> "; switch (Reason) { case NodeMatchReason::Added: printSpaces(OS, Right); OS << "<NULL>" << Arrow << Right->getPrintedName() << "\n"; return; case NodeMatchReason::Removed: printSpaces(OS, Left); OS << Left->getPrintedName() << Arrow << "<NULL>\n"; return; default: printSpaces(OS, Left); OS << Left->getPrintedName() << Arrow << Right->getPrintedName() << "\n"; return; } } static StringRef getParentProtocolName(SDKNode *Node) { if (auto *Acc = dyn_cast<SDKNodeDeclAccessor>(Node)) { Node = Acc->getStorage(); } return Node->getParent()->getAs<SDKNodeDecl>()->getFullyQualifiedName(); } public: PrunePass(SDKContext &Ctx): Ctx(Ctx), UpdateMap(Ctx.getNodeUpdateMap()) {} PrunePass(SDKContext &Ctx, llvm::StringSet<> prWhitelist): Ctx(Ctx), UpdateMap(Ctx.getNodeUpdateMap()), ProtocolReqWhitelist(std::move(prWhitelist)) {} void diagnoseMissingAvailable(SDKNodeDecl *D) { // For extensions of external types, we diagnose individual member's missing // available attribute instead of the extension itself. // The reason is we may merge several extensions into a single one; some // attributes are missing. if (auto *DT = dyn_cast<SDKNodeDeclType>(D)) { if (DT->isExtension()) { for(auto MD: DT->getChildren()) { diagnoseMissingAvailable(cast<SDKNodeDecl>(MD)); } return; } } // Diagnose the missing of @available attributes. // Decls with @_alwaysEmitIntoClient aren't required to have an // @available attribute. if (!Ctx.getOpts().SkipOSCheck && DeclAttribute::canAttributeAppearOnDeclKind(DeclAttrKind::DAK_Available, D->getDeclKind()) && !D->getIntroducingVersion().hasOSAvailability() && !D->hasDeclAttribute(DeclAttrKind::DAK_AlwaysEmitIntoClient)) { D->emitDiag(D->getLoc(), diag::new_decl_without_intro); } } void foundMatch(NodePtr Left, NodePtr Right, NodeMatchReason Reason) override { if (options::DebugMapping) debugMatch(Left, Right, Reason, llvm::errs()); switch (Reason) { case NodeMatchReason::Added: assert(!Left); Right->annotate(NodeAnnotation::Added); if (Ctx.checkingABI()) { // Any order-important decl added to a non-resilient type breaks ABI. if (auto *D = dyn_cast<SDKNodeDecl>(Right)) { if (D->hasFixedBinaryOrder()) { D->emitDiag(D->getLoc(), diag::decl_added); } diagnoseMissingAvailable(D); } } // Complain about added protocol requirements if (auto *D = dyn_cast<SDKNodeDecl>(Right)) { if (D->isNonOptionalProtocolRequirement()) { bool ShouldComplain = !D->isOverriding(); // We should allow added associated types with default. if (auto ATD = dyn_cast<SDKNodeDeclAssociatedType>(D)) { if (ATD->getDefault()) ShouldComplain = false; } if (ShouldComplain && ProtocolReqWhitelist.count(getParentProtocolName(D))) { // Ignore protocol requirement additions if the protocol has been added // to the whitelist. ShouldComplain = false; } if (ShouldComplain) D->emitDiag(D->getLoc(), diag::protocol_req_added); } } // Diagnose an inherited protocol has been added. if (auto *Conf = dyn_cast<SDKNodeConformance>(Right)) { auto *TD = Conf->getNominalTypeDecl(); if (TD->isProtocol()) { TD->emitDiag(TD->getLoc(), diag::conformance_added, Conf->getName()); } else { // Adding conformance to an existing type can be ABI breaking. if (Ctx.checkingABI() && !LeftRoot->getDescendantsByUsr(Conf->getUsr()).empty()) { TD->emitDiag(TD->getLoc(), diag::existing_conformance_added, Conf->getName()); } } } if (auto *CD = dyn_cast<SDKNodeDeclConstructor>(Right)) { if (auto *TD = dyn_cast<SDKNodeDeclType>(Right->getParent())) { if (TD->isOpen() && CD->getInitKind() == CtorInitializerKind::Designated) { // If client's subclass provides an implementation of all of its superclass designated // initializers, it automatically inherits all of the superclass convenience initializers. // This means if a new designated init is added to the base class, the inherited // convenience init may be missing and cause breakage. CD->emitDiag(CD->getLoc(), diag::desig_init_added); } } } // Adding an enum case is source-breaking. if (!Ctx.checkingABI()) { if (auto *Var = dyn_cast<SDKNodeDeclVar>(Right)) { if (Var->getDeclKind() == DeclKind::EnumElement) { if (Var->getParent()->getAs<SDKNodeDeclType>()->isEnumExhaustive()) { Var->emitDiag(Var->getLoc(), diag::enum_case_added); } } } } return; case NodeMatchReason::Removed: assert(!Right); Left->annotate(NodeAnnotation::Removed); if (auto *LT = dyn_cast<SDKNodeType>(Left)) { if (auto *AT = dyn_cast<SDKNodeDeclAssociatedType>(LT->getParent())) { AT->emitDiag(SourceLoc(), diag::default_associated_type_removed, LT->getPrintedName()); } } // Diagnose a protocol conformance has been removed. if (auto *Conf = dyn_cast<SDKNodeConformance>(Left)) { auto *TD = Conf->getNominalTypeDecl(); TD->emitDiag(SourceLoc(), diag::conformance_removed, Conf->getName(), TD->isProtocol()); } if (auto *Acc = dyn_cast<SDKNodeDeclAccessor>(Left)) { Acc->emitDiag(SourceLoc(), diag::removed_decl, Acc->isDeprecated()); } return; case NodeMatchReason::FuncToProperty: case NodeMatchReason::ModernizeEnum: case NodeMatchReason::TypeToTypeAlias: Left->annotate(NodeAnnotation::Removed); Right->annotate(NodeAnnotation::Added); return; case NodeMatchReason::Root: case NodeMatchReason::Name: case NodeMatchReason::Sequential: break; } assert(Left && Right); Left->annotate(NodeAnnotation::Updated); Right->annotate(NodeAnnotation::Updated); // Push the updated node to the map for future reference. UpdateMap.insert(Left, Right); Left->diagnose(Right); if (Left->getKind() != Right->getKind()) { assert(isa<SDKNodeType>(Left) && isa<SDKNodeType>(Right) && "only type nodes can match across kinds."); return; } assert(Left->getKind() == Right->getKind()); SDKNodeKind Kind = Left->getKind(); assert(Kind == SDKNodeKind::Root || *Left != *Right); switch(Kind) { case SDKNodeKind::DeclType: { // Remove common conformances and diagnose conformance changes. auto LConf = cast<SDKNodeDeclType>(Left)->getConformances(); auto RConf = cast<SDKNodeDeclType>(Right)->getConformances(); removeCommon(LConf, RConf); SameNameNodeMatcher(LConf, RConf, *this).match(); LLVM_FALLTHROUGH; } case SDKNodeKind::Conformance: case SDKNodeKind::Root: { // If the matched nodes are both modules, remove the contained // type decls that are identical. If the matched nodes are both type decls, // remove the contained function decls that are identical. removeCommonChildren(Left, Right); SameNameNodeMatcher SNMatcher(Left->getChildren(), Right->getChildren(), *this); SNMatcher.match(); break; } case SDKNodeKind::TypeWitness: case SDKNodeKind::DeclOperator: case SDKNodeKind::DeclAssociatedType: case SDKNodeKind::DeclFunction: case SDKNodeKind::DeclAccessor: case SDKNodeKind::DeclConstructor: case SDKNodeKind::DeclTypeAlias: case SDKNodeKind::TypeFunc: case SDKNodeKind::TypeNominal: case SDKNodeKind::TypeAlias: { // If matched nodes are both function/var/TypeAlias decls, mapping their // parameters sequentially. SequentialNodeMatcher SNMatcher(Left->getChildren(), Right->getChildren(), *this); SNMatcher.match(); break; } case SDKNodeKind::DeclSubscript: { auto *LSub = dyn_cast<SDKNodeDeclSubscript>(Left); auto *RSub = dyn_cast<SDKNodeDeclSubscript>(Right); SequentialNodeMatcher(LSub->getChildren(), RSub->getChildren(), *this).match(); #define ACCESSOR(ID) \ singleMatch(LSub->getAccessor(AccessorKind::ID), \ RSub->getAccessor(AccessorKind::ID), *this); #include "swift/AST/AccessorKinds.def" break; } case SDKNodeKind::DeclVar: { auto *LVar = dyn_cast<SDKNodeDeclVar>(Left); auto *RVar = dyn_cast<SDKNodeDeclVar>(Right); // Match property type. singleMatch(LVar->getType(), RVar->getType(), *this); #define ACCESSOR(ID) \ singleMatch(LVar->getAccessor(AccessorKind::ID), \ RVar->getAccessor(AccessorKind::ID), *this); #include "swift/AST/AccessorKinds.def" break; } } } void pass(NodePtr Left, NodePtr Right) override { LeftRoot = Left->getAs<SDKNodeRoot>(); RightRoot = Right->getAs<SDKNodeRoot>(); foundMatch(Left, Right, NodeMatchReason::Root); } }; // Class to build up a diff of structurally different nodes, based on the given // USR map for the left (original) side of the diff, based on parent types. class TypeMemberDiffFinder : public SDKNodeVisitor { friend class SDKNode; // for visit() SDKNodeRoot *diffAgainst; // Vector of {givenNodePtr, diffAgainstPtr} NodePairVector TypeMemberDiffs; void visit(NodePtr node) override { // Skip nodes that we don't have a correlate for auto declNode = dyn_cast<SDKNodeDecl>(node); if (!declNode) return; auto usr = declNode->getUsr(); auto &usrName = usr; // If we can find no nodes in the other tree with the same usr, abort. auto candidates = diffAgainst->getDescendantsByUsr(usrName); if (candidates.empty()) return; // If any of the candidates has the same kind and name with the node, we // shouldn't continue. for (auto Can : candidates) { if (Can->getKind() == declNode->getKind() && Can->getAs<SDKNodeDecl>()->getFullyQualifiedName() == declNode->getFullyQualifiedName()) return; } auto diffNode = candidates.front(); assert(node && diffNode && "nullptr visited?"); auto nodeParent = node->getParent(); auto diffParent = diffNode->getParent(); assert(nodeParent && diffParent && "trying to check Root?"); // Move from global variable to a member variable. if (nodeParent->getKind() == SDKNodeKind::DeclType && diffParent->getKind() == SDKNodeKind::Root) TypeMemberDiffs.insert({diffNode, node}); // Move from a member variable to global variable. if (nodeParent->getKind() == SDKNodeKind::Root && diffParent->getKind() == SDKNodeKind::DeclType) TypeMemberDiffs.insert({diffNode, node}); // Move from a member variable to another member variable if (nodeParent->getKind() == SDKNodeKind::DeclType && diffParent->getKind() == SDKNodeKind::DeclType && declNode->isStatic()) TypeMemberDiffs.insert({diffNode, node}); // Move from a getter/setter function to a property else if (node->getKind() == SDKNodeKind::DeclAccessor && diffNode->getKind() == SDKNodeKind::DeclFunction && node->isNameValid()) { diffNode->annotate(NodeAnnotation::Rename); diffNode->annotate(NodeAnnotation::RenameOldName, diffNode->getPrintedName()); diffNode->annotate(NodeAnnotation::RenameNewName, node->getParent()->getPrintedName()); } } public: TypeMemberDiffFinder(SDKNodeRoot *diffAgainst): diffAgainst(diffAgainst) {} void findDiffsFor(NodePtr ptr) { SDKNode::preorderVisit(ptr, *this); } const NodePairVector &getDiffs() const { return TypeMemberDiffs; } void dump(llvm::raw_ostream &) const; void dump() const { dump(llvm::errs()); } private: TypeMemberDiffFinder(const TypeMemberDiffFinder &) = delete; TypeMemberDiffFinder &operator=(const TypeMemberDiffFinder &) = delete; }; /// This is to find type alias of raw types being changed to RawRepresentable. /// e.g. AttributeName was a typealias of String in the old SDK however it becomes /// a RawRepresentable struct in the new SDK. /// This happens typically when we use apinotes to preserve API stability by /// using SwiftWrapper:none in the old SDK. class TypeAliasDiffFinder: public SDKNodeVisitor { SDKNodeRoot *leftRoot; SDKNodeRoot *rightRoot; NodeMap &result; static bool checkTypeMatch(const SDKNodeType* aliasType, const SDKNodeType* rawType) { StringRef Left = aliasType->getPrintedName(); StringRef Right = rawType->getPrintedName(); if (Left == "NSString" && Right == "String") return true; if (Left == "String" && Right == "String") return true; if (Left == "Int" && Right == "Int") return true; if (Left == "UInt" && Right == "UInt") return true; return false; } void visit(NodePtr node) override { auto alias = dyn_cast<SDKNodeDeclTypeAlias>(node); if (!alias) return; const SDKNodeType* aliasType = alias->getUnderlyingType(); for (auto *counter: rightRoot->getDescendantsByUsr(alias->getUsr())) { if (auto DT = dyn_cast<SDKNodeDeclType>(counter)) { if (auto *rawType = DT->getRawValueType()) { if (checkTypeMatch(aliasType, rawType)) { result.insert({alias, DT}); return; } } } } } public: TypeAliasDiffFinder(SDKNodeRoot *leftRoot, SDKNodeRoot *rightRoot, NodeMap &result): leftRoot(leftRoot), rightRoot(rightRoot), result(result) {} void search() { SDKNode::preorderVisit(leftRoot, *this); } }; // Given a condition, search whether a node satisfies that condition exists // in a tree. class SearchVisitor : public SDKNodeVisitor { bool isFound = false; llvm::function_ref<bool(NodePtr)> Predicate; public: SearchVisitor(llvm::function_ref<bool(NodePtr)> Predicate) : Predicate(Predicate) {} void visit(NodePtr Node) override { isFound |= Predicate(Node); } bool search(NodePtr Node) { SDKNode::preorderVisit(Node, *this); return isFound; } }; class InterfaceTypeChangeDetector { bool IsVisitingLeft; #define ANNOTATE(Node, Counter, X, Y) \ auto ToAnnotate = IsVisitingLeft ? Node : Counter; \ ToAnnotate->annotate(IsVisitingLeft ? X : Y); bool detectWrapOptional(SDKNodeType *Node, SDKNodeType *Counter) { if (Node->getTypeKind() != KnownTypeKind::Optional && Node->getTypeKind() != KnownTypeKind::ImplicitlyUnwrappedOptional && Counter->getTypeKind() == KnownTypeKind::Optional && *Node == *Counter->getOnlyChild()) { ANNOTATE(Node, Counter, NodeAnnotation::WrapOptional, NodeAnnotation::UnwrapOptional) return true; } return false; } bool detectWrapImplicitOptional(SDKNodeType *Node, SDKNodeType *Counter) { if (Node->getTypeKind() != KnownTypeKind::Optional && Node->getTypeKind() != KnownTypeKind::ImplicitlyUnwrappedOptional && Counter->getTypeKind() == KnownTypeKind::ImplicitlyUnwrappedOptional && *Node == *Counter->getOnlyChild()) { ANNOTATE(Node, Counter, NodeAnnotation::WrapImplicitOptional, NodeAnnotation::UnwrapOptional) return true; } return false; } bool detectOptionalUpdate(SDKNodeType *Node, SDKNodeType *Counter) { if (Node->getTypeKind() == KnownTypeKind::Optional && Counter->getTypeKind() == KnownTypeKind::ImplicitlyUnwrappedOptional && *Node->getOnlyChild() == *Counter->getOnlyChild()) { ANNOTATE(Node, Counter, NodeAnnotation::OptionalToImplicitOptional, NodeAnnotation::ImplicitOptionalToOptional) return true; } return false; } bool detectUnmanagedUpdate(SDKNodeType *Node, SDKNodeType *Counter) { if (IsVisitingLeft && Node->getTypeKind() == KnownTypeKind::Unmanaged && Counter->getTypeKind() != KnownTypeKind::Unmanaged && *Node->getOnlyChild() == *Counter) { Node->annotate(NodeAnnotation::UnwrapUnmanaged); return true; } return false; } #undef ANNOTATE bool detectTypeRewritten(SDKNodeType *Node, SDKNodeType *Counter) { if (IsVisitingLeft && Node->getPrintedName() != Counter->getPrintedName() && (Node->getName() != Counter->getName() || Node->getChildrenCount() != Counter->getChildrenCount())) { Node->annotate(NodeAnnotation::TypeRewritten); Node->annotate(NodeAnnotation::TypeRewrittenLeft, Node->getPrintedName()); Node->annotate(NodeAnnotation::TypeRewrittenRight, Counter->getPrintedName()); return true; } return false; } static bool isRawType(const SDKNodeType *T, StringRef &Raw) { if (auto Alias = dyn_cast<SDKNodeTypeAlias>(T)) { // In case this type is an alias of the raw type. return isRawType(Alias->getUnderlyingType(), Raw); } switch(T->getTypeKind()) { case KnownTypeKind::String: case KnownTypeKind::Int: Raw = T->getName(); return true; default: return false; } } static StringRef getStringRepresentableChange(SDKNode *L, SDKNode *R, StringRef &Raw) { if (!isRawType(L->getAs<SDKNodeType>(), Raw)) return StringRef(); auto* RKey = dyn_cast<SDKNodeTypeNominal>(R); if (!RKey) return StringRef(); if (Raw.empty()) return StringRef(); auto Results = RKey->getRootNode()->getDescendantsByUsr(RKey->getUsr()); if (Results.empty()) return StringRef(); if (auto DT = dyn_cast<SDKNodeDeclType>(Results.front())) { if (DT->isConformingTo(KnownProtocolKind::RawRepresentable)) { return DT->getFullyQualifiedName(); } } return StringRef(); } static StringRef detectDictionaryKeyChangeInternal(SDKNodeType *L, SDKNodeType *R, StringRef &Raw) { if (L->getTypeKind() != KnownTypeKind::Dictionary || R->getTypeKind() != KnownTypeKind::Dictionary) return StringRef(); auto *Left = dyn_cast<SDKNodeTypeNominal>(L); auto *Right = dyn_cast<SDKNodeTypeNominal>(R); assert(Left && Right); assert(Left->getChildrenCount() == 2); assert(Right->getChildrenCount() == 2); return getStringRepresentableChange(*Left->getChildBegin(), *Right->getChildBegin(), Raw); } bool detectDictionaryKeyChange(SDKNodeType *L, SDKNodeType *R) { // We only care if this the top-level type node. if (!L->isTopLevelType() || !R->isTopLevelType()) return false; StringRef Raw; StringRef KeyChangedTo; bool HasOptional = L->getTypeKind() == KnownTypeKind::Optional && R->getTypeKind() == KnownTypeKind::Optional; if (HasOptional) { // Detect [String: Any]? to [StringRepresentableStruct: Any]? Chnage KeyChangedTo = detectDictionaryKeyChangeInternal(L->getOnlyChild()->getAs<SDKNodeType>(), R->getOnlyChild()->getAs<SDKNodeType>(), Raw); } else { // Detect [String: Any] to [StringRepresentableStruct: Any] Chnage KeyChangedTo = detectDictionaryKeyChangeInternal(L, R, Raw); } if (!KeyChangedTo.empty()) { if (IsVisitingLeft) { L->annotate(HasOptional ? NodeAnnotation::OptionalDictionaryKeyUpdate : NodeAnnotation::DictionaryKeyUpdate); L->annotate(NodeAnnotation::RawTypeLeft, Raw); L->annotate(NodeAnnotation::RawTypeRight, KeyChangedTo); } else { R->annotate(HasOptional ? NodeAnnotation::RevertOptionalDictionaryKeyUpdate : NodeAnnotation::RevertDictionaryKeyUpdate); R->annotate(NodeAnnotation::RawTypeLeft, KeyChangedTo); R->annotate(NodeAnnotation::RawTypeRight, Raw); } return true; } return false; } static StringRef detectArrayMemberChangeInternal(SDKNodeType *L, SDKNodeType *R, StringRef &Raw) { if (L->getTypeKind() != KnownTypeKind::Array || R->getTypeKind() != KnownTypeKind::Array) return StringRef(); auto *Left = dyn_cast<SDKNodeTypeNominal>(L); auto *Right = dyn_cast<SDKNodeTypeNominal>(R); assert(Left && Right); assert(Left->getChildrenCount() == 1); assert(Right->getChildrenCount() == 1); return getStringRepresentableChange(Left->getOnlyChild(), Right->getOnlyChild(), Raw); } bool detectArrayMemberChange(SDKNodeType* L, SDKNodeType *R) { // We only care if this the top-level type node. if (!L->isTopLevelType() || !R->isTopLevelType()) return false; StringRef Raw; StringRef KeyChangedTo; bool HasOptional = L->getTypeKind() == KnownTypeKind::Optional && R->getTypeKind() == KnownTypeKind::Optional; if (HasOptional) { // Detect [String]? to [StringRepresentableStruct]? Chnage KeyChangedTo = detectArrayMemberChangeInternal(L->getOnlyChild()->getAs<SDKNodeType>(), R->getOnlyChild()->getAs<SDKNodeType>(), Raw); } else { // Detect [String] to [StringRepresentableStruct] Chnage KeyChangedTo = detectArrayMemberChangeInternal(L, R, Raw); } if (!KeyChangedTo.empty()) { if (IsVisitingLeft) { L->annotate(HasOptional ? NodeAnnotation::OptionalArrayMemberUpdate : NodeAnnotation::ArrayMemberUpdate); L->annotate(NodeAnnotation::RawTypeLeft, Raw); L->annotate(NodeAnnotation::RawTypeRight, KeyChangedTo); } else { R->annotate(HasOptional ? NodeAnnotation::RevertOptionalArrayMemberUpdate : NodeAnnotation::RevertArrayMemberUpdate); R->annotate(NodeAnnotation::RawTypeLeft, KeyChangedTo); R->annotate(NodeAnnotation::RawTypeRight, Raw); } return true; } return false; } bool detectSimpleStringRepresentableUpdate(SDKNodeType *L, SDKNodeType *R) { if (!L->isTopLevelType() || !R->isTopLevelType()) return false; StringRef KeyChangedTo; StringRef Raw; bool HasOptional = L->getTypeKind() == KnownTypeKind::Optional && R->getTypeKind() == KnownTypeKind::Optional; if (HasOptional) { // Detect String? changes to StringRepresentableStruct? change. KeyChangedTo = getStringRepresentableChange(L->getOnlyChild()->getAs<SDKNodeType>(), R->getOnlyChild()->getAs<SDKNodeType>(), Raw); } else { // Detect String changes to StringRepresentableStruct change. KeyChangedTo = getStringRepresentableChange(L, R, Raw); } if (!KeyChangedTo.empty()) { if (IsVisitingLeft) { L->annotate(NodeAnnotation::RawTypeLeft, Raw); L->annotate(NodeAnnotation::RawTypeRight, KeyChangedTo); L->annotate(HasOptional ? NodeAnnotation::SimpleOptionalStringRepresentableUpdate: NodeAnnotation::SimpleStringRepresentableUpdate); } else { R->annotate(NodeAnnotation::RawTypeLeft, KeyChangedTo); R->annotate(NodeAnnotation::RawTypeRight, Raw); R->annotate(HasOptional ? NodeAnnotation::RevertSimpleOptionalStringRepresentableUpdate: NodeAnnotation::RevertSimpleStringRepresentableUpdate); } return true; } return false; } bool isUnhandledCase(SDKNodeType *Node, SDKNodeType *Counter) { return Node->getTypeKind() == KnownTypeKind::Void || Counter->getTypeKind() == KnownTypeKind::Void; } static void clearTypeRewritten(SDKNode *N) { if (!N->isAnnotatedAs(NodeAnnotation::TypeRewritten)) return; N->removeAnnotate(NodeAnnotation::TypeRewritten); N->removeAnnotate(NodeAnnotation::TypeRewrittenLeft); N->removeAnnotate(NodeAnnotation::TypeRewrittenRight); } public: InterfaceTypeChangeDetector(bool IsVisitingLeft): IsVisitingLeft(IsVisitingLeft) {} void detect(SDKNode *Left, SDKNode *Right) { auto *Node = dyn_cast<SDKNodeType>(Left); auto *Counter = dyn_cast<SDKNodeType>(Right); if (!Node || !Counter || isUnhandledCase(Node, Counter)) return; if (detectWrapOptional(Node, Counter) || detectOptionalUpdate(Node, Counter) || detectWrapImplicitOptional(Node, Counter) || detectUnmanagedUpdate(Node, Counter)) { // we may have detected type rewritten before (when visiting left), // so clear the annotation here. clearTypeRewritten(Node); clearTypeRewritten(Counter); } else { // Detect type re-written then. detectTypeRewritten(Node, Counter); } // The raw representable changes can co-exist with above attributes. auto Result = detectDictionaryKeyChange(Node, Counter) || detectArrayMemberChange(Node, Counter) || detectSimpleStringRepresentableUpdate(Node, Counter); (void) Result; return; } }; class ChangeRefinementPass : public SDKTreeDiffPass, public SDKNodeVisitor { UpdatedNodesMap &UpdateMap; InterfaceTypeChangeDetector LeftDetector; InterfaceTypeChangeDetector RightDetector; InterfaceTypeChangeDetector *Detector; public: ChangeRefinementPass(UpdatedNodesMap &UpdateMap) : UpdateMap(UpdateMap), LeftDetector(true), RightDetector(false), Detector(nullptr) {} void pass(NodePtr Left, NodePtr Right) override { // Post-order visit is necessary since we propagate annotations bottom-up Detector = &LeftDetector; SDKNode::postorderVisit(Left, *this); Detector = &RightDetector; SDKNode::postorderVisit(Right, *this); } void visit(NodePtr Node) override { assert(Detector); if (!Node || !Node->isAnnotatedAs(NodeAnnotation::Updated)) return; auto *Counter = UpdateMap.findUpdateCounterpart(Node); Detector->detect(Node, Counter); return; } }; } // end anonymous namespace static void findTypeMemberDiffs(NodePtr leftSDKRoot, NodePtr rightSDKRoot, TypeMemberDiffVector &out); static void printNode(llvm::raw_ostream &os, NodePtr node) { os << "{" << node->getName() << " " << node->getKind() << " " << node->getPrintedName(); if (auto F = dyn_cast<SDKNodeDeclAbstractFunc>(node)) { if (F->hasSelfIndex()) { os << " selfIndex: "; os << F->getSelfIndex(); } } os << "}"; } void TypeMemberDiffFinder::dump(llvm::raw_ostream &os) const { for (auto pair : getDiffs()) { os << " - "; printNode(os, pair.first); os << " parent: "; printNode(os, pair.first->getParent()); os << "\n + "; printNode(os, pair.second); os << " parent: "; printNode(os, pair.second->getParent()); os << "\n\n"; } } namespace { template<typename T> void removeRedundantAndSort(std::vector<T> &Diffs) { std::set<T> DiffSet(Diffs.begin(), Diffs.end()); Diffs.assign(DiffSet.begin(), DiffSet.end()); std::sort(Diffs.begin(), Diffs.end()); } template<typename T> void serializeDiffs(llvm::raw_ostream &Fs, std::vector<T> &Diffs) { if (Diffs.empty()) return; Fs << "\n"; T::describe(Fs); for (auto &Diff : Diffs) { Diff.streamDef(Fs); Fs << "\n"; } T::undef(Fs); Fs << "\n"; } static bool isTypeChangeInterestedFuncNode(NodePtr Decl) { switch(Decl->getKind()) { case SDKNodeKind::DeclConstructor: case SDKNodeKind::DeclFunction: return true; default: return false; } } class DiffItemEmitter : public SDKNodeVisitor { DiffVector &AllItems; static bool isInterested(SDKNodeDecl* Decl, NodeAnnotation Anno) { switch (Anno) { case NodeAnnotation::WrapOptional: case NodeAnnotation::UnwrapOptional: case NodeAnnotation::ImplicitOptionalToOptional: case NodeAnnotation::OptionalToImplicitOptional: case NodeAnnotation::UnwrapUnmanaged: case NodeAnnotation::TypeRewritten: return isTypeChangeInterestedFuncNode(Decl) && Decl->getParent()->getKind() == SDKNodeKind::DeclType; default: return true; } } bool doesAncestorHaveTypeRewritten() { return std::find_if(Ancestors.begin(), Ancestors.end(),[](NodePtr N) { return N->isAnnotatedAs(NodeAnnotation::TypeRewritten); }) != Ancestors.end(); } static StringRef getLeftComment(NodePtr Node, NodeAnnotation Anno) { switch(Anno) { case NodeAnnotation::ArrayMemberUpdate: case NodeAnnotation::OptionalArrayMemberUpdate: case NodeAnnotation::DictionaryKeyUpdate: case NodeAnnotation::OptionalDictionaryKeyUpdate: case NodeAnnotation::SimpleStringRepresentableUpdate: case NodeAnnotation::SimpleOptionalStringRepresentableUpdate: case NodeAnnotation::RevertArrayMemberUpdate: case NodeAnnotation::RevertOptionalArrayMemberUpdate: case NodeAnnotation::RevertDictionaryKeyUpdate: case NodeAnnotation::RevertOptionalDictionaryKeyUpdate: case NodeAnnotation::RevertSimpleStringRepresentableUpdate: case NodeAnnotation::RevertSimpleOptionalStringRepresentableUpdate: return Node->getAnnotateComment(NodeAnnotation::RawTypeLeft); case NodeAnnotation::TypeRewritten: return Node->getAnnotateComment(NodeAnnotation::TypeRewrittenLeft); case NodeAnnotation::Rename: return Node->getAnnotateComment(NodeAnnotation::RenameOldName); default: return StringRef(); } } static StringRef getRightComment(NodePtr Node, NodeAnnotation Anno) { switch (Anno) { case NodeAnnotation::ArrayMemberUpdate: case NodeAnnotation::OptionalArrayMemberUpdate: case NodeAnnotation::DictionaryKeyUpdate: case NodeAnnotation::OptionalDictionaryKeyUpdate: case NodeAnnotation::SimpleStringRepresentableUpdate: case NodeAnnotation::SimpleOptionalStringRepresentableUpdate: case NodeAnnotation::RevertArrayMemberUpdate: case NodeAnnotation::RevertOptionalArrayMemberUpdate: case NodeAnnotation::RevertDictionaryKeyUpdate: case NodeAnnotation::RevertOptionalDictionaryKeyUpdate: case NodeAnnotation::RevertSimpleStringRepresentableUpdate: case NodeAnnotation::RevertSimpleOptionalStringRepresentableUpdate: return Node->getAnnotateComment(NodeAnnotation::RawTypeRight); case NodeAnnotation::TypeRewritten: return Node->getAnnotateComment(NodeAnnotation::TypeRewrittenRight); case NodeAnnotation::ModernizeEnum: return Node->getAnnotateComment(NodeAnnotation::ModernizeEnum); case NodeAnnotation::Rename: return Node->getAnnotateComment(NodeAnnotation::RenameNewName); case NodeAnnotation::GetterToProperty: case NodeAnnotation::SetterToProperty: return Node->getAnnotateComment(NodeAnnotation::PropertyName); default: return StringRef(); } } void handleAnnotations(NodePtr Node, SDKNodeDecl *NonTypeParent, StringRef Index, ArrayRef<NodeAnnotation> Annotations) { for (auto Anno: Annotations) { if (isInterested(NonTypeParent, Anno) && Node->isAnnotatedAs(Anno)) { auto Kind = NonTypeParent->getKind(); StringRef LC = getLeftComment(Node, Anno); StringRef RC = getRightComment(Node, Anno); AllItems.emplace_back(Kind, Anno, Index, NonTypeParent->getUsr(), StringRef(), LC, RC, NonTypeParent->getModuleName()); } } } void visit(NodePtr Node) override { auto *Parent = dyn_cast<SDKNodeDecl>(Node); if (!Parent) { if (auto TN = dyn_cast<SDKNodeType>(Node)) { Parent = TN->getClosestParentDecl(); } } if (!Parent) return; if (doesAncestorHaveTypeRewritten()) return; handleAnnotations(Node, Parent, isa<SDKNodeType>(Node) ? getIndexString(Node) : "0", { #define NODE_ANNOTATION_CHANGE_KIND(NAME) NodeAnnotation::NAME, #include "swift/IDE/DigesterEnums.def" }); } StringRef getIndexString(NodePtr Node) { llvm::SmallString<32> Builder; std::vector<int> Indexes; collectIndexes(Node, Indexes); auto First = true; for (auto I : Indexes) { if (!First) Builder.append(":"); else First = false; Builder.append(std::to_string(I)); } return Node->getSDKContext().buffer(Builder.str()); } void collectIndexes(NodePtr Node, std::vector<int> &Indexes) { for (unsigned I = Ancestors.size(); I > 0 && (I == Ancestors.size() || isa<SDKNodeType>(Ancestors[I])); -- I) { auto Child = I == Ancestors.size() ? Node : Ancestors[I]; auto Parent = Ancestors[I - 1]; Indexes.insert(Indexes.begin(), Parent->getChildIndex(Child)); } } DiffItemEmitter(DiffVector &AllItems) : AllItems(AllItems) {} public: static void collectDiffItems(NodePtr Root, DiffVector &DV) { DiffItemEmitter Emitter(DV); SDKNode::postorderVisit(Root, Emitter); } }; class DiagnosisEmitter : public SDKNodeVisitor { void handle(const SDKNodeDecl *D, NodeAnnotation Anno); void visitDecl(SDKNodeDecl *D); void visit(NodePtr Node) override; SDKNodeDecl *findAddedDecl(const SDKNodeDecl *Node); bool findTypeAliasDecl(const SDKNodeDecl *Node); static void collectAddedDecls(NodePtr Root, std::set<SDKNodeDecl*> &Results); std::set<SDKNodeDecl*> AddedDecls; UpdatedNodesMap &UpdateMap; NodeMap &TypeAliasUpdateMap; TypeMemberDiffVector &MemberChanges; DiagnosisEmitter(SDKContext &Ctx): UpdateMap(Ctx.getNodeUpdateMap()), TypeAliasUpdateMap(Ctx.getTypeAliasUpdateMap()), MemberChanges(Ctx.getTypeMemberDiffs()) {} public: static void diagnosis(NodePtr LeftRoot, NodePtr RightRoot, SDKContext &Ctx); }; void DiagnosisEmitter::collectAddedDecls(NodePtr Root, std::set<SDKNodeDecl*> &Results) { if (auto *D = dyn_cast<SDKNodeDecl>(Root)) { if (Root->isAnnotatedAs(NodeAnnotation::Added)) Results.insert(D); } for (auto &C : Root->getChildren()) collectAddedDecls(C, Results); } SDKNodeDecl *DiagnosisEmitter::findAddedDecl(const SDKNodeDecl *Root) { for (auto *Added : AddedDecls) { if (Root->getKind() == Added->getKind() && Root->getPrintedName() == Added->getPrintedName() && Root->getUsr() == Added->getUsr()) return Added; } return nullptr; } bool DiagnosisEmitter::findTypeAliasDecl(const SDKNodeDecl *Node) { if (Node->getKind() != SDKNodeKind::DeclType) return false; return std::any_of(AddedDecls.begin(), AddedDecls.end(), [&](SDKNodeDecl *Added) { return Added->getKind() == SDKNodeKind::DeclTypeAlias && Added->getPrintedName() == Node->getPrintedName(); }); } void DiagnosisEmitter::diagnosis(NodePtr LeftRoot, NodePtr RightRoot, SDKContext &Ctx) { DiagnosisEmitter Emitter(Ctx); collectAddedDecls(RightRoot, Emitter.AddedDecls); SDKNode::postorderVisit(LeftRoot, Emitter); } static bool diagnoseRemovedExtensionMembers(const SDKNode *Node) { // If the removed decl is an extension, diagnose each member as being removed rather than // the extension itself has been removed. if (auto *DT= dyn_cast<SDKNodeDeclType>(Node)) { if (DT->isExtension()) { for (auto *C: DT->getChildren()) { auto *MD = cast<SDKNodeDecl>(C); MD->emitDiag(SourceLoc(), diag::removed_decl, MD->isDeprecated()); } return true; } } return false; } void DiagnosisEmitter::handle(const SDKNodeDecl *Node, NodeAnnotation Anno) { assert(Node->isAnnotatedAs(Anno)); auto &Ctx = Node->getSDKContext(); switch(Anno) { case NodeAnnotation::Removed: { // If we can find a type alias decl with the same name of this type, we // consider the type is not removed. if (findTypeAliasDecl(Node)) return; if (auto *Added = findAddedDecl(Node)) { if (Node->getDeclKind() != DeclKind::Constructor) { Node->emitDiag(Added->getLoc(), diag::moved_decl, Ctx.buffer((Twine(getDeclKindStr(Added->getDeclKind())) + " " + Added->getFullyQualifiedName()).str())); return; } } // If we can find a hoisted member for this removed delcaration, we // emit the diagnostics as rename instead of removal. auto It = std::find_if(MemberChanges.begin(), MemberChanges.end(), [&](TypeMemberDiffItem &Item) { return Item.usr == Node->getUsr(); }); if (It != MemberChanges.end()) { Node->emitDiag(SourceLoc(), diag::renamed_decl, Ctx.buffer((Twine(getDeclKindStr(Node->getDeclKind())) + " " + It->newTypeName + "." + It->newPrintedName).str())); return; } // If a type alias of a raw type has been changed to a struct/enum that // conforms to RawRepresentable in the later version of SDK, we show the // refine diagnostics message instead of showing the type alias has been // removed. if (TypeAliasUpdateMap.find((SDKNode*)Node) != TypeAliasUpdateMap.end()) { Node->emitDiag(SourceLoc(), diag::raw_type_change, Node->getAs<SDKNodeDeclTypeAlias>()->getUnderlyingType()->getPrintedName(), TypeAliasUpdateMap[(SDKNode*)Node]->getAs<SDKNodeDeclType>()-> getRawValueType()->getPrintedName()); return; } // We should exlude those declarations that are pulled up to the super classes. bool FoundInSuperclass = false; if (auto PD = dyn_cast<SDKNodeDecl>(Node->getParent())) { if (PD->isAnnotatedAs(NodeAnnotation::Updated)) { // Get the updated counterpart of the parent decl. if (auto RTD = dyn_cast<SDKNodeDeclType>(UpdateMap. findUpdateCounterpart(PD))) { // Look up by the printed name in the counterpart. FoundInSuperclass = RTD->lookupChildByPrintedName(Node->getPrintedName()).hasValue(); } } } if (FoundInSuperclass) return; // When diagnosing API changes, avoid complaining the removal of these // synthesized functions since they are compiler implementation details. // If an enum is no longer equatable, another diagnostic about removing // conforming protocol will be emitted. if (!Ctx.checkingABI()) { if (Node->getName() == Ctx.Id_derived_struct_equals || Node->getName() == Ctx.Id_derived_enum_equals) { return; } } bool handled = diagnoseRemovedExtensionMembers(Node); if (!handled) Node->emitDiag(SourceLoc(), diag::removed_decl, Node->isDeprecated()); return; } case NodeAnnotation::Rename: { SourceLoc DiagLoc; // Try to get the source location from the later version of this node // via UpdateMap. if (auto CD = dyn_cast_or_null<SDKNodeDecl>(UpdateMap .findUpdateCounterpart(Node))) { DiagLoc = CD->getLoc(); } Node->emitDiag(DiagLoc, diag::renamed_decl, Ctx.buffer((Twine(getDeclKindStr(Node->getDeclKind())) + " " + Node->getAnnotateComment(NodeAnnotation::RenameNewName)).str())); return; } default: return; } } void DiagnosisEmitter::visitDecl(SDKNodeDecl *Node) { std::vector<NodeAnnotation> Scratch; for (auto Anno : Node->getAnnotations(Scratch)) handle(Node, Anno); } void DiagnosisEmitter::visit(NodePtr Node) { if (auto *DNode = dyn_cast<SDKNodeDecl>(Node)) { visitDecl(DNode); } } typedef std::vector<NoEscapeFuncParam> NoEscapeFuncParamVector; class NoEscapingFuncEmitter : public SDKNodeVisitor { NoEscapeFuncParamVector &AllItems; NoEscapingFuncEmitter(NoEscapeFuncParamVector &AllItems) : AllItems(AllItems) {} void visit(NodePtr Node) override { if (Node->getKind() != SDKNodeKind::TypeFunc) return; if (Node->getAs<SDKNodeTypeFunc>()->isEscaping()) return; auto Parent = Node->getParent(); if (auto ParentFunc = dyn_cast<SDKNodeDeclAbstractFunc>(Parent)) { if (ParentFunc->isObjc()) { unsigned Index = ParentFunc->getChildIndex(Node); AllItems.emplace_back(ParentFunc->getUsr(), Index); } } } public: static void collectDiffItems(NodePtr Root, NoEscapeFuncParamVector &DV) { NoEscapingFuncEmitter Emitter(DV); SDKNode::postorderVisit(Root, Emitter); } }; } // end anonymous namespace namespace fs = llvm::sys::fs; namespace path = llvm::sys::path; class RenameDetectorForMemberDiff : public MatchedNodeListener { InterfaceTypeChangeDetector LeftDetector; InterfaceTypeChangeDetector RightDetector; public: RenameDetectorForMemberDiff(): LeftDetector(true), RightDetector(false) {} void foundMatch(NodePtr Left, NodePtr Right, NodeMatchReason Reason) override { if (!Left || !Right) return; detectRename(Left, Right); LeftDetector.detect(Left, Right); RightDetector.detect(Right, Left); } void workOn(NodePtr Left, NodePtr Right) { if (Left->getKind() == Right->getKind() && Left->getKind() == SDKNodeKind::DeclType) { SameNameNodeMatcher SNMatcher(Left->getChildren(), Right->getChildren(), *this); SNMatcher.match(); } if (Left->getKind() == Right->getKind() && Left->getKind() == SDKNodeKind::DeclVar) { SequentialNodeMatcher Matcher(Left->getChildren(), Right->getChildren(), *this); Matcher.match(); } } }; static Optional<uint8_t> findSelfIndex(SDKNode* Node) { if (auto func = dyn_cast<SDKNodeDeclAbstractFunc>(Node)) { return func->getSelfIndexOptional(); } else if (auto vd = dyn_cast<SDKNodeDeclVar>(Node)) { for (auto &C : vd->getChildren()) { if (isa<SDKNodeDeclAbstractFunc>(C)) { if (auto Result = findSelfIndex(C)) return Result; } } } return None; } /// Find cases where a diff is due to a change to being a type member static void findTypeMemberDiffs(NodePtr leftSDKRoot, NodePtr rightSDKRoot, TypeMemberDiffVector &out) { TypeMemberDiffFinder diffFinder(cast<SDKNodeRoot>(leftSDKRoot)); diffFinder.findDiffsFor(rightSDKRoot); RenameDetectorForMemberDiff Detector; for (auto pair : diffFinder.getDiffs()) { auto left = pair.first; auto leftParent = left->getParent(); auto right = pair.second; auto rightParent = right->getParent(); // SDK_CHANGE_TYPE_MEMBER(USR, new type context name, new printed name, self // index, old printed name) TypeMemberDiffItem item = { right->getAs<SDKNodeDecl>()->getUsr(), rightParent->getKind() == SDKNodeKind::Root ? StringRef() : rightParent->getAs<SDKNodeDecl>()->getFullyQualifiedName(), right->getPrintedName(), findSelfIndex(right), None, leftParent->getKind() == SDKNodeKind::Root ? StringRef() : leftParent->getAs<SDKNodeDecl>()->getFullyQualifiedName(), left->getPrintedName() }; out.emplace_back(item); Detector.workOn(left, right); } } static std::unique_ptr<DiagnosticConsumer> createDiagConsumer(llvm::raw_ostream &OS, bool &FailOnError) { if (!options::SerializedDiagPath.empty()) { FailOnError = true; return serialized_diagnostics::createConsumer(options::SerializedDiagPath); } else if (options::CompilerStyleDiags) { FailOnError = true; return std::make_unique<PrintingDiagnosticConsumer>(); } else { FailOnError = false; return std::make_unique<ModuleDifferDiagsConsumer>(true, OS); } } static int diagnoseModuleChange(SDKContext &Ctx, SDKNodeRoot *LeftModule, SDKNodeRoot *RightModule, StringRef OutputPath, llvm::StringSet<> ProtocolReqWhitelist) { assert(LeftModule); assert(RightModule); llvm::raw_ostream *OS = &llvm::errs(); if (!LeftModule || !RightModule) { *OS << "Cannot diagnose null SDKNodeRoot"; exit(1); } std::unique_ptr<llvm::raw_ostream> FileOS; if (!OutputPath.empty()) { std::error_code EC; FileOS.reset(new llvm::raw_fd_ostream(OutputPath, EC, llvm::sys::fs::F_None)); OS = FileOS.get(); } bool FailOnError; std::unique_ptr<DiagnosticConsumer> pConsumer = createDiagConsumer(*OS, FailOnError); Ctx.addDiagConsumer(*pConsumer); Ctx.setCommonVersion(std::min(LeftModule->getJsonFormatVersion(), RightModule->getJsonFormatVersion())); TypeAliasDiffFinder(LeftModule, RightModule, Ctx.getTypeAliasUpdateMap()).search(); PrunePass Prune(Ctx, std::move(ProtocolReqWhitelist)); Prune.pass(LeftModule, RightModule); ChangeRefinementPass RefinementPass(Ctx.getNodeUpdateMap()); RefinementPass.pass(LeftModule, RightModule); // Find member hoist changes to help refine diagnostics. findTypeMemberDiffs(LeftModule, RightModule, Ctx.getTypeMemberDiffs()); DiagnosisEmitter::diagnosis(LeftModule, RightModule, Ctx); return FailOnError && Ctx.getDiags().hadAnyError() ? 1 : 0; } static int diagnoseModuleChange(StringRef LeftPath, StringRef RightPath, StringRef OutputPath, CheckerOptions Opts, llvm::StringSet<> ProtocolReqWhitelist) { if (!fs::exists(LeftPath)) { llvm::errs() << LeftPath << " does not exist\n"; return 1; } if (!fs::exists(RightPath)) { llvm::errs() << RightPath << " does not exist\n"; return 1; } SDKContext Ctx(Opts); SwiftDeclCollector LeftCollector(Ctx); LeftCollector.deSerialize(LeftPath); SwiftDeclCollector RightCollector(Ctx); RightCollector.deSerialize(RightPath); diagnoseModuleChange(Ctx, LeftCollector.getSDKRoot(), RightCollector.getSDKRoot(), OutputPath, std::move(ProtocolReqWhitelist)); return options::CompilerStyleDiags && Ctx.getDiags().hadAnyError() ? 1 : 0; } static void populateAliasChanges(NodeMap &AliasMap, DiffVector &AllItems, const bool isRevert) { for (auto Pair: AliasMap) { auto UnderlyingType = Pair.first->getAs<SDKNodeDeclTypeAlias>()-> getUnderlyingType()->getPrintedName(); auto RawType = AliasMap[(SDKNode*)Pair.first]->getAs<SDKNodeDeclType>()-> getRawValueType()->getPrintedName(); if (isRevert) { auto *D = Pair.second->getAs<SDKNodeDecl>(); AllItems.emplace_back(SDKNodeKind::DeclType, NodeAnnotation::RevertTypeAliasDeclToRawRepresentable, "0", D->getUsr(), "", RawType, UnderlyingType, D->getModuleName()); } else { auto *D = Pair.first->getAs<SDKNodeDecl>(); AllItems.emplace_back(SDKNodeKind::DeclTypeAlias, NodeAnnotation::TypeAliasDeclToRawRepresentable, "0", D->getUsr(), "", UnderlyingType, RawType, D->getModuleName()); } } } static int generateMigrationScript(StringRef LeftPath, StringRef RightPath, StringRef DiffPath, llvm::StringSet<> &IgnoredRemoveUsrs, CheckerOptions Opts) { if (!fs::exists(LeftPath)) { llvm::errs() << LeftPath << " does not exist\n"; return 1; } if (!fs::exists(RightPath)) { llvm::errs() << RightPath << " does not exist\n"; return 1; } llvm::errs() << "Diffing: " << LeftPath << " and " << RightPath << "\n"; std::unique_ptr<DiagnosticConsumer> pConsumer = options::CompilerStyleDiags ? std::make_unique<PrintingDiagnosticConsumer>(): std::make_unique<ModuleDifferDiagsConsumer>(false); SDKContext Ctx(Opts); Ctx.addDiagConsumer(*pConsumer); SwiftDeclCollector LeftCollector(Ctx); LeftCollector.deSerialize(LeftPath); SwiftDeclCollector RightCollector(Ctx); RightCollector.deSerialize(RightPath); llvm::errs() << "Finished deserializing" << "\n"; auto LeftModule = LeftCollector.getSDKRoot(); auto RightModule = RightCollector.getSDKRoot(); Ctx.setCommonVersion(std::min(LeftModule->getJsonFormatVersion(), RightModule->getJsonFormatVersion())); // Structural diffs: not merely name changes but changes in SDK tree // structure. llvm::errs() << "Detecting type member diffs" << "\n"; findTypeMemberDiffs(LeftModule, RightModule, Ctx.getTypeMemberDiffs()); PrunePass Prune(Ctx); Prune.pass(LeftModule, RightModule); llvm::errs() << "Finished pruning" << "\n"; ChangeRefinementPass RefinementPass(Ctx.getNodeUpdateMap()); RefinementPass.pass(LeftModule, RightModule); DiffVector AllItems; DiffItemEmitter::collectDiffItems(LeftModule, AllItems); // Find type alias change first. auto &AliasMap = Ctx.getTypeAliasUpdateMap(); TypeAliasDiffFinder(LeftModule, RightModule, AliasMap).search(); populateAliasChanges(AliasMap, AllItems, /*IsRevert*/false); // Find type alias revert change. auto &RevertAliasMap = Ctx.getRevertTypeAliasUpdateMap(); TypeAliasDiffFinder(RightModule, LeftModule, RevertAliasMap).search(); populateAliasChanges(RevertAliasMap, AllItems, /*IsRevert*/true); AllItems.erase(std::remove_if(AllItems.begin(), AllItems.end(), [&](CommonDiffItem &Item) { return Item.DiffKind == NodeAnnotation::RemovedDecl && IgnoredRemoveUsrs.find(Item.LeftUsr) != IgnoredRemoveUsrs.end(); }), AllItems.end()); NoEscapeFuncParamVector AllNoEscapingFuncs; NoEscapingFuncEmitter::collectDiffItems(RightModule, AllNoEscapingFuncs); llvm::errs() << "Dumping diff to " << DiffPath << '\n'; std::vector<OverloadedFuncInfo> Overloads; // OverloadMemberFunctionEmitter::collectDiffItems(RightModule, Overloads); auto &typeMemberDiffs = Ctx.getTypeMemberDiffs(); std::error_code EC; llvm::raw_fd_ostream Fs(DiffPath, EC, llvm::sys::fs::F_None); removeRedundantAndSort(AllItems); removeRedundantAndSort(typeMemberDiffs); removeRedundantAndSort(AllNoEscapingFuncs); removeRedundantAndSort(Overloads); if (options::OutputInJson) { std::vector<APIDiffItem*> TotalItems; std::transform(AllItems.begin(), AllItems.end(), std::back_inserter(TotalItems), [](CommonDiffItem &Item) { return &Item; }); std::transform(typeMemberDiffs.begin(), typeMemberDiffs.end(), std::back_inserter(TotalItems), [](TypeMemberDiffItem &Item) { return &Item; }); std::transform(AllNoEscapingFuncs.begin(), AllNoEscapingFuncs.end(), std::back_inserter(TotalItems), [](NoEscapeFuncParam &Item) { return &Item; }); std::transform(Overloads.begin(), Overloads.end(), std::back_inserter(TotalItems), [](OverloadedFuncInfo &Item) { return &Item; }); APIDiffItemStore::serialize(Fs, TotalItems); return 0; } serializeDiffs(Fs, AllItems); serializeDiffs(Fs, typeMemberDiffs); serializeDiffs(Fs, AllNoEscapingFuncs); serializeDiffs(Fs, Overloads); return 0; } static int readFileLineByLine(StringRef Path, llvm::StringSet<> &Lines) { auto FileBufOrErr = llvm::MemoryBuffer::getFile(Path); if (!FileBufOrErr) { llvm::errs() << "error opening file '" << Path << "': " << FileBufOrErr.getError().message() << '\n'; return 1; } StringRef BufferText = FileBufOrErr.get()->getBuffer(); while (!BufferText.empty()) { StringRef Line; std::tie(Line, BufferText) = BufferText.split('\n'); Line = Line.trim(); if (Line.empty()) continue; if (Line.startswith("// ")) // comment. continue; Lines.insert(Line); } return 0; } // This function isn't referenced outside its translation unit, but it // can't use the "static" keyword because its address is used for // getMainExecutable (since some platforms don't support taking the // address of main, and some platforms can't implement getMainExecutable // without being given the address of a function in the main executable). void anchorForGetMainExecutable() {} static void setSDKPath(CompilerInvocation &InitInvok, bool IsBaseline) { if (IsBaseline) { // Set baseline SDK if (!options::BaselineSDK.empty()) { InitInvok.setSDKPath(options::BaselineSDK); } } else { // Set current SDK if (!options::SDK.empty()) { InitInvok.setSDKPath(options::SDK); } else if (const char *SDKROOT = getenv("SDKROOT")) { InitInvok.setSDKPath(SDKROOT); } else { llvm::errs() << "Provide '-sdk <path>' option or run with 'xcrun -sdk <..>\ swift-api-digester'\n"; exit(1); } } } static int prepareForDump(const char *Main, CompilerInvocation &InitInvok, llvm::StringSet<> &Modules, bool IsBaseline = false) { InitInvok.setMainExecutablePath(fs::getMainExecutable(Main, reinterpret_cast<void *>(&anchorForGetMainExecutable))); InitInvok.setModuleName("swift_ide_test"); setSDKPath(InitInvok, IsBaseline); if (!options::Triple.empty()) InitInvok.setTargetTriple(options::Triple); // Ensure the tool works on linux properly InitInvok.getLangOptions().EnableObjCInterop = InitInvok.getLangOptions().Target.isOSDarwin(); InitInvok.getClangImporterOptions().ModuleCachePath = options::ModuleCachePath; if (!options::SwiftVersion.empty()) { using version::Version; bool isValid = false; if (auto Version = Version::parseVersionString(options::SwiftVersion, SourceLoc(), nullptr)) { if (auto Effective = Version.getValue().getEffectiveLanguageVersion()) { InitInvok.getLangOptions().EffectiveLanguageVersion = *Effective; isValid = true; } } if (!isValid) { llvm::errs() << "Unsupported Swift Version.\n"; exit(1); } } if (!options::ResourceDir.empty()) { InitInvok.setRuntimeResourcePath(options::ResourceDir); } std::vector<SearchPathOptions::FrameworkSearchPath> FramePaths; for (const auto &path : options::CCSystemFrameworkPaths) { FramePaths.push_back({path, /*isSystem=*/true}); } if (IsBaseline) { for (const auto &path : options::BaselineFrameworkPaths) { FramePaths.push_back({path, /*isSystem=*/false}); } InitInvok.setImportSearchPaths(options::BaselineModuleInputPaths); } else { for (const auto &path : options::FrameworkPaths) { FramePaths.push_back({path, /*isSystem=*/false}); } InitInvok.setImportSearchPaths(options::ModuleInputPaths); } InitInvok.setFrameworkSearchPaths(FramePaths); if (!options::ModuleList.empty()) { if (readFileLineByLine(options::ModuleList, Modules)) exit(1); } for (auto M : options::ModuleNames) { Modules.insert(M); } for (auto M: options::PreferInterfaceForModules) { InitInvok.getFrontendOptions().PreferInterfaceForModules.push_back(M); } if (Modules.empty()) { llvm::errs() << "Need to specify -include-all or -module <name>\n"; exit(1); } return 0; } static void readIgnoredUsrs(llvm::StringSet<> &IgnoredUsrs) { StringRef Path = options::IgnoreRemovedDeclUSRs; if (Path.empty()) return; if (!fs::exists(Path)) { llvm::errs() << Path << " does not exist.\n"; return; } readFileLineByLine(Path, IgnoredUsrs); } static int deserializeDiffItems(APIDiffItemStore &Store, StringRef DiffPath, StringRef OutputPath) { Store.addStorePath(DiffPath); std::error_code EC; llvm::raw_fd_ostream FS(OutputPath, EC, llvm::sys::fs::F_None); APIDiffItemStore::serialize(FS, Store.getAllDiffItems()); return 0; } static int deserializeNameCorrection(APIDiffItemStore &Store, StringRef OutputPath) { std::error_code EC; llvm::raw_fd_ostream FS(OutputPath, EC, llvm::sys::fs::F_None); std::set<NameCorrectionInfo> Result; for (auto *Item: Store.getAllDiffItems()) { if (auto *CI = dyn_cast<CommonDiffItem>(Item)) { if (CI->DiffKind == NodeAnnotation::Rename) { auto NewName = CI->getNewName(); auto Module = CI->ModuleName; if (CI->rightCommentUnderscored()) { Result.insert(NameCorrectionInfo(NewName, NewName, Module)); } } } } std::vector<NameCorrectionInfo> Vec; Vec.insert(Vec.end(), Result.begin(), Result.end()); APIDiffItemStore::serialize(FS, Vec); return EC.value(); } static CheckerOptions getCheckOpts(int argc, char *argv[]) { CheckerOptions Opts; Opts.AvoidLocation = options::AvoidLocation; Opts.AvoidToolArgs = options::AvoidToolArgs; Opts.ABI = options::Abi; Opts.Migrator = options::Migrator; Opts.Verbose = options::Verbose; Opts.AbortOnModuleLoadFailure = options::AbortOnModuleLoadFailure; Opts.LocationFilter = options::LocationFilter; Opts.PrintModule = options::PrintModule; // When ABI checking is enabled, we should only include Swift symbols because // the checking logics are language-specific. Opts.SwiftOnly = options::Abi || options::SwiftOnly; Opts.SkipOSCheck = options::DisableOSChecks; for (int i = 1; i < argc; ++i) Opts.ToolArgs.push_back(argv[i]); if (!options::SDK.empty()) { auto Ver = getSDKVersion(options::SDK); if (!Ver.empty()) { Opts.ToolArgs.push_back("-sdk-version"); Opts.ToolArgs.push_back(Ver); } } return Opts; } static SDKNodeRoot *getSDKRoot(const char *Main, SDKContext &Ctx, bool IsBaseline) { CompilerInvocation Invok; llvm::StringSet<> Modules; if (prepareForDump(Main, Invok, Modules, IsBaseline)) return nullptr; return getSDKNodeRoot(Ctx, Invok, Modules); } static bool hasBaselineInput() { return !options::BaselineModuleInputPaths.empty() || !options::BaselineFrameworkPaths.empty() || !options::BaselineSDK.empty(); } enum class ComparisonInputMode: uint8_t { BothJson, BaselineJson, BothLoad, }; static ComparisonInputMode checkComparisonInputMode() { if (options::SDKJsonPaths.size() == 2) return ComparisonInputMode::BothJson; else if (hasBaselineInput()) return ComparisonInputMode::BothLoad; else return ComparisonInputMode::BaselineJson; } static std::string getDefaultBaselineDir(const char *Main) { llvm::SmallString<128> BaselineDir; // The path of the swift-api-digester executable. std::string ExePath = llvm::sys::fs::getMainExecutable(Main, reinterpret_cast<void *>(&anchorForGetMainExecutable)); BaselineDir.append(ExePath); llvm::sys::path::remove_filename(BaselineDir); // Remove /swift-api-digester llvm::sys::path::remove_filename(BaselineDir); // Remove /bin llvm::sys::path::append(BaselineDir, "lib", "swift", "FrameworkABIBaseline"); return BaselineDir.str().str(); } static std::string getEmptyBaselinePath(const char *Main) { llvm::SmallString<128> BaselinePath(getDefaultBaselineDir(Main)); llvm::sys::path::append(BaselinePath, "nil.json"); return BaselinePath.str().str(); } static StringRef getBaselineFilename(llvm::Triple Triple) { if (Triple.isMacCatalystEnvironment()) return "iosmac.json"; else if (Triple.isMacOSX()) return "macos.json"; else if (Triple.isiOS()) return "iphoneos.json"; else if (Triple.isTvOS()) return "appletvos.json"; else if (Triple.isWatchOS()) return "watchos.json"; else if (Triple.isOSLinux()) return "linux.json"; else if (Triple.isOSWindows()) return "windows.json"; else { llvm::errs() << "Unsupported triple target\n"; exit(1); } } static std::string getDefaultBaselinePath(const char *Main, StringRef Module, llvm::Triple Triple, bool ABI) { llvm::SmallString<128> BaselinePath(getDefaultBaselineDir(Main)); llvm::sys::path::append(BaselinePath, Module); // Look for ABI or API baseline llvm::sys::path::append(BaselinePath, ABI? "ABI": "API"); llvm::sys::path::append(BaselinePath, getBaselineFilename(Triple)); return BaselinePath.str().str(); } static std::string getCustomBaselinePath(llvm::Triple Triple, bool ABI) { llvm::SmallString<128> BaselinePath(options::BaselineDirPath); // Look for ABI or API baseline llvm::sys::path::append(BaselinePath, ABI? "ABI": "API"); llvm::sys::path::append(BaselinePath, getBaselineFilename(Triple)); return BaselinePath.str().str(); } static SDKNodeRoot *getBaselineFromJson(const char *Main, SDKContext &Ctx) { SwiftDeclCollector Collector(Ctx); // If the baseline path has been given, honor that. if (!options::BaselineFilePath.empty()) { Collector.deSerialize(options::BaselineFilePath); return Collector.getSDKRoot(); } CompilerInvocation Invok; llvm::StringSet<> Modules; // We need to call prepareForDump to parse target triple. if (prepareForDump(Main, Invok, Modules, true)) return nullptr; assert(Modules.size() == 1 && "Cannot find builtin baseline for more than one module"); std::string Path; if (!options::BaselineDirPath.empty()) { Path = getCustomBaselinePath(Invok.getLangOptions().Target, Ctx.checkingABI()); } else if (options::UseEmptyBaseline) { Path = getEmptyBaselinePath(Main); } else { Path = getDefaultBaselinePath(Main, Modules.begin()->getKey(), Invok.getLangOptions().Target, Ctx.checkingABI()); } if (!fs::exists(Path)) { llvm::errs() << "Baseline at " << Path << " does not exist\n"; exit(1); } if (options::Verbose) { llvm::errs() << "Using baseline at " << Path << "\n"; } Collector.deSerialize(Path); return Collector.getSDKRoot(); } static std::string getJsonOutputFilePath(llvm::Triple Triple, bool ABI) { if (!options::OutputFile.empty()) return options::OutputFile; if (!options::OutputDir.empty()) { llvm::SmallString<128> OutputPath(options::OutputDir); llvm::sys::path::append(OutputPath, ABI? "ABI": "API"); if (!llvm::sys::fs::exists(OutputPath.str())) { llvm::errs() << "Baseline directory " << OutputPath.str() << " doesn't exist\n"; exit(1); } llvm::sys::path::append(OutputPath, getBaselineFilename(Triple)); return OutputPath.str(); } llvm::errs() << "Unable to decide output file path\n"; exit(1); } int main(int argc, char *argv[]) { PROGRAM_START(argc, argv); INITIALIZE_LLVM(); llvm::cl::HideUnrelatedOptions(options::Category); llvm::cl::ParseCommandLineOptions(argc, argv, "Swift SDK Digester\n"); CompilerInvocation InitInvok; llvm::StringSet<> Modules; std::vector<std::string> PrintApis; llvm::StringSet<> IgnoredUsrs; readIgnoredUsrs(IgnoredUsrs); CheckerOptions Opts = getCheckOpts(argc, argv); for (auto Name : options::ApisPrintUsrs) PrintApis.push_back(Name); switch (options::Action) { case ActionType::DumpSDK: return (prepareForDump(argv[0], InitInvok, Modules)) ? 1 : dumpSDKContent(InitInvok, Modules, getJsonOutputFilePath(InitInvok.getLangOptions().Target, Opts.ABI), Opts); case ActionType::MigratorGen: case ActionType::DiagnoseSDKs: { ComparisonInputMode Mode = checkComparisonInputMode(); llvm::StringSet<> protocolWhitelist; if (!options::ProtReqWhiteList.empty()) { if (readFileLineByLine(options::ProtReqWhiteList, protocolWhitelist)) return 1; } if (options::Action == ActionType::MigratorGen) { assert(Mode == ComparisonInputMode::BothJson && "Only BothJson mode is supported"); return generateMigrationScript(options::SDKJsonPaths[0], options::SDKJsonPaths[1], options::OutputFile, IgnoredUsrs, Opts); } switch(Mode) { case ComparisonInputMode::BothJson: { return diagnoseModuleChange(options::SDKJsonPaths[0], options::SDKJsonPaths[1], options::OutputFile, Opts, std::move(protocolWhitelist)); } case ComparisonInputMode::BaselineJson: { SDKContext Ctx(Opts); return diagnoseModuleChange(Ctx, getBaselineFromJson(argv[0], Ctx), getSDKRoot(argv[0], Ctx, false), options::OutputFile, std::move(protocolWhitelist)); } case ComparisonInputMode::BothLoad: { SDKContext Ctx(Opts); return diagnoseModuleChange(Ctx, getSDKRoot(argv[0], Ctx, true), getSDKRoot(argv[0], Ctx, false), options::OutputFile, std::move(protocolWhitelist)); } } } case ActionType::DeserializeSDK: case ActionType::DeserializeDiffItems: { if (options::SDKJsonPaths.size() != 1) { llvm::cl::PrintHelpMessage(); return 1; } if (options::Action == ActionType::DeserializeDiffItems) { CompilerInstance CI; APIDiffItemStore Store(CI.getDiags()); return deserializeDiffItems(Store, options::SDKJsonPaths[0], options::OutputFile); } else { return deserializeSDKDump(options::SDKJsonPaths[0], options::OutputFile, Opts); } } case ActionType::GenerateNameCorrectionTemplate: { CompilerInstance CI; APIDiffItemStore Store(CI.getDiags()); auto &Paths = options::SDKJsonPaths; for (unsigned I = 0; I < Paths.size(); I ++) Store.addStorePath(Paths[I]); return deserializeNameCorrection(Store, options::OutputFile); } case ActionType::GenerateEmptyBaseline: { SDKContext Ctx(Opts); dumpSDKRoot(getEmptySDKNodeRoot(Ctx), options::OutputFile); return 0; } case ActionType::FindUsr: { if (options::SDKJsonPaths.size() != 1) { llvm::cl::PrintHelpMessage(); return 1; } return findDeclUsr(options::SDKJsonPaths[0], Opts); } case ActionType::None: llvm::errs() << "Action required\n"; llvm::cl::PrintHelpMessage(); return 1; } }
105,491
32,933
#pragma once #include "lue/info/property/same_shape/constant_shape/property.hpp" #include "lue/object/property/properties_traits.hpp" #include "lue/core/collection.hpp" namespace lue { namespace data_model { namespace same_shape { namespace constant_shape { /*! @brief Collection of same shape x constant shape properties */ class Properties: public Collection<Property> { public: explicit Properties (hdf5::Group const& parent); explicit Properties (Collection<Property>&& collection); Properties (Properties const&)=default; Properties (Properties&&)=default; ~Properties () override =default; Properties& operator= (Properties const&)=default; Properties& operator= (Properties&&)=default; Property& add (std::string const& name, hdf5::Datatype const& datatype, std::string const& description=""); Property& add (std::string const& name, hdf5::Datatype const& datatype, hdf5::Shape const& shape, std::string const& description=""); private: }; Properties create_properties (hdf5::Group& parent); } // namespace constant_shape } // namespace same_shape template<> class PropertyTraits<same_shape::constant_shape::Properties> { public: using Property = same_shape::constant_shape::Properties::Element; using Value = ValueT<Property>; }; } // namespace data_model } // namespace lue
1,748
437
/*__________________________________________________________________________________________ (c) Hash(BEGIN(Satoshi[2010]), END(Sunny[2012])) == Videlicet[2014] ++ (c) Copyright The Nexus Developers 2014 - 2021 Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. "ad vocem populi" - To the Voice of the People ____________________________________________________________________________________________*/ #include <LLD/include/global.h> #include <TAO/Operation/include/migrate.h> #include <TAO/Operation/include/enum.h> #include <TAO/Operation/types/contract.h> #include <TAO/Register/include/constants.h> #include <TAO/Register/include/enum.h> #include <TAO/Register/include/reserved.h> #include <TAO/Register/types/object.h> /* Global TAO namespace. */ namespace TAO { /* Operation Layer namespace. */ namespace Operation { /* Commit the final state to disk. */ bool Migrate::Commit(const TAO::Register::Object& trust, const uint256_t& hashAddress, const uint256_t& hashCaller, const uint512_t& hashTx, const uint576_t& hashTrust, const uint512_t& hashLast, const uint8_t nFlags) { /* Check if this transfer is already claimed. Trust migration is always a send from a Legacy trust key, * so the hashProof is always the wildcard address. Also only one output UTXO sending to trust account * and thus the contract number is always zero. */ if(LLD::Ledger->HasProof(TAO::Register::WILDCARD_ADDRESS, hashTx, 0, nFlags)) return debug::error(FUNCTION, "migrate credit is already claimed"); /* Write the claimed proof. */ if(!LLD::Ledger->WriteProof(TAO::Register::WILDCARD_ADDRESS, hashTx, 0, nFlags)) return debug::error(FUNCTION, "failed to write migrate credit proof"); /* Write the new register's state. */ if(!LLD::Register->WriteState(hashAddress, trust, nFlags)) return debug::error(FUNCTION, "failed to write post-state to disk"); /* Migrate operation can be executed on mempool accept, so only write trust/stake items for BLOCK flag */ if(nFlags == TAO::Ledger::FLAGS::BLOCK) { /* Update the register database to index the trust account. (migrated trust account is post-Genesis) */ if(!LLD::Register->IndexTrust(hashCaller, hashAddress)) return debug::error(FUNCTION, "could not index the trust account genesis"); /* Set hash last trust for trust account to hash last trust for Legacy trust key. */ if(!LLD::Ledger->WriteStake(hashCaller, hashLast)) return debug::error(FUNCTION, "failed to write last trust to disk"); /* Record that the legacy trust key has completed migration. */ if(!config::fClient.load() && !LLD::Legacy->WriteTrustConversion(hashTrust)) return debug::error(FUNCTION, "failed to record trust key migration to disk"); } return true; } /* Migrate trust key data to trust account register. */ bool Migrate::Execute(TAO::Register::Object &trust, const uint64_t nAmount, const uint32_t nScore, const uint64_t nTimestamp) { /* Parse the account object register. */ if(!trust.Parse()) return debug::error(FUNCTION, "failed to parse account object register"); /* Check migrating to a trust account register. */ if(trust.Standard() != TAO::Register::OBJECTS::TRUST) return debug::error(FUNCTION, "cannot migrate to a non-trust account"); /* Check that there is no stake. */ if(trust.get<uint64_t>("stake") != 0) return debug::error(FUNCTION, "cannot migrate with already existing stake"); /* Check that there is no trust. */ if(trust.get<uint64_t>("trust") != 0) return debug::error(FUNCTION, "cannot migrate with already existing trust"); /* Write the migrated stake to trust account register. */ if(!trust.Write("stake", nAmount)) return debug::error(FUNCTION, "stake could not be written to object register"); /* Write the migrated trust to trust account register. Also converts old trust score from uint32_t to uint64_t */ if(!trust.Write("trust", static_cast<uint64_t>(nScore))) return debug::error(FUNCTION, "trust could not be written to object register"); /* Update the state register's timestamp. */ trust.nModified = nTimestamp; trust.SetChecksum(); /* Check that the register is in a valid state. */ if(!trust.IsValid()) return debug::error(FUNCTION, "trust account is in invalid state"); return true; } /* Verify trust migration rules. */ bool Migrate::Verify(const Contract& contract, const Contract& debit) { /* Reset the contract streams. */ contract.Reset(); /* Get operation byte. */ uint8_t OP; contract >> OP; /* Check operation byte. */ if(OP != OP::MIGRATE) return debug::error(FUNCTION, "called with incorrect OP"); /* Check transaction version. */ if(contract.Version() > 1) return debug::error(FUNCTION, "OP::MIGRATE: invalid transaction version"); /* Check for conditions. */ if(!debit.Empty(Contract::CONDITIONS)) return debug::error(FUNCTION, "OP::MIGRATE: conditions not allowed on migrate debit"); contract.Seek(64); /* Get the trust register address. (hash to) */ uint256_t hashAccount; contract >> hashAccount; /* Get the trust key hash. (hash from) */ uint576_t hashTrust; contract >> hashTrust; /* Get the amount to migrate. */ uint64_t nAmount; contract >> nAmount; /* Get the trust score to migrate. */ uint32_t nScore; contract >> nScore; /* Get the hash last stake. */ uint512_t hashLast; contract >> hashLast; /* Get the byte from pre-state. */ uint8_t nState; contract >>= nState; /* Check for the pre-state. */ if(nState != TAO::Register::STATES::PRESTATE) return debug::error(FUNCTION, "register contract not in pre-state"); /* Read pre-states. */ TAO::Register::Object trust; contract >>= trust; /* Check contract account */ if(contract.Caller() != trust.hashOwner) return debug::error(FUNCTION, "no write permissions for caller ", contract.Caller().SubString()); /* Parse the account. */ if(!trust.Parse()) return debug::error(FUNCTION, "failed to parse account"); /* Check whether a trust account Genesis already indexed. */ if(LLD::Register->HasTrust(contract.Caller())) return debug::error(FUNCTION, "trust account is not new"); /* Reset debit streams */ debit.Reset(); /* Get operation byte. */ OP = 0; debit >> OP; /* Check that prev is debit. */ if(OP != OP::DEBIT) return debug::error(FUNCTION, "tx claim is not a debit"); /* Get the hashFrom */ uint256_t hashFrom; debit >> hashFrom; /* Get the hashTo. */ uint256_t hashTo; debit >> hashTo; /* Get the debit amount. */ uint64_t nDebit; debit >> nDebit; /* Skip placeholder */ debit.Seek(8); /* Get the debit trust score */ uint32_t nScoreDebit; debit >> nScoreDebit; /* Get the debit last stake hash */ uint512_t hashLastDebit; debit >> hashLastDebit; /* Get the trust key hash */ uint576_t hashTrustDebit; debit >> hashTrustDebit; /* Check for reserved values. */ if(TAO::Register::Reserved(hashTo)) return debug::error(FUNCTION, "cannot credit register with reserved address"); /* Migrate should always have wildcard as hashFrom because it is from UTXO. */ if(hashFrom != TAO::Register::WILDCARD_ADDRESS) return debug::error(FUNCTION, "migrate debit register must be from UTXO"); /* Check whether the legacy trust key has already completed migration. */ if(!config::fClient.load() && LLD::Legacy->HasTrustConversion(hashTrust)) return debug::error(FUNCTION, "trust key is already converted"); /* Validate migrate is to address in UTXO output */ if(hashTo != hashAccount) return debug::error(FUNCTION, "trust account register address must match debit"); /* Check the debit amount. */ if(nDebit != nAmount) return debug::error(FUNCTION, "debit and credit value mismatch"); /* Verify the trust score */ if(nScoreDebit != nScore) return debug::error(FUNCTION, "debit and credit trust score mismatch"); /* Verify the hash last stake */ if(hashLastDebit != hashLast) return debug::error(FUNCTION, "debit and credit hash last stake mismatch"); /* Verify the trust key hash */ if(hashTrustDebit != hashTrust) return debug::error(FUNCTION, "debit and credit trust key mismatch"); return true; } } }
10,175
2,729
// license:BSD-3-Clause // copyright-holders:Aaron Giles /*************************************************************************** HAR MadMax hardware **************************************************************************/ #include "emu.h" #include "includes/dcheese.h" /************************************* * * Constants * *************************************/ #define DSTBITMAP_WIDTH 512 #define DSTBITMAP_HEIGHT 512 /************************************* * * Palette translation * *************************************/ PALETTE_INIT_MEMBER(dcheese_state, dcheese) { const uint16_t *src = (uint16_t *)memregion("user1")->base(); int i; /* really 65536 colors, but they don't use the later ones so we can stay */ /* within MAME's limits */ for (i = 0; i < 65534; i++) { int data = *src++; palette.set_pen_color(i, pal6bit(data >> 0), pal5bit(data >> 6), pal5bit(data >> 11)); } } /************************************* * * Scanline interrupt * *************************************/ void dcheese_state::update_scanline_irq() { /* if not in range, don't bother */ if (m_blitter_vidparam[0x22/2] <= m_blitter_vidparam[0x1e/2]) { int effscan; attotime time; /* compute the effective scanline of the interrupt */ effscan = m_blitter_vidparam[0x22/2] - m_blitter_vidparam[0x1a/2]; if (effscan < 0) effscan += m_blitter_vidparam[0x1e/2]; /* determine the time; if it's in this scanline, bump to the next frame */ time = m_screen->time_until_pos(effscan); if (time < m_screen->scan_period()) time += m_screen->frame_period(); m_blitter_timer->adjust(time); } } void dcheese_state::device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr) { switch (id) { case TIMER_BLITTER_SCANLINE: dcheese_signal_irq(3); update_scanline_irq(); break; case TIMER_SIGNAL_IRQ: dcheese_signal_irq(param); break; default: assert_always(false, "Unknown id in dcheese_state::device_timer"); } } /************************************* * * Video start * *************************************/ void dcheese_state::video_start() { /* the destination bitmap is not directly accessible to the CPU */ m_dstbitmap = std::make_unique<bitmap_ind16>(DSTBITMAP_WIDTH, DSTBITMAP_HEIGHT); /* create timers */ m_blitter_timer = timer_alloc(TIMER_BLITTER_SCANLINE); m_signal_irq_timer = timer_alloc(TIMER_SIGNAL_IRQ); /* register for saving */ save_item(NAME(m_blitter_color)); save_item(NAME(m_blitter_xparam)); save_item(NAME(m_blitter_yparam)); save_item(NAME(m_blitter_vidparam)); save_item(NAME(*m_dstbitmap)); } /************************************* * * Video update * *************************************/ uint32_t dcheese_state::screen_update_dcheese(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect) { int x, y; /* update the pixels */ for (y = cliprect.min_y; y <= cliprect.max_y; y++) { uint16_t *dest = &bitmap.pix16(y); uint16_t *src = &m_dstbitmap->pix16((y + m_blitter_vidparam[0x28/2]) % DSTBITMAP_HEIGHT); for (x = cliprect.min_x; x <= cliprect.max_x; x++) dest[x] = src[x]; } return 0; } /************************************* * * Blitter implementation * *************************************/ void dcheese_state::do_clear( ) { int y; /* clear the requested scanlines */ for (y = m_blitter_vidparam[0x2c/2]; y < m_blitter_vidparam[0x2a/2]; y++) memset(&m_dstbitmap->pix16(y % DSTBITMAP_HEIGHT), 0, DSTBITMAP_WIDTH * 2); /* signal an IRQ when done (timing is just a guess) */ m_signal_irq_timer->adjust(m_screen->scan_period(), 1); } void dcheese_state::do_blit( ) { int32_t srcminx = m_blitter_xparam[0] << 12; int32_t srcmaxx = m_blitter_xparam[1] << 12; int32_t srcminy = m_blitter_yparam[0] << 12; int32_t srcmaxy = m_blitter_yparam[1] << 12; int32_t srcx = ((m_blitter_xparam[2] & 0x0fff) | ((m_blitter_xparam[3] & 0x0fff) << 12)) << 7; int32_t srcy = ((m_blitter_yparam[2] & 0x0fff) | ((m_blitter_yparam[3] & 0x0fff) << 12)) << 7; int32_t dxdx = (int32_t)(((m_blitter_xparam[4] & 0x0fff) | ((m_blitter_xparam[5] & 0x0fff) << 12)) << 12) >> 12; int32_t dxdy = (int32_t)(((m_blitter_xparam[6] & 0x0fff) | ((m_blitter_xparam[7] & 0x0fff) << 12)) << 12) >> 12; int32_t dydx = (int32_t)(((m_blitter_yparam[4] & 0x0fff) | ((m_blitter_yparam[5] & 0x0fff) << 12)) << 12) >> 12; int32_t dydy = (int32_t)(((m_blitter_yparam[6] & 0x0fff) | ((m_blitter_yparam[7] & 0x0fff) << 12)) << 12) >> 12; uint8_t *src = memregion("gfx1")->base(); uint32_t pagemask = (memregion("gfx1")->bytes() - 1) / 0x40000; int xstart = m_blitter_xparam[14]; int xend = m_blitter_xparam[15] + 1; int ystart = m_blitter_yparam[14]; int yend = m_blitter_yparam[15]; int color = (m_blitter_color[0] << 8) & 0xff00; int mask = (m_blitter_color[0] >> 8) & 0x00ff; int opaque = (dxdx | dxdy | dydx | dydy) == 0; /* bit of a hack for fredmem */ int x, y; /* loop over target rows */ for (y = ystart; y <= yend; y++) { uint16_t *dst = &m_dstbitmap->pix16(y % DSTBITMAP_HEIGHT); /* loop over target columns */ for (x = xstart; x <= xend; x++) { /* compute current X/Y positions */ int sx = (srcx + dxdx * (x - xstart) + dxdy * (y - ystart)) & 0xffffff; int sy = (srcy + dydx * (x - xstart) + dydy * (y - ystart)) & 0xffffff; /* clip to source cliprect */ if (sx >= srcminx && sx <= srcmaxx && sy >= srcminy && sy <= srcmaxy) { /* page comes from bit 22 of Y and bit 21 of X */ int page = (((sy >> 21) & 2) | ((sx >> 21) & 1) | ((sx >> 20) & 4)) & pagemask; int pix = src[0x40000 * page + ((sy >> 12) & 0x1ff) * 512 + ((sx >> 12) & 0x1ff)]; /* only non-zero pixels get written */ if (pix | opaque) dst[x % DSTBITMAP_WIDTH] = (pix & mask) | color; } } } /* signal an IRQ when done (timing is just a guess) */ m_signal_irq_timer->adjust(m_screen->scan_period() / 2, 2); /* these extra parameters are written but they are always zero, so I don't know what they do */ if (m_blitter_xparam[8] != 0 || m_blitter_xparam[9] != 0 || m_blitter_xparam[10] != 0 || m_blitter_xparam[11] != 0 || m_blitter_yparam[8] != 0 || m_blitter_yparam[9] != 0 || m_blitter_yparam[10] != 0 || m_blitter_yparam[11] != 0) { logerror("%s:blit! (%04X)\n", machine().describe_context(), m_blitter_color[0]); logerror(" %04X %04X %04X %04X - %04X %04X %04X %04X - %04X %04X %04X %04X - %04X %04X %04X %04X\n", m_blitter_xparam[0], m_blitter_xparam[1], m_blitter_xparam[2], m_blitter_xparam[3], m_blitter_xparam[4], m_blitter_xparam[5], m_blitter_xparam[6], m_blitter_xparam[7], m_blitter_xparam[8], m_blitter_xparam[9], m_blitter_xparam[10], m_blitter_xparam[11], m_blitter_xparam[12], m_blitter_xparam[13], m_blitter_xparam[14], m_blitter_xparam[15]); logerror(" %04X %04X %04X %04X - %04X %04X %04X %04X - %04X %04X %04X %04X - %04X %04X %04X %04X\n", m_blitter_yparam[0], m_blitter_yparam[1], m_blitter_yparam[2], m_blitter_yparam[3], m_blitter_yparam[4], m_blitter_yparam[5], m_blitter_yparam[6], m_blitter_yparam[7], m_blitter_yparam[8], m_blitter_yparam[9], m_blitter_yparam[10], m_blitter_yparam[11], m_blitter_yparam[12], m_blitter_yparam[13], m_blitter_yparam[14], m_blitter_yparam[15]); } } /************************************* * * Blitter read/write * *************************************/ WRITE16_MEMBER(dcheese_state::madmax_blitter_color_w) { COMBINE_DATA(&m_blitter_color[offset]); } WRITE16_MEMBER(dcheese_state::madmax_blitter_xparam_w) { COMBINE_DATA(&m_blitter_xparam[offset]); } WRITE16_MEMBER(dcheese_state::madmax_blitter_yparam_w) { COMBINE_DATA(&m_blitter_yparam[offset]); } WRITE16_MEMBER(dcheese_state::madmax_blitter_vidparam_w) { COMBINE_DATA(&m_blitter_vidparam[offset]); switch (offset) { case 0x10/2: /* horiz front porch */ case 0x12/2: /* horiz display start */ case 0x14/2: /* horiz display end */ case 0x16/2: /* horiz back porch */ case 0x18/2: /* vert front porch */ case 0x1a/2: /* vert display start */ case 0x1c/2: /* vert display end */ case 0x1e/2: /* vert back porch */ break; case 0x22/2: /* scanline interrupt */ update_scanline_irq(); break; case 0x24/2: /* writes here after writing to 0x28 */ break; case 0x28/2: /* display starting y */ case 0x2a/2: /* clear end y */ case 0x2c/2: /* clear start y */ break; case 0x38/2: /* blit */ do_blit(); break; case 0x3e/2: /* clear */ do_clear(); break; default: logerror("%06X:write to %06X = %04X & %04x\n", m_maincpu->pc(), 0x2a0000 + 2 * offset, data, mem_mask); break; } } WRITE16_MEMBER(dcheese_state::madmax_blitter_unknown_w) { /* written to just before the blitter command register is written */ logerror("%06X:write to %06X = %04X & %04X\n", m_maincpu->pc(), 0x300000 + 2 * offset, data, mem_mask); } READ16_MEMBER(dcheese_state::madmax_blitter_vidparam_r) { /* analog inputs seem to be hooked up here -- might not actually map to blitter */ if (offset == 0x02/2) return ioport("2a0002")->read(); if (offset == 0x0e/2) return ioport("2a000e")->read(); /* early code polls on this bit, wants it to be 0 */ if (offset == 0x36/2) return 0xffff ^ (1 << 5); /* log everything else */ logerror("%06X:read from %06X\n", m_maincpu->pc(), 0x2a0000 + 2 * offset); return 0xffff; }
9,455
4,336
//============================================================== // Copyright (C) Intel Corporation // // SPDX-License-Identifier: MIT // ============================================================= #include <math.h> #include <string.h> #include <algorithm> #include <chrono> #include <iomanip> #include <iostream> #include <set> #include <CL/cl.h> #include "cl_utils.h" #define A_VALUE 0.128f #define B_VALUE 0.256f #define MAX_EPS 1.0e-4f struct HardwareThreadInfo { cl_ulong start; cl_ulong end; cl_uint tid; cl_uint euid; cl_uint ssid; cl_uint sid; }; struct HardwareKernelInfo { cl_ulong cycles; cl_ulong thread_count; cl_ulong eu_count; cl_ulong subslice_count; cl_ulong slice_count; cl_ulong total_samples; cl_ulong bad_samples; }; const char* kKernelSource = "ulong __attribute__((overloadable)) intel_get_cycle_counter();\n" "uint __attribute__((overloadable)) intel_get_hw_thread_id();\n" "uint __attribute__((overloadable)) intel_get_slice_id();\n" "uint __attribute__((overloadable)) intel_get_subslice_id();\n" "uint __attribute__((overloadable)) intel_get_eu_id();\n" "uint __attribute__((overloadable)) intel_get_eu_thread_id();\n" "\n" "struct HardwareThreadInfo {\n" " ulong start;\n" " ulong end;\n" " uint tid;\n" " uint euid;\n" " uint ssid;\n" " uint sid;\n" "};\n" "\n" "__kernel void SmartGEMM(__global float* a, __global float* b,\n" " __global float* c, unsigned size,\n" " __global struct HardwareThreadInfo* info,\n" " int simd_width) {\n" "\n" " ulong start = intel_get_cycle_counter();\n" "\n" " int j = get_global_id(0);\n" " int i = get_global_id(1);\n" " float sum = 0.0f;\n" " for (unsigned k = 0; k < size; ++k) {\n" " sum += a[i * size + k] * b[k * size + j];\n" " }\n" " c[i * size + j] = sum;\n" "\n" " ulong end = intel_get_cycle_counter();\n" "\n" " int id = (i * size + j) / simd_width;\n" " info[id].start = start;\n" " info[id].end = end;\n" " info[id].tid = intel_get_eu_thread_id();\n" " info[id].euid = intel_get_eu_id();\n" " info[id].ssid = intel_get_subslice_id();\n" " info[id].sid = intel_get_slice_id();\n" "}"; static float Check(const std::vector<float>& a, float value) { PTI_ASSERT(value > MAX_EPS); float eps = 0.0f; for (size_t i = 0; i < a.size(); ++i) { eps += fabs((a[i] - value) / value); } return eps / a.size(); } static HardwareKernelInfo ProcessHardwareInfo( const std::vector<HardwareThreadInfo>& info) { cl_ulong total_samples = info.size(); cl_ulong bad_samples = 0; cl_ulong total_cycles = 0; for (auto item : info) { if (item.start < item.end) { total_cycles += item.end - item.start; } else { ++bad_samples; } } std::set<unsigned> tid; std::set<unsigned> euid; std::set<unsigned> sid; std::set<unsigned> ssid; for (auto item : info) { tid.insert(item.tid); euid.insert(item.euid); ssid.insert(item.ssid); sid.insert(item.sid); } cl_ulong average_thread_cycles = bad_samples < total_samples ? total_cycles / (total_samples - bad_samples) : 0; return { average_thread_cycles, tid.size(), euid.size(), ssid.size(), sid.size(), total_samples, bad_samples }; } static void PrintInfo(const std::vector<HardwareKernelInfo>& info) { HardwareKernelInfo kernel_info = { 0 }; PTI_ASSERT(info.size() > 0); cl_ulong total_cycles = 0; for (auto item : info) { total_cycles += item.cycles; kernel_info.total_samples += item.total_samples; kernel_info.bad_samples += item.bad_samples; kernel_info.thread_count = (std::max)( kernel_info.thread_count, item.thread_count); kernel_info.eu_count = (std::max)(kernel_info.eu_count, item.eu_count); kernel_info.subslice_count = (std::max)( kernel_info.subslice_count, item.subslice_count); kernel_info.slice_count = (std::max)( kernel_info.slice_count, item.slice_count); } kernel_info.cycles = total_cycles / info.size(); PTI_ASSERT(kernel_info.total_samples > 0); std::string prologue = "======== GEMM Instrumentation Results ========"; std::string epilogue(prologue.size(), '='); std::cout << prologue << std::endl; float bad_samples_percent = 100.0f * kernel_info.bad_samples / kernel_info.total_samples; if (bad_samples_percent > 90.0f) { std::cout << "Too many bad samples (" << std::setprecision(2) << std::fixed << bad_samples_percent << "%) : Looks like OpenCL " << "built-in intrinsics are not supported" << std::endl; } else { std::cout << "Samples collected: " << kernel_info.total_samples << " (" << std::setprecision(2) << std::fixed << bad_samples_percent << "% of bad samples)" << std::endl; std::cout << "Estimated average HW thread duration: ~ " << kernel_info.cycles / NSEC_IN_USEC << " us (" << kernel_info.cycles << " cycles)" << std::endl; std::cout << "Estimated number of HW threads per EU: " << kernel_info.thread_count << std::endl; std::cout << "Estimated number of EUs per subslice: " << kernel_info.eu_count << std::endl; std::cout << "Estimated number of subslices per slice: " << kernel_info.subslice_count << std::endl; std::cout << "Estimated number of slices: " << kernel_info.slice_count << std::endl; std::cout << "Estimated total number EUs: " << kernel_info.eu_count * kernel_info.subslice_count * kernel_info.slice_count << std::endl; std::cout << "Estimated total number of HW threads: " << kernel_info.thread_count * kernel_info.eu_count * kernel_info.subslice_count * kernel_info.slice_count << std::endl; } std::cout << epilogue << std::endl; } static float RunAndCheck(cl_device_id device, cl_kernel kernel, cl_command_queue queue, const std::vector<float>& a, const std::vector<float>& b, std::vector<float>& c, unsigned size, float expected_result, std::vector<HardwareKernelInfo>& kernel_info) { PTI_ASSERT(kernel != nullptr && queue != nullptr); PTI_ASSERT(size > 0); PTI_ASSERT(a.size() == size * size); PTI_ASSERT(b.size() == size * size); PTI_ASSERT(c.size() == size * size); size_t local_size[3] = { utils::cl::GetKernelLocalSize(device, kernel), 1, 1 }; int simd_width = utils::cl::GetSimdWidth(device, kernel, local_size); PTI_ASSERT(simd_width >= 1 && simd_width <= 32); int hardware_thread_count = (size * size + simd_width - 1) / simd_width; std::vector<HardwareThreadInfo> info(hardware_thread_count); cl_int status = CL_SUCCESS; cl_context context = utils::cl::GetContext(kernel); PTI_ASSERT(context != nullptr); cl_mem dev_a = clCreateBuffer(context, CL_MEM_READ_ONLY, a.size() * sizeof(float), nullptr, &status); PTI_ASSERT(status == CL_SUCCESS && dev_a != nullptr); cl_mem dev_b = clCreateBuffer(context, CL_MEM_READ_ONLY, b.size() * sizeof(float), nullptr, &status); PTI_ASSERT(status == CL_SUCCESS && dev_b != nullptr); cl_mem dev_c = clCreateBuffer(context, CL_MEM_WRITE_ONLY, c.size() * sizeof(float), nullptr, &status); PTI_ASSERT(status == CL_SUCCESS && dev_c != nullptr); cl_mem dev_info = clCreateBuffer(context, CL_MEM_WRITE_ONLY, info.size() * sizeof(HardwareThreadInfo), nullptr, &status); PTI_ASSERT(status == CL_SUCCESS); status = clEnqueueWriteBuffer(queue, dev_a, CL_FALSE, 0, a.size() * sizeof(float), a.data(), 0, nullptr, nullptr); PTI_ASSERT(status == CL_SUCCESS); status = clEnqueueWriteBuffer(queue, dev_b, CL_FALSE, 0, b.size() * sizeof(float), b.data(), 0, nullptr, nullptr); PTI_ASSERT(status == CL_SUCCESS); status = clSetKernelArg(kernel, 0, sizeof(cl_mem), &dev_a); PTI_ASSERT(status == CL_SUCCESS); status = clSetKernelArg(kernel, 1, sizeof(cl_mem), &dev_b); PTI_ASSERT(status == CL_SUCCESS); status = clSetKernelArg(kernel, 2, sizeof(cl_mem), &dev_c); PTI_ASSERT(status == CL_SUCCESS); status = clSetKernelArg(kernel, 3, sizeof(unsigned), &size); PTI_ASSERT(status == CL_SUCCESS); status = clSetKernelArg(kernel, 4, sizeof(cl_mem), &dev_info); PTI_ASSERT(status == CL_SUCCESS); status = clSetKernelArg(kernel, 5, sizeof(int), &simd_width); PTI_ASSERT(status == CL_SUCCESS); size_t global_work_size[]{size, size}; cl_event event = nullptr; status = clEnqueueNDRangeKernel(queue, kernel, 2, nullptr, global_work_size, nullptr, 0, nullptr, &event); PTI_ASSERT(status == CL_SUCCESS); status = clFinish(queue); PTI_ASSERT(status == CL_SUCCESS); status = clEnqueueReadBuffer(queue, dev_c, CL_TRUE, 0, c.size() * sizeof(float), c.data(), 0, nullptr, nullptr); PTI_ASSERT(status == CL_SUCCESS); status = clEnqueueReadBuffer(queue, dev_info, CL_TRUE, 0, info.size() * sizeof(HardwareThreadInfo), const_cast<HardwareThreadInfo*>(info.data()), 0, nullptr, nullptr); PTI_ASSERT(status == CL_SUCCESS); status = clReleaseMemObject(dev_info); PTI_ASSERT(status == CL_SUCCESS); status = clReleaseMemObject(dev_a); PTI_ASSERT(status == CL_SUCCESS); status = clReleaseMemObject(dev_b); PTI_ASSERT(status == CL_SUCCESS); status = clReleaseMemObject(dev_c); PTI_ASSERT(status == CL_SUCCESS); cl_ulong start = 0, end = 0; status = clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_START, sizeof(cl_ulong), &start, nullptr); PTI_ASSERT(status == CL_SUCCESS); status = clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &end, nullptr); PTI_ASSERT(status == CL_SUCCESS); double time = static_cast<double>(end - start) / NSEC_IN_SEC; std::cout << "Matrix multiplication time: " << time << " sec" << std::endl; kernel_info.push_back(ProcessHardwareInfo(info)); return Check(c, expected_result); } static void Compute(cl_device_id device, const std::vector<float>& a, const std::vector<float>& b, std::vector<float>& c, unsigned size, unsigned repeat_count, float expected_result) { PTI_ASSERT(device != nullptr); cl_int status = CL_SUCCESS; cl_context context = clCreateContext(nullptr, 1, &device, nullptr, nullptr, &status); PTI_ASSERT(status == CL_SUCCESS && context != nullptr); cl_queue_properties props[] = { CL_QUEUE_PROPERTIES, CL_QUEUE_PROFILING_ENABLE, 0 }; cl_command_queue queue = clCreateCommandQueueWithProperties( context, device, props, &status); PTI_ASSERT(status == CL_SUCCESS && queue != nullptr); cl_program program = clCreateProgramWithSource(context, 1, &kKernelSource, nullptr, &status); PTI_ASSERT(status == CL_SUCCESS && program != nullptr); status = clBuildProgram(program, 1, &device, nullptr, nullptr, nullptr); PTI_ASSERT(status == CL_SUCCESS); cl_kernel kernel = clCreateKernel(program, "SmartGEMM", &status); PTI_ASSERT(status == CL_SUCCESS && kernel != nullptr); std::vector<HardwareKernelInfo> kernel_info; for (unsigned i = 0; i < repeat_count; ++i) { float eps = RunAndCheck(device, kernel, queue, a, b, c, size, expected_result, kernel_info); std::cout << "Results are " << ((eps < MAX_EPS) ? "" : "IN") << "CORRECT with accuracy: " << eps << std::endl; } status = clReleaseKernel(kernel); PTI_ASSERT(status == CL_SUCCESS); status = clReleaseProgram(program); PTI_ASSERT(status == CL_SUCCESS); status = clReleaseCommandQueue(queue); PTI_ASSERT(status == CL_SUCCESS); status = clReleaseContext(context); PTI_ASSERT(status == CL_SUCCESS); PrintInfo(kernel_info); } int main(int argc, char* argv[]) { cl_device_id device = utils::cl::GetIntelDevice(CL_DEVICE_TYPE_GPU); if (device == nullptr) { std::cout << "Unable to find target device" << std::endl; return 0; } unsigned size = 1024; if (argc > 1) { size = std::stoul(argv[1]); } unsigned repeat_count = 4; if (argc > 2) { repeat_count = std::stoul(argv[2]); } std::cout << "OpenCL Matrix Multiplication (matrix size: " << size << " x " << size << ", repeats " << repeat_count << " times)" << std::endl; std::cout << "Target device: " << utils::cl::GetDeviceName(device) << std::endl; std::vector<float> a(size * size, A_VALUE); std::vector<float> b(size * size, B_VALUE); std::vector<float> c(size * size, 0.0f); auto start = std::chrono::steady_clock::now(); float expected_result = A_VALUE * B_VALUE * size; Compute(device, a, b, c, size, repeat_count, expected_result); auto end = std::chrono::steady_clock::now(); std::chrono::duration<float> time = end - start; std::cout << "Total execution time: " << time.count() << " sec" << std::endl; return 0; }
13,616
4,831
#include <iostream> #include <string> void answer(const std::string& v) { std::cout << v << '\n'; } void solve(const std::string& s) { std::string t; for (const char c : s) { while (!t.empty() && t.back() < c) t.pop_back(); t.push_back(c); } answer(t); } int main() { std::string s; std::cin >> s; solve(s); return 0; }
392
158
#pragma once #include <Register/Utility.hpp> namespace Kvasir { //Core Platform Miscellaneous Control Module namespace McmPlasc{ ///<Crossbar switch (AXBS) slave configuration using Addr = Register::Address<0xe0080008,0xffffff00,0x00000000,unsigned>; ///Each bit in the ASC field indicates if there is a corresponding connection to the crossbar switch's slave input port. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> asc{}; } namespace McmPlamc{ ///<Crossbar switch (AXBS) master configuration using Addr = Register::Address<0xe008000a,0xffffff00,0x00000000,unsigned>; ///Each bit in the AMC field indicates if there is a corresponding connection to the AXBS master input port. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> amc{}; } namespace McmSramap{ ///<SRAM arbitration and protection using Addr = Register::Address<0xe008000c,0x88ffffff,0x00000000,unsigned>; ///SRAM_U arbitration priority enum class SramuapVal { v00=0x00000000, ///<Round robin v01=0x00000001, ///<Special round robin (favors SRAM backoor accesses over the processor) v10=0x00000002, ///<Fixed priority. Processor has highest, backdoor has lowest v11=0x00000003, ///<Fixed priority. Backdoor has highest, processor has lowest }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,24),Register::ReadWriteAccess,SramuapVal> sramuap{}; namespace SramuapValC{ constexpr Register::FieldValue<decltype(sramuap)::Type,SramuapVal::v00> v00{}; constexpr Register::FieldValue<decltype(sramuap)::Type,SramuapVal::v01> v01{}; constexpr Register::FieldValue<decltype(sramuap)::Type,SramuapVal::v10> v10{}; constexpr Register::FieldValue<decltype(sramuap)::Type,SramuapVal::v11> v11{}; } ///SRAM_U write protect constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> sramuwp{}; ///SRAM_L arbitration priority enum class SramlapVal { v00=0x00000000, ///<Round robin v01=0x00000001, ///<Special round robin (favors SRAM backoor accesses over the processor) v10=0x00000002, ///<Fixed priority. Processor has highest, backdoor has lowest v11=0x00000003, ///<Fixed priority. Backdoor has highest, processor has lowest }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,SramlapVal> sramlap{}; namespace SramlapValC{ constexpr Register::FieldValue<decltype(sramlap)::Type,SramlapVal::v00> v00{}; constexpr Register::FieldValue<decltype(sramlap)::Type,SramlapVal::v01> v01{}; constexpr Register::FieldValue<decltype(sramlap)::Type,SramlapVal::v10> v10{}; constexpr Register::FieldValue<decltype(sramlap)::Type,SramlapVal::v11> v11{}; } ///SRAM_L write protect constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> sramlwp{}; } namespace McmIsr{ ///<Interrupt status register using Addr = Register::Address<0xe0080010,0xfffffff9,0x00000000,unsigned>; ///Normal interrupt pending enum class IrqVal { v0=0x00000000, ///<No pending interrupt v1=0x00000001, ///<Due to the ETB counter expiring, a normal interrupt is pending }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,IrqVal> irq{}; namespace IrqValC{ constexpr Register::FieldValue<decltype(irq)::Type,IrqVal::v0> v0{}; constexpr Register::FieldValue<decltype(irq)::Type,IrqVal::v1> v1{}; } ///Non-maskable interrupt pending enum class NmiVal { v0=0x00000000, ///<No pending NMI v1=0x00000001, ///<Due to the ETB counter expiring, an NMI is pending }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,NmiVal> nmi{}; namespace NmiValC{ constexpr Register::FieldValue<decltype(nmi)::Type,NmiVal::v0> v0{}; constexpr Register::FieldValue<decltype(nmi)::Type,NmiVal::v1> v1{}; } } namespace McmEtbcc{ ///<ETB counter control register using Addr = Register::Address<0xe0080014,0xffffffc0,0x00000000,unsigned>; ///Counter enable enum class CntenVal { v0=0x00000000, ///<ETB counter disabled v1=0x00000001, ///<ETB counter enabled }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,CntenVal> cnten{}; namespace CntenValC{ constexpr Register::FieldValue<decltype(cnten)::Type,CntenVal::v0> v0{}; constexpr Register::FieldValue<decltype(cnten)::Type,CntenVal::v1> v1{}; } ///Response type enum class RsptVal { v00=0x00000000, ///<No response when the ETB count expires v01=0x00000001, ///<Generate a normal interrupt when the ETB count expires v10=0x00000002, ///<Generate an NMI when the ETB count expires v11=0x00000003, ///<Generate a debug halt when the ETB count expires }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,1),Register::ReadWriteAccess,RsptVal> rspt{}; namespace RsptValC{ constexpr Register::FieldValue<decltype(rspt)::Type,RsptVal::v00> v00{}; constexpr Register::FieldValue<decltype(rspt)::Type,RsptVal::v01> v01{}; constexpr Register::FieldValue<decltype(rspt)::Type,RsptVal::v10> v10{}; constexpr Register::FieldValue<decltype(rspt)::Type,RsptVal::v11> v11{}; } ///Reload request enum class RlrqVal { v0=0x00000000, ///<No effect v1=0x00000001, ///<Clears pending debug halt, NMI, or IRQ interrupt requests }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,RlrqVal> rlrq{}; namespace RlrqValC{ constexpr Register::FieldValue<decltype(rlrq)::Type,RlrqVal::v0> v0{}; constexpr Register::FieldValue<decltype(rlrq)::Type,RlrqVal::v1> v1{}; } ///ETM-to-TPIU disable enum class EtdisVal { v0=0x00000000, ///<ETM-to-TPIU trace path enabled v1=0x00000001, ///<ETM-to-TPIU trace path disabled }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,EtdisVal> etdis{}; namespace EtdisValC{ constexpr Register::FieldValue<decltype(etdis)::Type,EtdisVal::v0> v0{}; constexpr Register::FieldValue<decltype(etdis)::Type,EtdisVal::v1> v1{}; } ///ITM-to-TPIU disable enum class ItdisVal { v0=0x00000000, ///<ITM-to-TPIU trace path enabled v1=0x00000001, ///<ITM-to-TPIU trace path disabled }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,ItdisVal> itdis{}; namespace ItdisValC{ constexpr Register::FieldValue<decltype(itdis)::Type,ItdisVal::v0> v0{}; constexpr Register::FieldValue<decltype(itdis)::Type,ItdisVal::v1> v1{}; } } namespace McmEtbrl{ ///<ETB reload register using Addr = Register::Address<0xe0080018,0xfffff800,0x00000000,unsigned>; ///Byte count reload value constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,0),Register::ReadWriteAccess,unsigned> reload{}; } namespace McmEtbcnt{ ///<ETB counter value register using Addr = Register::Address<0xe008001c,0xfffff800,0x00000000,unsigned>; ///Byte count counter value constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> counter{}; } }
8,586
2,940
// Copyright John Maddock 2015. // Use, modification and distribution are 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) #ifndef SC_ # define SC_(x) static_cast<T>(BOOST_JOIN(x, L)) #endif static const boost::array<boost::array<typename table_type<T>::type, 4>, 221> ellint_rf_0yy = {{ {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.3980121253550848455436022016469058470638e-33), SC_(1.3980121253550848455436022016469058470638e-33), SC_(4.2011134328710924123568675963633830394318e+16) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.7494794261211793309535608228238390754549e-33), SC_(1.7494794261211793309535608228238390754549e-33), SC_(3.7554800327933727372706425945100239072845e+16) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(5.8726742677921440789517852801186900989207e-33), SC_(5.8726742677921440789517852801186900989207e-33), SC_(2.0497548397148665107630958693942691659345e+16) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.1309113765786506096540062665750175659960e-32), SC_(1.1309113765786506096540062665750175659960e-32), SC_(1.4770853493447921736098258541412996180989e+16) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.3891181146915726390794029968681816070943e-32), SC_(1.3891181146915726390794029968681816070943e-32), SC_(1.3327549053323440668722578635205718335450e+16) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(4.8536338069604874547155326932387107373984e-32), SC_(4.8536338069604874547155326932387107373984e-32), SC_(7.1299481820424706099755641475235630224298e+15) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(9.4336713037670874919513419574389437932846e-32), SC_(9.4336713037670874919513419574389437932846e-32), SC_(5.1142211858846531258743753567048129710036e+15) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.2040325324738106751721983353783124694865e-31), SC_(1.2040325324738106751721983353783124694865e-31), SC_(4.5268985959206997318160223917930173682065e+15) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(3.2192605509133527499735325052444797920840e-31), SC_(3.2192605509133527499735325052444797920840e-31), SC_(2.7684826947146390333934627850738946314261e+15) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(5.1598089430474145704786096554063029578715e-31), SC_(5.1598089430474145704786096554063029578715e-31), SC_(2.1867697952837347494353619419469972994415e+15) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(8.6580669655578129845734803403304892059082e-31), SC_(8.6580669655578129845734803403304892059082e-31), SC_(1.6881436782981871757856272617193320335881e+15) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.4410831025899022881322276426055071978088e-30), SC_(2.4410831025899022881322276426055071978088e-30), SC_(1.0053761877394506247990797590547509932445e+15) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(4.0342289035474833635882447965222031649226e-30), SC_(4.0342289035474833635882447965222031649226e-30), SC_(7.8205916286975768201582362951392158530002e+14) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(7.4997427315795683999931409064612184484767e-30), SC_(7.4997427315795683999931409064612184484767e-30), SC_(5.7358355870132192845036795529116466004622e+14) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.9524385645124032915396812389852876697084e-29), SC_(1.9524385645124032915396812389852876697084e-29), SC_(3.5549311045264652089376376128995610653495e+14) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(5.0307396633271274021036423836193003824470e-29), SC_(5.0307396633271274021036423836193003824470e-29), SC_(2.2146441588391558634818947164424977714924e+14) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(9.8828830280863654554637712926778439923276e-29), SC_(9.8828830280863654554637712926778439923276e-29), SC_(1.5800762651540760009290282618266899294729e+14) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.0159108358364658025376430240459520615557e-28), SC_(2.0159108358364658025376430240459520615557e-28), SC_(1.1063287981858817479953084254076726440032e+14) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(3.9680608719690755813060883143357162268402e-28), SC_(3.9680608719690755813060883143357162268402e-28), SC_(7.8855268369770930868571674694699148129542e+13) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(7.9474558416608700456074110588635447509500e-28), SC_(7.9474558416608700456074110588635447509500e-28), SC_(5.5719320977924261881688450263574951885748e+13) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(9.3511217333788972162109341828680044038835e-28), SC_(9.3511217333788972162109341828680044038835e-28), SC_(5.1367451751815636329822746455279713646875e+13) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.7882427361992658143258966170331945402566e-27), SC_(2.7882427361992658143258966170331945402566e-27), SC_(2.9747781801253276176729006565683786122303e+13) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(6.3673277743463290223091457894565066834118e-27), SC_(6.3673277743463290223091457894565066834118e-27), SC_(1.9685265364185948535157211661215046822256e+13) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.2802620846058105842978295818115658417924e-26), SC_(1.2802620846058105842978295818115658417924e-26), SC_(1.3882587999565971273272148568313421369529e+13) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.5295786350139981648664921989981478850189e-26), SC_(2.5295786350139981648664921989981478850189e-26), SC_(9.8763343682942275756205942653797662676068e+12) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.8689244097271181025975906229169039426616e-26), SC_(2.8689244097271181025975906229169039426616e-26), SC_(9.2738554900908167203450178512952653860378e+12) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(7.6792108552998581016945261284770797094792e-26), SC_(7.6792108552998581016945261284770797094792e-26), SC_(5.6684142446104558263603119935472584223454e+12) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.8591977352242616487743079115958899226631e-25), SC_(1.8591977352242616487743079115958899226631e-25), SC_(3.6429825099820212175947594284015184803895e+12) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(3.7228919776082830648394626760138917268353e-25), SC_(3.7228919776082830648394626760138917268353e-25), SC_(2.5744215342633328942805828125611602544858e+12) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(5.3643882618567678488066742377790444354368e-25), SC_(5.3643882618567678488066742377790444354368e-25), SC_(2.1446665353906586866868265233747971049878e+12) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(9.4454615474045197976285755041988786463725e-25), SC_(9.4454615474045197976285755041988786463725e-25), SC_(1.6162490583365811137699525978529227826072e+12) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.6622742888463273191629024333782773358015e-24), SC_(1.6622742888463273191629024333782773358015e-24), SC_(1.2183400849218288532388652854576933184887e+12) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(4.7042126583826492571881501298937085578378e-24), SC_(4.7042126583826492571881501298937085578378e-24), SC_(7.2422982183606624987687287777721105859382e+11) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(7.3616720556278283564328024996187890133248e-24), SC_(7.3616720556278283564328024996187890133248e-24), SC_(5.7893744966269982332281168189872602674103e+11) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.5354544851880595018243965945098708503203e-23), SC_(2.5354544851880595018243965945098708503203e-23), SC_(3.1195501204171640382171025842375559943751e+11) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(4.3404174612542203037430892437393593896733e-23), SC_(4.3404174612542203037430892437393593896733e-23), SC_(2.3842628176476240945263649326315534217229e+11) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(9.4878661342759511104190386438428025939196e-23), SC_(9.4878661342759511104190386438428025939196e-23), SC_(1.6126332229905406201327391876664749008560e+11) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.9888655119526487934053853251590432416052e-22), SC_(1.9888655119526487934053853251590432416052e-22), SC_(1.1138255311266631150972773089885656032494e+11) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(4.1493861471394310727732518591110572048208e-22), SC_(4.1493861471394310727732518591110572048208e-22), SC_(7.7113062404087698433811707306889246281285e+10) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(6.3682587603765391777064795220987536428225e-22), SC_(6.3682587603765391777064795220987536428225e-22), SC_(6.2245724495240543440623392598135079959691e+10) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.4024669571251856037905211219835033276127e-21), SC_(1.4024669571251856037905211219835033276127e-21), SC_(4.1944358640883529139121930351099815544535e+10) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(3.0458090701845262557668142034197900080983e-21), SC_(3.0458090701845262557668142034197900080983e-21), SC_(2.8462204794437549144654032012692583134977e+10) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(3.5091263406486883653093633225750203052939e-21), SC_(3.5091263406486883653093633225750203052939e-21), SC_(2.6516754922661909029607830047227924204839e+10) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(9.2244855466440840911323921502695810659134e-21), SC_(9.2244855466440840911323921502695810659134e-21), SC_(1.6354934142720324169448881162436143268725e+10) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.5060373697831631136892266593918510153571e-20), SC_(2.5060373697831631136892266593918510153571e-20), SC_(9.9226141924086718379281058590373925860419e+09) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(3.2849267904344328986699199160459450297367e-20), SC_(3.2849267904344328986699199160459450297367e-20), SC_(8.6667651733785352367471433771143838329392e+09) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.0484196316561675708982576474270764776975e-19), SC_(1.0484196316561675708982576474270764776975e-19), SC_(4.8512349090701506431913612732538796091145e+09) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.8229333961140025508894553507577285245134e-19), SC_(1.8229333961140025508894553507577285245134e-19), SC_(3.6790397179943982356440079442363105882313e+09) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(3.6401757896136402713757954097140157045942e-19), SC_(3.6401757896136402713757954097140157045942e-19), SC_(2.6035066936056491931367579338946949032797e+09) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(6.0660607797570928288862987520779768146895e-19), SC_(6.0660607797570928288862987520779768146895e-19), SC_(2.0168170227020895599392377803929816915151e+09) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.5245964393311865802196902741627582145156e-18), SC_(1.5245964393311865802196902741627582145156e-18), SC_(1.2721620221921002600233735750816295018705e+09) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(3.0195417624247973304059400323495765405823e-18), SC_(3.0195417624247973304059400323495765405823e-18), SC_(9.0396029817777994373227376201042335410798e+08) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(6.0477044011936223152393898860879062340246e-18), SC_(6.0477044011936223152393898860879062340246e-18), SC_(6.3874071369279596499575470045503802273474e+08) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.0233193632958864486594274811892546495073e-17), SC_(1.0233193632958864486594274811892546495073e-17), SC_(4.9103707156177871496158616957815692215598e+08) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.9321026667662503885011804349858266505180e-17), SC_(1.9321026667662503885011804349858266505180e-17), SC_(3.5735904351559194482707033465014385210959e+08) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(3.9470861839323539803359164324092489550821e-17), SC_(3.9470861839323539803359164324092489550821e-17), SC_(2.5002392715513164130641809006634693728021e+08) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(9.1897463183816027049166663687174150254577e-17), SC_(9.1897463183816027049166663687174150254577e-17), SC_(1.6385817577550454022059551703002701492381e+08) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.3032517747881629428807759296660151449032e-16), SC_(1.3032517747881629428807759296660151449032e-16), SC_(1.3759597010412717412333655360439245056417e+08) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.6005563194954166295058683999741333536804e-16), SC_(2.6005563194954166295058683999741333536804e-16), SC_(9.7406232342383903896799298674395774455834e+07) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(5.7816541979623537611532313462703314144164e-16), SC_(5.7816541979623537611532313462703314144164e-16), SC_(6.5327166362641758833061300258289268510725e+07) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.5152733329692157082657644195933244191110e-15), SC_(1.5152733329692157082657644195933244191110e-15), SC_(4.0352866155020383319774222880808714672319e+07) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(3.1926103267695439547058100515641854144633e-15), SC_(3.1926103267695439547058100515641854144633e-15), SC_(2.7800135966370728218087169205661553164089e+07) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(3.6658061297861060934266674848913680762053e-15), SC_(3.6658061297861060934266674848913680762053e-15), SC_(2.5943892161934870935090045349620610701266e+07) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(9.3546521982672270478786913372459821403027e-15), SC_(9.3546521982672270478786913372459821403027e-15), SC_(1.6240748999770288374425176465875421177501e+07) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.8146163011881905058331199143140111118555e-14), SC_(1.8146163011881905058331199143140111118555e-14), SC_(1.1660776544886839296295225583995742651057e+07) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(5.3217629955581990941482217749580740928650e-14), SC_(5.3217629955581990941482217749580740928650e-14), SC_(6.8091376281905587429856036361000129593602e+06) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(5.9467947059743675453091782401315867900848e-14), SC_(5.9467947059743675453091782401315867900848e-14), SC_(6.4413723389236104206794992826588993910726e+06) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.3063909762994763141819021257106214761734e-13), SC_(1.3063909762994763141819021257106214761734e-13), SC_(4.3459356461191084104143489741712274663344e+06) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.4945887369676178479949157917872071266174e-13), SC_(2.4945887369676178479949157917872071266174e-13), SC_(3.1449981798854718593189457928155871496500e+06) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(9.0679720676778430288322851993143558502197e-13), SC_(9.0679720676778430288322851993143558502197e-13), SC_(1.6495473643217726836011224166830953097521e+06) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.6584251333329191879784048069268465042114e-12), SC_(1.6584251333329191879784048069268465042114e-12), SC_(1.2197531310762298663189586952256648433339e+06) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(3.3140226673999961803929181769490242004395e-12), SC_(3.3140226673999961803929181769490242004395e-12), SC_(8.6286358235112858037296533013261636911475e+05) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(6.1657502020695531541605305392295122146606e-12), SC_(6.1657502020695531541605305392295122146606e-12), SC_(6.3259668844539328405151023722522566654293e+05) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(8.1867811141389523754696710966527462005615e-12), SC_(8.1867811141389523754696710966527462005615e-12), SC_(5.4898855107324420145865323923786368221660e+05) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.9166314368934678213918232358992099761963e-11), SC_(1.9166314368934678213918232358992099761963e-11), SC_(3.5879846253791511509734305905673752265012e+05) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(5.1331883188510118998237885534763336181641e-11), SC_(5.1331883188510118998237885534763336181641e-11), SC_(2.1924327376165153483968547637051596635812e+05) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.1351786177726808091392740607261657714844e-10), SC_(1.1351786177726808091392740607261657714844e-10), SC_(1.4743064853074308777017011514773486132225e+05) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.7352735914855088594777043908834457397461e-10), SC_(1.7352735914855088594777043908834457397461e-10), SC_(1.1924382494376618510264692109547130643219e+05) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.4085067273915683472296223044395446777344e-10), SC_(2.4085067273915683472296223044395446777344e-10), SC_(1.0121524837465215858139133760308966307600e+05) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(7.7467654513441175367916002869606018066406e-10), SC_(7.7467654513441175367916002869606018066406e-10), SC_(5.6436448157919138830942838835097023554536e+04) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.3399348297582491795765236020088195800781e-09), SC_(1.3399348297582491795765236020088195800781e-09), SC_(4.2911929132846361808468975183496149896449e+04) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.0971455683138628955930471420288085937500e-09), SC_(2.0971455683138628955930471420288085937500e-09), SC_(3.4300905777107095945813103793274526878997e+04) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(5.1467061723542428808286786079406738281250e-09), SC_(5.1467061723542428808286786079406738281250e-09), SC_(2.1895516259311051317340055158304803232015e+04) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(9.0167588950862409546971321105957031250000e-09), SC_(9.0167588950862409546971321105957031250000e-09), SC_(1.6542252613068418401216429250767931535092e+04) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.6308249800877092638984322547912597656250e-08), SC_(2.6308249800877092638984322547912597656250e-08), SC_(9.6844263027984243181674748885446411463737e+03) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(3.1328681870945729315280914306640625000000e-08), SC_(3.1328681870945729315280914306640625000000e-08), SC_(8.8746005771146423099742233788623216837125e+03) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.0700225061555102001875638961791992187500e-07), SC_(1.0700225061555102001875638961791992187500e-07), SC_(4.8020139880831732646113990435108587351967e+03) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.2355337730696192011237144470214843750000e-07), SC_(1.2355337730696192011237144470214843750000e-07), SC_(4.4688169580879146103694019887136958256866e+03) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.8297245080466382205486297607421875000000e-07), SC_(2.8297245080466382205486297607421875000000e-07), SC_(2.9528936025402861368176294291215913886846e+03) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(6.7173527895647566765546798706054687500000e-07), SC_(6.7173527895647566765546798706054687500000e-07), SC_(1.9165528435168479514042609856706555957405e+03) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.4207498679752461612224578857421875000000e-06), SC_(1.4207498679752461612224578857421875000000e-06), SC_(1.3178350824870658973826259556668867059341e+03) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.7808937375084497034549713134765625000000e-06), SC_(2.7808937375084497034549713134765625000000e-06), SC_(9.4194963027140372863412359979780612017033e+02) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(5.5144737416412681341171264648437500000000e-06), SC_(5.5144737416412681341171264648437500000000e-06), SC_(6.6891023399250656952954919986801827106966e+02) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.1349249689374119043350219726562500000000e-05), SC_(1.1349249689374119043350219726562500000000e-05), SC_(4.6626874165627786835543372734029714240102e+02) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.5120738428086042404174804687500000000000e-05), SC_(2.5120738428086042404174804687500000000000e-05), SC_(3.1340338027366868091134639954749841302458e+02) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(5.4747768444940447807312011718750000000000e-05), SC_(5.4747768444940447807312011718750000000000e-05), SC_(2.1229348485237662650108789091001961742416e+02) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.0433135321363806724548339843750000000000e-04), SC_(1.0433135321363806724548339843750000000000e-04), SC_(1.5378446171663395186552764113230005366247e+02) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.3448176216334104537963867187500000000000e-04), SC_(2.3448176216334104537963867187500000000000e-04), SC_(1.0258062538342855754510901779054580903026e+02) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(4.2839022353291511535644531250000000000000e-04), SC_(4.2839022353291511535644531250000000000000e-04), SC_(7.5892717073165503057533662308345853916021e+01) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(8.8258343748748302459716796875000000000000e-04), SC_(8.8258343748748302459716796875000000000000e-04), SC_(5.2873978537413327959151412094712808682997e+01) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.2461179867386817932128906250000000000000e-03), SC_(1.2461179867386817932128906250000000000000e-03), SC_(4.4497979811000542882612951169881102451928e+01) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(3.3315904438495635986328125000000000000000e-03), SC_(3.3315904438495635986328125000000000000000e-03), SC_(2.7214106070655758377392296022637285699244e+01) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(6.5613389015197753906250000000000000000000e-03), SC_(6.5613389015197753906250000000000000000000e-03), SC_(1.9392046413019165083845775475714305408618e+01) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(7.8345164656639099121093750000000000000000e-03), SC_(7.8345164656639099121093750000000000000000e-03), SC_(1.7746543510522016088738427144628998047515e+01) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.5860905647277832031250000000000000000000e-02), SC_(2.5860905647277832031250000000000000000000e-02), SC_(9.7678281924063500221602486899234887546712e+00) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(5.3459495306015014648437500000000000000000e-02), SC_(5.3459495306015014648437500000000000000000e-02), SC_(6.7937169678857219280047269070189587702236e+00) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(7.2663217782974243164062500000000000000000e-02), SC_(7.2663217782974243164062500000000000000000e-02), SC_(5.8272354212273738232874189986287049899336e+00) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.0549511909484863281250000000000000000000e-01), SC_(2.0549511909484863281250000000000000000000e-01), SC_(3.4651267208085065592082899698426957513267e+00) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.7974939346313476562500000000000000000000e-01), SC_(2.7974939346313476562500000000000000000000e-01), SC_(2.9698553717699451833875749067031175709028e+00) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(7.2801637649536132812500000000000000000000e-01), SC_(7.2801637649536132812500000000000000000000e-01), SC_(1.8409809843443633527552512241717805473321e+00) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.4983639717102050781250000000000000000000e+00), SC_(1.4983639717102050781250000000000000000000e+00), SC_(1.2832498320938247118637885181417739497472e+00) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(3.5478343963623046875000000000000000000000e+00), SC_(3.5478343963623046875000000000000000000000e+00), SC_(8.3394653217071146358397859025671880495235e-01) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(7.8389759063720703125000000000000000000000e+00), SC_(7.8389759063720703125000000000000000000000e+00), SC_(5.6103533172981726106212407438292675623528e-01) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.2590034484863281250000000000000000000000e+01), SC_(1.2590034484863281250000000000000000000000e+01), SC_(4.4269683513721801669343506625171505405743e-01) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.1446166992187500000000000000000000000000e+01), SC_(2.1446166992187500000000000000000000000000e+01), SC_(3.3919155848627308154366912596917356853942e-01) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(6.0056228637695312500000000000000000000000e+01), SC_(6.0056228637695312500000000000000000000000e+01), SC_(2.0269397932058961197095590077264964102522e-01) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.0145712280273437500000000000000000000000e+02), SC_(1.0145712280273437500000000000000000000000e+02), SC_(1.5594756787311734170509575118114785874767e-01) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.3144647216796875000000000000000000000000e+02), SC_(2.3144647216796875000000000000000000000000e+02), SC_(1.0325107792566896871233492968741046048822e-01) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(3.1329577636718750000000000000000000000000e+02), SC_(3.1329577636718750000000000000000000000000e+02), SC_(8.8744737062649603088644197774752944853419e-02) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(5.2110009765625000000000000000000000000000e+02), SC_(5.2110009765625000000000000000000000000000e+02), SC_(6.8811226645352375754842430752554384679394e-02) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.7932973632812500000000000000000000000000e+03), SC_(1.7932973632812500000000000000000000000000e+03), SC_(3.7093150538065676749368524707498372997278e-02) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(3.7299111328125000000000000000000000000000e+03), SC_(3.7299111328125000000000000000000000000000e+03), SC_(2.5719980484102840723278304951793121062558e-02) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(5.1408691406250000000000000000000000000000e+03), SC_(5.1408691406250000000000000000000000000000e+03), SC_(2.1907943006838348450477277662553612327578e-02) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.4916328125000000000000000000000000000000e+04), SC_(1.4916328125000000000000000000000000000000e+04), SC_(1.2861419768853935982239068956576343130392e-02) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.4673601562500000000000000000000000000000e+04), SC_(2.4673601562500000000000000000000000000000e+04), SC_(1.0000082970968746467282203495421779652220e-02) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(6.3572343750000000000000000000000000000000e+04), SC_(6.3572343750000000000000000000000000000000e+04), SC_(6.2299672766608239363524933472154053536055e-03) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.1135068750000000000000000000000000000000e+05), SC_(1.1135068750000000000000000000000000000000e+05), SC_(4.7073167842595312017012760895460652350443e-03) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.8516100000000000000000000000000000000000e+05), SC_(1.8516100000000000000000000000000000000000e+05), SC_(3.6504391898387560654266856752676771252279e-03) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(4.9568887500000000000000000000000000000000e+05), SC_(4.9568887500000000000000000000000000000000e+05), SC_(2.2310807601985745932174552260221013072244e-03) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(7.4614825000000000000000000000000000000000e+05), SC_(7.4614825000000000000000000000000000000000e+05), SC_(1.8184749154834315363535644723738773764725e-03) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.0544660000000000000000000000000000000000e+06), SC_(2.0544660000000000000000000000000000000000e+06), SC_(1.0958986648871014422155267746529841592224e-03) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(3.3155060000000000000000000000000000000000e+06), SC_(3.3155060000000000000000000000000000000000e+06), SC_(8.6267054139915274161303043297420285872437e-04) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(6.4894920000000000000000000000000000000000e+06), SC_(6.4894920000000000000000000000000000000000e+06), SC_(6.1661562615374795282124164577791944127602e-04) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(9.7144880000000000000000000000000000000000e+06), SC_(9.7144880000000000000000000000000000000000e+06), SC_(5.0397607391562830048751272628132105595723e-04) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.9102944000000000000000000000000000000000e+07), SC_(1.9102944000000000000000000000000000000000e+07), SC_(3.5939309249609764628944404482658719570962e-04) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(5.9113888000000000000000000000000000000000e+07), SC_(5.9113888000000000000000000000000000000000e+07), SC_(2.0430317449428664563061218033332752522124e-04) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(7.7127808000000000000000000000000000000000e+07), SC_(7.7127808000000000000000000000000000000000e+07), SC_(1.7886047619002652664398933933155696529025e-04) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.6510873600000000000000000000000000000000e+08), SC_(1.6510873600000000000000000000000000000000e+08), SC_(1.2224605437898073313859184064917154950367e-04) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(3.3755980800000000000000000000000000000000e+08), SC_(3.3755980800000000000000000000000000000000e+08), SC_(8.5495747043194846465579139004114162994262e-05) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(9.7159372800000000000000000000000000000000e+08), SC_(9.7159372800000000000000000000000000000000e+08), SC_(5.0393848466082725043016409698477440556268e-05) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.9764551680000000000000000000000000000000e+09), SC_(1.9764551680000000000000000000000000000000e+09), SC_(3.5332664792276628674815986589190753109051e-05) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(4.2703175680000000000000000000000000000000e+09), SC_(4.2703175680000000000000000000000000000000e+09), SC_(2.4037527298914057900881914048597579860304e-05) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(5.3871001600000000000000000000000000000000e+09), SC_(5.3871001600000000000000000000000000000000e+09), SC_(2.1401408263394570165259854795562126185137e-05) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.1445641216000000000000000000000000000000e+10), SC_(1.1445641216000000000000000000000000000000e+10), SC_(1.4682493356419926126827769100992277400348e-05) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(3.1169175552000000000000000000000000000000e+10), SC_(3.1169175552000000000000000000000000000000e+10), SC_(8.8972792084979337405342027424798394698550e-06) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(4.4661866496000000000000000000000000000000e+10), SC_(4.4661866496000000000000000000000000000000e+10), SC_(7.4327828074730100378586223747836646793010e-06) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(8.5454389248000000000000000000000000000000e+10), SC_(8.5454389248000000000000000000000000000000e+10), SC_(5.3734435367618667468389251644251321331587e-06) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.3929971712000000000000000000000000000000e+11), SC_(1.3929971712000000000000000000000000000000e+11), SC_(4.2086688908376450260307184597278656803804e-06) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(5.3031193804800000000000000000000000000000e+11), SC_(5.3031193804800000000000000000000000000000e+11), SC_(2.1570200159538943947160056500073734233350e-06) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(6.6918337740800000000000000000000000000000e+11), SC_(6.6918337740800000000000000000000000000000e+11), SC_(1.9202037114544938447891033653540257975927e-06) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.4843227668480000000000000000000000000000e+12), SC_(1.4843227668480000000000000000000000000000e+12), SC_(1.2893051061136271356500478930295477183115e-06) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(4.1943386030080000000000000000000000000000e+12), SC_(4.1943386030080000000000000000000000000000e+12), SC_(7.6698723012702169752128824402850542460624e-07) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(5.2626813091840000000000000000000000000000e+12), SC_(5.2626813091840000000000000000000000000000e+12), SC_(6.8472524700545641607678970799558241938200e-07) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.6259294953472000000000000000000000000000e+13), SC_(1.6259294953472000000000000000000000000000e+13), SC_(3.8955521466903579856657308863522563392596e-07) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.2009299861504000000000000000000000000000e+13), SC_(2.2009299861504000000000000000000000000000e+13), SC_(3.3482414100461508504128414631274893927621e-07) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(6.8786065506304000000000000000000000000000e+13), SC_(6.8786065506304000000000000000000000000000e+13), SC_(1.8939549411952226166261029822808148439374e-07) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.1371902350131200000000000000000000000000e+14), SC_(1.1371902350131200000000000000000000000000e+14), SC_(1.4730019309043810704249274558517913287536e-07) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.5035760310681600000000000000000000000000e+14), SC_(2.5035760310681600000000000000000000000000e+14), SC_(9.9274906000734681844918478203921969419230e-08) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(4.1469385637888000000000000000000000000000e+14), SC_(4.1469385637888000000000000000000000000000e+14), SC_(7.7135815671781622483609276277678711342941e-08) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.1188403227852800000000000000000000000000e+15), SC_(1.1188403227852800000000000000000000000000e+15), SC_(4.6960836264618260132243015582621438058334e-08) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.5218330776371200000000000000000000000000e+15), SC_(1.5218330776371200000000000000000000000000e+15), SC_(4.0265803268155909446337842717162402264302e-08) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.4040102334300160000000000000000000000000e+15), SC_(2.4040102334300160000000000000000000000000e+15), SC_(3.2036991131321235344454278685758143400897e-08) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(8.2453193010708480000000000000000000000000e+15), SC_(8.2453193010708480000000000000000000000000e+15), SC_(1.7298806381497319415418090256890851524168e-08) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.6155287555670016000000000000000000000000e+16), SC_(1.6155287555670016000000000000000000000000e+16), SC_(1.2358408051655442361552826818036192154626e-08) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.8557572558553088000000000000000000000000e+16), SC_(2.8557572558553088000000000000000000000000e+16), SC_(9.2952105704018897780144498940392455512880e-09) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(5.7448039442284544000000000000000000000000e+16), SC_(5.7448039442284544000000000000000000000000e+16), SC_(6.5536353181458368827477149476652939709597e-09) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.1166935585443020800000000000000000000000e+17), SC_(1.1166935585443020800000000000000000000000e+17), SC_(4.7005954031214617466216840094271193438949e-09) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.4972259272897331200000000000000000000000e+17), SC_(2.4972259272897331200000000000000000000000e+17), SC_(3.1433371067855328702420607565739005692462e-09) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(5.5259337852138291200000000000000000000000e+17), SC_(5.5259337852138291200000000000000000000000e+17), SC_(2.1130853482062694977990166236902005792906e-09) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(9.7723521452893798400000000000000000000000e+17), SC_(9.7723521452893798400000000000000000000000e+17), SC_(1.5889869222376992607670446319231504690358e-09) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.4824715277303808000000000000000000000000e+18), SC_(1.4824715277303808000000000000000000000000e+18), SC_(1.2901098660477035102345047272370563623399e-09) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(3.8734002442595205120000000000000000000000e+18), SC_(3.8734002442595205120000000000000000000000e+18), SC_(7.9813009907622332835564651054616044455088e-10) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(8.1036557834067640320000000000000000000000e+18), SC_(8.1036557834067640320000000000000000000000e+18), SC_(5.5179706273033215046095113457550819723747e-10) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.2841886794098147328000000000000000000000e+19), SC_(1.2841886794098147328000000000000000000000e+19), SC_(4.3833430262278918282653122961008145231052e-10) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(3.2350587576425381888000000000000000000000e+19), SC_(3.2350587576425381888000000000000000000000e+19), SC_(2.7617145657875482648326811246703048528181e-10) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(5.7611295478532538368000000000000000000000e+19), SC_(5.7611295478532538368000000000000000000000e+19), SC_(2.0695029817579195271331288004212096798881e-10) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.0185889793465699532800000000000000000000e+20), SC_(1.0185889793465699532800000000000000000000e+20), SC_(1.5563970197496983398047078177765990012080e-10) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.7827935411160009932800000000000000000000e+20), SC_(1.7827935411160009932800000000000000000000e+20), SC_(1.1764388312446528782220821981355647542597e-10) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(4.6273923221278425088000000000000000000000e+20), SC_(4.6273923221278425088000000000000000000000e+20), SC_(7.3021662466341990452628446338437164058585e-11) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(9.0160094215120355328000000000000000000000e+20), SC_(9.0160094215120355328000000000000000000000e+20), SC_(5.2313370077676905925803870205520990111100e-11) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.2701445734077667737600000000000000000000e+21), SC_(1.2701445734077667737600000000000000000000e+21), SC_(4.4075099205723903014008875100098995274402e-11) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(3.3155928298666191749120000000000000000000e+21), SC_(3.3155928298666191749120000000000000000000e+21), SC_(2.7279680599751090263821091591749259332758e-11) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(4.9771373655898078576640000000000000000000e+21), SC_(4.9771373655898078576640000000000000000000e+21), SC_(2.2265377533437408356815079273892635128930e-11) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.2776477955669473886208000000000000000000e+22), SC_(1.2776477955669473886208000000000000000000e+22), SC_(1.3896783833206721691429219856436838792758e-11) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.8915946875483827732480000000000000000000e+22), SC_(2.8915946875483827732480000000000000000000e+22), SC_(9.2374301605030297330760223434451077501749e-12) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(6.0175170680284052979712000000000000000000e+22), SC_(6.0175170680284052979712000000000000000000e+22), SC_(6.4034085514030491342072262868282568410087e-12) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.3443007097640605397811200000000000000000e+23), SC_(1.3443007097640605397811200000000000000000e+23), SC_(4.2842190014147909278365079758466714171612e-12) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.0496508805231257269043200000000000000000e+23), SC_(2.0496508805231257269043200000000000000000e+23), SC_(3.4696041635771519981628347635085067687969e-12) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(5.8451880892949689322700800000000000000000e+23), SC_(5.8451880892949689322700800000000000000000e+23), SC_(2.0545685299806069727577846167337411619675e-12) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.1877492456483867611627520000000000000000e+24), SC_(1.1877492456483867611627520000000000000000e+24), SC_(1.4413103171434762196802784234663166554758e-12) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.3659727517469077458124800000000000000000e+24), SC_(1.3659727517469077458124800000000000000000e+24), SC_(1.3439987318720801138572158525504643077758e-12) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.7912598561413239479992320000000000000000e+24), SC_(2.7912598561413239479992320000000000000000e+24), SC_(9.4019890754089219280160210161534082331989e-13) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(7.5863641567366151374110720000000000000000e+24), SC_(7.5863641567366151374110720000000000000000e+24), SC_(5.7029955696704363657183391096410506386339e-13) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.3490721907030264366759936000000000000000e+25), SC_(1.3490721907030264366759936000000000000000e+25), SC_(4.2766359466790852949170778955420243416387e-13) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.8422143749589281569505280000000000000000e+25), SC_(2.8422143749589281569505280000000000000000e+25), SC_(2.9463983403307002013779422234083601185818e-13) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(5.3668403805728358185041920000000000000000e+25), SC_(5.3668403805728358185041920000000000000000e+25), SC_(2.1441765284755659177838528477825589060259e-13) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(7.8292113919495847997865984000000000000000e+25), SC_(7.8292113919495847997865984000000000000000e+25), SC_(1.7752555021371039101417870902094653927125e-13) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.6723325902934740461577830400000000000000e+26), SC_(2.6723325902934740461577830400000000000000e+26), SC_(9.6089210029732720631668249221640828810492e-14) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(4.1381935158038852363563827200000000000000e+26), SC_(4.1381935158038852363563827200000000000000e+26), SC_(7.7217276387173339316228602139361276696830e-14) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(8.5948309609429296171135795200000000000000e+26), SC_(8.5948309609429296171135795200000000000000e+26), SC_(5.3579814689053488365105049803597755182814e-14) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.4387120406003935998650613760000000000000e+27), SC_(1.4387120406003935998650613760000000000000e+27), SC_(4.1412641987135004125398992677505859620162e-14) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(4.7722405758868522542091468800000000000000e+27), SC_(4.7722405758868522542091468800000000000000e+27), SC_(2.2738337720061142590311839557466375850359e-14) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(8.8848657238129553346144501760000000000000e+27), SC_(8.8848657238129553346144501760000000000000e+27), SC_(1.6664582690561207345997448514984065249335e-14) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.4222615588981551190220210176000000000000e+28), SC_(1.4222615588981551190220210176000000000000e+28), SC_(1.3171345471471175550632318634078278410483e-14) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.5971287269650318385179787264000000000000e+28), SC_(2.5971287269650318385179787264000000000000e+28), SC_(9.7470487684575495227114000002323253771025e-15) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(7.3788279667987478486078980096000000000000e+28), SC_(7.3788279667987478486078980096000000000000e+28), SC_(5.7826403788494239476913638776944597818384e-15) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.2110285949621213703269305548800000000000e+29), SC_(1.2110285949621213703269305548800000000000e+29), SC_(4.5138038028128852153442693393179442153791e-15) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.5675627459944222489782622617600000000000e+29), SC_(2.5675627459944222489782622617600000000000e+29), SC_(3.0999832282890590126942418598861471207285e-15) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(3.6940874261654810399932311142400000000000e+29), SC_(3.6940874261654810399932311142400000000000e+29), SC_(2.5844390371396999635360049725791733762238e-15) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(7.0959714371010081353141059584000000000000e+29), SC_(7.0959714371010081353141059584000000000000e+29), SC_(1.8647213689217269093280383995429126476546e-15) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.0307529873257442803568470917120000000000e+30), SC_(2.0307529873257442803568470917120000000000e+30), SC_(1.1022784748326613472643766950915870266214e-15) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(3.7318536643073322480964646993920000000000e+30), SC_(3.7318536643073322480964646993920000000000e+30), SC_(8.1312548741077384914760734681077184318119e-16) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(6.4040234014314612931042308259840000000000e+30), SC_(6.4040234014314612931042308259840000000000e+30), SC_(6.2071668848445719575214289055934381666647e-16) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.3591440405379759208451461349376000000000e+31), SC_(1.3591440405379759208451461349376000000000e+31), SC_(4.2607606128595662177290950502474781053227e-16) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(3.3548706991994435886603137187840000000000e+31), SC_(3.3548706991994435886603137187840000000000e+31), SC_(2.7119519078084773713513001089799261003714e-16) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(6.2057760084058088674091939659776000000000e+31), SC_(6.2057760084058088674091939659776000000000e+31), SC_(1.9939847338616881135469544661367878643461e-16) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.3704533965093724230190214466764800000000e+32), SC_(1.3704533965093724230190214466764800000000e+32), SC_(1.3417998569903162736257142762866916683070e-16) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(2.7845325737156862002881598429593600000000e+32), SC_(2.7845325737156862002881598429593600000000e+32), SC_(9.4133395764747646992674799662015469129317e-17) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(5.6730753221070809445480004793139200000000e+32), SC_(5.6730753221070809445480004793139200000000e+32), SC_(6.5949362552637029247447266438533130992429e-17) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.2905320649443607278078011679703040000000e+33), SC_(1.2905320649443607278078011679703040000000e+33), SC_(4.3725569761634527092424992635267307715942e-17) }}, {{ SC_(0.0000000000000000000000000000000000000000e+00), SC_(1.8829105135731812542623926420766720000000e+33), SC_(1.8829105135731812542623926420766720000000e+33), SC_(3.6199705454105465095323814245693615037155e-17) }} }}; //#undef SC_
49,917
44,586
/* Developers: DSOR Team -> @irt.ist.pt Instituto Superior Tecnico Description: Please check the documentation of this package for more info. */ #include "SensorSim.h" /* ####################################################################################################################### @.@ CONSTRUCTOR: put all dirty work of initializations here Note the odd syntax: have to pass nodehandle pointer into constructor for constructor to build subscribers, etc ####################################################################################################################### */ SensorSim::SensorSim(ros::NodeHandle *nh, ros::NodeHandle *nh_private):nh_(*nh), nh_private_(*nh_private){ ROS_INFO("in class constructor of SensorSim"); initializeSubscribers(); initializePublishers(); initializeServices(); loadParams(); initializeTimer(); } /* ####################################################################################################################### @.@ Destructor ####################################################################################################################### */ SensorSim::~SensorSim() { // +.+ shutdown publishers pub_gnss.shutdown(); pub_range.shutdown(); pub_model.shutdown(); pub_position.shutdown(); pub_velocity.shutdown(); pub_orientation.shutdown(); pub_thrusters.shutdown(); pub_thrustStatus.shutdown(); // +.+ shutdown subscribers sub_odometry.shutdown(); sub_thruster.shutdown(); // +.+ shutdown node nh_.shutdown(); } /* ####################################################################################################################### @.@ Member Helper function to set up subscribers; note odd syntax: &SensorSim::subscriberCallback is a pointer to a member function of SensorSim "this" keyword is required, to refer to the current instance of SensorSim ####################################################################################################################### */ void SensorSim::initializeSubscribers() { ROS_INFO("Initializing Subscribers for SensorSim"); std::vector<std::string> ros_subs = MedusaGimmicks::getParameters<std::vector<std::string>>(nh_private_, "topics/subscribers"); sub_odometry = nh_.subscribe(ros_subs[0], 1, &SensorSim::stateCallback , this); // } /* ####################################################################################################################### @.@ Member helper function to set up publishers; ####################################################################################################################### */ void SensorSim::initializePublishers() { ROS_INFO("Initializing Publishers for SensorSim"); // ---> add publishers here std::vector<std::string> ros_pubs = MedusaGimmicks::getParameters<std::vector<std::string>>(nh_private_, "topics/publishers"); pub_position = nh_.advertise<dsor_msgs::Measurement>(ros_pubs[0], 10); pub_velocity = nh_.advertise<dsor_msgs::Measurement>(ros_pubs[1], 10); pub_orientation = nh_.advertise<dsor_msgs::Measurement>(ros_pubs[2], 10); pub_gnss = nh_.advertise<sensor_msgs::NavSatFix>(ros_pubs[3], 10); pub_range = nh_.advertise<medusa_msgs::mUSBLFix> (ros_pubs[4], 10); pub_model = nh_.advertise<auv_msgs::NavigationStatus>(ros_pubs[5], 10); pub_thrustStatus = nh_.advertise<medusa_msgs::mThrusterStatus>(ros_pubs[6], 10); } void SensorSim::initializeServices(){ enable_dvl_srv_ = nh_.advertiseService(MedusaGimmicks::getParameters<std::string>(nh_private_, "services/enable_dvl", "enable_dvl"), &SensorSim::enableDVLService, this); enable_altimeter_srv_ = nh_.advertiseService(MedusaGimmicks::getParameters<std::string>(nh_private_, "services/enable_altimeter", "enable_altimeter"), &SensorSim::enableAltimeterService, this); } /* ####################################################################################################################### @.@ Member helper function to set up the timer; This is a more flexible and useful form of the ros::Rate ####################################################################################################################### */ void SensorSim::initializeTimer() { timer_sensor = nh_.createTimer(ros::Duration(1.0/SensorSim::nodeFrequency()), &SensorSim::sensorTimerCallback, this); } /* ####################################################################################################################### @.@ Set frequency of the node default is 10 ####################################################################################################################### */ double SensorSim::nodeFrequency() { double node_frequency; nh_.param("node_frequency", node_frequency, 10.0); ROS_INFO("Node will run at : %lf [hz]", node_frequency); return node_frequency; } /* ####################################################################################################################### @.@ Load the parameters ####################################################################################################################### */ void SensorSim::loadParams() { ROS_INFO("Load the SensorSim parameters"); p_water_column_length = MedusaGimmicks::getParameters<double>(nh_private_, "water_column_length", 100); int zone; bool northp; double gamma, k; double origin_lat = MedusaGimmicks::getParameters<double>(nh_, "/originLat", 38.765852); double origin_lon = MedusaGimmicks::getParameters<double>(nh_, "/originLon", -9.09281873); try { GeographicLib::UTMUPS::Forward(origin_lat, origin_lon, zone, northp, origin_east, origin_north, gamma, k); } catch (const GeographicLib::GeographicErr::exception &ex) { ROS_WARN("SensorSim caught exception: %s", ex.what()); } // ######################################## // Input Sensors // ######################################## sensors = extractSensors(MedusaGimmicks::getParameters<XmlRpc::XmlRpcValue>(nh_private_, "sensors")); sensors[0].zone = zone; sensors[0].northp = northp; SENSOR_COUNT = sensors.size(); // Get the frame id for the base_link and world frame world_frame_id = MedusaGimmicks::getParameters<std::string>(nh_, "world_frame"); base_link_frame_id = MedusaGimmicks::getParameters<std::string>(nh_, "base_link"); } /* ####################################################################################################################### @.@ Callbacks Section / Methods ####################################################################################################################### */ /* ####################################################################################################################### @.@ Iteration via timer callback ####################################################################################################################### */ void SensorSim::sensorTimerCallback(const ros::TimerEvent &event) { // std::cout << "#1: " << initialized << std::endl; if (!initialized) return; for (int i = 0; i < SENSOR_COUNT; i++){ // std::cout << "#2: " << sensors[i].count << " : " << sensors[i].thresh << std::endl; if (sensors[i].count++ > sensors[i].thresh && sensors[i].thresh != 0) continue; if ((ros::Time::now().toSec() - sensors[i].last_update) > 1/sensors[i].frequency){ sensors[i].last_update = ros::Time::now().toSec(); // TODO: Try using void pointer to make implementation more generic here if (sensors[i].type == Sensor::MODEL){ pub_model.publish(state); } else if (sensors[i].type == Sensor::GNSS){ sensor_msgs::NavSatFix m; sensors[i].zone = sensors[0].zone; sensors[i].northp = sensors[0].northp; if(addNoise(state, sensors[i], m)); pub_gnss.publish(m); } else if (sensors[i].type == Sensor::RANGE){ medusa_msgs::mUSBLFix m; addNoise(state, sensors[i], m); pub_range.publish(m); } else{ dsor_msgs::Measurement m; if(addNoise(state, sensors[i], m)){ switch(sensors[i].type){ case Sensor::AHRS: pub_orientation.publish(m); break; case Sensor::DEPTH: case Sensor::ALTIMETER: pub_position.publish(m); break; case Sensor::DVL_BT: case Sensor::DVL_WT: pub_velocity.publish(m); break; } } } } } } /* ####################################################################################################################### @.@ Callback Flag ####################################################################################################################### */ void SensorSim::stateCallback(const nav_msgs::Odometry &msg) { if(msg.header.stamp > t_latest){ initialized = true; t_latest = msg.header.stamp; // convert and store odometry in world frame state.header.stamp = msg.header.stamp; state.header.frame_id = msg.header.frame_id; // transform position state.position.north = origin_north + msg.pose.pose.position.x; state.position.east = origin_east + msg.pose.pose.position.y; state.position.depth = msg.pose.pose.position.z; state.altitude = p_water_column_length - state.position.depth; // Set linear speed - is transformed later state.body_velocity.x = msg.twist.twist.linear.x; state.body_velocity.y = msg.twist.twist.linear.y; state.body_velocity.z = msg.twist.twist.linear.z; try { geometry_msgs::TransformStamped transformStamped; transformStamped.header.stamp = msg.header.stamp; transformStamped.header.frame_id = world_frame_id; transformStamped.child_frame_id = base_link_frame_id; transformStamped.transform.rotation = msg.pose.pose.orientation; tf2::doTransform(state.body_velocity, state.seafloor_velocity, transformStamped); } catch (tf2::TransformException &ex) { ROS_ERROR_DELAYED_THROTTLE(10.0, "Could not transform sea_floor velocity: %s", ex.what()); return; } // set angles tf2::Quaternion tf_quat; tf2::convert(msg.pose.pose.orientation, tf_quat); tf2::Matrix3x3 m3x3(tf_quat); m3x3.getRPY(state.orientation.x, state.orientation.y, state.orientation.z); state.orientation_rate = msg.twist.twist.angular; // set message status state.status = auv_msgs::NavigationStatus::STATUS_ALL_OK; } } void SensorSim::thrustStatusCallback(dsor_msgs::Thruster data){ for (int i = 0; i < data.value.size(); i++){ medusa_msgs::mThrusterStatus thrustStatus; thrustStatus.header.stamp = ros::Time::now(); thrustStatus.header.frame_id = std::to_string(i); thrustStatus.Speed = data.value[i]; thrustStatus.Temperature = 20; pub_thrustStatus.publish(thrustStatus); } } bool SensorSim::enableDVLService(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &res){ if(req.data){ enable_dvl_ = true; res.success = true; res.message = "DVL activated"; } else{ enable_dvl_ = false; res.success = false; res.message = "DVL deactivated"; } return true; } bool SensorSim::enableAltimeterService(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &res){ if(req.data){ enable_altimeter_ = true; res.success = true; res.message = "Altimeter activated"; } else{ enable_altimeter_ = false; res.success = false; res.message = "Altimter deactivated"; } return true; } std::vector<SensorSim::Sensor> SensorSim::extractSensors(XmlRpc::XmlRpcValue valueXml){ std::vector<Sensor> sensors; for (int32_t i = 0; i < valueXml.size(); ++i){ Sensor sensor; // std::cout << "#1: " << valueXml[i]["frame_id"].toXml() << std::endl; readXML(sensor.frame_id, valueXml[i]["frame_id"], std::string("0")); readXML(sensor.debug, valueXml[i]["debug"], false); readXML(sensor.frequency, valueXml[i]["frequency"], 1.0); readXML(sensor.thresh, valueXml[i]["count"], 0); std::string type; readXML(type, valueXml[i]["type"], std::string("null")); sensor.type = sensor.enum_map[type]; extractArrayDouble(sensor.noise, valueXml[i]["noise"]); readXML(sensor.variance, valueXml[i]["variance"], 0.0); readXML(sensor.altitude, valueXml[i]["altitude"], 0.0); extractArrayDouble(sensor.beacon, valueXml[i]["beacon"]); sensors.push_back(sensor); } return sensors; } bool SensorSim::addNoise(const auv_msgs::NavigationStatus &state, const Sensor &sensor, dsor_msgs::Measurement &m){ m.header.stamp = ros::Time::now(); m.header.frame_id = sensor.frame_id; double x; switch(sensor.type){ case Sensor::AHRS: x = state.orientation.x + randn(0.0, sensor.noise[0]); m.value.push_back(x); x = state.orientation.y + randn(0.0, sensor.noise[0]); m.value.push_back(x); x = state.orientation.z + randn(0.0, sensor.noise[0]); m.value.push_back(x); x = state.orientation_rate.x + randn(0.0, sensor.noise[1]); m.value.push_back(x); x = state.orientation_rate.y + randn(0.0, sensor.noise[1]); m.value.push_back(x); x = state.orientation_rate.z + randn(0.0, sensor.noise[1]); m.value.push_back(x); for (int i = 0; i < 3; i++) m.noise.push_back(sensor.noise[0] + sensor.variance); for (int i = 0; i < 3; i++) m.noise.push_back(sensor.noise[1] + sensor.variance); break; case Sensor::DVL_BT: if ((state.altitude > sensor.altitude && sensor.debug == false) || enable_dvl_ == false) return false; x = state.seafloor_velocity.x + randn(0.0, sensor.noise[0]); m.value.push_back(x); x = state.seafloor_velocity.y + randn(0.0, sensor.noise[0]); m.value.push_back(x); for (int i = 0; i < 2; i++) m.noise.push_back(sensor.noise[0] + sensor.variance); break; case Sensor::DVL_WT: if ((state.altitude < sensor.altitude && sensor.debug == false) || enable_dvl_ == false) return false; x = state.body_velocity.x + randn(0.0, sensor.noise[0]); m.value.push_back(x); x = state.body_velocity.y + randn(0.0, sensor.noise[0]); m.value.push_back(x); for (int i = 0; i < 2; i++) m.noise.push_back(sensor.noise[0] + sensor.variance); break; case Sensor::DEPTH: x = state.position.depth + randn(0.0, sensor.noise[0]); m.value.push_back(x); m.noise.push_back(sensor.noise[0] + sensor.variance); break; case Sensor::ALTIMETER: if (enable_altimeter_ == false) return false; x = state.altitude + randn(0.0, sensor.noise[0]); m.value.push_back(x); m.noise.push_back(sensor.noise[0] + sensor.variance); break; } return true; } bool SensorSim::addNoise(const auv_msgs::NavigationStatus &state, const Sensor &sensor, sensor_msgs::NavSatFix &m){ if (state.position.depth > 0.5 && sensor.debug == false) return false; m.header.stamp = ros::Time::now(); m.header.frame_id = sensor.frame_id; double x = state.position.east + randn(0.0, sensor.noise[0]); double y = state.position.north + randn(0.0, sensor.noise[0]); try{ GeographicLib::UTMUPS::Reverse(sensor.zone, sensor.northp, x, y, m.latitude, m.longitude); } catch(...){ ROS_ERROR_DELAYED_THROTTLE(10.0, "Could not convert UTM to GPS"); return false; } m.position_covariance[0] = sensor.noise[0] + sensor.variance; m.position_covariance[4] = sensor.noise[0] + sensor.variance; return true; } void SensorSim::addNoise(const auv_msgs::NavigationStatus &state, const Sensor &sensor, medusa_msgs::mUSBLFix &m){ m.header.stamp = ros::Time::now(); m.header.frame_id = sensor.frame_id; double x = pow((state.position.north - sensor.beacon[0]), 2) + pow((state.position.east - sensor.beacon[1]), 2) + pow((state.position.depth - sensor.beacon[2]), 2); m.range = pow (x, 0.5) + randn(0.0, sensor.noise[0]); m.position_covariance[0] = sensor.noise[0] + sensor.variance; } // from http://phoxis.org/2013/05/04/generating-random-numbers-from-normal-distribution-in-c/ double SensorSim::randn(double mu, double sigma){ double U1, U2, W, mult; static double X1, X2; static int call = 0; if (call) { call = !call; return (mu + sigma * (double)X2); } do { U1 = -1 + ((double)rand() / RAND_MAX) * 2; U2 = -1 + ((double)rand() / RAND_MAX) * 2; W = pow(U1, 2) + pow(U2, 2); } while (W >= 1 || W == 0); mult = sqrt((-2 * log(W)) / W); X1 = U1 * mult; X2 = U2 * mult; call = !call; return (mu + sigma * (double)X1); } void SensorSim::extractArrayDouble(double* array, XmlRpc::XmlRpcValue &double_array){ if(double_array.getType() == XmlRpc::XmlRpcValue::TypeInvalid) return; if(double_array.getType() == XmlRpc::XmlRpcValue::TypeDouble){ array[0] = static_cast<double>(double_array); return; } for (int32_t i = 0; i < double_array.size(); ++i) { if (double_array[i].getType() == XmlRpc::XmlRpcValue::TypeDouble) array[i] = (static_cast<double>(double_array[i])); else if(double_array[i].getType() == XmlRpc::XmlRpcValue::TypeInt) array[i] = (static_cast<double>(static_cast<int>(double_array[i]))); } } /* ####################################################################################################################### @.@ Main ####################################################################################################################### */ int main(int argc, char** argv) { // +.+ ROS set-ups: ros::init(argc, argv, "medusa_sim_node"); //node name // +.+ create a node handle; need to pass this to the class constructor ros::NodeHandle nh, nh_private("~"); ROS_INFO("main: instantiating an object of type SensorSim"); // +.+ instantiate an SensorSim class object and pass in pointer to nodehandle for constructor to use SensorSim medusaSim(&nh, &nh_private); // +.+ Added to work with timer -> going into spin; let the callbacks do all the work ros::spin(); return 0; }
17,513
6,294
//------------------------------------------------------------------------------ // This file was generated using the Faust compiler (https://faust.grame.fr), // and the Faust post-processor (https://github.com/jpcima/faustpp). // // Source: NoiseLFO.dsp // Name: NoiseLFO // Author: // Copyright: // License: // Version: //------------------------------------------------------------------------------ #include "NoiseLFO.hpp" #include <utility> #include <cmath> class NoiseLFO::BasicDsp { public: virtual ~BasicDsp() {} }; //------------------------------------------------------------------------------ // Begin the Faust code section namespace { template <class T> inline T min(T a, T b) { return (a < b) ? a : b; } template <class T> inline T max(T a, T b) { return (a > b) ? a : b; } class Meta { public: // dummy void declare(...) {} }; class UI { public: // dummy void openHorizontalBox(...) {} void openVerticalBox(...) {} void closeBox(...) {} void declare(...) {} void addButton(...) {} void addCheckButton(...) {} void addVerticalSlider(...) {} void addHorizontalSlider(...) {} void addVerticalBargraph(...) {} }; typedef NoiseLFO::BasicDsp dsp; } // namespace #define FAUSTPP_VIRTUAL // do not declare any methods virtual #define FAUSTPP_PRIVATE public // do not hide any members #define FAUSTPP_PROTECTED public // do not hide any members // define the DSP in the anonymous namespace #define FAUSTPP_BEGIN_NAMESPACE namespace { #define FAUSTPP_END_NAMESPACE } #if defined(__GNUC__) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-parameter" #endif #ifndef FAUSTPP_PRIVATE # define FAUSTPP_PRIVATE private #endif #ifndef FAUSTPP_PROTECTED # define FAUSTPP_PROTECTED protected #endif #ifndef FAUSTPP_VIRTUAL # define FAUSTPP_VIRTUAL virtual #endif #ifndef FAUSTPP_BEGIN_NAMESPACE # define FAUSTPP_BEGIN_NAMESPACE #endif #ifndef FAUSTPP_END_NAMESPACE # define FAUSTPP_END_NAMESPACE #endif FAUSTPP_BEGIN_NAMESPACE #ifndef FAUSTFLOAT #define FAUSTFLOAT float #endif FAUSTPP_END_NAMESPACE #include <algorithm> #include <cmath> #include <math.h> FAUSTPP_BEGIN_NAMESPACE #ifndef FAUSTCLASS #define FAUSTCLASS NoiseLFODsp #endif #ifdef __APPLE__ #define exp10f __exp10f #define exp10 __exp10 #endif class NoiseLFODsp : public dsp { FAUSTPP_PRIVATE: int fSampleRate; float fConst0; float fConst1; FAUSTFLOAT fHslider0; int iVec0[2]; float fConst2; float fRec6[2]; float fRec7[2]; int iRec8[2]; float fRec5[2]; float fRec4[2]; float fRec3[2]; float fRec2[2]; float fRec1[2]; float fRec0[2]; public: void metadata(Meta* m) { m->declare("basics.lib/name", "Faust Basic Element Library"); m->declare("basics.lib/version", "0.1"); m->declare("filename", "NoiseLFO.dsp"); m->declare("filters.lib/lowpass0_highpass1", "Copyright (C) 2003-2019 by Julius O. Smith III <jos@ccrma.stanford.edu>"); m->declare("filters.lib/lowpass0_highpass1:author", "Julius O. Smith III"); m->declare("filters.lib/lowpass:author", "Julius O. Smith III"); m->declare("filters.lib/lowpass:copyright", "Copyright (C) 2003-2019 by Julius O. Smith III <jos@ccrma.stanford.edu>"); m->declare("filters.lib/lowpass:license", "MIT-style STK-4.3 license"); m->declare("filters.lib/name", "Faust Filters Library"); m->declare("filters.lib/nlf2:author", "Julius O. Smith III"); m->declare("filters.lib/nlf2:copyright", "Copyright (C) 2003-2019 by Julius O. Smith III <jos@ccrma.stanford.edu>"); m->declare("filters.lib/nlf2:license", "MIT-style STK-4.3 license"); m->declare("filters.lib/tf1:author", "Julius O. Smith III"); m->declare("filters.lib/tf1:copyright", "Copyright (C) 2003-2019 by Julius O. Smith III <jos@ccrma.stanford.edu>"); m->declare("filters.lib/tf1:license", "MIT-style STK-4.3 license"); m->declare("filters.lib/tf1s:author", "Julius O. Smith III"); m->declare("filters.lib/tf1s:copyright", "Copyright (C) 2003-2019 by Julius O. Smith III <jos@ccrma.stanford.edu>"); m->declare("filters.lib/tf1s:license", "MIT-style STK-4.3 license"); m->declare("maths.lib/author", "GRAME"); m->declare("maths.lib/copyright", "GRAME"); m->declare("maths.lib/license", "LGPL with exception"); m->declare("maths.lib/name", "Faust Math Library"); m->declare("maths.lib/version", "2.1"); m->declare("name", "NoiseLFO"); m->declare("noises.lib/name", "Faust Noise Generator Library"); m->declare("noises.lib/version", "0.0"); m->declare("oscillators.lib/name", "Faust Oscillator Library"); m->declare("oscillators.lib/version", "0.0"); } FAUSTPP_VIRTUAL int getNumInputs() { return 0; } FAUSTPP_VIRTUAL int getNumOutputs() { return 1; } FAUSTPP_VIRTUAL int getInputRate(int channel) { int rate; switch ((channel)) { default: { rate = -1; break; } } return rate; } FAUSTPP_VIRTUAL int getOutputRate(int channel) { int rate; switch ((channel)) { case 0: { rate = 1; break; } default: { rate = -1; break; } } return rate; } static void classInit(int sample_rate) { } FAUSTPP_VIRTUAL void instanceConstants(int sample_rate) { fSampleRate = sample_rate; fConst0 = std::min<float>(192000.0f, std::max<float>(1.0f, float(fSampleRate))); fConst1 = (3.14159274f / fConst0); fConst2 = (6.28318548f / fConst0); } FAUSTPP_VIRTUAL void instanceResetUserInterface() { fHslider0 = FAUSTFLOAT(1.0f); } FAUSTPP_VIRTUAL void instanceClear() { for (int l0 = 0; (l0 < 2); l0 = (l0 + 1)) { iVec0[l0] = 0; } for (int l1 = 0; (l1 < 2); l1 = (l1 + 1)) { fRec6[l1] = 0.0f; } for (int l2 = 0; (l2 < 2); l2 = (l2 + 1)) { fRec7[l2] = 0.0f; } for (int l3 = 0; (l3 < 2); l3 = (l3 + 1)) { iRec8[l3] = 0; } for (int l4 = 0; (l4 < 2); l4 = (l4 + 1)) { fRec5[l4] = 0.0f; } for (int l5 = 0; (l5 < 2); l5 = (l5 + 1)) { fRec4[l5] = 0.0f; } for (int l6 = 0; (l6 < 2); l6 = (l6 + 1)) { fRec3[l6] = 0.0f; } for (int l7 = 0; (l7 < 2); l7 = (l7 + 1)) { fRec2[l7] = 0.0f; } for (int l8 = 0; (l8 < 2); l8 = (l8 + 1)) { fRec1[l8] = 0.0f; } for (int l9 = 0; (l9 < 2); l9 = (l9 + 1)) { fRec0[l9] = 0.0f; } } FAUSTPP_VIRTUAL void init(int sample_rate) { classInit(sample_rate); instanceInit(sample_rate); } FAUSTPP_VIRTUAL void instanceInit(int sample_rate) { instanceConstants(sample_rate); instanceResetUserInterface(); instanceClear(); } FAUSTPP_VIRTUAL NoiseLFODsp* clone() { return new NoiseLFODsp(); } FAUSTPP_VIRTUAL int getSampleRate() { return fSampleRate; } FAUSTPP_VIRTUAL void buildUserInterface(UI* ui_interface) { ui_interface->openVerticalBox("NoiseLFO"); ui_interface->declare(&fHslider0, "1", ""); ui_interface->declare(&fHslider0, "symbol", "frequency"); ui_interface->declare(&fHslider0, "unit", "Hz"); ui_interface->addHorizontalSlider("Frequency", &fHslider0, 1.0f, 0.0f, 100.0f, 1.0f); ui_interface->closeBox(); } FAUSTPP_VIRTUAL void compute(int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { FAUSTFLOAT* output0 = outputs[0]; float fSlow0 = float(fHslider0); float fSlow1 = (1.0f / std::tan((fConst1 * fSlow0))); float fSlow2 = (1.0f / (fSlow1 + 1.0f)); float fSlow3 = (1.0f - fSlow1); float fSlow4 = (fConst2 * fSlow0); float fSlow5 = std::sin(fSlow4); float fSlow6 = std::cos(fSlow4); for (int i = 0; (i < count); i = (i + 1)) { iVec0[0] = 1; fRec6[0] = ((fSlow5 * fRec7[1]) + (fSlow6 * fRec6[1])); fRec7[0] = ((float((1 - iVec0[1])) + (fSlow6 * fRec7[1])) - (fSlow5 * fRec6[1])); int iTemp0 = ((fRec6[1] <= 0.0f) & (fRec6[0] > 0.0f)); iRec8[0] = ((1103515245 * iRec8[1]) + 12345); fRec5[0] = ((fRec5[1] * float((1 - iTemp0))) + (4.65661287e-10f * (float(iRec8[0]) * float(iTemp0)))); fRec4[0] = (0.0f - (fSlow2 * ((fSlow3 * fRec4[1]) - (fRec5[0] + fRec5[1])))); fRec3[0] = (0.0f - (fSlow2 * ((fSlow3 * fRec3[1]) - (fRec4[0] + fRec4[1])))); fRec2[0] = (0.0f - (fSlow2 * ((fSlow3 * fRec2[1]) - (fRec3[0] + fRec3[1])))); fRec1[0] = (0.0f - (fSlow2 * ((fSlow3 * fRec1[1]) - (fRec2[0] + fRec2[1])))); fRec0[0] = (0.0f - (fSlow2 * ((fSlow3 * fRec0[1]) - (fRec1[0] + fRec1[1])))); output0[i] = FAUSTFLOAT(fRec0[0]); iVec0[1] = iVec0[0]; fRec6[1] = fRec6[0]; fRec7[1] = fRec7[0]; iRec8[1] = iRec8[0]; fRec5[1] = fRec5[0]; fRec4[1] = fRec4[0]; fRec3[1] = fRec3[0]; fRec2[1] = fRec2[0]; fRec1[1] = fRec1[0]; fRec0[1] = fRec0[0]; } } }; FAUSTPP_END_NAMESPACE #if defined(__GNUC__) # pragma GCC diagnostic pop #endif //------------------------------------------------------------------------------ // End the Faust code section NoiseLFO::NoiseLFO() { NoiseLFODsp *dsp = new NoiseLFODsp; fDsp.reset(dsp); dsp->instanceResetUserInterface(); } NoiseLFO::~NoiseLFO() { } void NoiseLFO::init(float sample_rate) { NoiseLFODsp &dsp = static_cast<NoiseLFODsp &>(*fDsp); dsp.classInit(sample_rate); dsp.instanceConstants(sample_rate); clear(); } void NoiseLFO::clear() noexcept { NoiseLFODsp &dsp = static_cast<NoiseLFODsp &>(*fDsp); dsp.instanceClear(); } void NoiseLFO::process( float *out0, unsigned count) noexcept { NoiseLFODsp &dsp = static_cast<NoiseLFODsp &>(*fDsp); float *inputs[] = { }; float *outputs[] = { out0, }; dsp.compute(count, inputs, outputs); } const char *NoiseLFO::parameter_label(unsigned index) noexcept { switch (index) { case 0: return "Frequency"; default: return 0; } } const char *NoiseLFO::parameter_short_label(unsigned index) noexcept { switch (index) { case 0: return ""; default: return 0; } } const char *NoiseLFO::parameter_symbol(unsigned index) noexcept { switch (index) { case 0: return "frequency"; default: return 0; } } const char *NoiseLFO::parameter_unit(unsigned index) noexcept { switch (index) { case 0: return "Hz"; default: return 0; } } const NoiseLFO::ParameterRange *NoiseLFO::parameter_range(unsigned index) noexcept { switch (index) { case 0: { static const ParameterRange range = { 1, 0, 100 }; return &range; } default: return 0; } } bool NoiseLFO::parameter_is_trigger(unsigned index) noexcept { switch (index) { default: return false; } } bool NoiseLFO::parameter_is_boolean(unsigned index) noexcept { switch (index) { default: return false; } } bool NoiseLFO::parameter_is_integer(unsigned index) noexcept { switch (index) { default: return false; } } bool NoiseLFO::parameter_is_logarithmic(unsigned index) noexcept { switch (index) { default: return false; } } float NoiseLFO::get_parameter(unsigned index) const noexcept { NoiseLFODsp &dsp = static_cast<NoiseLFODsp &>(*fDsp); switch (index) { case 0: return dsp.fHslider0; default: (void)dsp; return 0; } } void NoiseLFO::set_parameter(unsigned index, float value) noexcept { NoiseLFODsp &dsp = static_cast<NoiseLFODsp &>(*fDsp); switch (index) { case 0: dsp.fHslider0 = value; break; default: (void)dsp; (void)value; break; } } float NoiseLFO::get_frequency() const noexcept { NoiseLFODsp &dsp = static_cast<NoiseLFODsp &>(*fDsp); return dsp.fHslider0; } void NoiseLFO::set_frequency(float value) noexcept { NoiseLFODsp &dsp = static_cast<NoiseLFODsp &>(*fDsp); dsp.fHslider0 = value; }
11,739
5,217
/*ckwg +29 * Copyright 2016 by Kitware, 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 name of Kitware, Inc. nor the names of any 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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * \file * \brief core polygon implementation */ #include "polygon.h" #include <stdexcept> #include <sstream> namespace kwiver { namespace vital { // ------------------------------------------------------------------ polygon:: polygon() { } polygon:: polygon( const std::vector< point_t > &dat ) : m_polygon( dat ) { } // ------------------------------------------------------------------ polygon:: ~polygon() { } // ------------------------------------------------------------------ void polygon:: push_back( double x, double y ) { m_polygon.push_back( point_t( x, y ) ); } // ------------------------------------------------------------------ void polygon:: push_back( const kwiver::vital::polygon::point_t& pt ) { m_polygon.push_back( pt ); } // ------------------------------------------------------------------ size_t polygon:: num_vertices() const { return m_polygon.size(); } // ------------------------------------------------------------------ bool polygon:: contains( double x, double y ) { bool c = false; int n = static_cast<int>(m_polygon.size()); for (int i = 0, j = n-1; i < n; j = i++) { const point_t& p_i = m_polygon[i]; const point_t& p_j = m_polygon[j]; // by definition, corner points and edge points are inside the polygon: if ((p_j.x() - x) * (p_i.y() - y) == (p_i.x() - x) * (p_j.y() - y) && (((p_i.x()<=x) && (x<=p_j.x())) || ((p_j.x()<=x) && (x<=p_i.x()))) && (((p_i.y()<=y) && (y<=p_j.y())) || ((p_j.y()<=y) && (y<=p_i.y())))) { return true; } // invert c for each edge crossing: if ((((p_i.y()<=y) && (y<p_j.y())) || ((p_j.y()<=y) && (y<p_i.y()))) && (x < (p_j.x() - p_i.x()) * (y - p_i.y()) / (p_j.y() - p_i.y()) + p_i.x())) { c = !c; } } // end for return c; } // ------------------------------------------------------------------ bool polygon:: contains( const kwiver::vital::polygon::point_t& pt ) { return contains( pt[0], pt[1] ); } // ------------------------------------------------------------------ kwiver::vital::polygon::point_t polygon:: at( size_t idx ) const { if ( idx >= m_polygon.size() ) { std::stringstream str; str << "Requested index " << idx << " is beyond the end of the polygon. Last valid index is " << m_polygon.size()-1; throw std::out_of_range( str.str() ); } return m_polygon[idx]; } // ------------------------------------------------------------------ std::vector< kwiver::vital::polygon::point_t > polygon:: get_vertices() const { return m_polygon; } } } // end namespace
4,177
1,480
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkEventRecorder.h" #include "mitkEventFactory.h" #include "mitkInteractionEvent.h" #include "mitkInteractionEventConst.h" #include "mitkBaseRenderer.h" static void WriteEventXMLHeader(std::ofstream& stream) { stream << mitk::InteractionEventConst::xmlHead() << "\n"; } static void WriteEventXMLConfig(std::ofstream& stream) { // <config> stream << " <" << mitk::InteractionEventConst::xmlTagConfigRoot() << ">\n"; //write renderer config //for all registered 2D renderers write name and viewdirection. mitk::BaseRenderer::BaseRendererMapType::iterator rendererIterator = mitk::BaseRenderer::baseRendererMap.begin(); mitk::BaseRenderer::BaseRendererMapType::iterator end = mitk::BaseRenderer::baseRendererMap.end(); for(; rendererIterator != end; rendererIterator++) { std::string rendererName = (*rendererIterator).second->GetName(); mitk::SliceNavigationController::ViewDirection viewDirection = (*rendererIterator).second->GetSliceNavigationController()->GetDefaultViewDirection(); mitk::BaseRenderer::MapperSlotId mapperID = (*rendererIterator).second->GetMapperID(); // <renderer RendererName="stdmulti.widget2" ViewDirection="1" MapperID="1"/> stream << " <" << mitk::InteractionEventConst::xmlTagRenderer() << " " << mitk::InteractionEventConst::xmlEventPropertyRendererName() << "=\"" << rendererName << "\" " << mitk::InteractionEventConst::xmlEventPropertyViewDirection() << "=\"" << viewDirection << "\" " << mitk::InteractionEventConst::xmlEventPropertyMapperID() << "=\"" << mapperID << "\"/>\n"; } // </config> stream << " </" << mitk::InteractionEventConst::xmlTagConfigRoot() << ">\n"; } static void WriteEventXMLEventsOpen(std::ofstream& stream) { stream << " <" << mitk::InteractionEventConst::xmlTagEvents() << ">\n"; } static void WriteEventXMLEventsClose(std::ofstream& stream) { stream << " </" << mitk::InteractionEventConst::xmlTagEvents() << ">\n"; } static void WriteEventXMLInteractionsOpen(std::ofstream& stream) { stream << "<" << mitk::InteractionEventConst::xmlTagInteractions() << ">\n"; } static void WriteEventXMLInteractionsClose(std::ofstream& stream) { stream << "</" << mitk::InteractionEventConst::xmlTagInteractions() << ">"; } static void WriteEventXMLClose(std::ofstream& stream) { WriteEventXMLEventsClose(stream); WriteEventXMLInteractionsClose(stream); } mitk::EventRecorder::EventRecorder() : m_Active(false) { } mitk::EventRecorder::~EventRecorder() { if (m_FileStream.is_open()) { m_FileStream.flush(); m_FileStream.close(); } } void mitk::EventRecorder::Notify(mitk::InteractionEvent *interactionEvent, bool /*isHandled*/) { std::cout << EventFactory::EventToXML(interactionEvent) << "\n"; if (m_FileStream.is_open()) m_FileStream << EventFactory::EventToXML(interactionEvent) << "\n"; } void mitk::EventRecorder::SetEventIgnoreList(std::vector<std::string> list) { m_IgnoreList = list; } void mitk::EventRecorder::StartRecording() { if (m_FileName == "") { MITK_ERROR << "EventRecorder::StartRecording - Filename needs to be set first."; return; } if (m_FileStream.is_open()) { MITK_ERROR << "EventRecorder::StartRecording - Still recording. Stop recording before starting it again."; return; } m_FileStream.open(m_FileName.c_str(), std::ofstream::out ); if ( !m_FileStream.good() ) { MITK_ERROR << "File " << m_FileName << " could not be opened!"; m_FileStream.close(); return; } m_Active = true; //write head and config // <?xml version="1.0"?> // <interactions> // <config> // <renderer RendererName="stdmulti.widget2" ViewDirection="1"/> // <renderer RendererName="stdmulti.widget1" ViewDirection="0"/> // ... // </config> // <events> WriteEventXMLHeader(m_FileStream); WriteEventXMLInteractionsOpen(m_FileStream); WriteEventXMLConfig(m_FileStream); WriteEventXMLEventsOpen(m_FileStream); } void mitk::EventRecorder::StopRecording() { if (m_FileStream.is_open()) { //write end tag // </events> // </interactions> WriteEventXMLClose(m_FileStream); m_FileStream.flush(); m_FileStream.close(); m_Active =false; } }
4,729
1,541
#include <ellalgo/cutting_plane.hpp> // for cutting_plane_dc #include <ellalgo/ell.hpp> // for ell #include <gsl/span> // for span #include <lmisolver/lmi_old_oracle.hpp> // for lmi_old_oracle #include <lmisolver/lmi_oracle.hpp> // for lmi_oracle #include <tuple> // for tuple #include <type_traits> // for move #include <vector> // for vector #include <xtensor/xlayout.hpp> // for layout_type, layout_type::ro... #include <xtensor/xmath.hpp> // for sum #include <xtensor/xoperation.hpp> // for operator* #include <xtensor/xtensor_forward.hpp> // for xarray #include "benchmark/benchmark.h" // for BENCHMARK, State, BENCHMARK_... /** * @brief * * @tparam Oracle */ template <typename Oracle> class my_oracle { using Arr = xt::xarray<double, xt::layout_type::row_major>; using Cut = std::tuple<Arr, double>; private: Oracle lmi1; Oracle lmi2; const Arr c; public: /** * @brief Construct a new my oracle object * * @param[in] F1 * @param[in] B1 * @param[in] F2 * @param[in] B2 * @param[in] c */ my_oracle(gsl::span<const Arr> F1, const Arr& B1, gsl::span<const Arr> F2, const Arr& B2, Arr c) : lmi1{F1, B1}, lmi2{F2, B2}, c{std::move(c)} {} /** * @brief * * @param[in] x * @param[in,out] t * @return std::tuple<Cut, double> */ std::tuple<Cut, bool> operator()(const Arr& x, double& t) { const auto f0 = xt::sum(this->c * x)(); const auto f1 = f0 - t; if (f1 > 0) { return {{this->c, f1}, false}; } const auto cut1 = this->lmi1(x); if (cut1) { return {*cut1, false}; } const auto cut2 = this->lmi2(x); if (cut2) { return {*cut2, false}; } t = f0; return {{this->c, 0.0}, true}; } }; /** * @brief * * @param[in,out] state */ static void LMI_Lazy(benchmark::State& state) { using Arr = xt::xarray<double, xt::layout_type::row_major>; // auto c = Arr {1.0, -1.0, 1.0}; const auto F1 = std::vector<Arr>{ {{-7.0, -11.0}, {-11.0, 3.0}}, {{7.0, -18.0}, {-18.0, 8.0}}, {{-2.0, -8.0}, {-8.0, 1.0}}}; const auto B1 = Arr{{33.0, -9.0}, {-9.0, 26.0}}; const auto F2 = std::vector<Arr>{{{-21.0, -11.0, 0.0}, {-11.0, 10.0, 8.0}, {0.0, 8.0, 5.0}}, {{0.0, 10.0, 16.0}, {10.0, -10.0, -10.0}, {16.0, -10.0, 3.0}}, {{-5.0, 2.0, -17.0}, {2.0, -6.0, 8.0}, {-17.0, 8.0, 6.0}}}; const auto B2 = Arr{{14.0, 9.0, 40.0}, {9.0, 91.0, 10.0}, {40.0, 10.0, 15.0}}; while (state.KeepRunning()) { auto P = my_oracle<lmi_oracle<Arr>>(F1, B1, F2, B2, Arr{1.0, -1.0, 1.0}); auto E = ell(10.0, Arr{0.0, 0.0, 0.0}); auto t = 1e100; // std::numeric_limits<double>::max() [[maybe_unused]] const auto rslt = cutting_plane_dc(P, E, t); } } // Register the function as a benchmark BENCHMARK(LMI_Lazy); //~~~~~~~~~~~~~~~~ /** * @brief Define another benchmark * * @param[in,out] state */ static void LMI_old(benchmark::State& state) { using Arr = xt::xarray<double, xt::layout_type::row_major>; // auto c = Arr {1.0, -1.0, 1.0}; const auto F1 = std::vector<Arr>{ {{-7.0, -11.0}, {-11.0, 3.0}}, {{7.0, -18.0}, {-18.0, 8.0}}, {{-2.0, -8.0}, {-8.0, 1.0}}}; const auto B1 = Arr{{33.0, -9.0}, {-9.0, 26.0}}; const auto F2 = std::vector<Arr>{{{-21.0, -11.0, 0.0}, {-11.0, 10.0, 8.0}, {0.0, 8.0, 5.0}}, {{0.0, 10.0, 16.0}, {10.0, -10.0, -10.0}, {16.0, -10.0, 3.0}}, {{-5.0, 2.0, -17.0}, {2.0, -6.0, 8.0}, {-17.0, 8.0, 6.0}}}; const auto B2 = Arr{{14.0, 9.0, 40.0}, {9.0, 91.0, 10.0}, {40.0, 10.0, 15.0}}; while (state.KeepRunning()) { auto P = my_oracle<lmi_old_oracle<Arr>>(F1, B1, F2, B2, Arr{1.0, -1.0, 1.0}); auto E = ell(10.0, Arr{0.0, 0.0, 0.0}); auto t = 1e100; // std::numeric_limits<double>::max() [[maybe_unused]] const auto rslt = cutting_plane_dc(P, E, t); } } BENCHMARK(LMI_old); /** * @brief * * @param[in,out] state */ static void LMI_No_Trick(benchmark::State& state) { using Arr = xt::xarray<double, xt::layout_type::row_major>; // const auto c = Arr {1.0, -1.0, 1.0}; const auto F1 = std::vector<Arr>{ {{-7.0, -11.0}, {-11.0, 3.0}}, {{7.0, -18.0}, {-18.0, 8.0}}, {{-2.0, -8.0}, {-8.0, 1.0}}}; const auto B1 = Arr{{33.0, -9.0}, {-9.0, 26.0}}; const auto F2 = std::vector<Arr>{{{-21.0, -11.0, 0.0}, {-11.0, 10.0, 8.0}, {0.0, 8.0, 5.0}}, {{0.0, 10.0, 16.0}, {10.0, -10.0, -10.0}, {16.0, -10.0, 3.0}}, {{-5.0, 2.0, -17.0}, {2.0, -6.0, 8.0}, {-17.0, 8.0, 6.0}}}; const auto B2 = Arr{{14.0, 9.0, 40.0}, {9.0, 91.0, 10.0}, {40.0, 10.0, 15.0}}; while (state.KeepRunning()) { auto P = my_oracle<lmi_oracle<Arr>>(F1, B1, F2, B2, Arr{1.0, -1.0, 1.0}); auto E = ell(10.0, Arr{0.0, 0.0, 0.0}); E.no_defer_trick = true; auto t = 1e100; // std::numeric_limits<double>::max() [[maybe_unused]] const auto rslt = cutting_plane_dc(P, E, t); } } // Register the function as a benchmark BENCHMARK(LMI_No_Trick); BENCHMARK_MAIN(); /* ---------------------------------------------------------- Benchmark Time CPU Iterations ---------------------------------------------------------- LMI_Lazy 131235 ns 131245 ns 4447 LMI_old 196694 ns 196708 ns 3548 LMI_No_Trick 129743 ns 129750 ns 5357 */
5,804
2,641
#ifndef RFM69_MESSAGING_HANDLER_HPP_ #define RFM69_MESSAGING_HANDLER_HPP_ #include "message.hpp" #include "message_handler.hpp" namespace PeripheralMessages { class RFM69Handler { public: static void begin(uint8_t node); static void initializeIncomingMessages(); static bool publishMessage(const MessageBuffer& buffer, const uint16_t node=0); static void serviceOnce(); private: static constexpr uint8_t GATEWAY_ID = 10; static constexpr int BUFFER_SIZE = 32; static uint8_t mHandlerBuffer[BUFFER_SIZE]; static bool mSentUpdate; static void serviceHeartbeat(); static void handleVersionQuery(void* args, void* msg,const uint16_t calling_id); }; } #endif //RFM69_MESSAGING_HANDLER_HPP_
691
257
/* Author: Zachary Kingston */ #include <robowflex_dart/joints.h> #include <robowflex_dart/space.h> using namespace robowflex::darts; /// /// RnJoint /// RnJoint::RnJoint(StateSpace *space, // dart::dynamics::Joint *joint, // double low, double high) : RnJoint(space, joint, // 1, 0, // Eigen::VectorXd::Constant(1, low), // Eigen::VectorXd::Constant(1, high)) { } RnJoint::RnJoint(StateSpace *space, // dart::dynamics::Joint *joint, // unsigned int n, unsigned int start, // Eigen::VectorXd low, Eigen::VectorXd high) : Joint(space, joint, n, start, n), low_(low), high_(high) { if (low_.size() != numDof_ or high_.size() != numDof_) { } for (unsigned int i = 0; i < numDof_; ++i) space_->addDimension(low[i], high[i]); } // L1 double RnJoint::distance(const Eigen::Ref<const Eigen::VectorXd> &a, const Eigen::Ref<const Eigen::VectorXd> &b) const { return (a - b).lpNorm<1>(); } double RnJoint::getMaximumExtent() const { return distance(low_, high_); } void RnJoint::interpolate(const Eigen::Ref<const Eigen::VectorXd> &a, // const Eigen::Ref<const Eigen::VectorXd> &b, // double t, // Eigen::Ref<Eigen::VectorXd> c) const { c = a + t * (b - a); } void RnJoint::enforceBounds(Eigen::Ref<Eigen::VectorXd> a) const { for (unsigned int i = 0; i < numDof_; ++i) { double &v = a[i]; v = (v < low_[i]) ? low_[i] : ((v > high_[i]) ? high_[i] : v); } } bool RnJoint::satisfiesBounds(const Eigen::Ref<const Eigen::VectorXd> &a) const { for (unsigned int i = 0; i < numDof_; ++i) { const double &v = a[i]; if ((v < low_[i]) or (v > high_[i])) return false; } return true; } void RnJoint::sample(Eigen::Ref<Eigen::VectorXd> a) const { for (unsigned int i = 0; i < numDof_; ++i) a[i] = rng_.uniformReal(low_[i], high_[i]); } void RnJoint::sampleNear(Eigen::Ref<Eigen::VectorXd> a, // const Eigen::Ref<const Eigen::VectorXd> &near, // double r) const { for (unsigned int i = 0; i < numDof_; ++i) a[i] = rng_.uniformReal(near[i] - r, near[i] + r); enforceBounds(a); } void RnJoint::setUpperLimits(const Eigen::Ref<const Eigen::VectorXd> &v) { if (v.size() != high_.size()) throw std::runtime_error("Incorrect size for limits!"); high_ = v; for (std::size_t i = 0; i < sizeInSpace_; ++i) space_->bounds_.setHigh(startInSpace_ + i, high_[i]); } void RnJoint::setLowerLimits(const Eigen::Ref<const Eigen::VectorXd> &v) { if (v.size() != low_.size()) throw std::runtime_error("Incorrect size for limits!"); low_ = v; for (std::size_t i = 0; i < sizeInSpace_; ++i) space_->bounds_.setLow(startInSpace_ + i, low_[i]); }
3,140
1,157
// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. // 3d flow over a cylinder benchmark example #include "navier_solver.hpp" #include <fstream> using namespace mfem; using namespace navier; struct s_NavierContext { int order = 4; double kin_vis = 0.001; double t_final = 10; double dt = 1e-3; } ctx; // vel 应该就是真解?不, 应该只是初值 void vel(const Vector &x, double t, Vector &u) { double xi = x(0); double yi = x(1); double zi = x(2); double U = 2.25; if (xi <= 1e-8) { u(0) = 16.0 * U * yi * zi * sin(M_PI * t / 8.0) * (0.41 - yi) * (0.41 - zi) / pow(0.41, 4.0); } else { u(0) = 0.0; } u(1) = 0.0; u(2) = 0.0; } int main(int argc, char *argv[]) { MPI_Session mpi(argc, argv); int serial_refinements = 0; Mesh *mesh = new Mesh("box-cylinder.mesh"); for (int i = 0; i < serial_refinements; ++i) { mesh->UniformRefinement(); } if (mpi.Root()) { std::cout << "Number of elements: " << mesh->GetNE() << std::endl; } auto *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh); delete mesh; if (mpi.Root()) { // 和上面的 mesh->GetNE() 不一样的 std::cout << "Number of elements: " << pmesh->GetNE() << std::endl; } // Create the flow solver. NavierSolver flowsolver(pmesh, ctx.order, ctx.kin_vis); flowsolver.EnablePA(true); // Set the initial condition. ParGridFunction *u_ic = flowsolver.GetCurrentVelocity(); VectorFunctionCoefficient u_excoeff(pmesh->Dimension(), vel); u_ic->ProjectCoefficient(u_excoeff); // Add Dirichlet boundary conditions to velocity space restricted to // selected attributes on the mesh. Array<int> attr(pmesh->bdr_attributes.Max()); // Inlet is attribute 1. attr[0] = 1; // Walls is attribute 3. attr[2] = 1; flowsolver.AddVelDirichletBC(vel, attr); double t = 0.0; double dt = ctx.dt; double t_final = ctx.t_final; bool last_step = false; flowsolver.Setup(dt); ParGridFunction *u_gf = flowsolver.GetCurrentVelocity(); ParGridFunction *p_gf = flowsolver.GetCurrentPressure(); ParaViewDataCollection pvdc("3dfoc", pmesh); pvdc.SetDataFormat(VTKFormat::BINARY32); pvdc.SetHighOrderOutput(true); pvdc.SetLevelsOfDetail(ctx.order); pvdc.SetCycle(0); pvdc.SetTime(t); pvdc.RegisterField("velocity", u_gf); pvdc.RegisterField("pressure", p_gf); pvdc.Save(); for (int step = 0; !last_step; ++step) { if (t + dt >= t_final - dt / 2) { last_step = true; } flowsolver.Step(t, dt, step); if (step % 10 == 0) { pvdc.SetCycle(step); pvdc.SetTime(t); pvdc.Save(); } if (mpi.Root()) { printf("%11s %11s\n", "Time", "dt"); printf("%.5E %.5E\n", t, dt); fflush(stdout); } } flowsolver.PrintTimingData(); delete pmesh; return 0; }
3,394
1,365
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2021 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 4.0.2019.08.13 #include <Graphics/GL45/GTGraphicsGL45PCH.h> #include <Graphics/GL45/GLSLShader.h> using namespace gte; GLSLShader::GLSLShader(GLSLReflection const& reflector, GraphicsObjectType type, int glslType) : Shader(type) { // If this is a compute shader, then query the number of threads per // group. if (GLSLReflection::ST_COMPUTE == glslType) { GLint sizeX, sizeY, sizeZ; reflector.GetComputeShaderWorkGroupSize(sizeX, sizeY, sizeZ); mNumXThreads = sizeX; mNumYThreads = sizeY; mNumZThreads = sizeZ; } // Will need to access uniforms more than once. auto const& uniforms = reflector.GetUniforms(); // Gather the uninforms information to create texture data. for (auto const& uni : uniforms) { if (uni.referencedBy[glslType]) { // Only interested in these particular uniform types (for // gsampler* and gimage*). switch (uni.type) { case GL_SAMPLER_1D: case GL_INT_SAMPLER_1D: case GL_UNSIGNED_INT_SAMPLER_1D: mData[TextureSingle::shaderDataLookup].push_back( Data(GT_TEXTURE_SINGLE, uni.name, uni.location, 0, 1, false)); mData[SamplerState::shaderDataLookup].push_back( Data(GT_SAMPLER_STATE, uni.name, uni.location, 0, GT_TEXTURE1, false)); break; case GL_SAMPLER_2D: case GL_INT_SAMPLER_2D: case GL_UNSIGNED_INT_SAMPLER_2D: mData[TextureSingle::shaderDataLookup].push_back( Data(GT_TEXTURE_SINGLE, uni.name, uni.location, 0, 2, false)); mData[SamplerState::shaderDataLookup].push_back( Data(GT_SAMPLER_STATE, uni.name, uni.location, 0, GT_TEXTURE2, false)); break; case GL_SAMPLER_3D: case GL_INT_SAMPLER_3D: case GL_UNSIGNED_INT_SAMPLER_3D: mData[TextureSingle::shaderDataLookup].push_back( Data(GT_TEXTURE_SINGLE, uni.name, uni.location, 0, 3, false)); mData[SamplerState::shaderDataLookup].push_back( Data(GT_SAMPLER_STATE, uni.name, uni.location, 0, GT_TEXTURE3, false)); break; case GL_SAMPLER_1D_ARRAY: case GL_INT_SAMPLER_1D_ARRAY: case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: mData[TextureArray::shaderDataLookup].push_back( Data(GT_TEXTURE_ARRAY, uni.name, uni.location, 0, 1, false)); mData[SamplerState::shaderDataLookup].push_back( Data(GT_SAMPLER_STATE, uni.name, uni.location, 0, GT_TEXTURE1_ARRAY, false)); break; case GL_SAMPLER_2D_ARRAY: case GL_INT_SAMPLER_2D_ARRAY: case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: mData[TextureArray::shaderDataLookup].push_back( Data(GT_TEXTURE_ARRAY, uni.name, uni.location, 0, 2, false)); mData[SamplerState::shaderDataLookup].push_back( Data(GT_SAMPLER_STATE, uni.name, uni.location, 0, GT_TEXTURE2_ARRAY, false)); break; case GL_SAMPLER_CUBE: case GL_INT_SAMPLER_CUBE: case GL_UNSIGNED_INT_SAMPLER_CUBE: mData[TextureArray::shaderDataLookup].push_back( Data(GT_TEXTURE_ARRAY, uni.name, uni.location, 0, 2, false)); mData[SamplerState::shaderDataLookup].push_back( Data(GT_SAMPLER_STATE, uni.name, uni.location, 0, GT_TEXTURE_CUBE, false)); break; case GL_SAMPLER_CUBE_MAP_ARRAY: case GL_INT_SAMPLER_CUBE_MAP_ARRAY: case GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY: mData[TextureArray::shaderDataLookup].push_back( Data(GT_TEXTURE_ARRAY, uni.name, uni.location, 0, 3, false)); mData[SamplerState::shaderDataLookup].push_back( Data(GT_SAMPLER_STATE, uni.name, uni.location, 0, GT_TEXTURE_CUBE_ARRAY, false)); break; case GL_IMAGE_1D: case GL_INT_IMAGE_1D: case GL_UNSIGNED_INT_IMAGE_1D: mData[TextureSingle::shaderDataLookup].push_back( Data(GT_TEXTURE_SINGLE, uni.name, uni.location, 0, 1, true)); break; case GL_IMAGE_2D: case GL_INT_IMAGE_2D: case GL_UNSIGNED_INT_IMAGE_2D: mData[TextureSingle::shaderDataLookup].push_back( Data(GT_TEXTURE_SINGLE, uni.name, uni.location, 0, 2, true)); break; case GL_IMAGE_3D: case GL_INT_IMAGE_3D: case GL_UNSIGNED_INT_IMAGE_3D: mData[TextureSingle::shaderDataLookup].push_back( Data(GT_TEXTURE_SINGLE, uni.name, uni.location, 0, 3, true)); break; case GL_IMAGE_1D_ARRAY: case GL_INT_IMAGE_1D_ARRAY: case GL_UNSIGNED_INT_IMAGE_1D_ARRAY: mData[TextureArray::shaderDataLookup].push_back( Data(GT_TEXTURE_ARRAY, uni.name, uni.location, 0, 1, true)); break; case GL_IMAGE_2D_ARRAY: case GL_INT_IMAGE_2D_ARRAY: case GL_UNSIGNED_INT_IMAGE_2D_ARRAY: mData[TextureArray::shaderDataLookup].push_back( Data(GT_TEXTURE_ARRAY, uni.name, uni.location, 0, 2, true)); break; case GL_IMAGE_CUBE: case GL_INT_IMAGE_CUBE: case GL_UNSIGNED_INT_IMAGE_CUBE: mData[TextureArray::shaderDataLookup].push_back( Data(GT_TEXTURE_ARRAY, uni.name, uni.location, 0, 2, true)); break; case GL_IMAGE_CUBE_MAP_ARRAY: case GL_INT_IMAGE_CUBE_MAP_ARRAY: case GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY: mData[TextureArray::shaderDataLookup].push_back( Data(GT_TEXTURE_ARRAY, uni.name, uni.location, 0, 3, true)); break; } } } // Gather the uniform blocks information to create constant buffer data. auto const& uniformBlocks = reflector.GetUniformBlocks(); int numUniformBlockReferences = 0; for (auto const& block : uniformBlocks) { if (block.referencedBy[glslType]) { ++numUniformBlockReferences; } } if (numUniformBlockReferences > 0) { mCBufferLayouts.resize(numUniformBlockReferences); // Store information needed by GL4Engine for enabling/disabling the // constant buffers. int blockIndex = 0; int layoutIndex = 0; for (auto const& block : uniformBlocks) { if (block.referencedBy[glslType]) { mData[ConstantBuffer::shaderDataLookup].push_back( Data(GT_CONSTANT_BUFFER, block.name, block.bufferBinding, block.bufferDataSize, 0, false)); // Assemble the constant buffer layout information. for (auto const& uniform : uniforms) { if (uniform.blockIndex != blockIndex) { continue; } MemberLayout item; item.name = uniform.name; item.offset = uniform.offset; // TODO: The HLSL reflection has numElements of 0 when // the item is not an array, but the actual number when // it is an array. ConstantBuffer::SetMember(...) uses // this information, so we need to adhere to the pattern. // Change this design in a refactor? item.numElements = (uniform.arraySize > 1 ? uniform.arraySize : 0); mCBufferLayouts[layoutIndex].push_back(item); } ++layoutIndex; } ++blockIndex; } } // Gather the atomic counter buffer information to create atomic counter // buffer data. auto const& atomicCounterBuffers = reflector.GetAtomicCounterBuffers(); int numAtomicCounterBufferReferences = 0; for (auto const& block : atomicCounterBuffers) { if (block.referencedBy[glslType]) { ++numAtomicCounterBufferReferences; } } if (numAtomicCounterBufferReferences > 0) { unsigned blockIndex = 0; for (auto const& block : atomicCounterBuffers) { if (block.referencedBy[glslType]) { // It is possible for the atomic counter buffer to indicate it // only has 4 bytes for a single counter located at offset=4. // But we will want to allocate a buffer large enough to store // from offset=0 to the last counter declared in the buffer. unsigned bufferDataSize = block.bufferDataSize; for (unsigned i=0; i < block.activeVariables.size(); ++i) { auto const& ac = uniforms[block.activeVariables[i]]; unsigned const lastByte = ac.offset + 4; bufferDataSize = std::max(bufferDataSize, lastByte); } mData[AtomicCounterBufferShaderDataLookup].push_back( Data(GT_RESOURCE, "atomicCounterBuffer" + std::to_string(blockIndex), block.bufferBinding, bufferDataSize, 0, true)); } ++blockIndex; } } // Gather the buffer blocks information to create structured buffer data. auto const& bufferBlocks = reflector.GetBufferBlocks(); int numBufferBlockReferences = 0; for (auto const& block : bufferBlocks) { if (block.referencedBy[glslType]) { ++numBufferBlockReferences; } } if (numBufferBlockReferences > 0) { auto const& bufferVariables = reflector.GetBufferVariables(); mSBufferLayouts.resize(numBufferBlockReferences); // Store information needed by GL4Engine for enabling/disabling the // structured buffers. int blockIndex = 0; int layoutIndex = 0; for (auto const& block : bufferBlocks) { if (block.referencedBy[glslType]) { // Search through uniforms looking for atomic counter with // the same name and "Counter" suffix. The ID is the index // for this uniform so that it can be looked up later. auto const counterName = block.name + "Counter"; bool hasAtomicCounter = false; unsigned int idAtomicCounter = ~0U; for (auto const& uniform : uniforms) { if ((counterName == uniform.name) && (uniform.atomicCounterBufferIndex >= 0)) { hasAtomicCounter = true; idAtomicCounter = static_cast<unsigned int>(mData[AtomicCounterShaderDataLookup].size()); mData[AtomicCounterShaderDataLookup].push_back( Data(GT_STRUCTURED_BUFFER, uniform.name, uniform.atomicCounterBufferIndex, 4, uniform.offset, false)); break; } } // Assemble the structured buffer layout information. Only // interested in variables in the buffer that are part of a // top level array stride. Anything up to this block is // ignored and anything after this block is ignored which // means only one top level array is supported. auto& layout = mSBufferLayouts[layoutIndex]; GLint structSize = 0; for (unsigned v = 0; v < block.activeVariables.size(); ++v) { auto const& bufferVar = bufferVariables[block.activeVariables[v]]; if (bufferVar.topLevelArrayStride != structSize) { // Stop when we were processing buffer variables with // a certain top-level array stride and that changed. if (0 != structSize) { break; } structSize = bufferVar.topLevelArrayStride; } // These are the variables in the structured buffer. if (structSize > 0) { MemberLayout item; item.name = bufferVar.name; item.offset = bufferVar.offset; // TODO: The HLSL reflection has numElements of 0 when // the item is not an array, but the actual number // when it is an array. ConstantBuffer::SetMember(...) // uses this information, so we need to adhere to the // pattern. Change this design in a refactor? item.numElements = (bufferVar.arraySize > 1 ? bufferVar.arraySize : 0); layout.push_back(item); } } // Use the top level array stride as a better indication // of the overall struct size. mData[StructuredBuffer::shaderDataLookup].push_back( Data(GT_STRUCTURED_BUFFER, block.name, block.bufferBinding, structSize, idAtomicCounter, hasAtomicCounter)); // OpenGL implementions might store structured buffer member // information in different orders; for example, alphabetical // by name or by offset. To produce a consistent layout, sort // the layout by offset. std::sort(layout.begin(), layout.end(), [](MemberLayout const& layout0, MemberLayout const& layout1) { return layout0.offset < layout1.offset; } ); ++layoutIndex; } ++blockIndex; } } } void GLSLShader::Set(std::string const&, std::shared_ptr<TextureSingle> const& texture, std::string const& samplerName, std::shared_ptr<SamplerState> const& state) { Shader::Set(samplerName, texture); Shader::Set(samplerName, state); } void GLSLShader::Set(std::string const&, std::shared_ptr<TextureArray> const& texture, std::string const& samplerName, std::shared_ptr<SamplerState> const& state) { Shader::Set(samplerName, texture); Shader::Set(samplerName, state); } bool GLSLShader::IsValid(Data const& goal, ConstantBuffer* resource) const { if (!resource) { // resource is null return false; } if (goal.type != GT_CONSTANT_BUFFER) { // mismatch of buffer type return false; } if (resource->GetNumBytes() >= static_cast<size_t>(goal.numBytes)) { return true; } // invalid number of bytes return false; } bool GLSLShader::IsValid(Data const& goal, TextureBuffer* resource) const { if (!resource) { // resource is null return false; } if (goal.type != GT_TEXTURE_BUFFER) { // mismatch of buffer type return false; } if (resource->GetNumBytes() >= static_cast<size_t>(goal.numBytes)) { return true; } // invalid number of bytes return false; } bool GLSLShader::IsValid(Data const& goal, StructuredBuffer* resource) const { if (!resource) { // resource is null return false; } if (goal.type != GT_STRUCTURED_BUFFER) { // invalid number of bytes return false; } // GL4 reflection does not provide information about writable access of // buffer objects in a shader because by definition, shader storage buffer // objects can be read-write by shaders. For GL4, the isGpuWritable flag // is used to indicate whether the structured buffer has a counter // attached or not. Thus, the test that is performed in the DX11 IsValid // code cannot be used here. // OpenGL does not have the concept of an append-consume type structured // buffer nor does it have the concept of a structured buffer with // counter. But, this GL4 support does associate an atomic counter with // a structured buffer as long as it has the same name. If the shader is // expecting a counter, then the structured buffer needs to be declared // with one. if (goal.isGpuWritable && (StructuredBuffer::CT_NONE == resource->GetCounterType())) { // mismatch of counter type return false; } return true; } bool GLSLShader::IsValid(Data const& goal, RawBuffer* resource) const { if (!resource) { // resource is null return false; } if (goal.type != GT_RAW_BUFFER) { // mismatch of buffer type return false; } if (goal.isGpuWritable && resource->GetUsage() != Resource::SHADER_OUTPUT) { // mismatch of GPU write flag return false; } return true; } bool GLSLShader::IsValid(Data const& goal, TextureSingle* resource) const { if (!resource) { // resource is null return false; } if (goal.type != GT_TEXTURE_SINGLE) { // mismatch of texture type return false; } // GL4 reflection does not provide information about writable access of // gimage* and gsampler* objects in a shader. For GL4, the isGpuWritable // flag is used to indicate whether the texture could be writable in // shader which is false for gshader* objects and is true for gimage* // objects. Thus, the test that is performed in the DX11 IsValid code // cannot be used here. if (goal.extra != resource->GetNumDimensions()) { // mismatch of texture dimensions return false; } return true; } bool GLSLShader::IsValid(Data const& goal, TextureArray* resource) const { if (!resource) { // resource is null return false; } if (goal.type != GT_TEXTURE_ARRAY) { // mismatch of texture type return false; } // GL4 reflection does not provide information about writable access of // gimage* and gsampler* objects in a shader. For GL4, the isGpuWritable // flag is used to indicate whether the texture could be writable in // shader which is false for gshader* objects and is true for gimage* // objects. Thus, the test that is performed in the DX11 IsValid code // cannot be used here. if (goal.extra != resource->GetNumDimensions()) { // mismatch of texture dimensions return false; } return true; } bool GLSLShader::IsValid(Data const& goal, SamplerState* resource) const { if (!resource) { // resource is null return false; } if (goal.type != GT_SAMPLER_STATE) { // mismatch of state return false; } return true; }
20,202
5,814
/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, Willow Garage, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * */ #ifndef PCL_FEATURES_IMPL_BOARD_H_ #define PCL_FEATURES_IMPL_BOARD_H_ #include <pcl/features/board.h> #include <utility> #include <pcl/common/transforms.h> ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointNT, typename PointOutT> void pcl::BOARDLocalReferenceFrameEstimation<PointInT, PointNT, PointOutT>:: directedOrthogonalAxis(Eigen::Vector3f const &axis, Eigen::Vector3f const &axis_origin, Eigen::Vector3f const &point, Eigen::Vector3f &directed_ortho_axis) { Eigen::Vector3f projection; projectPointOnPlane(point, axis_origin, axis, projection); directed_ortho_axis = projection - axis_origin; directed_ortho_axis.normalize(); // check if the computed x axis is orthogonal to the normal // assert(areEquals((float)(directed_ortho_axis.dot(axis)), 0.0f, 1E-3f)); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointNT, typename PointOutT> void pcl::BOARDLocalReferenceFrameEstimation<PointInT, PointNT, PointOutT>:: projectPointOnPlane(Eigen::Vector3f const &point, Eigen::Vector3f const &origin_point, Eigen::Vector3f const &plane_normal, Eigen::Vector3f &projected_point) { float t; Eigen::Vector3f xo; xo = point - origin_point; t = plane_normal.dot(xo); projected_point = point - (t * plane_normal); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointNT, typename PointOutT> float pcl::BOARDLocalReferenceFrameEstimation<PointInT, PointNT, PointOutT>:: getAngleBetweenUnitVectors(Eigen::Vector3f const &v1, Eigen::Vector3f const &v2, Eigen::Vector3f const &axis) { Eigen::Vector3f angle_orientation; angle_orientation = v1.cross(v2); float angle_radians = acosf(std::max(-1.0f, std::min(1.0f, v1.dot(v2)))); angle_radians = angle_orientation.dot(axis) < 0.f ? (2 * static_cast<float>(M_PI) - angle_radians) : angle_radians; return (angle_radians); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointNT, typename PointOutT> void pcl::BOARDLocalReferenceFrameEstimation<PointInT, PointNT, PointOutT>:: randomOrthogonalAxis(Eigen::Vector3f const &axis, Eigen::Vector3f &rand_ortho_axis) { if (!areEquals(axis.z(), 0.0f)) { rand_ortho_axis.x() = (static_cast<float>(rand()) / static_cast<float>(RAND_MAX)) * 2.0f - 1.0f; rand_ortho_axis.y() = (static_cast<float>(rand()) / static_cast<float>(RAND_MAX)) * 2.0f - 1.0f; rand_ortho_axis.z() = -(axis.x() * rand_ortho_axis.x() + axis.y() * rand_ortho_axis.y()) / axis.z(); } else if (!areEquals(axis.y(), 0.0f)) { rand_ortho_axis.x() = (static_cast<float>(rand()) / static_cast<float>(RAND_MAX)) * 2.0f - 1.0f; rand_ortho_axis.z() = (static_cast<float>(rand()) / static_cast<float>(RAND_MAX)) * 2.0f - 1.0f; rand_ortho_axis.y() = -(axis.x() * rand_ortho_axis.x() + axis.z() * rand_ortho_axis.z()) / axis.y(); } else if (!areEquals(axis.x(), 0.0f)) { rand_ortho_axis.y() = (static_cast<float>(rand()) / static_cast<float>(RAND_MAX)) * 2.0f - 1.0f; rand_ortho_axis.z() = (static_cast<float>(rand()) / static_cast<float>(RAND_MAX)) * 2.0f - 1.0f; rand_ortho_axis.x() = -(axis.y() * rand_ortho_axis.y() + axis.z() * rand_ortho_axis.z()) / axis.x(); } rand_ortho_axis.normalize(); // check if the computed x axis is orthogonal to the normal // assert(areEquals(rand_ortho_axis.dot(axis), 0.0f, 1E-6f)); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointNT, typename PointOutT> void pcl::BOARDLocalReferenceFrameEstimation<PointInT, PointNT, PointOutT>:: planeFitting(Eigen::Matrix<float, Eigen::Dynamic, 3> const &points, Eigen::Vector3f &center, Eigen::Vector3f &norm) { // ----------------------------------------------------- // Plane Fitting using Singular Value Decomposition (SVD) // ----------------------------------------------------- int n_points = static_cast<int>(points.rows()); if (n_points == 0) { return; } // find the center by averaging the points positions center.setZero(); for (int i = 0; i < n_points; ++i) { center += points.row(i); } center /= static_cast<float>(n_points); // copy points - average (center) Eigen::Matrix<float, Eigen::Dynamic, 3> A(n_points, 3); // PointData for (int i = 0; i < n_points; ++i) { A(i, 0) = points(i, 0) - center.x(); A(i, 1) = points(i, 1) - center.y(); A(i, 2) = points(i, 2) - center.z(); } Eigen::JacobiSVD<Eigen::MatrixXf> svd(A, Eigen::ComputeFullV); norm = svd.matrixV().col(2); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointNT, typename PointOutT> void pcl::BOARDLocalReferenceFrameEstimation<PointInT, PointNT, PointOutT>:: normalDisambiguation(pcl::PointCloud<PointNT> const &normal_cloud, std::vector<int> const &normal_indices, Eigen::Vector3f &normal) { Eigen::Vector3f normal_mean; normal_mean.setZero(); for (size_t i = 0; i < normal_indices.size(); ++i) { const PointNT &curPt = normal_cloud[normal_indices[i]]; normal_mean += curPt.getNormalVector3fMap(); } normal_mean.normalize(); if (normal.dot(normal_mean) < 0) { normal = -normal; } } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointNT, typename PointOutT> float pcl::BOARDLocalReferenceFrameEstimation< PointInT, PointNT, PointOutT>::computePointLRF(const int &index, Eigen::Matrix3f &lrf) { // find Z axis // extract support points for Rz radius std::vector<int> neighbours_indices; std::vector<float> neighbours_distances; int n_neighbours = this->searchForNeighbors( index, search_parameter_, neighbours_indices, neighbours_distances); // check if there are enough neighbor points, otherwise compute a random X // axis and use normal as Z axis if (n_neighbours < 6) { // PCL_WARN( // "[pcl::%s::computePointLRF] Warning! Neighborhood has less than 6 // vertices. Aborting description of point with index %d\n", // getClassName().c_str(), index); // setting lrf to NaN lrf.setConstant(std::numeric_limits<float>::quiet_NaN()); return (std::numeric_limits<float>::max()); } // copy neighbours coordinates into eigen matrix Eigen::Matrix<float, Eigen::Dynamic, 3> neigh_points_mat(n_neighbours, 3); for (int i = 0; i < n_neighbours; ++i) { neigh_points_mat.row(i) = (*surface_)[neighbours_indices[i]].getVector3fMap(); } Eigen::Vector3f x_axis, y_axis; // plane fitting to find direction of Z axis Eigen::Vector3f fitted_normal; // z_axis Eigen::Vector3f centroid; planeFitting(neigh_points_mat, centroid, fitted_normal); // disambiguate Z axis with normal mean normalDisambiguation(*normals_, neighbours_indices, fitted_normal); // setting LRF Z axis lrf.row(2).matrix() = fitted_normal; ///////////////////////////////////////////////////////////////////////////////////////// // find X axis // extract support points for Rx radius if (tangent_radius_ != 0.0f && search_parameter_ != tangent_radius_) { n_neighbours = this->searchForNeighbors( index, tangent_radius_, neighbours_indices, neighbours_distances); } // find point with the "most different" normal (with respect to // fittedNormal) float min_normal_cos = std::numeric_limits<float>::max(); int min_normal_index = -1; bool margin_point_found = false; Eigen::Vector3f best_margin_point; bool best_point_found_on_margins = false; float radius2 = tangent_radius_ * tangent_radius_; float margin_distance2 = margin_thresh_ * margin_thresh_ * radius2; float max_boundary_angle = 0; if (find_holes_) { randomOrthogonalAxis(fitted_normal, x_axis); lrf.row(0).matrix() = x_axis; for (int i = 0; i < check_margin_array_size_; i++) { check_margin_array_[i] = false; margin_array_min_angle_[i] = std::numeric_limits<float>::max(); margin_array_max_angle_[i] = -std::numeric_limits<float>::max(); margin_array_min_angle_normal_[i] = -1.0; margin_array_max_angle_normal_[i] = -1.0; } max_boundary_angle = (2 * static_cast<float>(M_PI)) / static_cast<float>(check_margin_array_size_); } for (int curr_neigh = 0; curr_neigh < n_neighbours; ++curr_neigh) { const int &curr_neigh_idx = neighbours_indices[curr_neigh]; const float &neigh_distance_sqr = neighbours_distances[curr_neigh]; if (neigh_distance_sqr <= margin_distance2) { continue; } // point normalIndex is inside the ring between marginThresh and Radius margin_point_found = true; Eigen::Vector3f normal_mean = normals_->at(curr_neigh_idx).getNormalVector3fMap(); float normal_cos = fitted_normal.dot(normal_mean); if (normal_cos < min_normal_cos) { min_normal_index = curr_neigh_idx; min_normal_cos = normal_cos; best_point_found_on_margins = false; } if (find_holes_) { // find angle with respect to random axis previously calculated Eigen::Vector3f indicating_normal_vect; directedOrthogonalAxis( fitted_normal, input_->at(index).getVector3fMap(), surface_->at(curr_neigh_idx).getVector3fMap(), indicating_normal_vect); float angle = getAngleBetweenUnitVectors( x_axis, indicating_normal_vect, fitted_normal); int check_margin_array_idx = std::min(static_cast<int>(floor(angle / max_boundary_angle)), check_margin_array_size_ - 1); check_margin_array_[check_margin_array_idx] = true; if (angle < margin_array_min_angle_[check_margin_array_idx]) { margin_array_min_angle_[check_margin_array_idx] = angle; margin_array_min_angle_normal_[check_margin_array_idx] = normal_cos; } if (angle > margin_array_max_angle_[check_margin_array_idx]) { margin_array_max_angle_[check_margin_array_idx] = angle; margin_array_max_angle_normal_[check_margin_array_idx] = normal_cos; } } } // for each neighbor if (!margin_point_found) { // find among points with neighDistance <= marginThresh*radius for (int curr_neigh = 0; curr_neigh < n_neighbours; curr_neigh++) { const int &curr_neigh_idx = neighbours_indices[curr_neigh]; const float &neigh_distance_sqr = neighbours_distances[curr_neigh]; if (neigh_distance_sqr > margin_distance2) continue; Eigen::Vector3f normal_mean = normals_->at(curr_neigh_idx).getNormalVector3fMap(); float normal_cos = fitted_normal.dot(normal_mean); if (normal_cos < min_normal_cos) { min_normal_index = curr_neigh_idx; min_normal_cos = normal_cos; } } // for each neighbor // find orthogonal axis directed to minNormalIndex point projection on // plane with fittedNormal as axis directedOrthogonalAxis( fitted_normal, input_->at(index).getVector3fMap(), surface_->at(min_normal_index).getVector3fMap(), x_axis); y_axis = fitted_normal.cross(x_axis); lrf.row(0).matrix() = x_axis; lrf.row(1).matrix() = y_axis; // z axis already set return (min_normal_cos); } if (!find_holes_) { if (best_point_found_on_margins) { // if most inclined normal is on support margin directedOrthogonalAxis(fitted_normal, input_->at(index).getVector3fMap(), best_margin_point, x_axis); y_axis = fitted_normal.cross(x_axis); lrf.row(0).matrix() = x_axis; lrf.row(1).matrix() = y_axis; // z axis already set return (min_normal_cos); } directedOrthogonalAxis( fitted_normal, input_->at(index).getVector3fMap(), surface_->at(min_normal_index).getVector3fMap(), x_axis); y_axis = fitted_normal.cross(x_axis); lrf.row(0).matrix() = x_axis; lrf.row(1).matrix() = y_axis; // z axis already set return (min_normal_cos); } // if(!find_holes_) // check if there is at least a hole bool is_hole_present = false; for (int i = 0; i < check_margin_array_size_; i++) { if (!check_margin_array_[i]) { is_hole_present = true; break; } } if (!is_hole_present) { if (best_point_found_on_margins) { // if most inclined normal is on support margin directedOrthogonalAxis(fitted_normal, input_->at(index).getVector3fMap(), best_margin_point, x_axis); y_axis = fitted_normal.cross(x_axis); lrf.row(0).matrix() = x_axis; lrf.row(1).matrix() = y_axis; // z axis already set return (min_normal_cos); } // find orthogonal axis directed to minNormalIndex point projection on // plane with fittedNormal as axis directedOrthogonalAxis( fitted_normal, input_->at(index).getVector3fMap(), surface_->at(min_normal_index).getVector3fMap(), x_axis); y_axis = fitted_normal.cross(x_axis); lrf.row(0).matrix() = x_axis; lrf.row(1).matrix() = y_axis; // z axis already set return (min_normal_cos); } // if (!is_hole_present) // case hole found // find missing region float angle = 0.0; int hole_end; int hole_first; // find first no border pie int first_no_border = -1; if (check_margin_array_[check_margin_array_size_ - 1]) { first_no_border = 0; } else { for (int i = 0; i < check_margin_array_size_; i++) { if (check_margin_array_[i]) { first_no_border = i; break; } } } // float steep_prob = 0.0; float max_hole_prob = -std::numeric_limits<float>::max(); // find holes for (int ch = first_no_border; ch < check_margin_array_size_; ch++) { if (!check_margin_array_[ch]) { // border beginning found hole_first = ch; hole_end = hole_first + 1; while (!check_margin_array_[hole_end % check_margin_array_size_]) { ++hole_end; } // border end found, find angle if ((hole_end - hole_first) > 0) { // check if hole can be a shapeness hole int previous_hole = (((hole_first - 1) < 0) ? (hole_first - 1) + check_margin_array_size_ : (hole_first - 1)) % check_margin_array_size_; int following_hole = (hole_end) % check_margin_array_size_; float normal_begin = margin_array_max_angle_normal_[previous_hole]; float normal_end = margin_array_min_angle_normal_[following_hole]; normal_begin -= min_normal_cos; normal_end -= min_normal_cos; normal_begin = normal_begin / (1.0f - min_normal_cos); normal_end = normal_end / (1.0f - min_normal_cos); normal_begin = 1.0f - normal_begin; normal_end = 1.0f - normal_end; // evaluate P(Hole); float hole_width = 0.0f; if (following_hole < previous_hole) { hole_width = margin_array_min_angle_[following_hole] + 2 * static_cast<float>(M_PI) - margin_array_max_angle_[previous_hole]; } else { hole_width = margin_array_min_angle_[following_hole] - margin_array_max_angle_[previous_hole]; } float hole_prob = hole_width / (2 * static_cast<float>(M_PI)); // evaluate P(zmin|Hole) float steep_prob = (normal_end + normal_begin) / 2.0f; // check hole prob and after that, check steepThresh if (hole_prob > hole_size_prob_thresh_) { if (steep_prob > steep_thresh_) { if (hole_prob > max_hole_prob) { max_hole_prob = hole_prob; float angle_weight = ((normal_end - normal_begin) + 1.0f) / 2.0f; if (following_hole < previous_hole) { angle = margin_array_max_angle_[previous_hole] + (margin_array_min_angle_[following_hole] + 2 * static_cast<float>(M_PI) - margin_array_max_angle_[previous_hole]) * angle_weight; } else { angle = margin_array_max_angle_[previous_hole] + (margin_array_min_angle_[following_hole] - margin_array_max_angle_[previous_hole]) * angle_weight; } } } } } //(hole_end-hole_first) > 0 if (hole_end >= check_margin_array_size_) { break; } else { ch = hole_end - 1; } } } if (max_hole_prob > -std::numeric_limits<float>::max()) { // hole found Eigen::AngleAxisf rotation = Eigen::AngleAxisf(angle, fitted_normal); x_axis = rotation * x_axis; min_normal_cos -= 10.0f; } else { if (best_point_found_on_margins) { // if most inclined normal is on support margin directedOrthogonalAxis(fitted_normal, input_->at(index).getVector3fMap(), best_margin_point, x_axis); } else { // find orthogonal axis directed to minNormalIndex point projection // on plane with fittedNormal as axis directedOrthogonalAxis( fitted_normal, input_->at(index).getVector3fMap(), surface_->at(min_normal_index).getVector3fMap(), x_axis); } } y_axis = fitted_normal.cross(x_axis); lrf.row(0).matrix() = x_axis; lrf.row(1).matrix() = y_axis; // z axis already set return (min_normal_cos); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointNT, typename PointOutT> void pcl::BOARDLocalReferenceFrameEstimation< PointInT, PointNT, PointOutT>::computeFeature(PointCloudOut &output) { // check whether used with search radius or search k-neighbors if (this->getKSearch() != 0) { PCL_ERROR("[pcl::%s::computeFeature] Error! Search method set to " "k-neighborhood. Call setKSearch(0) and setRadiusSearch( " "radius ) to use this class.\n", getClassName().c_str()); return; } this->resetData(); for (size_t point_idx = 0; point_idx < indices_->size(); ++point_idx) { Eigen::Matrix3f currentLrf; PointOutT &rf = output[point_idx]; // rf.confidence = computePointLRF (*indices_[point_idx], currentLrf); // if (rf.confidence == std::numeric_limits<float>::max ()) if (computePointLRF((*indices_)[point_idx], currentLrf) == std::numeric_limits<float>::max()) { output.is_dense = false; } for (int d = 0; d < 3; ++d) { rf.x_axis[d] = currentLrf(0, d); rf.y_axis[d] = currentLrf(1, d); rf.z_axis[d] = currentLrf(2, d); } } } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointNT> void pcl::BOARDLocalReferenceFrameEstimation<PointInT, PointNT, Eigen::MatrixXf>:: computeFeatureEigen(pcl::PointCloud<Eigen::MatrixXf> &output) { // check whether used with search radius or search k-neighbors if (this->getKSearch() != 0) { PCL_ERROR("[pcl::%s::computeFeatureEigen] Error! Search method set to " "k-neighborhood. Call setKSearch(0) and setRadiusSearch( " "radius ) to use this class.\n", getClassName().c_str()); return; } this->resetData(); // Set up the output channels output.channels["board"].name = "board"; output.channels["board"].offset = 0; output.channels["board"].size = 4; output.channels["board"].count = 9; output.channels["board"].datatype = sensor_msgs::PointField::FLOAT32; // output.points.resize (indices_->size (), 10); output.points.resize(indices_->size(), 9); for (size_t point_idx = 0; point_idx < indices_->size(); ++point_idx) { Eigen::Matrix3f currentLrf; // output.points (point_idx, 9) = computePointLRF (*indices_[point_idx], // currentLrf); if (output.points (point_idx, 9) == // std::numeric_limits<float>::max ()) if (this->computePointLRF((*indices_)[point_idx], currentLrf) == std::numeric_limits<float>::max()) { output.is_dense = false; } output.points.block<1, 3>(point_idx, 0).matrix() = currentLrf.row(0); output.points.block<1, 3>(point_idx, 3).matrix() = currentLrf.row(1); output.points.block<1, 3>(point_idx, 6).matrix() = currentLrf.row(2); } } #define PCL_INSTANTIATE_BOARDLocalReferenceFrameEstimation(T, NT, OutT) \ template class PCL_EXPORTS \ pcl::BOARDLocalReferenceFrameEstimation<T, NT, OutT>; #endif // PCL_FEATURES_IMPL_BOARD_H_
25,492
7,879
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <future> // class promise<R> // void promise::set_value_at_thread_exit(R&& r); #include <future> #include <memory> #include <cassert> #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES void func(std::promise<std::unique_ptr<int>>& p) { p.set_value_at_thread_exit(std::unique_ptr<int>(new int(5))); } #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES int main() { #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES { std::promise<std::unique_ptr<int>> p; std::future<std::unique_ptr<int>> f = p.get_future(); std::thread(func, std::move(p)).detach(); assert(*f.get() == 5); } #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES }
1,006
357
#include "RC4.h" NAMESPACE_UPP RC4::RC4() : Cypher(1 /* stream cypher */) { memset(sbox, 0, 256); si = sj = 0; } RC4::RC4(String const &key, String const &nonce) : Cypher(1 /* stream cypher */) { SetKey(key, nonce); } RC4::RC4(byte const *keyBuf, size_t keyLen, byte const *nonce, size_t nonceLen) : Cypher(1 /* stream cypher */) { SetKey(keyBuf, keyLen, nonce, nonceLen); } bool RC4::CypherKey(byte const *kBuf, size_t keyLen, byte const *nonce, size_t nonceLen) { int i, j; unsigned char keyarr[256], swap; // appends NONCE at key -- avoids repeated encoding of same soruce stream Buffer<byte>keyBuf(keyLen + nonceLen); memcpy(keyBuf, kBuf, keyLen); memcpy(keyBuf + keyLen, nonce, nonceLen); keyLen += nonceLen; si = sj = 0; for (i = j = 0; i < 256; i++, j = (j + 1) % keyLen) { sbox[i] = i; keyarr[i] = keyBuf[j]; } for (i = j = 0; i < 256; i++) { j += sbox[i] + keyarr[i]; j %= 256; swap = sbox[i]; sbox[i] = sbox[j]; sbox[j] = swap; } // discards first 256 stream values -- see wikipedia for details for(i = 0; i < 256; i++) { sj += sbox[++si]; swap = sbox[si]; sbox[si] = sbox[sj]; sbox[sj] = swap; swap = sbox[si] + sbox[sj]; } return true; } // encode/decode buffer, dest on different buffer void RC4::CypherCypher(const byte *src, byte *dst, size_t len) { unsigned char swap; while (len--) { sj += sbox[++si]; swap = sbox[si]; sbox[si] = sbox[sj]; sbox[sj] = swap; swap = sbox[si] + sbox[sj]; *dst++ = *src++ ^ sbox[swap]; } } END_UPP_NAMESPACE;
1,540
758
#include "../headers/File_not_found.h" File_not_found::File_not_found(std::string erro) : std::runtime_error(std::string("File : ")+erro+std::string(" not found!\n")) { } File_not_found::File_not_found() :std::runtime_error("File not found !") { } File_not_found::~File_not_found() { }
295
122