max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
332
<reponame>wwjiang007/spring-xd /** * Package for twitter integration extensions. */ package org.springframework.integration.x.twitter;
40
499
#define SOFTFLOAT_68K #include <stdint.h> #include <stdlib.h> #include "softfloat/softfloat.h" /* * QEMU float support * * The code in this source file is derived from release 2a of the SoftFloat * IEC/IEEE Floating-point Arithmetic Package. Those parts of the code (and * some later contributions) are provided under that license, as detailed below. * It has subsequently been modified by contributors to the QEMU Project, * so some portions are provided under: * the SoftFloat-2a license * the BSD license * GPL-v2-or-later * * Any future contributions to this file after December 1st 2014 will be * taken to be licensed under the Softfloat-2a license unless specifically * indicated otherwise. */ /* =============================================================================== This C source file is part of the SoftFloat IEC/IEEE Floating-point Arithmetic Package, Release 2a. Written by <NAME>. This work was made possible in part by the International Computer Science Institute, located at Suite 600, 1947 Center Street, Berkeley, California 94704. Funding was partially provided by the National Science Foundation under grant MIP-9311980. The original version of this code was written as part of a project to build a fixed-point vector processor in collaboration with the University of California at Berkeley, overseen by Profs. <NAME> and <NAME>. More information is available through the Web page `http://HTTP.CS.Berkeley.EDU/~jhauser/ arithmetic/SoftFloat.html'. THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE. Although reasonable effort has been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT TIMES RESULT IN INCORRECT BEHAVIOR. USE OF THIS SOFTWARE IS RESTRICTED TO PERSONS AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ANY AND ALL LOSSES, COSTS, OR OTHER PROBLEMS ARISING FROM ITS USE. Derivative works are acceptable, even for commercial purposes, so long as (1) they include prominent notice that the work is derivative, and (2) they include prominent notice akin to these four paragraphs for those parts of this code that are retained. =============================================================================== */ /* BSD licensing: * Copyright (c) 2006, <NAME> * 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. */ /* Portions of this work are licensed under the terms of the GNU GPL, * version 2 or later. See the COPYING file in the top-level directory. */ /* We only need stdlib for abort() */ /*---------------------------------------------------------------------------- | Primitive arithmetic functions, including multi-word arithmetic, and | division and square root approximations. (Can be specialized to target if | desired.) *----------------------------------------------------------------------------*/ #include "softfloat-macros.h" /*---------------------------------------------------------------------------- | Variables for storing sign, exponent and significand of internal extended | double-precision floating-point value for external use. *----------------------------------------------------------------------------*/ flag floatx80_internal_sign = 0; int32_t floatx80_internal_exp = 0; uint64_t floatx80_internal_sig = 0; int32_t floatx80_internal_exp0 = 0; uint64_t floatx80_internal_sig0 = 0; uint64_t floatx80_internal_sig1 = 0; int8_t floatx80_internal_precision = 80; int8_t floatx80_internal_mode = float_round_nearest_even; /*---------------------------------------------------------------------------- | Functions for storing sign, exponent and significand of extended | double-precision floating-point intermediate result for external use. *----------------------------------------------------------------------------*/ floatx80 roundSaveFloatx80Internal( int8_t roundingPrecision, flag zSign, int32_t zExp, uint64_t zSig0, uint64_t zSig1, float_status *status ) { uint64_t roundIncrement, roundMask, roundBits; flag increment; if ( roundingPrecision == 80 ) { goto precision80; } else if ( roundingPrecision == 64 ) { roundIncrement = LIT64( 0x0000000000000400 ); roundMask = LIT64( 0x00000000000007FF ); } else if ( roundingPrecision == 32 ) { roundIncrement = LIT64( 0x0000008000000000 ); roundMask = LIT64( 0x000000FFFFFFFFFF ); } else { goto precision80; } zSig0 |= ( zSig1 != 0 ); if ( status->float_rounding_mode != float_round_nearest_even ) { if ( status->float_rounding_mode == float_round_to_zero ) { roundIncrement = 0; } else { roundIncrement = roundMask; if ( zSign ) { if ( status->float_rounding_mode == float_round_up ) roundIncrement = 0; } else { if ( status->float_rounding_mode == float_round_down ) roundIncrement = 0; } } } roundBits = zSig0 & roundMask; zSig0 += roundIncrement; if ( zSig0 < roundIncrement ) { ++zExp; zSig0 = LIT64( 0x8000000000000000 ); } roundIncrement = roundMask + 1; if ( status->float_rounding_mode == float_round_nearest_even && ( roundBits<<1 == roundIncrement ) ) { roundMask |= roundIncrement; } zSig0 &= ~ roundMask; if ( zSig0 == 0 ) zExp = 0; return packFloatx80( zSign, zExp, zSig0 ); precision80: increment = ( (int64_t) zSig1 < 0 ); if ( status->float_rounding_mode != float_round_nearest_even ) { if ( status->float_rounding_mode == float_round_to_zero ) { increment = 0; } else { if ( zSign ) { increment = ( status->float_rounding_mode == float_round_down ) && zSig1; } else { increment = ( status->float_rounding_mode == float_round_up ) && zSig1; } } } if ( increment ) { ++zSig0; if ( zSig0 == 0 ) { ++zExp; zSig0 = LIT64( 0x8000000000000000 ); } else { if ((zSig1 << 1) == 0 && status->float_rounding_mode == float_round_nearest_even) zSig0 &= ~1; } } else { if ( zSig0 == 0 ) zExp = 0; } return packFloatx80( zSign, zExp, zSig0 ); } static void saveFloatx80Internal( int8_t prec, flag zSign, int32_t zExp, uint64_t zSig0, uint64_t zSig1, float_status *status ) { floatx80_internal_sign = zSign; floatx80_internal_exp = zExp; floatx80_internal_sig0 = zSig0; floatx80_internal_sig1 = zSig1; floatx80_internal_precision = prec; floatx80_internal_mode = status->float_rounding_mode; } static void saveFloat64Internal( flag zSign, int16_t zExp, uint64_t zSig, float_status *status ) { floatx80_internal_sign = zSign; floatx80_internal_exp = zExp + 0x3C01; floatx80_internal_sig0 = zSig<<1; floatx80_internal_sig1 = 0; floatx80_internal_precision = 64; floatx80_internal_mode = status->float_rounding_mode; } static void saveFloat32Internal( flag zSign, int16_t zExp, uint32_t zSig, float_status *status ) { floatx80 z = roundSaveFloatx80Internal( 32, zSign, zExp + 0x3F81, ( (uint64_t) zSig )<<33, 0, status ); floatx80_internal_sign = zSign; floatx80_internal_exp = extractFloatx80Exp( z ); floatx80_internal_sig = extractFloatx80Frac( z ); floatx80_internal_exp0 = zExp + 0x3F81; floatx80_internal_sig0 = ( (uint64_t) zSig )<<33; floatx80_internal_sig1 = 0; } /*---------------------------------------------------------------------------- | Functions for returning sign, exponent and significand of extended | double-precision floating-point intermediate result for external use. *----------------------------------------------------------------------------*/ void getRoundedFloatInternal( int8_t roundingPrecision, flag *pzSign, int32_t *pzExp, uint64_t *pzSig ) { uint64_t roundIncrement, roundMask, roundBits; flag increment; flag zSign = floatx80_internal_sign; int32_t zExp = floatx80_internal_exp; uint64_t zSig0 = floatx80_internal_sig0; uint64_t zSig1 = floatx80_internal_sig1; if ( roundingPrecision == 80 ) { goto precision80; } else if ( roundingPrecision == 64 ) { roundIncrement = LIT64( 0x0000000000000400 ); roundMask = LIT64( 0x00000000000007FF ); } else if ( roundingPrecision == 32 ) { roundIncrement = LIT64( 0x0000008000000000 ); roundMask = LIT64( 0x000000FFFFFFFFFF ); } else { goto precision80; } zSig0 |= ( zSig1 != 0 ); if ( floatx80_internal_mode != float_round_nearest_even ) { if ( floatx80_internal_mode == float_round_to_zero ) { roundIncrement = 0; } else { roundIncrement = roundMask; if ( zSign ) { if ( floatx80_internal_mode == float_round_up ) roundIncrement = 0; } else { if ( floatx80_internal_mode == float_round_down ) roundIncrement = 0; } } } roundBits = zSig0 & roundMask; zSig0 += roundIncrement; if ( zSig0 < roundIncrement ) { ++zExp; zSig0 = LIT64( 0x8000000000000000 ); } roundIncrement = roundMask + 1; if ( floatx80_internal_mode == float_round_nearest_even && ( roundBits<<1 == roundIncrement ) ) { roundMask |= roundIncrement; } zSig0 &= ~ roundMask; if ( zSig0 == 0 ) zExp = 0; *pzSign = zSign; *pzExp = zExp; *pzSig = zSig0; return; precision80: increment = ( (int64_t) zSig1 < 0 ); if ( floatx80_internal_mode != float_round_nearest_even ) { if ( floatx80_internal_mode == float_round_to_zero ) { increment = 0; } else { if ( zSign ) { increment = ( floatx80_internal_mode == float_round_down ) && zSig1; } else { increment = ( floatx80_internal_mode == float_round_up ) && zSig1; } } } if ( increment ) { ++zSig0; if ( zSig0 == 0 ) { ++zExp; zSig0 = LIT64( 0x8000000000000000 ); } else { if ((zSig1 << 1) == 0 && floatx80_internal_mode == float_round_nearest_even) zSig0 &= ~1; } } else { if ( zSig0 == 0 ) zExp = 0; } *pzSign = zSign; *pzExp = zExp; *pzSig = zSig0; } floatx80 getFloatInternalOverflow( void ) { flag zSign; int32_t zExp; uint64_t zSig; getRoundedFloatInternal( floatx80_internal_precision, &zSign, &zExp, &zSig ); if (zExp > (0x7fff + 0x6000)) { // catastrophic zExp = 0; } else { zExp -= 0x6000; } return packFloatx80( zSign, zExp, zSig ); } floatx80 getFloatInternalUnderflow( void ) { flag zSign; int32_t zExp; uint64_t zSig; getRoundedFloatInternal( floatx80_internal_precision, &zSign, &zExp, &zSig ); if (zExp < (0x0000 - 0x6000)) { // catastrophic zExp = 0; } else { zExp += 0x6000; } return packFloatx80( zSign, zExp, zSig ); } floatx80 getFloatInternalRoundedAll( void ) { flag zSign; int32_t zExp; uint64_t zSig, zSig32, zSig64, zSig80; if (floatx80_internal_precision == 80) { getRoundedFloatInternal( 80, &zSign, &zExp, &zSig80 ); zSig = zSig80; } else if (floatx80_internal_precision == 64) { getRoundedFloatInternal( 80, &zSign, &zExp, &zSig80 ); getRoundedFloatInternal( 64, &zSign, &zExp, &zSig64 ); zSig = zSig64; zSig |= zSig80 & LIT64( 0x00000000000007FF ); } else { getRoundedFloatInternal( 80, &zSign, &zExp, &zSig80 ); getRoundedFloatInternal( 64, &zSign, &zExp, &zSig64 ); getRoundedFloatInternal( 32, &zSign, &zExp, &zSig32 ); zSig = zSig32; zSig |= zSig64 & LIT64( 0x000000FFFFFFFFFF ); zSig |= zSig80 & LIT64( 0x00000000000007FF ); } return packFloatx80( zSign, zExp & 0x7FFF, zSig ); } floatx80 getFloatInternalRoundedSome( void ) { flag zSign; int32_t zExp; uint64_t zSig, zSig32, zSig64, zSig80; if (floatx80_internal_precision == 80) { getRoundedFloatInternal( 80, &zSign, &zExp, &zSig80 ); zSig = zSig80; } else if (floatx80_internal_precision == 64) { getRoundedFloatInternal( 64, &zSign, &zExp, &zSig64 ); zSig80 = floatx80_internal_sig0; if (zSig64 != (zSig80 & LIT64( 0xFFFFFFFFFFFFF800 ))) { zSig80++; } zSig = zSig64; zSig |= zSig80 & LIT64( 0x00000000000007FF ); } else { getRoundedFloatInternal( 32, &zSign, &zExp, &zSig32 ); zSig80 = floatx80_internal_sig0; if (zSig32 != (zSig80 & LIT64( 0xFFFFFF0000000000 ))) { zSig80++; } zSig = zSig32; zSig |= zSig80 & LIT64( 0x000000FFFFFFFFFF ); } return packFloatx80( zSign, zExp & 0x7FFF, zSig ); } floatx80 getFloatInternalFloatx80( void ) { flag zSign; int32_t zExp; uint64_t zSig; getRoundedFloatInternal( 80, &zSign, &zExp, &zSig ); return packFloatx80( zSign, zExp & 0x7FFF, zSig ); } floatx80 getFloatInternalUnrounded( void ) { flag zSign = floatx80_internal_sign; int32_t zExp = floatx80_internal_exp; uint64_t zSig = floatx80_internal_sig0; return packFloatx80( zSign, zExp & 0x7FFF, zSig ); } uint64_t getFloatInternalGRS( void ) { #if 1 if (floatx80_internal_sig1) return 5; if (floatx80_internal_precision == 64 && floatx80_internal_sig0 & LIT64( 0x00000000000007FF )) { return 1; } if (floatx80_internal_precision == 32 && floatx80_internal_sig0 & LIT64( 0x000000FFFFFFFFFF )) { return 1; } return 0; #else uint64_t roundbits; shift64RightJamming(floatx80_internal_sig1, 61, &roundbits); return roundbits; #endif } /*---------------------------------------------------------------------------- | Functions and definitions to determine: (1) whether tininess for underflow | is detected before or after rounding by default, (2) what (if anything) | happens when exceptions are raised, (3) how signaling NaNs are distinguished | from quiet NaNs, (4) the default generated quiet NaNs, and (5) how NaNs | are propagated from function inputs to output. These details are target- | specific. *----------------------------------------------------------------------------*/ #include "softfloat-specialize.h" /*---------------------------------------------------------------------------- | Raises the exceptions specified by `flags'. Floating-point traps can be | defined here if desired. It is currently not possible for such a trap | to substitute a result value. If traps are not implemented, this routine | should be simply `float_exception_flags |= flags;'. *----------------------------------------------------------------------------*/ void float_raise(uint8_t flags, float_status *status) { status->float_exception_flags |= flags; } /*---------------------------------------------------------------------------- | Takes a 64-bit fixed-point value `absZ' with binary point between bits 6 | and 7, and returns the properly rounded 32-bit integer corresponding to the | input. If `zSign' is 1, the input is negated before being converted to an | integer. Bit 63 of `absZ' must be zero. Ordinarily, the fixed-point input | is simply rounded to an integer, with the inexact exception raised if the | input cannot be represented exactly as an integer. However, if the fixed- | point input is too large, the invalid exception is raised and the largest | positive or negative integer is returned. *----------------------------------------------------------------------------*/ static int32_t roundAndPackInt32(flag zSign, uint64_t absZ, float_status *status) { int8_t roundingMode; flag roundNearestEven; int8_t roundIncrement, roundBits; int32_t z; roundingMode = status->float_rounding_mode; roundNearestEven = ( roundingMode == float_round_nearest_even ); switch (roundingMode) { case float_round_nearest_even: case float_round_ties_away: roundIncrement = 0x40; break; case float_round_to_zero: roundIncrement = 0; break; case float_round_up: roundIncrement = zSign ? 0 : 0x7f; break; case float_round_down: roundIncrement = zSign ? 0x7f : 0; break; default: abort(); } roundBits = absZ & 0x7F; absZ = ( absZ + roundIncrement )>>7; absZ &= ~ ( ( ( roundBits ^ 0x40 ) == 0 ) & roundNearestEven ); z = absZ; if ( zSign ) z = - z; if ( ( absZ>>32 ) || ( z && ( ( z < 0 ) ^ zSign ) ) ) { float_raise(float_flag_invalid, status); return zSign ? (int32_t) 0x80000000 : 0x7FFFFFFF; } if (roundBits) { status->float_exception_flags |= float_flag_inexact; } return z; } #ifdef SOFTFLOAT_68K // 30-01-2017: Added for Previous static int16_t roundAndPackInt16( flag zSign, uint64_t absZ, float_status *status ) { int8_t roundingMode; flag roundNearestEven; int8_t roundIncrement, roundBits; int16_t z; roundingMode = status->float_rounding_mode; roundNearestEven = ( roundingMode == float_round_nearest_even ); roundIncrement = 0x40; if ( ! roundNearestEven ) { if ( roundingMode == float_round_to_zero ) { roundIncrement = 0; } else { roundIncrement = 0x7F; if ( zSign ) { if ( roundingMode == float_round_up ) roundIncrement = 0; } else { if ( roundingMode == float_round_down ) roundIncrement = 0; } } } roundBits = absZ & 0x7F; absZ = ( absZ + roundIncrement )>>7; absZ &= ~ ( ( ( roundBits ^ 0x40 ) == 0 ) & roundNearestEven ); z = absZ; if ( zSign ) z = - z; z = (int16_t) z; if ( ( absZ>>16 ) || ( z && ( ( z < 0 ) ^ zSign ) ) ) { float_raise( float_flag_invalid, status ); return zSign ? (int16_t) 0x8000 : 0x7FFF; } if ( roundBits ) status->float_exception_flags |= float_flag_inexact; return z; } static int8_t roundAndPackInt8( flag zSign, uint64_t absZ, float_status *status ) { int8_t roundingMode; flag roundNearestEven; int8_t roundIncrement, roundBits; int8_t z; roundingMode = status->float_rounding_mode; roundNearestEven = ( roundingMode == float_round_nearest_even ); roundIncrement = 0x40; if ( ! roundNearestEven ) { if ( roundingMode == float_round_to_zero ) { roundIncrement = 0; } else { roundIncrement = 0x7F; if ( zSign ) { if ( roundingMode == float_round_up ) roundIncrement = 0; } else { if ( roundingMode == float_round_down ) roundIncrement = 0; } } } roundBits = absZ & 0x7F; absZ = ( absZ + roundIncrement )>>7; absZ &= ~ ( ( ( roundBits ^ 0x40 ) == 0 ) & roundNearestEven ); z = absZ; if ( zSign ) z = - z; z = (int8_t) z; if ( ( absZ>>8 ) || ( z && ( ( z < 0 ) ^ zSign ) ) ) { float_raise( float_flag_invalid, status ); return zSign ? (int8_t) 0x80 : 0x7F; } if ( roundBits ) status->float_exception_flags |= float_flag_inexact; return z; } #endif // End of addition for Previous /*---------------------------------------------------------------------------- | Takes the 128-bit fixed-point value formed by concatenating `absZ0' and | `absZ1', with binary point between bits 63 and 64 (between the input words), | and returns the properly rounded 64-bit integer corresponding to the input. | If `zSign' is 1, the input is negated before being converted to an integer. | Ordinarily, the fixed-point input is simply rounded to an integer, with | the inexact exception raised if the input cannot be represented exactly as | an integer. However, if the fixed-point input is too large, the invalid | exception is raised and the largest positive or negative integer is | returned. *----------------------------------------------------------------------------*/ static int64_t roundAndPackInt64(flag zSign, uint64_t absZ0, uint64_t absZ1, float_status *status) { int8_t roundingMode; flag roundNearestEven, increment; int64_t z; roundingMode = status->float_rounding_mode; roundNearestEven = ( roundingMode == float_round_nearest_even ); switch (roundingMode) { case float_round_nearest_even: case float_round_ties_away: increment = ((int64_t) absZ1 < 0); break; case float_round_to_zero: increment = 0; break; case float_round_up: increment = !zSign && absZ1; break; case float_round_down: increment = zSign && absZ1; break; default: abort(); } if ( increment ) { ++absZ0; if ( absZ0 == 0 ) goto overflow; absZ0 &= ~ ( ( (uint64_t) ( absZ1<<1 ) == 0 ) & roundNearestEven ); } z = absZ0; if ( zSign ) z = - z; if ( z && ( ( z < 0 ) ^ zSign ) ) { overflow: float_raise(float_flag_invalid, status); return zSign ? (uint64_t) LIT64( 0x8000000000000000 ) : LIT64( 0x7FFFFFFFFFFFFFFF ); } if (absZ1) { status->float_exception_flags |= float_flag_inexact; } return z; } /*---------------------------------------------------------------------------- | Returns the fraction bits of the single-precision floating-point value `a'. *----------------------------------------------------------------------------*/ static inline uint32_t extractFloat32Frac( float32 a ) { return float32_val(a) & 0x007FFFFF; } /*---------------------------------------------------------------------------- | Returns the exponent bits of the single-precision floating-point value `a'. *----------------------------------------------------------------------------*/ static inline int extractFloat32Exp(float32 a) { return ( float32_val(a)>>23 ) & 0xFF; } /*---------------------------------------------------------------------------- | Returns the sign bit of the single-precision floating-point value `a'. *----------------------------------------------------------------------------*/ static inline flag extractFloat32Sign( float32 a ) { return float32_val(a)>>31; } /*---------------------------------------------------------------------------- | Normalizes the subnormal single-precision floating-point value represented | by the denormalized significand `aSig'. The normalized exponent and | significand are stored at the locations pointed to by `zExpPtr' and | `zSigPtr', respectively. *----------------------------------------------------------------------------*/ static void normalizeFloat32Subnormal(uint32_t aSig, int *zExpPtr, uint32_t *zSigPtr) { int8_t shiftCount; shiftCount = countLeadingZeros32( aSig ) - 8; *zSigPtr = aSig<<shiftCount; *zExpPtr = 1 - shiftCount; } /*---------------------------------------------------------------------------- | Packs the sign `zSign', exponent `zExp', and significand `zSig' into a | single-precision floating-point value, returning the result. After being | shifted into the proper positions, the three fields are simply added | together to form the result. This means that any integer portion of `zSig' | will be added into the exponent. Since a properly normalized significand | will have an integer portion equal to 1, the `zExp' input should be 1 less | than the desired result exponent whenever `zSig' is a complete, normalized | significand. *----------------------------------------------------------------------------*/ static inline float32 packFloat32(flag zSign, int zExp, uint32_t zSig) { return make_float32( ( ( (uint32_t) zSign )<<31 ) + ( ( (uint32_t) zExp )<<23 ) + zSig); } /*---------------------------------------------------------------------------- | Takes an abstract floating-point value having sign `zSign', exponent `zExp', | and significand `zSig', and returns the proper single-precision floating- | point value corresponding to the abstract input. Ordinarily, the abstract | value is simply rounded and packed into the single-precision format, with | the inexact exception raised if the abstract input cannot be represented | exactly. However, if the abstract value is too large, the overflow and | inexact exceptions are raised and an infinity or maximal finite value is | returned. If the abstract value is too small, the input value is rounded to | a subnormal number, and the underflow and inexact exceptions are raised if | the abstract input cannot be represented exactly as a subnormal single- | precision floating-point number. | The input significand `zSig' has its binary point between bits 30 | and 29, which is 7 bits to the left of the usual location. This shifted | significand must be normalized or smaller. If `zSig' is not normalized, | `zExp' must be 0; in that case, the result returned is a subnormal number, | and it must not require rounding. In the usual case that `zSig' is | normalized, `zExp' must be 1 less than the ``true'' floating-point exponent. | The handling of underflow and overflow follows the IEC/IEEE Standard for | Binary Floating-Point Arithmetic. *----------------------------------------------------------------------------*/ static float32 roundAndPackFloat32(flag zSign, int zExp, uint32_t zSig, float_status *status) { int8_t roundingMode; flag roundNearestEven; int8_t roundIncrement, roundBits; flag isTiny; roundingMode = status->float_rounding_mode; roundNearestEven = ( roundingMode == float_round_nearest_even ); switch (roundingMode) { case float_round_nearest_even: case float_round_ties_away: roundIncrement = 0x40; break; case float_round_to_zero: roundIncrement = 0; break; case float_round_up: roundIncrement = zSign ? 0 : 0x7f; break; case float_round_down: roundIncrement = zSign ? 0x7f : 0; break; default: abort(); break; } roundBits = zSig & 0x7F; if ( 0xFD <= (uint16_t) zExp ) { if ( ( 0xFD < zExp ) || ( ( zExp == 0xFD ) && ( (int32_t) ( zSig + roundIncrement ) < 0 ) ) ) { #ifdef SOFTFLOAT_68K float_raise( float_flag_overflow, status ); saveFloat32Internal( zSign, zExp, zSig, status ); if ( roundBits ) float_raise( float_flag_inexact, status ); #else float_raise(float_flag_overflow | float_flag_inexact, status); #endif return packFloat32( zSign, 0xFF, - ( roundIncrement == 0 )); } if ( zExp < 0 ) { if (status->flush_to_zero) { //float_raise(float_flag_output_denormal, status); return packFloat32(zSign, 0, 0); } isTiny = (status->float_detect_tininess == float_tininess_before_rounding) || ( zExp < -1 ) || ( zSig + roundIncrement < 0x80000000 ); #ifdef SOFTFLOAT_68K if ( isTiny ) { float_raise( float_flag_underflow, status ); saveFloat32Internal( zSign, zExp, zSig, status ); } #endif shift32RightJamming( zSig, - zExp, &zSig ); zExp = 0; roundBits = zSig & 0x7F; #ifndef SOFTFLOAT_68K if (isTiny && roundBits) float_raise(float_flag_underflow, status); #endif } } if (roundBits) { status->float_exception_flags |= float_flag_inexact; } zSig = ( zSig + roundIncrement )>>7; zSig &= ~ ( ( ( roundBits ^ 0x40 ) == 0 ) & roundNearestEven ); if ( zSig == 0 ) zExp = 0; return packFloat32( zSign, zExp, zSig ); } /*---------------------------------------------------------------------------- | Returns the fraction bits of the double-precision floating-point value `a'. *----------------------------------------------------------------------------*/ static inline uint64_t extractFloat64Frac( float64 a ) { return float64_val(a) & LIT64( 0x000FFFFFFFFFFFFF ); } /*---------------------------------------------------------------------------- | Returns the exponent bits of the double-precision floating-point value `a'. *----------------------------------------------------------------------------*/ static inline int extractFloat64Exp(float64 a) { return ( float64_val(a)>>52 ) & 0x7FF; } /*---------------------------------------------------------------------------- | Returns the sign bit of the double-precision floating-point value `a'. *----------------------------------------------------------------------------*/ static inline flag extractFloat64Sign( float64 a ) { return float64_val(a)>>63; } /*---------------------------------------------------------------------------- | If `a' is denormal and we are in flush-to-zero mode then set the | input-denormal exception and return zero. Otherwise just return the value. *----------------------------------------------------------------------------*/ float64 float64_squash_input_denormal(float64 a, float_status *status) { if (status->flush_inputs_to_zero) { if (extractFloat64Exp(a) == 0 && extractFloat64Frac(a) != 0) { //float_raise(float_flag_input_denormal, status); return make_float64(float64_val(a) & (1ULL << 63)); } } return a; } /*---------------------------------------------------------------------------- | Normalizes the subnormal double-precision floating-point value represented | by the denormalized significand `aSig'. The normalized exponent and | significand are stored at the locations pointed to by `zExpPtr' and | `zSigPtr', respectively. *----------------------------------------------------------------------------*/ static void normalizeFloat64Subnormal(uint64_t aSig, int *zExpPtr, uint64_t *zSigPtr) { int8_t shiftCount; shiftCount = countLeadingZeros64( aSig ) - 11; *zSigPtr = aSig<<shiftCount; *zExpPtr = 1 - shiftCount; } /*---------------------------------------------------------------------------- | Packs the sign `zSign', exponent `zExp', and significand `zSig' into a | double-precision floating-point value, returning the result. After being | shifted into the proper positions, the three fields are simply added | together to form the result. This means that any integer portion of `zSig' | will be added into the exponent. Since a properly normalized significand | will have an integer portion equal to 1, the `zExp' input should be 1 less | than the desired result exponent whenever `zSig' is a complete, normalized | significand. *----------------------------------------------------------------------------*/ static inline float64 packFloat64(flag zSign, int zExp, uint64_t zSig) { return make_float64( ( ( (uint64_t) zSign )<<63 ) + ( ( (uint64_t) zExp )<<52 ) + zSig); } /*---------------------------------------------------------------------------- | Takes an abstract floating-point value having sign `zSign', exponent `zExp', | and significand `zSig', and returns the proper double-precision floating- | point value corresponding to the abstract input. Ordinarily, the abstract | value is simply rounded and packed into the double-precision format, with | the inexact exception raised if the abstract input cannot be represented | exactly. However, if the abstract value is too large, the overflow and | inexact exceptions are raised and an infinity or maximal finite value is | returned. If the abstract value is too small, the input value is rounded to | a subnormal number, and the underflow and inexact exceptions are raised if | the abstract input cannot be represented exactly as a subnormal double- | precision floating-point number. | The input significand `zSig' has its binary point between bits 62 | and 61, which is 10 bits to the left of the usual location. This shifted | significand must be normalized or smaller. If `zSig' is not normalized, | `zExp' must be 0; in that case, the result returned is a subnormal number, | and it must not require rounding. In the usual case that `zSig' is | normalized, `zExp' must be 1 less than the ``true'' floating-point exponent. | The handling of underflow and overflow follows the IEC/IEEE Standard for | Binary Floating-Point Arithmetic. *----------------------------------------------------------------------------*/ static float64 roundAndPackFloat64(flag zSign, int zExp, uint64_t zSig, float_status *status) { int8_t roundingMode; flag roundNearestEven; int roundIncrement, roundBits; flag isTiny; roundingMode = status->float_rounding_mode; roundNearestEven = ( roundingMode == float_round_nearest_even ); switch (roundingMode) { case float_round_nearest_even: case float_round_ties_away: roundIncrement = 0x200; break; case float_round_to_zero: roundIncrement = 0; break; case float_round_up: roundIncrement = zSign ? 0 : 0x3ff; break; case float_round_down: roundIncrement = zSign ? 0x3ff : 0; break; default: abort(); } roundBits = zSig & 0x3FF; if ( 0x7FD <= (uint16_t) zExp ) { if ( ( 0x7FD < zExp ) || ( ( zExp == 0x7FD ) && ( (int64_t) ( zSig + roundIncrement ) < 0 ) ) ) { #ifdef SOFTFLOAT_68K float_raise( float_flag_overflow, status ); saveFloat64Internal( zSign, zExp, zSig, status ); if ( roundBits ) float_raise( float_flag_inexact, status ); #else float_raise(float_flag_overflow | float_flag_inexact, status); #endif return packFloat64( zSign, 0x7FF, - ( roundIncrement == 0 )); } if ( zExp < 0 ) { if (status->flush_to_zero) { //float_raise(float_flag_output_denormal, status); return packFloat64(zSign, 0, 0); } isTiny = (status->float_detect_tininess == float_tininess_before_rounding) || ( zExp < -1 ) || ( zSig + roundIncrement < LIT64( 0x8000000000000000 ) ); #ifdef SOFTFLOAT_68K if ( isTiny ) { float_raise( float_flag_underflow, status ); saveFloat64Internal( zSign, zExp, zSig, status ); } #endif shift64RightJamming( zSig, - zExp, &zSig ); zExp = 0; roundBits = zSig & 0x3FF; #ifndef SOFTFLOAT_68K if (isTiny && roundBits) float_raise(float_flag_underflow, status); #endif } } if (roundBits) { status->float_exception_flags |= float_flag_inexact; } zSig = ( zSig + roundIncrement )>>10; zSig &= ~ ( ( ( roundBits ^ 0x200 ) == 0 ) & roundNearestEven ); if ( zSig == 0 ) zExp = 0; return packFloat64( zSign, zExp, zSig ); } /*---------------------------------------------------------------------------- | Returns the fraction bits of the extended double-precision floating-point | value `a'. *----------------------------------------------------------------------------*/ uint64_t extractFloatx80Frac( floatx80 a ) { return a.low; } /*---------------------------------------------------------------------------- | Returns the exponent bits of the extended double-precision floating-point | value `a'. *----------------------------------------------------------------------------*/ int32_t extractFloatx80Exp( floatx80 a ) { return a.high & 0x7FFF; } /*---------------------------------------------------------------------------- | Returns the sign bit of the extended double-precision floating-point value | `a'. *----------------------------------------------------------------------------*/ flag extractFloatx80Sign( floatx80 a ) { return a.high>>15; } /*---------------------------------------------------------------------------- | Normalizes the subnormal extended double-precision floating-point value | represented by the denormalized significand `aSig'. The normalized exponent | and significand are stored at the locations pointed to by `zExpPtr' and | `zSigPtr', respectively. *----------------------------------------------------------------------------*/ void normalizeFloatx80Subnormal( uint64_t aSig, int32_t *zExpPtr, uint64_t *zSigPtr ) { int8_t shiftCount; shiftCount = countLeadingZeros64( aSig ); *zSigPtr = aSig<<shiftCount; #ifdef SOFTFLOAT_68K *zExpPtr = -shiftCount; #else *zExpPtr = 1 - shiftCount; #endif } /*---------------------------------------------------------------------------- | Packs the sign `zSign', exponent `zExp', and significand `zSig' into an | extended double-precision floating-point value, returning the result. *----------------------------------------------------------------------------*/ floatx80 packFloatx80( flag zSign, int32_t zExp, uint64_t zSig ) { floatx80 z; z.low = zSig; z.high = ( ( (uint16_t) zSign )<<15 ) + zExp; return z; } /*---------------------------------------------------------------------------- | Takes an abstract floating-point value having sign `zSign', exponent `zExp', | and extended significand formed by the concatenation of `zSig0' and `zSig1', | and returns the proper extended double-precision floating-point value | corresponding to the abstract input. Ordinarily, the abstract value is | rounded and packed into the extended double-precision format, with the | inexact exception raised if the abstract input cannot be represented | exactly. However, if the abstract value is too large, the overflow and | inexact exceptions are raised and an infinity or maximal finite value is | returned. If the abstract value is too small, the input value is rounded to | a subnormal number, and the underflow and inexact exceptions are raised if | the abstract input cannot be represented exactly as a subnormal extended | double-precision floating-point number. | If `roundingPrecision' is 32 or 64, the result is rounded to the same | number of bits as single or double precision, respectively. Otherwise, the | result is rounded to the full precision of the extended double-precision | format. | The input significand must be normalized or smaller. If the input | significand is not normalized, `zExp' must be 0; in that case, the result | returned is a subnormal number, and it must not require rounding. The | handling of underflow and overflow follows the IEC/IEEE Standard for Binary | Floating-Point Arithmetic. *----------------------------------------------------------------------------*/ #ifndef SOFTFLOAT_68K floatx80 roundAndPackFloatx80(int8_t roundingPrecision, flag zSign, int32_t zExp, uint64_t zSig0, uint64_t zSig1, float_status *status) { int8_t roundingMode; flag roundNearestEven, increment, isTiny; int64_t roundIncrement, roundMask, roundBits; roundingMode = status->float_rounding_mode; roundNearestEven = ( roundingMode == float_round_nearest_even ); if ( roundingPrecision == 80 ) goto precision80; if ( roundingPrecision == 64 ) { roundIncrement = LIT64( 0x0000000000000400 ); roundMask = LIT64( 0x00000000000007FF ); } else if ( roundingPrecision == 32 ) { roundIncrement = LIT64( 0x0000008000000000 ); roundMask = LIT64( 0x000000FFFFFFFFFF ); } else { goto precision80; } zSig0 |= ( zSig1 != 0 ); switch (roundingMode) { case float_round_nearest_even: case float_round_ties_away: break; case float_round_to_zero: roundIncrement = 0; break; case float_round_up: roundIncrement = zSign ? 0 : roundMask; break; case float_round_down: roundIncrement = zSign ? roundMask : 0; break; default: abort(); } roundBits = zSig0 & roundMask; #ifdef SOFTFLOAT_68K if ( 0x7FFE <= (uint32_t) zExp ) { #else if ( 0x7FFD <= (uint32_t) ( zExp - 1 ) ) { #endif if ( ( 0x7FFE < zExp ) || ( ( zExp == 0x7FFE ) && ( zSig0 + roundIncrement < zSig0 ) ) ) { goto overflow; } #ifdef SOFTFLOAT_68K if ( zExp < 0 ) { #else if ( zExp <= 0 ) { #endif if (status->flush_to_zero) { //float_raise(float_flag_output_denormal, status); return packFloatx80(zSign, 0, 0); } isTiny = (status->float_detect_tininess == float_tininess_before_rounding) #ifdef SOFTFLOAT_68K || ( zExp < -1 ) #else || ( zExp < 0 ) #endif || ( zSig0 <= zSig0 + roundIncrement ); #ifdef SOFTFLOAT_68K if ( isTiny ) { float_raise( float_flag_underflow, status ); saveFloatx80Internal( zSign, zExp, zSig0, zSig1, status ); } shift64RightJamming( zSig0, -zExp, &zSig0 ); #else shift64RightJamming( zSig0, 1 - zExp, &zSig0 ); #endif zExp = 0; roundBits = zSig0 & roundMask; #ifdef SOFTFLOAT_68K if ( isTiny ) float_raise( float_flag_underflow, status ); #else if (isTiny && roundBits) { float_raise(float_flag_underflow, status); } #endif if (roundBits) { status->float_exception_flags |= float_flag_inexact; } zSig0 += roundIncrement; #ifndef SOFTFLOAT_68K if ( (int64_t) zSig0 < 0 ) zExp = 1; #endif roundIncrement = roundMask + 1; if ( roundNearestEven && ( roundBits<<1 == roundIncrement ) ) { roundMask |= roundIncrement; } zSig0 &= ~ roundMask; return packFloatx80( zSign, zExp, zSig0 ); } } if (roundBits) { status->float_exception_flags |= float_flag_inexact; } zSig0 += roundIncrement; if ( zSig0 < roundIncrement ) { ++zExp; zSig0 = LIT64( 0x8000000000000000 ); } roundIncrement = roundMask + 1; if ( roundNearestEven && ( roundBits<<1 == roundIncrement ) ) { roundMask |= roundIncrement; } zSig0 &= ~ roundMask; if ( zSig0 == 0 ) zExp = 0; return packFloatx80( zSign, zExp, zSig0 ); precision80: switch (roundingMode) { case float_round_nearest_even: case float_round_ties_away: increment = ((int64_t)zSig1 < 0); break; case float_round_to_zero: increment = 0; break; case float_round_up: increment = !zSign && zSig1; break; case float_round_down: increment = zSign && zSig1; break; default: abort(); } #ifdef SOFTFLOAT_68K if ( 0x7FFE <= (uint32_t) zExp ) { #else if ( 0x7FFD <= (uint32_t) ( zExp - 1 ) ) { #endif if ( ( 0x7FFE < zExp ) || ( ( zExp == 0x7FFE ) && ( zSig0 == LIT64( 0xFFFFFFFFFFFFFFFF ) ) && increment ) ) { roundMask = 0; overflow: #ifndef SOFTFLOAT_68K float_raise(float_flag_overflow | float_flag_inexact, status); #else float_raise( float_flag_overflow, status ); saveFloatx80Internal( zSign, zExp, zSig0, zSig1, status ); if ( ( zSig0 & roundMask ) || zSig1 ) float_raise( float_flag_inexact, status ); #endif if ( ( roundingMode == float_round_to_zero ) || ( zSign && ( roundingMode == float_round_up ) ) || ( ! zSign && ( roundingMode == float_round_down ) ) ) { return packFloatx80( zSign, 0x7FFE, ~ roundMask ); } return packFloatx80( zSign, 0x7FFF, floatx80_default_infinity_low ); } #ifdef SOFTFLOAT_68K if ( zExp < 0 ) { #else if ( zExp <= 0 ) { #endif isTiny = (status->float_detect_tininess == float_tininess_before_rounding) #ifdef SOFTFLOAT_68K || ( zExp < -1 ) #else || ( zExp < 0 ) #endif || ! increment || ( zSig0 < LIT64( 0xFFFFFFFFFFFFFFFF ) ); #ifdef SOFTFLOAT_68K if ( isTiny ) { float_raise( float_flag_underflow, status ); saveFloatx80Internal( zSign, zExp, zSig0, zSig1, status ); } shift64ExtraRightJamming( zSig0, zSig1, -zExp, &zSig0, &zSig1 ); #else shift64ExtraRightJamming( zSig0, zSig1, 1 - zExp, &zSig0, &zSig1 ); #endif zExp = 0; #ifndef SOFTFLOAT_68K if ( isTiny && zSig1 ) float_raise( float_flag_underflow, status ); #endif if (zSig1) float_raise(float_flag_inexact, status); switch (roundingMode) { case float_round_nearest_even: case float_round_ties_away: increment = ((int64_t)zSig1 < 0); break; case float_round_to_zero: increment = 0; break; case float_round_up: increment = !zSign && zSig1; break; case float_round_down: increment = zSign && zSig1; break; default: abort(); } if ( increment ) { ++zSig0; zSig0 &= ~ ( ( (uint64_t) ( zSig1<<1 ) == 0 ) & roundNearestEven ); #ifndef SOFTFLOAT_68K if ( (int64_t) zSig0 < 0 ) zExp = 1; #endif } return packFloatx80( zSign, zExp, zSig0 ); } } if (zSig1) { status->float_exception_flags |= float_flag_inexact; } if ( increment ) { ++zSig0; if ( zSig0 == 0 ) { ++zExp; zSig0 = LIT64( 0x8000000000000000 ); } else { zSig0 &= ~ ( ( (uint64_t) ( zSig1<<1 ) == 0 ) & roundNearestEven ); } } else { if ( zSig0 == 0 ) zExp = 0; } return packFloatx80( zSign, zExp, zSig0 ); } #else // SOFTFLOAT_68K floatx80 roundAndPackFloatx80( int8_t roundingPrecision, flag zSign, int32_t zExp, uint64_t zSig0, uint64_t zSig1, float_status *status ) { int8_t roundingMode; flag roundNearestEven, increment; uint64_t roundIncrement, roundMask, roundBits; int32_t expOffset; roundingMode = status->float_rounding_mode; roundNearestEven = ( roundingMode == float_round_nearest_even ); if ( roundingPrecision == 80 ) goto precision80; if ( roundingPrecision == 64 ) { roundIncrement = LIT64( 0x0000000000000400 ); roundMask = LIT64( 0x00000000000007FF ); expOffset = 0x3C00; } else if ( roundingPrecision == 32 ) { roundIncrement = LIT64( 0x0000008000000000 ); roundMask = LIT64( 0x000000FFFFFFFFFF ); expOffset = 0x3F80; } else { goto precision80; } zSig0 |= ( zSig1 != 0 ); if ( ! roundNearestEven ) { if ( roundingMode == float_round_to_zero ) { roundIncrement = 0; } else { roundIncrement = roundMask; if ( zSign ) { if ( roundingMode == float_round_up ) roundIncrement = 0; } else { if ( roundingMode == float_round_down ) roundIncrement = 0; } } } roundBits = zSig0 & roundMask; if ( ( ( 0x7FFE - expOffset ) < zExp ) || ( ( zExp == ( 0x7FFE - expOffset ) ) && ( zSig0 + roundIncrement < zSig0 ) ) ) { float_raise( float_flag_overflow, status ); saveFloatx80Internal( roundingPrecision, zSign, zExp, zSig0, zSig1, status ); if ( zSig0 & roundMask ) float_raise( float_flag_inexact, status ); if ( ( roundingMode == float_round_to_zero ) || ( zSign && ( roundingMode == float_round_up ) ) || ( ! zSign && ( roundingMode == float_round_down ) ) ) { return packFloatx80( zSign, 0x7FFE - expOffset, ~ roundMask ); } return packFloatx80( zSign, 0x7FFF, floatx80_default_infinity_low ); } if ( zExp < ( expOffset + 1 ) ) { float_raise( float_flag_underflow, status ); saveFloatx80Internal( roundingPrecision, zSign, zExp, zSig0, zSig1, status ); shift64RightJamming( zSig0, -( zExp - ( expOffset + 1 ) ), &zSig0 ); zExp = expOffset + 1; roundBits = zSig0 & roundMask; if ( roundBits ) float_raise( float_flag_inexact, status ); zSig0 += roundIncrement; roundIncrement = roundMask + 1; if ( roundNearestEven && ( roundBits<<1 == roundIncrement ) ) { roundMask |= roundIncrement; } zSig0 &= ~ roundMask; return packFloatx80( zSign, zExp, zSig0 ); } if ( roundBits ) { float_raise( float_flag_inexact, status ); saveFloatx80Internal( roundingPrecision, zSign, zExp, zSig0, zSig1, status); } zSig0 += roundIncrement; if ( zSig0 < roundIncrement ) { ++zExp; zSig0 = LIT64( 0x8000000000000000 ); } roundIncrement = roundMask + 1; if ( roundNearestEven && ( roundBits<<1 == roundIncrement ) ) { roundMask |= roundIncrement; } zSig0 &= ~ roundMask; if ( zSig0 == 0 ) zExp = 0; return packFloatx80( zSign, zExp, zSig0 ); precision80: increment = ( (int64_t) zSig1 < 0 ); if ( ! roundNearestEven ) { if ( roundingMode == float_round_to_zero ) { increment = 0; } else { if ( zSign ) { increment = ( roundingMode == float_round_down ) && zSig1; } else { increment = ( roundingMode == float_round_up ) && zSig1; } } } if ( 0x7FFE <= (uint32_t) zExp ) { if ( ( 0x7FFE < zExp ) || ( ( zExp == 0x7FFE ) && ( zSig0 == LIT64( 0xFFFFFFFFFFFFFFFF ) ) && increment ) ) { roundMask = 0; float_raise( float_flag_overflow, status ); saveFloatx80Internal( roundingPrecision, zSign, zExp, zSig0, zSig1, status ); if ( ( zSig0 & roundMask ) || zSig1 ) float_raise( float_flag_inexact, status ); if ( ( roundingMode == float_round_to_zero ) || ( zSign && ( roundingMode == float_round_up ) ) || ( ! zSign && ( roundingMode == float_round_down ) ) ) { return packFloatx80( zSign, 0x7FFE, ~ roundMask ); } return packFloatx80( zSign, 0x7FFF, floatx80_default_infinity_low ); } if ( zExp < 0 ) { float_raise( float_flag_underflow, status ); saveFloatx80Internal( roundingPrecision, zSign, zExp, zSig0, zSig1, status); shift64ExtraRightJamming( zSig0, zSig1, -zExp, &zSig0, &zSig1 ); zExp = 0; if ( zSig1 ) float_raise( float_flag_inexact, status ); if ( roundNearestEven ) { increment = ( (int64_t) zSig1 < 0 ); } else { if ( zSign ) { increment = ( roundingMode == float_round_down ) && zSig1; } else { increment = ( roundingMode == float_round_up ) && zSig1; } } if ( increment ) { ++zSig0; zSig0 &= ~ ( ( (uint64_t) ( zSig1<<1 ) == 0 ) & roundNearestEven ); } return packFloatx80( zSign, zExp, zSig0 ); } } if ( zSig1 ) { float_raise( float_flag_inexact, status ); saveFloatx80Internal( roundingPrecision, zSign, zExp, zSig0, zSig1, status ); } if ( increment ) { ++zSig0; if ( zSig0 == 0 ) { ++zExp; zSig0 = LIT64( 0x8000000000000000 ); } else { zSig0 &= ~ ( ( (uint64_t) ( zSig1<<1 ) == 0 ) & roundNearestEven ); } } else { if ( zSig0 == 0 ) zExp = 0; } return packFloatx80( zSign, zExp, zSig0 ); } #endif #ifdef SOFTFLOAT_68K // 21-01-2017: Added for Previous floatx80 roundSigAndPackFloatx80( int8_t roundingPrecision, flag zSign, int32_t zExp, uint64_t zSig0, uint64_t zSig1, float_status *status ) { int8_t roundingMode; flag roundNearestEven, isTiny; uint64_t roundIncrement, roundMask, roundBits; roundingMode = status->float_rounding_mode; roundNearestEven = ( roundingMode == float_round_nearest_even ); if ( roundingPrecision == 32 ) { roundIncrement = LIT64( 0x0000008000000000 ); roundMask = LIT64( 0x000000FFFFFFFFFF ); } else if ( roundingPrecision == 64 ) { roundIncrement = LIT64( 0x0000000000000400 ); roundMask = LIT64( 0x00000000000007FF ); } else { return roundAndPackFloatx80( 80, zSign, zExp, zSig0, zSig1, status ); } zSig0 |= ( zSig1 != 0 ); if ( ! roundNearestEven ) { if ( roundingMode == float_round_to_zero ) { roundIncrement = 0; } else { roundIncrement = roundMask; if ( zSign ) { if ( roundingMode == float_round_up ) roundIncrement = 0; } else { if ( roundingMode == float_round_down ) roundIncrement = 0; } } } roundBits = zSig0 & roundMask; if ( 0x7FFE <= (uint32_t) zExp ) { if ( ( 0x7FFE < zExp ) || ( ( zExp == 0x7FFE ) && ( zSig0 + roundIncrement < zSig0 ) ) ) { float_raise( float_flag_overflow, status ); saveFloatx80Internal( roundingPrecision, zSign, zExp, zSig0, zSig1, status); if ( zSig0 & roundMask ) float_raise( float_flag_inexact, status ); if ( ( roundingMode == float_round_to_zero ) || ( zSign && ( roundingMode == float_round_up ) ) || ( ! zSign && ( roundingMode == float_round_down ) ) ) { return packFloatx80( zSign, 0x7FFE, LIT64( 0xFFFFFFFFFFFFFFFF ) ); } return packFloatx80( zSign, 0x7FFF, floatx80_default_infinity_low ); } if ( zExp < 0 ) { isTiny = ( status->float_detect_tininess == float_tininess_before_rounding ) || ( zExp < -1 ) || ( zSig0 <= zSig0 + roundIncrement ); if ( isTiny ) { float_raise( float_flag_underflow, status ); saveFloatx80Internal( roundingPrecision, zSign, zExp, zSig0, zSig1, status ); } shift64RightJamming( zSig0, -zExp, &zSig0 ); zExp = 0; roundBits = zSig0 & roundMask; if ( roundBits ) float_raise ( float_flag_inexact, status ); zSig0 += roundIncrement; if ( roundNearestEven && ( roundBits == roundIncrement ) ) { roundMask |= roundIncrement<<1; } zSig0 &= ~roundMask; return packFloatx80( zSign, zExp, zSig0 ); } } if ( roundBits ) { float_raise( float_flag_inexact, status ); saveFloatx80Internal( roundingPrecision, zSign, zExp, zSig0, zSig1, status ); } zSig0 += roundIncrement; if ( zSig0 < roundIncrement ) { ++zExp; zSig0 = LIT64( 0x8000000000000000 ); } roundIncrement = roundMask + 1; if ( roundNearestEven && ( roundBits<<1 == roundIncrement ) ) { roundMask |= roundIncrement; } zSig0 &= ~ roundMask; if ( zSig0 == 0 ) zExp = 0; return packFloatx80( zSign, zExp, zSig0 ); } #endif // End of Addition for Previous /*---------------------------------------------------------------------------- | Takes an abstract floating-point value having sign `zSign', exponent | `zExp', and significand formed by the concatenation of `zSig0' and `zSig1', | and returns the proper extended double-precision floating-point value | corresponding to the abstract input. This routine is just like | `roundAndPackFloatx80' except that the input significand does not have to be | normalized. *----------------------------------------------------------------------------*/ static floatx80 normalizeRoundAndPackFloatx80(int8_t roundingPrecision, flag zSign, int32_t zExp, uint64_t zSig0, uint64_t zSig1, float_status *status) { int8_t shiftCount; if ( zSig0 == 0 ) { zSig0 = zSig1; zSig1 = 0; zExp -= 64; } shiftCount = countLeadingZeros64( zSig0 ); shortShift128Left( zSig0, zSig1, shiftCount, &zSig0, &zSig1 ); zExp -= shiftCount; return roundAndPackFloatx80(roundingPrecision, zSign, zExp, zSig0, zSig1, status); } /*---------------------------------------------------------------------------- | Returns the result of converting the 32-bit two's complement integer `a' | to the extended double-precision floating-point format. The conversion | is performed according to the IEC/IEEE Standard for Binary Floating-Point | Arithmetic. *----------------------------------------------------------------------------*/ floatx80 int32_to_floatx80(int32_t a) { flag zSign; uint32_t absA; int8_t shiftCount; uint64_t zSig; if ( a == 0 ) return packFloatx80( 0, 0, 0 ); zSign = ( a < 0 ); absA = zSign ? - a : a; shiftCount = countLeadingZeros32( absA ) + 32; zSig = absA; return packFloatx80( zSign, 0x403E - shiftCount, zSig<<shiftCount ); } /*---------------------------------------------------------------------------- | Returns the result of converting the single-precision floating-point value | `a' to the extended double-precision floating-point format. The conversion | is performed according to the IEC/IEEE Standard for Binary Floating-Point | Arithmetic. *----------------------------------------------------------------------------*/ floatx80 float32_to_floatx80(float32 a, float_status *status) { flag aSign; int aExp; uint32_t aSig; aSig = extractFloat32Frac( a ); aExp = extractFloat32Exp( a ); aSign = extractFloat32Sign( a ); if ( aExp == 0xFF ) { if ( aSig ) return commonNaNToFloatx80( float32ToCommonNaN( a, status ), status ); return packFloatx80( aSign, 0x7FFF, floatx80_default_infinity_low ); } if ( aExp == 0 ) { if ( aSig == 0 ) return packFloatx80( aSign, 0, 0 ); normalizeFloat32Subnormal( aSig, &aExp, &aSig ); } aSig |= 0x00800000; return packFloatx80( aSign, aExp + 0x3F80, ( (uint64_t) aSig )<<40 ); } #ifdef SOFTFLOAT_68K // 31-12-2016: Added for Previous floatx80 float32_to_floatx80_allowunnormal(float32 a , float_status *status) { (void)status; flag aSign; int16_t aExp; uint32_t aSig; aSig = extractFloat32Frac(a); aExp = extractFloat32Exp(a); aSign = extractFloat32Sign(a); if (aExp == 0xFF) { return packFloatx80( aSign, 0x7FFF, ( (uint64_t) aSig )<<40 ); } if (aExp == 0) { if (aSig == 0) return packFloatx80(aSign, 0, 0); return packFloatx80(aSign, 0x3F81, ((uint64_t) aSig) << 40); } aSig |= 0x00800000; return packFloatx80(aSign, aExp + 0x3F80, ((uint64_t)aSig) << 40); } #endif // end of addition for Previous /*---------------------------------------------------------------------------- | Returns the result of converting the double-precision floating-point value | `a' to the extended double-precision floating-point format. The conversion | is performed according to the IEC/IEEE Standard for Binary Floating-Point | Arithmetic. *----------------------------------------------------------------------------*/ floatx80 float64_to_floatx80(float64 a, float_status *status) { flag aSign; int aExp; uint64_t aSig; aSig = extractFloat64Frac( a ); aExp = extractFloat64Exp( a ); aSign = extractFloat64Sign( a ); if ( aExp == 0x7FF ) { if ( aSig ) return commonNaNToFloatx80( float64ToCommonNaN( a, status ), status ); return packFloatx80( aSign, 0x7FFF, floatx80_default_infinity_low ); } if ( aExp == 0 ) { if ( aSig == 0 ) return packFloatx80( aSign, 0, 0 ); normalizeFloat64Subnormal( aSig, &aExp, &aSig ); } return packFloatx80( aSign, aExp + 0x3C00, ( aSig | LIT64( 0x0010000000000000 ) )<<11 ); } #ifdef SOFTFLOAT_68K // 31-12-2016: Added for Previous floatx80 float64_to_floatx80_allowunnormal( float64 a, float_status *status ) { (void)status; flag aSign; int16_t aExp; uint64_t aSig; aSig = extractFloat64Frac( a ); aExp = extractFloat64Exp( a ); aSign = extractFloat64Sign( a ); if ( aExp == 0x7FF ) { return packFloatx80( aSign, 0x7FFF, aSig<<11 ); } if ( aExp == 0 ) { if ( aSig == 0 ) return packFloatx80( aSign, 0, 0 ); return packFloatx80( aSign, 0x3C01, aSig<<11 ); } return packFloatx80( aSign, aExp + 0x3C00, ( aSig | LIT64( 0x0010000000000000 ) )<<11 ); } #endif // end of addition for Previous /*---------------------------------------------------------------------------- | Returns the result of converting the extended double-precision floating- | point value `a' to the 32-bit two's complement integer format. The | conversion is performed according to the IEC/IEEE Standard for Binary | Floating-Point Arithmetic---which means in particular that the conversion | is rounded according to the current rounding mode. If `a' is a NaN, the | largest positive integer is returned. Otherwise, if the conversion | overflows, the largest integer with the same sign as `a' is returned. *----------------------------------------------------------------------------*/ int32_t floatx80_to_int32(floatx80 a, float_status *status) { flag aSign; int32_t aExp, shiftCount; uint64_t aSig; aSig = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); aSign = extractFloatx80Sign( a ); #ifdef SOFTFLOAT_68K if ( aExp == 0x7FFF ) { if ( (uint64_t) ( aSig<<1 ) ) { a = propagateFloatx80NaNOneArg( a, status ); if ( a.low == aSig ) float_raise( float_flag_invalid, status ); return (int32_t)(a.low>>32); } float_raise( float_flag_invalid, status ); return aSign ? (int32_t) 0x80000000 : 0x7FFFFFFF; } #else if ( ( aExp == 0x7FFF ) && (bits64) ( aSig<<1 ) ) aSign = 0; #endif shiftCount = 0x4037 - aExp; if ( shiftCount <= 0 ) shiftCount = 1; shift64RightJamming( aSig, shiftCount, &aSig ); return roundAndPackInt32(aSign, aSig, status); } #ifdef SOFTFLOAT_68K // 30-01-2017: Addition for Previous int16_t floatx80_to_int16( floatx80 a, float_status *status) { flag aSign; int32_t aExp, shiftCount; uint64_t aSig; aSig = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); aSign = extractFloatx80Sign( a ); if ( aExp == 0x7FFF ) { float_raise( float_flag_invalid, status ); if ( (uint64_t) ( aSig<<1 ) ) { a = propagateFloatx80NaNOneArg( a, status ); if ( a.low == aSig ) float_raise( float_flag_invalid, status ); return (int16_t)(a.low>>48); } return aSign ? (int16_t) 0x8000 : 0x7FFF; } shiftCount = 0x4037 - aExp; if ( shiftCount <= 0 ) shiftCount = 1; shift64RightJamming( aSig, shiftCount, &aSig ); return roundAndPackInt16( aSign, aSig, status ); } int8_t floatx80_to_int8( floatx80 a, float_status *status) { flag aSign; int32_t aExp, shiftCount; uint64_t aSig; aSig = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); aSign = extractFloatx80Sign( a ); if ( aExp == 0x7FFF ) { if ( (uint64_t) ( aSig<<1 ) ) { a = propagateFloatx80NaNOneArg( a, status ); if ( a.low == aSig ) float_raise( float_flag_invalid, status ); return (int8_t)(a.low>>56); } float_raise( float_flag_invalid, status ); return aSign ? (int8_t) 0x80 : 0x7F; } shiftCount = 0x4037 - aExp; if ( shiftCount <= 0 ) shiftCount = 1; shift64RightJamming( aSig, shiftCount, &aSig ); return roundAndPackInt8( aSign, aSig, status ); } #endif // End of addition for Previous /*---------------------------------------------------------------------------- | Returns the result of converting the extended double-precision floating- | point value `a' to the 32-bit two's complement integer format. The | conversion is performed according to the IEC/IEEE Standard for Binary | Floating-Point Arithmetic, except that the conversion is always rounded | toward zero. If `a' is a NaN, the largest positive integer is returned. | Otherwise, if the conversion overflows, the largest integer with the same | sign as `a' is returned. *----------------------------------------------------------------------------*/ int32_t floatx80_to_int32_round_to_zero(floatx80 a, float_status *status) { flag aSign; int32_t aExp, shiftCount; uint64_t aSig, savedASig; int32_t z; if (floatx80_invalid_encoding(a)) { float_raise(float_flag_invalid, status); return 1 << 31; } aSig = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); aSign = extractFloatx80Sign( a ); if ( 0x401E < aExp ) { if ( ( aExp == 0x7FFF ) && (uint64_t) ( aSig<<1 ) ) aSign = 0; goto invalid; } else if ( aExp < 0x3FFF ) { if (aExp || aSig) { status->float_exception_flags |= float_flag_inexact; } return 0; } shiftCount = 0x403E - aExp; savedASig = aSig; aSig >>= shiftCount; z = aSig; if ( aSign ) z = - z; if ( ( z < 0 ) ^ aSign ) { invalid: float_raise(float_flag_invalid, status); return aSign ? (int32_t) 0x80000000 : 0x7FFFFFFF; } if ( ( aSig<<shiftCount ) != savedASig ) { status->float_exception_flags |= float_flag_inexact; } return z; } /*---------------------------------------------------------------------------- | Returns the result of converting the extended double-precision floating- | point value `a' to the 64-bit two's complement integer format. The | conversion is performed according to the IEC/IEEE Standard for Binary | Floating-Point Arithmetic---which means in particular that the conversion | is rounded according to the current rounding mode. If `a' is a NaN, | the largest positive integer is returned. Otherwise, if the conversion | overflows, the largest integer with the same sign as `a' is returned. *----------------------------------------------------------------------------*/ int64_t floatx80_to_int64(floatx80 a, float_status *status) { flag aSign; int32_t aExp, shiftCount; uint64_t aSig, aSigExtra; if (floatx80_invalid_encoding(a)) { float_raise(float_flag_invalid, status); return 1ULL << 63; } aSig = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); aSign = extractFloatx80Sign( a ); shiftCount = 0x403E - aExp; if ( shiftCount <= 0 ) { if ( shiftCount ) { float_raise(float_flag_invalid, status); if ( ! aSign || ( ( aExp == 0x7FFF ) && ( aSig != LIT64( 0x8000000000000000 ) ) ) ) { return LIT64( 0x7FFFFFFFFFFFFFFF ); } return (int64_t) LIT64( 0x8000000000000000 ); } aSigExtra = 0; } else { shift64ExtraRightJamming( aSig, 0, shiftCount, &aSig, &aSigExtra ); } return roundAndPackInt64(aSign, aSig, aSigExtra, status); } /*---------------------------------------------------------------------------- | Returns the result of converting the extended double-precision floating- | point value `a' to the single-precision floating-point format. The | conversion is performed according to the IEC/IEEE Standard for Binary | Floating-Point Arithmetic. *----------------------------------------------------------------------------*/ float32 floatx80_to_float32(floatx80 a, float_status *status) { flag aSign; int32_t aExp; uint64_t aSig; aSig = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); aSign = extractFloatx80Sign( a ); if ( aExp == 0x7FFF ) { if ( (uint64_t) ( aSig<<1 ) ) { return commonNaNToFloat32(floatx80ToCommonNaN(a, status)); } return packFloat32( aSign, 0xFF, 0 ); } #ifdef SOFTFLOAT_68K if ( aExp == 0 ) { if ( aSig == 0) return packFloat32( aSign, 0, 0 ); normalizeFloatx80Subnormal( aSig, &aExp, &aSig ); } shift64RightJamming( aSig, 33, &aSig ); aExp -= 0x3F81; #else shift64RightJamming( aSig, 33, &aSig ); if ( aExp || aSig ) aExp -= 0x3F81; #endif return roundAndPackFloat32(aSign, aExp, aSig, status); } /*---------------------------------------------------------------------------- | Returns the result of converting the extended double-precision floating- | point value `a' to the double-precision floating-point format. The | conversion is performed according to the IEC/IEEE Standard for Binary | Floating-Point Arithmetic. *----------------------------------------------------------------------------*/ float64 floatx80_to_float64(floatx80 a, float_status *status) { flag aSign; int32_t aExp; uint64_t aSig, zSig; aSig = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); aSign = extractFloatx80Sign( a ); if ( aExp == 0x7FFF ) { if ( (uint64_t) ( aSig<<1 ) ) { return commonNaNToFloat64(floatx80ToCommonNaN(a, status), status); } return packFloat64( aSign, 0x7FF, 0 ); } #ifdef SOFTFLOAT_68K if ( aExp == 0 ) { if ( aSig == 0) return packFloat64( aSign, 0, 0 ); normalizeFloatx80Subnormal( aSig, &aExp, &aSig ); } shift64RightJamming( aSig, 1, &zSig ); aExp -= 0x3C01; #else shift64RightJamming( aSig, 1, &zSig ); if ( aExp || aSig ) aExp -= 0x3C01; #endif return roundAndPackFloat64(aSign, aExp, zSig, status); } #ifdef SOFTFLOAT_68K // 31-01-2017 /*---------------------------------------------------------------------------- | Returns the result of converting the extended double-precision floating- | point value `a' to the extended double-precision floating-point format. | The conversion is performed according to the IEC/IEEE Standard for Binary | Floating-Point Arithmetic. *----------------------------------------------------------------------------*/ floatx80 floatx80_to_floatx80( floatx80 a, float_status *status ) { flag aSign; int32_t aExp; uint64_t aSig; aSig = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); aSign = extractFloatx80Sign( a ); if ( aExp == 0x7FFF && (uint64_t) ( aSig<<1 ) ) { return propagateFloatx80NaNOneArg( a, status ); } if ( aExp == 0 && aSig != 0 ) { return normalizeRoundAndPackFloatx80( status->floatx80_rounding_precision, aSign, aExp, aSig, 0, status ); } return a; } #endif #ifdef SOFTFLOAT_68K // 30-01-2016: Added for Previous floatx80 floatx80_round32( floatx80 a, float_status *status ) { flag aSign; int32_t aExp; uint64_t aSig; aSig = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); aSign = extractFloatx80Sign( a ); if ( aExp == 0x7FFF || aSig == 0 ) { return a; } if ( aExp == 0 ) { normalizeFloatx80Subnormal( aSig, &aExp, &aSig ); } return roundSigAndPackFloatx80( 32, aSign, aExp, aSig, 0, status ); } floatx80 floatx80_round64( floatx80 a, float_status *status ) { flag aSign; int32_t aExp; uint64_t aSig; aSig = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); aSign = extractFloatx80Sign( a ); if ( aExp == 0x7FFF || aSig == 0 ) { return a; } if ( aExp == 0 ) { normalizeFloatx80Subnormal( aSig, &aExp, &aSig ); } return roundSigAndPackFloatx80( 64, aSign, aExp, aSig, 0, status ); } floatx80 floatx80_round_to_float32( floatx80 a, float_status *status ) { flag aSign; int32_t aExp; uint64_t aSig; aSign = extractFloatx80Sign( a ); aSig = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); if ( aExp == 0x7FFF ) { if ( (uint64_t) ( aSig<<1 ) ) return propagateFloatx80NaNOneArg( a, status ); return a; } if ( aExp == 0 ) { if ( aSig == 0 ) return a; normalizeFloatx80Subnormal( aSig, &aExp, &aSig ); } return roundAndPackFloatx80( 32, aSign, aExp, aSig, 0, status ); } floatx80 floatx80_round_to_float64( floatx80 a, float_status *status ) { flag aSign; int32_t aExp; uint64_t aSig; aSign = extractFloatx80Sign( a ); aSig = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); if ( aExp == 0x7FFF ) { if ( (uint64_t) ( aSig<<1 ) ) return propagateFloatx80NaNOneArg( a, status ); return a; } if ( aExp == 0 ) { if ( aSig == 0 ) return a; normalizeFloatx80Subnormal( aSig, &aExp, &aSig ); } return roundAndPackFloatx80( 64, aSign, aExp, aSig, 0, status ); } floatx80 floatx80_normalize( floatx80 a ) { flag aSign; int16_t aExp; uint64_t aSig; int8_t shiftCount; aSig = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); aSign = extractFloatx80Sign( a ); if ( aExp == 0x7FFF || aExp == 0 ) return a; if ( aSig == 0 ) return packFloatx80(aSign, 0, 0); shiftCount = countLeadingZeros64( aSig ); if ( shiftCount > aExp ) shiftCount = aExp; aExp -= shiftCount; aSig <<= shiftCount; return packFloatx80( aSign, aExp, aSig ); } #endif // end of addition for Previous /*---------------------------------------------------------------------------- | Rounds the extended double-precision floating-point value `a' to an integer, | and returns the result as an extended quadruple-precision floating-point | value. The operation is performed according to the IEC/IEEE Standard for | Binary Floating-Point Arithmetic. *----------------------------------------------------------------------------*/ floatx80 floatx80_round_to_int(floatx80 a, float_status *status) { flag aSign; int32_t aExp; uint64_t lastBitMask, roundBitsMask; // int8_t roundingMode; floatx80 z; // roundingMode = status->float_rounding_mode; aSign = extractFloatx80Sign(a); aExp = extractFloatx80Exp( a ); if ( 0x403E <= aExp ) { if ( aExp == 0x7FFF ) { if ((uint64_t) ( extractFloatx80Frac( a )<<1 ) ) return propagateFloatx80NaNOneArg(a, status); return inf_clear_intbit(status) ? packFloatx80(aSign, aExp, 0) : a; } return a; } if ( aExp < 0x3FFF ) { if ( ( aExp == 0 ) #ifdef SOFTFLOAT_68K && ( (uint64_t) extractFloatx80Frac( a ) == 0 ) ) { #else && ( (uint64_t) ( extractFloatx80Frac( a )<<1 ) == 0 ) ) { #endif return a; } status->float_exception_flags |= float_flag_inexact; switch (status->float_rounding_mode) { case float_round_nearest_even: if ( ( aExp == 0x3FFE ) && (uint64_t) ( extractFloatx80Frac( a )<<1 ) ) { return packFloatx80( aSign, 0x3FFF, LIT64( 0x8000000000000000 ) ); } break; case float_round_ties_away: if (aExp == 0x3FFE) { return packFloatx80(aSign, 0x3FFF, LIT64(0x8000000000000000)); } break; case float_round_down: return aSign ? packFloatx80( 1, 0x3FFF, LIT64( 0x8000000000000000 ) ) : packFloatx80( 0, 0, 0 ); case float_round_up: return aSign ? packFloatx80( 1, 0, 0 ) : packFloatx80( 0, 0x3FFF, LIT64( 0x8000000000000000 ) ); } return packFloatx80( aSign, 0, 0 ); } lastBitMask = 1; lastBitMask <<= 0x403E - aExp; roundBitsMask = lastBitMask - 1; z = a; switch (status->float_rounding_mode) { case float_round_nearest_even: z.low += lastBitMask>>1; if ((z.low & roundBitsMask) == 0) { z.low &= ~lastBitMask; } break; case float_round_ties_away: z.low += lastBitMask >> 1; break; case float_round_to_zero: break; case float_round_up: if (!extractFloatx80Sign(z)) { z.low += roundBitsMask; } break; case float_round_down: if (extractFloatx80Sign(z)) { z.low += roundBitsMask; } break; default: abort(); } z.low &= ~ roundBitsMask; if ( z.low == 0 ) { ++z.high; z.low = LIT64( 0x8000000000000000 ); } if (z.low != a.low) { status->float_exception_flags |= float_flag_inexact; } return z; } #ifdef SOFTFLOAT_68K // 09-01-2017: Added for Previous floatx80 floatx80_round_to_int_toward_zero( floatx80 a, float_status *status) { flag aSign; int32_t aExp; uint64_t lastBitMask, roundBitsMask; floatx80 z; aSign = extractFloatx80Sign(a); aExp = extractFloatx80Exp( a ); if ( 0x403E <= aExp ) { if ( aExp == 0x7FFF ) { if ( (uint64_t) ( extractFloatx80Frac( a )<<1 ) ) return propagateFloatx80NaNOneArg( a, status ); return inf_clear_intbit(status) ? packFloatx80(aSign, aExp, 0) : a; } return a; } if ( aExp < 0x3FFF ) { if ( ( aExp == 0 ) #ifdef SOFTFLOAT_68K && ( (uint64_t) extractFloatx80Frac( a ) == 0 ) ) { #else && ( (uint64_t) ( extractFloatx80Frac( a )<<1 ) == 0 ) ) { #endif return a; } status->float_exception_flags |= float_flag_inexact; return packFloatx80( aSign, 0, 0 ); } lastBitMask = 1; lastBitMask <<= 0x403E - aExp; roundBitsMask = lastBitMask - 1; z = a; z.low &= ~ roundBitsMask; if ( z.low == 0 ) { ++z.high; z.low = LIT64( 0x8000000000000000 ); } if ( z.low != a.low ) status->float_exception_flags |= float_flag_inexact; return z; } #endif // End of addition for Previous /*---------------------------------------------------------------------------- | Returns the result of adding the absolute values of the extended double- | precision floating-point values `a' and `b'. If `zSign' is 1, the sum is | negated before being returned. `zSign' is ignored if the result is a NaN. | The addition is performed according to the IEC/IEEE Standard for Binary | Floating-Point Arithmetic. *----------------------------------------------------------------------------*/ static floatx80 addFloatx80Sigs(floatx80 a, floatx80 b, flag zSign, float_status *status) { int32_t aExp, bExp, zExp; uint64_t aSig, bSig, zSig0, zSig1; int32_t expDiff; aSig = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); bSig = extractFloatx80Frac( b ); bExp = extractFloatx80Exp( b ); #ifdef SOFTFLOAT_68K if ( aExp == 0 ) { normalizeFloatx80Subnormal( aSig, &aExp, &aSig ); } if ( bExp == 0 ) { normalizeFloatx80Subnormal( bSig, &bExp, &bSig ); } #endif expDiff = aExp - bExp; if ( 0 < expDiff ) { if ( aExp == 0x7FFF ) { if ((uint64_t)(aSig << 1)) return propagateFloatx80NaN(a, b, status); return inf_clear_intbit(status) ? packFloatx80(extractFloatx80Sign(a), aExp, 0) : a; } #ifndef SOFTFLOAT_68K if ( bExp == 0 ) --expDiff; #endif shift64ExtraRightJamming( bSig, 0, expDiff, &bSig, &zSig1 ); zExp = aExp; } else if ( expDiff < 0 ) { if ( bExp == 0x7FFF ) { if ((uint64_t)(bSig << 1)) return propagateFloatx80NaN(a, b, status); if (inf_clear_intbit(status)) bSig = 0; return packFloatx80( zSign, bExp, bSig ); } #ifndef SOFTFLOAT_68K if ( aExp == 0 ) ++expDiff; #endif shift64ExtraRightJamming( aSig, 0, - expDiff, &aSig, &zSig1 ); zExp = bExp; } else { if ( aExp == 0x7FFF ) { if ( (uint64_t) ( ( aSig | bSig )<<1 ) ) { return propagateFloatx80NaN(a, b, status); } if (inf_clear_intbit(status)) return packFloatx80(extractFloatx80Sign(a), aExp, 0); return faddsub_swap_inf(status) ? b : a; } zSig1 = 0; zSig0 = aSig + bSig; #ifndef SOFTFLOAT_68K if ( aExp == 0 ) { normalizeFloatx80Subnormal( zSig0, &zExp, &zSig0 ); goto roundAndPack; } #endif zExp = aExp; #ifdef SOFTFLOAT_68K if ( aSig == 0 && bSig == 0 ) return packFloatx80( zSign, 0, 0 ); if ( aSig == 0 || bSig == 0 ) goto roundAndPack; #endif goto shiftRight1; } zSig0 = aSig + bSig; if ( (int64_t) zSig0 < 0 ) goto roundAndPack; shiftRight1: shift64ExtraRightJamming( zSig0, zSig1, 1, &zSig0, &zSig1 ); zSig0 |= LIT64( 0x8000000000000000 ); ++zExp; roundAndPack: return roundAndPackFloatx80(status->floatx80_rounding_precision, zSign, zExp, zSig0, zSig1, status); } /*---------------------------------------------------------------------------- | Returns the result of subtracting the absolute values of the extended | double-precision floating-point values `a' and `b'. If `zSign' is 1, the | difference is negated before being returned. `zSign' is ignored if the | result is a NaN. The subtraction is performed according to the IEC/IEEE | Standard for Binary Floating-Point Arithmetic. *----------------------------------------------------------------------------*/ static floatx80 subFloatx80Sigs(floatx80 a, floatx80 b, flag zSign, float_status *status) { int32_t aExp, bExp, zExp; uint64_t aSig, bSig, zSig0, zSig1; int32_t expDiff; aSig = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); bSig = extractFloatx80Frac( b ); bExp = extractFloatx80Exp( b ); expDiff = aExp - bExp; if ( 0 < expDiff ) goto aExpBigger; if ( expDiff < 0 ) goto bExpBigger; if ( aExp == 0x7FFF ) { if ( (uint64_t) ( ( aSig | bSig )<<1 ) ) { return propagateFloatx80NaN(a, b, status); } float_raise(float_flag_invalid, status); return floatx80_default_nan(status); } #ifndef SOFTFLOAT_68K if ( aExp == 0 ) { aExp = 1; bExp = 1; } #endif zSig1 = 0; if ( bSig < aSig ) goto aBigger; if ( aSig < bSig ) goto bBigger; return packFloatx80(status->float_rounding_mode == float_round_down, 0, 0); bExpBigger: if ( bExp == 0x7FFF ) { if ((uint64_t)(bSig << 1)) return propagateFloatx80NaN(a, b, status); if (inf_clear_intbit(status)) bSig = 0; return packFloatx80(zSign ^ 1, bExp, bSig); } #ifndef SOFTFLOAT_68K if ( aExp == 0 ) ++expDiff; #endif shift128RightJamming( aSig, 0, - expDiff, &aSig, &zSig1 ); bBigger: sub128( bSig, 0, aSig, zSig1, &zSig0, &zSig1 ); zExp = bExp; zSign ^= 1; goto normalizeRoundAndPack; aExpBigger: if ( aExp == 0x7FFF ) { if ((uint64_t)(aSig << 1)) return propagateFloatx80NaN(a, b, status); return inf_clear_intbit(status) ? packFloatx80(extractFloatx80Sign(a), aExp, 0) : a; } #ifndef SOFTFLOAT_68K if ( bExp == 0 ) --expDiff; #endif shift128RightJamming( bSig, 0, expDiff, &bSig, &zSig1 ); aBigger: sub128( aSig, 0, bSig, zSig1, &zSig0, &zSig1 ); zExp = aExp; normalizeRoundAndPack: return normalizeRoundAndPackFloatx80(status->floatx80_rounding_precision, zSign, zExp, zSig0, zSig1, status); } /*---------------------------------------------------------------------------- | Returns the result of adding the extended double-precision floating-point | values `a' and `b'. The operation is performed according to the IEC/IEEE | Standard for Binary Floating-Point Arithmetic. *----------------------------------------------------------------------------*/ floatx80 floatx80_add(floatx80 a, floatx80 b, float_status *status) { flag aSign, bSign; if (floatx80_invalid_encoding(a) || floatx80_invalid_encoding(b)) { float_raise(float_flag_invalid, status); return floatx80_default_nan(status); } aSign = extractFloatx80Sign( a ); bSign = extractFloatx80Sign( b ); if ( aSign == bSign ) { return addFloatx80Sigs(a, b, aSign, status); } else { return subFloatx80Sigs(a, b, aSign, status); } } /*---------------------------------------------------------------------------- | Returns the result of subtracting the extended double-precision floating- | point values `a' and `b'. The operation is performed according to the | IEC/IEEE Standard for Binary Floating-Point Arithmetic. *----------------------------------------------------------------------------*/ floatx80 floatx80_sub(floatx80 a, floatx80 b, float_status *status) { flag aSign, bSign; if (floatx80_invalid_encoding(a) || floatx80_invalid_encoding(b)) { float_raise(float_flag_invalid, status); return floatx80_default_nan(status); } aSign = extractFloatx80Sign( a ); bSign = extractFloatx80Sign( b ); if ( aSign == bSign ) { return subFloatx80Sigs(a, b, aSign, status); } else { return addFloatx80Sigs(a, b, aSign, status); } } /*---------------------------------------------------------------------------- | Returns the result of multiplying the extended double-precision floating- | point values `a' and `b'. The operation is performed according to the | IEC/IEEE Standard for Binary Floating-Point Arithmetic. *----------------------------------------------------------------------------*/ floatx80 floatx80_mul(floatx80 a, floatx80 b, float_status *status) { flag aSign, bSign, zSign; int32_t aExp, bExp, zExp; uint64_t aSig, bSig, zSig0, zSig1; if (floatx80_invalid_encoding(a) || floatx80_invalid_encoding(b)) { float_raise(float_flag_invalid, status); return floatx80_default_nan(status); } aSig = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); aSign = extractFloatx80Sign( a ); bSig = extractFloatx80Frac( b ); bExp = extractFloatx80Exp( b ); bSign = extractFloatx80Sign( b ); zSign = aSign ^ bSign; if ( aExp == 0x7FFF ) { if ( (uint64_t) ( aSig<<1 ) || ( ( bExp == 0x7FFF ) && (uint64_t) ( bSig<<1 ) ) ) { return propagateFloatx80NaN(a, b, status); } if ( ( bExp | bSig ) == 0 ) goto invalid; if (inf_clear_intbit(status)) aSig = 0; return packFloatx80(zSign, aExp, aSig); } if ( bExp == 0x7FFF ) { if ((uint64_t)(bSig << 1)) { return propagateFloatx80NaN(a, b, status); } if ( ( aExp | aSig ) == 0 ) { invalid: float_raise(float_flag_invalid, status); return floatx80_default_nan(status); } if (inf_clear_intbit(status)) bSig = 0; return packFloatx80(zSign, bExp, bSig); } if ( aExp == 0 ) { if ( aSig == 0 ) return packFloatx80( zSign, 0, 0 ); normalizeFloatx80Subnormal( aSig, &aExp, &aSig ); } if ( bExp == 0 ) { if ( bSig == 0 ) return packFloatx80( zSign, 0, 0 ); normalizeFloatx80Subnormal( bSig, &bExp, &bSig ); } zExp = aExp + bExp - 0x3FFE; mul64To128( aSig, bSig, &zSig0, &zSig1 ); if ( 0 < (int64_t) zSig0 ) { shortShift128Left( zSig0, zSig1, 1, &zSig0, &zSig1 ); --zExp; } return roundAndPackFloatx80(status->floatx80_rounding_precision, zSign, zExp, zSig0, zSig1, status); } #ifdef SOFTFLOAT_68K // 21-01-2017: Added for Previous floatx80 floatx80_sglmul( floatx80 a, floatx80 b, float_status *status ) { flag aSign, bSign, zSign; int32_t aExp, bExp, zExp; uint64_t aSig, bSig, zSig0, zSig1; aSig = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); aSign = extractFloatx80Sign( a ); bSig = extractFloatx80Frac( b ); bExp = extractFloatx80Exp( b ); bSign = extractFloatx80Sign( b ); zSign = aSign ^ bSign; if ( aExp == 0x7FFF ) { if ( (uint64_t) ( aSig<<1 ) || ( ( bExp == 0x7FFF ) && (uint64_t) ( bSig<<1 ) ) ) { return propagateFloatx80NaN( a, b, status ); } if ( ( bExp | bSig ) == 0 ) goto invalid; if (inf_clear_intbit(status)) aSig = 0; return packFloatx80(zSign, aExp, aSig); } if ( bExp == 0x7FFF ) { if ( (uint64_t) ( bSig<<1 ) ) return propagateFloatx80NaN( a, b, status ); if ( ( aExp | aSig ) == 0 ) { invalid: float_raise( float_flag_invalid, status ); return floatx80_default_nan(status); } if (inf_clear_intbit(status)) bSig = 0; return packFloatx80(zSign, bExp, bSig); } if ( aExp == 0 ) { if ( aSig == 0 ) return packFloatx80( zSign, 0, 0 ); normalizeFloatx80Subnormal( aSig, &aExp, &aSig ); } if ( bExp == 0 ) { if ( bSig == 0 ) return packFloatx80( zSign, 0, 0 ); normalizeFloatx80Subnormal( bSig, &bExp, &bSig ); } aSig &= LIT64( 0xFFFFFF0000000000 ); bSig &= LIT64( 0xFFFFFF0000000000 ); zExp = aExp + bExp - 0x3FFE; mul64To128( aSig, bSig, &zSig0, &zSig1 ); if ( 0 < (int64_t) zSig0 ) { shortShift128Left( zSig0, zSig1, 1, &zSig0, &zSig1 ); --zExp; } return roundSigAndPackFloatx80( 32, zSign, zExp, zSig0, zSig1, status); } #endif // End of addition for Previous /*---------------------------------------------------------------------------- | Returns the result of dividing the extended double-precision floating-point | value `a' by the corresponding value `b'. The operation is performed | according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic. *----------------------------------------------------------------------------*/ floatx80 floatx80_div(floatx80 a, floatx80 b, float_status *status) { flag aSign, bSign, zSign; int32_t aExp, bExp, zExp; uint64_t aSig, bSig, zSig0, zSig1; uint64_t rem0, rem1, rem2, term0, term1, term2; if (floatx80_invalid_encoding(a) || floatx80_invalid_encoding(b)) { float_raise(float_flag_invalid, status); return floatx80_default_nan(status); } aSig = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); aSign = extractFloatx80Sign( a ); bSig = extractFloatx80Frac( b ); bExp = extractFloatx80Exp( b ); bSign = extractFloatx80Sign( b ); zSign = aSign ^ bSign; if ( aExp == 0x7FFF ) { if ((uint64_t)(aSig << 1)) { return propagateFloatx80NaN(a, b, status); } if ( bExp == 0x7FFF ) { if ((uint64_t)(bSig << 1)) { return propagateFloatx80NaN(a, b, status); } goto invalid; } if (inf_clear_intbit(status)) aSig = 0; return packFloatx80(zSign, aExp, aSig); } if ( bExp == 0x7FFF ) { if ((uint64_t)(bSig << 1)) { return propagateFloatx80NaN(a, b, status); } return packFloatx80( zSign, 0, 0 ); } if ( bExp == 0 ) { if ( bSig == 0 ) { if ( ( aExp | aSig ) == 0 ) { invalid: float_raise(float_flag_invalid, status); return floatx80_default_nan(status); } float_raise(float_flag_divbyzero, status); return packFloatx80( zSign, 0x7FFF, floatx80_default_infinity_low ); } normalizeFloatx80Subnormal( bSig, &bExp, &bSig ); } if ( aExp == 0 ) { if ( aSig == 0 ) return packFloatx80( zSign, 0, 0 ); normalizeFloatx80Subnormal( aSig, &aExp, &aSig ); } zExp = aExp - bExp + 0x3FFE; rem1 = 0; if ( bSig <= aSig ) { shift128Right( aSig, 0, 1, &aSig, &rem1 ); ++zExp; } zSig0 = estimateDiv128To64( aSig, rem1, bSig ); mul64To128( bSig, zSig0, &term0, &term1 ); sub128( aSig, rem1, term0, term1, &rem0, &rem1 ); while ( (int64_t) rem0 < 0 ) { --zSig0; add128( rem0, rem1, 0, bSig, &rem0, &rem1 ); } zSig1 = estimateDiv128To64( rem1, 0, bSig ); if ( (uint64_t) ( zSig1<<1 ) <= 8 ) { mul64To128( bSig, zSig1, &term1, &term2 ); sub128( rem1, 0, term1, term2, &rem1, &rem2 ); while ( (int64_t) rem1 < 0 ) { --zSig1; add128( rem1, rem2, 0, bSig, &rem1, &rem2 ); } zSig1 |= ( ( rem1 | rem2 ) != 0 ); } return roundAndPackFloatx80(status->floatx80_rounding_precision, zSign, zExp, zSig0, zSig1, status); } #ifdef SOFTFLOAT_68K // 21-01-2017: Addition for Previous floatx80 floatx80_sgldiv( floatx80 a, floatx80 b, float_status *status ) { flag aSign, bSign, zSign; int32_t aExp, bExp, zExp; uint64_t aSig, bSig, zSig0, zSig1; uint64_t rem0, rem1, rem2, term0, term1, term2; aSig = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); aSign = extractFloatx80Sign( a ); bSig = extractFloatx80Frac( b ); bExp = extractFloatx80Exp( b ); bSign = extractFloatx80Sign( b ); zSign = aSign ^ bSign; if ( aExp == 0x7FFF ) { if ( (uint64_t) ( aSig<<1 ) ) return propagateFloatx80NaN( a, b, status ); if ( bExp == 0x7FFF ) { if ( (uint64_t) ( bSig<<1 ) ) return propagateFloatx80NaN( a, b, status ); goto invalid; } if (inf_clear_intbit(status)) aSig = 0; return packFloatx80(zSign, aExp, aSig); } if ( bExp == 0x7FFF ) { if ( (uint64_t) ( bSig<<1 ) ) return propagateFloatx80NaN( a, b, status ); return packFloatx80( zSign, 0, 0 ); } if ( bExp == 0 ) { if ( bSig == 0 ) { if ( ( aExp | aSig ) == 0 ) { invalid: float_raise( float_flag_invalid, status ); return floatx80_default_nan(status); } float_raise( float_flag_divbyzero, status ); return packFloatx80( zSign, 0x7FFF, floatx80_default_infinity_low ); } normalizeFloatx80Subnormal( bSig, &bExp, &bSig ); } if ( aExp == 0 ) { if ( aSig == 0 ) return packFloatx80( zSign, 0, 0 ); normalizeFloatx80Subnormal( aSig, &aExp, &aSig ); } zExp = aExp - bExp + 0x3FFE; rem1 = 0; if ( bSig <= aSig ) { shift128Right( aSig, 0, 1, &aSig, &rem1 ); ++zExp; } zSig0 = estimateDiv128To64( aSig, rem1, bSig ); mul64To128( bSig, zSig0, &term0, &term1 ); sub128( aSig, rem1, term0, term1, &rem0, &rem1 ); while ( (int64_t) rem0 < 0 ) { --zSig0; add128( rem0, rem1, 0, bSig, &rem0, &rem1 ); } zSig1 = estimateDiv128To64( rem1, 0, bSig ); if ( (uint64_t) ( zSig1<<1 ) <= 8 ) { mul64To128( bSig, zSig1, &term1, &term2 ); sub128( rem1, 0, term1, term2, &rem1, &rem2 ); while ( (int64_t) rem1 < 0 ) { --zSig1; add128( rem1, rem2, 0, bSig, &rem1, &rem2 ); } zSig1 |= ( ( rem1 | rem2 ) != 0 ); } return roundSigAndPackFloatx80( 32, zSign, zExp, zSig0, zSig1, status); } #endif // End of addition for Previous /*---------------------------------------------------------------------------- | Returns the remainder of the extended double-precision floating-point value | `a' with respect to the corresponding value `b'. The operation is performed | according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic. *----------------------------------------------------------------------------*/ #ifndef SOFTFLOAT_68K floatx80 floatx80_rem(floatx80 a, floatx80 b, float_status *status) { flag aSign, zSign; int32_t aExp, bExp, expDiff; uint64_t aSig0, aSig1, bSig; uint64_t q, term0, term1, alternateASig0, alternateASig1; if (floatx80_invalid_encoding(a) || floatx80_invalid_encoding(b)) { float_raise(float_flag_invalid, status); return floatx80_default_nan(status); } aSig0 = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); aSign = extractFloatx80Sign( a ); bSig = extractFloatx80Frac( b ); bExp = extractFloatx80Exp( b ); if ( aExp == 0x7FFF ) { if ( (uint64_t) ( aSig0<<1 ) || ( ( bExp == 0x7FFF ) && (uint64_t) ( bSig<<1 ) ) ) { return propagateFloatx80NaN(a, b, status); } goto invalid; } if ( bExp == 0x7FFF ) { if ((uint64_t)(bSig << 1)) { return propagateFloatx80NaN(a, b, status); } return a; } if ( bExp == 0 ) { if ( bSig == 0 ) { invalid: float_raise(float_flag_invalid, status); return floatx80_default_nan(status); } normalizeFloatx80Subnormal( bSig, &bExp, &bSig ); } if ( aExp == 0 ) { if ( (uint64_t) ( aSig0<<1 ) == 0 ) return a; normalizeFloatx80Subnormal( aSig0, &aExp, &aSig0 ); } bSig |= LIT64( 0x8000000000000000 ); zSign = aSign; expDiff = aExp - bExp; aSig1 = 0; if ( expDiff < 0 ) { if ( expDiff < -1 ) return a; shift128Right( aSig0, 0, 1, &aSig0, &aSig1 ); expDiff = 0; } q = ( bSig <= aSig0 ); if ( q ) aSig0 -= bSig; expDiff -= 64; while ( 0 < expDiff ) { q = estimateDiv128To64( aSig0, aSig1, bSig ); q = ( 2 < q ) ? q - 2 : 0; mul64To128( bSig, q, &term0, &term1 ); sub128( aSig0, aSig1, term0, term1, &aSig0, &aSig1 ); shortShift128Left( aSig0, aSig1, 62, &aSig0, &aSig1 ); expDiff -= 62; } expDiff += 64; if ( 0 < expDiff ) { q = estimateDiv128To64( aSig0, aSig1, bSig ); q = ( 2 < q ) ? q - 2 : 0; q >>= 64 - expDiff; mul64To128( bSig, q<<( 64 - expDiff ), &term0, &term1 ); sub128( aSig0, aSig1, term0, term1, &aSig0, &aSig1 ); shortShift128Left( 0, bSig, 64 - expDiff, &term0, &term1 ); while ( le128( term0, term1, aSig0, aSig1 ) ) { ++q; sub128( aSig0, aSig1, term0, term1, &aSig0, &aSig1 ); } } else { term1 = 0; term0 = bSig; } sub128( term0, term1, aSig0, aSig1, &alternateASig0, &alternateASig1 ); if ( lt128( alternateASig0, alternateASig1, aSig0, aSig1 ) || ( eq128( alternateASig0, alternateASig1, aSig0, aSig1 ) && ( q & 1 ) ) ) { aSig0 = alternateASig0; aSig1 = alternateASig1; zSign = ! zSign; } return normalizeRoundAndPackFloatx80( 80, zSign, bExp + expDiff, aSig0, aSig1, status); } #else // 09-01-2017: Modified version for Previous floatx80 floatx80_rem( floatx80 a, floatx80 b, uint64_t *q, flag *s, float_status *status ) { flag aSign, bSign, zSign; int32_t aExp, bExp, expDiff; uint64_t aSig0, aSig1, bSig; uint64_t qTemp, term0, term1, alternateASig0, alternateASig1; aSig0 = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); aSign = extractFloatx80Sign( a ); bSig = extractFloatx80Frac( b ); bExp = extractFloatx80Exp( b ); bSign = extractFloatx80Sign( b ); if ( aExp == 0x7FFF ) { if ( (uint64_t) ( aSig0<<1 ) || ( ( bExp == 0x7FFF ) && (uint64_t) ( bSig<<1 ) ) ) { return propagateFloatx80NaN( a, b, status ); } goto invalid; } if ( bExp == 0x7FFF ) { if ( (uint64_t) ( bSig<<1 ) ) return propagateFloatx80NaN( a, b, status ); *s = (aSign != bSign); *q = 0; return a; } if ( bExp == 0 ) { if ( bSig == 0 ) { invalid: float_raise( float_flag_invalid, status ); return floatx80_default_nan(status); } normalizeFloatx80Subnormal( bSig, &bExp, &bSig ); } if ( aExp == 0 ) { #ifdef SOFTFLOAT_68K if ( aSig0 == 0 ) { *s = (aSign != bSign); *q = 0; return a; } #else if ( (uint64_t) ( aSig0<<1 ) == 0 ) return a; #endif normalizeFloatx80Subnormal( aSig0, &aExp, &aSig0 ); } bSig |= LIT64( 0x8000000000000000 ); zSign = aSign; expDiff = aExp - bExp; *s = (aSign != bSign); aSig1 = 0; if ( expDiff < 0 ) { if ( expDiff < -1 ) return a; shift128Right( aSig0, 0, 1, &aSig0, &aSig1 ); expDiff = 0; } qTemp = ( bSig <= aSig0 ); if ( qTemp ) aSig0 -= bSig; *q = ( expDiff > 63 ) ? 0 : ( qTemp<<expDiff ); expDiff -= 64; while ( 0 < expDiff ) { qTemp = estimateDiv128To64( aSig0, aSig1, bSig ); qTemp = ( 2 < qTemp ) ? qTemp - 2 : 0; mul64To128( bSig, qTemp, &term0, &term1 ); sub128( aSig0, aSig1, term0, term1, &aSig0, &aSig1 ); shortShift128Left( aSig0, aSig1, 62, &aSig0, &aSig1 ); *q = ( expDiff > 63 ) ? 0 : ( qTemp<<expDiff ); expDiff -= 62; } expDiff += 64; if ( 0 < expDiff ) { qTemp = estimateDiv128To64( aSig0, aSig1, bSig ); qTemp = ( 2 < qTemp ) ? qTemp - 2 : 0; qTemp >>= 64 - expDiff; mul64To128( bSig, qTemp<<( 64 - expDiff ), &term0, &term1 ); sub128( aSig0, aSig1, term0, term1, &aSig0, &aSig1 ); shortShift128Left( 0, bSig, 64 - expDiff, &term0, &term1 ); while ( le128( term0, term1, aSig0, aSig1 ) ) { ++qTemp; sub128( aSig0, aSig1, term0, term1, &aSig0, &aSig1 ); } *q += qTemp; } else { term1 = 0; term0 = bSig; } sub128( term0, term1, aSig0, aSig1, &alternateASig0, &alternateASig1 ); if ( lt128( alternateASig0, alternateASig1, aSig0, aSig1 ) || ( eq128( alternateASig0, alternateASig1, aSig0, aSig1 ) && ( qTemp & 1 ) ) ) { aSig0 = alternateASig0; aSig1 = alternateASig1; zSign = ! zSign; ++*q; } return normalizeRoundAndPackFloatx80(status->floatx80_rounding_precision, zSign, bExp + expDiff, aSig0, aSig1, status ); } #endif // End of modification #ifdef SOFTFLOAT_68K // 08-01-2017: Added for Previous /*---------------------------------------------------------------------------- | Returns the modulo remainder of the extended double-precision floating-point | value `a' with respect to the corresponding value `b'. *----------------------------------------------------------------------------*/ floatx80 floatx80_mod( floatx80 a, floatx80 b, uint64_t *q, flag *s, float_status *status ) { flag aSign, bSign, zSign; int32_t aExp, bExp, expDiff; uint64_t aSig0, aSig1, bSig; uint64_t qTemp, term0, term1; aSig0 = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); aSign = extractFloatx80Sign( a ); bSig = extractFloatx80Frac( b ); bExp = extractFloatx80Exp( b ); bSign = extractFloatx80Sign( b ); if ( aExp == 0x7FFF ) { if ( (uint64_t) ( aSig0<<1 ) || ( ( bExp == 0x7FFF ) && (uint64_t) ( bSig<<1 ) ) ) { return propagateFloatx80NaN( a, b, status ); } goto invalid; } if ( bExp == 0x7FFF ) { if ( (uint64_t) ( bSig<<1 ) ) return propagateFloatx80NaN( a, b, status ); *s = (aSign != bSign); *q = 0; return a; } if ( bExp == 0 ) { if ( bSig == 0 ) { invalid: float_raise( float_flag_invalid, status ); return floatx80_default_nan(status); } normalizeFloatx80Subnormal( bSig, &bExp, &bSig ); } if ( aExp == 0 ) { #ifdef SOFTFLOAT_68K if ( aSig0 == 0 ) { *s = (aSign != bSign); *q = 0; return a; } #else if ( (uint64_t) ( aSig0<<1 ) == 0 ) return a; #endif normalizeFloatx80Subnormal( aSig0, &aExp, &aSig0 ); } bSig |= LIT64( 0x8000000000000000 ); zSign = aSign; expDiff = aExp - bExp; *s = (aSign != bSign); aSig1 = 0; if ( expDiff < 0 ) return a; qTemp = ( bSig <= aSig0 ); if ( qTemp ) aSig0 -= bSig; *q = ( expDiff > 63 ) ? 0 : ( qTemp<<expDiff ); expDiff -= 64; while ( 0 < expDiff ) { qTemp = estimateDiv128To64( aSig0, aSig1, bSig ); qTemp = ( 2 < qTemp ) ? qTemp - 2 : 0; mul64To128( bSig, qTemp, &term0, &term1 ); sub128( aSig0, aSig1, term0, term1, &aSig0, &aSig1 ); shortShift128Left( aSig0, aSig1, 62, &aSig0, &aSig1 ); *q = ( expDiff > 63 ) ? 0 : ( qTemp<<expDiff ); expDiff -= 62; } expDiff += 64; if ( 0 < expDiff ) { qTemp = estimateDiv128To64( aSig0, aSig1, bSig ); qTemp = ( 2 < qTemp ) ? qTemp - 2 : 0; qTemp >>= 64 - expDiff; mul64To128( bSig, qTemp<<( 64 - expDiff ), &term0, &term1 ); sub128( aSig0, aSig1, term0, term1, &aSig0, &aSig1 ); shortShift128Left( 0, bSig, 64 - expDiff, &term0, &term1 ); while ( le128( term0, term1, aSig0, aSig1 ) ) { ++qTemp; sub128( aSig0, aSig1, term0, term1, &aSig0, &aSig1 ); } *q += qTemp; } return normalizeRoundAndPackFloatx80(status->floatx80_rounding_precision, zSign, bExp + expDiff, aSig0, aSig1, status ); } #endif // end of addition for Previous /*---------------------------------------------------------------------------- | Returns the square root of the extended double-precision floating-point | value `a'. The operation is performed according to the IEC/IEEE Standard | for Binary Floating-Point Arithmetic. *----------------------------------------------------------------------------*/ floatx80 floatx80_sqrt(floatx80 a, float_status *status) { flag aSign; int32_t aExp, zExp; uint64_t aSig0, aSig1, zSig0, zSig1, doubleZSig0; uint64_t rem0, rem1, rem2, rem3, term0, term1, term2, term3; if (floatx80_invalid_encoding(a)) { float_raise(float_flag_invalid, status); return floatx80_default_nan(status); } aSig0 = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); aSign = extractFloatx80Sign( a ); if ( aExp == 0x7FFF ) { if ((uint64_t)(aSig0 << 1)) return propagateFloatx80NaNOneArg(a, status); if (!aSign) return inf_clear_intbit(status) ? packFloatx80(aSign, aExp, 0) : a; goto invalid; } if ( aSign ) { if ( ( aExp | aSig0 ) == 0 ) return a; invalid: float_raise(float_flag_invalid, status); return floatx80_default_nan(status); } if ( aExp == 0 ) { if ( aSig0 == 0 ) return packFloatx80( 0, 0, 0 ); normalizeFloatx80Subnormal( aSig0, &aExp, &aSig0 ); } zExp = ( ( aExp - 0x3FFF )>>1 ) + 0x3FFF; zSig0 = estimateSqrt32( aExp, aSig0>>32 ); shift128Right( aSig0, 0, 2 + ( aExp & 1 ), &aSig0, &aSig1 ); zSig0 = estimateDiv128To64( aSig0, aSig1, zSig0<<32 ) + ( zSig0<<30 ); doubleZSig0 = zSig0<<1; mul64To128( zSig0, zSig0, &term0, &term1 ); sub128( aSig0, aSig1, term0, term1, &rem0, &rem1 ); while ( (int64_t) rem0 < 0 ) { --zSig0; doubleZSig0 -= 2; add128( rem0, rem1, zSig0>>63, doubleZSig0 | 1, &rem0, &rem1 ); } zSig1 = estimateDiv128To64( rem1, 0, doubleZSig0 ); if ( ( zSig1 & LIT64( 0x3FFFFFFFFFFFFFFF ) ) <= 5 ) { if ( zSig1 == 0 ) zSig1 = 1; mul64To128( doubleZSig0, zSig1, &term1, &term2 ); sub128( rem1, 0, term1, term2, &rem1, &rem2 ); mul64To128( zSig1, zSig1, &term2, &term3 ); sub192( rem1, rem2, 0, 0, term2, term3, &rem1, &rem2, &rem3 ); while ( (int64_t) rem1 < 0 ) { --zSig1; shortShift128Left( 0, zSig1, 1, &term2, &term3 ); term3 |= 1; term2 |= doubleZSig0; add192( rem1, rem2, rem3, 0, term2, term3, &rem1, &rem2, &rem3 ); } zSig1 |= ( ( rem1 | rem2 | rem3 ) != 0 ); } shortShift128Left( 0, zSig1, 1, &zSig0, &zSig1 ); zSig0 |= doubleZSig0; return roundAndPackFloatx80(status->floatx80_rounding_precision, 0, zExp, zSig0, zSig1, status); } #ifdef SOFTFLOAT_68K // 07-01-2017: Added for Previous /*---------------------------------------------------------------------------- | Returns the mantissa of the extended double-precision floating-point | value `a'. *----------------------------------------------------------------------------*/ floatx80 floatx80_getman( floatx80 a, float_status *status) { flag aSign; int32_t aExp; uint64_t aSig; aSig = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); aSign = extractFloatx80Sign( a ); if ( aExp == 0x7FFF ) { if ( (uint64_t) ( aSig<<1 ) ) return propagateFloatx80NaNOneArg( a, status ); float_raise( float_flag_invalid, status ); return floatx80_default_nan(status); } if ( aExp == 0 ) { if ( aSig == 0 ) return packFloatx80( aSign, 0, 0 ); normalizeFloatx80Subnormal( aSig, &aExp, &aSig ); } return packFloatx80(aSign, 0x3fff, aSig); } /*---------------------------------------------------------------------------- | Returns the exponent of the extended double-precision floating-point | value `a' as an extended double-precision value. *----------------------------------------------------------------------------*/ floatx80 floatx80_getexp( floatx80 a, float_status *status) { flag aSign; int32_t aExp; uint64_t aSig; aSig = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); aSign = extractFloatx80Sign( a ); if ( aExp == 0x7FFF ) { if ( (uint64_t) ( aSig<<1 ) ) return propagateFloatx80NaNOneArg( a, status ); float_raise( float_flag_invalid, status ); return floatx80_default_nan(status); } if ( aExp == 0 ) { if ( aSig == 0 ) return packFloatx80( aSign, 0, 0 ); normalizeFloatx80Subnormal( aSig, &aExp, &aSig ); } return int32_to_floatx80(aExp - 0x3FFF); } /*---------------------------------------------------------------------------- | Scales extended double-precision floating-point value in operand `a' by | value `b'. The function truncates the value in the second operand 'b' to | an integral value and adds that value to the exponent of the operand 'a'. | The operation performed according to the IEC/IEEE Standard for Binary | Floating-Point Arithmetic. *----------------------------------------------------------------------------*/ floatx80 floatx80_scale(floatx80 a, floatx80 b, float_status *status) { flag aSign, bSign; int32_t aExp, bExp, shiftCount; uint64_t aSig, bSig; aSig = extractFloatx80Frac(a); aExp = extractFloatx80Exp(a); aSign = extractFloatx80Sign(a); bSig = extractFloatx80Frac(b); bExp = extractFloatx80Exp(b); bSign = extractFloatx80Sign(b); if ( bExp == 0x7FFF ) { if ( (uint64_t) ( bSig<<1 ) || ( ( aExp == 0x7FFF ) && (uint64_t) ( aSig<<1 ) ) ) { return propagateFloatx80NaN( a, b, status ); } float_raise( float_flag_invalid, status ); return floatx80_default_nan(status); } if ( aExp == 0x7FFF ) { if ( (uint64_t) ( aSig<<1 ) ) return propagateFloatx80NaN( a, b, status ); return a; } if ( aExp == 0 ) { if ( aSig == 0 ) return packFloatx80( aSign, 0, 0); if ( bExp < 0x3FFF ) return a; normalizeFloatx80Subnormal( aSig, &aExp, &aSig ); } if (bExp < 0x3FFF) { return roundAndPackFloatx80( status->floatx80_rounding_precision, aSign, aExp, aSig, 0, status); } if ( 0x400F < bExp ) { aExp = bSign ? -0x6001 : 0xE000; return roundAndPackFloatx80( status->floatx80_rounding_precision, aSign, aExp, aSig, 0, status ); } shiftCount = 0x403E - bExp; bSig >>= shiftCount; aExp = bSign ? ( aExp - bSig ) : ( aExp + bSig ); return roundAndPackFloatx80( status->floatx80_rounding_precision, aSign, aExp, aSig, 0, status); } /*----------------------------------------------------------------------------- | Calculates the absolute value of the extended double-precision floating-point | value `a'. The operation is performed according to the IEC/IEEE Standard | for Binary Floating-Point Arithmetic. *----------------------------------------------------------------------------*/ floatx80 floatx80_abs(floatx80 a, float_status *status) { int32_t aExp; uint64_t aSig; aSig = extractFloatx80Frac(a); aExp = extractFloatx80Exp(a); if ( aExp == 0x7FFF ) { if ( (uint64_t) ( aSig<<1 ) ) return propagateFloatx80NaNOneArg( a, status ); if (inf_clear_intbit(status)) aSig = 0; return packFloatx80(0, aExp, aSig); } if ( aExp == 0 ) { if ( aSig == 0 ) return packFloatx80( 0, 0, 0 ); normalizeFloatx80Subnormal( aSig, &aExp, &aSig ); } return roundAndPackFloatx80( status->floatx80_rounding_precision, 0, aExp, aSig, 0, status ); } /*----------------------------------------------------------------------------- | Changes the sign of the extended double-precision floating-point value 'a'. | The operation is performed according to the IEC/IEEE Standard for Binary | Floating-Point Arithmetic. *----------------------------------------------------------------------------*/ floatx80 floatx80_neg(floatx80 a, float_status *status) { flag aSign; int32_t aExp; uint64_t aSig; aSig = extractFloatx80Frac(a); aExp = extractFloatx80Exp(a); aSign = extractFloatx80Sign(a); if ( aExp == 0x7FFF ) { if ( (uint64_t) ( aSig<<1 ) ) return propagateFloatx80NaNOneArg( a, status ); if (inf_clear_intbit(status)) aSig = 0; return packFloatx80(!aSign, aExp, aSig); } aSign = !aSign; if ( aExp == 0 ) { if ( aSig == 0 ) return packFloatx80( aSign, 0, 0 ); normalizeFloatx80Subnormal( aSig, &aExp, &aSig ); } return roundAndPackFloatx80( status->floatx80_rounding_precision, aSign, aExp, aSig, 0, status ); } /*---------------------------------------------------------------------------- | Returns the result of comparing the extended double-precision floating- | point values `a' and `b'. The result is abstracted for matching the | corresponding condition codes. *----------------------------------------------------------------------------*/ floatx80 floatx80_cmp( floatx80 a, floatx80 b, float_status *status ) { flag aSign, bSign; int32_t aExp, bExp; uint64_t aSig, bSig; aSig = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); aSign = extractFloatx80Sign( a ); bSig = extractFloatx80Frac( b ); bExp = extractFloatx80Exp( b ); bSign = extractFloatx80Sign( b ); if ( ( aExp == 0x7FFF && (uint64_t) ( aSig<<1 ) ) || ( bExp == 0x7FFF && (uint64_t) ( bSig<<1 ) ) ) { // 68040 FCMP -NaN return N flag set if (fcmp_signed_nan(status)) return propagateFloatx80NaN(a, b, status ); return propagateFloatx80NaN(packFloatx80(0, aExp, aSig), packFloatx80(0, bExp, bSig), status); } if ( bExp < aExp ) return packFloatx80( aSign, 0x3FFF, LIT64( 0x8000000000000000 ) ); if ( aExp < bExp ) return packFloatx80( bSign ^ 1, 0x3FFF, LIT64( 0x8000000000000000 ) ); if ( aExp == 0x7FFF ) { if ( aSign == bSign ) return packFloatx80( aSign, 0, 0 ); return packFloatx80( aSign, 0x3FFF, LIT64( 0x8000000000000000 ) ); } if ( bSig < aSig ) return packFloatx80( aSign, 0x3FFF, LIT64( 0x8000000000000000 ) ); if ( aSig < bSig ) return packFloatx80( bSign ^ 1, 0x3FFF, LIT64( 0x8000000000000000 ) ); if ( aSig == 0 ) return packFloatx80( aSign, 0, 0 ); if ( aSign == bSign ) return packFloatx80( 0, 0, 0 ); return packFloatx80( aSign, 0x3FFF, LIT64( 0x8000000000000000 ) ); } floatx80 floatx80_tst( floatx80 a, float_status *status ) { int32_t aExp; uint64_t aSig; aSig = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); if ( aExp == 0x7FFF && (uint64_t) ( aSig<<1 ) ) return propagateFloatx80NaNOneArg( a, status ); return a; } floatx80 floatx80_move( floatx80 a, float_status *status ) { flag aSign; int32_t aExp; uint64_t aSig; aSig = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); aSign = extractFloatx80Sign( a ); if ( aExp == 0x7FFF ) { if ((uint64_t)(aSig << 1)) return propagateFloatx80NaNOneArg(a, status); return inf_clear_intbit(status) ? packFloatx80(aSign, aExp, 0) : a; } if ( aExp == 0 ) { if ( aSig == 0 ) return a; return normalizeRoundAndPackFloatx80( status->floatx80_rounding_precision, aSign, aExp, aSig, 0, status ); } return roundAndPackFloatx80( status->floatx80_rounding_precision, aSign, aExp, aSig, 0, status ); } floatx80 floatx80_denormalize( floatx80 a, flag eSign) { flag aSign; int32_t aExp; uint64_t aSig; int32_t shiftCount; aSig = extractFloatx80Frac( a ); aExp = extractFloatx80Exp( a ); aSign = extractFloatx80Sign( a ); if ( eSign ) { shiftCount = 0x8000 - aExp; aExp = 0; if (shiftCount > 63) { aSig = 0; } else { aSig >>= shiftCount; } } return packFloatx80(aSign, aExp, aSig); } #endif // End of addition for Previous /*---------------------------------------------------------------------------- | Returns 1 if the extended double-precision floating-point value `a' is | equal to the corresponding value `b', and 0 otherwise. The comparison is | performed according to the IEC/IEEE Standard for Binary Floating-Point | Arithmetic. *----------------------------------------------------------------------------*/ flag floatx80_eq( floatx80 a, floatx80 b, float_status *status ) { if ( ( ( extractFloatx80Exp( a ) == 0x7FFF ) && (uint64_t) ( extractFloatx80Frac( a )<<1 ) ) || ( ( extractFloatx80Exp( b ) == 0x7FFF ) && (uint64_t) ( extractFloatx80Frac( b )<<1 ) ) ) { if ( floatx80_is_signaling_nan( a ) || floatx80_is_signaling_nan( b ) ) { float_raise( float_flag_invalid, status ); } return 0; } return ( a.low == b.low ) && ( ( a.high == b.high ) || ( ( a.low == 0 ) && ( (uint16_t) ( ( a.high | b.high )<<1 ) == 0 ) ) ); } /*---------------------------------------------------------------------------- | Returns 1 if the extended double-precision floating-point value `a' is | less than or equal to the corresponding value `b', and 0 otherwise. The | comparison is performed according to the IEC/IEEE Standard for Binary | Floating-Point Arithmetic. *----------------------------------------------------------------------------*/ flag floatx80_le( floatx80 a, floatx80 b, float_status *status ) { flag aSign, bSign; if ( ( ( extractFloatx80Exp( a ) == 0x7FFF ) && (uint64_t) ( extractFloatx80Frac( a )<<1 ) ) || ( ( extractFloatx80Exp( b ) == 0x7FFF ) && (uint64_t) ( extractFloatx80Frac( b )<<1 ) ) ) { float_raise( float_flag_invalid, status ); return 0; } aSign = extractFloatx80Sign( a ); bSign = extractFloatx80Sign( b ); if ( aSign != bSign ) { return aSign || ( ( ( (uint16_t) ( ( a.high | b.high )<<1 ) ) | a.low | b.low ) == 0 ); } return aSign ? le128( b.high, b.low, a.high, a.low ) : le128( a.high, a.low, b.high, b.low ); } /*---------------------------------------------------------------------------- | Returns 1 if the extended double-precision floating-point value `a' is | less than the corresponding value `b', and 0 otherwise. The comparison | is performed according to the IEC/IEEE Standard for Binary Floating-Point | Arithmetic. *----------------------------------------------------------------------------*/ flag floatx80_lt( floatx80 a, floatx80 b, float_status *status ) { flag aSign, bSign; if ( ( ( extractFloatx80Exp( a ) == 0x7FFF ) && (uint64_t) ( extractFloatx80Frac( a )<<1 ) ) || ( ( extractFloatx80Exp( b ) == 0x7FFF ) && (uint64_t) ( extractFloatx80Frac( b )<<1 ) ) ) { float_raise( float_flag_invalid, status ); return 0; } aSign = extractFloatx80Sign( a ); bSign = extractFloatx80Sign( b ); if ( aSign != bSign ) { return aSign && ( ( ( (uint16_t) ( ( a.high | b.high )<<1 ) ) | a.low | b.low ) != 0 ); } return aSign ? lt128( b.high, b.low, a.high, a.low ) : lt128( a.high, a.low, b.high, b.low ); } /*---------------------------------------------------------------------------- | Returns the result of converting the 64-bit two's complement integer `a' | to the extended double-precision floating-point format. The conversion | is performed according to the IEC/IEEE Standard for Binary Floating-Point | Arithmetic. *----------------------------------------------------------------------------*/ floatx80 int64_to_floatx80( int64_t a ) { flag zSign; uint64_t absA; int8_t shiftCount; if ( a == 0 ) return packFloatx80( 0, 0, 0 ); zSign = ( a < 0 ); absA = zSign ? - a : a; shiftCount = countLeadingZeros64( absA ); return packFloatx80( zSign, 0x403E - shiftCount, absA<<shiftCount ); }
52,478
575
<gh_stars>100-1000 // Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SERVICES_DEVICE_BLUETOOTH_BLUETOOTH_SYSTEM_H_ #define SERVICES_DEVICE_BLUETOOTH_BLUETOOTH_SYSTEM_H_ #include <string> #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/optional.h" #include "dbus/object_path.h" #include "device/bluetooth/dbus/bluetooth_adapter_client.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/remote.h" #include "services/device/public/mojom/bluetooth_system.mojom.h" namespace bluez { class BluetoothAdapterClient; class BluetoothDeviceClient; } namespace device { class BluetoothSystem : public mojom::BluetoothSystem, public bluez::BluetoothAdapterClient::Observer { public: static void Create(mojo::PendingReceiver<mojom::BluetoothSystem> receiver, mojo::PendingRemote<mojom::BluetoothSystemClient> client); explicit BluetoothSystem( mojo::PendingRemote<mojom::BluetoothSystemClient> client); ~BluetoothSystem() override; // bluez::BluetoothAdapterClient::Observer void AdapterAdded(const dbus::ObjectPath& object_path) override; void AdapterRemoved(const dbus::ObjectPath& object_path) override; void AdapterPropertyChanged(const dbus::ObjectPath& object_path, const std::string& property_name) override; // mojom::BluetoothSystem void GetState(GetStateCallback callback) override; void SetPowered(bool powered, SetPoweredCallback callback) override; void GetScanState(GetScanStateCallback callback) override; void StartScan(StartScanCallback callback) override; void StopScan(StopScanCallback callback) override; void GetAvailableDevices(GetAvailableDevicesCallback callback) override; private: bluez::BluetoothAdapterClient* GetBluetoothAdapterClient(); bluez::BluetoothDeviceClient* GetBluetoothDeviceClient(); void UpdateStateAndNotifyIfNecessary(); ScanState GetScanStateFromActiveAdapter(); void OnSetPoweredFinished(SetPoweredCallback callback, bool succeeded); void OnStartDiscovery( StartScanCallback callback, const base::Optional<bluez::BluetoothAdapterClient::Error>& error); void OnStopDiscovery( StopScanCallback callback, const base::Optional<bluez::BluetoothAdapterClient::Error>& error); mojo::Remote<mojom::BluetoothSystemClient> client_; // The ObjectPath of the adapter being used. Updated as BT adapters are // added and removed. nullopt if there is no adapter. base::Optional<dbus::ObjectPath> active_adapter_; // State of |active_adapter_| or kUnavailable if there is no // |active_adapter_|. State state_ = State::kUnavailable; // Note: This should remain the last member so it'll be destroyed and // invalidate its weak pointers before any other members are destroyed. base::WeakPtrFactory<BluetoothSystem> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(BluetoothSystem); }; } // namespace device #endif // SERVICES_DEVICE_BLUETOOTH_BLUETOOTH_SYSTEM_H_
1,048
357
package com.vmware.identity.cdc; class HeartbeatInfoNative { String serviceName; int port; int lastHeartbeat; int isAlive; }
55
469
<gh_stars>100-1000 /* * math.h * * Author: * <NAME> (<EMAIL>) * * (C) Ximian, Inc. 2002 */ #ifndef __METADATA_SYSMATH_H__ #define __METADATA_SYSMATH_H__ #include <config.h> #include <glib.h> #include "mono/utils/mono-compiler.h" extern gdouble ves_icall_System_Math_Floor (gdouble x) MONO_INTERNAL; extern gdouble ves_icall_System_Math_Round (gdouble x) MONO_INTERNAL; extern gdouble ves_icall_System_Math_Round2 (gdouble value, gint32 digits, gboolean away_from_zero) MONO_INTERNAL; extern gdouble ves_icall_System_Math_Sin (gdouble x) MONO_INTERNAL; extern gdouble ves_icall_System_Math_Cos (gdouble x) MONO_INTERNAL; extern gdouble ves_icall_System_Math_Tan (gdouble x) MONO_INTERNAL; extern gdouble ves_icall_System_Math_Sinh (gdouble x) MONO_INTERNAL; extern gdouble ves_icall_System_Math_Cosh (gdouble x) MONO_INTERNAL; extern gdouble ves_icall_System_Math_Tanh (gdouble x) MONO_INTERNAL; extern gdouble ves_icall_System_Math_Acos (gdouble x) MONO_INTERNAL; extern gdouble ves_icall_System_Math_Asin (gdouble x) MONO_INTERNAL; extern gdouble ves_icall_System_Math_Atan (gdouble x) MONO_INTERNAL; extern gdouble ves_icall_System_Math_Atan2 (gdouble y, gdouble x) MONO_INTERNAL; extern gdouble ves_icall_System_Math_Exp (gdouble x) MONO_INTERNAL; extern gdouble ves_icall_System_Math_Log (gdouble x) MONO_INTERNAL; extern gdouble ves_icall_System_Math_Log10 (gdouble x) MONO_INTERNAL; extern gdouble ves_icall_System_Math_Pow (gdouble x, gdouble y) MONO_INTERNAL; extern gdouble ves_icall_System_Math_Sqrt (gdouble x) MONO_INTERNAL; #endif
690
339
/* *Copyright (c) 2005-2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * *WSO2 Inc. 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. */ package org.wso2.ei.businessprocess.integration.tests.humantasks; import org.apache.axis2.AxisFault; import org.apache.axis2.databinding.types.URI; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; import org.wso2.ei.businessprocess.integration.common.clients.humantasks.HumanTaskClientApiClient; import org.wso2.ei.businessprocess.integration.common.clients.humantasks.HumanTaskPackageManagementClient; import org.wso2.ei.businessprocess.integration.common.utils.BPSMasterTest; import org.wso2.ei.businessprocess.integration.common.utils.BPSTestConstants; import org.wso2.ei.businessprocess.integration.common.utils.RequestSender; import org.wso2.carbon.automation.engine.FrameworkConstants; import org.wso2.carbon.automation.engine.context.AutomationContext; import org.wso2.carbon.automation.engine.frameworkutils.FrameworkPathUtil; import org.wso2.carbon.humantask.stub.ui.task.client.api.types.*; import org.wso2.carbon.integration.common.admin.client.UserManagementClient; import org.wso2.carbon.integration.common.utils.LoginLogoutClient; import java.io.File; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; /** * This test case test followings scenarios. * - PeopleAssignment. * - Expression Based People Assignment. * - Literal Based People Assignment. * - Excluded Owner * - Xpath functions. * - Union * - Except * - intersect */ public class HumanTaskPeopleAssignment extends BPSMasterTest { private static final Log log = LogFactory.getLog(HumanTaskPeopleAssignment.class); //Test Automation API Clients private HumanTaskClientApiClient clerk1Client, clerk2Client, clerk3Client, clerk4Client, clerk5Client, clerk6Client, manager1Client, manager2Client, manager3Client; private HumanTaskPackageManagementClient humanTaskPackageManagementClient; private UserManagementClient userManagementClient; private RequestSender requestSender; private URI taskID = null; @BeforeClass(alwaysRun = true) public void setEnvironment() throws Exception { init(); //init master class humanTaskPackageManagementClient = new HumanTaskPackageManagementClient(backEndUrl, sessionCookie); requestSender = new RequestSender(); initialize(); //initialize HT Client API for Clerk1 user AutomationContext clerk1AutomationContext = new AutomationContext("BPS", "bpsServerInstance0001", FrameworkConstants.SUPER_TENANT_KEY, "clerk1"); LoginLogoutClient clerk1LoginLogoutClient = new LoginLogoutClient(clerk1AutomationContext); String clerk1SessionCookie = clerk1LoginLogoutClient.login(); clerk1Client = new HumanTaskClientApiClient(backEndUrl, clerk1SessionCookie); //initialize HT Client API for Clerk2 user AutomationContext clerk2AutomationContext = new AutomationContext("BPS", "bpsServerInstance0001", FrameworkConstants.SUPER_TENANT_KEY, "clerk2"); LoginLogoutClient clerk2LoginLogoutClient = new LoginLogoutClient(clerk2AutomationContext); String clerk2SessionCookie = clerk2LoginLogoutClient.login(); clerk2Client = new HumanTaskClientApiClient(backEndUrl, clerk2SessionCookie); //initialize HT Client API for Clerk3 user AutomationContext clerk3AutomationContext = new AutomationContext("BPS", "bpsServerInstance0001", FrameworkConstants.SUPER_TENANT_KEY, "clerk3"); LoginLogoutClient clerk3LoginLogoutClient = new LoginLogoutClient(clerk3AutomationContext); String clerk3SessionCookie = clerk3LoginLogoutClient.login(); clerk3Client = new HumanTaskClientApiClient(backEndUrl, clerk3SessionCookie); //initialize HT Client API for Clerk4 user AutomationContext clerk4AutomationContext = new AutomationContext("BPS", "bpsServerInstance0001", FrameworkConstants.SUPER_TENANT_KEY, "clerk4"); LoginLogoutClient clerk4LoginLogoutClient = new LoginLogoutClient(clerk4AutomationContext); String clerk4SessionCookie = clerk4LoginLogoutClient.login(); clerk4Client = new HumanTaskClientApiClient(backEndUrl, clerk4SessionCookie); //initialize HT Client API for Clerk5 user AutomationContext clerk5AutomationContext = new AutomationContext("BPS", "bpsServerInstance0001", FrameworkConstants.SUPER_TENANT_KEY, "clerk5"); LoginLogoutClient clerk5LoginLogoutClient = new LoginLogoutClient(clerk5AutomationContext); String clerk5SessionCookie = clerk5LoginLogoutClient.login(); clerk5Client = new HumanTaskClientApiClient(backEndUrl, clerk5SessionCookie); //initialize HT Client API for Clerk6 user AutomationContext clerk6AutomationContext = new AutomationContext("BPS", "bpsServerInstance0001", FrameworkConstants.SUPER_TENANT_KEY, "clerk6"); LoginLogoutClient clerk6LoginLogoutClient = new LoginLogoutClient(clerk6AutomationContext); String clerk6SessionCookie = clerk6LoginLogoutClient.login(); clerk6Client = new HumanTaskClientApiClient(backEndUrl, clerk6SessionCookie); //initialize HT Client API for Manager1 user AutomationContext manager1AutomationContext = new AutomationContext("BPS", "bpsServerInstance0001", FrameworkConstants.SUPER_TENANT_KEY, "manager1"); LoginLogoutClient manager1LoginLogoutClient = new LoginLogoutClient(manager1AutomationContext); String manager1SessionCookie = manager1LoginLogoutClient.login(); manager1Client = new HumanTaskClientApiClient(backEndUrl, manager1SessionCookie); //initialize HT Client API for Manager2 user AutomationContext manager2AutomationContext = new AutomationContext("BPS", "bpsServerInstance0001", FrameworkConstants.SUPER_TENANT_KEY, "manager2"); LoginLogoutClient manager2LoginLogoutClient = new LoginLogoutClient(manager2AutomationContext); String manager2SessionCookie = manager2LoginLogoutClient.login(); manager2Client = new HumanTaskClientApiClient(backEndUrl, manager2SessionCookie); //initialize HT Client API for Manager3 user AutomationContext manager3AutomationContext = new AutomationContext("BPS", "bpsServerInstance0001", FrameworkConstants.SUPER_TENANT_KEY, "manager3"); LoginLogoutClient manager3LoginLogoutClient = new LoginLogoutClient(manager3AutomationContext); String manager3SessionCookie = manager3LoginLogoutClient.login(); manager3Client = new HumanTaskClientApiClient(backEndUrl, manager3SessionCookie); } @BeforeGroups(groups = {"wso2.bps.task.people.assignment"}) protected void initialize() throws Exception { log.info("Initializing HumanTask task creation Test..."); userManagementClient = new UserManagementClient(backEndUrl, sessionCookie); addRoles(); humanTaskPackageManagementClient = new HumanTaskPackageManagementClient(backEndUrl, sessionCookie); log.info("Add users success !"); deployArtifact(); requestSender.waitForProcessDeployment(backEndUrl + HumanTaskTestConstants.CLAIM_SERVICE); } /** * deployArtifact() test1 sample Generic Human Roles. * potentialOwners - htd:getInput("ClaimApprovalRequest")/test10:cust/test10:owners * businessAdministrators - htd:union(htd:getInput("ClaimApprovalRequest")/test10:cust/test10:globleAdmins,htd:getInput("ClaimApprovalRequest")/test10:cust/test10:regionalAdmins) * excludedOwners - htd:getInput("ClaimApprovalRequest")/test10:cust/test10:excludedOwners */ public void deployArtifact() throws Exception { final String artifactLocation = FrameworkPathUtil.getSystemResourceLocation() + BPSTestConstants.DIR_ARTIFACTS + File.separator + BPSTestConstants.DIR_HUMAN_TASK + File.separator + HumanTaskTestConstants.DIR_PEOPLE_ASSIGNMENT + File.separator + "test1"; uploadHumanTaskForTest(HumanTaskTestConstants.CLAIMS_APPROVAL_PACKAGE_ORG_ENTITY_NAME, artifactLocation); } private void addRoles() throws Exception { String[] rc1 = new String[]{HumanTaskTestConstants.CLERK1_USER, HumanTaskTestConstants.CLERK2_USER, HumanTaskTestConstants.CLERK3_USER}; String[] rc2 = new String[]{HumanTaskTestConstants.CLERK3_USER, HumanTaskTestConstants.CLERK4_USER, HumanTaskTestConstants.CLERK5_USER}; String[] rc3 = new String[]{HumanTaskTestConstants.CLERK4_USER, HumanTaskTestConstants.CLERK5_USER, HumanTaskTestConstants.CLERK6_USER}; String[] rm1 = new String[]{HumanTaskTestConstants.MANAGER1_USER, HumanTaskTestConstants.MANAGER2_USER}; String[] rm2 = new String[]{HumanTaskTestConstants.MANAGER2_USER, HumanTaskTestConstants.MANAGER3_USER}; userManagementClient.addRole(HumanTaskTestConstants.REGIONAL_CLERKS_ROLE, rc1, new String[]{"/permission/admin/login", "/permission/admin/manage/humantask/viewtasks"}, false); userManagementClient.addRole(HumanTaskTestConstants.REGIONAL_CLERKS_ROLE_2, rc2, new String[]{"/permission/admin/login", "/permission/admin/manage/humantask/viewtasks"}, false); userManagementClient.addRole(HumanTaskTestConstants.REGIONAL_CLERKS_ROLE_3, rc3, new String[]{"/permission/admin/login", "/permission/admin/manage/humantask/viewtasks"}, false); userManagementClient.addRole(HumanTaskTestConstants.REGIONAL_MANAGER_ROLE, rm1, new String[]{"/permission/admin/login", "/permission/admin/manage/humantask"}, false); userManagementClient.addRole(HumanTaskTestConstants.REGIONAL_MANAGER_ROLE_2, rm2, new String[]{"/permission/admin/login", "/permission/admin/manage/humantask"}, false); } @Test(groups = {"wso2.bps.task.createTask"}, description = "Create Task 1", priority = 1, singleThreaded = true) public void createTask() throws Exception { String soapBody = "<sch:ClaimApprovalData xmlns:sch=\"http://www.example.com/claims/schema\" xmlns:ns=\"http://docs.oasis-open.org/ns/bpel4people/ws-humantask/types/200803\">\n" + " <sch:cust>\n" + " <sch:id>123</sch:id>\n" + " <sch:firstname>Hasitha</sch:firstname>\n" + " <sch:lastname>Aravinda</sch:lastname>\n" + " <sch:owners>\n" + " <ns:group>" + HumanTaskTestConstants.REGIONAL_CLERKS_ROLE + "</ns:group>\n" + " </sch:owners>\n" + " <sch:excludedOwners>\n" + " <ns:user>" + HumanTaskTestConstants.CLERK3_USER + "</ns:user>\n" + " </sch:excludedOwners>\n" + " <sch:globleAdmins>\n" + " <ns:group>" + HumanTaskTestConstants.REGIONAL_MANAGER_ROLE + "</ns:group>\n" + " </sch:globleAdmins>\n" + " <sch:regionalAdmins>\n" + " <ns:group>" + HumanTaskTestConstants.REGIONAL_MANAGER_ROLE_2 + "</ns:group>\n" + " </sch:regionalAdmins>\n" + " </sch:cust>\n" + " <sch:amount>2500</sch:amount>\n" + " <sch:region>lk</sch:region>\n" + " <sch:priority>9</sch:priority>\n" + " </sch:ClaimApprovalData>"; String operation = "approve"; String serviceName = "ClaimService"; List<String> expectedOutput = new ArrayList<String>(); expectedOutput.add("taskid>"); log.info("Calling Service: " + backEndUrl + serviceName); requestSender.sendRequest(backEndUrl + serviceName, operation, soapBody, 1, expectedOutput, true); } @Test(groups = {"wso2.bps.task.createTask"}, description = "Check created Task", priority = 2, singleThreaded = true) public void checkCreatedTask() throws Exception { //Clerk1 can claim this task. TSimpleQueryInput queryInput = new TSimpleQueryInput(); queryInput.setPageNumber(0); queryInput.setSimpleQueryCategory(TSimpleQueryCategory.CLAIMABLE); //Query as Clerk1 user TTaskSimpleQueryResultSet taskResults = clerk1Client.simpleQuery(queryInput); TTaskSimpleQueryResultRow[] rows = taskResults.getRow(); Assert.assertNotNull(rows, "No tasks found. Task creation has failed. "); Assert.assertTrue(rows.length == 1, "There should be only one claimable task in the engine, but found " + rows.length + " tasks."); } @Test(groups = {"wso2.bps.task.claim"}, description = "Clerk1 claim task", priority = 3, singleThreaded = true) public void clerk1Claim() throws Exception { //Clerk1 can claim this task. TSimpleQueryInput queryInput = new TSimpleQueryInput(); queryInput.setPageNumber(0); queryInput.setSimpleQueryCategory(TSimpleQueryCategory.CLAIMABLE); //Query as Clerk1 user TTaskSimpleQueryResultSet taskResults = clerk1Client.simpleQuery(queryInput); TTaskSimpleQueryResultRow[] rows = taskResults.getRow(); TTaskSimpleQueryResultRow b4pTask = rows[0]; this.taskID = b4pTask.getId(); clerk1Client.claim(taskID); TTaskAbstract loadedTask = clerk1Client.loadTask(taskID); Assert.assertEquals(loadedTask.getActualOwner().getTUser(), HumanTaskTestConstants.CLERK1_USER, "The assignee should be clerk1 !"); Assert.assertEquals(loadedTask.getStatus().toString(), "RESERVED", "The task status should be RESERVED!"); } @Test(groups = {"wso2.bps.task.claim"}, description = "Clerk2 claim task which is RESERVED", priority = 4, singleThreaded = true, expectedExceptions = AxisFault.class) public void clerk2Claim() throws Exception { //Clerk2 can't claim this task since clerk1 already claimed it. //Claim As Clerk2 user clerk2Client.claim(this.taskID); } @Test(groups = {"wso2.bps.task.claim"}, description = "Clerk1 release task", priority = 5, singleThreaded = true) public void clerk1Release() throws Exception { //Release As Clerk1 user clerk1Client.release(this.taskID); TTaskAbstract loadedTask = clerk1Client.loadTask(taskID); Assert.assertNull(loadedTask.getActualOwner(), "Task has an actual owner. Task Release failed"); Assert.assertEquals(loadedTask.getStatus().toString(), "READY", "The task status should be READY!"); } @Test(groups = {"wso2.bps.task.claim"}, description = "Clerk2 re-claim task and release", priority = 6, singleThreaded = true) public void clerk2ReClaimAndRelease() throws Exception { //Login As Clerk2 user clerk2Client.claim(this.taskID); TTaskAbstract loadedTask = clerk2Client.loadTask(taskID); Assert.assertEquals(loadedTask.getActualOwner().getTUser(), HumanTaskTestConstants.CLERK2_USER, "The assignee should be clerk2 !"); Assert.assertEquals(loadedTask.getStatus().toString(), "RESERVED", "The task status should be RESERVED!"); clerk2Client.release(this.taskID); loadedTask = clerk2Client.loadTask(taskID); Assert.assertNull(loadedTask.getActualOwner(), "Task has an actual owner. Task Release failed"); Assert.assertEquals(loadedTask.getStatus().toString(), "READY", "The task status should be READY!"); } @Test(groups = {"wso2.bps.task.claim"}, description = "Clerk3 (an excluded owner) try to claim", priority = 7, singleThreaded = true, expectedExceptions = AxisFault.class) public void clerk3Claim() throws Exception { //Login As Clerk3 user clerk3Client.claim(this.taskID); } @Test(groups = { "wso2.bps.task.xpath" }, description = "Test Xpath operation -Union", priority = 10, singleThreaded = true) public void testUnion() throws Exception { // All 3 manager users should able to perform administrative task. //Login As manager1 user TPriority tPriority = new TPriority(); tPriority.setTPriority(BigInteger.valueOf(2)); manager1Client.setPriority(taskID, tPriority); TTaskAbstract taskAfterPriorityChange1 = manager1Client.loadTask(taskID); TPriority prio1 = taskAfterPriorityChange1.getPriority(); int newPriority1Int = prio1.getTPriority().intValue(); Assert.assertEquals(newPriority1Int, 2, "The new priority should be 2 after the set priority operation"); //Login As manager3 user tPriority = new TPriority(); tPriority.setTPriority(BigInteger.valueOf(3)); manager3Client.setPriority(taskID, tPriority); taskAfterPriorityChange1 = manager3Client.loadTask(taskID); TPriority prio2 = taskAfterPriorityChange1.getPriority(); int newPriority1Int2 = prio2.getTPriority().intValue(); Assert.assertEquals(newPriority1Int2, 3, "The new priority should be 3 after the set priority operation"); } /** * deployArtifact() test2 artifact. Sample Generic Human Roles. * potentialOwners - htd:getInput("ClaimApprovalRequest")/test10:cust/test10:owners * businessAdministrators - htd:except(htd:getInput("ClaimApprovalRequest")/test10:cust/test10:globleAdmins,htd:getInput("ClaimApprovalRequest")/test10:cust/test10:regionalAdmins) * excludedOwners - htd:getInput("ClaimApprovalRequest")/test10:cust/test10:excludedOwners */ @Test(groups = { "wso2.bps.task.xpath" }, description = "Deploy and Create Except HumanTask", priority = 20, singleThreaded = true) public void deployAndCreateExceptHumanTask() throws Exception { final String artifactLocation = FrameworkPathUtil.getSystemResourceLocation() + BPSTestConstants.DIR_ARTIFACTS + File.separator + BPSTestConstants.DIR_HUMAN_TASK + File.separator + HumanTaskTestConstants.DIR_PEOPLE_ASSIGNMENT + File.separator + "test2"; uploadHumanTaskForTest(HumanTaskTestConstants.CLAIMS_APPROVAL_PACKAGE_ORG_ENTITY_NAME, artifactLocation); Thread.sleep(30000); // Wait for new version of task deploy. createTask(); // create task TSimpleQueryInput queryInput = new TSimpleQueryInput(); queryInput.setPageNumber(0); queryInput.setSimpleQueryCategory(TSimpleQueryCategory.ALL_TASKS); //Login As Clerk1 user TTaskSimpleQueryResultSet taskResults = clerk1Client.simpleQuery(queryInput); TTaskSimpleQueryResultRow[] rows = taskResults.getRow(); TTaskSimpleQueryResultRow b4pTask = null; Assert.assertNotNull(rows, "No tasks found. Task creation has failed. "); // looking for the latest task for (TTaskSimpleQueryResultRow row : rows) { if (b4pTask == null) { b4pTask = row; } else { if (Long.parseLong(b4pTask.getId().toString()) < Long.parseLong(row.getId().toString())) { b4pTask = row; } } } // Validating Task Assert.assertNotNull(b4pTask, "Task creation has failed"); Assert.assertNotEquals(b4pTask.getId().toString(), this.taskID.toString(), "Task creation failed."); this.taskID = b4pTask.getId(); } @Test(groups = {"wso2.bps.task.xpath" }, description = "Test Xpath operation -Except", priority = 21, singleThreaded = true) public void testExcept() throws Exception { // Only Manager1 able to change the priority. final int newPriority = 7; TPriority tPriority = new TPriority(); TTaskAbstract taskAfterPriorityChange1; tPriority.setTPriority(BigInteger.valueOf(newPriority)); //Login As manager3 user manager1Client.setPriority(taskID, tPriority); taskAfterPriorityChange1 = manager1Client.loadTask(taskID); TPriority prio2 = taskAfterPriorityChange1.getPriority(); int newPriority1Int2 = prio2.getTPriority().intValue(); Assert.assertEquals(newPriority1Int2, newPriority, "The new priority should change after setPriority operation."); } @Test(groups = { "wso2.bps.task.xpath" }, description = "Test Xpath operation - Except negative case", priority = 21, singleThreaded = true, expectedExceptions = AxisFault.class) public void testExceptNegative() throws Exception { // Only Manager1 able to change the priority. final int newPriority = 8; TPriority tPriority = new TPriority(); TTaskAbstract taskAfterPriorityChange1; tPriority.setTPriority(BigInteger.valueOf(newPriority)); //Login As manager3 user manager3Client.setPriority(taskID, tPriority); taskAfterPriorityChange1 = manager3Client.loadTask(taskID); TPriority prio2 = taskAfterPriorityChange1.getPriority(); int newPriority1Int2 = prio2.getTPriority().intValue(); Assert.assertNotEquals(newPriority1Int2, newPriority, "Task priority should not changed."); } /** * deployArtifact() test3 artifact. Sample Generic Human Roles. * potentialOwners - htd:getInput("ClaimApprovalRequest")/test10:cust/test10:owners * businessAdministrators - htd:intersect(htd:getInput("ClaimApprovalRequest")/test10:cust/test10:globleAdmins,htd:getInput("ClaimApprovalRequest")/test10:cust/test10:regionalAdmins) * excludedOwners - htd:getInput("ClaimApprovalRequest")/test10:cust/test10:excludedOwners */ @Test(groups = { "wso2.bps.task.xpath" }, description = "Deploy and Create Except HumanTask", priority = 30, singleThreaded = true) public void deployAndCreateIntersectHumanTask() throws Exception { final String artifactLocation = FrameworkPathUtil.getSystemResourceLocation() + BPSTestConstants.DIR_ARTIFACTS + File.separator + BPSTestConstants.DIR_HUMAN_TASK + File.separator + HumanTaskTestConstants.DIR_PEOPLE_ASSIGNMENT + File.separator + "test3"; uploadHumanTaskForTest(HumanTaskTestConstants.CLAIMS_APPROVAL_PACKAGE_ORG_ENTITY_NAME, artifactLocation); Thread.sleep(30000); // Wait for new version of task deploy. createTask(); // create task TSimpleQueryInput queryInput = new TSimpleQueryInput(); queryInput.setPageNumber(0); queryInput.setSimpleQueryCategory(TSimpleQueryCategory.ALL_TASKS); //Login As Clerk1 user TTaskSimpleQueryResultSet taskResults = clerk1Client.simpleQuery(queryInput); TTaskSimpleQueryResultRow[] rows = taskResults.getRow(); TTaskSimpleQueryResultRow b4pTask = null; Assert.assertNotNull(rows, "No tasks found. Task creation has failed. "); // looking for the latest task for (TTaskSimpleQueryResultRow row : rows) { if (b4pTask == null) { b4pTask = row; } else { if (Long.parseLong(b4pTask.getId().toString()) < Long.parseLong(row.getId().toString())) { b4pTask = row; } } } // Validating Task Assert.assertNotNull(b4pTask, "Task creation has failed"); Assert.assertNotEquals(b4pTask.getId().toString(), this.taskID.toString(), "Task creation failed."); this.taskID = b4pTask.getId(); } @Test(groups = { "wso2.bps.task.xpath" }, description = "Test Xpath operation - Intersect", priority = 31, singleThreaded = true) public void testIntersect() throws Exception { // Only Manager 2 able to change the priority. final int newPriority = 8; TPriority tPriority = new TPriority(); TTaskAbstract taskAfterPriorityChange1; tPriority.setTPriority(BigInteger.valueOf(newPriority)); //Login As manager2 user manager2Client.setPriority(taskID, tPriority); taskAfterPriorityChange1 = manager2Client.loadTask(taskID); TPriority prio2 = taskAfterPriorityChange1.getPriority(); int newPriority1Int2 = prio2.getTPriority().intValue(); Assert.assertEquals(newPriority1Int2, newPriority, "The new priority should change after setPriority operation."); } @Test(groups = { "wso2.bps.task.xpath" }, description = "Test Xpath operation - Intersect Negative test case", priority = 32, singleThreaded = true, expectedExceptions = AxisFault.class) public void testIntersectNegative() throws Exception { // Only Manager1 able to change the priority. final int newPriority = 7; TPriority tPriority = new TPriority(); TTaskAbstract taskAfterPriorityChange1; tPriority.setTPriority(BigInteger.valueOf(newPriority)); //Login As manager3 user manager3Client.setPriority(taskID, tPriority); taskAfterPriorityChange1 = manager3Client.loadTask(taskID); TPriority prio2 = taskAfterPriorityChange1.getPriority(); int newPriority1Int2 = prio2.getTPriority().intValue(); Assert.assertNotEquals(newPriority1Int2, newPriority, "Task priority should not changed."); } /** * deployArtifact() test4 artifact. * Potential owners : * <htt:user>clerk1</htt:user> * <htt:user>clerk2</htt:user> * <htt:user>clerk3</htt:user> * <htt:group>regionalClerksRole2</htt:group> */ @Test(groups = { "wso2.bps.task.literal" }, description = "Deploy and Create Literal based HumanTask", priority = 40, singleThreaded = true) public void deployAndCreateLiteralBasedHumanTask() throws Exception { final String artifactLocation = FrameworkPathUtil.getSystemResourceLocation() + BPSTestConstants.DIR_ARTIFACTS + File.separator + BPSTestConstants.DIR_HUMAN_TASK + File.separator + HumanTaskTestConstants.DIR_PEOPLE_ASSIGNMENT + File.separator + "test4"; uploadHumanTaskForTest(HumanTaskTestConstants.CLAIMS_APPROVAL_PACKAGE_ORG_ENTITY_NAME, artifactLocation); Thread.sleep(30000); // Wait for new version of task deploy. createTask(); // create task TSimpleQueryInput queryInput = new TSimpleQueryInput(); queryInput.setPageNumber(0); queryInput.setSimpleQueryCategory(TSimpleQueryCategory.ALL_TASKS); //Login As Clerk1 user TTaskSimpleQueryResultSet taskResults = clerk1Client.simpleQuery(queryInput); TTaskSimpleQueryResultRow[] rows = taskResults.getRow(); TTaskSimpleQueryResultRow b4pTask = null; Assert.assertNotNull(rows, "No tasks found. Task creation has failed. "); // looking for the latest task for (TTaskSimpleQueryResultRow row : rows) { if (b4pTask == null) { b4pTask = row; } else { if (Long.parseLong(b4pTask.getId().toString()) < Long.parseLong(row.getId().toString())) { b4pTask = row; } } } // Validating Task Assert.assertNotNull(b4pTask, "Task creation has failed"); Assert.assertNotEquals(b4pTask.getId().toString(), this.taskID.toString(), "Task creation failed."); this.taskID = b4pTask.getId(); } @Test(groups = { "wso2.bps.task.literal" }, description = "Perform humanTask", priority = 41, singleThreaded = true, expectedExceptions = AxisFault.class) public void testLiteralBasedPeopleAssignment() throws Exception { // clerk1, clerk2, clerk4, clerk5 users will able to work on task. Clerk3 will be a excluded used. boolean failed = false; try { clerk1Client.start(taskID); clerk1Client.release(taskID); clerk2Client.start(taskID); clerk2Client.release(taskID); clerk4Client.start(taskID); clerk4Client.release(taskID); clerk5Client.start(taskID); clerk5Client.release(taskID); } catch (Exception e) { failed = true; } Assert.assertTrue(!failed, "Expected users can't perform task"); clerk6Client.start(taskID); } @Test(groups = { "wso2.bps.task.clean" }, description = "Clean up server", priority = 100, singleThreaded = true) public void cleanTestEnvironment() throws Exception { userManagementClient.deleteRole(HumanTaskTestConstants.REGIONAL_CLERKS_ROLE); userManagementClient.deleteRole(HumanTaskTestConstants.REGIONAL_CLERKS_ROLE_2); userManagementClient.deleteRole(HumanTaskTestConstants.REGIONAL_CLERKS_ROLE_3); userManagementClient.deleteRole(HumanTaskTestConstants.REGIONAL_MANAGER_ROLE); userManagementClient.deleteRole(HumanTaskTestConstants.REGIONAL_MANAGER_ROLE_2); Assert.assertFalse(userManagementClient.roleNameExists(HumanTaskTestConstants.REGIONAL_CLERKS_ROLE)); Assert.assertFalse(userManagementClient.roleNameExists(HumanTaskTestConstants.REGIONAL_CLERKS_ROLE_2)); Assert.assertFalse(userManagementClient.roleNameExists(HumanTaskTestConstants.REGIONAL_CLERKS_ROLE_3)); Assert.assertFalse(userManagementClient.roleNameExists(HumanTaskTestConstants.REGIONAL_MANAGER_ROLE)); Assert.assertFalse(userManagementClient.roleNameExists(HumanTaskTestConstants.REGIONAL_MANAGER_ROLE_2)); humanTaskPackageManagementClient.unDeployHumanTask(HumanTaskTestConstants.CLAIMS_APPROVAL_PACKAGE_ORG_ENTITY_NAME, "ApproveClaim"); loginLogoutClient.logout(); } }
9,634
368
/** * @author github.com/luncliff (<EMAIL>) */ #undef NDEBUG #include <cassert> #include <coroutine/yield.hpp> using namespace std; using namespace coro; auto yield_once(int value = 0) -> enumerable<int> { co_yield value; co_return; }; int main(int, char*[]) { auto count = 0u; auto g = yield_once(); auto m = move(g); // g lost its handle. so it is not iterable anymore assert(g.begin() == g.end()); for (auto v : g) { v = count; // code to suppress C4189 return __LINE__; // null generator won't go into loop } for (auto v : m) { assert(v == 0); count += 1; } assert(count > 0); return EXIT_SUCCESS; }
307
938
package slimeknights.tconstruct.library.book.elements; import slimeknights.mantle.client.book.data.element.TextData; /** @deprecated use {@link slimeknights.mantle.client.screen.book.element.ListingLeftElement} */ @Deprecated public class ListingLeftElement extends slimeknights.mantle.client.screen.book.element.ListingLeftElement { public ListingLeftElement(int x, int y, int width, int height, boolean subSection, TextData... text) { super(x, y, width, height, subSection, text); } }
154
8,747
/* * SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD * * SPDX-License-Identifier: Apache-2.0 */ #include "soc/compare_set.h" #include "soc/spinlock.h" #include "soc/soc_caps.h" #if __XTENSA__ && SOC_SPIRAM_SUPPORTED static spinlock_t global_extram_lock = SPINLOCK_INITIALIZER; void compare_and_set_extram(volatile uint32_t *addr, uint32_t compare, uint32_t *set) { uint32_t intlevel, old_value; __asm__ __volatile__ ("rsil %0, " XTSTR(XCHAL_EXCM_LEVEL) "\n" : "=r"(intlevel)); spinlock_acquire(&global_extram_lock, SPINLOCK_WAIT_FOREVER); old_value = *addr; if (old_value == compare) { *addr = *set; } spinlock_release(&global_extram_lock); __asm__ __volatile__ ("memw \n" "wsr %0, ps\n" :: "r"(intlevel)); *set = old_value; } #else // __XTENSA__ && SOC_SPIRAM_SUPPORTED void compare_and_set_extram(volatile uint32_t *addr, uint32_t compare, uint32_t *set) { compare_and_set_native(addr, compare, set); } #endif // endif
464
310
<reponame>dreeves/usesthis { "name": "Android", "description": "A mobile phone platform.", "url": "https://developers.google.com/android/?csw=1" }
57
540
# ***************************************************************************** # Copyright (c) 2019-2021, Intel Corporation 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. # # 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. # ***************************************************************************** import argparse import os import shutil import traceback import re from pathlib import Path from utilities import SDC_Build_Utilities def check_sdc_installed(sdc_utils, sdc_package): cmd_output = sdc_utils.get_command_output('conda list sdc') pattern = sdc_package.replace('=', r'\s+') return re.search(pattern, cmd_output) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--python', default='3.7', choices=['3.6', '3.7', '3.8'], help='Python version, default = 3.7') parser.add_argument('--channels', default=None, help='Default env channels') parser.add_argument('--sdc-channel', default=None, help='Intel SDC channel') args = parser.parse_args() sdc_utils = SDC_Build_Utilities(args.python, args.channels, args.sdc_channel) sdc_utils.log_info('Test Intel(R) SDC conda install', separate=True) sdc_utils.log_info(sdc_utils.line_double) sdc_utils.create_environment() sdc_package = f'sdc={sdc_utils.get_sdc_version_from_channel()}' # channels list is aligned with install instruction in README.rst install_channels = "-c intel/label/beta -c intel -c defaults -c conda-forge" sdc_utils.install_conda_package([sdc_package], channels=install_channels) assert check_sdc_installed(sdc_utils, sdc_package), "SDC package was not installed"
916
647
#include "trick/env_proto.h"
14
448
// C++ program to find the diameter of a Binary Tree #include <bits/stdc++.h> using namespace std; struct node { int data; struct node *left, *right; }; struct node* newNode(int data); int diameterOpt(struct node* root, int* height) { int lh = 0, rh = 0; int ldiameter = 0, rdiameter = 0; if (root == NULL) { *height = 0; return 0; } ldiameter = diameterOpt(root->left, &lh); rdiameter = diameterOpt(root->right, &rh); *height = max(lh, rh) + 1; return max(lh + rh + 1, max(ldiameter, rdiameter)); } struct node* newNode(int data) { struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return (node); } // Driver Code int main() { struct node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); int height = 0; cout << "Diameter of the given binary tree is " << diameterOpt(root, &height); return 0; }
383
679
<filename>main/vcl/inc/vcl/gradient.hxx /************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef _SV_GRADIENT_HXX #define _SV_GRADIENT_HXX #include <vcl/dllapi.h> #include <tools/color.hxx> #include <vcl/vclenum.hxx> // ------------------ // - Gradient-Types - // ------------------ /* #ifndef ENUM_GRADIENTSTYLE_DECLARED #define ENUM_GRADIENTSTYLE_DECLARED enum GradientStyle { GRADIENT_LINEAR, GRADIENT_AXIAL, GRADIENT_RADIAL, GRADIENT_ELLIPTICAL, GRADIENT_SQUARE, GRADIENT_RECT }; #endif */ // ---------------- // - Impl_Gradient - // ---------------- class SvStream; class Impl_Gradient { public: sal_uLong mnRefCount; GradientStyle meStyle; Color maStartColor; Color maEndColor; sal_uInt16 mnAngle; sal_uInt16 mnBorder; sal_uInt16 mnOfsX; sal_uInt16 mnOfsY; sal_uInt16 mnIntensityStart; sal_uInt16 mnIntensityEnd; sal_uInt16 mnStepCount; friend SvStream& operator>>( SvStream& rIStm, Impl_Gradient& rImplGradient ); friend SvStream& operator<<( SvStream& rOStm, const Impl_Gradient& rImplGradient ); Impl_Gradient(); Impl_Gradient( const Impl_Gradient& rImplGradient ); }; // ------------ // - Gradient - // ------------ class VCL_DLLPUBLIC Gradient { private: Impl_Gradient* mpImplGradient; void MakeUnique(); public: Gradient(); Gradient( const Gradient& rGradient ); Gradient( GradientStyle eStyle ); Gradient( GradientStyle eStyle, const Color& rStartColor, const Color& rEndColor ); ~Gradient(); void SetStyle( GradientStyle eStyle ); GradientStyle GetStyle() const { return mpImplGradient->meStyle; } void SetStartColor( const Color& rColor ); const Color& GetStartColor() const { return mpImplGradient->maStartColor; } void SetEndColor( const Color& rColor ); const Color& GetEndColor() const { return mpImplGradient->maEndColor; } void SetAngle( sal_uInt16 nAngle ); sal_uInt16 GetAngle() const { return mpImplGradient->mnAngle; } void SetBorder( sal_uInt16 nBorder ); sal_uInt16 GetBorder() const { return mpImplGradient->mnBorder; } void SetOfsX( sal_uInt16 nOfsX ); sal_uInt16 GetOfsX() const { return mpImplGradient->mnOfsX; } void SetOfsY( sal_uInt16 nOfsY ); sal_uInt16 GetOfsY() const { return mpImplGradient->mnOfsY; } void SetStartIntensity( sal_uInt16 nIntens ); sal_uInt16 GetStartIntensity() const { return mpImplGradient->mnIntensityStart; } void SetEndIntensity( sal_uInt16 nIntens ); sal_uInt16 GetEndIntensity() const { return mpImplGradient->mnIntensityEnd; } void SetSteps( sal_uInt16 nSteps ); sal_uInt16 GetSteps() const { return mpImplGradient->mnStepCount; } Gradient& operator=( const Gradient& rGradient ); sal_Bool operator==( const Gradient& rGradient ) const; sal_Bool operator!=( const Gradient& rGradient ) const { return !(Gradient::operator==( rGradient )); } sal_Bool IsSameInstance( const Gradient& rGradient ) const { return (mpImplGradient == rGradient.mpImplGradient); } friend VCL_DLLPUBLIC SvStream& operator>>( SvStream& rIStm, Gradient& rGradient ); friend VCL_DLLPUBLIC SvStream& operator<<( SvStream& rOStm, const Gradient& rGradient ); }; #endif // _SV_GRADIENT_HXX
1,991
317
<reponame>dinisAbranches/nwchem #ifndef _PAW_ERROR_FUNCTION_H_ #define _PAW_ERROR_FUNCTION_H_ /* $Id$ */ extern double paw_my_erf(double x); #endif
77
463
<reponame>rachfop/redpen package cc.redpen.util; import java.util.function.Predicate; import static java.lang.Math.min; public class LanguageDetector { public String detectLanguage(String text) { if (has(text, StringUtils::isProbablyJapanese)) { boolean zenkaku = text.indexOf('。') >= 0 || text.indexOf('、') >= 0 || text.indexOf('!') >= 0 || text.indexOf('?') >= 0; boolean zenkaku2 = text.indexOf('.') >= 0 || text.indexOf(',') >= 0; boolean hankaku = text.indexOf('.') >= 0 || text.indexOf(',') >= 0 || text.indexOf('!') >= 0 || text.indexOf('?') >= 0; return zenkaku ? "ja" : zenkaku2 ? "ja.zenkaku2" : hankaku ? "ja.hankaku": "ja"; } else if (has(text, StringUtils::isCyrillic)) { return "ru"; } else if (has(text, StringUtils::isKorean)) { return "ko"; } return "en"; } private boolean has(String text, Predicate<Character> func) { char[] chars = text.toCharArray(); for (int i = 0; i < min(chars.length, 100); i++) { char c = chars[i]; if (func.test(c)) return true; } return false; } }
484
481
package com.tarek360.sample; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.util.Base64; import android.view.View; import android.widget.ImageView; import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher; import java.io.ByteArrayOutputStream; /** * Created by tarek on 5/25/17. */ public class ScreenshotMatcher extends TypeSafeMatcher<View> { private final static String NOT_EMPTY = "not_empty"; private final String expectedBase64; private String textDescription; public ScreenshotMatcher() { this(NOT_EMPTY); } public ScreenshotMatcher(String expectedBase64) { super(View.class); this.expectedBase64 = expectedBase64; } @Override protected boolean matchesSafely(View target) { if (!(target instanceof ImageView)) { return false; } ImageView imageView = (ImageView) target; if (expectedBase64 == null) { textDescription = "the expectedBase64 is null"; return false; } if (expectedBase64.equals(NOT_EMPTY)) { if (imageView.getDrawable() != null) { textDescription = "imageView has a drawable"; return true; } else { textDescription = "imageView hasn't drawable"; return false; } } BitmapDrawable bitmapDrawable = (BitmapDrawable) imageView.getDrawable(); if (bitmapDrawable == null) { textDescription = "imageView hasn't drawable"; return false; } Bitmap bitmap = bitmapDrawable.getBitmap(); if (bitmap == null) { textDescription = "bitmapDrawable .getBitmap() return null"; return false; } ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos); byte[] bytes = bos.toByteArray(); String image = Base64.encodeToString(bytes, Base64.DEFAULT); if (image.equals(expectedBase64)) { textDescription = "expectedBase64 match the imageView drawable"; return true; } else { textDescription = "expectedBase64 doesn't match the imageView drawable"; return false; } } @Override public void describeTo(Description description) { description.appendText(textDescription); } }
1,030
704
/* * Copyright (c) 2013 <NAME> * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source * distribution. */ #ifndef FTL_BASIC_CONCEPTS_H #define FTL_BASIC_CONCEPTS_H #include <type_traits> namespace ftl { /** * \defgroup concepts_basic Basic Concepts * * Module containg definitions and checks for various basic concepts. * * \code * #include <ftl/concepts/basic.h> * \endcode * * \par Dependencies * - `<type_traits>` */ /** * \page defcons DefaultConstructible * * Any type that has a default constructor. * * This includes types that have an implicit default constructor (by either * not declaring any of the standard constructors, or declaring it as * `default`). * * More formally, the expressions * - `T t;` * - `T t{};` * - `T{}` * - `T()` * * must all be valid and behave as expected. Which is to say, they should * construct an instance of `T` with whatever default semantics are * appropriate. */ /** * Predicate to check if a type is \ref defcons. * * \par Examples * * Using explicit `value` check: * \code * template<typename T> * void foo() { * static_assert( * DefaultConstructible<T>::value, * "foo: T is not an instance of DefaultConstructible" * ); * * // Construct Ts using its default c-tor * } * \endcode * * Using implicit bool conversion: * \code * template<typename T> * void foo() { * static_assert( * DefaultConstructible<T>{}, * "foo: T is not an instance of DefaultConstructible" * ); * * // Construct Ts using its default c-tor * } * \endcode * * \ingroup concepts_basic */ template<typename T> struct DefaultConstructible { static constexpr bool value = std::is_default_constructible<T>::value; constexpr operator bool() const noexcept { return value; } }; /** * \page movecons MoveConstructible * * Any type that has a move constructor. * * This includes types that have an implicit move constructor (by either not * declaring any of the standard constructors, or declaring it as * `default`). * * More formally, the expressions * - `T t = rv;` * - `T(rv);` * * where `rv` is an rvalue reference of `T` must both be valid and behave * as expected. */ /** * Predicate to check if a type is \ref movecons. * * \par Examples * * Using explicit `value` member and SFINAE: * \code * template<typename T, typename = Requires<MoveConstructible<T>::value>> * void foo() { * // Consturct Ts using the move c-tor * } * \endcode * * Using implicit bool conversion: * \code * template<typename T> * void foo() { * static_assert( * MoveConstructible<T>{}, * "foo: T is not an instance of MoveConstructible" * ); * * // Construct Ts using its move c-tor * } * \endcode * * \ingroup concepts_basic */ template<typename T> struct MoveConstructible { static constexpr bool value = std::is_move_constructible<T>::value; constexpr operator bool() const noexcept { return value; } }; /** * \page copycons CopyConstructible * * Any type that has a copy constructor. * * This includes types that have an implicit copy constructor (by either not * declaring any of the standard constructors, or declaring it as * `default`). * * More formally, the expressions * - `T t = v;` * - `T(v);` * * where `v` is an instance of `T` must both be valid and result in objects * that are equivalent of `v`, while leaving it completely unmodified. */ /** * Predicate to check if a type is \ref copycons. * * \par Examples * * Using explicit `value` member and SFINAE: * \code * template<typename T, typename = Requires<CopyConstructible<T>::value>> * void foo() { * // Consturct Ts using the copy c-tor * } * \endcode * * Using implicit bool conversion: * \code * template<typename T> * void foo() { * static_assert( * CopyConstructible<T>{}, * "foo: T is not an instance of CopyConstructible" * ); * * // Construct Ts using its copy c-tor * } * \endcode * * * \ingroup concepts_basic */ template<typename T> struct CopyConstructible { static constexpr bool value = std::is_copy_constructible<T>::value; constexpr operator bool() const noexcept { return value; } }; /** * \page moveassignable MoveAssignable * * Types that can be move assigned to. * * Requires that the expression * - `a = rv;` * * where `rv` is an rvalue reference of `T` is valid. After the operation, * `a` must be equivalent of whatever `rv` was _before_ it. `rv` may be * changed by the operation. */ /** * Predicate to check if a type is \ref moveassignable. * * \par Examples * * Using implicit bool conversion: * \code * template<typename T> * void foo() { * static_assert( * MoveAssignable<T>{}, * "foo: T is not an instance of MoveAssignable" * ); * * // Assign rvalues to Ts * } * \endcode * * Using explicit `value`: * \code * template<typename T> * void foo() { * static_assert( * MoveAssignable<T>::value, * "foo: T is not an instance of MoveAssignable" * ); * * // Assign rvalues to Ts * } * \endcode * * \ingroup concepts_basic */ template<typename T> struct MoveAssignable { static constexpr bool value = std::is_move_assignable<T>::value; constexpr operator bool() const noexcept { return value; } }; /** * \page copyassignable CopyAssignable * * Types that can be copy assigned to. * * Requires that the expression * - `a = v;` * * where `v` is an instance of `T` is valid. After the operation, `a` * must be equivalent of `v`, while leaving the latter completely * unmodified. */ /** * Predicate to check if a type is \ref copyassignable. * * \par Examples * * Using explicit `value` and SFINAE * \code * template<typename T, Requires<CopyAssignable<T>::value> * void foo() { * // Assign lvalues to Ts * } * \endcode * * Using implicit bool conversion: * \code * template<typename T> * void foo() { * static_assert( * CopyAssignable<T>{}, * "foo: T is not an instance of CopyAssignable" * ); * * // Assign lvalues to Ts * } * \endcode * * \ingroup concepts_basic */ template<typename T> struct CopyAssignable { static constexpr bool value = std::is_copy_assignable<T>::value; constexpr operator bool() const noexcept { return value; } }; /** * \page destructible Destructible * * Types that can be destructed. * * The expression * - `t.~T();` * * must be valid and result in all resources currently held exclusively by * `t` being freed. No exception must be thrown. Accessing members of `t` * after the destructor has been called may result in undefined or illegal * behaviour. */ /** * Predicate to check if a type is \ref destructible. * * \ingroup concepts_basic */ template<typename T> struct Destructible { static constexpr bool value = std::is_destructible<T>::value; constexpr operator bool() const noexcept { return value; } }; /** * Check that a compile-time predicate holds for an arbitrary list of types. * * \tparam Pred must contain a static, compile time member named `value`, of * type `bool` or one that is convertible to it. * * \par Examples * * Statically enforce Eq on a variadic type list: * \code * template<typename...Ts> * void example() { * static_assert(All<Eq,Ts...>{}, "All types in Ts must satisfy Eq"); * } * \endcode * * \ingroup concepts_basic */ template<template<typename> class Pred, typename...Ts> struct All; template<template<typename> class Pred> struct All<Pred> { static constexpr bool value = true; constexpr operator bool() const noexcept { return true; } }; template<template<typename> class Pred, typename T, typename...Ts> struct All<Pred, T, Ts...> { static constexpr bool value = Pred<T>::value && All<Pred,Ts...>::value; constexpr operator bool() const noexcept { return value; } }; } #endif
3,370
20,546
/* Copyright (c) 2013, <NAME>. All rights reserved. Licensed under the MIT license <http://opensource.org/licenses/MIT> 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. */ #import <Cocoa/Cocoa.h> #import "YMJNWCollectionViewCell.h" #import "YMJNWCollectionViewReusableView.h" #import "NSIndexPath+YMJNWAdditions.h" #if defined(COCOAPODS) #import <YMJNWScrollView/YMJNWScrollView.h> #else #import "YMJNWScrollView.h" #endif typedef NS_ENUM(NSInteger, YMJNWCollectionViewScrollPosition) { /// Does not scroll, only selects. YMJNWCollectionViewScrollPositionNone, /// Scrolls the minimum amount necessary to make visible. YMJNWCollectionViewScrollPositionNearest, /// Scrolls the rect to be at the top of the screen, if possible. YMJNWCollectionViewScrollPositionTop, /// Center the rect in the center of the screen, if possible. YMJNWCollectionViewScrollPositionMiddle, /// Scrolls the rect to be at the bottom of the screen, if possible. YMJNWCollectionViewScrollPositionBottom }; @class YMJNWCollectionView; #pragma mark - Data Source Protocol /// The data source is the protocol which defines a set of methods for both information about the data model /// and the views needed for creating the collection view. /// /// The object that conforms to the data source must implement both `-collectionView:numberOfItemsInSection:` /// and `-collectionView:cellForItemAtIndexPath:`, otherwise an exception will be thrown. @protocol YMJNWCollectionViewDataSource <NSObject> /// Asks the data source how many items are in the section index specified. The first section begins at 0. /// /// Required. - (NSUInteger)collectionView:(YMJNWCollectionView *)collectionView numberOfItemsInSection:(NSInteger)section; /// Asks the data source for the view that should be used for the cell at the specified index path. The returned /// view must be non-nil, and it must be a subclass of YMJNWCollectionViewCell, otherwise an exception will be thrown. /// /// Required. - (YMJNWCollectionViewCell *)collectionView:(YMJNWCollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath; @optional /// Asks the data source for the number of sections in the collection view. /// /// If this method is not implemented, the collection view will default to 1 section. - (NSInteger)numberOfSectionsInCollectionView:(YMJNWCollectionView *)collectionView; /// Asks the data source for the view used for the supplementary view for the specified section. The returned /// view must be a subclass of YMJNWCollectionViewReusableView, otherwise an exception will be thrown. /// /// Note that this data source method will *not* be called unless a class has been registered for a supplementary /// view kind. So if you wish to use supplementary views, you must register at least one class using /// -registerClass:forSupplementaryViewOfKind:withReuseIdentifier:. - (YMJNWCollectionViewReusableView *)collectionView:(YMJNWCollectionView *)collectionView viewForSupplementaryViewOfKind:(NSString *)kind inSection:(NSInteger)section; @end #pragma mark Delegate Protocol /// The delegate is the protocol which defines a set of methods with information about mouse clicks and selection. /// /// All delegate methods are optional. @protocol YMJNWCollectionViewDelegate <NSObject> @optional /// Tells the delegate that the mouse is down inside of the item at the specified index path with triggering event. - (void)collectionView:(YMJNWCollectionView *)collectionView mouseDownInItemAtIndexPath:(NSIndexPath *)indexPath withEvent:(NSEvent *)event; /// Tells the delegate that the mouse click originating from the item at the specified index path is now up with triggering event. /// /// The mouse up event can occur outside of the originating cell. - (void)collectionView:(YMJNWCollectionView *)collectionView mouseUpInItemAtIndexPath:(NSIndexPath *)indexPath withEvent:(NSEvent *)event; - (void)collectionView:(YMJNWCollectionView *)collectionView mouseDownInItemAtIndexPath:(NSIndexPath *)indexPath __deprecated_msg("Use collectionView:mouseDownInItemAtIndexPath:withEvent: instead."); - (void)collectionView:(YMJNWCollectionView *)collectionView mouseUpInItemAtIndexPath:(NSIndexPath *)indexPath __deprecated_msg("Use collectionView:mouseUpInItemAtIndexPath:withEvent: instead."); /// Tells the delegate that the mouse moved inside the specified index path cell. - (void)collectionView:(YMJNWCollectionView *)collectionView mouseMovedInItemAtIndexPath:(NSIndexPath *)indexPath withEvent:(NSEvent *)event; /// Tells the delegate that the mouse started a drag session inside the specified index path cell. - (void)collectionView:(YMJNWCollectionView *)collectionView mouseDraggedInItemAtIndexPath:(NSIndexPath *)indexPath withEvent:(NSEvent *)event; /// Tells the delegate that the mouse entered in the specified index path cell. - (void)collectionView:(YMJNWCollectionView *)collectionView mouseEnteredInItemAtIndexPath:(NSIndexPath *)indexPath withEvent:(NSEvent *)event; /// Tells the delegate that the mouse exited from the specified index path cell. - (void)collectionView:(YMJNWCollectionView *)collectionView mouseExitedInItemAtIndexPath:(NSIndexPath *)indexPath withEvent:(NSEvent *)event; /// Asks the delegate if the item at the specified index path should be selected. - (BOOL)collectionView:(YMJNWCollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath; /// Tells the delegate that the item at the specified index path has been selected. - (void)collectionView:(YMJNWCollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath; /// Asks the delegate if the item at the specified index path should be deselected. - (BOOL)collectionView:(YMJNWCollectionView *)collectionView shouldDeselectItemAtIndexPath:(NSIndexPath *)indexPath; /// Tells the delegate that the item at the specified index path has been deselected. - (void)collectionView:(YMJNWCollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath; /// Tells the delegate that the item at the specified index path has been double-clicked. - (void)collectionView:(YMJNWCollectionView *)collectionView didDoubleClickItemAtIndexPath:(NSIndexPath *)indexPath; /// Tells the delegate that the item at the specified index path has been right-clicked. - (void)collectionView:(YMJNWCollectionView *)collectionView didRightClickItemAtIndexPath:(NSIndexPath *)indexPath; /// Asks the delegate if the item at the specified index path should be scrolled to. - (BOOL)collectionView:(YMJNWCollectionView *)collectionView shouldScrollToItemAtIndexPath:(NSIndexPath *)indexPath; /// Tells the delegate that the specified index path has been scrolled to. - (void)collectionView:(YMJNWCollectionView *)collectionView didScrollToItemAtIndexPath:(NSIndexPath *)indexPath; /// Tells the delegate that the cell for the specified index path has been put /// back into the reuse queue. - (void)collectionView:(YMJNWCollectionView *)collectionView didEndDisplayingCell:(YMJNWCollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath; /// Asks the delegate if a contextual menu should be used for the given event. - (NSMenu *)collectionView:(YMJNWCollectionView *)collectionView menuForEvent:(NSEvent *)event; /// Asks the delegate for an objectValue for the YMJNWCollectionViewCell at the given indexPath. /// The objectValue object is used for data binding. - (id)collectionView:(YMJNWCollectionView *)collectionView objectValueForItemAtIndexPath:(NSIndexPath *)indexPath; @end #pragma mark Reloading and customizing @class YMJNWCollectionViewLayout; @interface YMJNWCollectionView : YMJNWScrollView /// The delegate for the collection view. @property (nonatomic, unsafe_unretained) IBOutlet id<YMJNWCollectionViewDelegate> delegate; /// The data source for the collection view. /// /// Required. @property (nonatomic, unsafe_unretained) IBOutlet id<YMJNWCollectionViewDataSource> dataSource; /// Calling this method will cause the collection view to clean up all the views and /// recalculate item info. It will then perform a layout pass. /// /// This method should be called after the data source has been set and initial setup on the collection /// view has been completed. - (void)reloadData; /// In order for cell or supplementary view dequeueing to occur, a class must be registered with the appropriate /// registration method. /// /// The class passed in will be used to initialize a new instance of the view, as needed. The class /// must be a subclass of YMJNWCollectionViewCell for the cell class, and YMJNWCollectionViewReusableView /// for the supplementary view class, otherwise an exception will be thrown. /// /// Registering a class or nib are exclusive: registering one will unregister the other. - (void)registerClass:(Class)cellClass forCellWithReuseIdentifier:(NSString *)reuseIdentifier; - (void)registerClass:(Class)supplementaryViewClass forSupplementaryViewOfKind:(NSString *)kind withReuseIdentifier:(NSString *)reuseIdentifier; /// You can also register a nib instead of a class to be able to dequeue a cell or supplementary view. /// /// The nib must contain a top-level object of a subclass of YMJNWCollectionViewCell for the cell, and /// YMJNWCollectionViewReusableView for the supplementary view, otherwise an exception will be thrown when dequeuing. /// /// Registering a class or nib are exclusive: registering one will unregister the other. - (void)registerNib:(NSNib *)cellNib forCellWithReuseIdentifier:(NSString *)identifier; - (void)registerNib:(NSNib *)supplementaryViewNib forSupplementaryViewOfKind:(NSString *)kind withReuseIdentifier:(NSString *)reuseIdentifier; /// These methods are used to create or reuse a new view. Cells should not be created manually. Instead, /// these methods should be called with a reuse identifier previously registered using /// -registerClass:forCellWithReuseIdentifier: or -registerClass:forSupplementaryViewOfKind:withReuseIdentifier:. /// /// If a class was not previously registered, the base cell class will be used to create the view. /// However, for supplementary views, the class must be registered, otherwise the collection view /// will not attempt to load any supplementary views for that kind. /// /// The identifer must not be nil, otherwise an exception will be thrown. - (YMJNWCollectionViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier; - (YMJNWCollectionViewReusableView *)dequeueReusableSupplementaryViewOfKind:(NSString *)kind withReuseIdentifer:(NSString *)identifier; /// The layout is responsible for providing the positioning and layout attributes for cells and views. /// It is also responsible for handling selection changes that are performed via the keyboard. See the /// documentation in YMJNWCollectionViewLayout.h. /// /// A valid layout must be set before calling -reloadData, otherwise an exception will be thrown. /// /// Layouts must not be reused between separate collection view instances. A single layout can be /// associated with only one collection view at any given time. /// /// Defaults to nil. @property (nonatomic, strong) YMJNWCollectionViewLayout *collectionViewLayout; /// The background color determines what is drawn underneath any cells that might be visible /// at the time. If this is a repeating pattern image, it will scroll along with the content. /// /// Defaults to a white color. @property (copy) NSColor *backgroundColor; /// Whether or not the collection view draws the background color. If the collection view /// background color needs to be transparent, this should be disabled. /// /// Defaults to YES. @property (assign) BOOL drawsBackground; #pragma mark - Information /// Returns the total number of sections. - (NSInteger)numberOfSections; /// Returns the number of items in the specified section. - (NSInteger)numberOfItemsInSection:(NSInteger)section; /// The following methods will return frames in flipped coordinates, where the origin is the /// top left point in the scroll view. All of these methods will return CGRectZero if an invalid /// index path or section is specified. - (CGRect)rectForItemAtIndexPath:(NSIndexPath *)indexPath; - (CGRect)rectForSupplementaryViewWithKind:(NSString *)kind inSection:(NSInteger)section; - (CGRect)rectForSection:(NSInteger)section; /// the frame encompassing the cells and views in the specified section /// Provides the size of the visible document area in which the collection view is currently /// displaying cells and other supplementary views. /// /// Equivalent to the size of -documentVisibleRect. @property (nonatomic, assign, readonly) CGSize visibleSize; /// Returns the index path for the item at the specified point, otherwise nil if no item is found. - (NSIndexPath *)indexPathForItemAtPoint:(CGPoint)point; /// Returns the index path for the specified cell, otherwise returns nil if the cell isn't visible. - (NSIndexPath *)indexPathForCell:(YMJNWCollectionViewCell *)cell; /// Returns an array of all of the index paths contained within the specified frame. - (NSArray *)indexPathsForItemsInRect:(CGRect)rect; /// Returns an index set containing the indexes for all sections that intersect the specified rect. - (NSIndexSet *)indexesForSectionsInRect:(CGRect)rect; /// Returns the cell at the specified index path, otherwise returns nil if the index path /// is invalid or if the cell is not visible. - (YMJNWCollectionViewCell *)cellForItemAtIndexPath:(NSIndexPath *)indexPath; /// Returns the supplementary view of the specified kind and reuse identifier in the section, otherwise returns nil if /// the supplementary view is no longer visible or if the kind and reuse identifier are invalid or have not been /// previously registered in -registerClass:forSupplementaryViewOfKind:reuseIdentifier:. - (YMJNWCollectionViewReusableView *)supplementaryViewForKind:(NSString *)kind reuseIdentifier:(NSString *)reuseIdentifier inSection:(NSInteger)section; /// Returns an array of all the currently visible cells. The cells are not guaranteed to be in any order. - (NSArray *)visibleCells; /// Returns the index paths for all the items in the visible rect. Order is not guaranteed. - (NSArray *)indexPathsForVisibleItems; /// Returns the index paths for any selected items. Order is not guaranteed. - (NSArray *)indexPathsForSelectedItems; #pragma mark - Selection /// If set to YES, any changes to the backgroundImage or backgroundColor properties of the collection view cell /// will be animated with a crossfade. /// /// Defaults to NO. @property (nonatomic, assign) BOOL animatesSelection; /// If set to NO, the collection view will not automatically select cells either through clicks or /// through keyboard actions. /// /// Defaults to YES. @property (nonatomic, assign) BOOL allowsSelection; /// If set to NO, the collection view will force at least one cell to be selected as long as the /// collection view isn't empty. If no cells are selected, the first one will be selected automatically. /// /// Defaults to YES. @property (nonatomic, assign) BOOL allowsEmptySelection; /// Returns the list of indexPaths of the selected items @property (nonatomic, readonly) NSMutableArray *selectedIndexes; /// Scrolls the collection view to the item at the specified path, optionally animated. The scroll position determines /// where the item is positioned on the screen. - (void)scrollToItemAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(YMJNWCollectionViewScrollPosition)scrollPosition animated:(BOOL)animated; /// Selects the item at the specified index path, deselecting any other selected items in the process, optionally animated. /// The collection view will then scroll to that item in the position as determined by scrollPosition. If no scroll is /// desired, pass in YMJNWCollectionViewScrollPositionNone to prevent the scroll.. - (void)selectItemAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(YMJNWCollectionViewScrollPosition)scrollPosition animated:(BOOL)animated; /// Selects all items in the collection view. - (void)selectAllItems; /// Deselects all items in the collection view. - (void)deselectAllItems; @end
4,347
1,724
<reponame>GeGuNa/skift_oss2 #include <libutils/Vec.h> #include <skift/NumberFormatter.h> #include <string.h> #include "system/Streams.h" #include "pci/PCI.h" #include "ps2/Legacy.h" #include "system/devices/Devices.h" #include "system/devices/Driver.h" #include "unix/UNIX.h" static Vec<Ref<Device>> *_devices = nullptr; static int _device_ids[(uint8_t)DeviceClass::__COUNT] = {}; static const char *_device_names[(uint8_t)DeviceClass::__COUNT] = { #define DEVICE_NAMES_ENTRY(__type, __name) #__name, DEVICE_CLASS_LIST(DEVICE_NAMES_ENTRY)}; void device_scan(IterFunc<DeviceAddress> callback) { if (legacy_scan([&](LegacyAddress address) { return callback(DeviceAddress(address)); }) == Iter::STOP) { return; } if (pci_scan([&](PCIAddress address) { return callback(DeviceAddress(address)); }) == Iter::STOP) { return; } if (unix_scan([&](UNIXAddress address) { return callback(DeviceAddress(address)); }) == Iter::STOP) { return; } } String device_claim_name(DeviceClass klass) { _device_ids[(uint8_t)klass]++; if (_device_ids[(uint8_t)klass] == 1) { return _device_names[(uint8_t)klass]; } else { return IO::format( "{}{}", _device_names[(uint8_t)klass], _device_ids[(uint8_t)klass] - 1); } } void device_iterate(IterFunc<Ref<Device>> callback) { if (_devices) { _devices->foreach([&](auto &device) { if (callback(device) == Iter::STOP) { return Iter::STOP; } return device->iterate(callback); }); } } void devices_acknowledge_interrupt(int interrupt) { device_iterate([&](auto device) { if (device->interrupt() == interrupt) { device->acknowledge_interrupt(); } return Iter::CONTINUE; }); } void devices_handle_interrupt(int interrupt) { device_iterate([&](auto device) { if (device->interrupt() == interrupt) { device->handle_interrupt(); } return Iter::CONTINUE; }); } void device_initialize() { pci_initialize(); Kernel::logln("Initializing devices..."); _devices = new Vec<Ref<Device>>(); device_scan([&](DeviceAddress address) { Kernel::logln("Initializing device {}...", address.as_static_cstring()); auto driver = driver_for(address); if (!driver) { Kernel::logln("No driver found!"); return Iter::CONTINUE; } Kernel::logln("Found a driver: {}", driver->name()); auto device = driver->instance(address); if (!device->did_fail()) { _devices->push_back(device); } return Iter::CONTINUE; }); }
1,485
1,444
<reponame>GabrielSturtevant/mage<filename>Mage.Sets/src/mage/cards/s/SylvanAdvocate.java package mage.cards.s; import java.util.UUID; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.condition.common.PermanentsOnTheBattlefieldCondition; import mage.abilities.decorator.ConditionalContinuousEffect; import mage.abilities.effects.common.continuous.BoostControlledEffect; import mage.abilities.effects.common.continuous.BoostSourceEffect; import mage.abilities.keyword.VigilanceAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.ComparisonType; import mage.constants.Duration; import mage.constants.Zone; import mage.filter.common.FilterControlledLandPermanent; import mage.filter.common.FilterCreaturePermanent; /** * @author fireshoes */ public final class SylvanAdvocate extends CardImpl { private static final String rule1 = "As long as you control six or more lands, {this}"; private static final String rule2 = "and land creatures you control get +2/+2."; private static final FilterCreaturePermanent filter = new FilterCreaturePermanent("land creatures"); static { filter.add(CardType.LAND.getPredicate()); } public SylvanAdvocate(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{G}"); this.subtype.add(SubType.ELF); this.subtype.add(SubType.DRUID); this.subtype.add(SubType.ALLY); this.power = new MageInt(2); this.toughness = new MageInt(3); // Vigilance this.addAbility(VigilanceAbility.getInstance()); // As long as you control six or more lands, Sylvan Advocate and land creatures you control get +2/+2. ConditionalContinuousEffect effect1 = new ConditionalContinuousEffect(new BoostSourceEffect(2, 2, Duration.WhileOnBattlefield), new PermanentsOnTheBattlefieldCondition(new FilterControlledLandPermanent(), ComparisonType.MORE_THAN, 5), rule1); ConditionalContinuousEffect effect2 = new ConditionalContinuousEffect(new BoostControlledEffect(2, 2, Duration.WhileOnBattlefield, filter, true), new PermanentsOnTheBattlefieldCondition(new FilterControlledLandPermanent(), ComparisonType.MORE_THAN, 5), rule2); Ability ability = new SimpleStaticAbility(Zone.BATTLEFIELD, effect1); ability.addEffect(effect2); this.addAbility(ability); } private SylvanAdvocate(final SylvanAdvocate card) { super(card); } @Override public SylvanAdvocate copy() { return new SylvanAdvocate(this); } }
930
342
/* TA-LIB Copyright (c) 1999-2007, <NAME> * 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 author nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * REGENTS 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 TA_ABSTRACT_H #define TA_ABSTRACT_H #ifndef TA_COMMON_H #include "ta_common.h" #endif #ifdef __cplusplus extern "C" { #endif /* This file defines the interface for calling all the TA functions without * knowing at priori the parameters. * * This capability is particularly useful for an application who needs * to support the complete list of TA functions without having to * re-write new code each time a new function is added to TA-Lib. * * Example 1: * Lets say you are doing a charting software. When the user select * a price bar, a side list offers blindly all the TA functions * that could be applied to a price bar. The user selects one of * these, then a dialog open for allowing to adjust some parameter * (TA-LIB will tell your software which parameter are needed and the * valid range for each). Once all the parameter are set, you can * call blindly the corresponding TA function. The returned * information can then also blindly be drawn on the chart (some * output flags allows to get some hint about how the data shall be * displayed). * The same "abstract" logic apply to all the TA functions. * Some TA Functions works only on volume, or can work indiferently * with any time serie data (the open, close, another indicator...). * All the applicable functions to the currently selected/available * data can be determined through this "virtual" interface. * * Example 2: * Let's say you do not like the direct interface for * calling the TA Functions, you can write a code that * re-generate a different interface. This is already * done even for the 'C' interface (ta_func.h is generated). * * Example 3: * With the abstract interface you can easily generate * glue code. Like generating an interface that integrates * well within Perl... see the project SWIG if you are * interested by such things. * * The abstract interface is used within TA-Lib to perform at least * the following: * - used by gen_code to generate all the glue code. * - used by the Excel interface to call all the TA functions. * - used to generate a XML representation of the TA functions. */ /* The following functions are used to obtain the name of all the * TA function groups ("Market Strength", "Trend Indicator" etc...). * * On success, it becomes the responsibility of the caller to * call TA_GroupTableFree once the 'table' is no longuer needed. * * Example: * This code snippet will print out the name of all the supported * function group available: * * TA_StringTable *table; * TA_RetCode retCode; * int i; * * retCode = TA_GroupTableAlloc( &table ); * * if( retCode == TA_SUCCESS ) * { * for( i=0; i < table->size; i++ ) * printf( "%s\n", table->string[i] ); * * TA_GroupTableFree( table ); * } */ TA_RetCode TA_GroupTableAlloc( TA_StringTable **table ); TA_RetCode TA_GroupTableFree ( TA_StringTable *table ); /* The following functions are used to obtain the name of all the * function provided in a certain group. * * On success, it becomes the responsibility of the caller to * call TA_FuncTableFree once the 'table' is no longuer needed. * * Passing NULL as the group string will return ALL the TA functions. * (Note: All TA_Functions have a unique string identifier even when in * seperate group). * * Example: * This code snippet will print out the name of all the supported * function in the "market strength" category: * * TA_StringTable *table; * TA_RetCode retCode; * int i; * * retCode = TA_FuncTableAlloc( "Market Strength", &table ); * * if( retCode == TA_SUCCESS ) * { * for( i=0; i < table->size; i++ ) * printf( "%s\n", table->string[i] ); * * TA_FuncTableFree( table ); * } */ TA_RetCode TA_FuncTableAlloc( const char *group, TA_StringTable **table ); TA_RetCode TA_FuncTableFree ( TA_StringTable *table ); /* Using the name, you can obtain an handle unique to this function. * This handle is further used for obtaining information on the * parameters needed and also for potentially calling this TA function. * * For convenience, this handle can also be found in * the TA_FuncInfo structure (see below). */ typedef unsigned int TA_FuncHandle; TA_RetCode TA_GetFuncHandle( const char *name, const TA_FuncHandle **handle ); /* Get some basic information about a function. * * A const pointer will be set on the corresponding TA_FuncInfo structure. * The whole structure are hard coded constants and it can be assumed they * will not change at runtime. * * Example: * Print the number of inputs used by the MA (moving average) function. * * TA_RetCode retCode; * TA_FuncHandle *handle; * const TA_FuncInfo *theInfo; * * retCode = TA_GetFuncHandle( "MA", &handle ); * * if( retCode == TA_SUCCESS ) * { * retCode = TA_GetFuncInfo( handle, &theInfo ); * if( retCode == TA_SUCCESS ) * printf( "Nb Input = %d\n", theInfo->nbInput ); * } * */ typedef int TA_FuncFlags; #define TA_FUNC_FLG_OVERLAP 0x01000000 /* Output scale same as input data. */ #define TA_FUNC_FLG_VOLUME 0x04000000 /* Output shall be over the volume data. */ #define TA_FUNC_FLG_UNST_PER 0x08000000 /* Indicate if this function have an unstable * initial period. Some additional code exist * for these functions for allowing to set that * unstable period. See Documentation. */ #define TA_FUNC_FLG_CANDLESTICK 0x10000000 /* Output shall be a candlestick */ typedef struct TA_FuncInfo { /* Constant information about the function. The * information found in this structure is guarantee * to not change at runtime. */ const char * name; const char * group; const char * hint; const char * camelCaseName; TA_FuncFlags flags; unsigned int nbInput; unsigned int nbOptInput; unsigned int nbOutput; const TA_FuncHandle *handle; } TA_FuncInfo; TA_RetCode TA_GetFuncInfo( const TA_FuncHandle *handle, const TA_FuncInfo **funcInfo ); /* An alternate way to access all the functions is through the * use of the TA_ForEachFunc(). You can setup a function to be * call back for each TA function in the TA-Lib. * * Example: * This code will print the group and name of all available functions. * * void printFuncInfo( const TA_FuncInfo *funcInfo, void *opaqueData ) * { * printf( "Group=%s Name=%s\n", funcInfo->group, funcInfo->name ); * } * * void displayListOfTAFunctions( void ) * { * TA_ForEachFunc( printFuncInfo, NULL ); * } */ typedef void (*TA_CallForEachFunc)(const TA_FuncInfo *funcInfo, void *opaqueData ); TA_RetCode TA_ForEachFunc( TA_CallForEachFunc functionToCall, void *opaqueData ); /* The next section includes the data structures and function allowing to * proceed with the call of a Tech. Analysis function. * * At first, it may seems a little bit complicated, but it is worth to take the * effort to learn about it. Once you succeed to interface with TA-Abstract you get * access to the complete library of TA functions at once without further effort. */ /* Structures representing extended information on a parameter. */ typedef struct TA_RealRange { TA_Real min; TA_Real max; TA_Integer precision; /* nb of digit after the '.' */ /* The following suggested value are used by Tech. Analysis software * doing parameter "optimization". Can be ignored by most user. */ TA_Real suggested_start; TA_Real suggested_end; TA_Real suggested_increment; } TA_RealRange; typedef struct TA_IntegerRange { TA_Integer min; TA_Integer max; /* The following suggested value are used by Tech. Analysis software * doing parameter "optimization". Can be ignored by most user. */ TA_Integer suggested_start; TA_Integer suggested_end; TA_Integer suggested_increment; } TA_IntegerRange; typedef struct TA_RealDataPair { /* A TA_Real value and the corresponding string. */ TA_Real value; const char *string; } TA_RealDataPair; typedef struct TA_IntegerDataPair { /* A TA_Integer value and the corresponding string. */ TA_Integer value; const char *string; } TA_IntegerDataPair; typedef struct TA_RealList { const TA_RealDataPair *data; unsigned int nbElement; } TA_RealList; typedef struct TA_IntegerList { const TA_IntegerDataPair *data; unsigned int nbElement; } TA_IntegerList; typedef enum { TA_Input_Price, TA_Input_Real, TA_Input_Integer } TA_InputParameterType; typedef enum { TA_OptInput_RealRange, TA_OptInput_RealList, TA_OptInput_IntegerRange, TA_OptInput_IntegerList } TA_OptInputParameterType; typedef enum { TA_Output_Real, TA_Output_Integer } TA_OutputParameterType; /* When the input is a TA_Input_Price, the following * TA_InputFlags indicates the required components. * These can be combined for functions requiring more * than one component. * * Example: * (TA_IN_PRICE_OPEN|TA_IN_PRICE_HIGH) * Indicates that the functions requires two inputs * that must be specifically the open and the high. */ typedef int TA_InputFlags; #define TA_IN_PRICE_OPEN 0x00000001 #define TA_IN_PRICE_HIGH 0x00000002 #define TA_IN_PRICE_LOW 0x00000004 #define TA_IN_PRICE_CLOSE 0x00000008 #define TA_IN_PRICE_VOLUME 0x00000010 #define TA_IN_PRICE_OPENINTEREST 0x00000020 #define TA_IN_PRICE_TIMESTAMP 0x00000040 /* The following are flags for optional inputs. * * TA_OPTIN_IS_PERCENT: Input is a percentage. * * TA_OPTIN_IS_DEGREE: Input is a degree (0-360). * * TA_OPTIN_IS_CURRENCY: Input is a currency. * * TA_OPTIN_ADVANCED: * Used for parameters who are rarely changed. * Most application can hide these advanced optional inputs to their * end-user (or make it harder to change). */ typedef int TA_OptInputFlags; #define TA_OPTIN_IS_PERCENT 0x00100000 /* Input is a percentage. */ #define TA_OPTIN_IS_DEGREE 0x00200000 /* Input is a degree (0-360). */ #define TA_OPTIN_IS_CURRENCY 0x00400000 /* Input is a currency. */ #define TA_OPTIN_ADVANCED 0x01000000 /* The following are flags giving hint on what * could be done with the output. */ typedef int TA_OutputFlags; #define TA_OUT_LINE 0x00000001 /* Suggest to display as a connected line. */ #define TA_OUT_DOT_LINE 0x00000002 /* Suggest to display as a 'dotted' line. */ #define TA_OUT_DASH_LINE 0x00000004 /* Suggest to display as a 'dashed' line. */ #define TA_OUT_DOT 0x00000008 /* Suggest to display with dots only. */ #define TA_OUT_HISTO 0x00000010 /* Suggest to display as an histogram. */ #define TA_OUT_PATTERN_BOOL 0x00000020 /* Indicates if pattern exists (!=0) or not (0) */ #define TA_OUT_PATTERN_BULL_BEAR 0x00000040 /* =0 no pattern, > 0 bullish, < 0 bearish */ #define TA_OUT_PATTERN_STRENGTH 0x00000080 /* =0 neutral, ]0..100] getting bullish, ]100..200] bullish, [-100..0[ getting bearish, [-200..100[ bearish */ #define TA_OUT_POSITIVE 0x00000100 /* Output can be positive */ #define TA_OUT_NEGATIVE 0x00000200 /* Output can be negative */ #define TA_OUT_ZERO 0x00000400 /* Output can be zero */ #define TA_OUT_UPPER_LIMIT 0x00000800 /* Indicates that the values represent an upper limit. */ #define TA_OUT_LOWER_LIMIT 0x00001000 /* Indicates that the values represent a lower limit. */ /* The following 3 structures will exist for each input, optional * input and output. * * These structures tells you everything you need to know for identifying * the parameters applicable to the function. */ typedef struct TA_InputParameterInfo { TA_InputParameterType type; const char *paramName; TA_InputFlags flags; } TA_InputParameterInfo; typedef struct TA_OptInputParameterInfo { TA_OptInputParameterType type; const char *paramName; TA_OptInputFlags flags; const char *displayName; const void *dataSet; TA_Real defaultValue; const char *hint; const char *helpFile; } TA_OptInputParameterInfo; typedef struct TA_OutputParameterInfo { TA_OutputParameterType type; const char *paramName; TA_OutputFlags flags; } TA_OutputParameterInfo; /* Functions to get a const ptr on the "TA_XXXXXXParameterInfo". * Max value for the 'paramIndex' can be found in the TA_FuncInfo structure. * The 'handle' can be obtained from TA_GetFuncHandle or from a TA_FuncInfo. * * Short example: * * void displayInputType( const TA_FuncInfo *funcInfo ) * { * unsigned int i; * const TA_InputParameterInfo *paramInfo; * * for( i=0; i < funcInfo->nbInput; i++ ) * { * TA_GetInputParameterInfo( funcInfo->handle, i, &paramInfo ); * switch( paramInfo->type ) * { * case TA_Input_Price: * printf( "This function needs price bars as input\n" ); * break; * case TA_Input_Real: * printf( "This function needs an array of floats as input\n" ); * break; * (... etc. ...) * } * } * } */ TA_RetCode TA_GetInputParameterInfo( const TA_FuncHandle *handle, unsigned int paramIndex, const TA_InputParameterInfo **info ); TA_RetCode TA_GetOptInputParameterInfo( const TA_FuncHandle *handle, unsigned int paramIndex, const TA_OptInputParameterInfo **info ); TA_RetCode TA_GetOutputParameterInfo( const TA_FuncHandle *handle, unsigned int paramIndex, const TA_OutputParameterInfo **info ); /* Alloc a structure allowing to build the list of parameters * for doing a call. * * All input and output parameters must be setup. If not, TA_BAD_PARAM * will be returned when TA_CallFunc is called. * * The optional input are not required to be setup. A default value * will always be used in that case. * * If there is an attempts to set a parameter with the wrong function * (and thus the wrong type), TA_BAD_PARAM will be immediatly returned. * * Although this mechanism looks complicated, it is written for being fairly solid. * If you provide a wrong parameter value, or wrong type, or wrong pointer etc. the * library shall return TA_BAD_PARAM or TA_BAD_OBJECT and not hang. */ typedef struct TA_ParamHolder { /* Implementation is hidden. */ void *hiddenData; } TA_ParamHolder; TA_RetCode TA_ParamHolderAlloc( const TA_FuncHandle *handle, TA_ParamHolder **allocatedParams ); TA_RetCode TA_ParamHolderFree( TA_ParamHolder *params ); /* Setup the values of the data input parameters. * * paramIndex is zero for the first input. */ TA_RetCode TA_SetInputParamIntegerPtr( TA_ParamHolder *params, unsigned int paramIndex, const TA_Integer *value ); TA_RetCode TA_SetInputParamRealPtr( TA_ParamHolder *params, unsigned int paramIndex, const TA_Real *value ); TA_RetCode TA_SetInputParamPricePtr( TA_ParamHolder *params, unsigned int paramIndex, const TA_Real *open, const TA_Real *high, const TA_Real *low, const TA_Real *close, const TA_Real *volume, const TA_Real *openInterest ); /* Setup the values of the optional input parameters. * If an optional input is not set, a default value will be used. * * paramIndex is zero for the first optional input. */ TA_RetCode TA_SetOptInputParamInteger( TA_ParamHolder *params, unsigned int paramIndex, TA_Integer optInValue ); TA_RetCode TA_SetOptInputParamReal( TA_ParamHolder *params, unsigned int paramIndex, TA_Real optInValue ); /* Setup the parameters indicating where to store the output. * * The caller is responsible to allocate sufficient memory. A safe bet is to * always do: nb of output elements == (endIdx-startIdx+1) * * paramIndex is zero for the first output. * */ TA_RetCode TA_SetOutputParamIntegerPtr( TA_ParamHolder *params, unsigned int paramIndex, TA_Integer *out ); TA_RetCode TA_SetOutputParamRealPtr( TA_ParamHolder *params, unsigned int paramIndex, TA_Real *out ); /* Once the optional parameter are set, it is possible to * get the lookback for this call. This information can be * used to calculate the optimal size for the output buffers. * (See the documentation for method to calculate the output size). */ TA_RetCode TA_GetLookback( const TA_ParamHolder *params, TA_Integer *lookback ); /* Finally, call the TA function with the parameters. * * The TA function who is going to be called was specified * when the TA_ParamHolderAlloc was done. */ TA_RetCode TA_CallFunc( const TA_ParamHolder *params, TA_Integer startIdx, TA_Integer endIdx, TA_Integer *outBegIdx, TA_Integer *outNbElement ); /* Return XML representation of all the TA functions. * The returned array is the same as the ta_func_api.xml file. */ const char *TA_FunctionDescriptionXML( void ); #ifdef __cplusplus } #endif #endif
8,075
1,412
<filename>Presentations/How to call C libraries from C++/Code/Po7/Po7_inet.cpp // // Po7_inet.cpp // PlusPlus // // Created by <NAME> on 9/1/14. // Released into the public domain by <NAME>, 2014. // #include "Po7_inet.h" #include "Po7_Invoke.h" const char *Po7::inet_ntop( socket_domain_t af, const void *src, char *dst, socklen_t size ) { return Invoke( Result< const char * >() + FailsWhenFalse(), ::inet_ntop, In( af, src, dst, size ), ThrowErrorFromErrno() ); } void Po7::inet_pton( socket_domain_t af, const char *src, void *dst ) { return Invoke( Result< int >() + NotReturned() + FailsWhen( []( int r ){ return r != 1; } ), ::inet_pton, In( af, src, dst ), ThrowErrorFromErrno() ); }
521
575
<gh_stars>100-1000 // 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/network/public/cpp/web_sandbox_flags.h" #include <set> #include "base/stl_util.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "services/network/public/mojom/web_sandbox_flags.mojom.h" namespace network { using mojom::WebSandboxFlags; namespace { // See: https://infra.spec.whatwg.org/#ascii-whitespace // This is different from: base::kWhitespaceASCII. const char* kHtmlWhitespace = " \n\t\r\f"; WebSandboxFlags ParseWebSandboxToken(const base::StringPiece& token) { constexpr struct { const char* token; WebSandboxFlags flags; } table[] = { {"allow-downloads", WebSandboxFlags::kDownloads}, {"allow-forms", WebSandboxFlags::kForms}, {"allow-modals", WebSandboxFlags::kModals}, {"allow-orientation-lock", WebSandboxFlags::kOrientationLock}, {"allow-pointer-lock", WebSandboxFlags::kPointerLock}, {"allow-popups", WebSandboxFlags::kPopups}, {"allow-popups-to-escape-sandbox", WebSandboxFlags::kPropagatesToAuxiliaryBrowsingContexts}, {"allow-presentation", WebSandboxFlags::kPresentationController}, {"allow-same-origin", WebSandboxFlags::kOrigin}, {"allow-scripts", WebSandboxFlags::kAutomaticFeatures | WebSandboxFlags::kScripts}, {"allow-storage-access-by-user-activation", WebSandboxFlags::kStorageAccessByUserActivation}, {"allow-top-navigation", WebSandboxFlags::kTopNavigation}, {"allow-top-navigation-by-user-activation", WebSandboxFlags::kTopNavigationByUserActivation}, }; for (const auto& it : table) { if (CompareCaseInsensitiveASCII(it.token, token) == 0) return it.flags; } return WebSandboxFlags::kNone; // Not found. } } // namespace // See: http://www.w3.org/TR/html5/the-iframe-element.html#attr-iframe-sandbox WebSandboxFlagsParsingResult ParseWebSandboxPolicy( const base::StringPiece& input, WebSandboxFlags ignored_flags) { WebSandboxFlagsParsingResult out; out.flags = WebSandboxFlags::kAll; std::vector<base::StringPiece> error_tokens; for (const auto& token : base::SplitStringPiece(input, kHtmlWhitespace, base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) { WebSandboxFlags flags = ~ParseWebSandboxToken(token); flags |= ignored_flags; out.flags &= flags; if (flags == WebSandboxFlags::kAll) error_tokens.push_back(token); } if (!error_tokens.empty()) { // Some tests expect the order of error tokens to be preserved, while // removing the duplicates: // See /fast/frames/sandboxed-iframe-attribute-parsing-03.html std::set<base::StringPiece> set; base::EraseIf(error_tokens, [&](auto x) { return !set.insert(x).second; }); out.error_message = "'" + base::JoinString(error_tokens, "', '") + (error_tokens.size() > 1 ? "' are invalid sandbox flags." : "' is an invalid sandbox flag."); } return out; } } // namespace network
1,244
3,459
<gh_stars>1000+ // Specification file for Bookmark class #define FLASH_PHASE_MAX 11 #define FLASH_PHASE_BUTTONHELD 6 enum FLASH_TYPES { FLASH_TYPE_SET = 0, FLASH_TYPE_JUMP = 1, FLASH_TYPE_DEPLOY = 2, }; #define SCREENSHOT_WIDTH 256 #define SCREENSHOT_HEIGHT 240 #define SCREENSHOT_SIZE SCREENSHOT_WIDTH * SCREENSHOT_HEIGHT class BOOKMARK { public: BOOKMARK(); void init(); void free(); bool isDifferentFromCurrentMovie(); void set(); void handleJump(); void handleDeploy(); void save(EMUFILE *os); bool load(EMUFILE *is); bool skipLoad(EMUFILE *is); // saved vars bool notEmpty; SNAPSHOT snapshot; std::vector<uint8> savestate; std::vector<uint8> savedScreenshot; // not saved vars int flashPhase; int flashType; int floatingPhase; private: };
362
2,399
// // NSFileManager+MCS.h // SJMediaCacheServer // // Created by BlueDancer on 2020/11/26. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface NSFileManager (MCS) - (UInt64)mcs_fileSizeAtPath:(NSString *)path; - (UInt64)mcs_directorySizeAtPath:(NSString *)path; - (UInt64)mcs_freeDiskSpace; - (void)mcs_createDirectoryAtPath:(NSString *)path backupable:(BOOL)backupable; @end NS_ASSUME_NONNULL_END
177
407
<filename>paas/tesla-authproxy/tesla-authproxy-server/src/main/java/com/alibaba/tesla/authproxy/model/repository/RolePermissionRelRepository.java<gh_stars>100-1000 package com.alibaba.tesla.authproxy.model.repository; import com.alibaba.tesla.authproxy.model.RolePermissionRelDO; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import java.util.Collection; import java.util.List; public interface RolePermissionRelRepository extends JpaRepository<RolePermissionRelDO, Long>, JpaSpecificationExecutor<RolePermissionRelDO> { List<RolePermissionRelDO> findAllByTenantIdAndRoleIdIn(String tenantId, Collection<String> roleIds); }
241
1,350
<reponame>Manny27nyc/azure-sdk-for-java // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.digitaltwins.core.implementation; import com.azure.core.annotation.BodyParam; import com.azure.core.annotation.Delete; import com.azure.core.annotation.ExpectedResponses; import com.azure.core.annotation.Get; import com.azure.core.annotation.HeaderParam; import com.azure.core.annotation.Host; import com.azure.core.annotation.HostParam; import com.azure.core.annotation.Patch; import com.azure.core.annotation.PathParam; import com.azure.core.annotation.Post; import com.azure.core.annotation.Put; import com.azure.core.annotation.QueryParam; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceInterface; import com.azure.core.annotation.ServiceMethod; import com.azure.core.annotation.UnexpectedResponseExceptionType; import com.azure.core.http.rest.PagedResponse; import com.azure.core.http.rest.PagedResponseBase; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.RestProxy; import com.azure.core.models.JsonPatchDocument; import com.azure.core.util.Context; import com.azure.digitaltwins.core.implementation.models.DigitalTwinsAddOptions; import com.azure.digitaltwins.core.implementation.models.DigitalTwinsAddRelationshipOptions; import com.azure.digitaltwins.core.implementation.models.DigitalTwinsAddRelationshipResponse; import com.azure.digitaltwins.core.implementation.models.DigitalTwinsAddResponse; import com.azure.digitaltwins.core.implementation.models.DigitalTwinsDeleteOptions; import com.azure.digitaltwins.core.implementation.models.DigitalTwinsDeleteRelationshipOptions; import com.azure.digitaltwins.core.implementation.models.DigitalTwinsGetByIdOptions; import com.azure.digitaltwins.core.implementation.models.DigitalTwinsGetByIdResponse; import com.azure.digitaltwins.core.implementation.models.DigitalTwinsGetComponentOptions; import com.azure.digitaltwins.core.implementation.models.DigitalTwinsGetComponentResponse; import com.azure.digitaltwins.core.implementation.models.DigitalTwinsGetRelationshipByIdOptions; import com.azure.digitaltwins.core.implementation.models.DigitalTwinsGetRelationshipByIdResponse; import com.azure.digitaltwins.core.implementation.models.DigitalTwinsListIncomingRelationshipsOptions; import com.azure.digitaltwins.core.implementation.models.DigitalTwinsListRelationshipsOptions; import com.azure.digitaltwins.core.implementation.models.DigitalTwinsSendComponentTelemetryOptions; import com.azure.digitaltwins.core.implementation.models.DigitalTwinsSendTelemetryOptions; import com.azure.digitaltwins.core.implementation.models.DigitalTwinsUpdateComponentOptions; import com.azure.digitaltwins.core.implementation.models.DigitalTwinsUpdateComponentResponse; import com.azure.digitaltwins.core.implementation.models.DigitalTwinsUpdateOptions; import com.azure.digitaltwins.core.implementation.models.DigitalTwinsUpdateRelationshipOptions; import com.azure.digitaltwins.core.implementation.models.DigitalTwinsUpdateRelationshipResponse; import com.azure.digitaltwins.core.implementation.models.DigitalTwinsUpdateResponse; import com.azure.digitaltwins.core.implementation.models.ErrorResponseException; import com.azure.digitaltwins.core.implementation.models.IncomingRelationship; import com.azure.digitaltwins.core.implementation.models.IncomingRelationshipCollection; import com.azure.digitaltwins.core.implementation.models.RelationshipCollection; import reactor.core.publisher.Mono; /** An instance of this class provides access to all the operations defined in DigitalTwins. */ public final class DigitalTwinsImpl { /** The proxy service used to perform REST calls. */ private final DigitalTwinsService service; /** The service client containing this operation class. */ private final AzureDigitalTwinsAPIImpl client; /** * Initializes an instance of DigitalTwinsImpl. * * @param client the instance of the service client containing this operation class. */ DigitalTwinsImpl(AzureDigitalTwinsAPIImpl client) { this.service = RestProxy.create(DigitalTwinsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); this.client = client; } /** * The interface defining all the services for AzureDigitalTwinsAPIDigitalTwins to be used by the proxy service to * perform REST calls. */ @Host("{$host}") @ServiceInterface(name = "AzureDigitalTwinsAPI") public interface DigitalTwinsService { @Get("/digitaltwins/{id}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ErrorResponseException.class) Mono<DigitalTwinsGetByIdResponse> getById( @HostParam("$host") String host, @HeaderParam("traceparent") String traceparent, @HeaderParam("tracestate") String tracestate, @PathParam("id") String id, @QueryParam("api-version") String apiVersion, Context context); @Put("/digitaltwins/{id}") @ExpectedResponses({200, 202}) @UnexpectedResponseExceptionType(ErrorResponseException.class) Mono<DigitalTwinsAddResponse> add( @HostParam("$host") String host, @HeaderParam("traceparent") String traceparent, @HeaderParam("tracestate") String tracestate, @PathParam("id") String id, @HeaderParam("If-None-Match") String ifNoneMatch, @QueryParam("api-version") String apiVersion, @BodyParam("application/json") Object twin, Context context); @Delete("/digitaltwins/{id}") @ExpectedResponses({204}) @UnexpectedResponseExceptionType(ErrorResponseException.class) Mono<Response<Void>> delete( @HostParam("$host") String host, @HeaderParam("traceparent") String traceparent, @HeaderParam("tracestate") String tracestate, @PathParam("id") String id, @HeaderParam("If-Match") String ifMatch, @QueryParam("api-version") String apiVersion, Context context); @Patch("/digitaltwins/{id}") @ExpectedResponses({202, 204}) @UnexpectedResponseExceptionType(ErrorResponseException.class) Mono<DigitalTwinsUpdateResponse> update( @HostParam("$host") String host, @HeaderParam("traceparent") String traceparent, @HeaderParam("tracestate") String tracestate, @PathParam("id") String id, @HeaderParam("If-Match") String ifMatch, @QueryParam("api-version") String apiVersion, @BodyParam("application/json-patch+json") JsonPatchDocument patchDocument, Context context); @Get("/digitaltwins/{id}/relationships/{relationshipId}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ErrorResponseException.class) Mono<DigitalTwinsGetRelationshipByIdResponse> getRelationshipById( @HostParam("$host") String host, @HeaderParam("traceparent") String traceparent, @HeaderParam("tracestate") String tracestate, @PathParam("id") String id, @PathParam("relationshipId") String relationshipId, @QueryParam("api-version") String apiVersion, Context context); @Put("/digitaltwins/{id}/relationships/{relationshipId}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ErrorResponseException.class) Mono<DigitalTwinsAddRelationshipResponse> addRelationship( @HostParam("$host") String host, @HeaderParam("traceparent") String traceparent, @HeaderParam("tracestate") String tracestate, @PathParam("id") String id, @PathParam("relationshipId") String relationshipId, @HeaderParam("If-None-Match") String ifNoneMatch, @QueryParam("api-version") String apiVersion, @BodyParam("application/json") Object relationship, Context context); @Delete("/digitaltwins/{id}/relationships/{relationshipId}") @ExpectedResponses({204}) @UnexpectedResponseExceptionType(ErrorResponseException.class) Mono<Response<Void>> deleteRelationship( @HostParam("$host") String host, @HeaderParam("traceparent") String traceparent, @HeaderParam("tracestate") String tracestate, @PathParam("id") String id, @PathParam("relationshipId") String relationshipId, @HeaderParam("If-Match") String ifMatch, @QueryParam("api-version") String apiVersion, Context context); @Patch("/digitaltwins/{id}/relationships/{relationshipId}") @ExpectedResponses({204}) @UnexpectedResponseExceptionType(ErrorResponseException.class) Mono<DigitalTwinsUpdateRelationshipResponse> updateRelationship( @HostParam("$host") String host, @HeaderParam("traceparent") String traceparent, @HeaderParam("tracestate") String tracestate, @PathParam("id") String id, @PathParam("relationshipId") String relationshipId, @HeaderParam("If-Match") String ifMatch, @QueryParam("api-version") String apiVersion, @BodyParam("application/json-patch+json") JsonPatchDocument patchDocument, Context context); @Get("/digitaltwins/{id}/relationships") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ErrorResponseException.class) Mono<Response<RelationshipCollection>> listRelationships( @HostParam("$host") String host, @HeaderParam("traceparent") String traceparent, @HeaderParam("tracestate") String tracestate, @PathParam("id") String id, @QueryParam("relationshipName") String relationshipName, @QueryParam("api-version") String apiVersion, Context context); @Get("/digitaltwins/{id}/incomingrelationships") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ErrorResponseException.class) Mono<Response<IncomingRelationshipCollection>> listIncomingRelationships( @HostParam("$host") String host, @HeaderParam("traceparent") String traceparent, @HeaderParam("tracestate") String tracestate, @PathParam("id") String id, @QueryParam("api-version") String apiVersion, Context context); @Post("/digitaltwins/{id}/telemetry") @ExpectedResponses({204}) @UnexpectedResponseExceptionType(ErrorResponseException.class) Mono<Response<Void>> sendTelemetry( @HostParam("$host") String host, @HeaderParam("traceparent") String traceparent, @HeaderParam("tracestate") String tracestate, @PathParam("id") String id, @HeaderParam("Message-Id") String messageId, @HeaderParam("Telemetry-Source-Time") String telemetrySourceTime, @QueryParam("api-version") String apiVersion, @BodyParam("application/json") Object telemetry, Context context); @Post("/digitaltwins/{id}/components/{componentPath}/telemetry") @ExpectedResponses({204}) @UnexpectedResponseExceptionType(ErrorResponseException.class) Mono<Response<Void>> sendComponentTelemetry( @HostParam("$host") String host, @HeaderParam("traceparent") String traceparent, @HeaderParam("tracestate") String tracestate, @PathParam("id") String id, @PathParam("componentPath") String componentPath, @HeaderParam("Message-Id") String messageId, @HeaderParam("Telemetry-Source-Time") String telemetrySourceTime, @QueryParam("api-version") String apiVersion, @BodyParam("application/json") Object telemetry, Context context); @Get("/digitaltwins/{id}/components/{componentPath}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ErrorResponseException.class) Mono<DigitalTwinsGetComponentResponse> getComponent( @HostParam("$host") String host, @HeaderParam("traceparent") String traceparent, @HeaderParam("tracestate") String tracestate, @PathParam("id") String id, @PathParam("componentPath") String componentPath, @QueryParam("api-version") String apiVersion, Context context); @Patch("/digitaltwins/{id}/components/{componentPath}") @ExpectedResponses({202, 204}) @UnexpectedResponseExceptionType(ErrorResponseException.class) Mono<DigitalTwinsUpdateComponentResponse> updateComponent( @HostParam("$host") String host, @HeaderParam("traceparent") String traceparent, @HeaderParam("tracestate") String tracestate, @PathParam("id") String id, @PathParam("componentPath") String componentPath, @HeaderParam("If-Match") String ifMatch, @QueryParam("api-version") String apiVersion, @BodyParam("application/json-patch+json") JsonPatchDocument patchDocument, Context context); @Get("{nextLink}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ErrorResponseException.class) Mono<Response<RelationshipCollection>> listRelationshipsNext( @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String host, @HeaderParam("traceparent") String traceparent, @HeaderParam("tracestate") String tracestate, Context context); @Get("{nextLink}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ErrorResponseException.class) Mono<Response<IncomingRelationshipCollection>> listIncomingRelationshipsNext( @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String host, @HeaderParam("traceparent") String traceparent, @HeaderParam("tracestate") String tracestate, Context context); } /** * Retrieves a digital twin. Status codes: * 200 OK * 400 Bad Request * InvalidArgument - The digital twin id is * invalid. * 404 Not Found * DigitalTwinNotFound - The digital twin was not found. * * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param digitalTwinsGetByIdOptions Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return any object. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DigitalTwinsGetByIdResponse> getByIdWithResponseAsync( String id, DigitalTwinsGetByIdOptions digitalTwinsGetByIdOptions, Context context) { if (this.client.getHost() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getHost() is required and cannot be null.")); } if (id == null) { return Mono.error(new IllegalArgumentException("Parameter id is required and cannot be null.")); } if (digitalTwinsGetByIdOptions != null) { digitalTwinsGetByIdOptions.validate(); } String traceparentInternal = null; if (digitalTwinsGetByIdOptions != null) { traceparentInternal = digitalTwinsGetByIdOptions.getTraceparent(); } String traceparent = traceparentInternal; String tracestateInternal = null; if (digitalTwinsGetByIdOptions != null) { tracestateInternal = digitalTwinsGetByIdOptions.getTracestate(); } String tracestate = tracestateInternal; return service.getById( this.client.getHost(), traceparent, tracestate, id, this.client.getApiVersion(), context); } /** * Adds or replaces a digital twin. Status codes: * 200 OK * 400 Bad Request * InvalidArgument - The digital twin id * or payload is invalid. * ModelDecommissioned - The model for the digital twin is decommissioned. * * TwinLimitReached - The maximum number of digital twins allowed has been reached. * ValidationFailed - The digital * twin payload is not valid. * 412 Precondition Failed * PreconditionFailed - The precondition check (If-Match or * If-None-Match) failed. * * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param twin Any object. * @param digitalTwinsAddOptions Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return any object. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DigitalTwinsAddResponse> addWithResponseAsync( String id, Object twin, DigitalTwinsAddOptions digitalTwinsAddOptions, Context context) { if (this.client.getHost() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getHost() is required and cannot be null.")); } if (id == null) { return Mono.error(new IllegalArgumentException("Parameter id is required and cannot be null.")); } if (twin == null) { return Mono.error(new IllegalArgumentException("Parameter twin is required and cannot be null.")); } if (digitalTwinsAddOptions != null) { digitalTwinsAddOptions.validate(); } String traceparentInternal = null; if (digitalTwinsAddOptions != null) { traceparentInternal = digitalTwinsAddOptions.getTraceparent(); } String traceparent = traceparentInternal; String tracestateInternal = null; if (digitalTwinsAddOptions != null) { tracestateInternal = digitalTwinsAddOptions.getTracestate(); } String tracestate = tracestateInternal; String ifNoneMatchInternal = null; if (digitalTwinsAddOptions != null) { ifNoneMatchInternal = digitalTwinsAddOptions.getIfNoneMatch(); } String ifNoneMatch = ifNoneMatchInternal; return service.add( this.client.getHost(), traceparent, tracestate, id, ifNoneMatch, this.client.getApiVersion(), twin, context); } /** * Deletes a digital twin. All relationships referencing the digital twin must already be deleted. Status codes: * * 204 No Content * 400 Bad Request * InvalidArgument - The digital twin id is invalid. * RelationshipsNotDeleted - * The digital twin contains relationships. * 404 Not Found * DigitalTwinNotFound - The digital twin was not found. * * 412 Precondition Failed * PreconditionFailed - The precondition check (If-Match or If-None-Match) failed. * * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param digitalTwinsDeleteOptions Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteWithResponseAsync( String id, DigitalTwinsDeleteOptions digitalTwinsDeleteOptions, Context context) { if (this.client.getHost() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getHost() is required and cannot be null.")); } if (id == null) { return Mono.error(new IllegalArgumentException("Parameter id is required and cannot be null.")); } if (digitalTwinsDeleteOptions != null) { digitalTwinsDeleteOptions.validate(); } String traceparentInternal = null; if (digitalTwinsDeleteOptions != null) { traceparentInternal = digitalTwinsDeleteOptions.getTraceparent(); } String traceparent = traceparentInternal; String tracestateInternal = null; if (digitalTwinsDeleteOptions != null) { tracestateInternal = digitalTwinsDeleteOptions.getTracestate(); } String tracestate = tracestateInternal; String ifMatchInternal = null; if (digitalTwinsDeleteOptions != null) { ifMatchInternal = digitalTwinsDeleteOptions.getIfMatch(); } String ifMatch = ifMatchInternal; return service.delete( this.client.getHost(), traceparent, tracestate, id, ifMatch, this.client.getApiVersion(), context); } /** * Updates a digital twin. Status codes: * 204 No Content * 400 Bad Request * InvalidArgument - The digital twin id * or payload is invalid. * JsonPatchInvalid - The JSON Patch provided is invalid. * ValidationFailed - Applying the * patch results in an invalid digital twin. * 404 Not Found * DigitalTwinNotFound - The digital twin was not found. * * 412 Precondition Failed * PreconditionFailed - The precondition check (If-Match or If-None-Match) failed. * * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param patchDocument Array of any. * @param digitalTwinsUpdateOptions Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DigitalTwinsUpdateResponse> updateWithResponseAsync( String id, JsonPatchDocument patchDocument, DigitalTwinsUpdateOptions digitalTwinsUpdateOptions, Context context) { if (this.client.getHost() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getHost() is required and cannot be null.")); } if (id == null) { return Mono.error(new IllegalArgumentException("Parameter id is required and cannot be null.")); } if (patchDocument == null) { return Mono.error(new IllegalArgumentException("Parameter patchDocument is required and cannot be null.")); } if (digitalTwinsUpdateOptions != null) { digitalTwinsUpdateOptions.validate(); } String traceparentInternal = null; if (digitalTwinsUpdateOptions != null) { traceparentInternal = digitalTwinsUpdateOptions.getTraceparent(); } String traceparent = traceparentInternal; String tracestateInternal = null; if (digitalTwinsUpdateOptions != null) { tracestateInternal = digitalTwinsUpdateOptions.getTracestate(); } String tracestate = tracestateInternal; String ifMatchInternal = null; if (digitalTwinsUpdateOptions != null) { ifMatchInternal = digitalTwinsUpdateOptions.getIfMatch(); } String ifMatch = ifMatchInternal; return service.update( this.client.getHost(), traceparent, tracestate, id, ifMatch, this.client.getApiVersion(), patchDocument, context); } /** * Retrieves a relationship between two digital twins. Status codes: * 200 OK * 400 Bad Request * InvalidArgument - * The digital twin id or relationship id is invalid. * 404 Not Found * DigitalTwinNotFound - The digital twin was * not found. * RelationshipNotFound - The relationship was not found. * * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param relationshipId The id of the relationship. The id is unique within the digital twin and case sensitive. * @param digitalTwinsGetRelationshipByIdOptions Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return any object. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DigitalTwinsGetRelationshipByIdResponse> getRelationshipByIdWithResponseAsync( String id, String relationshipId, DigitalTwinsGetRelationshipByIdOptions digitalTwinsGetRelationshipByIdOptions, Context context) { if (this.client.getHost() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getHost() is required and cannot be null.")); } if (id == null) { return Mono.error(new IllegalArgumentException("Parameter id is required and cannot be null.")); } if (relationshipId == null) { return Mono.error(new IllegalArgumentException("Parameter relationshipId is required and cannot be null.")); } if (digitalTwinsGetRelationshipByIdOptions != null) { digitalTwinsGetRelationshipByIdOptions.validate(); } String traceparentInternal = null; if (digitalTwinsGetRelationshipByIdOptions != null) { traceparentInternal = digitalTwinsGetRelationshipByIdOptions.getTraceparent(); } String traceparent = traceparentInternal; String tracestateInternal = null; if (digitalTwinsGetRelationshipByIdOptions != null) { tracestateInternal = digitalTwinsGetRelationshipByIdOptions.getTracestate(); } String tracestate = tracestateInternal; return service.getRelationshipById( this.client.getHost(), traceparent, tracestate, id, relationshipId, this.client.getApiVersion(), context); } /** * Adds a relationship between two digital twins. Status codes: * 200 OK * 400 Bad Request * InvalidArgument - The * digital twin id, relationship id, or payload is invalid. * InvalidRelationship - The relationship is invalid. * * OperationNotAllowed - The relationship cannot connect to the same digital twin. * ValidationFailed - The * relationship content is invalid. * 404 Not Found * DigitalTwinNotFound - The digital twin was not found. * * TargetTwinNotFound - The digital twin target of the relationship was not found. * 412 Precondition Failed * * PreconditionFailed - The precondition check (If-Match or If-None-Match) failed. * * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param relationshipId The id of the relationship. The id is unique within the digital twin and case sensitive. * @param relationship Any object. * @param digitalTwinsAddRelationshipOptions Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return any object. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DigitalTwinsAddRelationshipResponse> addRelationshipWithResponseAsync( String id, String relationshipId, Object relationship, DigitalTwinsAddRelationshipOptions digitalTwinsAddRelationshipOptions, Context context) { if (this.client.getHost() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getHost() is required and cannot be null.")); } if (id == null) { return Mono.error(new IllegalArgumentException("Parameter id is required and cannot be null.")); } if (relationshipId == null) { return Mono.error(new IllegalArgumentException("Parameter relationshipId is required and cannot be null.")); } if (relationship == null) { return Mono.error(new IllegalArgumentException("Parameter relationship is required and cannot be null.")); } if (digitalTwinsAddRelationshipOptions != null) { digitalTwinsAddRelationshipOptions.validate(); } String traceparentInternal = null; if (digitalTwinsAddRelationshipOptions != null) { traceparentInternal = digitalTwinsAddRelationshipOptions.getTraceparent(); } String traceparent = traceparentInternal; String tracestateInternal = null; if (digitalTwinsAddRelationshipOptions != null) { tracestateInternal = digitalTwinsAddRelationshipOptions.getTracestate(); } String tracestate = tracestateInternal; String ifNoneMatchInternal = null; if (digitalTwinsAddRelationshipOptions != null) { ifNoneMatchInternal = digitalTwinsAddRelationshipOptions.getIfNoneMatch(); } String ifNoneMatch = ifNoneMatchInternal; return service.addRelationship( this.client.getHost(), traceparent, tracestate, id, relationshipId, ifNoneMatch, this.client.getApiVersion(), relationship, context); } /** * Deletes a relationship between two digital twins. Status codes: * 204 No Content * 400 Bad Request * * InvalidArgument - The digital twin id or relationship id is invalid. * 404 Not Found * DigitalTwinNotFound - The * digital twin was not found. * RelationshipNotFound - The relationship was not found. * 412 Precondition Failed * * PreconditionFailed - The precondition check (If-Match or If-None-Match) failed. * * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param relationshipId The id of the relationship. The id is unique within the digital twin and case sensitive. * @param digitalTwinsDeleteRelationshipOptions Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRelationshipWithResponseAsync( String id, String relationshipId, DigitalTwinsDeleteRelationshipOptions digitalTwinsDeleteRelationshipOptions, Context context) { if (this.client.getHost() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getHost() is required and cannot be null.")); } if (id == null) { return Mono.error(new IllegalArgumentException("Parameter id is required and cannot be null.")); } if (relationshipId == null) { return Mono.error(new IllegalArgumentException("Parameter relationshipId is required and cannot be null.")); } if (digitalTwinsDeleteRelationshipOptions != null) { digitalTwinsDeleteRelationshipOptions.validate(); } String traceparentInternal = null; if (digitalTwinsDeleteRelationshipOptions != null) { traceparentInternal = digitalTwinsDeleteRelationshipOptions.getTraceparent(); } String traceparent = traceparentInternal; String tracestateInternal = null; if (digitalTwinsDeleteRelationshipOptions != null) { tracestateInternal = digitalTwinsDeleteRelationshipOptions.getTracestate(); } String tracestate = tracestateInternal; String ifMatchInternal = null; if (digitalTwinsDeleteRelationshipOptions != null) { ifMatchInternal = digitalTwinsDeleteRelationshipOptions.getIfMatch(); } String ifMatch = ifMatchInternal; return service.deleteRelationship( this.client.getHost(), traceparent, tracestate, id, relationshipId, ifMatch, this.client.getApiVersion(), context); } /** * Updates the properties on a relationship between two digital twins. Status codes: * 204 No Content * 400 Bad * Request * InvalidArgument - The digital twin id or relationship id is invalid. * InvalidRelationship - The * relationship is invalid. * JsonPatchInvalid - The JSON Patch provided is invalid. * ValidationFailed - The * relationship content is invalid. * 404 Not Found * DigitalTwinNotFound - The digital twin was not found. * * RelationshipNotFound - The relationship was not found. * 409 Conflict * RelationshipAlreadyExists - The * relationship already exists. * 412 Precondition Failed * PreconditionFailed - The precondition check (If-Match or * If-None-Match) failed. * * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param relationshipId The id of the relationship. The id is unique within the digital twin and case sensitive. * @param patchDocument Array of any. * @param digitalTwinsUpdateRelationshipOptions Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DigitalTwinsUpdateRelationshipResponse> updateRelationshipWithResponseAsync( String id, String relationshipId, JsonPatchDocument patchDocument, DigitalTwinsUpdateRelationshipOptions digitalTwinsUpdateRelationshipOptions, Context context) { if (this.client.getHost() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getHost() is required and cannot be null.")); } if (id == null) { return Mono.error(new IllegalArgumentException("Parameter id is required and cannot be null.")); } if (relationshipId == null) { return Mono.error(new IllegalArgumentException("Parameter relationshipId is required and cannot be null.")); } if (patchDocument == null) { return Mono.error(new IllegalArgumentException("Parameter patchDocument is required and cannot be null.")); } if (digitalTwinsUpdateRelationshipOptions != null) { digitalTwinsUpdateRelationshipOptions.validate(); } String traceparentInternal = null; if (digitalTwinsUpdateRelationshipOptions != null) { traceparentInternal = digitalTwinsUpdateRelationshipOptions.getTraceparent(); } String traceparent = traceparentInternal; String tracestateInternal = null; if (digitalTwinsUpdateRelationshipOptions != null) { tracestateInternal = digitalTwinsUpdateRelationshipOptions.getTracestate(); } String tracestate = tracestateInternal; String ifMatchInternal = null; if (digitalTwinsUpdateRelationshipOptions != null) { ifMatchInternal = digitalTwinsUpdateRelationshipOptions.getIfMatch(); } String ifMatch = ifMatchInternal; return service.updateRelationship( this.client.getHost(), traceparent, tracestate, id, relationshipId, ifMatch, this.client.getApiVersion(), patchDocument, context); } /** * Retrieves the relationships from a digital twin. Status codes: * 200 OK * 400 Bad Request * InvalidArgument - The * digital twin id is invalid. * 404 Not Found * DigitalTwinNotFound - The digital twin was not found. * * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param relationshipName The name of the relationship. * @param digitalTwinsListRelationshipsOptions Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a collection of relationships which relate digital twins together. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PagedResponse<Object>> listRelationshipsSinglePageAsync( String id, String relationshipName, DigitalTwinsListRelationshipsOptions digitalTwinsListRelationshipsOptions, Context context) { if (this.client.getHost() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getHost() is required and cannot be null.")); } if (id == null) { return Mono.error(new IllegalArgumentException("Parameter id is required and cannot be null.")); } if (digitalTwinsListRelationshipsOptions != null) { digitalTwinsListRelationshipsOptions.validate(); } String traceparentInternal = null; if (digitalTwinsListRelationshipsOptions != null) { traceparentInternal = digitalTwinsListRelationshipsOptions.getTraceparent(); } String traceparent = traceparentInternal; String tracestateInternal = null; if (digitalTwinsListRelationshipsOptions != null) { tracestateInternal = digitalTwinsListRelationshipsOptions.getTracestate(); } String tracestate = tracestateInternal; return service.listRelationships( this.client.getHost(), traceparent, tracestate, id, relationshipName, this.client.getApiVersion(), context) .map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().getValue(), res.getValue().getNextLink(), null)); } /** * Retrieves all incoming relationship for a digital twin. Status codes: * 200 OK * 400 Bad Request * * InvalidArgument - The digital twin id is invalid. * 404 Not Found * DigitalTwinNotFound - The digital twin was * not found. * * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param digitalTwinsListIncomingRelationshipsOptions Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a collection of incoming relationships which relate digital twins together. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PagedResponse<IncomingRelationship>> listIncomingRelationshipsSinglePageAsync( String id, DigitalTwinsListIncomingRelationshipsOptions digitalTwinsListIncomingRelationshipsOptions, Context context) { if (this.client.getHost() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getHost() is required and cannot be null.")); } if (id == null) { return Mono.error(new IllegalArgumentException("Parameter id is required and cannot be null.")); } if (digitalTwinsListIncomingRelationshipsOptions != null) { digitalTwinsListIncomingRelationshipsOptions.validate(); } String traceparentInternal = null; if (digitalTwinsListIncomingRelationshipsOptions != null) { traceparentInternal = digitalTwinsListIncomingRelationshipsOptions.getTraceparent(); } String traceparent = traceparentInternal; String tracestateInternal = null; if (digitalTwinsListIncomingRelationshipsOptions != null) { tracestateInternal = digitalTwinsListIncomingRelationshipsOptions.getTracestate(); } String tracestate = tracestateInternal; return service.listIncomingRelationships( this.client.getHost(), traceparent, tracestate, id, this.client.getApiVersion(), context) .map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().getValue(), res.getValue().getNextLink(), null)); } /** * Sends telemetry on behalf of a digital twin. Status codes: * 204 No Content * 400 Bad Request * InvalidArgument - * The digital twin id or message id is invalid. * ValidationFailed - The telemetry content is invalid. * 404 Not * Found * DigitalTwinNotFound - The digital twin was not found. * * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param messageId A unique message identifier (in the scope of the digital twin id) that is commonly used for * de-duplicating messages. * @param telemetry Any object. * @param telemetrySourceTime An RFC 3339 timestamp that identifies the time the telemetry was measured. * @param digitalTwinsSendTelemetryOptions Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendTelemetryWithResponseAsync( String id, String messageId, Object telemetry, String telemetrySourceTime, DigitalTwinsSendTelemetryOptions digitalTwinsSendTelemetryOptions, Context context) { if (this.client.getHost() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getHost() is required and cannot be null.")); } if (id == null) { return Mono.error(new IllegalArgumentException("Parameter id is required and cannot be null.")); } if (messageId == null) { return Mono.error(new IllegalArgumentException("Parameter messageId is required and cannot be null.")); } if (telemetry == null) { return Mono.error(new IllegalArgumentException("Parameter telemetry is required and cannot be null.")); } if (digitalTwinsSendTelemetryOptions != null) { digitalTwinsSendTelemetryOptions.validate(); } String traceparentInternal = null; if (digitalTwinsSendTelemetryOptions != null) { traceparentInternal = digitalTwinsSendTelemetryOptions.getTraceparent(); } String traceparent = traceparentInternal; String tracestateInternal = null; if (digitalTwinsSendTelemetryOptions != null) { tracestateInternal = digitalTwinsSendTelemetryOptions.getTracestate(); } String tracestate = tracestateInternal; return service.sendTelemetry( this.client.getHost(), traceparent, tracestate, id, messageId, telemetrySourceTime, this.client.getApiVersion(), telemetry, context); } /** * Sends telemetry on behalf of a component in a digital twin. Status codes: * 204 No Content * 400 Bad Request * * InvalidArgument - The digital twin id, message id, or component path is invalid. * ValidationFailed - The * telemetry content is invalid. * 404 Not Found * DigitalTwinNotFound - The digital twin was not found. * * ComponentNotFound - The component path was not found. * * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param componentPath The name of the DTDL component. * @param messageId A unique message identifier (in the scope of the digital twin id) that is commonly used for * de-duplicating messages. * @param telemetry Any object. * @param telemetrySourceTime An RFC 3339 timestamp that identifies the time the telemetry was measured. * @param digitalTwinsSendComponentTelemetryOptions Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendComponentTelemetryWithResponseAsync( String id, String componentPath, String messageId, Object telemetry, String telemetrySourceTime, DigitalTwinsSendComponentTelemetryOptions digitalTwinsSendComponentTelemetryOptions, Context context) { if (this.client.getHost() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getHost() is required and cannot be null.")); } if (id == null) { return Mono.error(new IllegalArgumentException("Parameter id is required and cannot be null.")); } if (componentPath == null) { return Mono.error(new IllegalArgumentException("Parameter componentPath is required and cannot be null.")); } if (messageId == null) { return Mono.error(new IllegalArgumentException("Parameter messageId is required and cannot be null.")); } if (telemetry == null) { return Mono.error(new IllegalArgumentException("Parameter telemetry is required and cannot be null.")); } if (digitalTwinsSendComponentTelemetryOptions != null) { digitalTwinsSendComponentTelemetryOptions.validate(); } String traceparentInternal = null; if (digitalTwinsSendComponentTelemetryOptions != null) { traceparentInternal = digitalTwinsSendComponentTelemetryOptions.getTraceparent(); } String traceparent = traceparentInternal; String tracestateInternal = null; if (digitalTwinsSendComponentTelemetryOptions != null) { tracestateInternal = digitalTwinsSendComponentTelemetryOptions.getTracestate(); } String tracestate = tracestateInternal; return service.sendComponentTelemetry( this.client.getHost(), traceparent, tracestate, id, componentPath, messageId, telemetrySourceTime, this.client.getApiVersion(), telemetry, context); } /** * Retrieves a component from a digital twin. Status codes: * 200 OK * 400 Bad Request * InvalidArgument - The * digital twin id or component path is invalid. * 404 Not Found * DigitalTwinNotFound - The digital twin was not * found. * ComponentNotFound - The component path was not found. * * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param componentPath The name of the DTDL component. * @param digitalTwinsGetComponentOptions Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return any object. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DigitalTwinsGetComponentResponse> getComponentWithResponseAsync( String id, String componentPath, DigitalTwinsGetComponentOptions digitalTwinsGetComponentOptions, Context context) { if (this.client.getHost() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getHost() is required and cannot be null.")); } if (id == null) { return Mono.error(new IllegalArgumentException("Parameter id is required and cannot be null.")); } if (componentPath == null) { return Mono.error(new IllegalArgumentException("Parameter componentPath is required and cannot be null.")); } if (digitalTwinsGetComponentOptions != null) { digitalTwinsGetComponentOptions.validate(); } String traceparentInternal = null; if (digitalTwinsGetComponentOptions != null) { traceparentInternal = digitalTwinsGetComponentOptions.getTraceparent(); } String traceparent = traceparentInternal; String tracestateInternal = null; if (digitalTwinsGetComponentOptions != null) { tracestateInternal = digitalTwinsGetComponentOptions.getTracestate(); } String tracestate = tracestateInternal; return service.getComponent( this.client.getHost(), traceparent, tracestate, id, componentPath, this.client.getApiVersion(), context); } /** * Updates a component on a digital twin. Status codes: * 204 No Content * 400 Bad Request * InvalidArgument - The * digital twin id, component path, or payload is invalid. * JsonPatchInvalid - The JSON Patch provided is invalid. * * ValidationFailed - Applying the patch results in an invalid digital twin. * 404 Not Found * DigitalTwinNotFound * - The digital twin was not found. * 412 Precondition Failed * PreconditionFailed - The precondition check * (If-Match or If-None-Match) failed. * * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param componentPath The name of the DTDL component. * @param patchDocument Array of any. * @param digitalTwinsUpdateComponentOptions Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DigitalTwinsUpdateComponentResponse> updateComponentWithResponseAsync( String id, String componentPath, JsonPatchDocument patchDocument, DigitalTwinsUpdateComponentOptions digitalTwinsUpdateComponentOptions, Context context) { if (this.client.getHost() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getHost() is required and cannot be null.")); } if (id == null) { return Mono.error(new IllegalArgumentException("Parameter id is required and cannot be null.")); } if (componentPath == null) { return Mono.error(new IllegalArgumentException("Parameter componentPath is required and cannot be null.")); } if (patchDocument == null) { return Mono.error(new IllegalArgumentException("Parameter patchDocument is required and cannot be null.")); } if (digitalTwinsUpdateComponentOptions != null) { digitalTwinsUpdateComponentOptions.validate(); } String traceparentInternal = null; if (digitalTwinsUpdateComponentOptions != null) { traceparentInternal = digitalTwinsUpdateComponentOptions.getTraceparent(); } String traceparent = traceparentInternal; String tracestateInternal = null; if (digitalTwinsUpdateComponentOptions != null) { tracestateInternal = digitalTwinsUpdateComponentOptions.getTracestate(); } String tracestate = tracestateInternal; String ifMatchInternal = null; if (digitalTwinsUpdateComponentOptions != null) { ifMatchInternal = digitalTwinsUpdateComponentOptions.getIfMatch(); } String ifMatch = ifMatchInternal; return service.updateComponent( this.client.getHost(), traceparent, tracestate, id, componentPath, ifMatch, this.client.getApiVersion(), patchDocument, context); } /** * Get the next page of items. * * @param nextLink The nextLink parameter. * @param digitalTwinsListRelationshipsOptions Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a collection of relationships which relate digital twins together. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PagedResponse<Object>> listRelationshipsNextSinglePageAsync( String nextLink, DigitalTwinsListRelationshipsOptions digitalTwinsListRelationshipsOptions, Context context) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); } if (this.client.getHost() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getHost() is required and cannot be null.")); } if (digitalTwinsListRelationshipsOptions != null) { digitalTwinsListRelationshipsOptions.validate(); } String traceparentInternal = null; if (digitalTwinsListRelationshipsOptions != null) { traceparentInternal = digitalTwinsListRelationshipsOptions.getTraceparent(); } String traceparent = traceparentInternal; String tracestateInternal = null; if (digitalTwinsListRelationshipsOptions != null) { tracestateInternal = digitalTwinsListRelationshipsOptions.getTracestate(); } String tracestate = tracestateInternal; return service.listRelationshipsNext(nextLink, this.client.getHost(), traceparent, tracestate, context) .map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().getValue(), res.getValue().getNextLink(), null)); } /** * Get the next page of items. * * @param nextLink The nextLink parameter. * @param digitalTwinsListIncomingRelationshipsOptions Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a collection of incoming relationships which relate digital twins together. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PagedResponse<IncomingRelationship>> listIncomingRelationshipsNextSinglePageAsync( String nextLink, DigitalTwinsListIncomingRelationshipsOptions digitalTwinsListIncomingRelationshipsOptions, Context context) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); } if (this.client.getHost() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getHost() is required and cannot be null.")); } if (digitalTwinsListIncomingRelationshipsOptions != null) { digitalTwinsListIncomingRelationshipsOptions.validate(); } String traceparentInternal = null; if (digitalTwinsListIncomingRelationshipsOptions != null) { traceparentInternal = digitalTwinsListIncomingRelationshipsOptions.getTraceparent(); } String traceparent = traceparentInternal; String tracestateInternal = null; if (digitalTwinsListIncomingRelationshipsOptions != null) { tracestateInternal = digitalTwinsListIncomingRelationshipsOptions.getTracestate(); } String tracestate = tracestateInternal; return service.listIncomingRelationshipsNext(nextLink, this.client.getHost(), traceparent, tracestate, context) .map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().getValue(), res.getValue().getNextLink(), null)); } }
23,950
1,615
<reponame>mmdongxin/MLN<gh_stars>1000+ // // MLNUIArrayObserver.h // MLNUI // // Created by <NAME> on 2020/4/30. // #import "MLNUIObserver.h" NS_ASSUME_NONNULL_BEGIN @interface MLNUIArrayObserver : MLNUIObserver - (instancetype)initWithTarget:(NSMutableArray *)target keyPath:(NSString *)keyPath owner:(id)owner; @end NS_ASSUME_NONNULL_END
152
1,861
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. #include <spectrum/codecs/bitmap/BitmapDecompressor.h> #include <spectrum/testutils/TestUtils.h> #include <array> #include <cstddef> #include <memory> #include <string> #include <gtest/gtest.h> namespace facebook { namespace spectrum { namespace codecs { namespace bitmap { namespace test { // // Read // /** A 4 pixel long bitmap with 4 components */ static const std::string sampleBitmap = "\x10\x11\x12\x13\x20\x21\x22\x23\x30\x31\x32\x33\x40\x41\x42\x43"; TEST(plugins_bitmap_BitmapDecompressor, whenReadingRgba_thenScanlinesMatch) { auto source = io::testutils::makeVectorBitmapImageSource( sampleBitmap, image::Specification{ .size = image::Size{2, 2}, .format = image::formats::Bitmap, .pixelSpecification = image::pixel::specifications::RGBA, }); auto decompressor = BitmapDecompressor{source}; image::testutils::assertScanlineRgba( {{0x10, 0x11, 0x12, 0x13}, {0x20, 0x21, 0x22, 0x23}}, decompressor.readScanline().get()); image::testutils::assertScanlineRgba( {{0x30, 0x31, 0x32, 0x33}, {0x40, 0x41, 0x42, 0x43}}, decompressor.readScanline().get()); } TEST(codecs_bitmap_BitmapDecompressor, whenReadingArgb_thenScanlinesMatch) { auto source = io::testutils::makeVectorBitmapImageSource( sampleBitmap, image::Specification{ .size = image::Size{2, 2}, .format = image::formats::Bitmap, .pixelSpecification = image::pixel::specifications::ARGB, }); auto decompressor = BitmapDecompressor{source}; image::testutils::assertScanlineArgb( {{0x13, 0x10, 0x11, 0x12}, {0x13, 0x10, 0x11, 0x12}}, decompressor.readScanline().get()); image::testutils::assertScanlineArgb( {{0x33, 0x30, 0x31, 0x32}, {0x43, 0x40, 0x41, 0x42}}, decompressor.readScanline().get()); } TEST(codecs_bitmap_BitmapDecompressor, whenReadingRgb_thenScanlinesMatch) { auto source = io::testutils::makeVectorBitmapImageSource( sampleBitmap, image::Specification{ .size = image::Size{2, 2}, .format = image::formats::Bitmap, .pixelSpecification = image::pixel::specifications::RGB, }); auto decompressor = BitmapDecompressor{source}; image::testutils::assertScanlineRgb( {{0x11, 0x12, 0x13}, {0x21, 0x22, 0x23}}, decompressor.readScanline().get()); image::testutils::assertScanlineRgb( {{0x31, 0x32, 0x33}, {0x41, 0x42, 0x43}}, decompressor.readScanline().get()); } TEST(codecs_bitmap_BitmapDecompressor, whenReadingGray_thenScanlinesMatch) { const auto sampleGrayBitmap = "\x10\x11\x12\x13"; auto source = io::testutils::makeVectorBitmapImageSource( sampleGrayBitmap, image::Specification{ .size = image::Size{2, 2}, .format = image::formats::Bitmap, .pixelSpecification = image::pixel::specifications::Gray, }); auto decompressor = BitmapDecompressor{source}; image::testutils::assertScanlineGray( {{0x10}, {0x11}}, decompressor.readScanline().get()); image::testutils::assertScanlineGray( {{0x12}, {0x13}}, decompressor.readScanline().get()); } TEST(codecs_bitmap_BitmapDecompressor, whenReadingTooMuch_thenThrow) { auto source = io::testutils::makeVectorBitmapImageSource( sampleBitmap, image::Specification{ .size = image::Size{2, 2}, .format = image::formats::Bitmap, .pixelSpecification = image::pixel::specifications::RGBA, }); auto decompressor = BitmapDecompressor{source}; decompressor.readScanline(); decompressor.readScanline(); ASSERT_THROW(decompressor.readScanline(), SpectrumException); } } // namespace test } // namespace bitmap } // namespace codecs } // namespace spectrum } // namespace facebook
1,580
575
<filename>services/data_decoder/web_bundler.cc // 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/data_decoder/web_bundler.h" #include "base/big_endian.h" #include "base/numerics/safe_conversions.h" #include "base/strings/string_piece.h" #include "web_bundle_builder.h" namespace data_decoder { // WebBundler does not permit body size larder than ~1GB. const uint64_t kMaxBodySize = (1 << 30); WebBundler::WebBundler() = default; WebBundler::~WebBundler() = default; void WebBundler::Generate( std::vector<mojo::PendingRemote<mojom::ResourceSnapshotForWebBundle>> snapshots, base::File file, GenerateCallback callback) { DCHECK(snapshots_.empty()); DCHECK(!snapshots.empty()); for (auto& pending_snapshot : snapshots) { mojo::Remote<mojom::ResourceSnapshotForWebBundle> snapshot( std::move(pending_snapshot)); snapshot.set_disconnect_handler( base::BindOnce(&WebBundler::OnConnectionError, base::Unretained(this))); snapshots_.emplace_back(std::move(snapshot)); } file_ = std::move(file); callback_ = std::move(callback); GetNextResourceCount(); } void WebBundler::OnConnectionError() { if (callback_) { std::move(callback_).Run(0, mojom::WebBundlerError::kConnectionError); } } void WebBundler::GetNextResourceCount() { if (snapshots_.size() == resources_.size()) { WriteWebBundleIndex(); return; } snapshots_[resources_.size()]->GetResourceCount( base::BindOnce(&WebBundler::OnGetResourceCount, base::Unretained(this))); } void WebBundler::OnGetResourceCount(uint64_t count) { pending_resource_count_ = count; resources_.emplace_back(); bodies_.emplace_back(); GetNextResourceInfo(); } void WebBundler::GetNextResourceInfo() { if (pending_resource_count_ == 0) { GetNextResourceCount(); return; } snapshots_[resources_.size() - 1]->GetResourceInfo( resources_.rbegin()->size(), base::BindOnce(&WebBundler::OnGetResourceInfo, base::Unretained(this))); } void WebBundler::OnGetResourceInfo(mojom::SerializedResourceInfoPtr info) { resources_.rbegin()->emplace_back(std::move(info)); snapshots_[bodies_.size() - 1]->GetResourceBody( bodies_.rbegin()->size(), base::BindOnce(&WebBundler::OnGetResourceBody, base::Unretained(this))); } void WebBundler::OnGetResourceBody(base::Optional<mojo_base::BigBuffer> body) { if (body->size() > kMaxBodySize) { std::move(callback_).Run(0, mojom::WebBundlerError::kInvalidInput); return; } bodies_.rbegin()->emplace_back(std::move(body)); --pending_resource_count_; GetNextResourceInfo(); } void WebBundler::WriteWebBundleIndex() { if (!callback_) { return; } GURL url = resources_[0][0]->url; GURL::Replacements replacements; replacements.ClearRef(); url = url.ReplaceComponents(replacements); WebBundleBuilder builder(url.spec()); std::set<GURL> url_set; CHECK_EQ(resources_.size(), bodies_.size()); std::vector<mojom::SerializedResourceInfoPtr> resources; std::vector<base::Optional<mojo_base::BigBuffer>> bodies; for (size_t i = 0; i < resources_.size(); ++i) { auto& info_list = resources_[i]; auto& body_list = bodies_[i]; CHECK_EQ(info_list.size(), body_list.size()); for (size_t j = 0; j < info_list.size(); ++j) { auto& info = info_list[j]; auto& body = body_list[j]; if (url_set.find(info->url) == url_set.end() && info->url.is_valid() && info->url.SchemeIsHTTPOrHTTPS()) { url_set.insert(info->url); resources.emplace_back(std::move(info)); bodies.emplace_back(std::move(body)); } } } std::vector<uint8_t> bundle = builder.CreateBundle(std::move(resources), std::move(bodies)); int written_size = file_.WriteAtCurrentPos( reinterpret_cast<const char*>(bundle.data()), bundle.size()); DCHECK_EQ(static_cast<int>(bundle.size()), written_size); std::move(callback_).Run(written_size, mojom::WebBundlerError::kOK); } } // namespace data_decoder
1,558
831
<filename>android/testSrc/com/android/tools/idea/editors/strings/table/NeedsTranslationForLocaleRowFilterTest.java /* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.editors.strings.table; import com.android.tools.idea.editors.strings.StringResource; import com.android.tools.idea.editors.strings.StringResourceData; import com.android.tools.idea.editors.strings.StringResourceKey; import com.android.tools.idea.editors.strings.StringResourceRepository; import com.android.tools.idea.rendering.Locale; import java.util.Collections; import javax.swing.RowFilter.Entry; import org.jetbrains.android.AndroidTestCase; import org.jetbrains.annotations.NotNull; import org.mockito.Mockito; public final class NeedsTranslationForLocaleRowFilterTest extends AndroidTestCase { public void testInclude() { assertFalse(new NeedsTranslationForLocaleRowFilter(Locale.create("ar")).include(mockEntry())); } @NotNull private Entry<StringResourceTableModel, Integer> mockEntry() { StringResourceKey key = new StringResourceKey("key", null); StringResourceRepository repository = Mockito.mock(StringResourceRepository.class); Mockito.when(repository.getItems(key)).thenReturn(Collections.emptyList()); StringResource resource = new StringResource(key, StringResourceData.create(myModule.getProject(), repository)); resource.setTranslatable(false); StringResourceTableModel model = Mockito.mock(StringResourceTableModel.class); Mockito.when(model.getStringResourceAt(0)).thenReturn(resource); @SuppressWarnings("unchecked") Entry<StringResourceTableModel, Integer> entry = (Entry<StringResourceTableModel, Integer>)Mockito.mock(Entry.class); Mockito.when(entry.getModel()).thenReturn(model); Mockito.when(entry.getIdentifier()).thenReturn(0); return entry; } }
713
23,901
<gh_stars>1000+ # coding=utf-8 # Copyright 2021 The Google Research Authors. # # 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. """Computes the intrinsic image decomposition of a stack.""" import tensorflow.compat.v1 as tf from factorize_a_city.libs import image_alignment from factorize_a_city.libs import network from factorize_a_city.libs import stack_io from factorize_a_city.libs import utils tf.flags.DEFINE_string( "stack_folder", "", "Folder containing input panoramas of the same scene. " "Produces reflectance and shadings of the stack.") tf.flags.DEFINE_string("output_dir", "intrinsic_image_results", "Where to save the results.") FLAGS = tf.flags.FLAGS def main(unused_argv): if not FLAGS.stack_folder: raise ValueError("stack_folder was not defined") (pano_stack, alignment_params) = stack_io.read_stack(FLAGS.stack_folder) # [0, 1]-ranged panoramas of shape [384, 960]. pano_stack = tf.constant(pano_stack, dtype=tf.float32) alignment_params = tf.constant(alignment_params, dtype=tf.float32) # Align images using parameters. alignment_module = image_alignment.ImageAlignment(regularization=0.3) aligned_stack = alignment_module.align_images(pano_stack, alignment_params) factorize_model = network.FactorizeEncoderDecoder( { "lighting_dim": 32, "permanent_dim": 16 }, is_training=False) stack_factors = factorize_model.compute_decomposition( aligned_stack, single_image_decomposition=False, average_stack=True) # Restore factorization network weights from ckpt. tf.train.init_from_checkpoint("./factorize_a_city/ckpt/factorize_model.ckpt", {"decomp_internal/": "decomp_internal/"}) sess = tf.Session() sess.run(tf.global_variables_initializer()) log_shading, log_reflectance = sess.run( [stack_factors["log_shading"], stack_factors["log_reflectance"]]) stack_io.write_stack_images( FLAGS.output_dir, utils.outlier_normalization(log_shading), prefix="log_shading") stack_io.write_stack_images( FLAGS.output_dir, utils.outlier_normalization(log_reflectance), prefix="log_reflectance") if __name__ == "__main__": # spectral normalization does not work with TF2.0 tf.disable_eager_execution() tf.app.run(main)
1,002
3,083
// Copyright 2011-2016 Google LLC // // 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. package com.google.security.zynamics.binnavi.Database.NodeParser; import java.util.ArrayList; import java.util.HashMap; import com.google.security.zynamics.binnavi.Database.Interfaces.SQLProvider; import com.google.security.zynamics.binnavi.disassembly.CInstruction; import com.google.security.zynamics.binnavi.disassembly.COperandTree; import com.google.security.zynamics.binnavi.disassembly.COperandTreeNode; import com.google.security.zynamics.binnavi.disassembly.INaviModule; import com.google.security.zynamics.binnavi.disassembly.types.TypeInstanceContainer; import com.google.security.zynamics.binnavi.disassembly.types.TypeManager; import com.google.security.zynamics.zylib.disassembly.IAddress; /** * Turns instruction data from the database into a proper instruction object. */ public final class InstructionConverter { private InstructionConverter() { // You are not supposed to instantiate this class } /** * Converts a raw operand tree into a proper operand tree. * * @param rawTree The raw operand tree. * @param provider The connection to the database. * @param module * * @return The proper operand tree. */ private static COperandTree generateTree( final OperandTree rawTree, final SQLProvider provider, final INaviModule module) { final ArrayList<COperandTreeNode> realNodes = new ArrayList<COperandTreeNode>(); final HashMap<COperandTreeNode, OperandTreeNode> realToRawMapping = new HashMap<COperandTreeNode, OperandTreeNode>(); final HashMap<Integer, COperandTreeNode> idToRealMapping = new HashMap<Integer, COperandTreeNode>(); COperandTreeNode root = null; final TypeManager typeManager = module.getTypeManager(); final TypeInstanceContainer instanceContainer = module.getContent().getTypeInstanceContainer(); for (final OperandTreeNode rawNode : rawTree.getNodes()) { final COperandTreeNode node = new COperandTreeNode( rawNode.getId(), rawNode.getType(), rawNode.getValue(), rawNode.getReplacement(), rawNode.getReferences(), provider, typeManager, instanceContainer); if (rawNode.getTypeSubstitution() != null) { typeManager.initializeTypeSubstitution(node, rawNode.getTypeSubstitution()); } if (rawNode.getTypeInstanceId() != null) { instanceContainer.initializeTypeInstanceReference( rawNode.getAddress(), rawNode.getPosition(), rawNode.getId(), node); } realToRawMapping.put(node, rawNode); idToRealMapping.put(rawNode.getId(), node); if (rawNode.getParentId() == null) { root = node; } realNodes.add(node); } for (final COperandTreeNode realNode : realNodes) { // Link the real nodes here. // To link two real nodes, it is necessary to know // which node is the parent and which node is the // child. final OperandTreeNode rawNode = realToRawMapping.get(realNode); final Integer parentId = rawNode.getParentId(); if (parentId == null) { continue; } final COperandTreeNode realParent = idToRealMapping.get(parentId); COperandTreeNode.link(realParent, realNode); } return new COperandTree(root, provider, typeManager, instanceContainer); } /** * This line creates an instruction from the information of a raw instruction line. * * @param line The instruction line. * @param provider The connection to the database. * * @return The instruction object generated from the instruction line. */ public static CInstruction createInstruction( final InstructionLine line, final SQLProvider provider) { final ArrayList<COperandTree> operands = new ArrayList<COperandTree>(); final INaviModule module = line.getModule(); for (final OperandTree rawTree : line.getOperands()) { operands.add(generateTree(rawTree, provider, module)); } final IAddress address = line.getAddress(); final String mnemonic = line.getMnemonic(); final String architecture = line.getArchitecture(); final CInstruction instruction = new CInstruction( true, module, address, mnemonic, operands, line.getData(), architecture, provider); return instruction; } }
1,569
1,155
# Copyright 2019 The PlaNet Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname( os.path.abspath(__file__))))) import tensorflow as tf from planet import tools from planet.scripts import train class PlanetTest(tf.test.TestCase): def test_dummy_isolate_none(self): args = tools.AttrDict( logdir=self.get_temp_dir(), num_runs=1, config='debug', params=tools.AttrDict( task='dummy', isolate_envs='none', max_steps=30), ping_every=0, resume_runs=False) try: tf.app.run(lambda _: train.main(args), [sys.argv[0]]) except SystemExit: pass def test_dummy_isolate_thread(self): args = tools.AttrDict( logdir=self.get_temp_dir(), num_runs=1, config='debug', params=tools.AttrDict( task='dummy', isolate_envs='thread', max_steps=30), ping_every=0, resume_runs=False) try: tf.app.run(lambda _: train.main(args), [sys.argv[0]]) except SystemExit: pass def test_dummy_isolate_process(self): args = tools.AttrDict( logdir=self.get_temp_dir(), num_runs=1, config='debug', params=tools.AttrDict( task='dummy', isolate_envs='process', max_steps=30), ping_every=0, resume_runs=False) try: tf.app.run(lambda _: train.main(args), [sys.argv[0]]) except SystemExit: pass def test_dm_control_isolate_none(self): args = tools.AttrDict( logdir=self.get_temp_dir(), num_runs=1, config='debug', params=tools.AttrDict( task='cup_catch', isolate_envs='none', max_steps=30), ping_every=0, resume_runs=False) try: tf.app.run(lambda _: train.main(args), [sys.argv[0]]) except SystemExit: pass def test_dm_control_isolate_thread(self): args = tools.AttrDict( logdir=self.get_temp_dir(), num_runs=1, config='debug', params=tools.AttrDict( task='cup_catch', isolate_envs='thread', max_steps=30), ping_every=0, resume_runs=False) try: tf.app.run(lambda _: train.main(args), [sys.argv[0]]) except SystemExit: pass def test_dm_control_isolate_process(self): args = tools.AttrDict( logdir=self.get_temp_dir(), num_runs=1, config='debug', params=tools.AttrDict( task='cup_catch', isolate_envs='process', max_steps=30), ping_every=0, resume_runs=False) try: tf.app.run(lambda _: train.main(args), [sys.argv[0]]) except SystemExit: pass if __name__ == '__main__': tf.test.main()
1,634
398
package com.ruiyun.example; import com.ruiyun.jvppeteer.util.StreamUtil; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class ArchiveZipFileExample { public static void main(String[] args) throws IOException { extractZip("D:\\develop\\softwarePackage\\chrome-win.zip","D:\\develop\\softwarePackage"); } private static void extractZip(String archivePath, String folderPath) throws IOException { BufferedOutputStream wirter = null; BufferedInputStream reader = null; ZipFile zipFile = new ZipFile(archivePath); Enumeration<? extends ZipEntry> entries = zipFile.entries(); try { while (entries.hasMoreElements()){ ZipEntry zipEntry = entries.nextElement(); String name = zipEntry.getName(); Path path = Paths.get(folderPath, name); if (zipEntry.isDirectory()){ path.toFile().mkdirs(); }else{ reader = new BufferedInputStream(zipFile.getInputStream(zipEntry)); int bufferSize = 8192; int perReadcount = -1; byte[] buffer = new byte[bufferSize]; wirter = new BufferedOutputStream(new FileOutputStream(path.toString())); while((perReadcount = reader.read(buffer,0,bufferSize)) != -1){ wirter.write(buffer, 0, perReadcount); } wirter.flush(); } } } finally { StreamUtil.closeQuietly(wirter); StreamUtil.closeQuietly(reader); zipFile.close(); } } }
890
428
#include <stdlib.h> #include <ctype.h> #include <stdio.h> #include "agg_basics.h" #include "agg_rendering_buffer.h" #include "agg_rasterizer_scanline_aa.h" #include "agg_scanline_u.h" #include "agg_renderer_scanline.h" #include "agg_path_storage.h" #include "agg_conv_transform.h" #include "agg_trans_affine.h" #include "agg_trans_bilinear.h" #include "agg_trans_perspective.h" #include "agg_span_allocator.h" #include "agg_span_interpolator_linear.h" #include "agg_span_interpolator_trans.h" #include "agg_span_subdiv_adaptor.h" #include "agg_pixfmt_rgba.h" #include "agg_image_accessors.h" #include "agg_span_image_filter_rgba.h" #include "ctrl/agg_rbox_ctrl.h" #include "platform/agg_platform_support.h" #include "interactive_polygon.h" #define AGG_BGRA32 //#define AGG_BGRA128 #include "pixel_formats.h" enum flip_y_e { flip_y = true }; agg::rasterizer_scanline_aa<> g_rasterizer; agg::scanline_u8 g_scanline; double g_x1 = 0; double g_y1 = 0; double g_x2 = 0; double g_y2 = 0; class the_application : public agg::platform_support { public: typedef agg::renderer_base<pixfmt> renderer_base; typedef agg::renderer_scanline_aa_solid<renderer_base> renderer_solid; typedef agg::renderer_base<pixfmt_pre> renderer_base_pre; agg::interactive_polygon m_quad; agg::rbox_ctrl<color_type> m_trans_type; the_application(agg::pix_format_e format, bool flip_y) : agg::platform_support(format, flip_y), m_quad(4, 5.0), m_trans_type(420, 5.0, 420+170.0, 70.0, !flip_y) { m_trans_type.add_item("Affine Parallelogram"); m_trans_type.add_item("Bilinear"); m_trans_type.add_item("Perspective"); m_trans_type.cur_item(2); add_ctrl(m_trans_type); } virtual void on_init() { double d = 0.0; g_x1 = d; g_y1 = d; g_x2 = rbuf_img(0).width() - d; g_y2 = rbuf_img(0).height() - d; m_quad.xn(0) = 100; m_quad.yn(0) = 100; m_quad.xn(1) = width() - 100; m_quad.yn(1) = 100; m_quad.xn(2) = width() - 100; m_quad.yn(2) = height() - 100; m_quad.xn(3) = 100; m_quad.yn(3) = height() - 100; } virtual void on_draw() { pixfmt pixf(rbuf_window()); pixfmt_pre pixf_pre(rbuf_window()); renderer_base rb(pixf); renderer_base_pre rb_pre(pixf_pre); renderer_solid r(rb); rb.clear(agg::rgba(1, 1, 1)); if(m_trans_type.cur_item() == 0) { // For the affine parallelogram transformations we // calculate the 4-th (implicit) point of the parallelogram m_quad.xn(3) = m_quad.xn(0) + (m_quad.xn(2) - m_quad.xn(1)); m_quad.yn(3) = m_quad.yn(0) + (m_quad.yn(2) - m_quad.yn(1)); } //-------------------------- // Render the "quad" tool and controls g_rasterizer.add_path(m_quad); agg::render_scanlines_aa_solid(g_rasterizer, g_scanline, rb, agg::rgba(0, 0.3, 0.5, 0.6)); // Prepare the polygon to rasterize. Here we need to fill // the destination (transformed) polygon. g_rasterizer.clip_box(0, 0, width(), height()); g_rasterizer.reset(); g_rasterizer.move_to_d(m_quad.xn(0), m_quad.yn(0)); g_rasterizer.line_to_d(m_quad.xn(1), m_quad.yn(1)); g_rasterizer.line_to_d(m_quad.xn(2), m_quad.yn(2)); g_rasterizer.line_to_d(m_quad.xn(3), m_quad.yn(3)); agg::span_allocator<color_type> sa; agg::image_filter_bilinear filter_kernel; agg::image_filter_lut filter(filter_kernel, false); pixfmt pixf_img(rbuf_img(0)); //typedef agg::image_accessor_wrap<pixfmt, // agg::wrap_mode_reflect, // agg::wrap_mode_reflect> img_accessor_type; //img_accessor_type ia(pixf_img); //typedef agg::image_accessor_clip<pixfmt> img_accessor_type; //img_accessor_type ia(pixf_img, agg::rgba(1,1,1)); typedef agg::image_accessor_clone<pixfmt> img_accessor_type; img_accessor_type ia(pixf_img); start_timer(); switch(m_trans_type.cur_item()) { case 0: { // Note that we consruct an affine matrix that transforms // a parallelogram to a rectangle, i.e., it's inverted. // It's actually the same as: // tr(g_x1, g_y1, g_x2, g_y2, m_triangle.polygon()); // tr.invert(); agg::trans_affine tr(m_quad.polygon(), g_x1, g_y1, g_x2, g_y2); // Also note that we can use the linear interpolator instead of // arbitrary span_interpolator_trans. It works much faster, // but the transformations must be linear and parellel. typedef agg::span_interpolator_linear<agg::trans_affine> interpolator_type; interpolator_type interpolator(tr); typedef agg::span_image_filter_rgba_nn<img_accessor_type, interpolator_type> span_gen_type; span_gen_type sg(ia, interpolator); agg::render_scanlines_aa(g_rasterizer, g_scanline, rb_pre, sa, sg); break; } case 1: { agg::trans_bilinear tr(m_quad.polygon(), g_x1, g_y1, g_x2, g_y2); if(tr.is_valid()) { typedef agg::span_interpolator_linear<agg::trans_bilinear> interpolator_type; interpolator_type interpolator(tr); typedef agg::span_image_filter_rgba_2x2<img_accessor_type, interpolator_type> span_gen_type; span_gen_type sg(ia, interpolator, filter); agg::render_scanlines_aa(g_rasterizer, g_scanline, rb_pre, sa, sg); } break; } case 2: { agg::trans_perspective tr(m_quad.polygon(), g_x1, g_y1, g_x2, g_y2); if(tr.is_valid()) { // Subdivision and linear interpolation (faster, but less accurate) //----------------------- //typedef agg::span_interpolator_linear<agg::trans_perspective> interpolator_type; //typedef agg::span_subdiv_adaptor<interpolator_type> subdiv_adaptor_type; //interpolator_type interpolator(tr); //subdiv_adaptor_type subdiv_adaptor(interpolator); // //typedef agg::span_image_filter_rgba_2x2<img_accessor_type, // subdiv_adaptor_type> span_gen_type; //span_gen_type sg(ia, subdiv_adaptor, filter); //----------------------- // Direct calculations of the coordinates //----------------------- typedef agg::span_interpolator_trans<agg::trans_perspective> interpolator_type; interpolator_type interpolator(tr); typedef agg::span_image_filter_rgba_2x2<img_accessor_type, interpolator_type> span_gen_type; span_gen_type sg(ia, interpolator, filter); //----------------------- agg::render_scanlines_aa(g_rasterizer, g_scanline, rb_pre, sa, sg); } break; } } double tm = elapsed_time(); char buf[128]; agg::gsv_text t; t.size(10.0); agg::conv_stroke<agg::gsv_text> pt(t); pt.width(1.5); sprintf(buf, "%3.2f ms", tm); t.start_point(10.0, 10.0); t.text(buf); g_rasterizer.add_path(pt); agg::render_scanlines_aa_solid(g_rasterizer, g_scanline, rb, agg::rgba(0,0,0)); //-------------------------- agg::render_ctrl(g_rasterizer, g_scanline, rb, m_trans_type); } virtual void on_mouse_button_down(int x, int y, unsigned flags) { if(flags & agg::mouse_left) { if(m_quad.on_mouse_button_down(x, y)) { force_redraw(); } } } virtual void on_mouse_move(int x, int y, unsigned flags) { if(flags & agg::mouse_left) { if(m_quad.on_mouse_move(x, y)) { force_redraw(); } } if((flags & agg::mouse_left) == 0) { on_mouse_button_up(x, y, flags); } } virtual void on_mouse_button_up(int x, int y, unsigned flags) { if(m_quad.on_mouse_button_up(x, y)) { force_redraw(); } } }; int agg_main(int argc, char* argv[]) { the_application app(pix_format, flip_y); app.caption("AGG Example. Image Perspective Transformations"); const char* img_name = "spheres"; if(argc >= 2) img_name = argv[1]; if(!app.load_img(0, img_name)) { char buf[256]; if(strcmp(img_name, "spheres") == 0) { sprintf(buf, "File not found: %s%s. Download http://www.antigrain.com/%s%s\n" "or copy it from another directory if available.", img_name, app.img_ext(), img_name, app.img_ext()); } else { sprintf(buf, "File not found: %s%s", img_name, app.img_ext()); } app.message(buf); return 1; } /* // Testing the "black border" issue with alpha channel //---------------------------------------- the_application::pixfmt pixf(app.rbuf_img(0)); the_application::renderer_base rbase(pixf); rbase.clear(agg::srgba8(0,0,0,0)); unsigned i; for(i = 0; i < 50; i++) { agg::ellipse ell(rand() % rbase.width(), rand() % rbase.height(), rand() % 20 + 5, rand() % 20 + 5, 100); g_rasterizer.add_path(ell); agg::render_scanlines_aa_solid(g_rasterizer, g_scanline, rbase, agg::srgba8((rand() & 0x7F) + 127, (rand() & 0x7F) + 127, (rand() & 0x7F) + 127, 255)); } */ if(app.init(600, 600, agg::window_resize)) { return app.run(); } return 1; }
6,035
879
<reponame>luiz158/Hibernate-SpringBoot<gh_stars>100-1000 package com.bookstore.dao; import com.bookstore.dto.AuthorDto; import com.bookstore.transformer.AuthorBookTransformer; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; @Repository public class Dao implements AuthorDao { @PersistenceContext private EntityManager entityManager; @Override @Transactional(readOnly = true) public List<AuthorDto> fetchAuthorWithBook() { Query query = entityManager .createNativeQuery( "SELECT a.id AS author_id, a.name AS name, a.age AS age, " + "b.id AS book_id, b.title AS title " + "FROM author a JOIN book b ON a.id=b.author_id") .unwrap(org.hibernate.query.NativeQuery.class) .setResultTransformer(new AuthorBookTransformer()); List<AuthorDto> authors = query.getResultList(); return authors; } }
479
14,425
<reponame>bzhaoopenstack/hadoop /** * 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. */ package org.apache.hadoop.yarn.conf; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.junit.Before; import org.junit.Test; import java.util.Collection; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class TestHAUtil { private Configuration conf; private static final String RM1_ADDRESS_UNTRIMMED = " \t\t\n 1.2.3.4:8021 \n\t "; private static final String RM1_ADDRESS = RM1_ADDRESS_UNTRIMMED.trim(); private static final String RM2_ADDRESS = "localhost:8022"; private static final String RM3_ADDRESS = "localhost:8033"; private static final String RM1_NODE_ID_UNTRIMMED = "rm1 "; private static final String RM1_NODE_ID = RM1_NODE_ID_UNTRIMMED.trim(); private static final String RM2_NODE_ID = "rm2"; private static final String RM3_NODE_ID = "rm3"; private static final String RM_INVALID_NODE_ID = ".rm"; private static final String RM_NODE_IDS_UNTRIMMED = RM1_NODE_ID_UNTRIMMED + "," + RM2_NODE_ID; private static final String RM_NODE_IDS = RM1_NODE_ID + "," + RM2_NODE_ID; @Before public void setUp() { conf = new Configuration(); conf.set(YarnConfiguration.RM_HA_IDS, RM_NODE_IDS_UNTRIMMED); conf.set(YarnConfiguration.RM_HA_ID, RM1_NODE_ID_UNTRIMMED); for (String confKey : YarnConfiguration.getServiceAddressConfKeys(conf)) { // configuration key itself cannot contains space/tab/return chars. conf.set(HAUtil.addSuffix(confKey, RM1_NODE_ID), RM1_ADDRESS_UNTRIMMED); conf.set(HAUtil.addSuffix(confKey, RM2_NODE_ID), RM2_ADDRESS); } } @Test public void testGetRMServiceId() throws Exception { conf.set(YarnConfiguration.RM_HA_IDS, RM1_NODE_ID + "," + RM2_NODE_ID); Collection<String> rmhaIds = HAUtil.getRMHAIds(conf); assertEquals(2, rmhaIds.size()); String[] ids = rmhaIds.toArray(new String[0]); assertEquals(RM1_NODE_ID, ids[0]); assertEquals(RM2_NODE_ID, ids[1]); } @Test public void testGetRMId() throws Exception { conf.set(YarnConfiguration.RM_HA_ID, RM1_NODE_ID); assertEquals("Does not honor " + YarnConfiguration.RM_HA_ID, RM1_NODE_ID, HAUtil.getRMHAId(conf)); conf.clear(); assertNull("Return null when " + YarnConfiguration.RM_HA_ID + " is not set", HAUtil.getRMHAId(conf)); } @Test public void testVerifyAndSetConfiguration() throws Exception { Configuration myConf = new Configuration(conf); try { HAUtil.verifyAndSetConfiguration(myConf); } catch (YarnRuntimeException e) { fail("Should not throw any exceptions."); } assertEquals("Should be saved as Trimmed collection", StringUtils.getStringCollection(RM_NODE_IDS), HAUtil.getRMHAIds(myConf)); assertEquals("Should be saved as Trimmed string", RM1_NODE_ID, HAUtil.getRMHAId(myConf)); for (String confKey : YarnConfiguration.getServiceAddressConfKeys(myConf)) { assertEquals("RPC address not set for " + confKey, RM1_ADDRESS, myConf.get(confKey)); } myConf = new Configuration(conf); myConf.set(YarnConfiguration.RM_HA_IDS, RM1_NODE_ID); try { HAUtil.verifyAndSetConfiguration(myConf); } catch (YarnRuntimeException e) { assertEquals("YarnRuntimeException by verifyAndSetRMHAIds()", HAUtil.BAD_CONFIG_MESSAGE_PREFIX + HAUtil.getInvalidValueMessage(YarnConfiguration.RM_HA_IDS, myConf.get(YarnConfiguration.RM_HA_IDS) + "\nHA mode requires atleast two RMs"), e.getMessage()); } myConf = new Configuration(conf); // simulate the case YarnConfiguration.RM_HA_ID is not set myConf.set(YarnConfiguration.RM_HA_IDS, RM1_NODE_ID + "," + RM2_NODE_ID); for (String confKey : YarnConfiguration.getServiceAddressConfKeys(myConf)) { myConf.set(HAUtil.addSuffix(confKey, RM1_NODE_ID), RM1_ADDRESS); myConf.set(HAUtil.addSuffix(confKey, RM2_NODE_ID), RM2_ADDRESS); } try { HAUtil.verifyAndSetConfiguration(myConf); } catch (YarnRuntimeException e) { assertEquals("YarnRuntimeException by getRMId()", HAUtil.BAD_CONFIG_MESSAGE_PREFIX + HAUtil.getNeedToSetValueMessage(YarnConfiguration.RM_HA_ID), e.getMessage()); } myConf = new Configuration(conf); myConf.set(YarnConfiguration.RM_HA_ID, RM_INVALID_NODE_ID); myConf.set(YarnConfiguration.RM_HA_IDS, RM_INVALID_NODE_ID + "," + RM1_NODE_ID); for (String confKey : YarnConfiguration.getServiceAddressConfKeys(myConf)) { // simulate xml with invalid node id myConf.set(confKey + RM_INVALID_NODE_ID, RM_INVALID_NODE_ID); } try { HAUtil.verifyAndSetConfiguration(myConf); } catch (YarnRuntimeException e) { assertEquals("YarnRuntimeException by addSuffix()", HAUtil.BAD_CONFIG_MESSAGE_PREFIX + HAUtil.getInvalidValueMessage(YarnConfiguration.RM_HA_ID, RM_INVALID_NODE_ID), e.getMessage()); } myConf = new Configuration(); // simulate the case HAUtil.RM_RPC_ADDRESS_CONF_KEYS are not set myConf.set(YarnConfiguration.RM_HA_ID, RM1_NODE_ID); myConf.set(YarnConfiguration.RM_HA_IDS, RM1_NODE_ID + "," + RM2_NODE_ID); try { HAUtil.verifyAndSetConfiguration(myConf); fail("Should throw YarnRuntimeException. by Configuration#set()"); } catch (YarnRuntimeException e) { String confKey = HAUtil.addSuffix(YarnConfiguration.RM_ADDRESS, RM1_NODE_ID); assertEquals("YarnRuntimeException by Configuration#set()", HAUtil.BAD_CONFIG_MESSAGE_PREFIX + HAUtil.getNeedToSetValueMessage( HAUtil.addSuffix(YarnConfiguration.RM_HOSTNAME, RM1_NODE_ID) + " or " + confKey), e.getMessage()); } // simulate the case YarnConfiguration.RM_HA_IDS doesn't contain // the value of YarnConfiguration.RM_HA_ID myConf = new Configuration(conf); myConf.set(YarnConfiguration.RM_HA_IDS, RM2_NODE_ID + "," + RM3_NODE_ID); myConf.set(YarnConfiguration.RM_HA_ID, RM1_NODE_ID_UNTRIMMED); for (String confKey : YarnConfiguration.getServiceAddressConfKeys(myConf)) { myConf.set(HAUtil.addSuffix(confKey, RM1_NODE_ID), RM1_ADDRESS_UNTRIMMED); myConf.set(HAUtil.addSuffix(confKey, RM2_NODE_ID), RM2_ADDRESS); myConf.set(HAUtil.addSuffix(confKey, RM3_NODE_ID), RM3_ADDRESS); } try { HAUtil.verifyAndSetConfiguration(myConf); } catch (YarnRuntimeException e) { assertEquals("YarnRuntimeException by getRMId()'s validation", HAUtil.BAD_CONFIG_MESSAGE_PREFIX + HAUtil.getRMHAIdNeedToBeIncludedMessage("[rm2, rm3]", RM1_NODE_ID), e.getMessage()); } // simulate the case that no leader election is enabled myConf = new Configuration(conf); myConf.setBoolean(YarnConfiguration.RM_HA_ENABLED, true); myConf.setBoolean(YarnConfiguration.AUTO_FAILOVER_ENABLED, true); myConf.setBoolean(YarnConfiguration.AUTO_FAILOVER_EMBEDDED, false); myConf.setBoolean(YarnConfiguration.CURATOR_LEADER_ELECTOR, false); try { HAUtil.verifyAndSetConfiguration(myConf); } catch (YarnRuntimeException e) { assertEquals("YarnRuntimeException by getRMId()'s validation", HAUtil.BAD_CONFIG_MESSAGE_PREFIX + HAUtil.NO_LEADER_ELECTION_MESSAGE, e.getMessage()); } } @Test public void testGetConfKeyForRMInstance() { assertTrue("RM instance id is not suffixed", HAUtil.getConfKeyForRMInstance(YarnConfiguration.RM_ADDRESS, conf) .contains(HAUtil.getRMHAId(conf))); assertFalse("RM instance id is suffixed", HAUtil.getConfKeyForRMInstance(YarnConfiguration.NM_ADDRESS, conf) .contains(HAUtil.getRMHAId(conf))); } }
3,546
429
/* * (C) Copyright 2011,2016-2020 Intel Corporation. * * SPDX-License-Identifier: BSD-2-Clause-Patent */ /* GURT heap (bin heap) APIs. */ #ifndef __GURT_HEAP_H__ #define __GURT_HEAP_H__ #include <pthread.h> #include <stdint.h> #include <string.h> #include <stdbool.h> #include <gurt/common.h> #if defined(__cplusplus) extern "C" { #endif /** * \file * * Binary heap * * The binary heap is a scalable data structure created using a binary tree. It * is capable of maintaining large sets of objects sorted usually by one or * more object properties. User is required to register a comparison callback * to determine the relevant ordering of any two objects belong to the set. * * There is no traverse operation, rather the intention is for the object of the * lowest priority which will always be at the root of the tree (as this is an * implementation of a min-heap) to be removed by users for consumption. * * Users of the heap should embed a d_binheap_node_t object instance on every * object of the set that they wish the binary heap instance to handle, and * required to provide a d_binheap_ops::hop_compare() implementation which * is used by the heap as the binary predicate during its internal sorting. * * The implementation provides an optional internal lock supporting, user can * select to use its own external lock mechanism as well. */ /** @addtogroup GURT * @{ */ /** * Binary heap node. * * Objects of this type are embedded into objects of the ordered set that is to * be maintained by a struct d_binheap instance. */ struct d_binheap_node { /** Index into the binary tree */ uint32_t chn_idx; }; #define DBH_SHIFT (9) #define DBH_SIZE (1U << DBH_SHIFT) /* #ptrs per level */ #define DBH_MASK (DBH_SIZE - 1) #define DBH_NOB (DBH_SIZE * sizeof(struct d_binheap_node *)) #define DBH_POISON (0xdeadbeef) /** * Binary heap feature bits. */ enum d_bh_feats { /** * By default, the binheap is protected by pthread_mutex. */ /** * The bin heap has no lock, it means the bin heap is protected * by external lock, or only accessed by a single thread. */ DBH_FT_NOLOCK = (1 << 0), /** * It is a read-mostly bin heap, so it is protected by RW lock. */ DBH_FT_RWLOCK = (1 << 1), }; struct d_binheap; /** * Binary heap operations. */ struct d_binheap_ops { /** * Called right before inserting a node into the binary heap. * * Implementing this operation is optional. * * \param[in] h The heap * \param[in] e The node * * \return zero on success, negative value if error */ int (*hop_enter)(struct d_binheap *h, struct d_binheap_node *e); /** * Called right after removing a node from the binary heap. * * Implementing this operation is optional. * * \param[in] h The heap * \param[in] e The node * * \return zero on success, negative value if error */ int (*hop_exit)(struct d_binheap *h, struct d_binheap_node *e); /** * A binary predicate which is called during internal heap sorting, and * used in order to determine the relevant ordering of two heap nodes. * * Implementing this operation is mandatory. * * \param[in] a The first heap node * \param[in] b The second heap node * * \return true if node a < node b, * false if node a > node b. * * \see d_binheap_bubble() and d_biheap_sink() */ bool (*hop_compare)(struct d_binheap_node *a, struct d_binheap_node *b); }; /** * Binary heap. */ struct d_binheap { /** different type of locks based on cbt_feats */ union { pthread_mutex_t d_bh_mutex; pthread_rwlock_t d_bh_rwlock; }; /** feature bits */ uint32_t d_bh_feats; /** Triple indirect */ struct d_binheap_node ****d_bh_nodes3; /** double indirect */ struct d_binheap_node ***d_bh_nodes2; /** single indirect */ struct d_binheap_node **d_bh_nodes1; /** operations table */ struct d_binheap_ops *d_bh_ops; /** private data */ void *d_bh_priv; /** # elements referenced */ uint32_t d_bh_nodes_cnt; /** high water mark */ uint32_t d_bh_hwm; }; /** * Creates and initializes a binary heap instance. * * \param[in] feats The heap feats bits * \param[in] count The initial heap capacity in # of nodes * \param[in] priv An optional private argument * \param[in] ops The operations to be used * \param[in,out] h The 2nd level pointer of created binheap * * \return zero on success, negative value if error */ int d_binheap_create(uint32_t feats, uint32_t count, void *priv, struct d_binheap_ops *ops, struct d_binheap **h); /** * Creates and initializes a binary heap instance inplace. * * \param[in] feats The heap feats bits * \param[in] count The initial heap capacity in # of nodes * \param[in] priv An optional private argument * \param[in] ops The operations to be used * \param[in,out] h The pointer of binheap * * \return zero on success, negative value if error */ int d_binheap_create_inplace(uint32_t feats, uint32_t count, void *priv, struct d_binheap_ops *ops, struct d_binheap *h); /** * Releases all resources associated with a binary heap instance. * * Deallocates memory for all indirection levels and the binary heap object * itself. * * \param[in] h The binary heap object */ void d_binheap_destroy(struct d_binheap *h); /** * Releases all resources associated with a binary heap instance inplace. * * Deallocates memory for all indirection levels and clear data in binary heap * object as zero. * * \param[in] h The binary heap object */ void d_binheap_destroy_inplace(struct d_binheap *h); /** * Obtains a pointer to a heap node, given its index into the binary tree. * * \param[in] h The binary heap * \param[in] idx The requested node's index * * \return valid-pointer of the requested heap node, * NULL if index is out of bounds */ struct d_binheap_node *d_binheap_find(struct d_binheap *h, uint32_t idx); /** * Sort-inserts a node into the binary heap. * * \param[in] h The heap * \param[in] e The node * * \return 0 if the node inserted successfully * negative value if error */ int d_binheap_insert(struct d_binheap *h, struct d_binheap_node *e); /** * Removes a node from the binary heap. * * \param[in] h The heap * \param[in] e The node */ void d_binheap_remove(struct d_binheap *h, struct d_binheap_node *e); /** * Removes the root node from the binary heap. * * \param[in] h The heap * * \return valid pointer of the removed root node, * or NULL when empty. */ struct d_binheap_node *d_binheap_remove_root(struct d_binheap *h); /** * Queries the size (number of nodes) of the binary heap. * * \param[in] h The heap * * \return positive value of the size, * or -DER_INVAL for NULL heap. */ static inline int d_binheap_size(struct d_binheap *h) { if (h == NULL) { D_ERROR("invalid NULL heap.\n"); return -DER_INVAL; } return h->d_bh_nodes_cnt; } /** * Queries if the binary heap is empty. * * \param[in] h The heap * * \retval true heap is empty (or for NULL heap), * \retval false heap is non-empty. */ static inline bool d_binheap_is_empty(struct d_binheap *h) { if (h == NULL) return true; return h->d_bh_nodes_cnt == 0; } /** * Gets back the root node of the binary heap. * * \param[in] h The heap * * \return valid pointer of the root node, or NULL in error case. */ static inline struct d_binheap_node * d_binheap_root(struct d_binheap *h) { return d_binheap_find(h, 0); } #if defined(__cplusplus) } #endif /** @} */ #endif /* __GURT_HEAP_H__ */
2,719
794
<filename>uncertainty_baselines/models/classifier_utils_test.py # coding=utf-8 # Copyright 2021 The Uncertainty Baselines Authors. # # 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. """Tests for classifier utilities.""" import tensorflow as tf from uncertainty_baselines.models import classifier_utils class ClassifierUtilsTest(tf.test.TestCase): def setUp(self): super().setUp() self.random_seed = 42 self.num_classes = 2 self.batch_size = 4 self.hidden_dim = 8 def test_mpnn_gp_classifier(self): """Tests if GP classifier can be compiled successfully.""" # Compile a mock input model gp_layer_kwargs = dict( num_inducing=1024, gp_kernel_scale=1., gp_output_bias=0., normalize_input=True, gp_cov_momentum=0.999, gp_cov_ridge_penalty=1e-6) # Compiles classifier model. model = classifier_utils.build_classifier( num_classes=self.num_classes, gp_layer_kwargs=gp_layer_kwargs, use_gp_layer=True) # Computes output. tf.random.set_seed(self.random_seed) inputs_tensor = tf.random.normal((self.batch_size, self.hidden_dim)) logits, covmat = model(inputs_tensor, training=False) # Check if output tensors have correct shapes. logits_shape_observed = logits.shape.as_list() covmat_shape_observed = covmat.shape.as_list() logits_shape_expected = [self.batch_size, self.num_classes] covmat_shape_expected = [self.batch_size, self.batch_size] self.assertEqual(logits_shape_observed, logits_shape_expected) self.assertEqual(covmat_shape_observed, covmat_shape_expected) if __name__ == "__main__": tf.test.main()
787
1,441
<gh_stars>1000+ #import <Foundation/Foundation.h> @interface Dock : NSObject { } - (void) setBadge:(NSString*)value; - (NSString *) badge; @property (readwrite, copy) NSString *badge; @end
78
1,337
/* * Copyright (c) 2008-2016 Haulmont. * * 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. * */ package com.haulmont.cuba.gui.data.impl.testmodel1; import com.haulmont.cuba.core.entity.BaseUuidEntity; import javax.persistence.*; import java.util.Objects; @Entity(name = "test$PartEntity") public class TestPartEntity extends BaseUuidEntity { @Column(name = "NAME") private String partName; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "DETAIL_ID") private TestDetailEntity detail; public String getPartName() { return partName; } public void setPartName(String partName) { String o = this.partName; this.partName = partName; if (!Objects.equals(o, partName)) propertyChanged("partName", o, partName); } public TestDetailEntity getDetail() { return detail; } public void setDetail(TestDetailEntity detail) { TestDetailEntity o = this.detail; this.detail = detail; if (!Objects.equals(o, detail)) propertyChanged("detail", o, detail); } }
560
897
/* ___Implement Open Hashing___ Hashing is an important data structure that is used to map a given value with a particular index for faster access of elements. But sometimes more than one value gets mapped with a particular index. This can be resolved using open hashing. In open hashing, keys are stored in linked lists attached to cells of a hash table. */ #include<stdio.h> #include<stdlib.h> #define SIZE 10 struct node { int data; struct node *next; }; //array of pointers struct node *head[SIZE]={NULL},*c; void openDisplay(); void openInsert(); void openSearch(); void main() { //prints the hash function used in the program printf("\nHash function : h(k)=k (mod 10)+1"); int size,i,temp,ch=0; while(ch!=4) { printf("\n"); printf("1.Insert\n2.Search\n3.Display\n4.Exit\n"); printf("Enter your choice : "); scanf("%d",&ch); switch(ch) { case 1: openInsert(); break; case 2: openSearch(); break; case 3: openDisplay(); break; case 4: break; default: printf("Invalid choice\n"); } } } /* This function inserts elements into the hash table. Duplication is not allowed in hash table. We use an array of linked list to store the elements. */ void openInsert() { int i,j,key; printf("Enter the element : "); scanf("%d",&key); i=key%SIZE+1; for(c=head[i];c!=NULL;c=c->next) { if(c->data==key) //checks for duplication { printf("Duplication\n"); return; } } //dynamically allocates memory for the node struct node *newnode=(struct node*)malloc(sizeof(struct node)); newnode->data=key; newnode->next=NULL; //if head is empty then element made as head if(head[i]==NULL) head[i]=newnode; else { c=head[i]; while(c->next!=NULL) c=c->next; c->next=newnode; } } /* This function search for an element in the hash table. The index corresponding to that particular value is found. Search is made in the linked list whose head is at that index of the array. */ void openSearch() { int key,index; printf("Enter the element : "); scanf("%d",&key); index=key%SIZE+1; //finds the index of the key value //checks whether the head of the linked list is empty or not if(head[index]==NULL) printf("Element not found\n"); else { //traverse through the linked list for(c=head[index];c!=NULL;c=c->next) { if(c->data==key) { printf("%d found at index %d\n",key,index); break; } } if(c==NULL) printf("Element not found\n"); } } /* This function displays elements in the hash table. If no element is present the it displays "--" in the column value. */ void openDisplay() { int i; printf("Index\tValue\n"); printf("---------------\n"); for(i=1;i<=SIZE;i++) { if(head[i]==NULL) { printf("%d\t--",i); printf("\n"); continue; } else { c=head[i]; printf("%d\t%d",i,c->data); c=c->next; for(;c!=NULL;c=c->next) printf("->%d",c->data); } printf("\n"); } } /* Sample Input and Output: Hash function : h(k)=k (mod 10)+1 1.Insert 2.Search 3.Display 4.Exit Enter your choice 1 Enter the element : 44 1.Insert 2.Search 3.Display 4.Exit Enter your choice 1 Enter the element : 14 1.Insert 2.Search 3.Display 4.Exit Enter your choice : 1 Enter the element : 12 1.Insert 2.Search 3.Display 4.Exit Enter your choice : 1 Enter the element : 89 1.Insert 2.Search 3.Display 4.Exit Enter your choice : 1 Enter the element : 90 1.Insert 2.Search 3.Display 4.Exit Enter your choice : 1 Enter the element : 11 1.Insert 2.Search 3.Display 4.Exit Enter your choice : 3 Index Key --------------- 1 90 2 11 3 12 4 -- 5 44->14 6 -- 7 -- 8 -- 9 -- 10 89 Time complexity : Insertion - O(1) Deletion - O(1) */
1,994
335
{ "word": "Failure", "definitions": [ "Lack of success.", "An unsuccessful person or thing.", "The neglect or omission of expected or required action.", "A lack or deficiency of a desirable quality.", "The action or state of not functioning.", "A sudden cessation of power.", "The collapse of a business." ], "parts-of-speech": "Noun" }
155
862
/* * (c) Copyright 2018 Palantir Technologies Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.leader; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; import com.google.common.collect.ImmutableMap; import com.google.common.net.HostAndPort; import com.palantir.common.concurrent.CheckedRejectionExecutorService; import com.palantir.paxos.ImmutableLeaderPingerContext; import com.palantir.paxos.LeaderPingResults; import com.palantir.paxos.LeaderPinger; import com.palantir.paxos.SingleLeaderPinger; import com.palantir.sls.versions.OrderableSlsVersion; import java.time.Duration; import java.util.Optional; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class PaxosLeaderEventsTest { private static final UUID LOCAL_UUID = UUID.randomUUID(); private static final UUID REMOTE_UUID = UUID.randomUUID(); private static final HostAndPort HOST_AND_PORT = HostAndPort.fromParts("localhost", 8080); private final ExecutorService executorService = Executors.newSingleThreadExecutor(); @Mock private PingableLeader pingableLeader; @After public void after() { executorService.shutdown(); } @Test public void recordsLeaderPingFailure() { RuntimeException error = new RuntimeException("foo"); when(pingableLeader.pingV2()).thenThrow(error); when(pingableLeader.ping()).thenThrow(error); when(pingableLeader.getUUID()).thenReturn(REMOTE_UUID.toString()); LeaderPinger pinger = pingerWithTimeout(Duration.ofSeconds(10)); assertThat(pinger.pingLeaderWithUuid(REMOTE_UUID)) .isEqualTo(LeaderPingResults.pingCallFailedWithExecutionException(error)); } @Test public void recordsLeaderPingTimeout() { when(pingableLeader.pingV2()).thenAnswer($ -> { Thread.sleep(10_000); return PingResult.builder().isLeader(true).build(); }); when(pingableLeader.getUUID()).thenReturn(REMOTE_UUID.toString()); LeaderPinger pinger = pingerWithTimeout(Duration.ofMillis(100)); assertThat(pinger.pingLeaderWithUuid(REMOTE_UUID)).isEqualTo(LeaderPingResults.pingTimedOut()); } @Test public void recordsLeaderPingReturnedFalse() { when(pingableLeader.pingV2()) .thenReturn(PingResult.builder().isLeader(false).build()); when(pingableLeader.getUUID()).thenReturn(REMOTE_UUID.toString()); LeaderPinger pinger = pingerWithTimeout(Duration.ofSeconds(1)); assertThat(pinger.pingLeaderWithUuid(REMOTE_UUID)).isEqualTo(LeaderPingResults.pingReturnedFalse()); } @Test public void doesNotRecordLeaderPingSuccess() { when(pingableLeader.pingV2()) .thenReturn(PingResult.builder().isLeader(true).build()); when(pingableLeader.getUUID()).thenReturn(REMOTE_UUID.toString()); LeaderPinger pinger = pingerWithTimeout(Duration.ofSeconds(1)); assertThat(pinger.pingLeaderWithUuid(REMOTE_UUID)) .isEqualTo(LeaderPingResults.pingReturnedTrue(REMOTE_UUID, HOST_AND_PORT)); } @Test public void recordsLeaderPingReturnedTrueWithOlderVersion() { OrderableSlsVersion oldTimeLockVersion = OrderableSlsVersion.valueOf("1.1.2"); when(pingableLeader.pingV2()) .thenReturn(PingResult.builder() .isLeader(true) .timeLockVersion(oldTimeLockVersion) .build()); when(pingableLeader.getUUID()).thenReturn(REMOTE_UUID.toString()); LeaderPinger pinger = pingerWithVersion(OrderableSlsVersion.valueOf("2.1.1")); assertThat(pinger.pingLeaderWithUuid(REMOTE_UUID)) .isEqualTo(LeaderPingResults.pingReturnedTrueWithOlderVersion(oldTimeLockVersion)); } @Test public void leaderPingReturnsTrueWithLeaderOnNewerVersion() { when(pingableLeader.pingV2()) .thenReturn(PingResult.builder() .isLeader(true) .timeLockVersion(OrderableSlsVersion.valueOf("2.1.1")) .build()); when(pingableLeader.getUUID()).thenReturn(REMOTE_UUID.toString()); LeaderPinger pinger = pingerWithVersion(OrderableSlsVersion.valueOf("1.1.1")); assertThat(pinger.pingLeaderWithUuid(REMOTE_UUID)) .isEqualTo(LeaderPingResults.pingReturnedTrue(REMOTE_UUID, HOST_AND_PORT)); } private LeaderPinger pingerWithTimeout(Duration leaderPingResponseWait) { return new SingleLeaderPinger( ImmutableMap.of( ImmutableLeaderPingerContext.of(pingableLeader, HOST_AND_PORT), new CheckedRejectionExecutorService(executorService)), leaderPingResponseWait, LOCAL_UUID, true, Optional.empty()); } private LeaderPinger pingerWithVersion(OrderableSlsVersion version) { return new SingleLeaderPinger( ImmutableMap.of( ImmutableLeaderPingerContext.of(pingableLeader, HOST_AND_PORT), new CheckedRejectionExecutorService(executorService)), Duration.ofSeconds(5), LOCAL_UUID, true, Optional.of(version)); } }
2,500
3,200
<gh_stars>1000+ # Copyright 2020 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """grad base functions""" from .._register_for_op import Registry bprop_getters = Registry() bprops = Registry() def get_bprop_fn(prim): """get bprop function by primitive obj or prim name for c++""" out = bprop_getters.get(prim, None) if out: return out(prim) return bprops.get(prim, None)
280
5,986
# This file was automatically generated by SWIG (http://www.swig.org). # Version 4.0.2 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. from sys import version_info as _swig_python_version_info if _swig_python_version_info < (2, 7, 0): raise RuntimeError("Python 2.7 or later required") # Import the low-level C/C++ module if __package__ or "." in __name__: from . import _sentencepiece else: import _sentencepiece try: import builtins as __builtin__ except ImportError: import __builtin__ def _swig_repr(self): try: strthis = "proxy of " + self.this.__repr__() except __builtin__.Exception: strthis = "" return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,) def _swig_setattr_nondynamic_instance_variable(set): def set_instance_attr(self, name, value): if name == "thisown": self.this.own(value) elif name == "this": set(self, name, value) elif hasattr(self, name) and isinstance(getattr(type(self), name), property): set(self, name, value) else: raise AttributeError("You cannot add instance attributes to %s" % self) return set_instance_attr def _swig_setattr_nondynamic_class_variable(set): def set_class_attr(cls, name, value): if hasattr(cls, name) and not isinstance(getattr(cls, name), property): set(cls, name, value) else: raise AttributeError("You cannot add class attributes to %s" % cls) return set_class_attr def _swig_add_metaclass(metaclass): """Class decorator for adding a metaclass to a SWIG wrapped class - a slimmed down version of six.add_metaclass""" def wrapper(cls): return metaclass(cls.__name__, cls.__bases__, cls.__dict__.copy()) return wrapper class _SwigNonDynamicMeta(type): """Meta class to enforce nondynamic attributes (no new attributes) for a class""" __setattr__ = _swig_setattr_nondynamic_class_variable(type.__setattr__) EncoderVersion_kOptimized = _sentencepiece.EncoderVersion_kOptimized EncoderVersion_kOriginal = _sentencepiece.EncoderVersion_kOriginal class SentencePieceProcessor(object): thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): _sentencepiece.SentencePieceProcessor_swiginit(self, _sentencepiece.new_SentencePieceProcessor()) __swig_destroy__ = _sentencepiece.delete_SentencePieceProcessor def LoadFromSerializedProto(self, serialized): return _sentencepiece.SentencePieceProcessor_LoadFromSerializedProto(self, serialized) def SetEncodeExtraOptions(self, extra_option): return _sentencepiece.SentencePieceProcessor_SetEncodeExtraOptions(self, extra_option) def SetDecodeExtraOptions(self, extra_option): return _sentencepiece.SentencePieceProcessor_SetDecodeExtraOptions(self, extra_option) def SetVocabulary(self, valid_vocab): return _sentencepiece.SentencePieceProcessor_SetVocabulary(self, valid_vocab) def ResetVocabulary(self): return _sentencepiece.SentencePieceProcessor_ResetVocabulary(self) def LoadVocabulary(self, filename, threshold): return _sentencepiece.SentencePieceProcessor_LoadVocabulary(self, filename, threshold) def SetEncoderVersion(self, encoder_version): return _sentencepiece.SentencePieceProcessor_SetEncoderVersion(self, encoder_version) def GetEncoderVersion(self): return _sentencepiece.SentencePieceProcessor_GetEncoderVersion(self) def EncodeAsPieces(self, input): return _sentencepiece.SentencePieceProcessor_EncodeAsPieces(self, input) def EncodeAsIds(self, input): return _sentencepiece.SentencePieceProcessor_EncodeAsIds(self, input) def NBestEncodeAsPieces(self, input, nbest_size): return _sentencepiece.SentencePieceProcessor_NBestEncodeAsPieces(self, input, nbest_size) def NBestEncodeAsIds(self, input, nbest_size): return _sentencepiece.SentencePieceProcessor_NBestEncodeAsIds(self, input, nbest_size) def SampleEncodeAsPieces(self, input, nbest_size, alpha): return _sentencepiece.SentencePieceProcessor_SampleEncodeAsPieces(self, input, nbest_size, alpha) def SampleEncodeAsIds(self, input, nbest_size, alpha): return _sentencepiece.SentencePieceProcessor_SampleEncodeAsIds(self, input, nbest_size, alpha) def DecodePieces(self, pieces): return _sentencepiece.SentencePieceProcessor_DecodePieces(self, pieces) def EncodeAsSerializedProto(self, input): return _sentencepiece.SentencePieceProcessor_EncodeAsSerializedProto(self, input) def SampleEncodeAsSerializedProto(self, input, nbest_size, alpha): return _sentencepiece.SentencePieceProcessor_SampleEncodeAsSerializedProto(self, input, nbest_size, alpha) def NBestEncodeAsSerializedProto(self, input, nbest_size): return _sentencepiece.SentencePieceProcessor_NBestEncodeAsSerializedProto(self, input, nbest_size) def DecodePiecesAsSerializedProto(self, pieces): return _sentencepiece.SentencePieceProcessor_DecodePiecesAsSerializedProto(self, pieces) def GetPieceSize(self): return _sentencepiece.SentencePieceProcessor_GetPieceSize(self) def PieceToId(self, piece): return _sentencepiece.SentencePieceProcessor_PieceToId(self, piece) def IdToPiece(self, id): return _sentencepiece.SentencePieceProcessor_IdToPiece(self, id) def GetScore(self, id): return _sentencepiece.SentencePieceProcessor_GetScore(self, id) def IsUnknown(self, id): return _sentencepiece.SentencePieceProcessor_IsUnknown(self, id) def IsControl(self, id): return _sentencepiece.SentencePieceProcessor_IsControl(self, id) def IsUnused(self, id): return _sentencepiece.SentencePieceProcessor_IsUnused(self, id) def IsByte(self, id): return _sentencepiece.SentencePieceProcessor_IsByte(self, id) def unk_id(self): return _sentencepiece.SentencePieceProcessor_unk_id(self) def bos_id(self): return _sentencepiece.SentencePieceProcessor_bos_id(self) def eos_id(self): return _sentencepiece.SentencePieceProcessor_eos_id(self) def pad_id(self): return _sentencepiece.SentencePieceProcessor_pad_id(self) def serialized_model_proto(self): return _sentencepiece.SentencePieceProcessor_serialized_model_proto(self) def LoadFromFile(self, arg): return _sentencepiece.SentencePieceProcessor_LoadFromFile(self, arg) def DecodeIdsWithCheck(self, ids): return _sentencepiece.SentencePieceProcessor_DecodeIdsWithCheck(self, ids) def DecodeIdsAsSerializedProtoWithCheck(self, ids): return _sentencepiece.SentencePieceProcessor_DecodeIdsAsSerializedProtoWithCheck(self, ids) def Init(self, model_file=None, model_proto=None, out_type=int, add_bos=False, add_eos=False, reverse=False, enable_sampling=False, nbest_size=-1, alpha=0.1): """Initialzie sentencepieceProcessor. Args: model_file: The sentencepiece model file path. model_proto: The sentencepiece model serialized proto. out_type: output type. int or str. add_bos: Add <s> to the result (Default = false) add_eos: Add </s> to the result (Default = false) <s>/</s> is added after reversing (if enabled). reverse: Reverses the tokenized sequence (Default = false) nbest_size: sampling parameters for unigram. Invalid for BPE-Dropout. nbest_size = {0,1}: No sampling is performed. nbest_size > 1: samples from the nbest_size results. nbest_size < 0: assuming that nbest_size is infinite and samples from the all hypothesis (lattice) using forward-filtering-and-backward-sampling algorithm. alpha: Soothing parameter for unigram sampling, and dropout probability of merge operations for BPE-dropout. """ _sentencepiece_processor_init_native(self) self._out_type = out_type self._add_bos = add_bos self._add_eos = add_eos self._reverse = reverse self._enable_sampling = enable_sampling self._nbest_size = nbest_size self._alpha = alpha if model_file or model_proto: self.Load(model_file=model_file, model_proto=model_proto) def Encode(self, input, out_type=None, add_bos=None, add_eos=None, reverse=None, enable_sampling=None, nbest_size=None, alpha=None): """Encode text input to segmented ids or tokens. Args: input: input string. accepsts list of string. out_type: output type. int or str. add_bos: Add <s> to the result (Default = false) add_eos: Add </s> to the result (Default = false) <s>/</s> is added after reversing (if enabled). reverse: Reverses the tokenized sequence (Default = false) nbest_size: sampling parameters for unigram. Invalid for BPE-Dropout. nbest_size = {0,1}: No sampling is performed. nbest_size > 1: samples from the nbest_size results. nbest_size < 0: assuming that nbest_size is infinite and samples from the all hypothesis (lattice) using forward-filtering-and-backward-sampling algorithm. alpha: Soothing parameter for unigram sampling, and merge probability for BPE-dropout (probablity 'p' in BPE-dropout paper). """ if out_type is None: out_type = self._out_type if add_bos is None: add_bos = self._add_bos if add_eos is None: add_eos = self._add_eos if reverse is None: reverse = self._reverse if enable_sampling is None: enable_sampling = self._enable_sampling if nbest_size is None: nbest_size = self._nbest_size if alpha is None: alpha = self._alpha if enable_sampling == True and (nbest_size is None or nbest_size == 0 or nbest_size == 1 or alpha is None): raise RuntimeError( 'When enable_sampling is True, We must specify "nbest_size > 1" or "nbest_size = -1", ' 'and "alpha". "nbest_size" is enabled only on unigram mode ignored in BPE-dropout. ' 'when "nbest_size = -1" , this method samples from all candidates on the lattice ' 'instead of nbest segmentations.' ) def _encode(text): if out_type is int: if enable_sampling: result = self.SampleEncodeAsIds(text, nbest_size, alpha) else: result = self.EncodeAsIds(text) else: if enable_sampling: result = self.SampleEncodeAsPieces(text, nbest_size, alpha) else: result = self.EncodeAsPieces(text) if reverse: result.reverse() if add_bos: if out_type is int: result = [self.bos_id()] + result else: result = [self.IdToPiece(self.bos_id())] + result if add_eos: if out_type is int: result = result + [self.eos_id()] else: result = result + [self.IdToPiece(self.eos_id())] return result if type(input) is list: return [_encode(n) for n in input] return _encode(input) def Decode(self, input): """Decode processed id or token sequences.""" if not input: return self.DecodeIds([]) elif type(input) is int: return self.DecodeIdsWithCheck([input]) elif type(input) is str: return self.DecodePieces([input]) def _decode(input): if not input: return self.DecodeIds([]) if type(input[0]) is int: return self.DecodeIdsWithCheck(input) return self.DecodePieces(input) if type(input[0]) is list: return [_decode(n) for n in input] return _decode(input) def piece_size(self): return self.GetPieceSize() def vocab_size(self): return self.GetPieceSize() def __getstate__(self): return self.serialized_model_proto() def __setstate__(self, serialized_model_proto): self.__init__() self.LoadFromSerializedProto(serialized_model_proto) def __len__(self): return self.GetPieceSize() def __getitem__(self, piece): return self.PieceToId(piece) def Load(self, model_file=None, model_proto=None): """Overwride SentencePieceProcessor.Load to support both model_file and model_proto. Args: model_file: The sentencepiece model file path. model_proto: The sentencepiece model serialized proto. Either `model_file` or `model_proto` must be set. """ if model_file and model_proto: raise RuntimeError('model_file and model_proto must be exclusive.') if model_proto: return self.LoadFromSerializedProto(model_proto) return self.LoadFromFile(model_file) # Register SentencePieceProcessor in _sentencepiece: _sentencepiece.SentencePieceProcessor_swigregister(SentencePieceProcessor) def SetRandomGeneratorSeed(seed): return _sentencepiece.SetRandomGeneratorSeed(seed) class SentencePieceTrainer(object): thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr @staticmethod def _TrainFromString(arg): return _sentencepiece.SentencePieceTrainer__TrainFromString(arg) @staticmethod def _TrainFromMap(args): return _sentencepiece.SentencePieceTrainer__TrainFromMap(args) @staticmethod def _TrainFromMap2(args, iter): return _sentencepiece.SentencePieceTrainer__TrainFromMap2(args, iter) @staticmethod def _TrainFromMap3(args): return _sentencepiece.SentencePieceTrainer__TrainFromMap3(args) @staticmethod def _TrainFromMap4(args, iter): return _sentencepiece.SentencePieceTrainer__TrainFromMap4(args, iter) @staticmethod def Train(arg=None, **kwargs): """Train Sentencepiece model. Accept both kwargs and legacy string arg.""" if arg is not None and type(arg) is str: return SentencePieceTrainer._TrainFromString(arg) def _encode(value): """Encode value to CSV..""" if type(value) is list: if sys.version_info[0] == 3: f = StringIO() else: f = BytesIO() writer = csv.writer(f, lineterminator='') writer.writerow([str(v) for v in value]) return f.getvalue() else: return str(value) sentence_iterator = None model_writer = None new_kwargs = {} for key, value in kwargs.items(): if key in ['sentence_iterator', 'sentence_reader']: sentence_iterator = value elif key in ['model_writer']: model_writer = value else: new_kwargs[key] = _encode(value) if model_writer: if sentence_iterator: model_proto = SentencePieceTrainer._TrainFromMap4(new_kwargs, sentence_iterator) else: model_proto = SentencePieceTrainer._TrainFromMap3(new_kwargs) model_writer.write(model_proto) else: if sentence_iterator: return SentencePieceTrainer._TrainFromMap2(new_kwargs, sentence_iterator) else: return SentencePieceTrainer._TrainFromMap(new_kwargs) return None # Register SentencePieceTrainer in _sentencepiece: _sentencepiece.SentencePieceTrainer_swigregister(SentencePieceTrainer) def SentencePieceTrainer__TrainFromString(arg): return _sentencepiece.SentencePieceTrainer__TrainFromString(arg) def SentencePieceTrainer__TrainFromMap(args): return _sentencepiece.SentencePieceTrainer__TrainFromMap(args) def SentencePieceTrainer__TrainFromMap2(args, iter): return _sentencepiece.SentencePieceTrainer__TrainFromMap2(args, iter) def SentencePieceTrainer__TrainFromMap3(args): return _sentencepiece.SentencePieceTrainer__TrainFromMap3(args) def SentencePieceTrainer__TrainFromMap4(args, iter): return _sentencepiece.SentencePieceTrainer__TrainFromMap4(args, iter) import re import csv import sys from io import StringIO from io import BytesIO def _add_snake_case(classname): """Added snake_cased method from CammelCased method.""" snake_map = {} for k, v in classname.__dict__.items(): if re.match(r'^[A-Z]+', k): snake = re.sub(r'(?<!^)(?=[A-Z])', '_', k).lower().replace('n_best', 'nbest') snake_map[snake] = v for k, v in snake_map.items(): setattr(classname, k, v) def _batchnize(classname, name): """Enables batch request for the method classname.name.""" func = getattr(classname, name, None) def _func(v, n): if type(n) is int and (n < 0 or n >= v.piece_size()): raise IndexError('piece id is out of range.') return func(v, n) def _batched_func(self, arg): if type(arg) is list: return [_func(self, n) for n in arg] else: return _func(self, arg) setattr(classname, name, _batched_func) _sentencepiece_processor_init_native = SentencePieceProcessor.__init__ setattr(SentencePieceProcessor, '__init__', SentencePieceProcessor.Init) SentencePieceProcessor.Tokenize = SentencePieceProcessor.Encode SentencePieceProcessor.Detokenize = SentencePieceProcessor.Decode SentencePieceProcessor.DecodeIds = SentencePieceProcessor.DecodeIdsWithCheck SentencePieceProcessor.DecodeIdsAsSerializedProto = SentencePieceProcessor.DecodeIdsAsSerializedProtoWithCheck for m in [ 'PieceToId', 'IdToPiece', 'GetScore', 'IsUnknown', 'IsControl', 'IsUnused', 'IsByte' ]: _batchnize(SentencePieceProcessor, m) _add_snake_case(SentencePieceProcessor) _add_snake_case(SentencePieceTrainer) set_random_generator_seed = SetRandomGeneratorSeed
7,748
2,151
package junit.framework; import java.io.PrintWriter; import java.io.StringWriter; /** * A {@code TestFailure} collects a failed test together with * the caught exception. * * @see TestResult */ public class TestFailure { protected Test fFailedTest; protected Throwable fThrownException; /** * Constructs a TestFailure with the given test and exception. */ public TestFailure(Test failedTest, Throwable thrownException) { fFailedTest = failedTest; fThrownException = thrownException; } /** * Gets the failed test. */ public Test failedTest() { return fFailedTest; } /** * Gets the thrown exception. */ public Throwable thrownException() { return fThrownException; } /** * Returns a short description of the failure. */ @Override public String toString() { return fFailedTest + ": " + fThrownException.getMessage(); } /** * Returns a String containing the stack trace of the error * thrown by TestFailure. */ public String trace() { StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); thrownException().printStackTrace(writer); return stringWriter.toString(); } /** * Returns a String containing the message from the thrown exception. */ public String exceptionMessage() { return thrownException().getMessage(); } /** * Returns {@code true} if the error is considered a failure * (i.e. if it is an instance of {@code AssertionFailedError}), * {@code false} otherwise. */ public boolean isFailure() { return thrownException() instanceof AssertionFailedError; } }
640
751
<gh_stars>100-1000 /* *------------------------------------------------------------------ * vxlan_api.c - vxlan api * * Copyright (c) 2016 Cisco and/or its affiliates. * 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 <vnet/vnet.h> #include <vlibmemory/api.h> #include <vnet/interface.h> #include <vnet/api_errno.h> #include <vnet/feature/feature.h> #include <vnet/vxlan/vxlan.h> #include <vnet/fib/fib_table.h> #include <vnet/ip/ip_types_api.h> #include <vnet/udp/udp_local.h> #include <vnet/format_fns.h> #include <vxlan/vxlan.api_enum.h> #include <vxlan/vxlan.api_types.h> static u16 msg_id_base; #define REPLY_MSG_ID_BASE msg_id_base #include <vlibapi/api_helper_macros.h> static void vl_api_vxlan_offload_rx_t_handler (vl_api_vxlan_offload_rx_t * mp) { vl_api_vxlan_offload_rx_reply_t *rmp; int rv = 0; u32 hw_if_index = ntohl (mp->hw_if_index); u32 sw_if_index = ntohl (mp->sw_if_index); if (!vnet_hw_interface_is_valid (vnet_get_main (), hw_if_index)) { rv = VNET_API_ERROR_NO_SUCH_ENTRY; goto err; } VALIDATE_SW_IF_INDEX (mp); u32 t_index = vnet_vxlan_get_tunnel_index (sw_if_index); if (t_index == ~0) { rv = VNET_API_ERROR_INVALID_SW_IF_INDEX_2; goto err; } vxlan_main_t *vxm = &vxlan_main; vxlan_tunnel_t *t = pool_elt_at_index (vxm->tunnels, t_index); if (!ip46_address_is_ip4 (&t->dst)) { rv = VNET_API_ERROR_INVALID_ADDRESS_FAMILY; goto err; } vnet_main_t *vnm = vnet_get_main (); vnet_hw_interface_t *hw_if = vnet_get_hw_interface (vnm, hw_if_index); ip4_main_t *im = &ip4_main; u32 rx_fib_index = vec_elt (im->fib_index_by_sw_if_index, hw_if->sw_if_index); if (t->encap_fib_index != rx_fib_index) { rv = VNET_API_ERROR_NO_SUCH_FIB; goto err; } if (vnet_vxlan_add_del_rx_flow (hw_if_index, t_index, mp->enable)) { rv = VNET_API_ERROR_UNSPECIFIED; goto err; } BAD_SW_IF_INDEX_LABEL; err: REPLY_MACRO (VL_API_VXLAN_OFFLOAD_RX_REPLY); } static void vl_api_sw_interface_set_vxlan_bypass_t_handler (vl_api_sw_interface_set_vxlan_bypass_t * mp) { vl_api_sw_interface_set_vxlan_bypass_reply_t *rmp; int rv = 0; u32 sw_if_index = ntohl (mp->sw_if_index); VALIDATE_SW_IF_INDEX (mp); vnet_int_vxlan_bypass_mode (sw_if_index, mp->is_ipv6, mp->enable); BAD_SW_IF_INDEX_LABEL; REPLY_MACRO (VL_API_SW_INTERFACE_SET_VXLAN_BYPASS_REPLY); } static int vxlan_add_del_tunnel_clean_input (vnet_vxlan_add_del_tunnel_args_t *a, u32 encap_vrf_id) { a->is_ip6 = !ip46_address_is_ip4 (&a->src); a->encap_fib_index = fib_table_find (fib_ip_proto (a->is_ip6), encap_vrf_id); if (a->encap_fib_index == ~0) { return VNET_API_ERROR_NO_SUCH_FIB; } if (ip46_address_is_ip4 (&a->src) != ip46_address_is_ip4 (&a->dst)) { return VNET_API_ERROR_INVALID_VALUE; } /* Check src & dst are different */ if (ip46_address_cmp (&a->dst, &a->src) == 0) { return VNET_API_ERROR_SAME_SRC_DST; } if (ip46_address_is_multicast (&a->dst) && !vnet_sw_if_index_is_api_valid (a->mcast_sw_if_index)) { return VNET_API_ERROR_INVALID_SW_IF_INDEX; } return 0; } static void vl_api_vxlan_add_del_tunnel_t_handler (vl_api_vxlan_add_del_tunnel_t *mp) { vl_api_vxlan_add_del_tunnel_reply_t *rmp; u32 sw_if_index = ~0; int rv = 0; vnet_vxlan_add_del_tunnel_args_t a = { .is_add = mp->is_add, .instance = ntohl (mp->instance), .mcast_sw_if_index = ntohl (mp->mcast_sw_if_index), .decap_next_index = ntohl (mp->decap_next_index), .vni = ntohl (mp->vni), }; ip_address_decode (&mp->src_address, &a.src); ip_address_decode (&mp->dst_address, &a.dst); rv = vxlan_add_del_tunnel_clean_input (&a, ntohl (mp->encap_vrf_id)); if (rv) goto out; a.dst_port = a.is_ip6 ? UDP_DST_PORT_vxlan6 : UDP_DST_PORT_vxlan, a.src_port = a.is_ip6 ? UDP_DST_PORT_vxlan6 : UDP_DST_PORT_vxlan, rv = vnet_vxlan_add_del_tunnel (&a, &sw_if_index); out: REPLY_MACRO2(VL_API_VXLAN_ADD_DEL_TUNNEL_REPLY, ({ rmp->sw_if_index = ntohl (sw_if_index); })); } static void vl_api_vxlan_add_del_tunnel_v2_t_handler (vl_api_vxlan_add_del_tunnel_v2_t *mp) { vl_api_vxlan_add_del_tunnel_v2_reply_t *rmp; u32 sw_if_index = ~0; int rv = 0; vnet_vxlan_add_del_tunnel_args_t a = { .is_add = mp->is_add, .instance = ntohl (mp->instance), .mcast_sw_if_index = ntohl (mp->mcast_sw_if_index), .decap_next_index = ntohl (mp->decap_next_index), .vni = ntohl (mp->vni), .dst_port = ntohs (mp->dst_port), .src_port = ntohs (mp->src_port), }; ip_address_decode (&mp->src_address, &a.src); ip_address_decode (&mp->dst_address, &a.dst); rv = vxlan_add_del_tunnel_clean_input (&a, ntohl (mp->encap_vrf_id)); if (rv) goto out; rv = vnet_vxlan_add_del_tunnel (&a, &sw_if_index); out: REPLY_MACRO2 (VL_API_VXLAN_ADD_DEL_TUNNEL_V2_REPLY, ({ rmp->sw_if_index = ntohl (sw_if_index); })); } static void vl_api_vxlan_add_del_tunnel_v3_t_handler (vl_api_vxlan_add_del_tunnel_v3_t *mp) { vl_api_vxlan_add_del_tunnel_v3_reply_t *rmp; u32 sw_if_index = ~0; int rv = 0; vnet_vxlan_add_del_tunnel_args_t a = { .is_add = mp->is_add, .instance = ntohl (mp->instance), .mcast_sw_if_index = ntohl (mp->mcast_sw_if_index), .decap_next_index = ntohl (mp->decap_next_index), .vni = ntohl (mp->vni), .dst_port = ntohs (mp->dst_port), .src_port = ntohs (mp->src_port), .is_l3 = mp->is_l3, }; ip_address_decode (&mp->src_address, &a.src); ip_address_decode (&mp->dst_address, &a.dst); rv = vxlan_add_del_tunnel_clean_input (&a, ntohl (mp->encap_vrf_id)); if (rv) goto out; rv = vnet_vxlan_add_del_tunnel (&a, &sw_if_index); out: REPLY_MACRO2 (VL_API_VXLAN_ADD_DEL_TUNNEL_V3_REPLY, ({ rmp->sw_if_index = ntohl (sw_if_index); })); } static void send_vxlan_tunnel_details (vxlan_tunnel_t * t, vl_api_registration_t * reg, u32 context) { vl_api_vxlan_tunnel_details_t *rmp; ip4_main_t *im4 = &ip4_main; ip6_main_t *im6 = &ip6_main; rmp = vl_msg_api_alloc (sizeof (*rmp)); clib_memset (rmp, 0, sizeof (*rmp)); rmp->_vl_msg_id = ntohs (REPLY_MSG_ID_BASE + VL_API_VXLAN_TUNNEL_DETAILS); ip_address_encode (&t->src, IP46_TYPE_ANY, &rmp->src_address); ip_address_encode (&t->dst, IP46_TYPE_ANY, &rmp->dst_address); if (ip46_address_is_ip4 (&t->dst)) rmp->encap_vrf_id = htonl (im4->fibs[t->encap_fib_index].ft_table_id); else rmp->encap_vrf_id = htonl (im6->fibs[t->encap_fib_index].ft_table_id); rmp->instance = htonl (t->user_instance); rmp->mcast_sw_if_index = htonl (t->mcast_sw_if_index); rmp->vni = htonl (t->vni); rmp->decap_next_index = htonl (t->decap_next_index); rmp->sw_if_index = htonl (t->sw_if_index); rmp->context = context; vl_api_send_msg (reg, (u8 *) rmp); } static void vl_api_vxlan_tunnel_dump_t_handler (vl_api_vxlan_tunnel_dump_t * mp) { vl_api_registration_t *reg; vxlan_main_t *vxm = &vxlan_main; vxlan_tunnel_t *t; u32 sw_if_index; reg = vl_api_client_index_to_registration (mp->client_index); if (!reg) return; sw_if_index = ntohl (mp->sw_if_index); if (~0 == sw_if_index) { pool_foreach (t, vxm->tunnels) send_vxlan_tunnel_details(t, reg, mp->context); } else { if ((sw_if_index >= vec_len (vxm->tunnel_index_by_sw_if_index)) || (~0 == vxm->tunnel_index_by_sw_if_index[sw_if_index])) { return; } t = &vxm->tunnels[vxm->tunnel_index_by_sw_if_index[sw_if_index]]; send_vxlan_tunnel_details (t, reg, mp->context); } } static void send_vxlan_tunnel_v2_details (vxlan_tunnel_t *t, vl_api_registration_t *reg, u32 context) { vl_api_vxlan_tunnel_v2_details_t *rmp; ip4_main_t *im4 = &ip4_main; ip6_main_t *im6 = &ip6_main; rmp = vl_msg_api_alloc (sizeof (*rmp)); clib_memset (rmp, 0, sizeof (*rmp)); rmp->_vl_msg_id = ntohs (REPLY_MSG_ID_BASE + VL_API_VXLAN_TUNNEL_V2_DETAILS); ip_address_encode (&t->src, IP46_TYPE_ANY, &rmp->src_address); ip_address_encode (&t->dst, IP46_TYPE_ANY, &rmp->dst_address); rmp->src_port = htons (t->src_port); rmp->dst_port = htons (t->dst_port); if (ip46_address_is_ip4 (&t->dst)) rmp->encap_vrf_id = htonl (im4->fibs[t->encap_fib_index].ft_table_id); else rmp->encap_vrf_id = htonl (im6->fibs[t->encap_fib_index].ft_table_id); rmp->instance = htonl (t->user_instance); rmp->mcast_sw_if_index = htonl (t->mcast_sw_if_index); rmp->vni = htonl (t->vni); rmp->decap_next_index = htonl (t->decap_next_index); rmp->sw_if_index = htonl (t->sw_if_index); rmp->context = context; vl_api_send_msg (reg, (u8 *) rmp); } static void vl_api_vxlan_tunnel_v2_dump_t_handler (vl_api_vxlan_tunnel_v2_dump_t *mp) { vl_api_registration_t *reg; vxlan_main_t *vxm = &vxlan_main; vxlan_tunnel_t *t; u32 sw_if_index; reg = vl_api_client_index_to_registration (mp->client_index); if (!reg) return; sw_if_index = ntohl (mp->sw_if_index); if (~0 == sw_if_index) { pool_foreach (t, vxm->tunnels) send_vxlan_tunnel_v2_details (t, reg, mp->context); } else { if ((sw_if_index >= vec_len (vxm->tunnel_index_by_sw_if_index)) || (~0 == vxm->tunnel_index_by_sw_if_index[sw_if_index])) { return; } t = &vxm->tunnels[vxm->tunnel_index_by_sw_if_index[sw_if_index]]; send_vxlan_tunnel_v2_details (t, reg, mp->context); } } #include <vxlan/vxlan.api.c> static clib_error_t * vxlan_api_hookup (vlib_main_t * vm) { api_main_t *am = vlibapi_get_main (); am->api_trace_cfg[VL_API_VXLAN_ADD_DEL_TUNNEL].size += 16 * sizeof (u32); /* * Set up the (msg_name, crc, message-id) table */ msg_id_base = setup_message_id_table (); return 0; } VLIB_API_INIT_FUNCTION (vxlan_api_hookup); /* * fd.io coding-style-patch-verification: ON * * Local Variables: * eval: (c-set-style "gnu") * End: */
5,171
852
#ifndef RecoTauTag_RecoTau_DeepTauBase_h #define RecoTauTag_RecoTau_DeepTauBase_h /* * \class DeepTauBase * * Definition of the base class for tau identification using Deep NN. * * \author <NAME>, INFN Pisa * \author <NAME>, University of Siena & INFN Pisa */ #include <Math/VectorUtil.h> #include "FWCore/Framework/interface/stream/EDProducer.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "PhysicsTools/TensorFlow/interface/TensorFlow.h" #include "tensorflow/core/util/memmapped_file_system.h" #include "DataFormats/PatCandidates/interface/Electron.h" #include "DataFormats/PatCandidates/interface/Muon.h" #include "DataFormats/PatCandidates/interface/Tau.h" #include "DataFormats/TauReco/interface/TauDiscriminatorContainer.h" #include "DataFormats/TauReco/interface/PFTauDiscriminator.h" #include "DataFormats/PatCandidates/interface/PATTauDiscriminator.h" #include "CommonTools/Utils/interface/StringObjectFunction.h" #include "RecoTauTag/RecoTau/interface/PFRecoTauClusterVariables.h" #include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h" #include "FWCore/ParameterSet/interface/ParameterSetDescription.h" #include "DataFormats/Common/interface/View.h" #include "DataFormats/Common/interface/RefToBase.h" #include "DataFormats/Provenance/interface/ProductProvenance.h" #include "DataFormats/Provenance/interface/ProcessHistoryID.h" #include "FWCore/Common/interface/Provenance.h" #include <TF1.h> #include <map> namespace deep_tau { class TauWPThreshold { public: explicit TauWPThreshold(const std::string& cut_str); double operator()(const reco::BaseTau& tau, bool isPFTau) const; private: std::unique_ptr<TF1> fn_; double value_; }; class DeepTauCache { public: using GraphPtr = std::shared_ptr<tensorflow::GraphDef>; DeepTauCache(const std::map<std::string, std::string>& graph_names, bool mem_mapped); ~DeepTauCache(); // A Session allows concurrent calls to Run(), though a Session must // be created / extended by a single thread. tensorflow::Session& getSession(const std::string& name = "") const { return *sessions_.at(name); } const tensorflow::GraphDef& getGraph(const std::string& name = "") const { return *graphs_.at(name); } private: std::map<std::string, GraphPtr> graphs_; std::map<std::string, tensorflow::Session*> sessions_; std::map<std::string, std::unique_ptr<tensorflow::MemmappedEnv>> memmappedEnv_; }; class DeepTauBase : public edm::stream::EDProducer<edm::GlobalCache<DeepTauCache>> { public: using TauDiscriminator = reco::TauDiscriminatorContainer; using TauCollection = edm::View<reco::BaseTau>; using CandidateCollection = edm::View<reco::Candidate>; using TauRef = edm::Ref<TauCollection>; using TauRefProd = edm::RefProd<TauCollection>; using ElectronCollection = pat::ElectronCollection; using MuonCollection = pat::MuonCollection; using LorentzVectorXYZ = ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double>>; using Cutter = TauWPThreshold; using CutterPtr = std::unique_ptr<Cutter>; using WPList = std::vector<CutterPtr>; struct Output { std::vector<size_t> num_, den_; Output(const std::vector<size_t>& num, const std::vector<size_t>& den) : num_(num), den_(den) {} std::unique_ptr<TauDiscriminator> get_value(const edm::Handle<TauCollection>& taus, const tensorflow::Tensor& pred, const WPList* working_points, bool is_online) const; }; using OutputCollection = std::map<std::string, Output>; DeepTauBase(const edm::ParameterSet& cfg, const OutputCollection& outputs, const DeepTauCache* cache); ~DeepTauBase() override {} void produce(edm::Event& event, const edm::EventSetup& es) override; static std::unique_ptr<DeepTauCache> initializeGlobalCache(const edm::ParameterSet& cfg); static void globalEndJob(const DeepTauCache* cache) {} template <typename ConsumeType> struct TauDiscInfo { edm::InputTag label; edm::Handle<ConsumeType> handle; edm::EDGetTokenT<ConsumeType> disc_token; double cut; void fill(const edm::Event& evt) { evt.getByToken(disc_token, handle); } }; // select boolean operation on prediscriminants (and = 0x01, or = 0x00) uint8_t andPrediscriminants_; std::vector<TauDiscInfo<pat::PATTauDiscriminator>> patPrediscriminants_; std::vector<TauDiscInfo<reco::PFTauDiscriminator>> recoPrediscriminants_; enum BasicDiscriminator { ChargedIsoPtSum, NeutralIsoPtSum, NeutralIsoPtSumWeight, FootprintCorrection, PhotonPtSumOutsideSignalCone, PUcorrPtSum }; private: virtual tensorflow::Tensor getPredictions(edm::Event& event, edm::Handle<TauCollection> taus) = 0; virtual void createOutputs(edm::Event& event, const tensorflow::Tensor& pred, edm::Handle<TauCollection> taus); protected: edm::EDGetTokenT<TauCollection> tausToken_; edm::EDGetTokenT<CandidateCollection> pfcandToken_; edm::EDGetTokenT<reco::VertexCollection> vtxToken_; std::map<std::string, WPList> workingPoints_; const bool is_online_; OutputCollection outputs_; const DeepTauCache* cache_; static const std::map<BasicDiscriminator, std::string> stringFromDiscriminator_; static const std::vector<BasicDiscriminator> requiredBasicDiscriminators_; static const std::vector<BasicDiscriminator> requiredBasicDiscriminatorsdR03_; }; } // namespace deep_tau #endif
2,164
3,372
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ package com.amazonaws.services.elasticmapreduce.model.transform; import java.util.List; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.elasticmapreduce.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * StudioMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class StudioMarshaller { private static final MarshallingInfo<String> STUDIOID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("StudioId").build(); private static final MarshallingInfo<String> STUDIOARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("StudioArn").build(); private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Name").build(); private static final MarshallingInfo<String> DESCRIPTION_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Description").build(); private static final MarshallingInfo<String> AUTHMODE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("AuthMode").build(); private static final MarshallingInfo<String> VPCID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("VpcId").build(); private static final MarshallingInfo<List> SUBNETIDS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("SubnetIds").build(); private static final MarshallingInfo<String> SERVICEROLE_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ServiceRole").build(); private static final MarshallingInfo<String> USERROLE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("UserRole").build(); private static final MarshallingInfo<String> WORKSPACESECURITYGROUPID_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("WorkspaceSecurityGroupId").build(); private static final MarshallingInfo<String> ENGINESECURITYGROUPID_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("EngineSecurityGroupId").build(); private static final MarshallingInfo<String> URL_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Url").build(); private static final MarshallingInfo<java.util.Date> CREATIONTIME_BINDING = MarshallingInfo.builder(MarshallingType.DATE) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("CreationTime").timestampFormat("unixTimestamp").build(); private static final MarshallingInfo<String> DEFAULTS3LOCATION_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("DefaultS3Location").build(); private static final MarshallingInfo<String> IDPAUTHURL_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("IdpAuthUrl").build(); private static final MarshallingInfo<String> IDPRELAYSTATEPARAMETERNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("IdpRelayStateParameterName").build(); private static final MarshallingInfo<List> TAGS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Tags").build(); private static final StudioMarshaller instance = new StudioMarshaller(); public static StudioMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(Studio studio, ProtocolMarshaller protocolMarshaller) { if (studio == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(studio.getStudioId(), STUDIOID_BINDING); protocolMarshaller.marshall(studio.getStudioArn(), STUDIOARN_BINDING); protocolMarshaller.marshall(studio.getName(), NAME_BINDING); protocolMarshaller.marshall(studio.getDescription(), DESCRIPTION_BINDING); protocolMarshaller.marshall(studio.getAuthMode(), AUTHMODE_BINDING); protocolMarshaller.marshall(studio.getVpcId(), VPCID_BINDING); protocolMarshaller.marshall(studio.getSubnetIds(), SUBNETIDS_BINDING); protocolMarshaller.marshall(studio.getServiceRole(), SERVICEROLE_BINDING); protocolMarshaller.marshall(studio.getUserRole(), USERROLE_BINDING); protocolMarshaller.marshall(studio.getWorkspaceSecurityGroupId(), WORKSPACESECURITYGROUPID_BINDING); protocolMarshaller.marshall(studio.getEngineSecurityGroupId(), ENGINESECURITYGROUPID_BINDING); protocolMarshaller.marshall(studio.getUrl(), URL_BINDING); protocolMarshaller.marshall(studio.getCreationTime(), CREATIONTIME_BINDING); protocolMarshaller.marshall(studio.getDefaultS3Location(), DEFAULTS3LOCATION_BINDING); protocolMarshaller.marshall(studio.getIdpAuthUrl(), IDPAUTHURL_BINDING); protocolMarshaller.marshall(studio.getIdpRelayStateParameterName(), IDPRELAYSTATEPARAMETERNAME_BINDING); protocolMarshaller.marshall(studio.getTags(), TAGS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
2,419
335
<reponame>Safal08/Hacktoberfest-1<filename>N/Now_adverb.json { "word": "Now", "definitions": [ "At the present time or moment.", "At the time directly following the present moment; immediately.", "Under the present circumstances; as a result of something that has recently happened.", "On this further occasion, typically as the latest in a series of annoying situations or events.", "Used to emphasize a particular length of time.", "(in a narrative or account of past events) at the time spoken of or referred to.", "Used, especially in conversation, to draw attention to a particular statement or point in a narrative.", "Used in a request, instruction, or question, typically to give a slight emphasis to one's words.", "Used when pausing or considering one's next words.", "Used at the end of an ironic question echoing a previous statement." ], "parts-of-speech": "Adverb" }
302
3,102
<gh_stars>1000+ /// Comment for bar void bar(void);
20
352
// ========================================================================= // Copyright 2019 T-Mobile, US // // 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. // See the readme.txt file for additional language around disclaimer of warranties. // ========================================================================= package com.tmobile.cso.vault.api.model; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; public class LDAPUser implements Serializable { private String username; private String policies; public LDAPUser() { super(); } /** * * @param username * @param policies */ public LDAPUser(String username, String policies) { super(); this.username = username; this.policies = policies; } /** * * @return username */ @ApiModelProperty(example="user01", position=1) public String getUsername() { return username; } /** * * @param username */ public void setUsername(String username) { this.username = username; } /** * * @return policies */ @ApiModelProperty(example="r_users_safe01,w_users_safe02", position=2) public String getPolicies() { return policies; } /** * * @param policies */ public void setPolicies(String policies) { this.policies = policies; } }
634
3,631
<gh_stars>1000+ /* * Copyright 2021 Red Hat, Inc. and/or its affiliates. * * 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. */ package org.kie.dmn.core.alphasupport; import java.lang.Override; import java.util.Optional; import org.drools.core.common.DefaultFactHandle; import org.drools.ancompiler.CompiledNetwork; import org.kie.dmn.api.feel.runtime.events.FEELEvent; import org.kie.dmn.core.compiler.alphanetbased.DMNAlphaNetworkEvaluator; import org.kie.dmn.core.compiler.alphanetbased.AlphaNetworkEvaluationContext; import org.kie.dmn.core.compiler.alphanetbased.Results; import org.kie.dmn.feel.lang.EvaluationContext; import org.kie.dmn.core.compiler.alphanetbased.PropertyEvaluator; import org.kie.dmn.feel.runtime.decisiontables.DecisionTable; import org.kie.dmn.feel.runtime.decisiontables.HitPolicy; import org.kie.dmn.feel.runtime.events.InvalidInputEvent; // All implementations are used only for templating purposes and should never be called public class DMNAlphaNetworkTemplate implements DMNAlphaNetworkEvaluator { protected final CompiledNetwork compiledNetwork; protected final AlphaNetworkEvaluationContext alphaNetworkEvaluationContext; private final HitPolicy hitPolicy = HitPolicy.fromString("HIT_POLICY_NAME"); protected PropertyEvaluator propertyEvaluator; public DMNAlphaNetworkTemplate(CompiledNetwork compiledNetwork, AlphaNetworkEvaluationContext alphaNetworkEvaluationContext) { this.compiledNetwork = compiledNetwork; this.alphaNetworkEvaluationContext = alphaNetworkEvaluationContext; } public PropertyEvaluator getOrCreatePropertyEvaluator(EvaluationContext evaluationContext) { if(propertyEvaluator == null) { propertyEvaluator = new PropertyEvaluator(evaluationContext, "PROPERTY_NAMES"); } return propertyEvaluator; } @Override public Optional<InvalidInputEvent> validate(EvaluationContext evaluationContext) { PropertyEvaluator propertyEvaluator = getOrCreatePropertyEvaluator(evaluationContext); // Validation Column { Optional<InvalidInputEvent> resultValidation0 = ValidatorC0.getInstance().validate(evaluationContext, propertyEvaluator.getValue(777)); if (resultValidation0.isPresent()) { return resultValidation0; } } return Optional.empty(); } @Override public Object evaluate(EvaluationContext evaluationContext, DecisionTable decisionTable) { // Clean previous results Results results = alphaNetworkEvaluationContext.getResultCollector(); results.clearResults(); // init CompiledNetwork with object needed for results, compiledNetwork.init(alphaNetworkEvaluationContext); // create lambda constraints and results compiledNetwork.initConstraintsResults(); // Fire rete network compiledNetwork.propagateAssertObject(new DefaultFactHandle(getOrCreatePropertyEvaluator(evaluationContext)), null, null); // Find result with Hit Policy applied Object result = results.applyHitPolicy(evaluationContext, hitPolicy, decisionTable); return result; } }
1,316
528
#include "array/zfpcarray1.h" #include "array/zfpcarray2.h" #include "array/zfpcarray3.h" #include "array/zfpcarray4.h" #include "array/zfpfactory.h" using namespace zfp; extern "C" { #include "constants/2dDouble.h" } #include "gtest/gtest.h" #include "utils/gtestDoubleEnv.h" #include "utils/gtestBaseFixture.h" #include "utils/predicates.h" class CArray2dTestEnv : public ArrayDoubleTestEnv { public: virtual int getDims() { return 2; } }; CArray2dTestEnv* const testEnv = new CArray2dTestEnv; class CArray2dTest : public CArrayNdTestFixture {}; #define TEST_FIXTURE CArray2dTest #define ZFP_ARRAY_TYPE const_array2d #define ZFP_FULL_ARRAY_TYPE(BLOCK_TYPE) const_array2<double, zfp::codec::zfp2<double>, BLOCK_TYPE> #define ZFP_ARRAY_TYPE_WRONG_SCALAR const_array2f #define ZFP_ARRAY_TYPE_WRONG_DIM const_array3d #define ZFP_ARRAY_TYPE_WRONG_SCALAR_DIM const_array3f #define ZFP_ARRAY_NOT_INCLUDED_TYPE const_array1d #define UINT uint64 #define SCALAR double #define DIMS 2 #include "testConstArrayBase.cpp" #include "testConstArray2Base.cpp" int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); static_cast<void>(::testing::AddGlobalTestEnvironment(testEnv)); return RUN_ALL_TESTS(); }
502
7,746
/*++ Copyright (c) 2017 Microsoft Corporation Module Name: injectivity_tactic.cpp Abstract: Injectivity tactics - Discover axioms of the form `forall x. (= (g (f x)) x` Mark `f` as injective - Rewrite (sub)terms of the form `(= (f x) (f y))` to `(= x y)` whenever `f` is injective. Author: <NAME> (t-nibrau) 2017-08-10 Notes: --*/ #include <algorithm> #include <utility> #include "tactic/tactical.h" #include "ast/rewriter/rewriter_def.h" #include "tactic/core/injectivity_tactic.h" #include "util/dec_ref_util.h" class injectivity_tactic : public tactic { struct InjHelper : public obj_map<func_decl, obj_hashtable<func_decl>*> { ast_manager & m_manager; void insert(func_decl* const f, func_decl* const g) { obj_hashtable<func_decl> *m; if (! obj_map::find(f, m)) { m_manager.inc_ref(f); m = alloc(obj_hashtable<func_decl>); // TODO: Check we don't leak memory obj_map::insert(f, m); } if (!m->contains(g)) { m_manager.inc_ref(g); m->insert(g); } } bool find(func_decl* const f, func_decl* const g) const { obj_hashtable<func_decl> *m; if(! obj_map::find(f, m)) return false; return m->contains(g); } InjHelper(ast_manager& m) : obj_map<func_decl, obj_hashtable<func_decl>*>(), m_manager(m) {} ~InjHelper() { for(auto m : *this) { for (func_decl* f : *m.get_value()) m_manager.dec_ref(f); m_manager.dec_ref(m.m_key); dealloc(m.m_value); } } }; struct finder { ast_manager & m_manager; InjHelper & inj_map; finder(ast_manager & m, InjHelper & map, params_ref const & p) : m_manager(m), inj_map(map) { updt_params(p); } ast_manager & m() const { return m_manager; } bool is_axiom(expr* n, func_decl* &f, func_decl* &g) { if (!is_forall(n)) return false; quantifier* const q = to_quantifier(n); if (q->get_num_decls() != 1) return false; const expr * const body = q->get_expr(); // n ~= forall x. body if (!m().is_eq(body)) return false; const app * const body_a = to_app(body); if (body_a->get_num_args() != 2) return false; const expr* a = body_a->get_arg(0); const expr* b = body_a->get_arg(1); // n ~= forall x. (= a b) if (is_app(a) && is_var(b)) { // Do nothing } else if (is_app(b) && is_var(a)) { std::swap(a, b); } else return false; const app* const a_app = to_app(a); const var* const b_var = to_var(b); if (b_var->get_idx() != 0) // idx is the De Bruijn's index return false; if (a_app->get_num_args() != 1) return false; g = a_app->get_decl(); const expr* const a_body = a_app->get_arg(0); // n ~= forall x. (= (g a_body) x) if (!is_app(a_body)) return false; const app* const a_body_app = to_app(a_body); if (a_body_app->get_num_args() != 1) // Maybe TODO: support multi-argument functions return false; f = a_body_app->get_decl(); const expr* const a_body_body = a_body_app->get_arg(0); // n ~= forall x. (= (g (f a_body_body)) x) if (a_body_body != b_var) return false; // n ~= forall x. (= (g (f x)) x) return true; } void operator()(goal_ref const & goal, goal_ref_buffer & result) { tactic_report report("injectivity", *goal); fail_if_unsat_core_generation("injectivity", goal); // TODO: Support UNSAT cores fail_if_proof_generation("injectivity", goal); for (unsigned i = 0; i < goal->size(); ++i) { func_decl *f, *g; if (!is_axiom(goal->form(i), f, g)) continue; TRACE("injectivity", tout << "Marking " << f->get_name() << " as injective" << std::endl;); inj_map.insert(f, g); // TODO: Record that g is f's pseudoinverse } } void updt_params(params_ref const & p) {} }; struct rewriter_eq_cfg : public default_rewriter_cfg { ast_manager & m_manager; InjHelper & inj_map; // expr_ref_vector m_out; // sort_ref_vector m_bindings; ast_manager & m() const { return m_manager; } rewriter_eq_cfg(ast_manager & m, InjHelper & map, params_ref const & p) : m_manager(m), inj_map(map) { } ~rewriter_eq_cfg() { } void cleanup_buffers() { // m_out.finalize(); } void reset() { } br_status reduce_app(func_decl * f, unsigned num, expr * const * args, expr_ref & result, proof_ref & result_pr) { if(num != 2) return BR_FAILED; if (!m().is_eq(f)) return BR_FAILED; // We are rewriting (= a b) if (!is_app(args[0]) || !is_app(args[1])) return BR_FAILED; const app* const a = to_app(args[0]); const app* const b = to_app(args[1]); // a and b are applications of the same function if (a->get_decl() != b->get_decl()) return BR_FAILED; // Maybe TODO: Generalize to multi-parameter functions ? if (a->get_num_args() != 1 || b->get_num_args() != 1) return BR_FAILED; if (!inj_map.contains(a->get_decl())) return BR_FAILED; SASSERT(a->get_arg(0)->get_sort() == b->get_arg(0)->get_sort()); TRACE("injectivity", tout << "Rewriting (= " << mk_ismt2_pp(args[0], m()) << " " << mk_ismt2_pp(args[1], m()) << ")" << std::endl;); result = m().mk_eq(a->get_arg(0), b->get_arg(0)); result_pr = nullptr; return BR_DONE; } }; struct rewriter_eq : public rewriter_tpl<rewriter_eq_cfg> { rewriter_eq_cfg m_cfg; rewriter_eq(ast_manager & m, InjHelper & map, params_ref const & p) : rewriter_tpl<rewriter_eq_cfg>(m, m.proofs_enabled(), m_cfg), m_cfg(m, map, p) { } }; struct rewriter_inverse { }; finder * m_finder; rewriter_eq * m_eq; InjHelper * m_map; // rewriter_inverse * m_inverse; params_ref m_params; ast_manager & m_manager; public: injectivity_tactic(ast_manager & m, params_ref const & p): m_params(p), m_manager(m) { TRACE("injectivity", tout << "constructed new tactic" << std::endl;); m_map = alloc(InjHelper, m); m_finder = alloc(finder, m, *m_map, p); m_eq = alloc(rewriter_eq, m, *m_map, p); } tactic * translate(ast_manager & m) override { return alloc(injectivity_tactic, m, m_params); } ~injectivity_tactic() override { dealloc(m_finder); dealloc(m_eq); dealloc(m_map); } void updt_params(params_ref const & p) override { m_params = p; m_finder->updt_params(p); } void collect_param_descrs(param_descrs & r) override { insert_max_memory(r); insert_produce_models(r); } void operator()(goal_ref const & g, goal_ref_buffer & result) override { (*m_finder)(g, result); for (unsigned i = 0; i < g->size(); ++i) { expr* curr = g->form(i); expr_ref rw(m_manager); proof_ref pr(m_manager); (*m_eq)(curr, rw, pr); g->update(i, rw, pr, g->dep(i)); } result.push_back(g.get()); } void cleanup() override { InjHelper * m = alloc(InjHelper, m_manager); finder * f = alloc(finder, m_manager, *m, m_params); rewriter_eq * r = alloc(rewriter_eq, m_manager, *m, m_params); std::swap(m, m_map), std::swap(f, m_finder), std::swap(r, m_eq); dealloc(m), dealloc(f), dealloc(r); } }; tactic * mk_injectivity_tactic(ast_manager & m, params_ref const & p) { return alloc(injectivity_tactic, m, p); }
4,669
1,444
<reponame>J-VOL/mage package mage.game.events; import mage.abilities.Ability; import mage.cards.Cards; import mage.cards.CardsImpl; import java.util.UUID; /** * * @author htrajan */ public class DiscardedCardsEvent extends GameEvent { private final Cards discardedCards; public DiscardedCardsEvent(Ability source, UUID playerId, int amount, Cards discardedCards) { super(EventType.DISCARDED_CARDS, null, source, playerId, amount, false); this.discardedCards = new CardsImpl(discardedCards); } public Cards getDiscardedCards() { return discardedCards; } }
216
367
# Copyright 2022 The OFA-Sys Team. # All rights reserved. # This source code is licensed under the Apache 2.0 license # found in the LICENSE file in the root directory. import logging import re import torch.utils.data from fairseq.data import FairseqDataset logger = logging.getLogger(__name__) class OFADataset(FairseqDataset): def __init__(self, split, dataset, bpe, src_dict, tgt_dict): self.split = split self.dataset = dataset self.bpe = bpe self.src_dict = src_dict self.tgt_dict = tgt_dict self.bos = src_dict.bos() self.eos = src_dict.eos() self.pad = src_dict.pad() self.bos_item = torch.LongTensor([self.bos]) self.eos_item = torch.LongTensor([self.eos]) def __len__(self): return len(self.dataset) def encode_text(self, text, length=None, append_bos=False, append_eos=False, use_bpe=True): s = self.tgt_dict.encode_line( line=self.bpe.encode(text) if use_bpe else text, add_if_not_exist=False, append_eos=False ).long() if length is not None: s = s[:length] if append_bos: s = torch.cat([self.bos_item, s]) if append_eos: s = torch.cat([s, self.eos_item]) return s def pre_question(self, question, max_ques_words): question = question.lower().lstrip(",.!?*#:;~").replace('-', ' ').replace('/', ' ') question = re.sub( r"\s{2,}", ' ', question, ) question = question.rstrip('\n') question = question.strip(' ') # truncate question question_words = question.split(' ') if len(question_words) > max_ques_words: question = ' '.join(question_words[:max_ques_words]) return question def pre_caption(self, caption, max_words): caption = caption.lower().lstrip(",.!?*#:;~").replace('-', ' ').replace('/', ' ').replace('<person>', 'person') caption = re.sub( r"\s{2,}", ' ', caption, ) caption = caption.rstrip('\n') caption = caption.strip(' ') # truncate caption caption_words = caption.split(' ') if len(caption_words) > max_words: caption = ' '.join(caption_words[:max_words]) return caption
1,125
597
{"data":{"nu":["latn"],"year":{"0":"hierdie jaar","1":"volgende jaar","future":{"one":"oor {0} jaar","other":"oor {0} jaar"},"past":{"one":"{0} jaar gelede","other":"{0} jaar gelede"},"-1":"verlede jaar"},"year-short":{"0":"hierdie j.","1":"volgende j.","future":{"one":"oor {0} j.","other":"oor {0} j."},"past":{"one":"{0} j. gelede","other":"{0} j. gelede"},"-1":"verlede j."},"year-narrow":{"0":"hierdie j.","1":"volgende j.","future":{"one":"oor {0} j.","other":"oor {0} j."},"past":{"one":"{0} j. gelede","other":"{0} j. gelede"},"-1":"verlede j."},"quarter":{"0":"hierdie kwartaal","1":"volgende kwartaal","future":{"one":"oor {0} kwartaal","other":"oor {0} kwartale"},"past":{"one":"{0} kwartaal gelede","other":"{0} kwartale gelede"},"-1":"verlede kwartaal"},"quarter-short":{"0":"hierdie kwartaal","1":"volgende kwartaal","future":{"one":"oor {0} kw.","other":"oor {0} kw."},"past":{"one":"{0} kw. gelede","other":"{0} kw. gelede"},"-1":"verlede kwartaal"},"quarter-narrow":{"0":"hierdie kwartaal","1":"volgende kwartaal","future":{"one":"oor {0} kw.","other":"oor {0} kw."},"past":{"one":"{0} kw. gelede","other":"{0} kw. gelede"},"-1":"verlede kwartaal"},"month":{"0":"vandeesmaand","1":"volgende maand","future":{"one":"oor {0} maand","other":"oor {0} maande"},"past":{"one":"{0} maand gelede","other":"{0} maande gelede"},"-1":"verlede maand"},"month-short":{"0":"hierdie md.","1":"volgende md.","future":{"one":"oor {0} md.","other":"oor {0} md."},"past":{"one":"{0} md. gelede","other":"{0} md. gelede"},"-1":"verlede md."},"month-narrow":{"0":"hierdie md.","1":"volgende md.","future":{"one":"oor {0} md.","other":"oor {0} md."},"past":{"one":"{0} md. gelede","other":"{0} md. gelede"},"-1":"verlede md."},"week":{"0":"hierdie week","1":"volgende week","future":{"one":"oor {0} week","other":"oor {0} weke"},"past":{"one":"{0} week gelede","other":"{0} weke gelede"},"-1":"verlede week"},"week-short":{"0":"hierdie w.","1":"volgende w.","future":{"one":"oor {0} w.","other":"oor {0} w."},"past":{"one":"{0} w. gelede","other":"{0} w. gelede"},"-1":"verlede w."},"week-narrow":{"0":"hierdie w.","1":"volgende w.","future":{"one":"oor {0} w.","other":"oor {0} w."},"past":{"one":"{0} w. gelede","other":"{0} w. gelede"},"-1":"verlede w."},"day":{"0":"vandag","1":"môre","2":"oormôre","future":{"one":"oor {0} dag","other":"oor {0} dae"},"past":{"one":"{0} dag gelede","other":"{0} dae gelede"},"-2":"eergister","-1":"gister"},"day-short":{"0":"vandag","1":"môre","2":"oormôre","future":{"one":"oor {0} dag","other":"oor {0} dae"},"past":{"one":"{0} dag gelede","other":"{0} dae gelede"},"-2":"eergister","-1":"gister"},"day-narrow":{"0":"vandag","1":"môre","2":"oormôre","future":{"one":"oor {0} dag","other":"oor {0} dae"},"past":{"one":"{0} dag gelede","other":"{0} dae gelede"},"-2":"eergister","-1":"gister"},"hour":{"0":"hierdie uur","future":{"one":"oor {0} uur","other":"oor {0} uur"},"past":{"one":"{0} uur gelede","other":"{0} uur gelede"}},"hour-short":{"0":"hierdie uur","future":{"one":"oor {0} u.","other":"oor {0} u."},"past":{"one":"{0} u. gelede","other":"{0} u. gelede"}},"hour-narrow":{"0":"hierdie uur","future":{"one":"oor {0} u.","other":"oor {0} u."},"past":{"one":"{0} u. gelede","other":"{0} u. gelede"}},"minute":{"0":"hierdie minuut","future":{"one":"oor {0} minuut","other":"oor {0} minute"},"past":{"one":"{0} minuut gelede","other":"{0} minute gelede"}},"minute-short":{"0":"hierdie minuut","future":{"one":"oor {0} min.","other":"oor {0} min."},"past":{"one":"{0} min. gelede","other":"{0} min. gelede"}},"minute-narrow":{"0":"hierdie minuut","future":{"one":"oor {0} min.","other":"oor {0} min."},"past":{"one":"{0} min. gelede","other":"{0} min. gelede"}},"second":{"0":"nou","future":{"one":"oor {0} sekonde","other":"oor {0} sekondes"},"past":{"one":"{0} sekonde gelede","other":"{0} sekondes gelede"}},"second-short":{"0":"nou","future":{"one":"oor {0} s.","other":"oor {0} s."},"past":{"one":"{0} s. gelede","other":"{0} s. gelede"}},"second-narrow":{"0":"nou","future":{"one":"oor {0} s.","other":"oor {0} s."},"past":{"one":"{0} s. gelede","other":"{0} s. gelede"}}},"locale":"af"}
1,631
441
<gh_stars>100-1000 { "name": "babel.github.io", "private": true, "version": "1.0.0", "description": "", "main": "", "scripts": { "bootstrap": "run-s bootstrap:sponsors build", "bootstrap:sponsors": "node ./scripts/download-sponsors.js", "build": "run-s build:codemirror6 build:repl build:docusaurus build:redirects && run-s build:social-image", "build:docusaurus": "cd website && yarn && yarn build", "build:redirects": "cpy ./_redirects ./website/build/babel", "build:repl": "cross-env NODE_ENV=production webpack", "build:codemirror6": "rollup -c rollup.config.mjs", "build:social-image": "node ./scripts/add-blog-social-image.js", "flow": "flow", "lint": "eslint js website", "lint-staged": "lint-staged", "fix:css": "prettier --write website/static/css/*.css", "precommit": "run-s flow lint-staged", "start": "run-p start:codemirror6 start:repl start:docusaurus", "start:docusaurus": "cd website && yarn start", "start:repl": "webpack -d -w", "start:codemirror6": "cross-env NODE_ENV=development yarn build:codemirror6", "test": "remark docs README.md --quiet", "version": "node ./scripts/generate-repl-past-versions.mjs && git add ./js/repl/past-versions.json" }, "remarkConfig": { "plugins": { "preset-lint-recommended": true, "lint-list-item-indent": false, "lint-no-blockquote-without-caret": false, "lint-no-inline-padding": false, "lint-no-literal-urls": false, "lint-no-duplicate-headings-in-section": true, "lint-no-empty-url": true, "lint-list-item-bullet-indent": false } }, "author": "", "license": "MIT", "devDependencies": { "@babel/core": "^7.11.6", "@babel/plugin-proposal-class-properties": "^7.10.4", "@babel/preset-env": "^7.11.5", "@babel/preset-flow": "^7.10.4", "@babel/preset-react": "^7.10.4", "@codemirror/basic-setup": "0.17.1", "@codemirror/lang-javascript": "0.17.2", "@codemirror/theme-one-dark": "0.17.5", "@codemirror/view": "0.17.10", "@rollup/plugin-node-resolve": "^11.2.0", "babel-eslint": "^10.0.1", "babel-loader": "^8.1.0", "babel-plugin-emotion": "^9.1.2", "chalk": "^2.4.1", "cpy-cli": "^3.1.1", "cross-env": "^7.0.2", "eslint": "^7.10.0", "eslint-config-babel": "^9.0.0", "eslint-config-prettier": "^6.12.0", "eslint-plugin-flowtype": "^3.8.1", "eslint-plugin-markdown": "^1.0.0-beta.3", "eslint-plugin-prettier": "^3.1.4", "eslint-plugin-react": "^7.21.2", "flow-bin": "^0.98.1", "husky": "^4.3.0", "lint-staged": "^10.4.0", "node-fetch": "^2.6.1", "npm-run-all": "^4.1.5", "prettier": "1.17.0", "remark-cli": "^8.0.1", "remark-lint-list-item-indent": "^2.0.1", "remark-lint-no-blockquote-without-caret": "^2.0.0", "remark-lint-no-duplicate-headings-in-section": "^2.0.2", "remark-lint-no-empty-url": "^2.0.1", "remark-lint-no-literal-urls": "^2.0.1", "remark-preset-lint-recommended": "^4.0.1", "rollup": "^2.39.1", "rollup-plugin-terser": "^7.0.2", "staged-git-files": "^1.1.1", "terser-webpack-plugin": "^4.2.2", "webpack": "^4.44.2", "webpack-cli": "^3.3.12", "webpack-dev-server": "^3.11.0", "worker-loader": "^3.0.3" }, "dependencies": { "@babel/generator": "^7.11.6", "algoliasearch": "^4.5.1", "cheerio": "^1.0.0-rc.9", "codemirror": "5.56.0", "core-js": "^3.0.1", "emotion": "^9.1.3", "lodash.camelcase": "^4.3.0", "lodash.debounce": "^4.0.8", "lz-string": "^1.4.4", "react": "^16.0.0", "react-dom": "^16.0.0", "react-instantsearch-dom": "^6.7.0", "regenerator-runtime": "^0.13.7", "semver": "^5.4.1", "unfetch": "^4.2.0" }, "workspaces": [ "./website" ], "lint-staged": { "js/**/*.js": [ "eslint --format=codeframe --fix", "git add" ], "website/pages/en/*.js": [ "eslint --format=codeframe --fix", "git add" ], "website/data/*.js": [ "eslint --format=codeframe --fix", "git add" ] } }
2,094
852
import FWCore.ParameterSet.Config as cms process = cms.Process("EcalLaserSorting") process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) ) #source reading continuously files as they arrive in in/ directory: process.load("CalibCalorimetry.EcalLaserSorting.watcherSource_cfi") # MessageLogger: process.load("FWCore.MessageLogger.MessageLogger_cfi") process.MessageLogger.cerr.FwkReport.limit = 0 #Event sorting (laserSorter) process.load("CalibCalorimetry.EcalLaserSorting.laserSorter_cfi") #process.laserSorter.disableOutput = cms.untracked.bool(True) process.p = cms.Path(process.laserSorter)
229
567
<reponame>mkolod/Vitis-Tutorials #include "xilinx_ocl_helper.hpp" #include <unistd.h> namespace xilinx { namespace example_utils { std::vector<cl::Device> XilinxOclHelper::find_xilinx_devices() { size_t i; std::vector<cl::Platform> platforms; cl::Platform::get(&platforms); cl::Platform platform; for (i = 0; i < platforms.size(); i++) { platform = platforms[i]; std::string platform_name = platform.getInfo<CL_PLATFORM_NAME>(); if (platform_name == "Xilinx") { break; } } if (i == platforms.size()) { throw_lineexception("Unable to find Xilinx OpenCL devices"); } // Get ACCELERATOR devices std::vector<cl::Device> devices; platform.getDevices(CL_DEVICE_TYPE_ACCELERATOR, &devices); return devices; } void XilinxOclHelper::initialize(std::string xclbin_file_name) { // Find Xilinx OpenCL devices std::vector<cl::Device> devices = find_xilinx_devices(); bool programmed = false; // Load the XCLBIN if (access(xclbin_file_name.c_str(), R_OK) != 0) { throw_lineexception("Specified XCLBIN not found"); } std::ifstream xclbin(xclbin_file_name.c_str(), std::ifstream::binary); xclbin.seekg(0, xclbin.end); unsigned int nb = xclbin.tellg(); xclbin.seekg(0, xclbin.beg); char *buf = new char[nb]; xclbin.read(buf, nb); cl::Program::Binaries bins; bins.push_back({buf, nb}); cl_int err; // Initialize our OpenCL context for (unsigned int i = 0; i < devices.size(); i++) { device = devices[i]; context = cl::Context(device); // Attempt to program the devic try { program = cl::Program(context, {device}, bins, NULL, &err); } catch (cl::Error &e) { continue; } programmed = true; is_initialized = true; break; } if (!programmed) { throw_lineexception("Provided XCLBIN is not compatible with any system device"); } } cl::Kernel XilinxOclHelper::get_kernel(std::string kernel_name) { if (!is_initialized) { throw_lineexception("Attempted to get kernel without initializing OCL"); } cl::Kernel krnl(program, kernel_name.c_str()); return krnl; } cl::CommandQueue XilinxOclHelper::get_command_queue(bool in_order, bool enable_profiling) { if (!is_initialized) { throw_lineexception("Attempted to get command queue without initializing OCL"); } cl_command_queue_properties props = 0; if (!in_order) { props |= CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE; } if (enable_profiling) { props |= CL_QUEUE_PROFILING_ENABLE; } cl::CommandQueue q(context, device, props); return q; } cl::Buffer XilinxOclHelper::create_buffer(size_t size, cl_mem_flags flags) { if (!is_initialized) { throw_lineexception("Attempted to create buffer before initialization"); } cl::Buffer buf(context, flags, size, NULL, NULL); return buf; } cl::Buffer XilinxOclHelper::create_buffer_in_bank(int bank, size_t size, cl_mem_flags flags) { if (!is_initialized) { throw_lineexception("Attempted to create buffer before initialization"); } cl_mem_ext_ptr_t bank_ext; bank_ext.flags = bank | XCL_MEM_TOPOLOGY; bank_ext.obj = NULL; bank_ext.param = 0; cl::Buffer buf(context, flags | CL_MEM_EXT_PTR_XILINX, size, &bank_ext, NULL); return buf; } int XilinxOclHelper::get_fd_for_buffer(cl::Buffer buf) { int fd; xclGetMemObjectFd(buf(), &fd); return fd; } cl::Buffer XilinxOclHelper::get_buffer_from_fd(int fd) { cl::Buffer buffer; xclGetMemObjectFromFd(context(), device(), 0, fd, &buffer()); return buffer; } const cl::Context &XilinxOclHelper::get_context() { return context; } XilinxOclHelper::XilinxOclHelper() { } XilinxOclHelper::~XilinxOclHelper() { } } // namespace example_utils } // namespace xilinx
1,701
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"Nerville-la-Forêt","circ":"2ème circonscription","dpt":"Val-d'Oise","inscrits":448,"abs":200,"votants":248,"blancs":17,"nuls":4,"exp":227,"res":[{"nuance":"LR","nom":"M. <NAME>","voix":120},{"nuance":"REM","nom":"M. <NAME>","voix":107}]}
120
3,651
<reponame>aberdev/orientdb package com.orientechnologies.orient.core.storage.cluster; public class OClusterPageDebug { public long pageIndex = -1; public int inPagePosition = -1; public int inPageSize = -1; public byte[] content; }
80
14,668
// Copyright 2021 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 <cstdint> #include <memory> #include <utility> #include <vector> #include "ash/constants/app_types.h" #include "base/files/scoped_temp_dir.h" #include "base/run_loop.h" #include "base/test/bind.h" #include "base/test/scoped_feature_list.h" #include "base/timer/timer.h" #include "components/app_restore/app_launch_info.h" #include "components/app_restore/app_restore_data.h" #include "components/app_restore/features.h" #include "components/app_restore/full_restore_read_handler.h" #include "components/app_restore/full_restore_save_handler.h" #include "components/app_restore/full_restore_utils.h" #include "components/app_restore/restore_data.h" #include "components/app_restore/window_info.h" #include "components/app_restore/window_properties.h" #include "content/public/test/browser_task_environment.h" #include "extensions/common/constants.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/test/test_windows.h" #include "ui/aura/window.h" #include "url/gurl.h" namespace full_restore { namespace { constexpr char kAppId[] = "aaa"; constexpr int32_t kId1 = 100; constexpr int32_t kId2 = 200; constexpr int32_t kId3 = 300; constexpr int32_t kActivationIndex1 = 100; constexpr int32_t kActivationIndex2 = 101; constexpr int32_t kArcSessionId1 = 1; constexpr int32_t kArcSessionId2 = app_restore::kArcSessionIdOffsetForRestoredLaunching + 1; constexpr int32_t kArcTaskId1 = 666; constexpr int32_t kArcTaskId2 = 888; constexpr char kFilePath1[] = "path1"; constexpr char kFilePath2[] = "path2"; constexpr char kHandlerId[] = "audio"; constexpr char kExampleUrl1[] = "https://www.example1.com"; constexpr char kExampleUrl2[] = "https://www.example2.com"; } // namespace class FullRestoreReadHandlerTestApi { public: explicit FullRestoreReadHandlerTestApi(FullRestoreReadHandler* read_handler) : read_handler_(read_handler) {} FullRestoreReadHandlerTestApi(const FullRestoreReadHandlerTestApi&) = delete; FullRestoreReadHandlerTestApi& operator=( const FullRestoreReadHandlerTestApi&) = delete; ~FullRestoreReadHandlerTestApi() = default; const app_restore::ArcReadHandler* GetArcReadHander() const { DCHECK(read_handler_); return read_handler_->arc_read_handler_.get(); } const std::map<int32_t, std::string>& GetArcWindowIdMap() const { const auto* arc_read_handler = GetArcReadHander(); DCHECK(arc_read_handler); return arc_read_handler->window_id_to_app_id_; } const std::map<int32_t, int32_t>& GetArcSessionIdMap() const { const auto* arc_read_handler = GetArcReadHander(); DCHECK(arc_read_handler); return arc_read_handler->session_id_to_window_id_; } const std::map<int32_t, int32_t>& GetArcTaskIdMap() const { const auto* arc_read_handler = GetArcReadHander(); DCHECK(arc_read_handler); return arc_read_handler->task_id_to_window_id_; } void ClearRestoreData() { read_handler_->profile_path_to_restore_data_.clear(); } private: FullRestoreReadHandler* read_handler_; }; class FullRestoreSaveHandlerTestApi { public: explicit FullRestoreSaveHandlerTestApi(FullRestoreSaveHandler* save_handler) : save_handler_(save_handler) {} FullRestoreSaveHandlerTestApi(const FullRestoreSaveHandlerTestApi&) = delete; FullRestoreSaveHandlerTestApi& operator=( const FullRestoreSaveHandlerTestApi&) = delete; ~FullRestoreSaveHandlerTestApi() = default; const ArcSaveHandler* GetArcSaveHander() const { DCHECK(save_handler_); return save_handler_->arc_save_handler_.get(); } const ArcSaveHandler::SessionIdMap& GetArcSessionIdMap() const { const auto* arc_save_handler = GetArcSaveHander(); DCHECK(arc_save_handler); return arc_save_handler->session_id_to_app_launch_info_; } const std::map<int32_t, std::string>& GetArcTaskIdMap() const { const auto* arc_save_handler = GetArcSaveHander(); DCHECK(arc_save_handler); return arc_save_handler->task_id_to_app_id_; } void ModifyLaunchTime(int32_t session_id) { auto& session_id_to_app_launch_info = arc_save_handler()->session_id_to_app_launch_info_; auto it = session_id_to_app_launch_info.find(session_id); if (it == session_id_to_app_launch_info.end()) return; // If there is no task created for the session id in 600 seconds, the // session id record is removed. So set the record time as 601 seconds ago, // so that CheckTasksForAppLaunching can remove the session id record to // simulate the task is not created for the session id. it->second.second = it->second.second - base::Seconds(601); } base::RepeatingTimer* GetArcCheckTimer() { return &arc_save_handler()->check_timer_; } void CheckArcTasks() { arc_save_handler()->CheckTasksForAppLaunching(); } void ClearRestoreData() { save_handler_->profile_path_to_restore_data_.clear(); } private: ArcSaveHandler* arc_save_handler() { DCHECK(save_handler_); DCHECK(save_handler_->arc_save_handler_.get()); return save_handler_->arc_save_handler_.get(); } FullRestoreSaveHandler* save_handler_; }; // Unit tests for restore data. class FullRestoreReadAndSaveTest : public testing::Test { public: FullRestoreReadAndSaveTest() = default; ~FullRestoreReadAndSaveTest() override = default; FullRestoreReadAndSaveTest(const FullRestoreReadAndSaveTest&) = delete; FullRestoreReadAndSaveTest& operator=(const FullRestoreReadAndSaveTest&) = delete; void SetUp() override { scoped_feature_list_.InitAndEnableFeature(features::kFullRestore); ASSERT_TRUE(tmp_dir_.CreateUniqueTempDir()); } void TearDown() override { FullRestoreSaveHandler::GetInstance()->ClearForTesting(); } const base::FilePath& GetPath() { return tmp_dir_.GetPath(); } void ReadFromFile(const base::FilePath& file_path, bool clear_data = true) { FullRestoreReadHandler* read_handler = FullRestoreReadHandler::GetInstance(); if (clear_data) FullRestoreReadHandlerTestApi(read_handler).ClearRestoreData(); base::RunLoop run_loop; read_handler->ReadFromFile( file_path, base::BindLambdaForTesting( [&](std::unique_ptr<app_restore::RestoreData> restore_data) { run_loop.Quit(); restore_data_ = std::move(restore_data); })); run_loop.Run(); } FullRestoreSaveHandler* GetSaveHandler(bool start_save_timer = true) { auto* save_handler = FullRestoreSaveHandler::GetInstance(); save_handler->SetActiveProfilePath(GetPath()); save_handler->AllowSave(); return save_handler; } const app_restore::RestoreData* GetRestoreData( const base::FilePath& file_path) { return restore_data_.get(); } void AddAppLaunchInfo(const base::FilePath& file_path, int32_t id) { SaveAppLaunchInfo(file_path, std::make_unique<app_restore::AppLaunchInfo>(kAppId, id)); } void AddArcAppLaunchInfo(const base::FilePath& file_path) { SaveAppLaunchInfo(file_path, std::make_unique<app_restore::AppLaunchInfo>( kAppId, /*event_flags=*/0, kArcSessionId1, /*display_id*/ 0)); } void AddBrowserLaunchInfo(const base::FilePath& file_path, int32_t id, std::vector<GURL> urls, int32_t active_tab_index = 0) { auto launch_info = std::make_unique<app_restore::AppLaunchInfo>( extension_misc::kChromeAppId, id); launch_info->urls = urls; launch_info->active_tab_index = active_tab_index; SaveAppLaunchInfo(file_path, std::move(launch_info)); } void AddChromeAppLaunchInfo(const base::FilePath& file_path) { auto app_launch_info = std::make_unique<app_restore::AppLaunchInfo>( kAppId, kHandlerId, std::vector<base::FilePath>{base::FilePath(kFilePath1), base::FilePath(kFilePath2)}); app_launch_info->window_id = kId1; SaveAppLaunchInfo(file_path, std::move(app_launch_info)); } std::unique_ptr<aura::Window> CreateWindowInfo( int32_t id, int32_t index, ash::AppType app_type = ash::AppType::BROWSER) { std::unique_ptr<aura::Window> window( aura::test::CreateTestWindowWithId(id, nullptr)); app_restore::WindowInfo window_info; window_info.window = window.get(); window->SetProperty(aura::client::kAppType, static_cast<int>(app_type)); window->SetProperty(app_restore::kWindowIdKey, id); window_info.activation_index = index; SaveWindowInfo(window_info); return window; } std::unique_ptr<app_restore::WindowInfo> GetArcWindowInfo( int32_t restore_window_id) { std::unique_ptr<aura::Window> window( aura::test::CreateTestWindowWithId(restore_window_id, nullptr)); window->SetProperty(aura::client::kAppType, static_cast<int>(ash::AppType::ARC_APP)); window->SetProperty(app_restore::kRestoreWindowIdKey, restore_window_id); return FullRestoreReadHandler::GetInstance()->GetWindowInfo(window.get()); } void VerifyRestoreData(const base::FilePath& file_path, int32_t id, int32_t index) { ReadFromFile(file_path); const auto* restore_data = GetRestoreData(file_path); ASSERT_TRUE(restore_data != nullptr); const auto& launch_list = restore_data->app_id_to_launch_list(); EXPECT_EQ(1u, launch_list.size()); // Verify for |kAppId|. const auto launch_list_it = launch_list.find(kAppId); EXPECT_TRUE(launch_list_it != launch_list.end()); EXPECT_EQ(1u, launch_list_it->second.size()); // Verify for |id|. const auto app_restore_data_it = launch_list_it->second.find(id); EXPECT_TRUE(app_restore_data_it != launch_list_it->second.end()); const auto& data = app_restore_data_it->second; EXPECT_TRUE(data->activation_index.has_value()); EXPECT_EQ(index, data->activation_index.value()); } content::BrowserTaskEnvironment& task_environment() { return task_environment_; } private: content::BrowserTaskEnvironment task_environment_; base::ScopedTempDir tmp_dir_; base::test::ScopedFeatureList scoped_feature_list_; std::unique_ptr<app_restore::RestoreData> restore_data_; }; TEST_F(FullRestoreReadAndSaveTest, ReadEmptyRestoreData) { ReadFromFile(GetPath()); const auto* restore_data = GetRestoreData(GetPath()); ASSERT_TRUE(restore_data); ASSERT_TRUE(restore_data->app_id_to_launch_list().empty()); } TEST_F(FullRestoreReadAndSaveTest, StopSavingWhenShutdown) { FullRestoreSaveHandler* save_handler = GetSaveHandler(); base::OneShotTimer* timer = save_handler->GetTimerForTesting(); // Add app launch info, and verify the timer starts. AddAppLaunchInfo(GetPath(), kId1); EXPECT_TRUE(timer->IsRunning()); // Simulate timeout. timer->FireNow(); task_environment().RunUntilIdle(); // Add one more app launch info, and verify the timer is running. AddAppLaunchInfo(GetPath(), kId2); EXPECT_TRUE(timer->IsRunning()); // Simulate shutdown. save_handler->SetShutDown(); // Simulate timeout. timer->FireNow(); task_environment().RunUntilIdle(); FullRestoreReadHandler* read_handler = FullRestoreReadHandler::GetInstance(); FullRestoreReadHandlerTestApi(read_handler).ClearRestoreData(); // Add one more app launch info, to simulate a window is created during the // system startup phase. AddAppLaunchInfo(GetPath(), kId3); timer->FireNow(); task_environment().RunUntilIdle(); ReadFromFile(GetPath(), /*clear_data=*/false); // Verify the restore data can be read correctly. const auto* restore_data = GetRestoreData(GetPath()); ASSERT_TRUE(restore_data); const auto& launch_list = restore_data->app_id_to_launch_list(); EXPECT_EQ(1u, launch_list.size()); // Verify for |kAppId|. const auto launch_list_it = launch_list.find(kAppId); EXPECT_TRUE(launch_list_it != launch_list.end()); EXPECT_EQ(1u, launch_list_it->second.size()); // Verify the restore data for `kId1` exists. EXPECT_TRUE(base::Contains(launch_list_it->second, kId1)); // Verify the restore data for `kId2` and `kId3` doesn't exist. EXPECT_FALSE(base::Contains(launch_list_it->second, kId2)); EXPECT_FALSE(base::Contains(launch_list_it->second, kId3)); } TEST_F(FullRestoreReadAndSaveTest, StartSaveTimer) { FullRestoreSaveHandler* save_handler = GetSaveHandler(); base::OneShotTimer* timer = save_handler->GetTimerForTesting(); // Add app launch info, and verify the timer starts. AddAppLaunchInfo(GetPath(), kId1); EXPECT_TRUE(timer->IsRunning()); // Simulate timeout. timer->FireNow(); task_environment().RunUntilIdle(); // Simulate the system reboots. FullRestoreReadHandler* read_handler = FullRestoreReadHandler::GetInstance(); FullRestoreReadHandlerTestApi(read_handler).ClearRestoreData(); save_handler->ClearForTesting(); // Add one more app launch info, to simulate an app is launched during the // system startup phase. AddAppLaunchInfo(GetPath(), kId2); // Verify `timer` doesn't start. EXPECT_FALSE(timer->IsRunning()); ReadFromFile(GetPath(), /*clear_data=*/false); // Verify the restore data can be read correctly. auto* restore_data = GetRestoreData(GetPath()); ASSERT_TRUE(restore_data); auto& launch_list1 = restore_data->app_id_to_launch_list(); EXPECT_EQ(1u, launch_list1.size()); // Verify for |kAppId|. auto launch_list_it = launch_list1.find(kAppId); EXPECT_TRUE(launch_list_it != launch_list1.end()); EXPECT_EQ(1u, launch_list_it->second.size()); // Verify the restore data for `kId1` exists. EXPECT_TRUE(base::Contains(launch_list_it->second, kId1)); // Verify the restore data for `kId2` doesn't exist. EXPECT_FALSE(base::Contains(launch_list_it->second, kId2)); // Simulate the system reboots. FullRestoreReadHandlerTestApi(read_handler).ClearRestoreData(); save_handler->ClearForTesting(); ReadFromFile(GetPath(), /*clear_data=*/false); // Verify the original restore data can be read correctly. restore_data = GetRestoreData(GetPath()); ASSERT_TRUE(restore_data); auto& launch_list2 = restore_data->app_id_to_launch_list(); EXPECT_EQ(1u, launch_list2.size()); // Verify for |kAppId|. launch_list_it = launch_list2.find(kAppId); EXPECT_TRUE(launch_list_it != launch_list2.end()); EXPECT_EQ(1u, launch_list_it->second.size()); // Verify the restore data for `kId1` exists. EXPECT_TRUE(base::Contains(launch_list_it->second, kId1)); // Verify the restore data for `kId2` doesn't exist. EXPECT_FALSE(base::Contains(launch_list_it->second, kId2)); } TEST_F(FullRestoreReadAndSaveTest, SaveAndReadRestoreData) { FullRestoreSaveHandler* save_handler = GetSaveHandler(); base::OneShotTimer* timer = save_handler->GetTimerForTesting(); // Add app launch info, and verify the timer starts. AddAppLaunchInfo(GetPath(), kId1); EXPECT_TRUE(timer->IsRunning()); // Add one more app launch info, and verify the timer is still running. AddAppLaunchInfo(GetPath(), kId2); EXPECT_TRUE(timer->IsRunning()); std::unique_ptr<aura::Window> window1 = CreateWindowInfo(kId2, kActivationIndex2); // Simulate timeout, and verify the timer stops. timer->FireNow(); task_environment().RunUntilIdle(); // Modify the window info, and verify the timer starts. std::unique_ptr<aura::Window> window2 = CreateWindowInfo(kId1, kActivationIndex1); EXPECT_TRUE(timer->IsRunning()); timer->FireNow(); task_environment().RunUntilIdle(); // Verify that GetAppId() can get correct app id for |window1| and |window2|. EXPECT_EQ(save_handler->GetAppId(window1.get()), kAppId); EXPECT_EQ(save_handler->GetAppId(window2.get()), kAppId); // Modify the window id from `kId2` to `kId3` for `kAppId`. save_handler->ModifyWindowId(GetPath(), kAppId, kId2, kId3); EXPECT_TRUE(timer->IsRunning()); timer->FireNow(); task_environment().RunUntilIdle(); // Verify now GetAppId() can still get correct id for |window1| whose // app_restore::kWindowIdKey has changed. EXPECT_EQ(save_handler->GetAppId(window1.get()), kAppId); ReadFromFile(GetPath()); // Verify the restore data can be read correctly. const auto* restore_data = GetRestoreData(GetPath()); ASSERT_TRUE(restore_data); const auto& launch_list = restore_data->app_id_to_launch_list(); EXPECT_EQ(1u, launch_list.size()); // Verify for |kAppId|. const auto launch_list_it = launch_list.find(kAppId); EXPECT_TRUE(launch_list_it != launch_list.end()); EXPECT_EQ(2u, launch_list_it->second.size()); // Verify for |kId1|. const auto app_restore_data_it1 = launch_list_it->second.find(kId1); EXPECT_TRUE(app_restore_data_it1 != launch_list_it->second.end()); const auto& data1 = app_restore_data_it1->second; EXPECT_TRUE(data1->activation_index.has_value()); EXPECT_EQ(kActivationIndex1, data1->activation_index.value()); // Verify the restore data for |kId2| doesn't exist. EXPECT_TRUE(!base::Contains(launch_list_it->second, kId2)); // Verify the restore data for |kId2| is moved to |kId3|. const auto app_restore_data_it3 = launch_list_it->second.find(kId3); ASSERT_NE(app_restore_data_it3, launch_list_it->second.end()); const auto& data3 = app_restore_data_it3->second; EXPECT_TRUE(data3->activation_index.has_value()); EXPECT_EQ(kActivationIndex2, data3->activation_index.value()); } TEST_F(FullRestoreReadAndSaveTest, MultipleFilePaths) { FullRestoreSaveHandler* save_handler = GetSaveHandler(); base::OneShotTimer* timer = save_handler->GetTimerForTesting(); base::ScopedTempDir tmp_dir1; base::ScopedTempDir tmp_dir2; ASSERT_TRUE(tmp_dir1.CreateUniqueTempDir()); ASSERT_TRUE(tmp_dir2.CreateUniqueTempDir()); save_handler->SetActiveProfilePath(tmp_dir1.GetPath()); // Add app launch info for |tmp_dir1|, and verify the timer starts. AddAppLaunchInfo(tmp_dir1.GetPath(), kId1); EXPECT_TRUE(timer->IsRunning()); // Add app launch info for |tmp_dir2|, and verify the timer is still running. AddAppLaunchInfo(tmp_dir2.GetPath(), kId2); EXPECT_TRUE(timer->IsRunning()); CreateWindowInfo(kId2, kActivationIndex2); // Simulate timeout, and verify the timer stops. timer->FireNow(); task_environment().RunUntilIdle(); EXPECT_FALSE(timer->IsRunning()); // Modify the window info, and verify the timer starts. CreateWindowInfo(kId1, kActivationIndex1); EXPECT_TRUE(timer->IsRunning()); timer->FireNow(); task_environment().RunUntilIdle(); VerifyRestoreData(tmp_dir1.GetPath(), kId1, kActivationIndex1); // Set the active profile path to `tmp_dir2` to simulate the user is switched. save_handler->SetActiveProfilePath(tmp_dir2.GetPath()); timer->FireNow(); task_environment().RunUntilIdle(); VerifyRestoreData(tmp_dir2.GetPath(), kId2, kActivationIndex2); } TEST_F(FullRestoreReadAndSaveTest, ClearRestoreData) { FullRestoreSaveHandler* save_handler = GetSaveHandler(); FullRestoreSaveHandlerTestApi test_api(save_handler); base::OneShotTimer* timer = save_handler->GetTimerForTesting(); // Add app launch info, and verify the timer starts. AddAppLaunchInfo(GetPath(), kId1); EXPECT_TRUE(timer->IsRunning()); // Simulate timeout. timer->FireNow(); task_environment().RunUntilIdle(); // Read the restore data. ReadFromFile(GetPath()); // Clear restore data to simulate the system reboot. test_api.ClearRestoreData(); // Verify the restore data can be read correctly. const auto* restore_data = GetRestoreData(GetPath()); ASSERT_TRUE(restore_data); const auto& launch_list = restore_data->app_id_to_launch_list(); EXPECT_EQ(1u, launch_list.size()); // Verify for `kAppId`. const auto launch_list_it = launch_list.find(kAppId); EXPECT_TRUE(launch_list_it != launch_list.end()); EXPECT_EQ(1u, launch_list_it->second.size()); // Verify for `kId1`. const auto app_restore_data_it1 = launch_list_it->second.find(kId1); EXPECT_TRUE(app_restore_data_it1 != launch_list_it->second.end()); // Simulate timeout to clear restore data. timer->FireNow(); task_environment().RunUntilIdle(); // Read the restore data. ReadFromFile(GetPath()); // Verify the restore data has been cleared. ASSERT_TRUE(GetRestoreData(GetPath())); ASSERT_TRUE(GetRestoreData(GetPath())->app_id_to_launch_list().empty()); } TEST_F(FullRestoreReadAndSaveTest, ArcWindowSaving) { FullRestoreSaveHandler* save_handler = GetSaveHandler(); FullRestoreSaveHandlerTestApi test_api(save_handler); save_handler->SetPrimaryProfilePath(GetPath()); base::OneShotTimer* timer = save_handler->GetTimerForTesting(); // Add an ARC app launch info. AddArcAppLaunchInfo(GetPath()); const ArcSaveHandler* arc_save_handler = test_api.GetArcSaveHander(); ASSERT_TRUE(arc_save_handler); const auto& arc_session_id_map = test_api.GetArcSessionIdMap(); EXPECT_EQ(1u, arc_session_id_map.size()); auto session_it = arc_session_id_map.find(kArcSessionId1); EXPECT_TRUE(session_it != arc_session_id_map.end()); // Create a task. Since we have got the task, the arc session id map can be // cleared. save_handler->OnTaskCreated(kAppId, kArcTaskId1, kArcSessionId1); EXPECT_TRUE(arc_session_id_map.empty()); const auto& task_id_map = test_api.GetArcTaskIdMap(); EXPECT_EQ(1u, task_id_map.size()); auto task_id = task_id_map.find(kArcTaskId1); EXPECT_TRUE(task_id != task_id_map.end()); // Create a window to associate with the task id. std::unique_ptr<aura::Window> window = CreateWindowInfo(kArcTaskId1, kActivationIndex1, ash::AppType::ARC_APP); // Test that using ARC task id we can get the correct app id for the window. EXPECT_EQ(save_handler->GetAppId(window.get()), kAppId); // Destroy the task. save_handler->OnTaskDestroyed(kArcTaskId1); EXPECT_TRUE(task_id_map.empty()); timer->FireNow(); task_environment().RunUntilIdle(); ReadFromFile(GetPath()); // Verify there is not restore data. const auto* restore_data = GetRestoreData(GetPath()); ASSERT_TRUE(restore_data); EXPECT_TRUE(restore_data->app_id_to_launch_list().empty()); } TEST_F(FullRestoreReadAndSaveTest, ArcLaunchWithoutTask) { FullRestoreSaveHandler* save_handler = GetSaveHandler(); FullRestoreSaveHandlerTestApi test_api(save_handler); save_handler->SetPrimaryProfilePath(GetPath()); base::OneShotTimer* timer = save_handler->GetTimerForTesting(); // Add an ARC app launch info. AddArcAppLaunchInfo(GetPath()); // Verify the ARC app launch info is saved to |arc_session_id_map|. const auto& arc_session_id_map = test_api.GetArcSessionIdMap(); EXPECT_EQ(1u, arc_session_id_map.size()); auto session_it = arc_session_id_map.find(kArcSessionId1); EXPECT_TRUE(session_it != arc_session_id_map.end()); // Verify the ARC check timer starts running. base::RepeatingTimer* arc_check_timer = test_api.GetArcCheckTimer(); EXPECT_TRUE(arc_check_timer->IsRunning()); // Simulate more than 30 seconds have passed, OnTaskCreated is not called, and // the ARC check timer is expired to remove the ARC app launch info. test_api.ModifyLaunchTime(kArcSessionId1); test_api.CheckArcTasks(); EXPECT_TRUE(arc_session_id_map.empty()); EXPECT_TRUE(test_api.GetArcTaskIdMap().empty()); EXPECT_FALSE(arc_check_timer->IsRunning()); // Verify the timer in FullRestoreSaveHandler is not running, because there is // no app launching info to save. EXPECT_FALSE(timer->IsRunning()); task_environment().RunUntilIdle(); ReadFromFile(GetPath()); // Verify there is not restore data. const auto* restore_data = GetRestoreData(GetPath()); ASSERT_TRUE(restore_data); EXPECT_TRUE(restore_data->app_id_to_launch_list().empty()); } TEST_F(FullRestoreReadAndSaveTest, ArcWindowRestore) { FullRestoreSaveHandler* save_handler = GetSaveHandler(); FullRestoreSaveHandlerTestApi save_test_api(save_handler); save_handler->SetPrimaryProfilePath(GetPath()); base::OneShotTimer* timer = save_handler->GetTimerForTesting(); // Add an ARC app launch info. AddArcAppLaunchInfo(GetPath()); const ArcSaveHandler* arc_save_handler = save_test_api.GetArcSaveHander(); ASSERT_TRUE(arc_save_handler); EXPECT_EQ(1u, save_test_api.GetArcSessionIdMap().size()); // Verify the ARC check timer starts running. base::RepeatingTimer* arc_check_timer = save_test_api.GetArcCheckTimer(); EXPECT_TRUE(arc_check_timer->IsRunning()); // Create a task. Since we have got the task, the arc session id map can be // cleared. save_handler->OnTaskCreated(kAppId, kArcTaskId1, kArcSessionId1); EXPECT_TRUE(save_test_api.GetArcSessionIdMap().empty()); EXPECT_EQ(1u, save_test_api.GetArcTaskIdMap().size()); EXPECT_FALSE(arc_check_timer->IsRunning()); // Modify the window info. CreateWindowInfo(kArcTaskId1, kActivationIndex1, ash::AppType::ARC_APP); timer->FireNow(); task_environment().RunUntilIdle(); ReadFromFile(GetPath()); // Verify the restore data can be read correctly. const auto* restore_data = GetRestoreData(GetPath()); ASSERT_TRUE(restore_data); FullRestoreReadHandler* read_handler = FullRestoreReadHandler::GetInstance(); FullRestoreReadHandlerTestApi read_test_api(read_handler); ASSERT_TRUE(read_test_api.GetArcReadHander()); EXPECT_EQ(1u, read_test_api.GetArcWindowIdMap().size()); // Verify the map from app ids to launch list: // std::map<app_id, std::map<window_id, std::unique_ptr<AppRestoreData>>> const auto& launch_list = restore_data->app_id_to_launch_list(); EXPECT_EQ(1u, launch_list.size()); // Verify the launch list for |kAppId|: // std::map<window_id, std::unique_ptr<AppRestoreData>> const auto launch_list_it = launch_list.find(kAppId); EXPECT_TRUE(launch_list_it != launch_list.end()); EXPECT_EQ(1u, launch_list_it->second.size()); // Verify that there is an AppRestoreData for the window id |kArcTaskId1|. const auto app_restore_data_it = launch_list_it->second.find(kArcTaskId1); EXPECT_TRUE(app_restore_data_it != launch_list_it->second.end()); // Verify the AppRestoreData. const std::unique_ptr<app_restore::AppRestoreData>& data = app_restore_data_it->second; EXPECT_TRUE(data->activation_index.has_value()); EXPECT_EQ(kActivationIndex1, data->activation_index.value()); // Simulate the ARC app launching, and set the arc session id kArcSessionId2 // for the restore window id |kArcTaskId1|. read_handler->SetArcSessionIdForWindowId(kArcSessionId2, kArcTaskId1); EXPECT_EQ(1u, read_test_api.GetArcSessionIdMap().size()); // Before OnTaskCreated is called, return |kArcTaskId1| for |kArcSessionId2| // to simulate the ghost window property setting. EXPECT_EQ(kArcTaskId1, app_restore::GetArcRestoreWindowIdForSessionId(kArcSessionId2)); // Before OnTaskCreated is called, return -1 to add the ARC app window to the // hidden container. EXPECT_EQ(app_restore::kParentToHiddenContainer, app_restore::GetArcRestoreWindowIdForTaskId(kArcTaskId2)); // Call OnTaskCreated to simulate that the ARC app with |kAppId| has been // launched, and the new task id |kArcTaskId2| has been created with // |kArcSessionId2| returned. read_handler->OnTaskCreated(kAppId, kArcTaskId2, kArcSessionId2); EXPECT_EQ(1u, read_test_api.GetArcTaskIdMap().size()); // Since we have got the new task with |kArcSessionId2|, the arc session id // map can be cleared. And verify that we can get the restore window id // |kArcTaskId1| with the new |kArcTaskId2|. EXPECT_TRUE(read_test_api.GetArcSessionIdMap().empty()); EXPECT_EQ(kArcTaskId1, app_restore::GetArcRestoreWindowIdForTaskId(kArcTaskId2)); // Verify |window_info| for |kArcTaskId1|. auto window_info = GetArcWindowInfo(kArcTaskId1); EXPECT_TRUE(window_info); EXPECT_EQ(kActivationIndex1, window_info->activation_index); // Call OnTaskDestroyed to simulate the ARC app launching has been finished // for |kArcTaskId2|, and verify the task id map is now empty and a invalid // value is returned when trying to get the restore window id. read_handler->OnTaskDestroyed(kArcTaskId2); EXPECT_EQ(0, app_restore::GetArcRestoreWindowIdForTaskId(kArcTaskId2)); EXPECT_TRUE(read_test_api.GetArcTaskIdMap().empty()); EXPECT_TRUE(read_test_api.GetArcWindowIdMap().empty()); } TEST_F(FullRestoreReadAndSaveTest, ReadBrowserRestoreData) { FullRestoreSaveHandler* save_handler = GetSaveHandler(); base::OneShotTimer* timer = save_handler->GetTimerForTesting(); // Add browser launch info. std::vector<GURL> urls = {GURL(kExampleUrl1), GURL(kExampleUrl2)}; const int active_tab_index = 1; AddBrowserLaunchInfo(GetPath(), kId1, urls, /*active_tab_index=*/active_tab_index); EXPECT_TRUE(timer->IsRunning()); timer->FireNow(); task_environment().RunUntilIdle(); // Now read from the file. ReadFromFile(GetPath()); const auto* restore_data = GetRestoreData(GetPath()); ASSERT_TRUE(restore_data); const auto& launch_list = restore_data->app_id_to_launch_list(); EXPECT_EQ(1u, launch_list.size()); const auto launch_list_it = launch_list.find(extension_misc::kChromeAppId); EXPECT_TRUE(launch_list_it != launch_list.end()); EXPECT_EQ(1u, launch_list_it->second.size()); const auto app_restore_data_it = launch_list_it->second.find(kId1); EXPECT_TRUE(app_restore_data_it != launch_list_it->second.end()); const auto& data = app_restore_data_it->second; EXPECT_TRUE(data->urls.has_value()); EXPECT_EQ(data->urls.value().size(), 2u); EXPECT_EQ(data->urls.value()[0], GURL(kExampleUrl1)); EXPECT_EQ(data->urls.value()[1], GURL(kExampleUrl2)); EXPECT_TRUE(data->active_tab_index.has_value()); EXPECT_EQ(data->active_tab_index.value(), active_tab_index); } TEST_F(FullRestoreReadAndSaveTest, ReadChromeAppRestoreData) { FullRestoreSaveHandler* save_handler = GetSaveHandler(); base::OneShotTimer* timer = save_handler->GetTimerForTesting(); // Add Chrome app launch info. AddChromeAppLaunchInfo(GetPath()); EXPECT_TRUE(timer->IsRunning()); timer->FireNow(); task_environment().RunUntilIdle(); // Now read from the file. ReadFromFile(GetPath()); const auto* restore_data = GetRestoreData(GetPath()); ASSERT_TRUE(restore_data); const auto& launch_list = restore_data->app_id_to_launch_list(); EXPECT_EQ(1u, launch_list.size()); const auto launch_list_it = launch_list.find(kAppId); EXPECT_TRUE(launch_list_it != launch_list.end()); EXPECT_EQ(1u, launch_list_it->second.size()); const auto app_restore_data_it = launch_list_it->second.find(kId1); EXPECT_TRUE(app_restore_data_it != launch_list_it->second.end()); const auto& data = app_restore_data_it->second; EXPECT_TRUE(data->handler_id.has_value()); EXPECT_EQ(kHandlerId, data->handler_id.value()); EXPECT_TRUE(data->file_paths.has_value()); EXPECT_EQ(2u, data->file_paths.value().size()); EXPECT_EQ(base::FilePath(kFilePath1), data->file_paths.value()[0]); EXPECT_EQ(base::FilePath(kFilePath2), data->file_paths.value()[1]); } } // namespace full_restore
11,273
399
/* * 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. */ package com.wgzhao.addax.plugin.reader.httpreader; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONPath; import com.alibaba.fastjson.serializer.SerializerFeature; import com.wgzhao.addax.common.element.Record; import com.wgzhao.addax.common.element.StringColumn; import com.wgzhao.addax.common.exception.AddaxException; import com.wgzhao.addax.common.plugin.RecordSender; import com.wgzhao.addax.common.spi.Reader; import com.wgzhao.addax.common.util.Configuration; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.client.utils.URIBuilder; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.protocol.HttpContext; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.util.EntityUtils; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.Socket; import java.net.SocketTimeoutException; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class HttpReader extends Reader { public static class Job extends Reader.Job { private Configuration originConfig = null; @Override public void init() { this.originConfig = this.getPluginJobConf(); } @Override public void destroy() { // } @Override public List<Configuration> split(int adviceNumber) { List<Configuration> result = new ArrayList<>(); result.add(this.originConfig); return result; } } public static class Task extends Reader.Task { private Configuration readerSliceConfig = null; private URIBuilder uriBuilder; private final HttpClientContext context = HttpClientContext.create(); private String username; private String password; @Override public void init() { this.readerSliceConfig = this.getPluginJobConf(); this.username = readerSliceConfig.getString(HttpKey.USERNAME, null); this.password = readerSliceConfig.getString(HttpKey.PASSWORD, null); Configuration conn = readerSliceConfig.getListConfiguration(HttpKey.CONNECTION).get(0); uriBuilder = new URIBuilder(URI.create(conn.getString(HttpKey.URL))); if (conn.getString(HttpKey.PROXY, null) != null) { // set proxy createProxy(conn.getConfiguration(HttpKey.PROXY)); } Map<String, Object> requestParams = readerSliceConfig.getMap(HttpKey.REQUEST_PARAMETERS, new HashMap<>()); requestParams.forEach((k, v) -> uriBuilder.setParameter(k, v.toString())); } @Override public void destroy() { // } @Override public void startRead(RecordSender recordSender) { String method = readerSliceConfig.getString(HttpKey.METHOD, "get"); CloseableHttpResponse response; try { response = createCloseableHttpResponse(method); StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() != HttpStatus.SC_OK) { response.getEntity().getContent().close(); throw new IOException(statusLine.getReasonPhrase()); } HttpEntity entity = response.getEntity(); String encoding = readerSliceConfig.getString(HttpKey.ENCODING, null); Charset charset; if (encoding != null) { charset = Charset.forName(encoding); } else { charset = StandardCharsets.UTF_8; } String json = EntityUtils.toString(entity, charset); JSONArray jsonArray = null; String key = readerSliceConfig.get(HttpKey.RESULT_KEY, null); Object object; if (key != null) { object = JSON.parseObject(json).get(key); } else { object = JSON.parse(json); } // 需要判断返回的结果仅仅是一条记录还是多条记录,如果是一条记录,则是一个map // 否则是一个array if (object instanceof JSONArray) { // 有空值的情况下, toString会过滤掉,所以不能简单的使用 object.toString()方式 // https://github.com/wgzhao/Addax/issues/171 jsonArray = JSON.parseArray(JSONObject.toJSONString(object, SerializerFeature.WriteMapNullValue)); } else if (object instanceof JSONObject) { jsonArray = new JSONArray(); jsonArray.add(object); } if (jsonArray == null || jsonArray.isEmpty()) { // empty result return; } List<String> columns = readerSliceConfig.getList(HttpKey.COLUMN, String.class); if (columns == null || columns.isEmpty()) { throw AddaxException.asAddaxException( HttpReaderErrorCode.REQUIRED_VALUE, "The parameter [" + HttpKey.COLUMN + "] is not set." ); } Record record; JSONObject jsonObject = jsonArray.getJSONObject(0); if (columns.size() == 1 && "*".equals(columns.get(0))) { // 没有给定key的情况下,提取JSON的第一层key作为字段处理 columns.remove(0); for (Object obj : JSONPath.keySet(jsonObject, "/")) { columns.add(obj.toString()); } } for (int i = 0; i < jsonArray.size(); i++) { jsonObject = jsonArray.getJSONObject(i); record = recordSender.createRecord(); for (String k : columns) { Object v = JSONPath.eval(jsonObject, k); if (v == null) { record.addColumn(new StringColumn()); } else { record.addColumn(new StringColumn(v.toString())); } } recordSender.sendToWriter(record); } } catch (URISyntaxException | IOException e) { throw AddaxException.asAddaxException( HttpReaderErrorCode.ILLEGAL_VALUE, e.getMessage() ); } } private void createProxy(Configuration proxyConf) { String host = proxyConf.getString(HttpKey.HOST); URI uri = URI.create(host); this.context.setAttribute("proxy", uri); } private CloseableHttpResponse createCloseableHttpResponse(String method) throws URISyntaxException, IOException { Map<String, Object> headers = readerSliceConfig.getMap(HttpKey.HEADERS, new HashMap<>()); CloseableHttpClient httpClient; CloseableHttpResponse response; if ("get".equalsIgnoreCase(method)) { HttpGet request = new HttpGet(uriBuilder.build()); headers.forEach((k, v) -> request.setHeader(k, v.toString())); httpClient = createCloseableHttpClient(); response = httpClient.execute(request, this.context); } else if ("post".equalsIgnoreCase(method)) { HttpPost request = new HttpPost(uriBuilder.build()); headers.forEach((k, v) -> request.setHeader(k, v.toString())); httpClient = createCloseableHttpClient(); response = httpClient.execute(request, this.context); } else { throw AddaxException.asAddaxException( HttpReaderErrorCode.ILLEGAL_VALUE, "不支持的请求模式: " + method ); } return response; } private CloseableHttpClient createCloseableHttpClient() { HttpClientBuilder httpClientBuilder = HttpClients.custom(); if (context.getAttribute("proxy") != null) { Registry<ConnectionSocketFactory> reg = RegistryBuilder .<ConnectionSocketFactory>create() .register("http", new MyConnectionSocketFactory()) .register("https", new MyConnectionSocketFactory()) .build(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg); httpClientBuilder.setConnectionManager(cm); } if (this.password != null) { // setup BasicAuth CredentialsProvider provider = new BasicCredentialsProvider(); // Create the authentication scope HttpHost target = new HttpHost(uriBuilder.getHost(), uriBuilder.getPort(), uriBuilder.getScheme()); AuthScope scope = new AuthScope(target); // Create credential pair UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password); // Inject the credentials provider.setCredentials(scope, credentials); // Set the default credentials provider httpClientBuilder.setDefaultCredentialsProvider(provider); } httpClientBuilder.setSSLSocketFactory(ignoreSSLErrors()); return httpClientBuilder.build(); } private SSLConnectionSocketFactory ignoreSSLErrors() { try { // use the TrustSelfSignedStrategy to allow Self Signed Certificates SSLContext sslContext = SSLContextBuilder .create() .loadTrustMaterial(new TrustSelfSignedStrategy()) .build(); // we can optionally disable hostname verification. // if you don't want to further weaken the security, you don't have to include this. HostnameVerifier allowAllHosts = new NoopHostnameVerifier(); // create an SSL Socket Factory to use the SSLContext with the trust self-signed certificate strategy // and allow all hosts verifier. return new SSLConnectionSocketFactory(sslContext, allowAllHosts); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { e.printStackTrace(); return null; } } } static class MyConnectionSocketFactory implements ConnectionSocketFactory { @Override public Socket createSocket(final HttpContext context) { Proxy proxy = null; URI uri = (URI) context.getAttribute("proxy"); if (uri == null) { return null; } InetSocketAddress socksAddress = new InetSocketAddress(uri.getHost(), uri.getPort()); String proxyType = uri.getScheme(); if (proxyType.startsWith("socks")) { proxy = new Proxy(Proxy.Type.SOCKS, socksAddress); } else if (proxyType.startsWith("http")) { proxy = new Proxy(Proxy.Type.HTTP, socksAddress); } if (proxy == null) { return null; } else { return new Socket(proxy); } } @Override public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context) throws IOException { Socket sock; if (socket != null) { sock = socket; } else { sock = createSocket(context); } if (localAddress != null) { sock.bind(localAddress); } try { sock.connect(remoteAddress, connectTimeout); } catch (SocketTimeoutException ex) { throw new ConnectTimeoutException(ex, host, remoteAddress.getAddress()); } return sock; } } }
7,036
4,480
<filename>src/com/goide/inspections/GoRangeIterationOnIllegalTypeInspection.java<gh_stars>1000+ /* * Copyright 2013-2016 <NAME>, <NAME>, <NAME> * * 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. */ package com.goide.inspections; import com.goide.psi.GoExpression; import com.goide.psi.GoRangeClause; import com.goide.psi.GoType; import com.goide.psi.GoVisitor; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.psi.impl.GoTypeUtil; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import org.jetbrains.annotations.NotNull; public class GoRangeIterationOnIllegalTypeInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitRangeClause(@NotNull GoRangeClause o) { super.visitRangeClause(o); GoExpression expression = o.getRangeExpression(); GoType type = expression != null ? expression.getGoType(null) : null; if (type != null && !GoTypeUtil.isIterable(type)) { holder.registerProblem(expression, "Cannot range over data (type " + GoPsiImplUtil.getText(type) + ")", ProblemHighlightType.GENERIC_ERROR_OR_WARNING); } } }; } }
671
372
<filename>lwtest/src/lsa/lwt_lsa_check_group_info.c /* Editor Settings: expandtabs and use 4 spaces for indentation * ex: set softtabstop=4 tabstop=8 expandtab shiftwidth=4: * * -*- mode: c, c-basic-offset: 4 -*- */ /* * Copyright © BeyondTrust Software 2004 - 2019 * 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. * * BEYONDTRUST MAKES THIS SOFTWARE AVAILABLE UNDER OTHER LICENSING TERMS AS * WELL. IF YOU HAVE ENTERED INTO A SEPARATE LICENSE AGREEMENT WITH * BEYONDTRUST, THEN YOU MAY ELECT TO USE THE SOFTWARE UNDER THE TERMS OF THAT * SOFTWARE LICENSE AGREEMENT INSTEAD OF THE TERMS OF THE APACHE LICENSE, * NOTWITHSTANDING THE ABOVE NOTICE. IF YOU HAVE QUESTIONS, OR WISH TO REQUEST * A COPY OF THE ALTERNATE LICENSING TERMS OFFERED BY BEYONDTRUST, PLEASE CONTACT * BEYONDTRUST AT beyondtrust.com/contact */ /* * Module Name: lwt_lsa_check_group_info.c * * Verifies the group information returned from AD with the CSV file. * */ #include "includes.h" #define MAX_GROUP_INFOLEVEL 1 /* 0 and 1*/ /* * ValidateForInvalidParams * * Function validates the API for Invalid function parameters. * */ static DWORD ValidateForInvalidParams( HANDLE hLsaConnection, PTESTDATA pTestData ); static DWORD CheckForInvalidParams( HANDLE hLsaConnection, PLWTFAILDATA pInvalidData, DWORD dwGroupInfoLevel, PSTR pszMessage ); /* * ValidateGroupInfoLevel0 * * Function validates group level 0 information from AD with group information in csv file * */ static DWORD ValidateGroupInfoLevel0( PLSA_GROUP_INFO_0 pADGroupInfoList, PLWTGROUP pGroupList ) { DWORD dwError = LW_ERROR_SUCCESS; PCSTR pszTestDescription = "Validating level 0 group information"; PCSTR pszTestAPIs = "LsaGetGroupsForUserByName"; CHAR szTestMsg[256] = { 0 }; snprintf(szTestMsg, sizeof(szTestMsg), "Validating group info level 0 for group:%s\n", pADGroupInfoList->pszName); if (!pGroupList) { dwError = LW_ERROR_TEST_FAILED; snprintf(szTestMsg, sizeof(szTestMsg), "Grouplist structure don't have group information for group:%s\n", pADGroupInfoList->pszName); LWT_LOG_TEST(szTestMsg); goto error; } if (pGroupList->nGid != pADGroupInfoList->gid) { dwError = LW_ERROR_TEST_FAILED; snprintf(szTestMsg, sizeof(szTestMsg), "GID value mismatch for group:'%s', grouplist csv gives:%lu and API returns:%lu\n", pADGroupInfoList->pszName, (unsigned long)pGroupList->nGid, (unsigned long)pADGroupInfoList->gid); goto error; } if (!StringsAreEqual(pGroupList->pszSid, pADGroupInfoList->pszSid)) { dwError = LW_ERROR_TEST_FAILED; snprintf(szTestMsg, sizeof(szTestMsg), "SID value mismatch for group:'%s', \ grouplist csv file gives:%s and API returns:%s\n", pADGroupInfoList->pszName, pGroupList->pszSid, pADGroupInfoList->pszSid); goto error; } cleanup: LWT_LOG_TEST(szTestMsg); return dwError; error: goto cleanup; } /* * ValidateGroupMember * * Function validates a group member for group information * between user list and group list csv files. * */ static DWORD ValidateGroupMember( PSTR pszMember, PLWTGROUP pGroupList, PTESTDATA pTestData ) { DWORD dwError = LW_ERROR_SUCCESS; DWORD dwIndex = 0; PCSTR pszTestDescription = "Validating Group member with userlist structure"; PCSTR pszTestAPIs = "LsaGetGroupsForUserByName"; CHAR szTestMsg[256] = { 0 }; for (dwIndex = 0; dwIndex < pTestData->dwNumUsers; dwIndex++) { if (StringsAreEqual(pszMember, pTestData->ppUserList[dwIndex]->pszNetBiosName)) { if (pTestData->ppUserList[dwIndex]->nUserGid != pGroupList->nGid) { dwError = LW_ERROR_TEST_FAILED; snprintf(szTestMsg, sizeof(szTestMsg), "Group member:%s have different GID:'%lu' than its \ associated group:'%s's gid:'%lu'\n", pszMember, (unsigned long)pTestData->ppUserList[dwIndex]->nUserGid, (unsigned long)pGroupList->pszName, pGroupList->nGid); goto error; } } } if (dwIndex == pTestData->dwNumUsers) { dwError = LW_ERROR_TEST_FAILED; snprintf(szTestMsg, sizeof(szTestMsg), "Group member:%s is not found in userlist structure\n", pszMember); goto error; } cleanup: return dwError; error: LWT_LOG_TEST(szTestMsg); goto cleanup; } /* * SearchAndValidateGroupMember * * Function checks for existance of members in one list with the other list * */ static DWORD SearchAndValidateGroupMember( PSTR* ppszGrpMemberList_1, PSTR* ppszGrpMemberList_2 ) { DWORD dwError = LW_ERROR_SUCCESS; DWORD dwFirstMemberList = 0; PCSTR pszTestDescription = "Validating Group members in AD group and csv group structure"; PCSTR pszTestAPIs = "LsaGetGroupsForUserByName"; CHAR szTestMsg[256] = { 0 }; while (!IsNullOrEmpty(ppszGrpMemberList_1[dwFirstMemberList])) { BOOL bFound = FALSE; DWORD dwSecondMemberList = 0; while (!IsNullOrEmpty(ppszGrpMemberList_2[dwSecondMemberList])) { if (StringsAreEqual(ppszGrpMemberList_1[dwFirstMemberList], ppszGrpMemberList_2[dwSecondMemberList])) { bFound = TRUE; break; } dwSecondMemberList++; } if (FALSE == bFound) { dwError = LW_ERROR_TEST_FAILED; snprintf(szTestMsg, sizeof(szTestMsg), "Group member:'%s' is missing either in \ AD group list or group list structure\n", ppszGrpMemberList_1[dwFirstMemberList]); goto error; } dwFirstMemberList++; } cleanup: return dwError; error: LWT_LOG_TEST(szTestMsg); goto cleanup; } /* * ValidateGroupMembers * * Function validates group informations of group members. * */ static DWORD ValidateGroupMembers( PSTR* ppszMembers, PLWTGROUP pGroupList, PTESTDATA pTestData ) { DWORD dwError = LW_ERROR_SUCCESS; DWORD dwLocalError = LW_ERROR_SUCCESS; DWORD dwMember = 0; dwLocalError = SearchAndValidateGroupMember(pGroupList->ppszMembers, ppszMembers); BAIL_ON_TEST_BROKE(dwLocalError); dwLocalError = SearchAndValidateGroupMember(ppszMembers, pGroupList->ppszMembers); BAIL_ON_TEST_BROKE(dwLocalError); while (!IsNullOrEmpty(ppszMembers[dwMember])) { dwLocalError = ValidateGroupMember(ppszMembers[dwMember], pGroupList, pTestData); BAIL_ON_TEST_BROKE(dwLocalError); dwMember++; } cleanup: return dwError; error: goto cleanup; } /* * ValidateGroupInfoLeve1 * * Function validates group level 1 information * from AD with group information in csv file * */ static DWORD ValidateGroupInfoLevel1( PLSA_GROUP_INFO_1 pADGroupInfoList, PLWTGROUP pGroupList, PTESTDATA pTestData ) { DWORD dwError = LW_ERROR_SUCCESS; DWORD dwLocalError = LW_ERROR_SUCCESS; PCSTR pszTestDescription = "Comparing Level 1 Group information of a user"; PCSTR pszTestAPIs = "LsaGetGroupsForUserByName"; CHAR szTestMsg[256] = { 0 }; if (!pGroupList) { dwError = LW_ERROR_TEST_FAILED; snprintf(szTestMsg, sizeof(szTestMsg), "CSV file don't have group information for group:%s\n", pADGroupInfoList->pszName); goto error; } if ((!pGroupList->ppszMembers && pADGroupInfoList->ppszMembers) || (pGroupList->ppszMembers && !pADGroupInfoList->ppszMembers)) { dwError = LW_ERROR_TEST_FAILED; snprintf(szTestMsg, sizeof(szTestMsg), "Mismatch in Group member list in AD and \ group structure for group:'%s'\n", pADGroupInfoList->pszName); goto error; } else if (pGroupList->ppszMembers && pADGroupInfoList->ppszMembers) { dwLocalError = ValidateGroupMembers(pADGroupInfoList->ppszMembers, pGroupList, pTestData); BAIL_ON_TEST_BROKE(dwLocalError); } if (pGroupList->nGid != pADGroupInfoList->gid) { dwError = LW_ERROR_TEST_FAILED; snprintf(szTestMsg, sizeof(szTestMsg), "GID value mismatch for group:'%s', \ csv file gives:%lu and API returns:%lu\n", pADGroupInfoList->pszName, (unsigned long)pGroupList->nGid, (unsigned long)pADGroupInfoList->gid ); goto error; } if (!StringsAreEqual(pGroupList->pszSid, pADGroupInfoList->pszSid)) { dwError = LW_ERROR_TEST_FAILED; snprintf(szTestMsg, sizeof(szTestMsg), "SID value mismatch for group:'%s', \ csv file gives:'%s' and API returns:'%s'\n", pADGroupInfoList->pszName, pGroupList->pszSid, pADGroupInfoList->pszSid); goto error; } if (!StringsAreEqual(pGroupList->pszDN, pADGroupInfoList->pszDN)) { dwError = LW_ERROR_TEST_FAILED; snprintf(szTestMsg, sizeof(szTestMsg), "DN mismatch for group:'%s', \ csv file gives:'%s' and API returns:'%s'\n", pADGroupInfoList->pszName, pGroupList->pszDN, pADGroupInfoList->pszDN); goto error; } if (!StringsAreEqual(pGroupList->pszPassword, pADGroupInfoList->pszPasswd)) { dwError = LW_ERROR_TEST_FAILED; snprintf(szTestMsg, sizeof(szTestMsg), "Password mismatch for group:'%s', \ csv file gives:'%s' and API returns:'%s'\n", pADGroupInfoList->pszName, pGroupList->pszPassword, pADGroupInfoList->pszPasswd); goto error; } cleanup: return dwError; error: LWT_LOG_TEST(szTestMsg); goto cleanup; } /* * CompareGroupInfoLevels * * Function compares group information in level 0 and level1 * */ static DWORD CompareGroupInfoLevels( PLSA_GROUP_INFO_0 *ppListGrpInfoLevel0, DWORD dwGrpCountInLevel0, PLSA_GROUP_INFO_1 *ppListGrpInfoLevel1, DWORD dwGrpCountInLevel1 ) { DWORD dwError = LW_ERROR_SUCCESS; DWORD dwArrIndex1 = 0; DWORD dwArrIndex2 = 0; BOOL bUserFound = FALSE; PCSTR pszTestDescription = "Comparing Group information between level 0 and level 1"; PCSTR pszTestAPIs = "LsaGetGroupsForUserByName"; CHAR szTestMsg[256] = { 0 }; for (dwArrIndex1 = 0;dwArrIndex1 < dwGrpCountInLevel0; dwArrIndex1++) { bUserFound = FALSE; for (dwArrIndex2 = 0; dwArrIndex2 < dwGrpCountInLevel1; dwArrIndex2++) { if (ppListGrpInfoLevel0[dwArrIndex1] && ppListGrpInfoLevel1[dwArrIndex2]) { if (StringsAreEqual(ppListGrpInfoLevel0[dwArrIndex1]->pszName, ppListGrpInfoLevel1[dwArrIndex2]->pszName)) { bUserFound = TRUE; if (ppListGrpInfoLevel0[dwArrIndex1]->gid != ppListGrpInfoLevel1[dwArrIndex2]->gid) { dwError = LW_ERROR_TEST_FAILED; snprintf(szTestMsg, sizeof(szTestMsg), "GID mismatch for group:'%s', level 0 value:'%lu' and Level 1 value:'%lu'\n", ppListGrpInfoLevel0[dwArrIndex1]->pszName, (unsigned long)ppListGrpInfoLevel0[dwArrIndex1]->gid, (unsigned long)ppListGrpInfoLevel1[dwArrIndex2]->gid); LWT_LOG_TEST(szTestMsg); goto error; } if (!StringsAreEqual(ppListGrpInfoLevel0[dwArrIndex1]->pszSid, ppListGrpInfoLevel1[dwArrIndex2]->pszSid)) { dwError = LW_ERROR_TEST_FAILED; snprintf(szTestMsg, sizeof(szTestMsg), "SID value mismatch for group:'%s', level 0 value:'%s' and Level 1 value:'%s'\n", ppListGrpInfoLevel0[dwArrIndex1]->pszName, ppListGrpInfoLevel0[dwArrIndex1]->pszSid, ppListGrpInfoLevel1[dwArrIndex2]->pszSid); LWT_LOG_TEST(szTestMsg); goto error; } } } } if (FALSE == bUserFound) { dwError = LW_ERROR_TEST_FAILED; snprintf(szTestMsg, sizeof(szTestMsg), "User:'%s' doesn't exists in Group_Info_level 1\n", ppListGrpInfoLevel0[dwArrIndex1]->pszName); LWT_LOG_TEST(szTestMsg); goto error; } } cleanup: return dwError; error: goto cleanup; } /* * GetGroupListData * * Function gets the csv grouplist for a group * */ static DWORD GetGroupListData( PSTR pszGroupName, PTESTDATA pTestData, PLWTGROUP* ppGroupList ) { DWORD dwError = LW_ERROR_SUCCESS; DWORD dwGroupIndex = 0; PLWTGROUP pGroupList = NULL; for (dwGroupIndex = 0; dwGroupIndex < pTestData->dwNumGroups; dwGroupIndex++) { if (StringsNoCaseAreEqual(pszGroupName, pTestData->ppGroupList[dwGroupIndex]->pszName)) { pGroupList = pTestData->ppGroupList[dwGroupIndex]; break; } } /*cleanup: */ *ppGroupList = pGroupList; return dwError; /* error: goto cleanup;*/ } /* * VerifyUserGroupInfo * * Function gets and validates the group information for a user * */ static DWORD VerifyUserGroupInfo( HANDLE hLsaConnection, PTESTDATA pTestData, PCSTR pszUserName ) { DWORD dwError = LW_ERROR_SUCCESS; DWORD dwLocalError = LW_ERROR_SUCCESS; DWORD dwNumGroups = 0; DWORD dwGroupInfoLevel = 0; DWORD dwGrpCountInLevel0 = 0; DWORD dwGrpCountInLevel1 = 0; PVOID *ppGroupInfoList = NULL; LSA_FIND_FLAGS nFindFlags = 0; PLSA_GROUP_INFO_0 *ppListGrpInfoLevel0 = NULL; PLSA_GROUP_INFO_1 *ppListGrpInfoLevel1 = NULL; do { DWORD nIndex = 0; PLWTGROUP pGroupList = NULL; dwLocalError = LsaGetGroupsForUserByName( hLsaConnection, pszUserName, nFindFlags, dwGroupInfoLevel, &dwNumGroups, &ppGroupInfoList); BAIL_ON_TEST_BROKE(dwLocalError); switch (dwGroupInfoLevel) { case 0: ppListGrpInfoLevel0 = (PLSA_GROUP_INFO_0*)ppGroupInfoList; dwGrpCountInLevel0 = dwNumGroups; break; case 1: ppListGrpInfoLevel1 = (PLSA_GROUP_INFO_1*)ppGroupInfoList; dwGrpCountInLevel1 = dwNumGroups; break; default: break; } for (nIndex = 0; nIndex < dwNumGroups; nIndex++) { switch (dwGroupInfoLevel) { case 0: if (ppListGrpInfoLevel0[nIndex]) { GetGroupListData(ppListGrpInfoLevel0[nIndex]->pszName, pTestData, &pGroupList); dwLocalError = ValidateGroupInfoLevel0(ppListGrpInfoLevel0[nIndex], pGroupList); BAIL_ON_TEST_BROKE(dwLocalError); } break; case 1: if (ppListGrpInfoLevel1[nIndex]) { GetGroupListData(ppListGrpInfoLevel1[nIndex]->pszName, pTestData, &pGroupList); dwLocalError = ValidateGroupInfoLevel1(ppListGrpInfoLevel1[nIndex], pGroupList, pTestData); BAIL_ON_TEST_BROKE(dwLocalError); } break; default: dwError = LW_ERROR_UNSUPPORTED_GROUP_LEVEL; BAIL_ON_TEST_BROKE(dwError); break; } } dwGroupInfoLevel++; } while (dwGroupInfoLevel <= MAX_GROUP_INFOLEVEL); if (ppListGrpInfoLevel0 && ppListGrpInfoLevel1) { dwLocalError = CompareGroupInfoLevels(ppListGrpInfoLevel0, dwGrpCountInLevel0, ppListGrpInfoLevel1, dwGrpCountInLevel1); BAIL_ON_TEST_BROKE(dwLocalError); } cleanup: if (ppListGrpInfoLevel0) { LsaFreeGroupInfoList(0, (PVOID*)ppListGrpInfoLevel0, dwGrpCountInLevel0); ppListGrpInfoLevel0 = NULL; } if (ppListGrpInfoLevel1) { LsaFreeGroupInfoList(1, (PVOID*)ppListGrpInfoLevel1, dwGrpCountInLevel1); ppListGrpInfoLevel1 = NULL; } return dwError; error: goto cleanup; } /* * Lwt_LsaValidateUsersGroupInfo * * Function gets and validates the group information for users in userlist structure * */ DWORD Lwt_LsaValidateUsersGroupInfo( HANDLE hLsaConnection, PTESTDATA pTestData ) { DWORD dwError = LW_ERROR_SUCCESS; DWORD dwLocalError = LW_ERROR_SUCCESS; DWORD nUserIndex = 0; if ( !pTestData || !pTestData->ppUserList || !pTestData->ppGroupList ) { dwError = LW_ERROR_TEST_SKIPPED; goto error; } for (nUserIndex = 0 ; nUserIndex < pTestData->dwNumUsers; nUserIndex++) { PSTR pszName = NULL; if (!IsNullOrEmpty(pTestData->ppUserList[nUserIndex]->pszUserPrincipalName)) { pszName = pTestData->ppUserList[nUserIndex]->pszUserPrincipalName; } else if (!IsNullOrEmpty(pTestData->ppUserList[nUserIndex]->pszSamAccountName)) { pszName = pTestData->ppUserList[nUserIndex]->pszSamAccountName; } else { continue; } dwLocalError = VerifyUserGroupInfo(hLsaConnection, pTestData, pszName); BAIL_ON_TEST_BROKE(dwLocalError); } cleanup: return dwError; error: goto cleanup; } /* * Lwt_LsaNullAndInvalidParamsTest * * Function validates the API for NULL and invalid parameters. * */ DWORD Lwt_LsaNullAndInvalidParamsTest( HANDLE hLsaConnection, PSTR pszUserName ) { DWORD dwError = LW_ERROR_SUCCESS; DWORD dwLocalError = LW_ERROR_SUCCESS; DWORD dwNumGroups = 0; DWORD dwGroupInfoLevel = 0; PVOID *ppGroupInfoList = NULL; PCSTR pszTestDescription = "Testing the API behavior for NULL and Invalid parameters"; PCSTR pszTestAPIs = "LsaGetGroupsForUserByName"; CHAR szTestMsg[256] = { 0 }; LSA_FIND_FLAGS nFindFlags = 0; do { #if 0 /* Crashes the system - Testing NULL connection handler parameter*/ dwLocalError = LsaGetGroupsForUserByName( NULL, pszUserName, nFindFlags, dwGroupInfoLevel, &dwNumGroups, &ppGroupInfoList); if (!dwLocalError) { dwError = LW_ERROR_TEST_FAILED; snprintf(szTestMsg, sizeof(szTestMsg), "API failed for NULL Connection handler parameter in level %lu\n", (unsigned long)dwGroupInfoLevel); LWT_LOG_TEST(szTestMsg); } if (ppGroupInfoList) { LsaFreeGroupInfoList( dwGroupInfoLevel, ppGroupInfoList, dwNumGroups); ppGroupInfoList = NULL; } #endif /* Testing NULL username parameter - Function doesn't return error for NULL username. */ dwLocalError = LsaGetGroupsForUserByName( hLsaConnection, NULL, nFindFlags, dwGroupInfoLevel, &dwNumGroups, &ppGroupInfoList); if (!dwLocalError) { dwError = LW_ERROR_TEST_FAILED; snprintf( szTestMsg, sizeof(szTestMsg), "API failed for NULL User name parameter in level %lu\n", (unsigned long)dwGroupInfoLevel); LWT_LOG_TEST(szTestMsg); } if (ppGroupInfoList) { LsaFreeGroupInfoList( dwGroupInfoLevel, ppGroupInfoList, dwNumGroups); ppGroupInfoList = NULL; } #if 0 /* Crashes the system - Testing NULL pointer, representing number of groups, parameter */ dwLocalError = LsaGetGroupsForUserByName( hLsaConnection, pszUserName, nFindFlags, dwGroupInfoLevel, (PDWORD)NULL, &ppGroupInfoList); if (!dwLocalError) { dwError = LW_ERROR_TEST_FAILED; snprintf(szTestMsg, sizeof(szTestMsg), "API failed for NULL pointer for number of groups, parameter in level %lu\n", (unsigned long) dwGroupInfoLevel); LWT_LOG_TEST(szTestMsg); } if (ppGroupInfoList) { LsaFreeGroupInfoList( dwGroupInfoLevel, ppGroupInfoList, dwNumGroups); ppGroupInfoList = NULL; } /* Crashes the system - "Testing NULL GroupInfoList pointer */ dwLocalError = LsaGetGroupsForUserByName( hLsaConnection, pszUserName, nFindFlags, dwGroupInfoLevel, &dwNumGroups, (PVOID**)NULL); if (!dwLocalError) { dwError = LW_ERROR_TEST_FAILED; snprintf(szTestMsg, sizeof(szTestMsg), "API failed for NULL Group Info List pointer parameter in level %lu\n", (unsigned long)dwGroupInfoLevel); LWT_LOG_TEST(szTestMsg); } if (ppGroupInfoList) { LsaFreeGroupInfoList( dwGroupInfoLevel, ppGroupInfoList, dwNumGroups); ppGroupInfoList = NULL; } #endif /* Testing invalid FIND_FLAG parameter */ dwLocalError = LsaGetGroupsForUserByName( hLsaConnection, pszUserName, -1, dwGroupInfoLevel, &dwNumGroups, &ppGroupInfoList); if (!dwLocalError) { dwError = LW_ERROR_TEST_FAILED; snprintf(szTestMsg, sizeof(szTestMsg), "API failed for invalid FIND_FLAGS parameter in level %lu\n", (unsigned long)dwGroupInfoLevel); LWT_LOG_TEST(szTestMsg); } if (ppGroupInfoList) { LsaFreeGroupInfoList( dwGroupInfoLevel, ppGroupInfoList, dwNumGroups); ppGroupInfoList = NULL; } dwLocalError = LsaGetGroupsForUserByName( hLsaConnection, pszUserName, 1234567, dwGroupInfoLevel, &dwNumGroups, &ppGroupInfoList); if (!dwLocalError) { dwError = LW_ERROR_TEST_FAILED; snprintf(szTestMsg, sizeof(szTestMsg), "API failed for invalid FIND_FLAGS parameter in level %lu\n", (unsigned long)dwGroupInfoLevel); LWT_LOG_TEST(szTestMsg); } if (ppGroupInfoList) { LsaFreeGroupInfoList( dwGroupInfoLevel, ppGroupInfoList, dwNumGroups); ppGroupInfoList = NULL; } dwGroupInfoLevel++; }while (dwGroupInfoLevel <= MAX_GROUP_INFOLEVEL); cleanup: if (ppGroupInfoList) { LsaFreeGroupInfoList( dwGroupInfoLevel, ppGroupInfoList, dwNumGroups); ppGroupInfoList = NULL; } return dwError; error: goto cleanup; } int check_group_info_main( int argc, char *argv[] ) { DWORD dwError = LW_ERROR_SUCCESS; DWORD dwLocalError = LW_ERROR_SUCCESS; HANDLE hLsaConnection = (HANDLE)NULL; PTESTDATA pTestData = NULL; PSTR pszName = NULL; DWORD dwUserCount = 0; dwError = Lwt_LsaTestSetup( argc, argv, &hLsaConnection, &pTestData); if ( dwError ) goto error; dwLocalError = Lwt_LsaValidateUsersGroupInfo(hLsaConnection, pTestData); BAIL_ON_TEST_BROKE(dwLocalError); /* Getting a valid user name to do NULL and INVALID parameter test for API*/ do { if (!IsNullOrEmpty(pTestData->ppUserList[dwUserCount]->pszUserPrincipalName)) { pszName = pTestData->ppUserList[dwUserCount]->pszUserPrincipalName; break; } else if (!IsNullOrEmpty(pTestData->ppUserList[dwUserCount]->pszSamAccountName)) { pszName = pTestData->ppUserList[dwUserCount]->pszSamAccountName; break; } } while (++dwUserCount < pTestData->dwNumUsers); if (dwUserCount < pTestData->dwNumUsers) { dwLocalError = Lwt_LsaNullAndInvalidParamsTest(hLsaConnection, pszName); BAIL_ON_TEST_BROKE(dwLocalError); } dwLocalError = ValidateForInvalidParams(hLsaConnection, pTestData); BAIL_ON_TEST_BROKE(dwLocalError); cleanup: Lwt_LsaTestTeardown(&hLsaConnection, &pTestData); return LwtMapErrorToProgramStatus(dwError); error: goto cleanup; } /* * ValidateForInvalidParams * * Function validates the API for Invalid function parameters. * */ static DWORD ValidateForInvalidParams( HANDLE hLSAConnection, PTESTDATA pTestData ) { DWORD dwError = LW_ERROR_SUCCESS; DWORD dwLocalError = LW_ERROR_SUCCESS; DWORD dwTest = 0; PLWTFAILDATA pInvalidData = NULL; PSTR pszMessage = NULL; if ( !pTestData || !pTestData->pInvalidDataIface ) { dwLocalError = LW_ERROR_TEST_SKIPPED; BAIL_ON_TEST_BROKE(dwLocalError); } for ( dwTest = 0; dwTest < pTestData->dwNumInvalidDataSet; dwTest++ ) { dwLocalError = GetInvalidDataRecord( pTestData, dwTest, &pInvalidData); BAIL_ON_TEST_BROKE(dwLocalError); /* Testing invalid username parameter */ if ( LWTUSER_INVALID == pInvalidData->Field ) { pszMessage = "user name"; dwLocalError = CheckForInvalidParams( hLSAConnection, pInvalidData, pszMessage); BAIL_ON_TEST_BROKE(dwLocalError); } if ( LWTGROUPINFOLEVEL_INVALID == pInvalidData->Field ) { /* Testing invalid GroupInfoLevel parameter*/ pszMessage = "API returned with error code (%lu) for invalid group info level parameter" dwLocalError = CheckForInvalidParams( hLSAConnection, pInvalidData, pszMessage); BAIL_ON_TEST_BROKE(dwLocalError); } FreeInvalidDataRecord(pInvalidData); } error: return dwError; } static DWORD CheckForInvalidParams( HANDLE hLsaConnection, PLWTFAILDATA pInvalidData, DWORD dwGroupInfoLevel, PSTR pszMessage ) { DWORD dwError = LW_ERROR_SUCCESS; DWORD dwNumGroups = 0; PVOID *ppGroupInfoList = NULL; LSA_FIND_FLAGS nFindFlags = 0; PCSTR pszTestAPIs = "LsaGetGroupsForUserByName"; PCSTR pszTestDescription = "API returns invalid parameter error for invalid function parameters"; CHAR szTestMsg[256] = { 0 }; dwError = LsaGetGroupsForUserByName( hLsaConnection, pInvalidData->pszUserName, nFindFlags, pInvalidData->dwLevel, &dwNumGroups, &ppGroupInfoList); if ( dwLocalError != pInvalidData->dwErrorCode ) { snprintf( szTestMsg, sizeof(szTestMsg), "API returned with error code (%lu) for invalid (%s) parameter" (unsigned long)dwLocalError, pszMessage); LWT_LOG_TEST(szTestMsg); dwError = LW_ERROR_TEST_FAILED; } if (ppGroupInfoList) { LsaFreeGroupInfoList( pInvalidData->dwLevel, ppGroupInfoList, dwNumGroups); ppGroupInfoList = NULL; } cleanup: return dwError; error: goto cleanup; }
17,388
465
package com.ansel.bean; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; /** * 4.9 货运差错表 * @author Ansel * */ @Entity(name = "cargoerror") public class CargoError { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(length = 50) private String goodsRevertBillCode; @Column(length = 50) private String goodsBillCode; @Column(length = 50) private String customer; @Column(length = 50) private String goodsName; @Column(length = 50) private String mistakeType; @Column private int pieceAmount; @Column(length = 50) private String size; @Column private double goodsValue; public CargoError() { super(); } public CargoError(int id, String goodsRevertBillCode, String goodsBillCode, String customer, String goodsName, String mistakeType, int pieceAmount, String size, double goodsValue) { super(); this.id = id; this.goodsRevertBillCode = goodsRevertBillCode; this.goodsBillCode = goodsBillCode; this.customer = customer; this.goodsName = goodsName; this.mistakeType = mistakeType; this.pieceAmount = pieceAmount; this.size = size; this.goodsValue = goodsValue; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getGoodsRevertBillCode() { return goodsRevertBillCode; } public void setGoodsRevertBillCode(String goodsRevertBillCode) { this.goodsRevertBillCode = goodsRevertBillCode; } public String getGoodsBillCode() { return goodsBillCode; } public void setGoodsBillCode(String goodsBillCode) { this.goodsBillCode = goodsBillCode; } public String getCustomer() { return customer; } public void setCustomer(String customer) { this.customer = customer; } public String getGoodsName() { return goodsName; } public void setGoodsName(String goodsName) { this.goodsName = goodsName; } public String getMistakeType() { return mistakeType; } public void setMistakeType(String mistakeType) { this.mistakeType = mistakeType; } public int getPieceAmount() { return pieceAmount; } public void setPieceAmount(int pieceAmount) { this.pieceAmount = pieceAmount; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } public double getGoodsValue() { return goodsValue; } public void setGoodsValue(double goodsValue) { this.goodsValue = goodsValue; } @Override public String toString() { return "CargoError [id=" + id + ", goodsRevertBillCode=" + goodsRevertBillCode + ", goodsBillCode=" + goodsBillCode + ", customer=" + customer + ", goodsName=" + goodsName + ", mistakeType=" + mistakeType + ", pieceAmount=" + pieceAmount + ", size=" + size + ", goodsValue=" + goodsValue + "]"; } }
1,020
879
package org.zstack.header.storage.snapshot; import org.zstack.header.message.MessageReply; import java.util.ArrayList; import java.util.List; /** * Created by MaJin on 2019/8/8. */ public class GetVolumeSnapshotTreeRootNodeReply extends MessageReply { private String currentRootInstallPath; private List<String> previousRootInstallPaths = new ArrayList<>(); public String getCurrentRootInstallPath() { return currentRootInstallPath; } public void setCurrentRootInstallPath(String currentRootInstallPath) { this.currentRootInstallPath = currentRootInstallPath; } public List<String> getPreviousRootInstallPaths() { return previousRootInstallPaths; } public void setPreviousRootInstallPaths(List<String> previousRootInstallPaths) { this.previousRootInstallPaths = previousRootInstallPaths; } public void addPreviousRootInstallPath(String previousRootInstallPath) { this.previousRootInstallPaths.add(previousRootInstallPath); } }
329
412
<reponame>tobireinhard/cbmc /*******************************************************************\ Module: Alignment Checks Author: \*******************************************************************/ /// \file /// Alignment Checks #include "alignment_checks.h" #include <util/config.h> #include <util/namespace.h> #include <util/pointer_offset_size.h> #include <util/std_types.h> #include <util/symbol_table.h> #include <ostream> void print_struct_alignment_problems( const symbol_tablet &symbol_table, std::ostream &out) { for(const auto &symbol_pair : symbol_table.symbols) { if(symbol_pair.second.is_type && symbol_pair.second.type.id() == ID_struct) { const struct_typet &str = to_struct_type(symbol_pair.second.type); const struct_typet::componentst &components = str.components(); bool first_time_seen_in_struct = true; for(struct_typet::componentst::const_iterator it_mem = components.begin(); it_mem != components.end(); it_mem++) { mp_integer cumulated_length = 0; bool first_time_seen_from = true; // if the instruction cannot be aligned to the address, // try the next one if(it_mem->get_is_padding()) // || alignment(it_mem->type())%config.ansi_c.alignment!=0) continue; for(struct_typet::componentst::const_iterator it_next = it_mem; it_next != components.end(); it_next++) { const typet &it_type = it_next->type(); const namespacet ns(symbol_table); auto size = pointer_offset_size(it_type, ns); if(!size.has_value()) throw "type of unknown size:\n" + it_type.pretty(); cumulated_length += *size; // [it_mem;it_next] cannot be covered by an instruction if(cumulated_length > config.ansi_c.memory_operand_size) { // if interferences have been found, no need to check with // starting from an already covered member if(!first_time_seen_from) it_mem = it_next - 1; break; } if(it_mem != it_next && !it_next->get_is_padding()) { if(first_time_seen_in_struct) { first_time_seen_in_struct = false; first_time_seen_from = false; out << "\nWARNING: " << "declaration of structure " << str.find_type(ID_tag).pretty() << " at " << symbol_pair.second.location << '\n'; } out << "members " << it_mem->get_pretty_name() << " and " << it_next->get_pretty_name() << " might interfere\n"; } } } } else if(symbol_pair.second.type.id() == ID_array) { // is this structure likely to introduce data races? #if 0 const namespacet ns(symbol_table); const array_typet array=to_array_type(symbol_pair.second.type); const auto size= pointer_offset_size(array.subtype(), ns); if(!size.has_value()) throw "type of unknown size:\n"+it_type.pretty(); if(2*integer2long(*size)<=config.ansi_c.memory_operand_size) { out << "\nWARNING: " << "declaration of an array at " << symbol_pair.second.location << << "\nmight be concurrently accessed\n"; } #endif } } }
1,555
344
#ifndef GUARD_FAME_CHECKER_H #define GUARD_FAME_CHECKER_H #include "main.h" #define FAMECHECKER_OAK 0 #define FAMECHECKER_DAISY 1 #define FAMECHECKER_BROCK 2 #define FAMECHECKER_MISTY 3 #define FAMECHECKER_LTSURGE 4 #define FAMECHECKER_ERIKA 5 #define FAMECHECKER_KOGA 6 #define FAMECHECKER_SABRINA 7 #define FAMECHECKER_BLAINE 8 #define FAMECHECKER_LORELEI 9 #define FAMECHECKER_BRUNO 10 #define FAMECHECKER_AGATHA 11 #define FAMECHECKER_LANCE 12 #define FAMECHECKER_BILL 13 #define FAMECHECKER_MRFUJI 14 #define FAMECHECKER_GIOVANNI 15 #define NUM_FAMECHECKER_PERSONS 16 #define FCPICKSTATE_NO_DRAW 0 #define FCPICKSTATE_SILHOUETTE 1 #define FCPICKSTATE_COLORED 2 enum { FCWINDOWID_LIST, FCWINDOWID_UIHELP, FCWINDOWID_MSGBOX, FCWINDOWID_ICONDESC }; extern struct ListMenuTemplate gFameChecker_ListMenuTemplate; extern u8 gIconDescriptionBoxIsOpen; /* void ResetFameChecker(void); void FullyUnlockFameChecker(void); void UseFameChecker(MainCallback savedCallback); void SetFlavorTextFlagFromSpecialVars(void); void UpdatePickStateFromSpecialVar8005(void); */ #endif //GUARD_FAME_CHECKER_H
555
362
<filename>whois-api/src/main/java/net/ripe/db/whois/api/rdap/VCardBuilder.java package net.ripe.db.whois.api.rdap; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import net.ripe.db.whois.api.rdap.domain.vcard.VCard; import net.ripe.db.whois.api.rdap.domain.vcard.VCardKind; import static net.ripe.db.whois.api.rdap.domain.vcard.VCardName.EMAIL; import static net.ripe.db.whois.api.rdap.domain.vcard.VCardName.ADDRESS; import static net.ripe.db.whois.api.rdap.domain.vcard.VCardName.KIND; import static net.ripe.db.whois.api.rdap.domain.vcard.VCardName.FN; import static net.ripe.db.whois.api.rdap.domain.vcard.VCardName.GEO; import static net.ripe.db.whois.api.rdap.domain.vcard.VCardName.TELEPHONE; import static net.ripe.db.whois.api.rdap.domain.vcard.VCardName.VERSION; import static net.ripe.db.whois.api.rdap.domain.vcard.VCardName.ORG; import static net.ripe.db.whois.api.rdap.domain.vcard.VCardType.TEXT; import static net.ripe.db.whois.api.rdap.domain.vcard.VCardType.URI; import net.ripe.db.whois.api.rdap.domain.vcard.VCardName; import net.ripe.db.whois.api.rdap.domain.vcard.VCardType; import net.ripe.db.whois.api.rdap.domain.vcard.VCardProperty; import net.ripe.db.whois.common.domain.CIString; import static java.util.Collections.nCopies; import java.util.List; import java.util.Map; import java.util.Set; public class VCardBuilder { private static final Joiner NEWLINE_JOINER = Joiner.on("\n"); private final List<VCardProperty> properties = Lists.newArrayList(); private static final String PARAMETER_KEY = "type"; private static final Map ABUSE_MAP = ImmutableMap.of(PARAMETER_KEY,"abuse"); private static final Map EMAIL_MAP = ImmutableMap.of(PARAMETER_KEY,"email"); private static final Map PHONE_MAP = ImmutableMap.of(PARAMETER_KEY, "voice"); private static final Map FAX_MAP = ImmutableMap.of(PARAMETER_KEY, "fax"); private static final Map EMPTY_MAP = ImmutableMap.of(); public VCardBuilder addAdr(final Set<CIString> addresses) { final String label = "label"; if (!addresses.isEmpty()) { properties.add(new VCardProperty(ADDRESS, ImmutableMap.of(label,NEWLINE_JOINER.join(addresses)), TEXT, nCopies(7, ""))); //VCard format 7 empty elements for text } return this; } public VCardBuilder addEmail(final Set<CIString> emails) { emails.forEach( email -> addProperty(EMAIL, EMAIL_MAP, TEXT, email)); return this; } public VCardBuilder addAbuseMailBox(final CIString abuseMail) { if(abuseMail != null) { addProperty(EMAIL, ABUSE_MAP, TEXT, abuseMail); } return this; } public VCardBuilder addFn(final CIString value) { addProperty(FN, EMPTY_MAP, TEXT, value); return this; } public VCardBuilder addGeo(final Set<CIString> geolocs) { geolocs.forEach( geo -> addProperty(GEO, EMPTY_MAP, URI, geo)); return this; } public VCardBuilder addKind(final VCardKind kind) { addProperty(KIND, EMPTY_MAP, TEXT, kind.getValue()); return this; } public VCardBuilder addTel(final Set<CIString> phones) { phones.forEach( phone -> addProperty(TELEPHONE, PHONE_MAP, getTelType(phone), phone)); return this; } public VCardBuilder addFax(final Set<CIString> faxes) { faxes.forEach( fax -> addProperty(TELEPHONE, FAX_MAP, getTelType(fax), fax)); return this; } public VCardBuilder addVersion() { addProperty(VERSION, EMPTY_MAP, TEXT, "4.0"); return this; } public VCardBuilder addOrg(final Set<CIString> values) { values.forEach( org-> addProperty(ORG, EMPTY_MAP, TEXT, org)); return this; } private void addProperty(VCardName name, final Map parameters, final VCardType type, final String value) { properties.add(new VCardProperty(name, parameters, type, value)); } private void addProperty(VCardName name, final Map parameters, final VCardType type, final CIString value) { addProperty(name, parameters, type, value.toString()); } public VCard build() { return new VCard(properties); } private VCardType getTelType(CIString value) { return value.startsWith("tel:") ? URI : TEXT; } }
1,729
11,010
<filename>core/test/com/google/inject/internal/UniqueAnnotationsTest.java /* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.inject.internal; import java.lang.annotation.Annotation; import junit.framework.TestCase; /** @author <EMAIL> (<NAME>) */ public class UniqueAnnotationsTest extends TestCase { @UniqueAnnotations.Internal(31) public Void unused; public void testEqualsHashCodeToString() { Annotation actual = UniqueAnnotations.create(31); Annotation expected = getClass().getFields()[0].getAnnotations()[0]; assertEquals(expected.toString(), actual.toString()); assertEquals(expected.hashCode(), actual.hashCode()); assertEquals(expected, actual); } }
358
460
<reponame>dyzmapl/BumpTop /* * Copyright (C) 2003-2006 <NAME> and the CLucene Team * * Distributable under the terms of either the Apache License (Version 2.0) or * the GNU Lesser General Public License, as specified in the COPYING file. * * Changes are Copyright(C) 2007, 2008 by Nokia Corporation and/or its subsidiary(-ies), all rights reserved. */ #ifndef _lucene_index_termvector_h #define _lucene_index_termvector_h #if defined(_LUCENE_PRAGMA_ONCE) # pragma once #endif #include <QtCore/QString> #include "CLucene/store/Directory.h" #include "CLucene/store/IndexOutput.h" #include "FieldInfos.h" CL_NS_DEF(index) struct TermVectorOffsetInfo; class TermPositionVector; // Provides access to stored term vector of a document field. class TermFreqVector : LUCENE_BASE { public: virtual ~TermFreqVector() {} // @return The field this vector is associated with. virtual const TCHAR* getField() = 0; // @return The number of terms in the term vector. virtual int32_t size() = 0; // @return An Array of term texts in ascending order. virtual const TCHAR** getTerms() = 0; /* Array of term frequencies. Locations of the array correspond one to one * to the terms in the array obtained from <code>getTerms</code> * method. Each location in the array contains the number of times this * term occurs in the document or the document field. * * The size of the returned array is size() * @memory Returning a pointer to internal data. Do not delete. */ virtual const Array<int32_t>* getTermFrequencies() = 0; /* Return an index in the term numbers array returned from * <code>getTerms</code> at which the term with the specified * <code>term</code> appears. If this term does not appear in the array, * return -1. */ virtual int32_t indexOf(const TCHAR* term) = 0; /* Just like <code>indexOf(int32_t)</code> but searches for a number of terms * at the same time. Returns an array that has the same size as the number * of terms searched for, each slot containing the result of searching for * that term number. * * @param terms array containing terms to look for * @param start index in the array where the list of terms starts * @param len the number of terms in the list */ virtual void indexesOf(const TCHAR** terms, const int32_t start, const int32_t len, Array<int32_t>& ret) = 0; // Solve the diamond inheritence problem by providing a reinterpret function. // No dynamic casting is required and no RTTI data is needed to do this virtual TermPositionVector* __asTermPositionVector() = 0; }; /** * Writer works by opening a document and then opening the fields within the document and then * writing out the vectors for each field. * * Rough usage: * <CODE> for each document { writer.openDocument(); for each field on the document { writer.openField(field); for all of the terms { writer.addTerm(...) } writer.closeField } writer.closeDocument() } </CODE> */ class TermVectorsWriter : LUCENE_BASE { private: class TVField : LUCENE_BASE { public: int32_t number; int64_t tvfPointer; int32_t length; // number of distinct term positions bool storePositions; bool storeOffsets; TVField(int32_t number, bool storePos, bool storeOff) : tvfPointer(0) , length(0) { this->number = number; this->storePositions = storePos; this->storeOffsets = storeOff; } ~TVField() {} }; class TVTerm : LUCENE_BASE { const TCHAR* termText; int32_t termTextLen; //textlen cache public: TVTerm(); ~TVTerm(); int32_t freq; Array<int32_t>* positions; Array<TermVectorOffsetInfo>* offsets; const TCHAR* getTermText() const; size_t getTermTextLen(); void setTermText(const TCHAR* val); }; CL_NS(store)::IndexOutput* tvx, *tvd, *tvf; CL_NS(util)::CLVector<TVField*,CL_NS(util)::Deletor::Object<TVField> > fields; CL_NS(util)::CLVector<TVTerm*,CL_NS(util)::Deletor::Object<TVTerm> > terms; FieldInfos* fieldInfos; TVField* currentField; int64_t currentDocPointer; void addTermInternal(const TCHAR* termText, const int32_t freq, Array<int32_t>* positions, Array<TermVectorOffsetInfo>* offsets); void writeField(); void writeDoc(); void openField(int32_t fieldNumber, bool storePositionWithTermVector, bool storeOffsetWithTermVector); public: LUCENE_STATIC_CONSTANT(int32_t, FORMAT_VERSION = 2); // The size in bytes that the FORMAT_VERSION will take up at the beginning // of each file LUCENE_STATIC_CONSTANT(int32_t, FORMAT_SIZE = 4); LUCENE_STATIC_CONSTANT(uint8_t, STORE_POSITIONS_WITH_TERMVECTOR = 0x1); LUCENE_STATIC_CONSTANT(uint8_t, STORE_OFFSET_WITH_TERMVECTOR = 0x2); static const QLatin1String LUCENE_TVX_EXTENSION; static const QLatin1String LUCENE_TVD_EXTENSION; static const QLatin1String LUCENE_TVF_EXTENSION; TermVectorsWriter(CL_NS(store)::Directory* directory, const QString& segment, FieldInfos* fieldInfos); ~TermVectorsWriter(); void openDocument(); void closeDocument(); /** Close all streams. */ void close(); bool isDocumentOpen() const; /** Start processing a field. This can be followed by a number of calls to * addTerm, and a final call to closeField to indicate the end of * processing of this field. If a field was previously open, it is * closed automatically. */ void openField(const TCHAR* field); /** Finished processing current field. This should be followed by a call to * openField before future calls to addTerm. */ void closeField(); /** Return true if a field is currently open. */ bool isFieldOpen() const; /** * Add a complete document specified by all its term vectors. If document has no * term vectors, add value for tvx. * * @param vectors * @throws IOException */ void addAllDocVectors(Array<TermFreqVector*>& vectors); /** Add term to the field's term vector. Field must already be open. * Terms should be added in * increasing order of terms, one call per unique termNum. ProxPointer * is a pointer into the TermPosition file (prx). Freq is the number of * times this term appears in this field, in this document. * @throws IllegalStateException if document or field is not open */ void addTerm(const TCHAR* termText, int32_t freq, Array<int32_t>* positions = NULL, Array<TermVectorOffsetInfo>* offsets = NULL); }; class SegmentTermVector : public virtual TermFreqVector { private: const TCHAR* field; TCHAR** terms; int32_t termsLen; //cache Array<int32_t>* termFreqs; int32_t binarySearch(TCHAR** a, const int32_t arraylen, const TCHAR* key) const; public: //note: termFreqs must be the same length as terms SegmentTermVector(const TCHAR* field, TCHAR** terms, Array<int32_t>* termFreqs); virtual ~SegmentTermVector(); /** * * @return The number of the field this vector is associated with */ const TCHAR* getField(); TCHAR* toString() const; int32_t size(); const TCHAR** getTerms(); const Array<int32_t>* getTermFrequencies(); int32_t indexOf(const TCHAR* termText); void indexesOf(const TCHAR** termNumbers, const int32_t start, const int32_t len, Array<int32_t>& ret); virtual TermPositionVector* __asTermPositionVector(); }; class TermVectorsReader : LUCENE_BASE { private: FieldInfos* fieldInfos; CL_NS(store)::IndexInput* tvx; CL_NS(store)::IndexInput* tvd; CL_NS(store)::IndexInput* tvf; int64_t _size; int32_t tvdFormat; int32_t tvfFormat; int32_t checkValidFormat(CL_NS(store)::IndexInput* in); void readTermVectors(const TCHAR** fields, const int64_t* tvfPointers, const int32_t len, Array<TermFreqVector*>& _return); /** * * @param field The field to read in * @param tvfPointer The pointer within the tvf file where we should start reading * @return The TermVector located at that position * @throws IOException */ SegmentTermVector* readTermVector(const TCHAR* field, const int64_t tvfPointer); int64_t size(); DEFINE_MUTEX(THIS_LOCK) TermVectorsReader(const TermVectorsReader& copy); public: TermVectorsReader(CL_NS(store)::Directory* d, const QString& segment, FieldInfos* fieldInfos); ~TermVectorsReader(); void close(); TermVectorsReader* clone() const; /** * Retrieve the term vector for the given document and field * @param docNum The document number to retrieve the vector for * @param field The field within the document to retrieve * @return The TermFreqVector for the document and field or null if there is no termVector for this field. * @throws IOException if there is an error reading the term vector files */ TermFreqVector* get(const int32_t docNum, const TCHAR* field); /** * Return all term vectors stored for this document or null if the could not be read in. * * @param docNum The document number to retrieve the vector for * @return All term frequency vectors * @throws IOException if there is an error reading the term vector files */ bool get(int32_t docNum, Array<TermFreqVector*>& result); }; struct TermVectorOffsetInfo { int startOffset; int endOffset; public: static Array<TermVectorOffsetInfo> EMPTY_OFFSET_INFO; TermVectorOffsetInfo(); ~TermVectorOffsetInfo(); TermVectorOffsetInfo(int32_t startOffset, int32_t endOffset); int32_t getEndOffset() const; void setEndOffset(int32_t endOffset); int32_t getStartOffset() const; void setStartOffset(int32_t startOffset); bool equals(TermVectorOffsetInfo* o); size_t hashCode() const; }; /* Extends <code>TermFreqVector</code> to provide additional information about * positions in which each of the terms is found. A TermPositionVector not * necessarily contains both positions and offsets, but at least one of these * arrays exists. */ class TermPositionVector : public virtual TermFreqVector { public: /** Returns an array of positions in which the term is found. * Terms are identified by the index at which its number appears in the * term String array obtained from the <code>indexOf</code> method. * May return null if positions have not been stored. */ virtual Array<int32_t>* getTermPositions(int32_t index) = 0; /** * Returns an array of TermVectorOffsetInfo in which the term is found. * May return null if offsets have not been stored. * * @see org.apache.lucene.analysis.Token * * @param index The position in the array to get the offsets from * @return An array of TermVectorOffsetInfo objects or the empty list */ virtual Array<TermVectorOffsetInfo>* getOffsets(int32_t index) = 0; virtual ~TermPositionVector(){ } }; class SegmentTermPositionVector: public SegmentTermVector, public TermPositionVector { protected: Array< Array<int32_t> >* positions; Array< Array<TermVectorOffsetInfo> >* offsets; static Array<int32_t> EMPTY_TERM_POS; public: SegmentTermPositionVector(const TCHAR* field, TCHAR** terms, Array<int32_t>* termFreqs, Array< Array<int32_t> >* positions, Array< Array<TermVectorOffsetInfo> >* offsets); ~SegmentTermPositionVector(); /** * Returns an array of TermVectorOffsetInfo in which the term is found. * * @param index The position in the array to get the offsets from * @return An array of TermVectorOffsetInfo objects or the empty list * @see org.apache.lucene.analysis.Token */ Array<TermVectorOffsetInfo>* getOffsets(int32_t index); /** * Returns an array of positions in which the term is found. * Terms are identified by the index at which its number appears in the * term String array obtained from the <code>indexOf</code> method. */ Array<int32_t>* getTermPositions(int32_t index); const TCHAR* getField() { return SegmentTermVector::getField(); } TCHAR* toString() const { return SegmentTermVector::toString(); } int32_t size() { return SegmentTermVector::size(); } const TCHAR** getTerms() { return SegmentTermVector::getTerms(); } const Array<int32_t>* getTermFrequencies() { return SegmentTermVector::getTermFrequencies(); } int32_t indexOf(const TCHAR* termText) { return SegmentTermVector::indexOf(termText); } void indexesOf(const TCHAR** termNumbers, const int32_t start, const int32_t len, Array<int32_t>& ret) { SegmentTermVector::indexesOf(termNumbers, start, len, ret); } virtual TermPositionVector* __asTermPositionVector(); }; CL_NS_END #endif
4,737
12,252
<gh_stars>1000+ /* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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. */ package org.keycloak.representations.idm; import org.keycloak.common.util.MultivaluedHashMap; /** * @author <a href="mailto:<EMAIL>"><NAME></a> * @version $Revision: 1 $ */ public class CredentialRepresentation { public static final String SECRET = "secret"; public static final String PASSWORD = "password"; public static final String TOTP = "totp"; public static final String HOTP = "hotp"; public static final String KERBEROS = "kerberos"; private String id; private String type; private String userLabel; private Long createdDate; private String secretData; private String credentialData; private Integer priority; private String value; // only used when updating a credential. Might set required action protected Boolean temporary; // All those fields are just for backwards compatibility @Deprecated protected String device; @Deprecated protected String hashedSaltedValue; @Deprecated protected String salt; @Deprecated protected Integer hashIterations; @Deprecated protected Integer counter; @Deprecated private String algorithm; @Deprecated private Integer digits; @Deprecated private Integer period; @Deprecated private MultivaluedHashMap<String, String> config; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getUserLabel() { return userLabel; } public void setUserLabel(String userLabel) { this.userLabel = userLabel; } public String getSecretData() { return secretData; } public void setSecretData(String secretData) { this.secretData = secretData; } public String getCredentialData() { return credentialData; } public void setCredentialData(String credentialData) { this.credentialData = credentialData; } public Integer getPriority() { return priority; } public void setPriority(Integer priority) { this.priority = priority; } public Long getCreatedDate() { return createdDate; } public void setCreatedDate(Long createdDate) { this.createdDate = createdDate; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Boolean isTemporary() { return temporary; } public void setTemporary(Boolean temporary) { this.temporary = temporary; } @Deprecated public String getDevice() { return device; } @Deprecated public String getHashedSaltedValue() { return hashedSaltedValue; } @Deprecated public String getSalt() { return salt; } @Deprecated public Integer getHashIterations() { return hashIterations; } @Deprecated public Integer getCounter() { return counter; } @Deprecated public String getAlgorithm() { return algorithm; } @Deprecated public Integer getDigits() { return digits; } @Deprecated public Integer getPeriod() { return period; } @Deprecated public MultivaluedHashMap<String, String> getConfig() { return config; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((createdDate == null) ? 0 : createdDate.hashCode()); result = prime * result + ((userLabel == null) ? 0 : userLabel.hashCode()); result = prime * result + ((secretData == null) ? 0 : secretData.hashCode()); result = prime * result + ((credentialData == null) ? 0 : credentialData.hashCode()); result = prime * result + ((temporary == null) ? 0 : temporary.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); result = prime * result + ((priority == null) ? 0 : priority); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CredentialRepresentation other = (CredentialRepresentation) obj; if (secretData == null) { if (other.secretData != null) return false; } else if (!secretData.equals(other.secretData)) return false; if (credentialData == null) { if (other.credentialData != null) return false; } else if (!credentialData.equals(other.credentialData)) return false; if (createdDate == null) { if (other.createdDate != null) return false; } else if (!createdDate.equals(other.createdDate)) return false; if (userLabel == null) { if (other.userLabel != null) return false; } else if (!userLabel.equals(other.userLabel)) return false; if (temporary == null) { if (other.temporary != null) return false; } else if (!temporary.equals(other.temporary)) return false; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; if (priority == null) { if (other.priority != null) return false; } else if (!priority.equals(other.priority)) return false; return true; } }
2,771
1,845
<reponame>zhaofeng-shu33/plato /* Tencent is pleased to support the open source community by making Plato available. Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://opensource.org/licenses/BSD-3-Clause 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. See the AUTHORS file for names of contributors. */ #ifndef __PLATO_GRAPH_STATE_VIEW_HPP__ #define __PLATO_GRAPH_STATE_VIEW_HPP__ #include <cstdint> #include <cstdlib> #include <memory> #include <utility> #include <functional> #include <type_traits> #include "glog/logging.h" #include "plato/graph/base.hpp" #include "plato/util/bitmap.hpp" namespace plato { template <typename VIEW, typename BITMAP> struct active_v_view { VIEW view_; BITMAP bitmap_; // ******************************************************************************* // // required types & methods // traverse related inline void reset_traversal(const traverse_opts_t& opts = traverse_opts_t()); // Func looks like void(vid_t v_i, args...) template <typename Func> inline bool next_chunk(Func&& traversal, size_t* chunk_size); /* * foreach elements in this view, run in parallel * * \tparam PROCESS R(vid_t v_i, args...) * * \param traversal process callback * * \return * sum of process return **/ template <typename R, typename PROCESS> R foreach(PROCESS&& traversal); // ******************************************************************************* // }; template <typename VIEW, typename BITMAP> inline active_v_view<VIEW, BITMAP> create_active_v_view(VIEW&& view, BITMAP&& bitmap) { return { std::forward<VIEW>(view), std::forward<BITMAP>(bitmap) }; } // ************************************************************************************ // // implementations template <typename VIEW, typename BITMAP> void active_v_view<VIEW, BITMAP>::reset_traversal(const traverse_opts_t& opts) { view_.reset_traversal(opts); } namespace view_detail { template <typename F, typename BITMAP> struct traversal_rebind_t { F func_; BITMAP bitmap_; template <typename... Args> inline void operator()(vid_t v_i, Args... args) const { if (bitmap_.get_bit(v_i)) { func_(v_i, std::forward<Args>(args)...); } } }; template <typename F, typename BITMAP> traversal_rebind_t<F, BITMAP> bind_traversal(F&& func, BITMAP&& bitmap) { return { std::forward<F>(func), std::forward<BITMAP>(bitmap) }; } template <typename R, typename F, typename BITMAP> struct reduction_rebind_t { R&& rdu_; F func_; BITMAP bitmap_; template <typename... Args> inline void operator()(vid_t v_i, Args... args) { if (bitmap_.get_bit(v_i)) { rdu_ += func_(v_i, std::forward<Args>(args)...); } } }; template <typename R, typename F, typename BITMAP> reduction_rebind_t<R, F, BITMAP> bind_reduction(R&& rdu, F&& func, BITMAP&& bitmap) { return { std::forward<R>(rdu), std::forward<F>(func), std::forward<BITMAP>(bitmap) }; } } template <typename VIEW, typename BITMAP> template <typename Func> bool active_v_view<VIEW, BITMAP>::next_chunk(Func&& traversal, size_t* chunk_size) { return view_.next_chunk(view_detail::bind_traversal(std::forward<Func>(traversal), std::forward<BITMAP>(bitmap_)), chunk_size); } template <typename VIEW, typename BITMAP> template <typename R, typename PROCESS> R active_v_view<VIEW, BITMAP>::foreach(PROCESS&& traversal) { R rdu = R(); reset_traversal(); #pragma omp parallel reduction(+:rdu) { R __rdu = R(); size_t chunk_size = 4 * PAGESIZE; auto __traversal = view_detail::bind_reduction(std::forward<R>(__rdu), std::forward<PROCESS>(traversal), std::forward<BITMAP>(bitmap_)); while (view_.next_chunk(__traversal, &chunk_size)) { } rdu += __traversal.rdu_; } R grdu = R(); MPI_Allreduce(&rdu, &grdu, 1, get_mpi_data_type<R>(), MPI_SUM, MPI_COMM_WORLD); return grdu; } // ************************************************************************************ // } #endif
1,566
335
<reponame>Safal08/Hacktoberfest-1 { "word": "Frivolity", "definitions": [ "Lack of seriousness; light-heartedness." ], "parts-of-speech": "Noun" }
80
1,056
/* * 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. */ package org.netbeans.modules.project.ui.groups; import java.io.File; import java.io.IOException; import java.util.prefs.Preferences; import javax.swing.JFileChooser; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import org.netbeans.api.project.Project; import org.netbeans.api.project.ProjectManager; import static org.netbeans.modules.project.ui.groups.Group.KEY_PATH; import static org.netbeans.modules.project.ui.groups.Group.NODE; import static org.netbeans.modules.project.ui.groups.GroupEditPanel.PROP_READY; import org.netbeans.spi.project.ui.support.ProjectChooser; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.util.Exceptions; import org.openide.util.RequestProcessor; /** * Panel to configure state of an existing subproject-based group. * @author <NAME> */ public class SubprojectsGroupEditPanel extends GroupEditPanel { private final SubprojectsGroup g; public SubprojectsGroupEditPanel(SubprojectsGroup g) { this.g = g; initComponents(); DocumentListener l = new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { firePropertyChange(PROP_READY, null, null); } @Override public void removeUpdate(DocumentEvent e) { firePropertyChange(PROP_READY, null, null); } @Override public void changedUpdate(DocumentEvent e) {} }; nameField.setText(g.getName()); nameField.getDocument().addDocumentListener(l); FileObject dir = g.getMasterProjectDirectory(); if (dir != null) { File d = FileUtil.toFile(dir); if (d != null) { masterProjectField.setText(d.getAbsolutePath()); } } masterProjectField.getDocument().addDocumentListener(l); } @Override public void applyChanges() { g.setName(nameField.getText().trim()); updateMasterProject(); } private void updateMasterProject() { String s = masterProjectField.getText(); if (s != null && s.length() > 0) { File f = new File(s); FileObject fo = FileUtil.toFileObject(f); if (fo != null && fo.isFolder()) { try { Project p = ProjectManager.getDefault().findProject(fo); if (p != null){ String path = p.getProjectDirectory().toURL().toExternalForm(); Preferences pref = NODE.node(g.id); pref.put(KEY_PATH, path); if(g.equals(Group.getActiveGroup())) { RequestProcessor.getDefault().post(new Runnable() { @Override public void run() { Group.open(g, null, false, null); } }); } } } catch (IOException x) { Exceptions.printStackTrace(x); } } } } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { nameLabel = new javax.swing.JLabel(); nameField = new javax.swing.JTextField(); masterProjectLabel = new javax.swing.JLabel(); masterProjectField = new javax.swing.JTextField(); masterProjectButton = new javax.swing.JButton(); nameLabel.setLabelFor(nameField); org.openide.awt.Mnemonics.setLocalizedText(nameLabel, org.openide.util.NbBundle.getMessage(SubprojectsGroupEditPanel.class, "SubprojectsGroupEditPanel.nameLabel.text")); // NOI18N masterProjectLabel.setLabelFor(masterProjectField); org.openide.awt.Mnemonics.setLocalizedText(masterProjectLabel, org.openide.util.NbBundle.getMessage(SubprojectsGroupEditPanel.class, "SubprojectsGroupEditPanel.masterProjectLabel.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(masterProjectButton, org.openide.util.NbBundle.getMessage(SubprojectsGroupEditPanel.class, "SubprojectsGroupEditPanel.masterProjectButton.text")); // NOI18N masterProjectButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { masterProjectButtonActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(0, 0, 0) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(nameLabel) .addComponent(masterProjectLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(nameField, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(masterProjectField) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(masterProjectButton))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(0, 0, 0) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(nameLabel) .addComponent(nameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(masterProjectLabel) .addComponent(masterProjectField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(masterProjectButton)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); nameLabel.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(SubprojectsGroupEditPanel.class, "SubprojectsGroupEditPanel.nameLabel.AccessibleContext.accessibleDescription")); // NOI18N nameField.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(SubprojectsGroupEditPanel.class, "SubprojectsGroupEditPanel.nameField.AccessibleContext.accessibleName")); // NOI18N nameField.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(SubprojectsGroupEditPanel.class, "SubprojectsGroupEditPanel.nameField.AccessibleContext.accessibleDescription")); // NOI18N masterProjectLabel.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(SubprojectsGroupEditPanel.class, "SubprojectsGroupEditPanel.masterProjectLabel.AccessibleContext.accessibleDescription")); // NOI18N masterProjectField.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(SubprojectsGroupEditPanel.class, "SubprojectsGroupEditPanel.masterProjectField.AccessibleContext.accessibleName")); // NOI18N masterProjectField.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(SubprojectsGroupEditPanel.class, "SubprojectsGroupEditPanel.masterProjectField.AccessibleContext.accessibleDescription")); // NOI18N getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(SubprojectsGroupEditPanel.class, "SubprojectsGroupEditPanel.AccessibleContext.accessibleName")); // NOI18N getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(SubprojectsGroupEditPanel.class, "SubprojectsGroupEditPanel.AccessibleContext.accessibleDescription")); // NOI18N }// </editor-fold>//GEN-END:initComponents private void masterProjectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_masterProjectButtonActionPerformed JFileChooser chooser = ProjectChooser.projectChooser(); if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { File f = chooser.getSelectedFile(); if (f != null) { masterProjectField.setText(f.getAbsolutePath()); //firePropertyChange(PROP_READY, null, null); } } }//GEN-LAST:event_masterProjectButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton masterProjectButton; private javax.swing.JTextField masterProjectField; private javax.swing.JLabel masterProjectLabel; private javax.swing.JTextField nameField; private javax.swing.JLabel nameLabel; // End of variables declaration//GEN-END:variables @Override public boolean isReady() { if(!doCheckExistingGroups(nameField, g)) { return false; } String s = masterProjectField.getText(); if (s == null || s.length() == 0) { return false; } else { File f = FileUtil.normalizeFile(new File(s)); FileObject fo = FileUtil.toFileObject(f); if (fo != null && fo.isFolder()) { try { return ProjectManager.getDefault().findProject(fo) != null; } catch (IOException x) { Exceptions.printStackTrace(x); } } else { return false; } } return true; } }
4,649
611
package fr.adrienbrault.idea.symfony2plugin.routing.webDeployment; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.io.StreamUtil; import com.intellij.util.containers.HashMap; import com.jetbrains.php.lang.psi.PhpPsiElementFactory; import fr.adrienbrault.idea.symfony2plugin.Settings; import fr.adrienbrault.idea.symfony2plugin.routing.Route; import fr.adrienbrault.idea.symfony2plugin.routing.RouteHelper; import fr.adrienbrault.idea.symfony2plugin.webDeployment.storage.RemoteFileStorageInterface; import fr.adrienbrault.idea.symfony2plugin.webDeployment.utils.RemoteWebServerUtil; import org.apache.commons.lang.StringUtils; import org.apache.commons.vfs2.FileObject; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.util.Collection; import java.util.Map; /** * @author <NAME> <<EMAIL>> */ public class RoutingRemoteFileStorage implements RemoteFileStorageInterface<Map<String, Route>> { private Map<String, Route> routeMap = new HashMap<>(); @NotNull @Override public Collection<String> files(@NotNull Project project) { return RemoteWebServerUtil.getRemoteAbleFiles(Settings.getInstance(project).routingFiles); } @Override public void build(@NotNull Project project, @NotNull Collection<FileObject> fileObjects) { Map<String, Route> routeMap = new HashMap<>(); for (FileObject file : fileObjects) { String content; try { content = StreamUtil.readText(file.getContent().getInputStream(), "UTF-8"); } catch (IOException e) { continue; } if(StringUtils.isBlank(content)) { continue; } routeMap.putAll(RouteHelper.getRoutesInsideUrlGeneratorFile( PhpPsiElementFactory.createPsiFileFromText(project, content) )); } this.routeMap = routeMap; } @NotNull public Map<String, Route> getState() { return this.routeMap; } @Override public void clear() { this.routeMap = new HashMap<>(); } }
860
765
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera 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. *****************************************************************************/ /***************************************************************************** global.h -- Original Author: <NAME>, Synopsys, Inc., 2002-02-15 *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #ifndef GLOBALH #define GLOBALH // #include <iostream.h> #include <stdio.h> #define MAXBUFLEN 64 // cos constants, factor 512 #define c1d4 362L #define c1d8 473L #define c3d8 196L #define c1d16 502L #define c3d16 426L #define c5d16 284L #define c7d16 100L // correct digits #define MSCALE(expr) (COEFF)((expr)>>9) typedef unsigned char BYTE; typedef unsigned short WORD; typedef unsigned long DWORD; typedef BYTE BLOCK[8][8]; typedef BYTE COMPRESSED[MAXBUFLEN]; typedef WORD MATRIX64x12[64]; // type of the coefficient arrays typedef short COEFF; // typedefs for huffman tables typedef struct { BYTE size; WORD code; } HUFFMTBL_ENTRY; struct Block { BYTE b[8][8]; Block(); Block(BLOCK *); Block(const Block&); void operator=(const Block&); int operator==(const Block&) const; BYTE get(int x, int y) const; void put(int x, int y, BYTE val); BLOCK* get_ptr() const; }; struct Compressed { BYTE c[MAXBUFLEN]; Compressed(); Compressed(const Compressed&); void operator=(const Compressed&); int operator==(const Compressed&) const; void clear(); BYTE get(int x) const; void put(int x, BYTE val); }; struct Matrix64x12 { WORD m[64]; Matrix64x12(); Matrix64x12(const Matrix64x12&); void operator=(const Matrix64x12&); int operator==(const Matrix64x12&) const; WORD get(int x) const; void put(int x, WORD val); }; struct Coeff8 { COEFF c[8]; Coeff8(); Coeff8(const Coeff8&); void operator=(const Coeff8&); int operator==(const Coeff8&) const; COEFF get(int x) const; void put(int x, COEFF val); }; struct Coeff8x8 { COEFF c[8][8]; Coeff8x8(); Coeff8x8(const Coeff8x8&); void operator=(const Coeff8x8&); int operator==(const Coeff8x8&) const; COEFF get(int x, int y) const; void put(int x, int y, COEFF val); }; inline void sc_trace( sc_trace_file*, const Coeff8x8&, const std::string& ) { // NOT IMPLEMENTED } // quantization table 8-bit unsigned integer static const unsigned char coeff_quant[8][8] = { // v is row { 16, 11, 10, 16, 24, 40, 51, 61}, { 12, 12, 14, 19, 26, 58, 60, 55}, { 14, 13, 16, 24, 40, 57, 69, 56}, { 14, 17, 22, 29, 51, 87, 80, 82}, { 18, 22, 37, 56, 68, 109, 103, 77}, { 24, 35, 55, 64, 81, 104, 113, 92}, { 99, 64, 78, 87, 103, 121, 120, 101}, { 72, 92, 95, 98, 112, 100, 103, 99} }; // table of Huffman DC coefficients static const HUFFMTBL_ENTRY huffm_dc[12] = { { 2, 0X0000 }, { 3, 0X0002 }, { 3, 0X0003 }, { 3, 0X0004 }, { 3, 0X0005 }, { 3, 0X0006 }, { 4, 0X000E }, { 5, 0X001E }, { 6, 0X003E }, { 7, 0X007E }, { 8, 0X00FE }, { 9, 0X01FE } }; // table of Huffman AC coefficients static const HUFFMTBL_ENTRY huffm_ac[256] = { { 4, 0x000a }, { 2, 0x0000 }, { 2, 0x0001 }, { 3, 0x0004 }, { 4, 0x000b }, { 5, 0x001a }, { 7, 0x0078 }, { 8, 0x00f8 }, { 10, 0x03f6 }, { 16, 0xff82 }, { 16, 0xff83 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 4, 0x000c }, { 5, 0x001b }, { 7, 0x0079 }, { 9, 0x01f6 }, { 11, 0x07f6 }, { 16, 0xff84 }, { 16, 0xff85 }, { 16, 0xff86 }, { 16, 0xff87 }, { 16, 0xff88 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 5, 0x001c }, { 8, 0x00f9 }, { 10, 0x03f7 }, { 12, 0x0ff4 }, { 16, 0xff89 }, { 16, 0xff8a }, { 16, 0xff8b }, { 16, 0xff8c }, { 16, 0xff8d }, { 16, 0xff8e }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 6, 0x003a }, { 9, 0x01f7 }, { 12, 0x0ff5 }, { 16, 0xff8f }, { 16, 0xff90 }, { 16, 0xff91 }, { 16, 0xff92 }, { 16, 0xff93 }, { 16, 0xff94 }, { 16, 0xff95 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 6, 0x003b }, { 10, 0x03f8 }, { 16, 0xff96 }, { 16, 0xff97 }, { 16, 0xff98 }, { 16, 0xff99 }, { 16, 0xff9a }, { 16, 0xff9b }, { 16, 0xff9c }, { 16, 0xff9d }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 7, 0x007a }, { 11, 0x07f7 }, { 16, 0xff9e }, { 16, 0xff9f }, { 16, 0xffa0 }, { 16, 0xffa1 }, { 16, 0xffa2 }, { 16, 0xffa3 }, { 16, 0xffa4 }, { 16, 0xffa5 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 7, 0x007b }, { 12, 0x0ff6 }, { 16, 0xffa6 }, { 16, 0xffa7 }, { 16, 0xffa8 }, { 16, 0xffa9 }, { 16, 0xffaa }, { 16, 0xffab }, { 16, 0xffac }, { 16, 0xffad }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 8, 0x00fa }, { 12, 0x0ff7 }, { 16, 0xffae }, { 16, 0xffaf }, { 16, 0xffb0 }, { 16, 0xffb1 }, { 16, 0xffb2 }, { 16, 0xffb3 }, { 16, 0xffb4 }, { 16, 0xffb5 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 9, 0x01f8 }, { 15, 0x7fc0 }, { 16, 0xffb6 }, { 16, 0xffb7 }, { 16, 0xffb8 }, { 16, 0xffb9 }, { 16, 0xffba }, { 16, 0xffbb }, { 16, 0xffbc }, { 16, 0xffbd }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 9, 0x01f9 }, { 16, 0xffbe }, { 16, 0xffbf }, { 16, 0xffc0 }, { 16, 0xffc1 }, { 16, 0xffc2 }, { 16, 0xffc3 }, { 16, 0xffc4 }, { 16, 0xffc5 }, { 16, 0xffc6 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 9, 0x01fa }, { 16, 0xffc7 }, { 16, 0xffc8 }, { 16, 0xffc9 }, { 16, 0xffca }, { 16, 0xffcb }, { 16, 0xffcc }, { 16, 0xffcd }, { 16, 0xffce }, { 16, 0xffcf }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 10, 0x03f9 }, { 16, 0xffd0 }, { 16, 0xffd1 }, { 16, 0xffd2 }, { 16, 0xffd3 }, { 16, 0xffd4 }, { 16, 0xffd5 }, { 16, 0xffd6 }, { 16, 0xffd7 }, { 16, 0xffd8 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 10, 0x03fa }, { 16, 0xffd9 }, { 16, 0xffda }, { 16, 0xffdb }, { 16, 0xffdc }, { 16, 0xffdd }, { 16, 0xffde }, { 16, 0xffdf }, { 16, 0xffe0 }, { 16, 0xffe1 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 11, 0x07f8 }, { 16, 0xffe2 }, { 16, 0xffe3 }, { 16, 0xffe4 }, { 16, 0xffe5 }, { 16, 0xffe6 }, { 16, 0xffe7 }, { 16, 0xffe8 }, { 16, 0xffe9 }, { 16, 0xffea }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 16, 0xffeb }, { 16, 0xffec }, { 16, 0xffed }, { 16, 0xffee }, { 16, 0xffef }, { 16, 0xfff0 }, { 16, 0xfff1 }, { 16, 0xfff2 }, { 16, 0xfff3 }, { 16, 0xfff4 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 11, 0x07f9 }, { 16, 0xfff5 }, { 16, 0xfff6 }, { 16, 0xfff7 }, { 16, 0xfff8 }, { 16, 0xfff9 }, { 16, 0xfffa }, { 16, 0xfffb }, { 16, 0xfffc }, { 16, 0xfffd }, { 16, 0xfffe }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 }, { 0, 0x0000 } }; #endif
3,963
318
// __BEGIN_LICENSE__ // Copyright (c) 2006-2013, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NASA Vision Workbench is licensed under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // __END_LICENSE__ #include <cmath> #include <cstdlib> #include <iostream> #include <cmath> #include <cfloat> #include <cstring> #include <cassert> #include <vw/Geometry/baseUtils.h> #include <vw/Geometry/geomUtils.h> #include <vw/Geometry/edgeUtils.h> namespace vw { namespace geometry { using namespace std; std::ostream& operator<<(std::ostream& os, const anno& A){ os << A.x << ' ' << A.y << ' ' << A.label << std::endl; return os; } void snapPolyLineTo45DegAngles(bool isClosedPolyLine, int numVerts, double * xv, double * yv){ // Given a polygonal line, transform it such that all vertices are // integers and all edges make an angle multiple of 45 degrees // with the x axis. if (numVerts <= 0) return; // The vectors corresponding to angles multiple of 45 degree int numAngles = 8; double xs[numAngles], ys[numAngles]; for (int a = 0; a < numAngles; a++){ double theta = a*45*M_PI/180; xs[a] = cos(theta); ys[a] = sin(theta); } // Snap first vertex to int grid xv[0] = round(xv[0]); yv[0] = round(yv[0]); for (int v = 0; v < numVerts - 1; v++){ bool snap2ndClosest = false; // snap to closest, not second closest snapOneEdgeTo45(numAngles, xs, ys, snap2ndClosest, // inputs xv[v], yv[v], xv[v + 1], yv[v + 1] // in-out ); } if (!isClosedPolyLine || numVerts < 3) return; // The poly line is closed. After vertex n - 1 we have vertex 0. // Form a closed polygon satisfying the requirements. To do that, // walk backwards from vertex 0 and adjust edges until all edges // intersect on the integer grid and make 45 degree angles. for (int v = numVerts; v >= 0; v--){ int vp = (v + 1) % numVerts; int vc = v % numVerts; int vn = (v + numVerts - 1) % numVerts; double xp = xv[vp], xc = xv[vc], xc2 = xv[vc], xn = xv[vn]; double yp = yv[vp], yc = yv[vc], yc2 = yv[vc], yn = yv[vn]; bool snap2ndClosest = false; snapOneEdgeTo45(numAngles, xs, ys, snap2ndClosest, // inputs xn, yn, xc2, yc2 // in-out ); // Find the intersection of the edges // (xp, yp) --> (xc, yc) and (xc2, yc2) --> (xn, yn). double det = ( (xc-xp)*(yn-yc2) - (yc-yp)*(xn-xc2) ); double top = ( (xc2-xp)*(yn-yc2) - (yc2-yp)*(xn-xc2) ); double t = top/det; double xi = round( 2*( t*(xc-xp) + xp ) )/2.0; double yi = round( 2*( t*(yc-yp) + yp ) )/2.0; if (det != 0 && xi == round(xi) && yi == round(yi) ){ // Finally arrived at a point at which all vertices // are on grid xv[vc] = xi; yv[vc] = yi; break; } // Adjust the edge going from vc to vn, and hope that at the next iteration // that edge intersects properly with the edge after it. xv[vn] += xc - xc2; yv[vn] += yc - yc2; } // Validate for (int v = 0; v < numVerts; v++){ double dx = xv[(v+1)%numVerts] - xv[v]; double dy = yv[(v+1)%numVerts] - yv[v]; if ( xv[v] != round(xv[v]) || yv[v] != round(yv[v]) || !( dx == 0 || dy == 0 || std::abs(dx) == std::abs(dy) ) ){ cerr << "Error: Expecting integer vertices with 45 degree angles." << endl; cerr << "Instead, got the vector (" << dx << ", " << dy << ") " << "with starting point " << xv[v] << ' ' << yv[v] << endl; //assert(false); } } return; } void snapOneEdgeTo45(int numAngles, double* xs, double* ys, bool snap2ndClosest, double & x0, double & y0, double & x1, double & y1){ double dx = x1 - x0, dy = y1 - y0; double len = distance(0, 0, dx, dy); if (len == 0.0) return; dx /= len; dy /= len; // Find the closest angle multiple of 45 degrees from (dx, dy) int minAngle = 0; double minDist = DBL_MAX; for (int a = 0; a < numAngles; a++){ double dist = distance(dx, dy, xs[a], ys[a]); if (dist <= minDist){ minDist = dist; minAngle = a; } } // We prefer to snap to the second closest angle if for some reason // we know that snapping to the closest angle does not work. if (snap2ndClosest){ int minAngle2 = 0; double minDist2 = DBL_MAX; for (int a = 0; a < numAngles; a++){ double dist = distance(dx, dy, xs[a], ys[a]); if (dist <= minDist2 && a != minAngle){ minDist2 = dist; minAngle2 = a; } } minAngle = minAngle2; } // Snap to integer coordinates in the direction of minAngle double factor = std::abs(xs[minAngle]) + std::abs(ys[minAngle]); // 1 or sqrt(2) len = factor*round(len/factor); x1 = x0 + round( len*xs[minAngle] ); y1 = y0 + round( len*ys[minAngle] ); return; } void minDistFromPtToSeg(//inputs double xin, double yin, double x0, double y0, double x1, double y1, // outputs double & minX, double & minY, double & minDist ){ // Given the point (xin, yin) and the segment going from (x0, y0) to // (x1, y1), find the point (minX, minY) on this segment (not on its // continuation) closest to (xin, yin). double a = (x1 - x0)*(x1 - x0) + (y1 - y0)*(y1 - y0); double b = (xin - x0)*(x1 - x0) + (yin - y0)*(y1 - y0); double t; if (a == 0.0) t = 0.0; else t = b/a; t = max(t, 0.0); t = min(t, 1.0); minX = x0 + t*(x1 - x0); minY = y0 + t*(y1 - y0); minDist = sqrt ( (xin - minX)*(xin - minX) + (yin - minY)*(yin - minY) ); return; } void searchForColor(std::string lineStr, // input, not a reference on purpose std::string & color // output ){ // const char * xgraph_colors[] = // {"black", "white", "red", "blue", "green", "violet", // "orange", "yellow", "pink", "cyan", "lightGray", // "darkGray", "fuchsia", "aqua", "navy", "gold"}; const char * xgraph_colors[] = {"black", "white", "red", "blue", "green", "violet", // 0, ..., 5 "orange", "yellow", "pink", "cyan", "#A2B5CD", // 6, ..., 10 "#6C7B8B", "#FF00FF", "#00CDCD", "navy", "gold" // 11, ..., 15 }; char * line = (char*)lineStr.c_str(); const char * col = "color"; char * start = strstr(line, col); if (start == NULL) return; if (strlen(start) <= strlen(col)) return; start += strlen(col); // Strip the equal sign, quotes, etc. for (int i = 0; i < (int)strlen(start); i++){ if (start[i] == '"' || start[i] == '=' || start[i] == '\''){ start[i] = ' '; } } const char *delimiter = " \t"; char * pch = strtok (start, delimiter); if (pch == NULL) return; color = string(pch); int numColors = sizeof(xgraph_colors)/sizeof(char*); // If the color is given as a number, per xgraph's conventions // (e.g., red is color 2), convert that number to the color name. if ('0' <= pch[0] && pch[0] <= '9'){ int colorIndex = atoi(pch)%numColors; color = string( xgraph_colors[colorIndex] ); } return; } bool searchForAnnotation(std::string lineStr, anno & annotation){ // Search for annotations, which have the form: // anno xval yval label // Return true on success. istringstream iss (lineStr); string an, label; double x, y; if ( ( !(iss >> an >> x >> y) ) || an != "anno" ){ return false; } getline(iss, label); // Everything else goes to the label annotation.x = x; annotation.y = y; annotation.label = label; return true; } void searchForLayer(std::string lineStr, // input std::string & layer // output ){ layer = ""; // We are searching for ";" followed by zero or more spaces, // followed by something like "65:0" char * line = (char *) lineStr.c_str(); char * start1 = strstr(line, ";"); if (start1 == NULL) return; start1++; // Move beyond ";" if (*start1 == '\0') return; int l1 = atoi(start1); char * start2 = strstr(start1, ":"); if (start2 == NULL) return; start2++; // Move beyond ":" if (*start2 == '\0') return; int l2 = atoi(start2); ostringstream strout; strout << l1 << ':' << l2; layer = strout.str(); return; } double signedPolyArea(int numV, const double* xv, const double* yv){ // Subtract the first vertex when computing the area to handle more // accurately polygons very far from the origin. double area = 0.0; for (int vIter = 0; vIter < numV; vIter++){ int vNext = (vIter + 1)%numV; area += (xv[vIter] - xv[0])*(yv[vNext] - yv[0]) - (xv[vNext] - xv[0])*(yv[vIter] - yv[0]); } area /= 2.0; return area; } void expandBoxToGivenRatio(// inputs double aspectRatio, // inputs/outputs double & xll, double & yll, double & widx, double & widy){ // Expand the given box to have the aspect ratio equal to the number aspectRatio. assert(widx > 0.0 && widy > 0.0 && aspectRatio > 0.0); double nwidx = widx, nwidy = widy; if (widy/widx <= aspectRatio) nwidy = widx*aspectRatio; else nwidx = widy/aspectRatio; // Sanity checks double tol = 1.0e-3; bool check = ( nwidx >= widx*(1 - tol) && nwidy >= widy*(1 - tol) && std::abs(nwidy/nwidx - aspectRatio) < tol*aspectRatio ); if (!check){ cout << "ERROR!" << endl; cout << "widx widy are " << widx << ' ' << widy << endl; cout << "nwidx nwidy are " << nwidx << ' ' << nwidy << endl; cout << "Aspect ratio is " << aspectRatio << endl; cout << "|nwidy/nwidx - aspectRatio| = " << std::abs(nwidy/nwidx - aspectRatio) << endl; cout << "Max allowed error is " << tol*aspectRatio << endl; } assert(check); // Make the new bounding box have the same center as the old one xll += widx/2.0 - nwidx/2.0; yll += widy/2.0 - nwidy/2.0; // Overwrite the previous box widx = nwidx; widy = nwidy; return; } bool boxesIntersect(double xl1, double yl1, double xh1, double yh1, double xl2, double yl2, double xh2, double yh2){ assert(xl1 <= xh1 && yl1 <= yh1); assert(xl2 <= xh2 && yl2 <= yh2); return(std::max(xl1, xl2) <= std::min(xh1, xh2) && std::max(yl1, yl2) <= std::min(yh1, yh2)); } bool mergePolys(int an, const double * ax_in, const double * ay_in, int bn, const double * bx_in, const double * by_in, std::vector<double> & mergedX, std::vector<double> & mergedY ){ // Merge two polygons. This function is INCOMPLETE and BUGGY. // To be finished. mergedX.clear(); mergedY.clear(); // The tol value needs careful thinking double tol = 1e-12; // Copy the pointers to non-constant pointers so what we can std::swap // them. double* ax = (double*)ax_in; double* ay = (double*)ay_in; double* bx = (double*)bx_in; double* by = (double*)by_in; bool mergeWasSuccessful = false; int i = 0, in = 0, j = 0; // Start at a vertex of A which is not inside of B. for (int t = 0; t < an; t++){ if (isPointInPolyOrOnEdges(ax[t], ay[t], bn, bx, by)) continue; i = t; in = t; j = t; break; } double sx = ax[i], sy = ay[i]; double currX = ax[i], currY = ay[i]; mergedX.push_back(currX); mergedY.push_back(currY); while(1){ bool foundIntersection = false; double x = 0.0, y = 0.0; // Of all edges of poly B intersecting the current edge (if any) // of poly A find the one for which the intersection point // is closest to the start of the current edge of poly A. // Care is taken of situations when there is more than one // such edge. in = (i + 1)% an; j = 0; // Make initial minDistA big on purpose by some value. double minDistA = 2.0*distance(currX, currY, ax[in], ay[in]) + 1.0; double minDistB_beg = -1.0, maxDistB_end = -1.0; for (int jl = 0; jl < bn; jl++){ int jnl = (jl + 1) % bn; double xl, yl; if (edgesIntersect(currX, currY, ax[in], ay[in], bx[jl], by[jl], bx[jnl], by[jnl], xl, yl) && isPointOnEdge(currX, currY, ax[in], ay[in], xl, yl) && (std::abs(currX - xl) > tol || std::abs(currY - yl) > tol) ){ foundIntersection = true; mergeWasSuccessful = true; double distA = distance(currX, currY, xl, yl); double distB_beg = distance(bx[jl], by[jl], xl, yl); double distB_end = distance(xl, yl, bx[jnl], by[jnl]); if (minDistB_beg < 0.0) minDistB_beg = distB_beg; if (maxDistB_end < 0.0) maxDistB_end = distB_end; if (distA < minDistA || (distA == minDistA && distB_beg < minDistB_beg) || (distA == minDistA && distB_beg == minDistB_beg && distB_end >= maxDistB_end ) ){ minDistA = distA; minDistB_beg = distB_beg; maxDistB_end = distB_end; j = jl; ; x = xl; y = yl; } } } if (!foundIntersection){ i = in; if (sx == ax[i] && sy == ay[i]) break; // reached the starting point currX = ax[i]; currY = ay[i]; mergedX.push_back(currX); mergedY.push_back(currY); continue; } currX = x; currY = y; mergedX.push_back(currX); mergedY.push_back(currY); std::swap(ax, bx); std::swap(ay, by); std::swap(an, bn); i = j; //if (sx == ax[i] && sy == ay[i]) break; } return mergeWasSuccessful; } bool isPointInPolyOrOnEdges(double x, double y, int n, const double* xv, const double* yv){ // Is the given point either completely inside or on the edges // of the given polygon. if (n <= 0) return false; bool isInsideOrOnEdges = false; for (int i = 0; i < n; i++){ int j = (i + 1)%n; double x0 = xv[i], x1 = xv[j]; double y0 = yv[i], y1 = yv[j]; if (x0 > x1){ std::swap(x0, x1); std::swap(y0, y1); } if (x < x0 || x > x1) continue; if (x0 == x1){ if (y >= min(y0, y1) && y <= max(y0, y1)) return true; else continue; } double det = (y - y0)*(x1 - x0) - (x - x0)*(y1 - y0); if (det == 0) return true; // is on edge if (x < x1 && det < 0) isInsideOrOnEdges = !isInsideOrOnEdges; } return isInsideOrOnEdges; } }}
7,116
1,379
<reponame>ramiyer/voldemort<filename>clients/python/voldemort/serialization/ordered_dict.py class OrderedDict(dict): def __init__(self, args=None, **kwargs): dict.__init__(self) self.keyList = [] if args: if isinstance(args, dict): for k, v in args.iteritems(): self[k] = v else: for k, v in args: self[k] = v if kwargs: for k, v in kwargs.iteritems(): self[k] = v def keys(self): return self.keyList def iterkeys(self): return iter(self.keyList) def __iter__(self): return iter(self.keyList) def items(self): return [(k, self[k]) for k in self.iterkeys()] def iteritems(self): for k in self.iterkeys(): yield (k, self[k]) def itervalues(self): for k in self.iterkeys(): yield self[k] def values(self): return [self[k] for k in self.iterkeys()] def __setitem__(self, k, v): if dict.__contains__(self, k): self.keyList.remove(k) self.keyList.append(k) dict.__setitem__(self, k, v) def __delitem__(self, k): if dict.__contains__(self, k): self.keyList.remove(k) dict.__delitem__(self, k) def __str__(self): tokens = ['{'] for k, v in self.iteritems(): if len(tokens) > 1: tokens.append(', ') tokens.append(repr(k)) tokens.append(':') tokens.append(repr(v)) tokens.append('}') return ''.join(tokens) def __repr__(self): return str(self)
900
312
#ifndef _LOGGER_H #define _LOGGER_H #ifndef __GNUC__ #define __builtin_expect(a, b) (a) #endif #ifndef LOGGER_WIDTH #define LOGGER_WIDTH 80 #endif #ifndef LOGGER_INDENT #define LOGGER_INDENT 4 #endif #define LOGGER_SILENT 0 #define LOGGER_FATAL 1 #define LOGGER_ERROR 2 #define LOGGER_WARNING 3 #define LOGGER_INFO 4 #define LOGGER_VERBOSE 5 #define LOGGER_DEBUG 6 extern unsigned int logger_level; void logger_printf(char * fmt, ...) __attribute__((format(printf, 1, 2))); #define logger_printf_magic(level, ...) \ do { \ if (__builtin_expect(!!(level <= logger_level), 0)) { \ logger_printf(__VA_ARGS__); \ } \ } while (0) #define critical(...) do { logger_printf(__VA_ARGS__); } while (0) #define fatal(...) logger_printf_magic(LOGGER_FATAL, __VA_ARGS__) #define error(...) logger_printf_magic(LOGGER_ERROR, __VA_ARGS__) #define warning(...) logger_printf_magic(LOGGER_WARNING, __VA_ARGS__) #define info(...) logger_printf_magic(LOGGER_INFO, __VA_ARGS__) #define verbose(...) logger_printf_magic(LOGGER_VERBOSE, __VA_ARGS__) #ifdef NDEBUG #define debug(...) do { /* nop */ } while (0) #else #define debug(...) logger_printf_magic(LOGGER_DEBUG, __VA_ARGS__) #endif #endif
732
1,179
<filename>core/arch/arm/plat-vexpress/fvp_spmc_pm.c // SPDX-License-Identifier: BSD-2-Clause /* * Copyright (c) 2019-2021, Arm Limited */ #include <ffa.h> #include <kernel/boot.h> #include <kernel/panic.h> #include <kernel/thread.h> void ffa_secondary_cpu_ep_register(vaddr_t secondary_ep) { unsigned long ret = 0; /* * FFA_SECONDARY_EP_REGISTER_64 is handled by the SPMD if called by an * S-EL1 SPMC at secure physical FF-A instance. * It is handled by an S-EL2 SPMC if called by a SP at secure virtual * FF-A instance. */ ret = thread_smc(FFA_SECONDARY_EP_REGISTER_64, secondary_ep, 0, 0); if (ret != FFA_SUCCESS_64) { EMSG("FFA_SECONDARY_EP_REGISTER_64 ret %ld", ret); panic(); } }
296
1,396
/* * 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. */ package org.jdbi.v3.core.statement; import java.text.MessageFormat; import java.util.AbstractMap; import java.util.Comparator; import java.util.Set; /** * Uses the equivalent of {@link MessageFormat#format(String, Object...)} as a template engine. * * You must use "0", "1", "2", etc as keys: start at 0, increment by 1. Keys must be numerically unique. You must {@link org.jdbi.v3.core.config.Configurable#define(String, Object)} as many key/value pairs as there are placeholders in the pattern string. * * You may {@code define} key/value pairs in any order. Keys may contain leading {@code '0'}s. * * Any invalid use will trigger an {@link IllegalArgumentException} (or subclasses such as {@link NumberFormatException}) when {@link #render(String, StatementContext)} is called – typically when the statement is about to be executed. * * Example usage: * <pre>{@code * // select bar from foo where col = 'abc' * jdbi.useHandle(handle -> handle.createCall("select {1} from {0} where col = ''{2}''") * .setTemplateEngine(MessageFormatTemplateEngine.INSTANCE) * .define("0", "foo") * .define("1", "bar") * .define("2", "abc") * .invoke()); * }</pre> * * @deprecated {@link MessageFormat} formats integers with decimal separators, e.g. <code>1000</code> &rarr; <code>"1,000"</code>. This hindsight realization has led us to discourage its use. */ @Deprecated public class MessageFormatTemplateEngine implements TemplateEngine { public MessageFormatTemplateEngine() {} @Override public String render(String template, StatementContext ctx) { MessageFormat msgFormat = new MessageFormat(template); validateKeys(ctx.getAttributes().keySet(), msgFormat.getFormats().length); Object[] args = ctx.getAttributes() .entrySet() .stream() .map(x -> new AbstractMap.SimpleImmutableEntry<>(Integer.valueOf(x.getKey()), x.getValue())) .sorted(Comparator.comparingInt(AbstractMap.SimpleImmutableEntry::getKey)) .map(AbstractMap.SimpleImmutableEntry::getValue) .toArray(Object[]::new); return msgFormat.format(args); } private static void validateKeys(Set<String> keySet, int expectedCount) { if (keySet.size() != expectedCount) { throw new IllegalArgumentException("expected " + expectedCount + " keys but got " + keySet.size()); } if (keySet.isEmpty()) { return; } // keys inherently cannot be null, so we only need to check the content final int[] keys = keySet.stream() // throws IllegalArgumentException for us .mapToInt(Integer::parseInt) .sorted() .toArray(); if (keys[0] != 0) { throw new IllegalArgumentException("lowest key must be 0"); } for (int i = 1; i < keys.length; i++) { final int key = keys[i]; if (key < i) { throw new IllegalArgumentException("key " + key + " was given more than once"); } if (key > i) { throw new IllegalArgumentException("keys skip from " + (i - 1) + " to " + key); } } } }
1,392
839
/** * 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. */ package org.apache.cxf.aegis.databinding; import org.apache.cxf.aegis.util.NamespaceHelper; import org.apache.cxf.wsdl.service.factory.AbstractServiceConfiguration; /** * This service configuration uses XFire-compatible conventions for assigning namespace URI's to Java packages * when naming services. */ public class XFireCompatibilityServiceConfiguration extends AbstractServiceConfiguration { @Override public String getServiceNamespace() { String ret = super.getServiceNamespace(); if (ret == null) { ret = NamespaceHelper.makeNamespaceFromClassName(getServiceFactory().getServiceClass().getName(), "http"); } return ret; } }
467
679
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef _SFXDISPATCH_HXX #define _SFXDISPATCH_HXX #include "sal/config.h" #include "sfx2/dllapi.h" #include "sal/types.h" #include <stdarg.h> #define _SVSTDARR_USHORTS #include <svl/svstdarr.hxx> // SvUShorts #include <sfx2/bindings.hxx> #include <sfx2/viewfrm.hxx> class SfxSlotServer; class SfxShell; class SfxRequest; class SfxShellStack_Impl; class SfxHintPoster; class SfxViewFrame; class SfxBindings; class SfxItemSet; class SfxPopupMenuManager; class SfxModule; struct SfxDispatcher_Impl; struct SfxPlugInInfo_Impl; namespace com { namespace sun { namespace star { namespace frame { class XDispatch; } } } } //========================================================================= #define SFX_SHELL_POP_UNTIL 4 #define SFX_SHELL_POP_DELETE 2 #define SFX_SHELL_PUSH 1 //========================================================================= typedef SfxPoolItem* SfxPoolItemPtr; SV_DECL_PTRARR_DEL( SfxItemPtrArray, SfxPoolItemPtr, 4, 4 ) // fuer shell.cxx typedef SfxItemPtrArray SfxItemArray_Impl; class SfxExecuteItem : public SfxItemPtrArray, public SfxPoolItem { sal_uInt16 nSlot; SfxCallMode eCall; sal_uInt16 nModifier; public: sal_uInt16 GetSlot() const { return nSlot; } sal_uInt16 GetModifier() const { return nModifier; } void SetModifier( sal_uInt16 nModifierP ) { nModifier = nModifierP; } SfxCallMode GetCallMode() const { return eCall; } void SetCallMode( SfxCallMode eMode ) { eCall = eMode; } virtual int operator==( const SfxPoolItem& ) const; virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const; SfxExecuteItem( sal_uInt16 nWhich, sal_uInt16 nSlot, SfxCallMode eMode, const SfxPoolItem *pArg1, ... ); SfxExecuteItem( sal_uInt16 nWhich, sal_uInt16 nSlot, SfxCallMode eMode ); SfxExecuteItem( const SfxExecuteItem& ); }; //========================================================================= class SFX2_DLLPUBLIC SfxDispatcher { SfxDispatcher_Impl* pImp; sal_Bool bFlushed; private: // auf temporaer ausgewerteten Todos suchen SAL_DLLPRIVATE sal_Bool CheckVirtualStack( const SfxShell& rShell, sal_Bool bDeep ); #ifndef _SFX_HXX friend class SfxApplication; friend class SfxViewFrame; DECL_DLLPRIVATE_LINK( EventHdl_Impl, void * ); DECL_DLLPRIVATE_LINK( PostMsgHandler, SfxRequest * ); SAL_DLLPRIVATE int Call_Impl( SfxShell& rShell, const SfxSlot &rSlot, SfxRequest &rReq, sal_Bool bRecord ); SAL_DLLPRIVATE void _Update_Impl( sal_Bool,sal_Bool,sal_Bool,SfxWorkWindow*); SAL_DLLPRIVATE void CollectTools_Impl(SfxWorkWindow*); protected: friend class SfxBindings; friend class SfxStateCache; friend class SfxPopupMenuManager; friend class SfxHelp; // Fuer die Bindings: Finden einer Message; Level fuer // erneuten Zugriff SAL_DLLPRIVATE sal_Bool _TryIntercept_Impl( sal_uInt16 nId, SfxSlotServer &rServer, sal_Bool bModal ); sal_Bool _FindServer( sal_uInt16 nId, SfxSlotServer &rServer, sal_Bool bModal ); sal_Bool _FillState( const SfxSlotServer &rServer, SfxItemSet &rState, const SfxSlot *pRealSlot ); const SfxPoolItem* _Execute( const SfxSlotServer &rServer ); void _Execute( SfxShell &rShell, const SfxSlot &rSlot, SfxRequest &rReq, SfxCallMode eCall = SFX_CALLMODE_STANDARD); const SfxPoolItem* _Execute( sal_uInt16 nSlot, SfxCallMode eCall, va_list pArgs, const SfxPoolItem *pArg1 ); #endif protected: void FlushImpl(); public: SfxDispatcher( SfxDispatcher* pParent ); SfxDispatcher( SfxViewFrame *pFrame = 0 ); SAL_DLLPRIVATE void Construct_Impl( SfxDispatcher* pParent ); virtual ~SfxDispatcher(); const SfxPoolItem* Execute( const SfxExecuteItem& rItem ); virtual sal_uInt16 ExecuteFunction( sal_uInt16 nSID, SfxPoolItem** ppArgs=0, sal_uInt16 nMode=0 ); sal_uInt16 ExecuteFunction( sal_uInt16 nSID, const SfxItemSet& rArgs , sal_uInt16 nMode=0 ); virtual void SetExecuteMode( sal_uInt16 ); const SfxPoolItem* Execute( sal_uInt16 nSlot, SfxCallMode nCall = SFX_CALLMODE_SLOT, const SfxPoolItem **pArgs = 0, sal_uInt16 nModi = 0, const SfxPoolItem **pInternalArgs = 0); const SfxPoolItem* Execute( sal_uInt16 nSlot, SfxCallMode nCall, SfxItemSet* pArgs, SfxItemSet* pInternalArgs, sal_uInt16 nModi = 0); const SfxPoolItem* Execute( sal_uInt16 nSlot, SfxCallMode nCall, const SfxPoolItem *pArg1, ... ); const SfxPoolItem* Execute( sal_uInt16 nSlot, SfxCallMode nCall, const SfxItemSet &rArgs ); const SfxPoolItem* Execute( sal_uInt16 nSlot, SfxCallMode nCall, sal_uInt16 nModi, const SfxItemSet &rArgs ); sal_uInt16 GetSlotId( const String& rCommand ); const SfxSlot* GetSlot( const String& rCommand ); sal_Bool IsActive( const SfxShell& rShell ); sal_Bool IsOnTop( const SfxShell& rShell ); sal_uInt16 GetShellLevel( const SfxShell &rShell ); SfxBindings* GetBindings() const; void Push( SfxShell& rShell ); void Pop( SfxShell& rShell, sal_uInt16 nMode = 0 ); SfxShell* GetShell(sal_uInt16 nIdx) const; SfxViewFrame* GetFrame() const; SfxModule* GetModule() const; // caller has to clean up the Manager on his own static SfxPopupMenuManager* Popup( sal_uInt16 nConfigId,Window *pWin, const Point *pPos ); void ExecutePopup( const ResId &rId, Window *pWin = 0, const Point *pPosPixel = 0 ); static void ExecutePopup( sal_uInt16 nConfigId = 0, Window *pWin = 0, const Point *pPosPixel = 0 ); static void ExecutePopup( sal_uInt16 nConfigId, Window *pWin, const Point *pPosPixel, const SfxPoolItem *pArg1, ... ); sal_Bool IsAppDispatcher() const; sal_Bool IsFlushed() const; void Flush(); void Lock( sal_Bool bLock ); sal_Bool IsLocked( sal_uInt16 nSID = 0 ) const; void SetSlotFilter( sal_Bool bEnable = sal_False, sal_uInt16 nCount = 0, const sal_uInt16 *pSIDs = 0 ); void HideUI( sal_Bool bHide = sal_True ); void ShowObjectBar(sal_uInt16 nId, SfxShell *pShell=0) const; sal_uInt32 GetObjectBarId( sal_uInt16 nPos ) const; SfxItemState QueryState( sal_uInt16 nSID, const SfxPoolItem* &rpState ); SfxItemState QueryState( sal_uInt16 nSID, ::com::sun::star::uno::Any& rAny ); sal_Bool IsAllowed( sal_uInt16 nSlot ) const; ::com::sun::star::frame::XDispatch* GetDispatchInterface( const String& ); void SetDisableFlags( sal_uInt32 nFlags ); sal_uInt32 GetDisableFlags() const; //#if 0 // _SOLAR__PRIVATE SAL_DLLPRIVATE sal_Bool HasSlot_Impl( sal_uInt16 ); SAL_DLLPRIVATE void SetMenu_Impl(); SAL_DLLPRIVATE void Update_Impl( sal_Bool bForce = sal_False ); // ObjectBars etc. SAL_DLLPRIVATE sal_Bool IsUpdated_Impl() const; SAL_DLLPRIVATE void DebugOutput_Impl() const; SAL_DLLPRIVATE void ResetObjectBars_Impl(); SAL_DLLPRIVATE int GetShellAndSlot_Impl( sal_uInt16 nSlot, SfxShell **ppShell, const SfxSlot **ppSlot, sal_Bool bOwnShellsOnly, sal_Bool bModal, sal_Bool bRealSlot=sal_True ); SAL_DLLPRIVATE void LockUI_Impl( sal_Bool bLock = sal_True ); SAL_DLLPRIVATE void SetReadOnly_Impl( sal_Bool bOn ); SAL_DLLPRIVATE sal_Bool GetReadOnly_Impl() const; SAL_DLLPRIVATE sal_Bool IsSlotEnabledByFilter_Impl( sal_uInt16 nSID ) const; SAL_DLLPRIVATE void SetQuietMode_Impl( sal_Bool bOn ); SAL_DLLPRIVATE void SetModalMode_Impl( sal_Bool bOn ); SAL_DLLPRIVATE sal_Bool IsReadOnlyShell_Impl( sal_uInt16 nShell ) const; SAL_DLLPRIVATE void RemoveShell_Impl( SfxShell& rShell ); SAL_DLLPRIVATE void InsertShell_Impl( SfxShell& rShell, sal_uInt16 nPos ); SAL_DLLPRIVATE void DoParentActivate_Impl(); SAL_DLLPRIVATE void DoParentDeactivate_Impl(); SAL_DLLPRIVATE void DoActivate_Impl( sal_Bool bMDI, SfxViewFrame* pOld ); SAL_DLLPRIVATE void DoDeactivate_Impl( sal_Bool bMDI, SfxViewFrame* pNew ); SAL_DLLPRIVATE void InvalidateBindings_Impl(sal_Bool); SAL_DLLPRIVATE sal_uInt16 GetNextToolBox_Impl( sal_uInt16 nPos, sal_uInt16 nType, String *pStr ); //#endif }; //-------------------------------------------------------------------- inline sal_Bool SfxDispatcher::IsFlushed() const /* [Beschreibung] Mit dieser Methode l"a"st sich erfragen, ob der Stack des SfxDispatchers geflusht ist, oder noch Push- oder Pop-Befehle ausstehen. */ { return bFlushed; } //-------------------------------------------------------------------- inline void SfxDispatcher::Flush() /* [Beschreibung] Diese Methode f"uhrt ausstehenden Push- und Pop-Befehle aus. F"ur <SfxShell>s, die dabei neu auf den Stack kommen, wird <SfxShell::Activate(sal_Bool)> mit bMDI == sal_True aufgerufen, f"ur SfxShells, die vom Stack entfernt werden, wird <SfxShell::Deactivate(sal_Bool)> mit bMDI == sal_True aufgerufen. */ { if ( !bFlushed ) FlushImpl(); } //-------------------------------------------------------------------- inline void SfxDispatcher::Push( SfxShell& rShell ) /* [Beschreibung] Mit dieser Methode wird eine <SfxShell> auf den SfxDispatcher gepusht. Die SfxShell wird zun"achst zum pushen vermerkt und es wird ein Timer aufgesetzt. Erst bei Ablauf des Timers wird tats"achlich gepusht (<SfxDispatcher::Flush()>) und die <SfxBindings> werden invalidiert. W"ahrend der Timer l"auft gleichen sich entgegengesetzte Push und Pop Befehle mit derselben SfxShell aus. */ { Pop( rShell, SFX_SHELL_PUSH ); } //-------------------------------------------------------------------- inline sal_Bool SfxDispatcher::IsActive( const SfxShell& rShell ) /* [Beschreibung] Mit dieser Methode kann abgefragt werden, ob sich eine bestimmte <SfxShell>-Instanz auf dem SfxDispatcher befindet. [R"uckgabewert] sal_Bool sal_True Die SfxShell-Instanz befindet sich auf dem SfxDispatcher. sal_False Die SfxShell-Instanz befindet sich nicht auf dem SfxDispatcher. */ { return CheckVirtualStack( rShell, sal_True ); } //-------------------------------------------------------------------- inline sal_Bool SfxDispatcher::IsOnTop( const SfxShell& rShell ) /* [Beschreibung] Mit dieser Methode kann abgefragt werden, ob sich eine bestimmte <SfxShell>-Instanz zuoberst auf dem SfxDispatcher befindet. [R"uckgabewert] sal_Bool sal_True Die SfxShell-Instanz befindet sich als oberste SfxShell auf dem SfxDispatcher. sal_False Die SfxShell-Instanz befindet sich nicht als oberste SfxShell auf dem SfxDispatcher. */ { return CheckVirtualStack( rShell, sal_False ); } //-------------------------------------------------------------------- #endif
4,895
628
# -*- coding: utf-8 -*- import pytest from osf.models import QuickFilesNode from osf_tests.factories import AuthUserFactory from tests.base import test_app from webtest_plus import TestApp from addons.osfstorage.tests.utils import make_payload from framework.auth import signing @pytest.fixture() def user(): return AuthUserFactory() @pytest.fixture() def quickfiles(user): return QuickFilesNode.objects.get(creator=user) @pytest.fixture() def flask_app(): return TestApp(test_app) @pytest.fixture() def post_to_quickfiles(quickfiles, user, flask_app, **kwargs): def func(name, *args, **kwargs): osfstorage = quickfiles.get_addon('osfstorage') root = osfstorage.get_root() url = '/api/v1/{}/osfstorage/{}/children/'.format(quickfiles._id, root._id) expect_errors = kwargs.pop('expect_errors', False) payload = make_payload(user=user, name=name, **kwargs) res = flask_app.post_json(url, signing.sign_data(signing.default_signer, payload), expect_errors=expect_errors) return res return func @pytest.mark.django_db @pytest.mark.enable_quickfiles_creation class TestUserQuickFilesNodeFileCreation: def test_create_file(self, quickfiles, user, post_to_quickfiles): name = 'WoopThereItIs.pdf' res = post_to_quickfiles(name) assert res.status_code == 201 assert res.json['status'] == 'success' assert quickfiles.files.filter(name=name).exists() def test_create_folder_throws_error(self, flask_app, user, quickfiles, post_to_quickfiles): name = 'new_illegal_folder' res = post_to_quickfiles(name, kind='folder', expect_errors=True) assert res.status_code == 400
662
1,168
<filename>jmxtrans-output/jmxtrans-output-core/src/main/java/com/googlecode/jmxtrans/model/output/StackdriverWriter.java /** * The MIT License * Copyright © 2010 JmxTrans team * * 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. */ package com.googlecode.jmxtrans.model.output; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.googlecode.jmxtrans.model.Query; import com.googlecode.jmxtrans.model.Result; import com.googlecode.jmxtrans.model.Server; import com.googlecode.jmxtrans.model.ValidationException; import com.googlecode.jmxtrans.model.naming.KeyUtils; import com.googlecode.jmxtrans.model.naming.typename.TypeNameValuesStringBuilder; import lombok.EqualsAndHashCode; import lombok.ToString; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.io.Writer; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.MalformedURLException; import java.net.Proxy; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; import static com.google.common.base.Charsets.ISO_8859_1; import static com.google.common.base.Strings.isNullOrEmpty; import static com.googlecode.jmxtrans.util.NumberUtils.isNumeric; import static org.apache.commons.lang.StringUtils.isAlphanumeric; /** * <a href="https://www.stackdriver.com//">Stackdriver</a> implementation of the * {@linkplain com.googlecode.jmxtrans.model.OutputWriter}. * <p/> * This implementation uses <a href="https://custom-gateway.stackdriver.com/v1/custom"> POST {@code /v1/metrics}</a> * HTTP API. * <p/> * Settings: * <ul> * <li>"{@code url}": Stackdriver server URL. Optional, default value: {@value #DEFAULT_STACKDRIVER_API_URL}.</li> * <li>"{@code token}": Stackdriver API token. Mandatory</li> * <li>"{@code prefix}": Prefix for the metric names. If present will be prepended to the metric name. Should be alphanumeric. * Optional, shouldn't be used at the same time as source or detectInstance. Different way of namespacing.</li> * <li>"{@code source}": Instance of the machine ID that the JMX data is being collected from. Optional. * <li>"{@code detectInstance}": Set to "AWS" if you want to detect the local AWS instance ID on startup. Optional. * <li>"{@code timeoutInMillis}": read timeout of the calls to Stackdriver HTTP API. Optional, default * value: {@value #DEFAULT_STACKDRIVER_API_TIMEOUT_IN_MILLIS}.</li> * <li>"{@code enabled}": flag to enable/disable the writer. Optional, default value: <code>true</code>.</li> * </ul> * * @author <a href="mailto:<EMAIL>"><NAME></a> */ @EqualsAndHashCode(exclude = "jsonFactory") @ToString public class StackdriverWriter extends BaseOutputWriter { private static final Logger logger = LoggerFactory.getLogger(StackdriverWriter.class); // constant protocol version, this can be updated in future versions for protocol changes public static final int STACKDRIVER_PROTOCOL_VERSION = 1; // defaults for values that can be overridden in settings public static final int DEFAULT_STACKDRIVER_API_TIMEOUT_IN_MILLIS = 1000; public static final String DEFAULT_STACKDRIVER_API_URL = "https://custom-gateway.stackdriver.com/v1/custom"; // names of settings public static final String SETTING_STACKDRIVER_API_URL = "url"; public static final String SETTING_PROXY_PORT = "proxyPort"; public static final String SETTING_PROXY_HOST = "proxyHost"; public static final String SETTING_STACKDRIVER_API_KEY = "token"; public static final String SETTING_SOURCE_INSTANCE = "source"; public static final String SETTING_DETECT_INSTANCE = "detectInstance"; public static final String SETTING_STACKDRIVER_API_TIMEOUT_IN_MILLIS = "stackdriverApiTimeoutInMillis"; public static final String SETTING_PREFIX = "prefix"; /** * The instance ID that metrics from this writer should be associated with in Stackdriver, an example of this * would be an EC2 instance ID in the form i-00000000 that is present in your environment. */ private final String instanceId; private final String source; private final String detectInstance; /** * Prefix sent in the settings of this one writer. Will be prepended before the metric names that are sent * to Stackdriver with a period in between. Should be alphanumeric [A-Za-z0-9] with no punctuation or spaces. */ private final String prefix; /** * The gateway URL to post metrics to, this can be overridden for testing locally but should generally be * left at the default. * * @see #DEFAULT_STACKDRIVER_API_URL */ private final URL gatewayUrl; /** * A Proxy object that can be set using the proxyHost and proxyPort settings if the server can't post directly * to the gateway */ private final Proxy proxy; private final String proxyHost; private final Integer proxyPort; /** * Stackdriver API key generated in the account settings section on Stackdriver. Mandatory for data to be * recognized in the Stackdriver gateway. */ private final String apiKey; private int timeoutInMillis = DEFAULT_STACKDRIVER_API_TIMEOUT_IN_MILLIS; private JsonFactory jsonFactory = new JsonFactory(); @JsonCreator public StackdriverWriter( @JsonProperty("typeNames") ImmutableList<String> typeNames, @JsonProperty("booleanAsNumber") boolean booleanAsNumber, @JsonProperty("debug") Boolean debugEnabled, @JsonProperty("gatewayUrl") String gatewayUrl, @JsonProperty("apiKey") String apiKey, @JsonProperty("proxyHost") String proxyHost, @JsonProperty("proxyPort") Integer proxyPort, @JsonProperty("prefix") String prefix, @JsonProperty("timeoutInMillis") Integer timeoutInMillis, @JsonProperty("source") String source, @JsonProperty("detectInstance") String detectInstance, @JsonProperty("settings") Map<String, Object> settings) throws MalformedURLException { super(typeNames, booleanAsNumber, debugEnabled, settings); this.gatewayUrl = new URL(firstNonNull( gatewayUrl, (String) getSettings().get(SETTING_STACKDRIVER_API_URL), DEFAULT_STACKDRIVER_API_URL)); this.apiKey = MoreObjects.firstNonNull(apiKey, (String) getSettings().get(SETTING_STACKDRIVER_API_KEY)); // Proxy configuration if (proxyHost == null) { proxyHost = (String) getSettings().get(SETTING_PROXY_HOST); } if (proxyPort == null) { proxyPort = (Integer) getSettings().get(SETTING_PROXY_PORT); } this.proxyHost = proxyHost; this.proxyPort = proxyPort; if (!isNullOrEmpty(this.proxyHost)) { proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(this.proxyHost, this.proxyPort)); } else { proxy = null; } // Prefix this.prefix = firstNonNull(prefix, (String) getSettings().get(SETTING_PREFIX), ""); if (!isNullOrEmpty(this.prefix)) { if (!isAlphanumeric(this.prefix)) { throw new IllegalArgumentException("Prefix setting must be alphanumeric only [A-Za-z0-9]"); } } logger.info("Setting prefix to " + this.prefix); this.timeoutInMillis = firstNonNull( timeoutInMillis, Settings.getIntegerSetting(getSettings(), SETTING_STACKDRIVER_API_TIMEOUT_IN_MILLIS, null), DEFAULT_STACKDRIVER_API_TIMEOUT_IN_MILLIS); // try to get and instance ID if (source == null) { source = (String) getSettings().get(SETTING_SOURCE_INSTANCE); } this.source = source; if (detectInstance == null) { detectInstance = (String) getSettings().get(SETTING_DETECT_INSTANCE); } this.detectInstance = detectInstance; this.instanceId = computeInstanceId(this.source, this.detectInstance); } /** * Sets up the object and makes sure all the required parameters are available<br/> * Minimally a Stackdriver API key must be provided using the token setting */ @Override public void validateSetup(Server server, Query query) throws ValidationException { logger.info("Starting Stackdriver writer connected to '{}', proxy {} ...", gatewayUrl, proxy); } private String computeInstanceId(String source, String detectInstance) { String result; if (!isNullOrEmpty(source)) { // if one is set directly use that result = source; logger.info("Using instance ID {} from setting {}", result, SETTING_SOURCE_INSTANCE); } else { if ("AWS".equalsIgnoreCase(detectInstance)) { // if setting is to detect, look on the local machine URL logger.info("Detect instance set to AWS, trying to determine AWS instance ID"); result = getLocalInstanceId("AWS", "http://169.254.169.254/latest/meta-data/instance-id", null); if (result != null) { } else { logger.info("Unable to detect AWS instance ID for this machine, sending metrics without an instance ID"); } } else if ("GCE".equalsIgnoreCase(detectInstance)) { // if setting is to detect, look on the local machine URL logger.info("Detect instance set to GCE, trying to determine GCE instance ID"); result = getLocalInstanceId("GCE", "http://metadata/computeMetadata/v1/instance/id", ImmutableMap.of("X-Google-Metadata-Request", "True")); if (result == null) { logger.info("Unable to detect GCE instance ID for this machine, sending metrics without an instance ID"); } } else { // no instance ID, the metrics will be sent as "bare" custom metrics and not associated with an instance result = null; logger.info("No source instance ID passed, and not set to detect, sending metrics without an instance ID"); } } logger.info("Detected instance ID as {}", result); return result; } /** * Implementation of the base writing method. Operates in two stages: * <br/> * First turns the query result into a JSON message in Stackdriver format * <br/> * Second posts the message to the Stackdriver gateway via HTTP */ @Override public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception { String gatewayMessage = getGatewayMessage(results); // message won't be returned if there are no numeric values in the query results if (gatewayMessage != null) { logger.info(gatewayMessage); doSend(gatewayMessage); } } /** * Take query results, make a JSON String * * @param results List of Result objects * @return a String containing a JSON message, or null if there are no values to report * * @throws IOException if there is some problem generating the JSON, should be uncommon */ private String getGatewayMessage(final List<Result> results) throws IOException { int valueCount = 0; Writer writer = new StringWriter(); JsonGenerator g = jsonFactory.createGenerator(writer); g.writeStartObject(); g.writeNumberField("timestamp", System.currentTimeMillis() / 1000); g.writeNumberField("proto_version", STACKDRIVER_PROTOCOL_VERSION); g.writeArrayFieldStart("data"); List<String> typeNames = this.getTypeNames(); for (Result metric : results) { if (isNumeric(metric.getValue())) { // we have a numeric value, write a value into the message StringBuilder nameBuilder = new StringBuilder(); // put the prefix if set if (this.prefix != null) { nameBuilder.append(prefix); nameBuilder.append("."); } // put the class name or its alias if available if (!metric.getKeyAlias().isEmpty()) { nameBuilder.append(metric.getKeyAlias()); } else { nameBuilder.append(metric.getClassName()); } // Wildcard "typeNames" substitution String typeName = com.googlecode.jmxtrans.model.naming.StringUtils.cleanupStr( TypeNameValuesStringBuilder.getDefaultBuilder().build(typeNames, metric.getTypeName())); if (typeName != null && typeName.length() > 0) { nameBuilder.append("."); nameBuilder.append(typeName); } // add the attribute name nameBuilder.append("."); nameBuilder.append(KeyUtils.getValueKey(metric)); // check for Float/Double NaN since these will cause the message validation to fail if (metric.getValue() instanceof Float && ((Float) metric.getValue()).isNaN()) { logger.info("Metric value for " + nameBuilder.toString() + " is NaN, skipping"); continue; } if (metric.getValue() instanceof Double && ((Double) metric.getValue()).isNaN()) { logger.info("Metric value for " + nameBuilder.toString() + " is NaN, skipping"); continue; } valueCount++; g.writeStartObject(); g.writeStringField("name", nameBuilder.toString()); g.writeNumberField("value", Double.valueOf(metric.getValue().toString())); // if the metric is attached to an instance, include that in the message if (instanceId != null && !instanceId.isEmpty()) { g.writeStringField("instance", instanceId); } g.writeNumberField("collected_at", metric.getEpoch() / 1000); g.writeEndObject(); } } g.writeEndArray(); g.writeEndObject(); g.flush(); g.close(); // return the message if there are any values to report if (valueCount > 0) { return writer.toString(); } else { return null; } } /** * Post the formatted results to the gateway URL over HTTP * * @param gatewayMessage String in the Stackdriver custom metrics JSON format containing the data points */ private void doSend(final String gatewayMessage) { HttpURLConnection urlConnection = null; try { if (proxy == null) { urlConnection = (HttpURLConnection) gatewayUrl.openConnection(); } else { urlConnection = (HttpURLConnection) gatewayUrl.openConnection(proxy); } urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setReadTimeout(timeoutInMillis); urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8"); urlConnection.setRequestProperty("x-stackdriver-apikey", apiKey); // Stackdriver's own implementation does not specify char encoding // to use. Let's take the simplest approach and at lest ensure that // if we have problems they can be reproduced in consistant ways. // See https://github.com/Stackdriver/stackdriver-custommetrics-java/blob/master/src/main/java/com/stackdriver/api/custommetrics/CustomMetricsPoster.java#L262 // for details. urlConnection.getOutputStream().write(gatewayMessage.getBytes(ISO_8859_1)); int responseCode = urlConnection.getResponseCode(); if (responseCode != 200 && responseCode != 201) { logger.warn("Failed to send results to Stackdriver server: responseCode=" + responseCode + " message=" + urlConnection.getResponseMessage()); } } catch (Exception e) { logger.warn("Failure to send result to Stackdriver server", e); } finally { if (urlConnection != null) { try { InputStream in = urlConnection.getInputStream(); in.close(); InputStream err = urlConnection.getErrorStream(); if (err != null) { err.close(); } urlConnection.disconnect(); } catch (IOException e) { logger.warn("Error flushing http connection for one result, continuing"); logger.debug("Stack trace for the http connection, usually a network timeout", e); } } } } /** * Use a Cloud provider local metadata endpoint to determine the instance ID that this code is running on. * Useful if you don't want to configure the instance ID manually. * Pass detectInstance param with a cloud provider ID (AWS|GCE) to have this run in your configuration. * * @return String containing an instance id, or null if none is found */ private String getLocalInstanceId(final String cloudProvider, final String metadataEndpoint, final Map<String,String> headers) { String detectedInstanceId = null; try { final URL metadataUrl = new URL(metadataEndpoint); URLConnection metadataConnection = metadataUrl.openConnection(); // add any additional headers passed in if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { metadataConnection.setRequestProperty(header.getKey(), header.getValue()); } } BufferedReader in = new BufferedReader(new InputStreamReader(metadataConnection.getInputStream(), "UTF-8")); String inputLine; while ((inputLine = in.readLine()) != null) { detectedInstanceId = inputLine; } in.close(); } catch (Exception e) { logger.warn("unable to determine " + cloudProvider + " instance ID", e); } return detectedInstanceId; } public String getGatewayUrl() { return gatewayUrl.toString(); } public String getProxyHost() { return proxyHost; } public Integer getProxyPort() { return proxyPort; } public String getPrefix() { return prefix; } public String getApiKey() { return apiKey; } public int getTimeoutInMillis() { return timeoutInMillis; } public String getSource() { return source; } public String getDetectInstance() { return detectInstance; } }
5,848
392
<gh_stars>100-1000 package com.platform.shiro; import com.platform.cache.J2CacheUtils; import com.platform.utils.Constant; import org.apache.shiro.session.Session; import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO; import java.io.Serializable; /** * 分布式session管理 * * @author lipengjun * @date 2018年07月31日 上午14:50 */ public class CluterShiroSessionDao extends EnterpriseCacheSessionDAO { @Override protected Serializable doCreate(Session session) { Serializable sessionId = super.doCreate(session); final String key = Constant.SESSION_KEY + sessionId.toString(); setShiroSession(key, session); return sessionId; } @Override protected Session doReadSession(Serializable sessionId) { Session session = super.doReadSession(sessionId); if (null == session) { final String key = Constant.SESSION_KEY + sessionId.toString(); session = getShiroSession(key); } return session; } @Override protected void doUpdate(Session session) { super.doUpdate(session); final String key = Constant.SESSION_KEY + session.getId().toString(); setShiroSession(key, session); } @Override protected void doDelete(Session session) { super.doDelete(session); final String key = Constant.SESSION_KEY + session.getId().toString(); J2CacheUtils.remove(key); } private Session getShiroSession(String key) { return (Session) J2CacheUtils.get(key); } private void setShiroSession(String key, Session session) { J2CacheUtils.put(key, session); } }
642
1,143
<filename>src/java/com/twitter/common/net/loadbalancing/LoadBalancerImpl.java // ================================================================================================= // Copyright 2011 Twitter, Inc. // ------------------------------------------------------------------------------------------------- // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this work except in compliance with the License. // You may obtain a copy of the License in the LICENSE file, or 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. // ================================================================================================= package com.twitter.common.net.loadbalancing; import java.util.Collection; import java.util.Set; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.twitter.common.base.Closure; import com.twitter.common.net.loadbalancing.LoadBalancingStrategy.ConnectionResult; import com.twitter.common.net.pool.ResourceExhaustedException; /** * Implementation of a load balancer, that uses a pluggable {@link LoadBalancingStrategy} to define * actual load balancing behavior. This class handles the responsibility of associating connections * with backends. * * Calls to {@link #connected(Object, long)}, * {@link #requestResult(Object, RequestResult, long)}, and {@link #released(Object)} will not * be forwarded for unknown backends/connections. * * @author <NAME> */ public class LoadBalancerImpl<K> implements LoadBalancer<K> { private final LoadBalancingStrategy<K> strategy; private Set<K> offeredBackends = ImmutableSet.of(); /** * Creates a new load balancer that will use the given strategy. * * @param strategy Strategy to delegate load balancing work to. */ public LoadBalancerImpl(LoadBalancingStrategy<K> strategy) { this.strategy = Preconditions.checkNotNull(strategy); } @Override public synchronized void offerBackends(Set<K> offeredBackends, final Closure<Collection<K>> onBackendsChosen) { this.offeredBackends = ImmutableSet.copyOf(offeredBackends); strategy.offerBackends(offeredBackends, new Closure<Collection<K>>() { @Override public void execute(Collection<K> chosenBackends) { onBackendsChosen.execute(chosenBackends); } }); } @Override public synchronized K nextBackend() throws ResourceExhaustedException { return strategy.nextBackend(); } @Override public synchronized void connected(K backend, long connectTimeNanos) { Preconditions.checkNotNull(backend); if (!hasBackend(backend)) return; strategy.addConnectResult(backend, ConnectionResult.SUCCESS, connectTimeNanos); } private boolean hasBackend(K backend) { return offeredBackends.contains(backend); } @Override public synchronized void connectFailed(K backend, ConnectionResult result) { Preconditions.checkNotNull(backend); Preconditions.checkNotNull(result); Preconditions.checkArgument(result != ConnectionResult.SUCCESS); if (!hasBackend(backend)) return; strategy.addConnectResult(backend, result, 0); } @Override public synchronized void released(K backend) { Preconditions.checkNotNull(backend); if (!hasBackend(backend)) return; strategy.connectionReturned(backend); } @Override public synchronized void requestResult(K backend, RequestResult result, long requestTimeNanos) { Preconditions.checkNotNull(backend); Preconditions.checkNotNull(result); if (!hasBackend(backend)) return; strategy.addRequestResult(backend, result, requestTimeNanos); } /** * Convenience method to create a new load balancer. * * @param strategy Strategy to use. * @param <K> Backend type. * @return A new load balancer. */ public static <K> LoadBalancerImpl<K> create(LoadBalancingStrategy<K> strategy) { return new LoadBalancerImpl<K>(strategy); } }
1,229
1,018
/* * Copyright 2014-2016 the original author or authors. * * 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. */ package org.glowroot.agent.plugin.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OperationsPerInvocation; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.glowroot.agent.plugin.jdbc.support.MockConnection; import org.glowroot.microbenchmarks.support.TransactionWorthy; @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) @State(Scope.Thread) public class ResultSetBenchmark extends TransactionWorthy { @Param private Database database; private Connection connection; private PreparedStatement preparedStatement; @Setup public void setup() throws SQLException { switch (database) { case HSQLDB: connection = DriverManager.getConnection("jdbc:hsqldb:mem:benchmark", "sa", ""); Statement statement = connection.createStatement(); try { statement.execute("create table mock (name varchar(100))"); for (int i = 0; i < 10000; i++) { statement.execute("insert into mock (name) values ('mock" + 1 + "')"); } } finally { statement.close(); } break; case MOCK: connection = new MockConnection(); break; } preparedStatement = connection.prepareStatement("select * from mock"); } @TearDown public void tearDown() throws SQLException { preparedStatement.close(); connection.close(); } @Benchmark @OperationsPerInvocation(10000) public void next() throws Exception { doSomethingTransactionWorthy(); } @Override public void doSomethingTransactionWorthy() throws SQLException { ResultSet resultSet = preparedStatement.executeQuery(); for (int i = 0; i < 10000; i++) { resultSet.next(); } resultSet.close(); } public enum Database { HSQLDB, MOCK } }
1,225
16,989
<filename>src/main/java/com/google/devtools/build/lib/sandbox/SynchronousTreeDeleter.java<gh_stars>1000+ // Copyright 2019 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // 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. package com.google.devtools.build.lib.sandbox; import com.google.devtools.build.lib.exec.TreeDeleter; import com.google.devtools.build.lib.vfs.Path; import java.io.IOException; /** Executes file system tree deletions synchronously. */ public class SynchronousTreeDeleter implements TreeDeleter { @Override public void deleteTree(Path path) throws IOException { path.deleteTree(); } @Override public void deleteTreesBelow(Path path) throws IOException { path.deleteTreesBelow(); } @Override public void shutdown() {} }
365
341
package org.myproject.ms.monitoring.instrument.web; import java.util.Map; import org.myproject.ms.monitoring.Item; import org.myproject.ms.monitoring.ItemTextMap; import org.springframework.util.StringUtils; public class ZHSInject implements HSInject { private static final String HEADER_DELIMITER = "-"; @Override public void inject(Item span, ItemTextMap carrier) { setHeader(carrier, Item.TRACE_ID_NAME, span.traceIdString()); setIdHeader(carrier, Item.SPAN_ID_NAME, span.getSpanId()); setHeader(carrier, Item.SAMPLED_NAME, span.isExportable() ? Item.SPAN_SAMPLED : Item.SPAN_NOT_SAMPLED); setHeader(carrier, Item.SPAN_NAME_NAME, span.getName()); setIdHeader(carrier, Item.PARENT_ID_NAME, getParentId(span)); setHeader(carrier, Item.PROCESS_ID_NAME, span.getProcessId()); for (Map.Entry<String, String> entry : span.baggageItems()) { carrier.put(prefixedKey(entry.getKey()), entry.getValue()); } } private String prefixedKey(String key) { if (key.startsWith(Item.SPAN_BAGGAGE_HEADER_PREFIX + HEADER_DELIMITER)) { return key; } return Item.SPAN_BAGGAGE_HEADER_PREFIX + HEADER_DELIMITER + key; } private Long getParentId(Item span) { return !span.getParents().isEmpty() ? span.getParents().get(0) : null; } private void setIdHeader(ItemTextMap carrier, String name, Long value) { if (value != null) { setHeader(carrier, name, Item.idToHex(value)); } } private void setHeader(ItemTextMap carrier, String name, String value) { if (StringUtils.hasText(value)) { carrier.put(name, value); } } }
590
2,939
<reponame>mlwilkerson/lumen #include "lumen/EIR/Conversion/ConstantOpConversions.h" namespace lumen { namespace eir { template <typename Op> static Value lowerElementValue(RewritePatternContext<Op> &ctx, Attribute elementAttr); struct NullOpConversion : public EIROpConversion<NullOp> { using EIROpConversion::EIROpConversion; LogicalResult matchAndRewrite( NullOp op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { auto ctx = getRewriteContext(op, rewriter); auto ty = ctx.typeConverter.convertType(op.getType()).cast<LLVMType>(); rewriter.replaceOpWithNewOp<LLVM::NullOp>(op, ty); return success(); } }; struct ConstantAtomOpConversion : public EIROpConversion<ConstantAtomOp> { using EIROpConversion::EIROpConversion; LogicalResult matchAndRewrite( ConstantAtomOp op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { auto ctx = getRewriteContext(op, rewriter); auto atomAttr = op.getValue().cast<AtomAttr>(); auto id = (uint64_t)atomAttr.getValue().getLimitedValue(); if (op.getType().isa<BooleanType>()) { if (id > 1) { op.emitError("invalid atom used as boolean value"); return failure(); } // Lower to i1 auto i1Ty = ctx.getI1Type(); Value val = llvm_constant(i1Ty, ctx.getIntegerAttr(id)); rewriter.replaceOp(op, {val}); } else { // Lower to termTy auto termTy = ctx.getUsizeType(); auto taggedAtom = ctx.targetInfo.encodeImmediate(TypeKind::Atom, id); Value val = llvm_constant(termTy, ctx.getIntegerAttr(taggedAtom)); rewriter.replaceOp(op, {val}); } return success(); } }; struct ConstantBoolOpConversion : public EIROpConversion<ConstantBoolOp> { using EIROpConversion::EIROpConversion; LogicalResult matchAndRewrite( ConstantBoolOp op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { auto ctx = getRewriteContext(op, rewriter); auto attr = op.getValue().cast<BoolAttr>(); auto isTrue = attr.getValue(); auto valType = op.getType(); // Can be lowered to atoms if (valType.isa<AtomType>() || valType.isa<BooleanType>()) { auto ty = ctx.getUsizeType(); auto taggedAtom = ctx.targetInfo.encodeImmediate( TypeKind::Atom, (unsigned)(isTrue)); Value val = llvm_constant(ty, ctx.getIntegerAttr(taggedAtom)); rewriter.replaceOp(op, {val}); return success(); } // Otherwise we are expecting this to be an integer type (i1 almost // always) if (valType.isInteger(1)) { auto ty = ctx.typeConverter.convertType(valType).cast<LLVMType>(); Value val = llvm_constant(ty, ctx.getIntegerAttr((unsigned)(isTrue))); rewriter.replaceOp(op, {val}); return success(); } op.emitOpError("invalid type associated with constant boolean value"); return failure(); } }; struct ConstantBigIntOpConversion : public EIROpConversion<ConstantBigIntOp> { using EIROpConversion::EIROpConversion; LogicalResult matchAndRewrite( ConstantBigIntOp op, ArrayRef<Value> _operands, ConversionPatternRewriter &rewriter) const override { auto ctx = getRewriteContext(op, rewriter); auto bigIntAttr = op.getValue().cast<APIntAttr>(); auto bigIntStr = bigIntAttr.getValueAsString(); auto termTy = ctx.getUsizeType(); auto i8Ty = ctx.getI8Type(); auto i8PtrTy = i8Ty.getPointerTo(); // Create constant string to hold bigint value auto name = bigIntAttr.getHash(); auto bytesGlobal = ctx.getOrInsertConstantString(name, bigIntStr); // Invoke the runtime function that will reify a BigInt term from the // constant string auto globalPtr = llvm_bitcast(i8PtrTy, llvm_addressof(bytesGlobal)); Value size = llvm_constant(termTy, ctx.getIntegerAttr(bigIntStr.size())); StringRef symbolName("__lumen_builtin_bigint_from_cstr"); auto callee = ctx.getOrInsertFunction(symbolName, termTy, {i8PtrTy, termTy}); auto calleeSymbol = FlatSymbolRefAttr::get(symbolName, callee->getContext()); rewriter.replaceOpWithNewOp<mlir::CallOp>( op, calleeSymbol, termTy, ArrayRef<Value>{globalPtr, size}); return success(); } }; struct ConstantBinaryOpConversion : public EIROpConversion<ConstantBinaryOp> { using EIROpConversion::EIROpConversion; LogicalResult matchAndRewrite( ConstantBinaryOp op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { auto ctx = getRewriteContext(op, rewriter); auto binAttr = op.getValue().cast<BinaryAttr>(); auto bytes = binAttr.getValue(); auto byteSize = bytes.size(); auto ty = ctx.targetInfo.getBinaryType(); auto termTy = ctx.getUsizeType(); // We use the SHA-1 hash of the value as the name of the global, // this provides a nice way to de-duplicate constant strings while // not requiring any global state auto name = binAttr.getHash(); auto bytesGlobal = ctx.getOrInsertConstantString(name, bytes); auto headerName = std::string("binary_") + name; ModuleOp mod = ctx.getModule(); LLVM::GlobalOp headerConst = mod.lookupSymbol<LLVM::GlobalOp>(headerName); if (!headerConst) { auto i64Ty = ctx.getI64Type(); auto i8Ty = ctx.getI8Type(); auto i8PtrTy = i8Ty.getPointerTo(); PatternRewriter::InsertionGuard insertGuard(rewriter); rewriter.setInsertionPointAfter(bytesGlobal); headerConst = ctx.getOrInsertGlobalConstantOp(headerName, ty); auto &initRegion = headerConst.getInitializerRegion(); auto *initBlock = rewriter.createBlock(&initRegion); auto globalPtr = llvm_addressof(bytesGlobal); Value zero = llvm_constant(i64Ty, ctx.getIntegerAttr(0)); Value headerTerm = llvm_constant(termTy, ctx.getIntegerAttr(binAttr.getHeader())); Value flags = llvm_constant(termTy, ctx.getIntegerAttr(binAttr.getFlags())); Value header = llvm_undef(ty); Value address = llvm_gep(i8PtrTy, globalPtr, ArrayRef<Value>{zero, zero}); header = llvm_insertvalue(ty, header, headerTerm, rewriter.getI64ArrayAttr(0)); header = llvm_insertvalue(ty, header, flags, rewriter.getI64ArrayAttr(1)); header = llvm_insertvalue(ty, header, address, rewriter.getI64ArrayAttr(2)); rewriter.create<LLVM::ReturnOp>(op.getLoc(), header); } // Box the constant address auto headerPtr = llvm_addressof(headerConst); auto boxed = ctx.encodeLiteral(headerPtr); rewriter.replaceOp(op, boxed); return success(); } }; // This magic constant here matches the same value in the term encoding in Rust const uint64_t MIN_DOUBLE = ~((uint64_t)(INT64_MIN >> 12)); struct ConstantFloatOpConversion : public EIROpConversion<ConstantFloatOp> { using EIROpConversion::EIROpConversion; LogicalResult matchAndRewrite( ConstantFloatOp op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { auto ctx = getRewriteContext(op, rewriter); auto attr = op.getValue().cast<APFloatAttr>(); auto apVal = attr.getValue(); auto termTy = ctx.getUsizeType(); // On nanboxed targets, floats are treated normally if (!ctx.targetInfo.requiresPackedFloats()) { auto f = apVal.bitcastToAPInt(); // The magic constant here is MIN_DOUBLE, as defined in the term // encoding in Rust auto val = llvm_constant( termTy, ctx.getIntegerAttr(f.getLimitedValue() + MIN_DOUBLE)); rewriter.replaceOp(op, {val}); return success(); } // All other targets use boxed, packed floats // This requires generating a descriptor around the float, // which can then either be placed on the heap and boxed, or // passed by value on the stack and accessed directly auto floatTy = ctx.targetInfo.getFloatType(); auto val = llvm_constant( floatTy, rewriter.getF64FloatAttr(apVal.convertToDouble())); auto headerName = std::string("float_") + std::to_string(apVal.bitcastToAPInt().getLimitedValue()); ModuleOp mod = ctx.getModule(); LLVM::GlobalOp headerConst = mod.lookupSymbol<LLVM::GlobalOp>(headerName); if (!headerConst) { auto i64Ty = ctx.getI64Type(); auto f64Ty = ctx.getDoubleType(); auto i8Ty = ctx.getI8Type(); auto i8PtrTy = i8Ty.getPointerTo(); PatternRewriter::InsertionGuard insertGuard(rewriter); rewriter.setInsertionPointToStart(mod.getBody()); headerConst = ctx.getOrInsertGlobalConstantOp(headerName, floatTy); auto &initRegion = headerConst.getInitializerRegion(); auto *initBlock = rewriter.createBlock(&initRegion); Value zero = llvm_constant(i64Ty, ctx.getIntegerAttr(0)); APInt headerTermVal = ctx.targetInfo.encodeHeader(TypeKind::Float, 2); Value headerTerm = llvm_constant( termTy, ctx.getIntegerAttr(headerTermVal.getLimitedValue())); Value floatVal = llvm_constant( f64Ty, rewriter.getF64FloatAttr(apVal.convertToDouble())); Value header = llvm_undef(floatTy); header = llvm_insertvalue(floatTy, header, headerTerm, rewriter.getI64ArrayAttr(0)); header = llvm_insertvalue(floatTy, header, floatVal, rewriter.getI64ArrayAttr(1)); rewriter.create<LLVM::ReturnOp>(op.getLoc(), header); } // Box the constant address auto headerPtr = llvm_addressof(headerConst); auto boxed = ctx.encodeLiteral(headerPtr); rewriter.replaceOp(op, boxed); return success(); } }; struct ConstantIntOpConversion : public EIROpConversion<ConstantIntOp> { using EIROpConversion::EIROpConversion; LogicalResult matchAndRewrite( ConstantIntOp op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { auto ctx = getRewriteContext(op, rewriter); auto attr = op.getValue().cast<APIntAttr>(); auto termTy = ctx.getUsizeType(); auto value = attr.getValue(); if (ctx.targetInfo.isValidImmediateValue(value)) { auto taggedInt = ctx.targetInfo.encodeImmediate( TypeKind::Fixnum, value.getLimitedValue()); auto val = llvm_constant(termTy, ctx.getIntegerAttr(taggedInt)); rewriter.replaceOp(op, {val}); } else { // Too large for an immediate, promote to bigint rewriter.replaceOpWithNewOp<ConstantBigIntOp>(op, value); } return success(); } }; struct ConstantNilOpConversion : public EIROpConversion<ConstantNilOp> { using EIROpConversion::EIROpConversion; LogicalResult matchAndRewrite( ConstantNilOp op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { auto ctx = getRewriteContext(op, rewriter); auto termTy = ctx.getUsizeType(); auto val = llvm_constant( termTy, ctx.getIntegerAttr(ctx.targetInfo.getNilValue())); rewriter.replaceOp(op, {val}); return success(); } }; struct ConstantNoneOpConversion : public EIROpConversion<ConstantNoneOp> { using EIROpConversion::EIROpConversion; LogicalResult matchAndRewrite( ConstantNoneOp op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { auto ctx = getRewriteContext(op, rewriter); auto termTy = ctx.getUsizeType(); auto val = llvm_constant( termTy, ctx.getIntegerAttr(ctx.targetInfo.getNoneValue())); rewriter.replaceOp(op, {val}); return success(); } }; struct ConstantListOpConversion : public EIROpConversion<ConstantListOp> { using EIROpConversion::EIROpConversion; LogicalResult matchAndRewrite( ConstantListOp op, ArrayRef<mlir::Value> operands, ConversionPatternRewriter &rewriter) const override { auto ctx = getRewriteContext(op, rewriter); auto attr = op.getValue().cast<SeqAttr>(); auto elements = attr.getValue(); auto numElements = elements.size(); if (numElements == 0) { Value nil = eir_nil(); rewriter.replaceOp(op, nil); return success(); } SmallVector<Value, 4> elementValues; for (auto element : elements) { Value elementVal = lowerElementValue(ctx, element); assert(elementVal && "unsupported element type in cons cell"); elementValues.push_back(elementVal); } rewriter.replaceOpWithNewOp<ListOp>(op, elementValues); return success(); } }; struct ConstantMapOpConversion : public EIROpConversion<ConstantMapOp> { using EIROpConversion::EIROpConversion; LogicalResult matchAndRewrite( ConstantMapOp op, ArrayRef<Value> _operands, ConversionPatternRewriter &rewriter) const override { auto ctx = getRewriteContext(op, rewriter); auto termTy = ctx.getUsizeType(); auto attr = op.getValue().cast<SeqAttr>(); auto elementAttrs = attr.getValue(); SmallVector<Value, 2> elements; for (auto elementAttr : elementAttrs) { auto element = lowerElementValue(ctx, elementAttr); assert(element && "unsupported element type in map"); elements.push_back(element); } MapOp newMap = eir_map(elements); rewriter.replaceOp(op, newMap.out()); return success(); } }; struct ConstantTupleOpConversion : public EIROpConversion<ConstantTupleOp> { using EIROpConversion::EIROpConversion; LogicalResult matchAndRewrite( ConstantTupleOp op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { auto ctx = getRewriteContext(op, rewriter); auto termTy = ctx.getUsizeType(); auto attr = op.getValue().cast<SeqAttr>(); auto elementAttrs = attr.getValue(); SmallVector<Value, 2> elements; for (auto elementAttr : elementAttrs) { auto element = lowerElementValue(ctx, elementAttr); assert(element && "unsupported element type in tuple"); elements.push_back(element); } Value tuple = eir_tuple(elements); rewriter.replaceOp(op, tuple); return success(); } }; template <typename Op> static Value lowerElementValue(RewritePatternContext<Op> &ctx, Attribute elementAttr) { auto termTy = ctx.getUsizeType(); auto eirTermType = ctx.rewriter.template getType<TermType>(); // Symbols if (auto symAttr = elementAttr.dyn_cast_or_null<FlatSymbolRefAttr>()) { ModuleOp mod = ctx.getModule(); Operation *referencedOp = SymbolTable::lookupNearestSymbolFrom(mod, symAttr); auto symName = symAttr.getValue(); // Symbol must be a global reference, with a name that contains the type // of global constant if (auto global = dyn_cast_or_null<LLVM::GlobalOp>(referencedOp)) { auto ptr = llvm_addressof(global); // Check name prefix, if we are able to in the future, I'd prefer // this to dispatch on type information, but the current APIs are // insufficient (and we don't have access to the original EIR type // here) if (symName.startswith("binary_")) { return ctx.encodeLiteral(ptr); } if (symName.startswith("float_")) { return ctx.encodeLiteral(ptr); } if (symName.startswith("closure_")) { return ctx.encodeLiteral(ptr); } } return nullptr; } // None/Nil if (auto typeAttr = elementAttr.dyn_cast_or_null<TypeAttr>()) { auto type = typeAttr.getValue(); if (type.isa<NilType>()) { return eir_cast(eir_nil(), eirTermType); } if (type.isa<NoneType>()) { return eir_cast(eir_none(), eirTermType); } return nullptr; } // Booleans if (auto boolAttr = elementAttr.dyn_cast_or_null<BoolAttr>()) { auto b = boolAttr.getValue(); uint64_t id = b ? 1 : 0; auto tagged = ctx.targetInfo.encodeImmediate(TypeKind::Atom, id); return llvm_constant(termTy, ctx.getIntegerAttr(tagged)); } // Atoms if (auto atomAttr = elementAttr.dyn_cast_or_null<AtomAttr>()) { auto id = atomAttr.getValue().getLimitedValue(); auto tagged = ctx.targetInfo.encodeImmediate(TypeKind::Atom, id); return llvm_constant(termTy, ctx.getIntegerAttr(tagged)); } // Integers if (auto intAttr = elementAttr.dyn_cast_or_null<APIntAttr>()) { auto i = intAttr.getValue(); assert(i.getBitWidth() <= ctx.targetInfo.pointerSizeInBits && "support for bigint in constant aggregates not yet implemented"); auto tagged = ctx.targetInfo.encodeImmediate(TypeKind::Fixnum, i.getLimitedValue()); return llvm_constant(termTy, ctx.getIntegerAttr(tagged)); } if (auto intAttr = elementAttr.dyn_cast_or_null<IntegerAttr>()) { auto i = intAttr.getValue(); assert(i.getBitWidth() <= ctx.targetInfo.pointerSizeInBits && "support for bigint in constant aggregates not yet implemented"); auto tagged = ctx.targetInfo.encodeImmediate(TypeKind::Fixnum, i.getLimitedValue()); return llvm_constant(termTy, ctx.getIntegerAttr(tagged)); } // Floats if (auto floatAttr = elementAttr.dyn_cast_or_null<APFloatAttr>()) { if (!ctx.targetInfo.requiresPackedFloats()) { auto f = floatAttr.getValue().bitcastToAPInt() + MIN_DOUBLE; return llvm_constant(termTy, ctx.getIntegerAttr(f.getLimitedValue())); } // Packed float return eir_cast(eir_constant_float(floatAttr.getValue()), eirTermType); } if (auto floatAttr = elementAttr.dyn_cast_or_null<mlir::FloatAttr>()) { if (!ctx.targetInfo.requiresPackedFloats()) { auto f = floatAttr.getValue().bitcastToAPInt() + MIN_DOUBLE; return llvm_constant(termTy, ctx.getIntegerAttr(f.getLimitedValue())); } // Packed float return eir_cast(eir_constant_float(floatAttr.getValue()), eirTermType); } // Binaries if (auto binAttr = elementAttr.dyn_cast_or_null<BinaryAttr>()) { auto type = ctx.rewriter.template getType<BinaryType>(); return eir_cast(eir_constant_binary(type, binAttr), eirTermType); } // Nested aggregates if (auto aggAttr = elementAttr.dyn_cast_or_null<SeqAttr>()) { auto elementAttrs = aggAttr.getValue(); // Tuples if (auto tupleTy = aggAttr.getType().dyn_cast_or_null<TupleType>()) { SmallVector<Value, 2> elements; for (auto elementAttr : elementAttrs) { auto element = lowerElementValue(ctx, elementAttr); assert(element && "unsupported element type in tuple"); elements.push_back(element); } return eir_cast(eir_tuple(elements), eirTermType); } // Lists if (auto consTy = aggAttr.getType().dyn_cast_or_null<ConsType>()) { auto numElements = elementAttrs.size(); if (numElements == 0) { return eir_cast(eir_nil(), eirTermType); } // Lower to single cons cell if it fits if (numElements < 2) { Value head = lowerElementValue(ctx, elementAttrs[0]); assert(head && "unsupported element type in cons cell"); return eir_cast(eir_cons(head, eir_nil()), eirTermType); } unsigned cellsRequired = numElements; unsigned currentIndex = numElements; Value list; while (currentIndex > 0) { if (!list) { Value tail = lowerElementValue(ctx, elementAttrs[--currentIndex]); assert(tail && "unsupported element type in cons cell"); Value head = lowerElementValue(ctx, elementAttrs[--currentIndex]); assert(head && "unsupported element type in cons cell"); list = eir_cons(head, tail); } else { Value head = lowerElementValue(ctx, elementAttrs[--currentIndex]); assert(head && "unsupported element type in cons cell"); list = eir_cons(head, list); } } return eir_cast(list, eirTermType); } } return nullptr; } void populateConstantOpConversionPatterns(OwningRewritePatternList &patterns, MLIRContext *context, EirTypeConverter &converter, TargetInfo &targetInfo) { patterns.insert<ConstantAtomOpConversion, ConstantBoolOpConversion, ConstantBigIntOpConversion, ConstantBinaryOpConversion, ConstantFloatOpConversion, ConstantIntOpConversion, ConstantListOpConversion, ConstantMapOpConversion, ConstantNilOpConversion, ConstantNoneOpConversion, ConstantTupleOpConversion, NullOpConversion>( context, converter, targetInfo); } } // namespace eir } // namespace lumen
10,381
1,256
<gh_stars>1000+ #ifndef __FTP_NOTIFY_INTERNAL #define __FTP_NOTIFY_INTERNAL #include "fstdlib.h" //FAR plugin stdlib #include "../Plugin.h" #endif
78
764
<reponame>641589523/token-profile<gh_stars>100-1000 {"symbol": "DEV","address": "0x5cAf454Ba92e6F2c929DF14667Ee360eD9fD5b26","overview":{"en": ""},"email": "<EMAIL>","website": "https://devprtcl.com/","state": "NORMAL","links": {"blog": "https://medium.com/devprtcl","twitter": "https://twitter.com/devprtcl","telegram": "https://t.me/devprtcl","github": "https://github.com/dev-protocol/protocol"}}
160