answer
stringlengths
15
1.25M
#ifndef __MPFR_IMPL_H__ #define __MPFR_IMPL_H__ /* Let's include some standard headers unconditionally as they are already needed by several source files or when some options are enabled/disabled, and it is easy to forget them (some configure options may hide the error). Note: If some source file must not have such a header included (which is very unlikely and probably means something broken in this source file), we should do that with some macro (that would also force to disable incompatible features). */ #if defined (__cplusplus) #include <cstdio> #include <cstring> #else #include <stdio.h> #include <string.h> #endif #include <limits.h> #if _MPFR_EXP_FORMAT == 4 /* mpfr_exp_t will be defined as intmax_t */ # include "mpfr-intmax.h" #endif /* Check if we are inside a build of MPFR or inside the test suite. This is needed in mpfr.h to export or import the functions. It matters only for Windows DLL */ #ifndef __MPFR_TEST_H__ # define __MPFR_WITHIN_MPFR 1 #endif /* Include 'config.h' before using ANY configure macros if needed NOTE: It isn't MPFR 'config.h', but GMP's one! */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #ifdef MPFR_HAVE_GMP_IMPL /* Build with gmp internals*/ # ifndef __GMP_H__ # include "gmp.h" # endif # ifndef __GMP_IMPL_H__ # include "gmp-impl.h" # endif # ifdef <API key> # include "longlong.h" # endif # ifndef __MPFR_H # include "mpfr.h" # endif #else /* Build without gmp internals */ # ifndef __GMP_H__ # include "gmp.h" # endif # ifndef __MPFR_H # include "mpfr.h" # endif # ifndef __GMPFR_GMP_H__ # include "mpfr-gmp.h" # endif # ifdef <API key> # define LONGLONG_STANDALONE # include "mpfr-longlong.h" # endif #endif #undef <API key> /* If a mpn_sqr_n macro is not defined, use mpn_mul. GMP 4.x defines a mpn_sqr_n macro in gmp-impl.h (and this macro disappeared in GMP 5), so that GMP's macro can only be used when MPFR has been configured with --with-gmp-build (and only with GMP 4.x). */ #ifndef mpn_sqr_n # define mpn_sqr_n(dst,src,n) mpn_mul((dst),(src),(n),(src),(n)) #endif /* For the definition of MPFR_THREAD_ATTR. GCC/ICC detection macros are no longer used, as they sometimes gave incorrect information about the support of thread-local variables. A configure check is now done. If the use of detection macros is needed in the future, this could be moved below (after the detection macros are defined). */ #include "mpfr-thread.h" /* Macros to detect STDC, GCC, GLIBC, GMP and ICC version */ #if defined(__STDC_VERSION__) # define __MPFR_STDC(version) (__STDC_VERSION__>=(version)) #elif defined(__STDC__) # define __MPFR_STDC(version) (0 == (version)) #else # define __MPFR_STDC(version) 0 #endif #if defined(_WIN32) # define __MPFR_ICC(a,b,c) 0 #elif defined(__ICC) #elif defined(__INTEL_COMPILER) #else # define __MPFR_ICC(a,b,c) 0 #endif #if defined(__GNUC__) && defined(__GNUC_MINOR__) && ! __MPFR_ICC(0,0,0) # define __MPFR_GNUC(a,i) \ (MPFR_VERSION_NUM(__GNUC__,__GNUC_MINOR__,0) >= MPFR_VERSION_NUM(a,i,0)) #else # define __MPFR_GNUC(a,i) 0 #endif #if defined(__GLIBC__) && defined(__GLIBC_MINOR__) # define __MPFR_GLIBC(a,i) \ (MPFR_VERSION_NUM(__GLIBC__,__GLIBC_MINOR__,0) >= MPFR_VERSION_NUM(a,i,0)) #else # define __MPFR_GLIBC(a,i) 0 #endif #if defined(__GNU_MP_VERSION) && \ defined(<API key>) && \ defined(<API key>) # define __MPFR_GMP(a,b,c) \ (MPFR_VERSION_NUM(__GNU_MP_VERSION,<API key>,<API key>) >= MPFR_VERSION_NUM(a,b,c)) #else # define __MPFR_GMP(a,b,c) 0 #endif typedef mp_limb_t *mpfr_limb_ptr; typedef __gmp_const mp_limb_t *mpfr_limb_srcptr; #ifdef <API key> # ifdef <API key> # define MPFR_UINTMAX_MAX UINTMAX_MAX # define MPFR_INTMAX_MAX INTMAX_MAX # define MPFR_INTMAX_MIN INTMAX_MIN # else # define MPFR_UINTMAX_MAX ((uintmax_t) -1) # define MPFR_INTMAX_MAX ((intmax_t) (MPFR_UINTMAX_MAX >> 1)) # define MPFR_INTMAX_MIN (INT_MIN + INT_MAX - MPFR_INTMAX_MAX) # endif #endif #if !__MPFR_GMP(4,1,0) # error "GMP 4.1.0 or newer needed" #endif #if GMP_NAIL_BITS != 0 # error "MPFR doesn't support nonzero values of GMP_NAIL_BITS" #endif #if (GMP_NUMB_BITS<32) || (GMP_NUMB_BITS & (GMP_NUMB_BITS - 1)) # error "GMP_NUMB_BITS must be a power of 2, and >= 32" #endif #if GMP_NUMB_BITS == 16 # define <API key> 4 #elif GMP_NUMB_BITS == 32 # define <API key> 5 #elif GMP_NUMB_BITS == 64 # define <API key> 6 #elif GMP_NUMB_BITS == 128 # define <API key> 7 #elif GMP_NUMB_BITS == 256 # define <API key> 8 #else # error "Can't compute log2(GMP_NUMB_BITS)" #endif #if __MPFR_GNUC(3,0) || __MPFR_ICC(8,1,0) # define MPFR_NORETURN_ATTR __attribute__ ((noreturn)) # define MPFR_CONST_ATTR __attribute__ ((const)) #else # define MPFR_NORETURN_ATTR # define MPFR_CONST_ATTR #endif /* Cache struct */ struct __gmpfr_cache_s { mpfr_t x; int inexact; int (*func)(mpfr_ptr, mpfr_rnd_t); }; typedef struct __gmpfr_cache_s mpfr_cache_t[1]; typedef struct __gmpfr_cache_s *mpfr_cache_ptr; #if defined (__cplusplus) extern "C" { #endif __MPFR_DECLSPEC extern MPFR_THREAD_ATTR unsigned int __gmpfr_flags; __MPFR_DECLSPEC extern MPFR_THREAD_ATTR mpfr_exp_t __gmpfr_emin; __MPFR_DECLSPEC extern MPFR_THREAD_ATTR mpfr_exp_t __gmpfr_emax; __MPFR_DECLSPEC extern MPFR_THREAD_ATTR mpfr_prec_t <API key>; __MPFR_DECLSPEC extern MPFR_THREAD_ATTR mpfr_rnd_t <API key>; __MPFR_DECLSPEC extern MPFR_THREAD_ATTR mpfr_cache_t <API key>; __MPFR_DECLSPEC extern MPFR_THREAD_ATTR mpfr_cache_t <API key>; #ifndef MPFR_USE_LOGGING __MPFR_DECLSPEC extern MPFR_THREAD_ATTR mpfr_cache_t <API key>; __MPFR_DECLSPEC extern MPFR_THREAD_ATTR mpfr_cache_t <API key>; #else /* Two constants are used by the logging functions (via mpfr_fprintf, then mpfr_log, for the base conversion): pi and log(2). Since the mpfr_cache function isn't re-entrant when working on the same cache, we need to define two caches for each constant. */ __MPFR_DECLSPEC extern MPFR_THREAD_ATTR mpfr_cache_t __gmpfr_normal_pi; __MPFR_DECLSPEC extern MPFR_THREAD_ATTR mpfr_cache_t __gmpfr_normal_log2; __MPFR_DECLSPEC extern MPFR_THREAD_ATTR mpfr_cache_t __gmpfr_logging_pi; __MPFR_DECLSPEC extern MPFR_THREAD_ATTR mpfr_cache_t <API key>; __MPFR_DECLSPEC extern MPFR_THREAD_ATTR mpfr_cache_ptr <API key>; __MPFR_DECLSPEC extern MPFR_THREAD_ATTR mpfr_cache_ptr <API key>; #endif #define BASE_MAX 62 __MPFR_DECLSPEC extern const __mpfr_struct __gmpfr_l2b[BASE_MAX-1][2]; /* Note: do not use the following values when they can be outside the current exponent range, e.g. when the exponent range has not been extended yet; under such a condition, they can be used only in mpfr_cmpabs. */ __MPFR_DECLSPEC extern const mpfr_t __gmpfr_one; __MPFR_DECLSPEC extern const mpfr_t __gmpfr_two; __MPFR_DECLSPEC extern const mpfr_t __gmpfr_four; #if defined (__cplusplus) } #endif /* Flags of __gmpfr_flags */ #define <API key> 1 #define MPFR_FLAGS_OVERFLOW 2 #define MPFR_FLAGS_NAN 4 #define MPFR_FLAGS_INEXACT 8 #define MPFR_FLAGS_ERANGE 16 #define MPFR_FLAGS_DIVBY0 32 #define MPFR_FLAGS_ALL 63 /* Replace some common functions for direct access to the global vars */ #define mpfr_get_emin() (__gmpfr_emin + 0) #define mpfr_get_emax() (__gmpfr_emax + 0) #define <API key>() (<API key> + 0) #define <API key>() (<API key> + 0) #define mpfr_clear_flags() \ ((void) (__gmpfr_flags = 0)) #define <API key>() \ ((void) (__gmpfr_flags &= MPFR_FLAGS_ALL ^ <API key>)) #define mpfr_clear_overflow() \ ((void) (__gmpfr_flags &= MPFR_FLAGS_ALL ^ MPFR_FLAGS_OVERFLOW)) #define mpfr_clear_nanflag() \ ((void) (__gmpfr_flags &= MPFR_FLAGS_ALL ^ MPFR_FLAGS_NAN)) #define mpfr_clear_inexflag() \ ((void) (__gmpfr_flags &= MPFR_FLAGS_ALL ^ MPFR_FLAGS_INEXACT)) #define <API key>() \ ((void) (__gmpfr_flags &= MPFR_FLAGS_ALL ^ MPFR_FLAGS_ERANGE)) #define mpfr_clear_divby0() \ ((void) (__gmpfr_flags &= MPFR_FLAGS_ALL ^ MPFR_FLAGS_DIVBY0)) #define mpfr_underflow_p() \ ((int) (__gmpfr_flags & <API key>)) #define mpfr_overflow_p() \ ((int) (__gmpfr_flags & MPFR_FLAGS_OVERFLOW)) #define mpfr_nanflag_p() \ ((int) (__gmpfr_flags & MPFR_FLAGS_NAN)) #define mpfr_inexflag_p() \ ((int) (__gmpfr_flags & MPFR_FLAGS_INEXACT)) #define mpfr_erangeflag_p() \ ((int) (__gmpfr_flags & MPFR_FLAGS_ERANGE)) #define mpfr_divby0_p() \ ((int) (__gmpfr_flags & MPFR_FLAGS_DIVBY0)) #define MPFR_BLOCK_DECL(_flags) unsigned int _flags /* The (void) (_flags) makes sure that _flags is read at least once (it makes sense to use MPFR_BLOCK while _flags will never be read in the source, so that we wish to avoid the corresponding warning). */ #define MPFR_BLOCK(_flags,_op) \ do \ { \ mpfr_clear_flags (); \ _op; \ (_flags) = __gmpfr_flags; \ (void) (_flags); \ } \ while (0) #define MPFR_BLOCK_TEST(_flags,_f) MPFR_UNLIKELY ((_flags) & (_f)) #define MPFR_BLOCK_EXCEP (__gmpfr_flags & (<API key> | \ MPFR_FLAGS_OVERFLOW | \ MPFR_FLAGS_DIVBY0 | \ MPFR_FLAGS_NAN)) /* Let's use a MPFR_ prefix, because e.g. OVERFLOW is defined by glibc's math.h, though this is not a reserved identifier! */ #define MPFR_UNDERFLOW(_flags) MPFR_BLOCK_TEST (_flags, <API key>) #define MPFR_OVERFLOW(_flags) MPFR_BLOCK_TEST (_flags, MPFR_FLAGS_OVERFLOW) #define MPFR_NANFLAG(_flags) MPFR_BLOCK_TEST (_flags, MPFR_FLAGS_NAN) #define MPFR_INEXFLAG(_flags) MPFR_BLOCK_TEST (_flags, MPFR_FLAGS_INEXACT) #define MPFR_ERANGEFLAG(_flags) MPFR_BLOCK_TEST (_flags, MPFR_FLAGS_ERANGE) #define MPFR_DIVBY0(_flags) MPFR_BLOCK_TEST (_flags, MPFR_FLAGS_DIVBY0) /* Compile with -DWANT_ASSERT to check all assert statements */ /* Note: do not use GMP macros ASSERT_ALWAYS and ASSERT as they are not expressions, and as a consequence, they cannot be used in a for(), with a comma operator and so on. */ /* MPFR_ASSERTN(expr): assertions that should always be checked */ #define MPFR_ASSERTN(expr) \ ((void) ((MPFR_UNLIKELY(expr)) || MPFR_UNLIKELY( (ASSERT_FAIL(expr),0) ))) /* MPFR_ASSERTD(expr): assertions that should be checked when testing */ #ifdef WANT_ASSERT # define MPFR_EXP_CHECK 1 # define MPFR_ASSERTD(expr) MPFR_ASSERTN (expr) #else # define MPFR_ASSERTD(expr) ((void) 0) #endif /* Code to deal with impossible WARNING: It doesn't use do { } while (0) for Insure++*/ #define <API key>() {MPFR_ASSERTN(0); return 0;} /* MPFR_WARNING is no longer useful, but let's keep the macro in case it needs to be used again in the future. */ #ifdef MPFR_USE_WARNINGS # include <stdlib.h> # define MPFR_WARNING(W) \ do \ { \ char *q = getenv ("MPFR_QUIET"); \ if (q == NULL || *q == 0) \ fprintf (stderr, "MPFR: %s\n", W); \ } \ while (0) #else # define MPFR_WARNING(W) ((void) 0) #endif /* Precision used for lower precision computations */ #define <API key> 32 /* Definition of constants */ #define LOG2 0.<API key> /* log(2) rounded to zero on 53 bits */ #define ALPHA 4.3191365662914471407 /* a+2 = a*log(a), rounded to +infinity */ #define EXPM1 0.<API key> /* exp(-1), rounded to zero */ /* MPFR_DOUBLE_SPEC = 1 if the C type 'double' corresponds to IEEE-754 double precision, 0 if it doesn't, and undefined if one doesn't know. On all the tested machines, MPFR_DOUBLE_SPEC = 1. To have this macro defined here, #include <float.h> is needed. If need be, other values could be defined for other specs (once they are known). */ #if !defined(MPFR_DOUBLE_SPEC) && defined(FLT_RADIX) && \ defined(DBL_MANT_DIG) && defined(DBL_MIN_EXP) && defined(DBL_MAX_EXP) # if FLT_RADIX == 2 && DBL_MANT_DIG == 53 && \ DBL_MIN_EXP == -1021 && DBL_MAX_EXP == 1024 # define MPFR_DOUBLE_SPEC 1 # else # define MPFR_DOUBLE_SPEC 0 # endif #endif /* Debug non IEEE floats */ #ifdef XDEBUG # undef _GMP_IEEE_FLOATS #endif #ifndef _GMP_IEEE_FLOATS # define _GMP_IEEE_FLOATS 0 #endif #ifndef IEEE_DBL_MANT_DIG #define IEEE_DBL_MANT_DIG 53 #endif #define <API key> ((IEEE_DBL_MANT_DIG-1)/GMP_NUMB_BITS+1) #ifndef IEEE_FLT_MANT_DIG #define IEEE_FLT_MANT_DIG 24 #endif #define MPFR_LIMBS_PER_FLT ((IEEE_FLT_MANT_DIG-1)/GMP_NUMB_BITS+1) /* Visual C++ doesn't support +1.0/0.0, -1.0/0.0 and 0.0/0.0 at compile time. */ #if defined(_MSC_VER) && defined(_WIN32) && (_MSC_VER >= 1200) static double double_zero = 0.0; # define DBL_NAN (double_zero/double_zero) # define DBL_POS_INF ((double) 1.0/double_zero) # define DBL_NEG_INF ((double)-1.0/double_zero) # define DBL_NEG_ZERO (-double_zero) #else # define DBL_POS_INF ((double) 1.0/0.0) # define DBL_NEG_INF ((double)-1.0/0.0) # define DBL_NAN ((double) 0.0/0.0) # define DBL_NEG_ZERO (-0.0) #endif /* Note: In the past, there was specific code for _GMP_IEEE_FLOATS, which was based on NaN and Inf memory representations. This code was breaking the aliasing rules (see ISO C99, 6.5#6 and 6.5#7 on the effective type) and for this reason it did not behave correctly with GCC 4.5.0 20091119. The code needed a memory transfer and was probably not better than the macros below with a good compiler (a fix based on the NaN / Inf memory representation would be even worse due to C limitations), and this code could be selected only when MPFR was built with --with-gmp-build, thus introducing a difference (bad for maintaining/testing MPFR); therefore it has been removed. The old code required that the argument x be an lvalue of type double. We still require that, in case one would need to change the macros below, e.g. for some broken compiler. But the LVALUE(x) condition could be removed if really necessary. */ /* Below, the &(x) == &(x) || &(x) != &(x) allows to make sure that x is a lvalue without (probably) any warning from the compiler. The &(x) != &(x) is needed to avoid a failure under Mac OS X 10.4.11 (with Xcode 2.4.1, i.e. the latest one). */ #define LVALUE(x) (&(x) == &(x) || &(x) != &(x)) #define DOUBLE_ISINF(x) (LVALUE(x) && ((x) > DBL_MAX || (x) < -DBL_MAX)) #ifdef MPFR_NANISNAN /* Avoid MIPSpro / IRIX64 / gcc -ffast-math (incorrect) optimizations. The + must not be replaced by a ||. With gcc -ffast-math, NaN is regarded as a positive number or something like that; the second test catches this case. */ # define DOUBLE_ISNAN(x) \ (LVALUE(x) && !((((x) >= 0.0) + ((x) <= 0.0)) && -(x)*(x) <= 0.0)) #else # define DOUBLE_ISNAN(x) (LVALUE(x) && (x) != (x)) #endif /* We try to get the exact value of the precision of long double (provided by the implementation) in order to provide correct rounding in this case (not guaranteed if the C implementation does not have an adequate long double arithmetic). Note that it may be lower than the precision of some numbers that can be represented in a long double; e.g. on FreeBSD/x86, it is 53 because the processor is configured to round in double precision (even when using the long double type -- this is a limitation of the x87 arithmetic), and on Mac OS X, it is 106 because the implementation is a double-double arithmetic. Otherwise (e.g. in base 10), we get an upper bound of the precision, and correct rounding isn't currently provided. */ #if defined(LDBL_MANT_DIG) && FLT_RADIX == 2 # define MPFR_LDBL_MANT_DIG LDBL_MANT_DIG #else # define MPFR_LDBL_MANT_DIG \ (sizeof(long double)*GMP_NUMB_BITS/sizeof(mp_limb_t)) #endif #define <API key> \ ((sizeof(long double)-1)/sizeof(mp_limb_t)+1) /* <API key> executes the code "action" if x is a NaN. */ /* On hppa2.0n-hp-hpux10 with the unbundled HP cc, the test x!=x on a NaN has been seen false, meaning NaNs are not detected. This seemed to happen only after other comparisons, not sure what's really going on. In any case we can pick apart the bytes to identify a NaN. */ #ifdef <API key> # define <API key>(x, action) \ do { \ union { \ long double ld; \ struct { \ unsigned int sign : 1; \ unsigned int exp : 15; \ unsigned int man3 : 16; \ unsigned int man2 : 32; \ unsigned int man1 : 32; \ unsigned int man0 : 32; \ } s; \ } u; \ u.ld = (x); \ if (u.s.exp == 0x7FFFL \ && (u.s.man0 | u.s.man1 | u.s.man2 | u.s.man3) != 0) \ { action; } \ } while (0) #endif #ifdef <API key> # define <API key>(x, action) \ do { \ union { \ long double ld; \ struct { \ unsigned int man0 : 32; \ unsigned int man1 : 32; \ unsigned int man2 : 32; \ unsigned int man3 : 16; \ unsigned int exp : 15; \ unsigned int sign : 1; \ } s; \ } u; \ u.ld = (x); \ if (u.s.exp == 0x7FFFL \ && (u.s.man0 | u.s.man1 | u.s.man2 | u.s.man3) != 0) \ { action; } \ } while (0) #endif /* Under IEEE rules, NaN is not equal to anything, including itself. "volatile" here stops "cc" on mips64-sgi-irix6.5 from optimizing away x!=x. */ #ifndef <API key> # define <API key>(x, action) \ do { \ volatile long double __x = LONGDOUBLE_VOLATILE (x); \ if ((x) != __x) \ { action; } \ } while (0) # define <API key> 1 #endif /* If we don't have a proper "volatile" then volatile is #defined to empty, in this case call through an external function to stop the compiler optimizing anything. */ #ifdef <API key> # ifdef volatile __MPFR_DECLSPEC long double <API key> _MPFR_PROTO ((long double)) MPFR_CONST_ATTR; # define LONGDOUBLE_VOLATILE(x) (<API key> (x)) # define <API key> 1 # else # define LONGDOUBLE_VOLATILE(x) (x) # endif #endif /* Some special case for IEEE_EXT Litle Endian */ #if <API key> typedef union { long double ld; struct { unsigned int manl : 32; unsigned int manh : 32; unsigned int expl : 8 ; unsigned int exph : 7; unsigned int sign : 1; } s; } mpfr_long_double_t; /* #undef MPFR_LDBL_MANT_DIG */ #undef <API key> /* #define MPFR_LDBL_MANT_DIG 64 */ #define <API key> ((64-1)/GMP_NUMB_BITS+1) #endif #ifdef <API key> /* to cast between binary64 and decimal64 */ union <API key> { double d; _Decimal64 d64; }; #endif #define MPFR_PREC(x) ((x)->_mpfr_prec) #define MPFR_EXP(x) ((x)->_mpfr_exp) #define MPFR_MANT(x) ((x)->_mpfr_d) #define MPFR_LIMB_SIZE(x) ((MPFR_PREC((x))-1)/GMP_NUMB_BITS+1) /* Limits of the mpfr_exp_t type (NOT those of valid exponent values). These macros can be used in preprocessor directives. */ #if _MPFR_EXP_FORMAT == 1 # define MPFR_EXP_MAX (SHRT_MAX) # define MPFR_EXP_MIN (SHRT_MIN) #elif _MPFR_EXP_FORMAT == 2 # define MPFR_EXP_MAX (INT_MAX) # define MPFR_EXP_MIN (INT_MIN) #elif _MPFR_EXP_FORMAT == 3 # define MPFR_EXP_MAX (LONG_MAX) # define MPFR_EXP_MIN (LONG_MIN) #elif _MPFR_EXP_FORMAT == 4 # define MPFR_EXP_MAX (MPFR_INTMAX_MAX) # define MPFR_EXP_MIN (MPFR_INTMAX_MIN) #else # error "Invalid MPFR Exp format" #endif /* Before doing a cast to mpfr_uexp_t, make sure that the value is nonnegative. */ #define MPFR_UEXP(X) (MPFR_ASSERTD ((X) >= 0), (mpfr_uexp_t) (X)) #if MPFR_EXP_MIN >= LONG_MIN && MPFR_EXP_MAX <= LONG_MAX typedef long int mpfr_eexp_t; # define mpfr_get_exp_t(x,r) mpfr_get_si((x),(r)) # define mpfr_set_exp_t(x,e,r) mpfr_set_si((x),(e),(r)) # define MPFR_EXP_FSPEC "l" #elif defined (<API key>) typedef intmax_t mpfr_eexp_t; # define mpfr_get_exp_t(x,r) mpfr_get_sj((x),(r)) # define mpfr_set_exp_t(x,e,r) mpfr_set_sj((x),(e),(r)) # define MPFR_EXP_FSPEC "j" #else # error "Cannot define mpfr_get_exp_t and mpfr_set_exp_t" #endif /* Invalid exponent value (to track bugs...) */ #define MPFR_EXP_INVALID \ ((mpfr_exp_t) 1 << (GMP_NUMB_BITS*sizeof(mpfr_exp_t)/sizeof(mp_limb_t)-2)) /* Definition of the exponent limits for MPFR numbers. * These limits are chosen so that if e is such an exponent, then 2e-1 and * 2e+1 are representable. This is useful for intermediate computations, * in particular the multiplication. */ #undef MPFR_EMIN_MIN #undef MPFR_EMIN_MAX #undef MPFR_EMAX_MIN #undef MPFR_EMAX_MAX #define MPFR_EMIN_MIN (1-MPFR_EXP_INVALID) #define MPFR_EMIN_MAX (MPFR_EXP_INVALID-1) #define MPFR_EMAX_MIN (1-MPFR_EXP_INVALID) #define MPFR_EMAX_MAX (MPFR_EXP_INVALID-1) /* Use MPFR_GET_EXP and MPFR_SET_EXP instead of MPFR_EXP directly, unless when the exponent may be out-of-range, for instance when setting the exponent before calling mpfr_check_range. MPFR_EXP_CHECK is defined when WANT_ASSERT is defined, but if you don't use WANT_ASSERT (for speed reasons), you can still define MPFR_EXP_CHECK by setting -DMPFR_EXP_CHECK in $CFLAGS. */ #ifdef MPFR_EXP_CHECK # define MPFR_GET_EXP(x) (mpfr_get_exp) (x) # define MPFR_SET_EXP(x, exp) MPFR_ASSERTN (!mpfr_set_exp ((x), (exp))) # define <API key>(x) ((void) (MPFR_EXP (x) = MPFR_EXP_INVALID)) #else # define MPFR_GET_EXP(x) MPFR_EXP (x) # define MPFR_SET_EXP(x, exp) ((void) (MPFR_EXP (x) = (exp))) # define <API key>(x) ((void) 0) #endif /* Enum special value of exponent. */ # define MPFR_EXP_ZERO (MPFR_EXP_MIN+1) # define MPFR_EXP_NAN (MPFR_EXP_MIN+2) # define MPFR_EXP_INF (MPFR_EXP_MIN+3) #define MPFR_IS_NAN(x) (MPFR_EXP(x) == MPFR_EXP_NAN) #define MPFR_SET_NAN(x) (MPFR_EXP(x) = MPFR_EXP_NAN) #define MPFR_IS_INF(x) (MPFR_EXP(x) == MPFR_EXP_INF) #define MPFR_SET_INF(x) (MPFR_EXP(x) = MPFR_EXP_INF) #define MPFR_IS_ZERO(x) (MPFR_EXP(x) == MPFR_EXP_ZERO) #define MPFR_SET_ZERO(x) (MPFR_EXP(x) = MPFR_EXP_ZERO) #define MPFR_NOTZERO(x) (MPFR_EXP(x) != MPFR_EXP_ZERO) #define MPFR_IS_FP(x) (!MPFR_IS_NAN(x) && !MPFR_IS_INF(x)) #define MPFR_IS_SINGULAR(x) (MPFR_EXP(x) <= MPFR_EXP_INF) #define MPFR_IS_PURE_FP(x) (!MPFR_IS_SINGULAR(x) && \ (MPFR_ASSERTD (MPFR_MANT(x)[MPFR_LIMB_SIZE(x)-1] & MPFR_LIMB_HIGHBIT), 1)) #define MPFR_ARE_SINGULAR(x,y) \ (MPFR_UNLIKELY(MPFR_IS_SINGULAR(x)) || MPFR_UNLIKELY(MPFR_IS_SINGULAR(y))) #define MPFR_IS_POWER_OF_2(x) \ (mpfr_cmp_ui_2exp ((x), 1, MPFR_GET_EXP (x) - 1) == 0) #define MPFR_SIGN_POS (1) #define MPFR_SIGN_NEG (-1) #define MPFR_IS_STRICTPOS(x) (MPFR_NOTZERO((x)) && MPFR_SIGN(x) > 0) #define MPFR_IS_STRICTNEG(x) (MPFR_NOTZERO((x)) && MPFR_SIGN(x) < 0) #define MPFR_IS_NEG(x) (MPFR_SIGN(x) < 0) #define MPFR_IS_POS(x) (MPFR_SIGN(x) > 0) #define MPFR_SET_POS(x) (MPFR_SIGN(x) = MPFR_SIGN_POS) #define MPFR_SET_NEG(x) (MPFR_SIGN(x) = MPFR_SIGN_NEG) #define MPFR_CHANGE_SIGN(x) (MPFR_SIGN(x) = -MPFR_SIGN(x)) #define MPFR_SET_SAME_SIGN(x, y) (MPFR_SIGN(x) = MPFR_SIGN(y)) #define <API key>(x, y) (MPFR_SIGN(x) = -MPFR_SIGN(y)) #define MPFR_ASSERT_SIGN(s) \ (MPFR_ASSERTD((s) == MPFR_SIGN_POS || (s) == MPFR_SIGN_NEG)) #define MPFR_SET_SIGN(x, s) \ (MPFR_ASSERT_SIGN(s), MPFR_SIGN(x) = s) #define MPFR_IS_POS_SIGN(s1) (s1 > 0) #define MPFR_IS_NEG_SIGN(s1) (s1 < 0) #define MPFR_MULT_SIGN(s1, s2) ((s1) * (s2)) /* Transform a sign to 1 or -1 */ #define <API key>(s) (s) #define MPFR_INT_SIGN(x) <API key>(MPFR_SIGN(x)) /* Special inexact value */ #define MPFR_EVEN_INEX 2 /* Macros for functions returning two inexact values in an 'int' */ #define INEXPOS(y) ((y) == 0 ? 0 : (((y) > 0) ? 1 : 2)) #define INEX(y,z) (INEXPOS(y) | (INEXPOS(z) << 2)) /* When returning the ternary inexact value, ALWAYS use one of the following two macros, unless the flag comes from another function returning the ternary inexact value */ #define MPFR_RET(I) return \ (I) ? ((__gmpfr_flags |= MPFR_FLAGS_INEXACT), (I)) : 0 #define MPFR_RET_NAN return (__gmpfr_flags |= MPFR_FLAGS_NAN), 0 #define MPFR_SET_ERANGE() (__gmpfr_flags |= MPFR_FLAGS_ERANGE) #define SIGN(I) ((I) < 0 ? -1 : (I) > 0) #define SAME_SIGN(I1,I2) (SIGN (I1) == SIGN (I2)) /* MPFR_RND_MAX gives the number of supported rounding modes by all functions. * Once faithful rounding is implemented, MPFR_RNDA should be changed * to MPFR_RNDF. But this will also require more changes in the tests. */ #define MPFR_RND_MAX ((mpfr_rnd_t)((MPFR_RNDA)+1)) /* We want to test this : * (rnd == MPFR_RNDU && test) || (rnd == RNDD && !test) * ie it transforms RNDU or RNDD to Away or Zero according to the sign */ #define <API key>(rnd, test) \ (((rnd) + (test)) == MPFR_RNDD) /* We want to test if rnd = Zero, or Away. 'test' is 1 if negative, and 0 if positive. */ #define MPFR_IS_LIKE_RNDZ(rnd, test) \ ((rnd==MPFR_RNDZ) || <API key> (rnd, test)) #define MPFR_IS_LIKE_RNDU(rnd, sign) \ ((rnd==MPFR_RNDU) || (rnd==MPFR_RNDZ && sign<0) || (rnd==MPFR_RNDA && sign>0)) #define MPFR_IS_LIKE_RNDD(rnd, sign) \ ((rnd==MPFR_RNDD) || (rnd==MPFR_RNDZ && sign>0) || (rnd==MPFR_RNDA && sign<0)) /* Invert a rounding mode, RNDZ and RNDA are unchanged */ #define MPFR_INVERT_RND(rnd) ((rnd == MPFR_RNDU) ? MPFR_RNDD : \ ((rnd == MPFR_RNDD) ? MPFR_RNDU : rnd)) /* Transform RNDU and RNDD to RNDZ according to test */ #define <API key>(rnd, test) \ do { \ if (MPFR_UNLIKELY(<API key>(rnd, test))) \ rnd = MPFR_RNDZ; \ } while (0) /* Transform RNDU and RNDD to RNDZ or RNDA according to sign, leave the other modes unchanged */ #define <API key>(rnd, sign) \ do { \ if (rnd == MPFR_RNDU) \ rnd = (sign > 0) ? MPFR_RNDA : MPFR_RNDZ; \ else if (rnd == MPFR_RNDD) \ rnd = (sign < 0) ? MPFR_RNDA : MPFR_RNDZ; \ } while (0) /* Definition of MPFR_LIMB_HIGHBIT */ #if defined(GMP_LIMB_HIGHBIT) # define MPFR_LIMB_HIGHBIT GMP_LIMB_HIGHBIT #elif defined(MP_LIMB_T_HIGHBIT) # define MPFR_LIMB_HIGHBIT MP_LIMB_T_HIGHBIT #else # error "Neither GMP_LIMB_HIGHBIT nor MP_LIMB_T_HIGHBIT defined in GMP" #endif /* Mask to get the Most Significant Bit of a limb */ #define MPFR_LIMB_MSB(l) ((l)&MPFR_LIMB_HIGHBIT) /* Definition of MPFR_LIMB_ONE & MPFR_LIMB_ZERO */ #ifdef CNST_LIMB # define MPFR_LIMB_ONE CNST_LIMB(1) # define MPFR_LIMB_ZERO CNST_LIMB(0) #else # define MPFR_LIMB_ONE ((mp_limb_t) 1L) # define MPFR_LIMB_ZERO ((mp_limb_t) 0L) #endif /* Mask for the low 's' bits of a limb */ #define MPFR_LIMB_MASK(s) ((MPFR_LIMB_ONE<<(s))-MPFR_LIMB_ONE) /* Heap Memory gestion */ typedef union { mp_size_t s; mp_limb_t l; } mpfr_size_limb_t; #define MPFR_GET_ALLOC_SIZE(x) \ ( ((mp_size_t*) MPFR_MANT(x))[-1] + 0) #define MPFR_SET_ALLOC_SIZE(x, n) \ ( ((mp_size_t*) MPFR_MANT(x))[-1] = n) #define MPFR_MALLOC_SIZE(s) \ ( sizeof(mpfr_size_limb_t) + BYTES_PER_MP_LIMB * ((size_t) s) ) #define MPFR_SET_MANT_PTR(x,p) \ (MPFR_MANT(x) = (mp_limb_t*) ((mpfr_size_limb_t*) p + 1)) #define MPFR_GET_REAL_PTR(x) \ ((mp_limb_t*) ((mpfr_size_limb_t*) MPFR_MANT(x) - 1)) /* Temporary memory gestion */ #ifndef TMP_SALLOC /* GMP 4.1.x or below or internals */ #define MPFR_TMP_DECL TMP_DECL #define MPFR_TMP_MARK TMP_MARK #define MPFR_TMP_ALLOC TMP_ALLOC #define MPFR_TMP_FREE TMP_FREE #else #define MPFR_TMP_DECL(x) TMP_DECL #define MPFR_TMP_MARK(x) TMP_MARK #define MPFR_TMP_ALLOC(s) TMP_ALLOC(s) #define MPFR_TMP_FREE(x) TMP_FREE #endif /* This code is experimental: don't use it */ #ifdef <API key> extern unsigned char *mpfr_stack; #undef MPFR_TMP_DECL #undef MPFR_TMP_MARK #undef MPFR_TMP_ALLOC #undef MPFR_TMP_FREE #define MPFR_TMP_DECL(_x) unsigned char *(_x) #define MPFR_TMP_MARK(_x) ((_x) = mpfr_stack) #define MPFR_TMP_ALLOC(_s) (mpfr_stack += (_s), mpfr_stack - (_s)) #define MPFR_TMP_FREE(_x) (mpfr_stack = (_x)) #endif #define <API key>(N) \ ((mp_limb_t *) MPFR_TMP_ALLOC ((size_t) (N) * BYTES_PER_MP_LIMB)) /* temporary allocate 1 limb at xp, and initialize mpfr variable x */ /* The temporary var doesn't have any size field, but it doesn't matter * since only functions dealing with the Heap care about it */ #define MPFR_TMP_INIT1(xp, x, p) \ ( MPFR_PREC(x) = (p), \ MPFR_MANT(x) = (xp), \ MPFR_SET_POS(x), \ <API key>(x)) #define MPFR_TMP_INIT(xp, x, p, s) \ (xp = <API key>(s), \ MPFR_TMP_INIT1(xp, x, p)) #define MPFR_TMP_INIT_ABS(d, s) \ ( MPFR_PREC(d) = MPFR_PREC(s), \ MPFR_MANT(d) = MPFR_MANT(s), \ MPFR_SET_POS(d), \ MPFR_EXP(d) = MPFR_EXP(s)) #define mpfr_const_pi(_d,_r) mpfr_cache(_d, <API key>,_r) #define mpfr_const_log2(_d,_r) mpfr_cache(_d, <API key>, _r) #define mpfr_const_euler(_d,_r) mpfr_cache(_d, <API key>, _r) #define mpfr_const_catalan(_d,_r) mpfr_cache(_d,<API key>,_r) #define <API key>(_cache,_func) \ mpfr_cache_t MPFR_THREAD_ATTR _cache = \ {{{{0,MPFR_SIGN_POS,0,(mp_limb_t*)0}},0,_func}} #include "mparam.h" /* Theses macros help the compiler to determine if a test is likely or unlikely. The !! is necessary in case x is larger than a long. */ #if __MPFR_GNUC(3,0) || __MPFR_ICC(8,1,0) # define MPFR_LIKELY(x) (__builtin_expect(!!(x),1)) # define MPFR_UNLIKELY(x) (__builtin_expect(!!(x),0)) #else # define MPFR_LIKELY(x) (x) # define MPFR_UNLIKELY(x) (x) #endif #if defined(__GNUC__) # define INITIALIZED(VAR) VAR = VAR #else # define INITIALIZED(VAR) VAR #endif /* Ceil log 2: If GCC, uses a GCC extension, otherwise calls a function */ /* Warning: * Needs to define MPFR_NEED_LONGLONG. * Computes ceil(log2(x)) only for x integer (unsigned long) * Undefined if x is 0 */ #if __MPFR_GNUC(2,95) || __MPFR_ICC(8,1,0) # define MPFR_INT_CEIL_LOG2(x) \ (MPFR_UNLIKELY ((x) == 1) ? 0 : \ __extension__ ({ int _b; mp_limb_t _limb; \ MPFR_ASSERTN ((x) > 1); \ _limb = (x) - 1; \ MPFR_ASSERTN (_limb == (x) - 1); \ count_leading_zeros (_b, _limb); \ (GMP_NUMB_BITS - _b); })) #else # define MPFR_INT_CEIL_LOG2(x) (<API key>(x)) #endif /* Add two integers with overflow handling */ /* Example: MPFR_SADD_OVERFLOW (c, a, b, long, unsigned long, * LONG_MIN, LONG_MAX, * goto overflow, goto underflow); */ #define MPFR_UADD_OVERFLOW(c,a,b,ACTION_IF_OVERFLOW) \ do { \ (c) = (a) + (b); \ if ((c) < (a)) ACTION_IF_OVERFLOW; \ } while (0) #define MPFR_SADD_OVERFLOW(c,a,b,STYPE,UTYPE,MIN,MAX,<API key>,<API key>) \ do { \ if ((a) >= 0 && (b) >= 0) { \ UTYPE uc,ua,ub; \ ua = (UTYPE) (a); ub = (UTYPE) (b); \ MPFR_UADD_OVERFLOW (uc, ua, ub, <API key>); \ if (uc > (UTYPE)(MAX)) <API key>; \ else (c) = (STYPE) uc; \ } else if ((a) < 0 && (b) < 0) { \ UTYPE uc,ua,ub; \ ua = -(UTYPE) (a); ub = -(UTYPE) (b); \ MPFR_UADD_OVERFLOW (uc, ua, ub, <API key>); \ if (uc >= -(UTYPE)(MIN) || uc > (UTYPE)(MAX)) { \ if (uc == -(UTYPE)(MIN)) (c) = (MIN); \ else <API key>; } \ else (c) = -(STYPE) uc; \ } else (c) = (a) + (b); \ } while (0) /* Set a number to 1 (Fast) - It doesn't check if 1 is in the exponent range */ #define MPFR_SET_ONE(x) \ do { \ mp_size_t _size = MPFR_LIMB_SIZE(x) - 1; \ MPFR_SET_POS(x); \ MPFR_EXP(x) = 1; \ MPN_ZERO ( MPFR_MANT(x), _size); \ MPFR_MANT(x)[_size] = MPFR_LIMB_HIGHBIT; \ } while (0) /* Compute s = (-a) % GMP_NUMB_BITS as unsigned */ #define <API key>(s, a) \ do \ { \ if (IS_POW2 (GMP_NUMB_BITS)) \ (s) = (- (unsigned int) (a)) % GMP_NUMB_BITS; \ else \ { \ (s) = (a) % GMP_NUMB_BITS; \ if ((s) != 0) \ (s) = GMP_NUMB_BITS - (s); \ } \ MPFR_ASSERTD ((s) >= 0 && (s) < GMP_NUMB_BITS); \ } \ while (0) /* Use it only for debug reasons */ /* MPFR_TRACE (operation) : execute operation iff DEBUG flag is set */ /* MPFR_DUMP (x) : print x (a mpfr_t) on stdout */ #ifdef DEBUG # define MPFR_TRACE(x) x #else # define MPFR_TRACE(x) (void) 0 #endif #define MPFR_DUMP(x) ( printf(#x"="), mpfr_dump(x) ) /* Test if X (positive) is a power of 2 */ #define IS_POW2(X) (((X) & ((X) - 1)) == 0) #define NOT_POW2(X) (((X) & ((X) - 1)) != 0) /* Safe absolute value (to avoid possible integer overflow) */ /* type is the target (unsigned) type */ #define SAFE_ABS(type,x) ((x) >= 0 ? (type)(x) : -(type)(x)) #define mpfr_get_d1(x) mpfr_get_d(x,<API key>) /* Store in r the size in bits of the mpz_t z */ #define <API key>(r, z) \ do { \ int _cnt; \ mp_size_t _size; \ MPFR_ASSERTD (mpz_sgn (z) != 0); \ _size = ABSIZ(z); \ count_leading_zeros (_cnt, PTR(z)[_size-1]); \ (r) = _size * GMP_NUMB_BITS - _cnt; \ } while (0) /* Needs <locale.h> */ #ifdef HAVE_LOCALE_H #include <locale.h> /* Warning! In case of signed char, the value of MPFR_DECIMAL_POINT may be negative (the ISO C99 does not seem to forbid negative values). */ #define MPFR_DECIMAL_POINT (localeconv()->decimal_point[0]) #define <API key> (localeconv()->thousands_sep[0]) #else #define MPFR_DECIMAL_POINT ((char) '.') #define <API key> ('\0') #endif /* Set y to s*significand(x)*2^e, for example MPFR_ALIAS(y,x,1,MPFR_EXP(x)) sets y to |x|, and MPFR_ALIAS(y,x,MPFR_SIGN(x),0) sets y to x*2^f such that 1/2 <= |y| < 1. Does not check y is in the valid exponent range. WARNING! x and y share the same mantissa. So, some operations are not valid if x has been provided via an argument, e.g., trying to modify the mantissa of y, even temporarily, or calling mpfr_clear on y. */ #define MPFR_ALIAS(y,x,s,e) \ do \ { \ MPFR_PREC(y) = MPFR_PREC(x); \ MPFR_SIGN(y) = (s); \ MPFR_EXP(y) = (e); \ MPFR_MANT(y) = MPFR_MANT(x); \ } while (0) /* See README.dev for details on how to use the macros. They are used to set the exponent range to the maximum temporarily */ typedef struct { unsigned int saved_flags; mpfr_exp_t saved_emin; mpfr_exp_t saved_emax; } mpfr_save_expo_t; /* Minimum and maximum exponents of the extended exponent range. */ #define MPFR_EXT_EMIN MPFR_EMIN_MIN #define MPFR_EXT_EMAX MPFR_EMAX_MAX #define MPFR_SAVE_EXPO_DECL(x) mpfr_save_expo_t x #define MPFR_SAVE_EXPO_MARK(x) \ ((x).saved_flags = __gmpfr_flags, \ (x).saved_emin = __gmpfr_emin, \ (x).saved_emax = __gmpfr_emax, \ __gmpfr_emin = MPFR_EXT_EMIN, \ __gmpfr_emax = MPFR_EXT_EMAX) #define MPFR_SAVE_EXPO_FREE(x) \ (__gmpfr_flags = (x).saved_flags, \ __gmpfr_emin = (x).saved_emin, \ __gmpfr_emax = (x).saved_emax) #define <API key>(x, flags) \ (x).saved_flags |= (flags) /* Speed up final checking */ #define mpfr_check_range(x,t,r) \ (MPFR_LIKELY (MPFR_EXP (x) >= __gmpfr_emin && MPFR_EXP (x) <= __gmpfr_emax) \ ? ((t) ? (__gmpfr_flags |= MPFR_FLAGS_INEXACT, (t)) : 0) \ : mpfr_check_range(x,t,r)) /* * Note: due to the labels, one cannot use a macro MPFR_RNDRAW* more than * once in a function (otherwise these labels would not be unique). */ /* * Round mantissa (srcp, sprec) to mpfr_t dest using rounding mode rnd * assuming dest's sign is sign. * In rounding to nearest mode, execute MIDDLE_HANDLER when the value * is the middle of two consecutive numbers in dest precision. * Execute OVERFLOW_HANDLER in case of overflow when rounding. */ #define MPFR_RNDRAW_GEN(inexact, dest, srcp, sprec, rnd, sign, \ MIDDLE_HANDLER, OVERFLOW_HANDLER) \ do { \ mp_size_t _dests, _srcs; \ mp_limb_t *_destp; \ mpfr_prec_t _destprec, _srcprec; \ \ /* Check Trivial Case when Dest Mantissa has more bits than source */ \ _srcprec = (sprec); \ _destprec = MPFR_PREC (dest); \ _destp = MPFR_MANT (dest); \ if (MPFR_UNLIKELY (_destprec >= _srcprec)) \ { \ _srcs = (_srcprec + GMP_NUMB_BITS-1)/GMP_NUMB_BITS; \ _dests = (_destprec + GMP_NUMB_BITS-1)/GMP_NUMB_BITS - _srcs; \ MPN_COPY (_destp + _dests, srcp, _srcs); \ MPN_ZERO (_destp, _dests); \ inexact = 0; \ } \ else \ { \ /* Non trivial case: rounding needed */ \ mpfr_prec_t _sh; \ mp_limb_t *_sp; \ mp_limb_t _rb, _sb, _ulp; \ \ /* Compute Position and shift */ \ _srcs = (_srcprec + GMP_NUMB_BITS-1)/GMP_NUMB_BITS; \ _dests = (_destprec + GMP_NUMB_BITS-1)/GMP_NUMB_BITS; \ <API key> (_sh, _destprec); \ _sp = (srcp) + _srcs - _dests; \ \ /* General case when prec % GMP_NUMB_BITS != 0 */ \ if (MPFR_LIKELY (_sh != 0)) \ { \ mp_limb_t _mask; \ /* Compute Rounding Bit and Sticky Bit */ \ /* Note: in directed rounding modes, if the rounding bit */ \ /* is 1, the behavior does not depend on the sticky bit; */ \ /* thus we will not try to compute it in this case (this */ \ /* can be much faster and avoids to read uninitialized */ \ /* data in the current mpfr_mul implementation). We just */ \ /* make sure that _sb is initialized. */ \ _mask = MPFR_LIMB_ONE << (_sh - 1); \ _rb = _sp[0] & _mask; \ _sb = _sp[0] & (_mask - 1); \ if (MPFR_UNLIKELY (_sb == 0) && \ ((rnd) == MPFR_RNDN || _rb == 0)) \ { /* TODO: Improve it */ \ mp_limb_t *_tmp; \ mp_size_t _n; \ for (_tmp = _sp, _n = _srcs - _dests ; \ _n != 0 && _sb == 0 ; _n _sb = *--_tmp; \ } \ _ulp = 2 * _mask; \ } \ else /* _sh == 0 */ \ { \ MPFR_ASSERTD (_dests < _srcs); \ /* Compute Rounding Bit and Sticky Bit - see note above */ \ _rb = _sp[-1] & MPFR_LIMB_HIGHBIT; \ _sb = _sp[-1] & (MPFR_LIMB_HIGHBIT-1); \ if (MPFR_UNLIKELY (_sb == 0) && \ ((rnd) == MPFR_RNDN || _rb == 0)) \ { \ mp_limb_t *_tmp; \ mp_size_t _n; \ for (_tmp = _sp - 1, _n = _srcs - _dests - 1 ; \ _n != 0 && _sb == 0 ; _n _sb = *--_tmp; \ } \ _ulp = MPFR_LIMB_ONE; \ } \ /* Rounding */ \ if (MPFR_LIKELY (rnd == MPFR_RNDN)) \ { \ if (_rb == 0) \ { \ trunc: \ inexact = MPFR_LIKELY ((_sb | _rb) != 0) ? -sign : 0; \ trunc_doit: \ MPN_COPY (_destp, _sp, _dests); \ _destp[0] &= ~(_ulp - 1); \ } \ else if (MPFR_UNLIKELY (_sb == 0)) \ { /* Middle of two consecutive representable numbers */ \ MIDDLE_HANDLER; \ } \ else \ { \ if (0) \ goto addoneulp_doit; /* dummy code to avoid warning */ \ addoneulp: \ inexact = sign; \ addoneulp_doit: \ if (MPFR_UNLIKELY (mpn_add_1 (_destp, _sp, _dests, _ulp))) \ { \ _destp[_dests - 1] = MPFR_LIMB_HIGHBIT; \ OVERFLOW_HANDLER; \ } \ _destp[0] &= ~(_ulp - 1); \ } \ } \ else \ { /* Directed rounding mode */ \ if (MPFR_LIKELY (MPFR_IS_LIKE_RNDZ (rnd, \ MPFR_IS_NEG_SIGN (sign)))) \ goto trunc; \ else if (MPFR_UNLIKELY ((_sb | _rb) == 0)) \ { \ inexact = 0; \ goto trunc_doit; \ } \ else \ goto addoneulp; \ } \ } \ } while (0) /* * Round mantissa (srcp, sprec) to mpfr_t dest using rounding mode rnd * assuming dest's sign is sign. * Execute OVERFLOW_HANDLER in case of overflow when rounding. */ #define MPFR_RNDRAW(inexact, dest, srcp, sprec, rnd, sign, OVERFLOW_HANDLER) \ MPFR_RNDRAW_GEN (inexact, dest, srcp, sprec, rnd, sign, \ if ((_sp[0] & _ulp) == 0) \ { \ inexact = -sign; \ goto trunc_doit; \ } \ else \ goto addoneulp; \ , OVERFLOW_HANDLER) /* * Round mantissa (srcp, sprec) to mpfr_t dest using rounding mode rnd * assuming dest's sign is sign. * Execute OVERFLOW_HANDLER in case of overflow when rounding. * Set inexact to +/- MPFR_EVEN_INEX in case of even rounding. */ #define MPFR_RNDRAW_EVEN(inexact, dest, srcp, sprec, rnd, sign, \ OVERFLOW_HANDLER) \ MPFR_RNDRAW_GEN (inexact, dest, srcp, sprec, rnd, sign, \ if ((_sp[0] & _ulp) == 0) \ { \ inexact = -MPFR_EVEN_INEX * sign; \ goto trunc_doit; \ } \ else \ { \ inexact = MPFR_EVEN_INEX * sign; \ goto addoneulp_doit; \ } \ , OVERFLOW_HANDLER) /* Return TRUE if b is non singular and we can round it to precision 'prec' and determine the ternary value, with rounding mode 'rnd', and with error at most 'error' */ #define MPFR_CAN_ROUND(b,err,prec,rnd) \ (!MPFR_IS_SINGULAR (b) && mpfr_round_p (MPFR_MANT (b), MPFR_LIMB_SIZE (b), \ (err), (prec) + ((rnd)==MPFR_RNDN))) /* Copy the sign and the significand, and handle the exponent in exp. */ #define MPFR_SETRAW(inexact,dest,src,exp,rnd) \ if (MPFR_UNLIKELY (dest != src)) \ { \ MPFR_SET_SIGN (dest, MPFR_SIGN (src)); \ if (MPFR_LIKELY (MPFR_PREC (dest) == MPFR_PREC (src))) \ { \ MPN_COPY (MPFR_MANT (dest), MPFR_MANT (src), \ (MPFR_PREC (src) + GMP_NUMB_BITS-1)/GMP_NUMB_BITS); \ inexact = 0; \ } \ else \ { \ MPFR_RNDRAW (inexact, dest, MPFR_MANT (src), MPFR_PREC (src), \ rnd, MPFR_SIGN (src), exp++); \ } \ } \ else \ inexact = 0; /* TODO: fix this description (see round_near_x.c). */ /* Assuming that the function has a Taylor expansion which looks like: y=o(f(x)) = o(v + g(x)) with |g(x)| <= 2^(EXP(v)-err) we can quickly set y to v if x is small (ie err > prec(y)+1) in most cases. It assumes that f(x) is not representable exactly as a FP number. v must not be a singular value (NAN, INF or ZERO); usual values are v=1 or v=x. y is the destination (a mpfr_t), v the value to set (a mpfr_t), err1+err2 with err2 <= 3 the error term (mpfr_exp_t's), dir (an int) is the direction of the committed error (if dir = 0, it rounds toward 0, if dir=1, it rounds away from 0), rnd the rounding mode. It returns from the function a ternary value in case of success. If you want to free something, you must fill the "extra" field in consequences, otherwise put nothing in it. The test is less restrictive than necessary, but the function will finish the check itself. Note: err1 + err2 is allowed to overflow as mpfr_exp_t, but it must give its real value as mpfr_uexp_t. */ #define <API key>(y,v,err1,err2,dir,rnd,extra) \ do { \ mpfr_ptr _y = (y); \ mpfr_exp_t _err1 = (err1); \ mpfr_exp_t _err2 = (err2); \ if (_err1 > 0) \ { \ mpfr_uexp_t _err = (mpfr_uexp_t) _err1 + _err2; \ if (MPFR_UNLIKELY (_err > MPFR_PREC (_y) + 1)) \ { \ int _inexact = mpfr_round_near_x (_y,(v),_err,(dir),(rnd)); \ if (_inexact != 0) \ { \ extra; \ return _inexact; \ } \ } \ } \ } while (0) /* Variant, to be called somewhere after MPFR_SAVE_EXPO_MARK. This variant is needed when there are some computations before or when some non-zero real constant is used, such as __gmpfr_one for mpfr_cos. */ #define <API key>(y,v,err1,err2,dir,rnd,expo,extra) \ do { \ mpfr_ptr _y = (y); \ mpfr_exp_t _err1 = (err1); \ mpfr_exp_t _err2 = (err2); \ if (_err1 > 0) \ { \ mpfr_uexp_t _err = (mpfr_uexp_t) _err1 + _err2; \ if (MPFR_UNLIKELY (_err > MPFR_PREC (_y) + 1)) \ { \ int _inexact; \ mpfr_clear_flags (); \ _inexact = mpfr_round_near_x (_y,(v),_err,(dir),(rnd)); \ if (_inexact != 0) \ { \ extra; \ <API key> (expo, __gmpfr_flags); \ MPFR_SAVE_EXPO_FREE (expo); \ return mpfr_check_range (_y, _inexact, (rnd)); \ } \ } \ } \ } while (0) #ifndef MPFR_USE_LOGGING #define MPFR_ZIV_DECL(_x) mpfr_prec_t _x #define MPFR_ZIV_INIT(_x, _p) (_x) = GMP_NUMB_BITS #define MPFR_ZIV_NEXT(_x, _p) ((_p) += (_x), (_x) = (_p)/2) #define MPFR_ZIV_FREE(x) #else /* The following test on glibc is there mainly for Darwin (Mac OS X), to obtain a better error message. The real test should have been a test concerning nested functions in gcc, which are disabled by default on Darwin; but it is not possible to do that without a configure test. */ # if defined (__cplusplus) || !(__MPFR_GNUC(3,0) && __MPFR_GLIBC(2,0)) # error "Logging not supported (needs gcc >= 3.0 and GNU C Library >= 2.0)." # endif /* Use LOGGING */ /* Note: the mpfr_log_level >= 0 below avoids to take into account Ziv loops used by the MPFR functions called by the mpfr_fprintf in LOG_PRINT. */ #define MPFR_ZIV_DECL(_x) \ mpfr_prec_t _x; \ int _x ## _cpt = 1; \ static unsigned long _x ## _loop = 0, _x ## _bad = 0; \ static const char *_x ## _fname = __func__; \ auto void __attribute__ ((destructor)) x ## _f (void); \ void __attribute__ ((destructor)) x ## _f (void) { \ if (_x ## _loop != 0 && (MPFR_LOG_STAT_F & mpfr_log_type)) \ fprintf (mpfr_log_file, \ "%s: Ziv failed %2.2f%% (%lu bad cases / %lu calls)\n", \ _x ## _fname, (double) 100.0 * _x ## _bad / _x ## _loop, \ _x ## _bad, _x ## _loop ); } #define MPFR_ZIV_INIT(_x, _p) \ do \ { \ (_x) = GMP_NUMB_BITS; \ if (mpfr_log_level >= 0) \ _x ## _loop ++; \ if ((MPFR_LOG_BADCASE_F & mpfr_log_type) && \ (mpfr_log_current <= mpfr_log_level)) \ LOG_PRINT ("%s:ZIV 1st prec=%Pd\n", \ __func__, (mpfr_prec_t) (_p)); \ } \ while (0) #define MPFR_ZIV_NEXT(_x, _p) \ do \ { \ (_p) += (_x); \ (_x) = (_p) / 2; \ if (mpfr_log_level >= 0) \ _x ## _bad += (_x ## _cpt == 1); \ _x ## _cpt ++; \ if ((MPFR_LOG_BADCASE_F & mpfr_log_type) && \ (mpfr_log_current <= mpfr_log_level)) \ LOG_PRINT ("%s:ZIV new prec=%Pd\n", \ __func__, (mpfr_prec_t) (_p)); \ } \ while (0) #define MPFR_ZIV_FREE(_x) \ do \ { \ if ((MPFR_LOG_BADCASE_F & mpfr_log_type) && _x ## _cpt > 1 && \ (mpfr_log_current <= mpfr_log_level)) \ fprintf (mpfr_log_file, "%s:ZIV %d loops\n", \ __func__, _x ## _cpt); \ } \ while (0) #endif /* The different kind of LOG */ #define MPFR_LOG_INPUT_F 1 #define MPFR_LOG_OUTPUT_F 2 #define MPFR_LOG_INTERNAL_F 4 #define MPFR_LOG_TIME_F 8 #define MPFR_LOG_BADCASE_F 16 #define MPFR_LOG_MSG_F 32 #define MPFR_LOG_STAT_F 64 #ifdef MPFR_USE_LOGGING /* Check if we can support this feature */ # ifdef <API key> # error "Enable either `Logging' or `thread-safe', not both" # endif # if !__MPFR_GNUC(3,0) # error "Logging not supported (GCC >= 3.0)" # endif #if defined (__cplusplus) extern "C" { #endif __MPFR_DECLSPEC extern FILE *mpfr_log_file; __MPFR_DECLSPEC extern int mpfr_log_type; __MPFR_DECLSPEC extern int mpfr_log_level; __MPFR_DECLSPEC extern int mpfr_log_current; __MPFR_DECLSPEC extern mpfr_prec_t mpfr_log_prec; #if defined (__cplusplus) } #endif /* LOG_PRINT calls mpfr_fprintf on mpfr_log_file with logging disabled (recursive logging is not wanted and freezes MPFR). */ #define LOG_PRINT(format, ...) \ do \ { \ int old_level = mpfr_log_level; \ mpfr_log_level = -1; /* disable logging in mpfr_fprintf */ \ <API key> = __gmpfr_logging_pi; \ <API key> = <API key>; \ mpfr_fprintf (mpfr_log_file, format, __VA_ARGS__); \ mpfr_log_level = old_level; \ <API key> = __gmpfr_normal_pi; \ <API key> = __gmpfr_normal_log2; \ } \ while (0) #define MPFR_LOG_VAR(x) \ do \ if ((MPFR_LOG_INTERNAL_F & mpfr_log_type) && \ (mpfr_log_current <= mpfr_log_level)) \ LOG_PRINT ("%s.%d:%s[%#Pu]=%.*Rf\n", __func__, __LINE__, \ #x, mpfr_get_prec (x), mpfr_log_prec, x); \ while (0) #define MPFR_LOG_MSG2(format, ...) \ do \ if ((MPFR_LOG_MSG_F & mpfr_log_type) && \ (mpfr_log_current <= mpfr_log_level)) \ LOG_PRINT ("%s.%d: "format, __func__, __LINE__, __VA_ARGS__); \ while (0) #define MPFR_LOG_MSG(x) MPFR_LOG_MSG2 x #define MPFR_LOG_BEGIN2(format, ...) \ mpfr_log_current ++; \ if ((MPFR_LOG_INPUT_F & mpfr_log_type) && \ (mpfr_log_current <= mpfr_log_level)) \ LOG_PRINT ("%s:IN "format"\n", __func__, __VA_ARGS__); \ if ((MPFR_LOG_TIME_F & mpfr_log_type) && \ (mpfr_log_current <= mpfr_log_level)) \ __gmpfr_log_time = mpfr_get_cputime (); #define MPFR_LOG_BEGIN(x) \ int __gmpfr_log_time = 0; \ MPFR_LOG_BEGIN2 x #define MPFR_LOG_END2(format, ...) \ if ((MPFR_LOG_TIME_F & mpfr_log_type) && \ (mpfr_log_current <= mpfr_log_level)) \ fprintf (mpfr_log_file, "%s:TIM %dms\n", __mpfr_log_fname, \ mpfr_get_cputime () - __gmpfr_log_time); \ if ((MPFR_LOG_OUTPUT_F & mpfr_log_type) && \ (mpfr_log_current <= mpfr_log_level)) \ LOG_PRINT ("%s:OUT "format"\n", __mpfr_log_fname, __VA_ARGS__); \ mpfr_log_current #define MPFR_LOG_END(x) \ static const char *__mpfr_log_fname = __func__; \ MPFR_LOG_END2 x #define MPFR_LOG_FUNC(begin,end) \ static const char *__mpfr_log_fname = __func__; \ auto void __mpfr_log_cleanup (int *time); \ void __mpfr_log_cleanup (int *time) { \ int __gmpfr_log_time = *time; \ MPFR_LOG_END2 end; } \ int __gmpfr_log_time __attribute__ ((cleanup (__mpfr_log_cleanup))); \ __gmpfr_log_time = 0; \ MPFR_LOG_BEGIN2 begin #else /* MPFR_USE_LOGGING */ /* Define void macro for logging */ #define MPFR_LOG_VAR(x) #define MPFR_LOG_BEGIN(x) #define MPFR_LOG_END(x) #define MPFR_LOG_MSG(x) #define MPFR_LOG_FUNC(x,y) #endif /* MPFR_USE_LOGGING */ #ifndef <API key> # define <API key> 16 #endif struct mpfr_group_t { size_t alloc; mp_limb_t *mant; mp_limb_t tab[<API key>]; }; #define MPFR_GROUP_DECL(g) struct mpfr_group_t g #define MPFR_GROUP_CLEAR(g) do { \ MPFR_LOG_MSG (("GROUP_CLEAR: ptr = 0x%lX, size = %lu\n", \ (unsigned long) (g).mant, \ (unsigned long) (g).alloc)); \ if (MPFR_UNLIKELY ((g).alloc != 0)) { \ MPFR_ASSERTD ((g).mant != (g).tab); \ (*__gmp_free_func) ((g).mant, (g).alloc); \ }} while (0) #define <API key>(g, prec, num, handler) do { \ mpfr_prec_t _prec = (prec); \ mp_size_t _size; \ MPFR_ASSERTD (_prec >= MPFR_PREC_MIN); \ if (MPFR_UNLIKELY (_prec > MPFR_PREC_MAX)) \ mpfr_abort_prec_max (); \ _size = (mpfr_prec_t) (_prec + GMP_NUMB_BITS - 1) / GMP_NUMB_BITS; \ if (MPFR_UNLIKELY (_size * (num) > <API key>)) \ { \ (g).alloc = (num) * _size * sizeof (mp_limb_t); \ (g).mant = (mp_limb_t *) (*__gmp_allocate_func) ((g).alloc); \ } \ else \ { \ (g).alloc = 0; \ (g).mant = (g).tab; \ } \ MPFR_LOG_MSG (("GROUP_INIT: ptr = 0x%lX, size = %lu\n", \ (unsigned long) (g).mant, (unsigned long) (g).alloc)); \ handler; \ } while (0) #define MPFR_GROUP_TINIT(g, n, x) \ MPFR_TMP_INIT1 ((g).mant + _size * (n), x, _prec) #define MPFR_GROUP_INIT_1(g, prec, x) \ <API key>(g, prec, 1, MPFR_GROUP_TINIT(g, 0, x)) #define MPFR_GROUP_INIT_2(g, prec, x, y) \ <API key>(g, prec, 2, \ MPFR_GROUP_TINIT(g, 0, x);MPFR_GROUP_TINIT(g, 1, y)) #define MPFR_GROUP_INIT_3(g, prec, x, y, z) \ <API key>(g, prec, 3, \ MPFR_GROUP_TINIT(g, 0, x);MPFR_GROUP_TINIT(g, 1, y); \ MPFR_GROUP_TINIT(g, 2, z)) #define MPFR_GROUP_INIT_4(g, prec, x, y, z, t) \ <API key>(g, prec, 4, \ MPFR_GROUP_TINIT(g, 0, x);MPFR_GROUP_TINIT(g, 1, y); \ MPFR_GROUP_TINIT(g, 2, z);MPFR_GROUP_TINIT(g, 3, t)) #define MPFR_GROUP_INIT_5(g, prec, x, y, z, t, a) \ <API key>(g, prec, 5, \ MPFR_GROUP_TINIT(g, 0, x);MPFR_GROUP_TINIT(g, 1, y); \ MPFR_GROUP_TINIT(g, 2, z);MPFR_GROUP_TINIT(g, 3, t); \ MPFR_GROUP_TINIT(g, 4, a)) #define MPFR_GROUP_INIT_6(g, prec, x, y, z, t, a, b) \ <API key>(g, prec, 6, \ MPFR_GROUP_TINIT(g, 0, x);MPFR_GROUP_TINIT(g, 1, y); \ MPFR_GROUP_TINIT(g, 2, z);MPFR_GROUP_TINIT(g, 3, t); \ MPFR_GROUP_TINIT(g, 4, a);MPFR_GROUP_TINIT(g, 5, b)) #define <API key>(g, prec, num, handler) do { \ mpfr_prec_t _prec = (prec); \ size_t _oalloc = (g).alloc; \ mp_size_t _size; \ MPFR_LOG_MSG (("GROUP_REPREC: oldptr = 0x%lX, oldsize = %lu\n", \ (unsigned long) (g).mant, (unsigned long) _oalloc)); \ MPFR_ASSERTD (_prec >= MPFR_PREC_MIN); \ if (MPFR_UNLIKELY (_prec > MPFR_PREC_MAX)) \ mpfr_abort_prec_max (); \ _size = (mpfr_prec_t) (_prec + GMP_NUMB_BITS - 1) / GMP_NUMB_BITS; \ (g).alloc = (num) * _size * sizeof (mp_limb_t); \ if (MPFR_LIKELY (_oalloc == 0)) \ (g).mant = (mp_limb_t *) (*__gmp_allocate_func) ((g).alloc); \ else \ (g).mant = (mp_limb_t *) \ (*<API key>) ((g).mant, _oalloc, (g).alloc); \ MPFR_LOG_MSG (("GROUP_REPREC: newptr = 0x%lX, newsize = %lu\n", \ (unsigned long) (g).mant, (unsigned long) (g).alloc)); \ handler; \ } while (0) #define MPFR_GROUP_REPREC_1(g, prec, x) \ <API key>(g, prec, 1, MPFR_GROUP_TINIT(g, 0, x)) #define MPFR_GROUP_REPREC_2(g, prec, x, y) \ <API key>(g, prec, 2, \ MPFR_GROUP_TINIT(g, 0, x);MPFR_GROUP_TINIT(g, 1, y)) #define MPFR_GROUP_REPREC_3(g, prec, x, y, z) \ <API key>(g, prec, 3, \ MPFR_GROUP_TINIT(g, 0, x);MPFR_GROUP_TINIT(g, 1, y); \ MPFR_GROUP_TINIT(g, 2, z)) #define MPFR_GROUP_REPREC_4(g, prec, x, y, z, t) \ <API key>(g, prec, 4, \ MPFR_GROUP_TINIT(g, 0, x);MPFR_GROUP_TINIT(g, 1, y); \ MPFR_GROUP_TINIT(g, 2, z);MPFR_GROUP_TINIT(g, 3, t)) #define MPFR_GROUP_REPREC_5(g, prec, x, y, z, t, a) \ <API key>(g, prec, 5, \ MPFR_GROUP_TINIT(g, 0, x);MPFR_GROUP_TINIT(g, 1, y); \ MPFR_GROUP_TINIT(g, 2, z);MPFR_GROUP_TINIT(g, 3, t); \ MPFR_GROUP_TINIT(g, 4, a)) #define MPFR_GROUP_REPREC_6(g, prec, x, y, z, t, a, b) \ <API key>(g, prec, 6, \ MPFR_GROUP_TINIT(g, 0, x);MPFR_GROUP_TINIT(g, 1, y); \ MPFR_GROUP_TINIT(g, 2, z);MPFR_GROUP_TINIT(g, 3, t); \ MPFR_GROUP_TINIT(g, 4, a);MPFR_GROUP_TINIT(g, 5, b)) #if defined (__cplusplus) extern "C" { #endif __MPFR_DECLSPEC int mpfr_underflow _MPFR_PROTO ((mpfr_ptr, mpfr_rnd_t, int)); __MPFR_DECLSPEC int mpfr_overflow _MPFR_PROTO ((mpfr_ptr, mpfr_rnd_t, int)); __MPFR_DECLSPEC int mpfr_add1 _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_sub1 _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_add1sp _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_sub1sp _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_can_round_raw _MPFR_PROTO ((const mp_limb_t *, mp_size_t, int, mpfr_exp_t, mpfr_rnd_t, mpfr_rnd_t, mpfr_prec_t)); __MPFR_DECLSPEC int mpfr_cmp2 _MPFR_PROTO ((mpfr_srcptr, mpfr_srcptr, mpfr_prec_t *)); __MPFR_DECLSPEC long __gmpfr_ceil_log2 _MPFR_PROTO ((double)); __MPFR_DECLSPEC long __gmpfr_floor_log2 _MPFR_PROTO ((double)); __MPFR_DECLSPEC double __gmpfr_ceil_exp2 _MPFR_PROTO ((double)); __MPFR_DECLSPEC unsigned long __gmpfr_isqrt _MPFR_PROTO ((unsigned long)); __MPFR_DECLSPEC unsigned long __gmpfr_cuberoot _MPFR_PROTO ((unsigned long)); __MPFR_DECLSPEC int <API key> _MPFR_PROTO ((unsigned long)); __MPFR_DECLSPEC mpfr_exp_t mpfr_ceil_mul _MPFR_PROTO ((mpfr_exp_t, int, int)); __MPFR_DECLSPEC int mpfr_exp_2 _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_exp_3 _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_powerof2_raw _MPFR_PROTO ((mpfr_srcptr)); __MPFR_DECLSPEC int mpfr_pow_general _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_rnd_t, int, mpfr_save_expo_t *)); __MPFR_DECLSPEC void mpfr_setmax _MPFR_PROTO ((mpfr_ptr, mpfr_exp_t)); __MPFR_DECLSPEC void mpfr_setmin _MPFR_PROTO ((mpfr_ptr, mpfr_exp_t)); __MPFR_DECLSPEC long mpfr_mpn_exp _MPFR_PROTO ((mp_limb_t *, mpfr_exp_t *, int, mpfr_exp_t, size_t)); #ifdef _MPFR_H_HAVE_FILE __MPFR_DECLSPEC void mpfr_fprint_binary _MPFR_PROTO ((FILE *, mpfr_srcptr)); #endif __MPFR_DECLSPEC void mpfr_print_binary _MPFR_PROTO ((mpfr_srcptr)); __MPFR_DECLSPEC void <API key> _MPFR_PROTO ((const char*, const mp_limb_t*, mpfr_prec_t)); __MPFR_DECLSPEC void mpfr_set_str_binary _MPFR_PROTO((mpfr_ptr, const char*)); __MPFR_DECLSPEC int mpfr_round_raw _MPFR_PROTO ((mp_limb_t *, const mp_limb_t *, mpfr_prec_t, int, mpfr_prec_t, mpfr_rnd_t, int *)); __MPFR_DECLSPEC int mpfr_round_raw_2 _MPFR_PROTO ((const mp_limb_t *, mpfr_prec_t, int, mpfr_prec_t, mpfr_rnd_t)); /* No longer defined (see round_prec.c). Uncomment if it needs to be defined again. __MPFR_DECLSPEC int mpfr_round_raw_3 _MPFR_PROTO ((const mp_limb_t *, mpfr_prec_t, int, mpfr_prec_t, mpfr_rnd_t, int *)); */ __MPFR_DECLSPEC int mpfr_round_raw_4 _MPFR_PROTO ((mp_limb_t *, const mp_limb_t *, mpfr_prec_t, int, mpfr_prec_t, mpfr_rnd_t)); #define mpfr_round_raw2(xp, xn, neg, r, prec) \ mpfr_round_raw_2((xp),(xn)*GMP_NUMB_BITS,(neg),(prec),(r)) __MPFR_DECLSPEC int mpfr_check _MPFR_PROTO ((mpfr_srcptr)); __MPFR_DECLSPEC int mpfr_sum_sort _MPFR_PROTO ((mpfr_srcptr *const, unsigned long, mpfr_srcptr *)); __MPFR_DECLSPEC int mpfr_get_cputime _MPFR_PROTO ((void)); __MPFR_DECLSPEC void mpfr_nexttozero _MPFR_PROTO ((mpfr_ptr)); __MPFR_DECLSPEC void mpfr_nexttoinf _MPFR_PROTO ((mpfr_ptr)); __MPFR_DECLSPEC int <API key> _MPFR_PROTO ((mpfr_ptr,mpfr_rnd_t)); __MPFR_DECLSPEC int <API key> _MPFR_PROTO((mpfr_ptr,mpfr_rnd_t)); __MPFR_DECLSPEC int <API key> _MPFR_PROTO((mpfr_ptr, mpfr_rnd_t)); __MPFR_DECLSPEC int <API key> _MPFR_PROTO((mpfr_ptr, mpfr_rnd_t)); #if 0 __MPFR_DECLSPEC void mpfr_init_cache _MPFR_PROTO ((mpfr_cache_t, int(*)(mpfr_ptr,mpfr_rnd_t))); #endif __MPFR_DECLSPEC void mpfr_clear_cache _MPFR_PROTO ((mpfr_cache_t)); __MPFR_DECLSPEC int mpfr_cache _MPFR_PROTO ((mpfr_ptr, mpfr_cache_t, mpfr_rnd_t)); __MPFR_DECLSPEC void mpfr_mulhigh_n _MPFR_PROTO ((mpfr_limb_ptr, mpfr_limb_srcptr, mpfr_limb_srcptr, mp_size_t)); __MPFR_DECLSPEC void mpfr_mullow_n _MPFR_PROTO ((mpfr_limb_ptr, mpfr_limb_srcptr, mpfr_limb_srcptr, mp_size_t)); __MPFR_DECLSPEC void mpfr_sqrhigh_n _MPFR_PROTO ((mpfr_limb_ptr, mpfr_limb_srcptr, mp_size_t)); __MPFR_DECLSPEC mp_limb_t mpfr_divhigh_n _MPFR_PROTO ((mpfr_limb_ptr, mpfr_limb_ptr, mpfr_limb_ptr, mp_size_t)); __MPFR_DECLSPEC int mpfr_round_p _MPFR_PROTO ((mp_limb_t *, mp_size_t, mpfr_exp_t, mpfr_prec_t)); __MPFR_DECLSPEC void mpfr_dump_mant _MPFR_PROTO ((const mp_limb_t *, mpfr_prec_t, mpfr_prec_t, mpfr_prec_t)); __MPFR_DECLSPEC int mpfr_round_near_x _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_uexp_t, int, mpfr_rnd_t)); __MPFR_DECLSPEC void mpfr_abort_prec_max _MPFR_PROTO ((void)) MPFR_NORETURN_ATTR; __MPFR_DECLSPEC void mpfr_rand_raw _MPFR_PROTO((mpfr_limb_ptr, gmp_randstate_t, unsigned long)); __MPFR_DECLSPEC mpz_t* <API key> _MPFR_PROTO((mpz_t*, unsigned long)); __MPFR_DECLSPEC int mpfr_sincos_fast _MPFR_PROTO((mpfr_t, mpfr_t, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC double mpfr_scale2 _MPFR_PROTO((double, int)); __MPFR_DECLSPEC void mpfr_div_ui2 _MPFR_PROTO((mpfr_ptr, mpfr_srcptr, unsigned long int, unsigned long int, mpfr_rnd_t)); __MPFR_DECLSPEC void <API key> _MPFR_PROTO((mpfr_ptr, mpfr_ptr, mpfr_prec_t)); #if defined (__cplusplus) } #endif #endif
package net.paissad.waqtsalat.core.impl; import java.util.Calendar; import net.paissad.waqtsalat.core.WaqtSalatPackage; import net.paissad.waqtsalat.core.api.Pray; import net.paissad.waqtsalat.core.api.PrayName; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; /** * <!-- begin-user-doc --> An implementation of the model object ' <em><b>Pray</b></em>'. <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link net.paissad.waqtsalat.core.impl.PrayImpl#getName <em>Name</em>}</li> * <li>{@link net.paissad.waqtsalat.core.impl.PrayImpl#getTime <em>Time</em>}</li> * <li>{@link net.paissad.waqtsalat.core.impl.PrayImpl#isPlayingAdhan <em>Playing Adhan</em>}</li> * <li>{@link net.paissad.waqtsalat.core.impl.PrayImpl#getAdhanPlayer <em>Adhan Player</em>}</li> * </ul> * </p> * * @generated */ public class PrayImpl extends MinimalEObjectImpl.Container implements Pray { /** * The default value of the '{@link #getName() <em>Name</em>}' attribute. <!-- begin-user-doc --> <!-- end-user-doc * --> * * @see #getName() * @generated * @ordered */ protected static final PrayName NAME_EDEFAULT = PrayName.FADJR; /** * The cached value of the '{@link #getName() <em>Name</em>}' attribute. <!-- begin-user-doc --> <!-- end-user-doc * --> * * @see #getName() * @generated * @ordered */ protected PrayName name = NAME_EDEFAULT; /** * The default value of the '{@link #getTime() <em>Time</em>}' attribute. <!-- begin-user-doc --> <!-- end-user-doc * --> * * @see #getTime() * @generated * @ordered */ protected static final Calendar TIME_EDEFAULT = null; /** * The cached value of the '{@link #getTime() <em>Time</em>}' attribute. <!-- begin-user-doc --> <!-- end-user-doc * --> * * @see #getTime() * @generated * @ordered */ protected Calendar time = TIME_EDEFAULT; /** * The default value of the '{@link #isPlayingAdhan() <em>Playing Adhan</em>}' attribute. <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #isPlayingAdhan() * @generated * @ordered */ protected static final boolean <API key> = false; /** * The cached value of the '{@link #isPlayingAdhan() <em>Playing Adhan</em>}' attribute. <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #isPlayingAdhan() * @generated * @ordered */ protected boolean playingAdhan = <API key>; /** * The default value of the '{@link #getAdhanPlayer() <em>Adhan Player</em>}' attribute. <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getAdhanPlayer() * @generated * @ordered */ protected static final Object <API key> = null; /** * The cached value of the '{@link #getAdhanPlayer() <em>Adhan Player</em>}' attribute. <!-- begin-user-doc --> <!-- * end-user-doc --> * * @see #getAdhanPlayer() * @generated * @ordered */ protected Object adhanPlayer = <API key>; /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ protected PrayImpl() { super(); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override protected EClass eStaticClass() { return WaqtSalatPackage.Literals.PRAY; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public PrayName getName() { return name; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public void setName(PrayName newName) { PrayName oldName = name; name = newName == null ? NAME_EDEFAULT : newName; if (<API key>()) eNotify(new ENotificationImpl(this, Notification.SET, WaqtSalatPackage.PRAY__NAME, oldName, name)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public Calendar getTime() { return time; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public void setTime(Calendar newTime) { Calendar oldTime = time; time = newTime; if (<API key>()) eNotify(new ENotificationImpl(this, Notification.SET, WaqtSalatPackage.PRAY__TIME, oldTime, time)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public boolean isPlayingAdhan() { return playingAdhan; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public void setPlayingAdhan(boolean newPlayingAdhan) { boolean oldPlayingAdhan = playingAdhan; playingAdhan = newPlayingAdhan; if (<API key>()) eNotify(new ENotificationImpl(this, Notification.SET, WaqtSalatPackage.PRAY__PLAYING_ADHAN, oldPlayingAdhan, playingAdhan)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public Object getAdhanPlayer() { return adhanPlayer; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public void setAdhanPlayer(Object newAdhanPlayer) { Object oldAdhanPlayer = adhanPlayer; adhanPlayer = newAdhanPlayer; if (<API key>()) eNotify(new ENotificationImpl(this, Notification.SET, WaqtSalatPackage.PRAY__ADHAN_PLAYER, oldAdhanPlayer, adhanPlayer)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case WaqtSalatPackage.PRAY__NAME: return getName(); case WaqtSalatPackage.PRAY__TIME: return getTime(); case WaqtSalatPackage.PRAY__PLAYING_ADHAN: return isPlayingAdhan(); case WaqtSalatPackage.PRAY__ADHAN_PLAYER: return getAdhanPlayer(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case WaqtSalatPackage.PRAY__NAME: setName((PrayName) newValue); return; case WaqtSalatPackage.PRAY__TIME: setTime((Calendar) newValue); return; case WaqtSalatPackage.PRAY__PLAYING_ADHAN: setPlayingAdhan((Boolean) newValue); return; case WaqtSalatPackage.PRAY__ADHAN_PLAYER: setAdhanPlayer(newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case WaqtSalatPackage.PRAY__NAME: setName(NAME_EDEFAULT); return; case WaqtSalatPackage.PRAY__TIME: setTime(TIME_EDEFAULT); return; case WaqtSalatPackage.PRAY__PLAYING_ADHAN: setPlayingAdhan(<API key>); return; case WaqtSalatPackage.PRAY__ADHAN_PLAYER: setAdhanPlayer(<API key>); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case WaqtSalatPackage.PRAY__NAME: return name != NAME_EDEFAULT; case WaqtSalatPackage.PRAY__TIME: return TIME_EDEFAULT == null ? time != null : !TIME_EDEFAULT.equals(time); case WaqtSalatPackage.PRAY__PLAYING_ADHAN: return playingAdhan != <API key>; case WaqtSalatPackage.PRAY__ADHAN_PLAYER: return <API key> == null ? adhanPlayer != null : !<API key>.equals(adhanPlayer); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (name: "); //$NON-NLS-1$ result.append(name); result.append(", time: "); //$NON-NLS-1$ result.append(time); result.append(", playingAdhan: "); //$NON-NLS-1$ result.append(playingAdhan); result.append(", adhanPlayer: "); //$NON-NLS-1$ result.append(adhanPlayer); result.append(')'); return result.toString(); } } // PrayImpl
package xigua.battle.of.elements.model; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class IntWithMaxTest { private IntWithMax intWithMax; @Before public void setUp() { intWithMax = new IntWithMax(42); } @Test public void <API key>() { assertThat(intWithMax.getValue()).isEqualTo(42); } @Test public void <API key>() { intWithMax.setValue(100); assertThat(intWithMax.getValue()).isEqualTo(42); } @Test public void <API key>() { intWithMax.setValue(1); assertThat(intWithMax.getValue()).isEqualTo(1); } @Test public void <API key>() { assertThat(intWithMax.getMaxValue()).isEqualTo(42); } }
import { <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, SYNCING_NATIVE_MODE, DASHBOARD_UPDATE, <API key>, <API key>, <API key>, <API key>, <API key>, KV_HISTORY, <API key>, <API key>, <API key>, } from '../actions/storeType'; // TODO: refactor current coin props copy on change const defaults = { native: { coin: null, mode: null, send: false, receive: false, balance: 0, addresses: null, activeSection: 'default', showTransactionInfo: false, <API key>: null, txhistory: [], opids: null, lastSendToResponse: null, progress: null, rescanInProgress: false, <API key>: 0, net: { peers: null, totals: null, }, }, spv: { coin: null, mode: null, send: false, receive: false, balance: 0, addresses: null, activeSection: 'default', showTransactionInfo: false, <API key>: null, txhistory: [], lastSendToResponse: null, }, eth: { coin: null, mode: null, send: false, receive: false, balance: 0, addresses: null, activeSection: 'default', showTransactionInfo: false, <API key>: null, txhistory: [], lastSendToResponse: null, }, }; const checkCoinObjectKeys = (obj, mode) => { if (Object.keys(obj).length && mode) { for (let key in obj) { if (!defaults[mode].hasOwnProperty(key)) { delete obj[key]; } } } return obj; }; export const ActiveCoin = (state = { coins: { native: {}, spv: {}, eth: {}, }, coin: null, mode: null, send: false, receive: false, balance: 0, addresses: null, activeSection: 'default', showTransactionInfo: false, <API key>: null, txhistory: [], opids: null, lastSendToResponse: null, activeAddress: null, progress: null, rescanInProgress: false, <API key>: 0, net: { peers: null, totals: null, }, }, action) => { switch (action.type) { case <API key>: delete state.coins[action.mode][action.coin]; if (state.coin === action.coin) { return { state, defaults[action.mode], }; } else { return { state, }; } case <API key>: if (state.coins[action.mode] && state.coins[action.mode][action.coin]) { let _coins = state.coins; if (action.mode === state.mode) { const _coinData = state.coins[action.mode][action.coin]; const _coinDataToStore = checkCoinObjectKeys({ addresses: state.addresses, coin: state.coin, mode: state.mode, balance: state.balance, txhistory: state.txhistory, send: state.send, receive: state.receive, showTransactionInfo: state.showTransactionInfo, <API key>: state.<API key>, activeSection: state.activeSection, lastSendToResponse: state.lastSendToResponse, opids: state.mode === 'native' ? state.opids : null, activeAddress: state.activeAddress, progress: state.mode === 'native' ? state.progress : null, rescanInProgress: state.mode === 'native' ? state.rescanInProgress : false, <API key>: state.mode === 'native' ? state.<API key> : 0, net: state.mode === 'native' ? state.net : {}, }, action.mode); if (!action.skip) { _coins[action.mode][state.coin] = _coinDataToStore; } delete _coins.undefined; return { state, coins: _coins, checkCoinObjectKeys({ addresses: _coinData.addresses, coin: _coinData.coin, mode: _coinData.mode, balance: _coinData.balance, txhistory: _coinData.txhistory, send: _coinData.send, receive: _coinData.receive, showTransactionInfo: _coinData.showTransactionInfo, <API key>: _coinData.<API key>, activeSection: _coinData.activeSection, lastSendToResponse: _coinData.lastSendToResponse, opids: _coinData.mode === 'native' ? _coinData.opids : null, activeAddress: _coinData.activeAddress, progress: _coinData.mode === 'native' ? _coinData.progress : null, rescanInProgress: _coinData.mode === 'native' ? _coinData.rescanInProgress : false, <API key>: _coinData.mode === 'native' ? _coinData.<API key> : 0, net: _coinData.mode === 'native' ? _coinData.net : {}, }, _coinData.mode), }; } else { delete _coins.undefined; return { state, coins: state.coins, checkCoinObjectKeys({ coin: action.coin, mode: action.mode, balance: 0, addresses: null, txhistory: 'loading', send: false, receive: false, showTransactionInfo: false, <API key>: null, activeSection: 'default', progress: null, rescanInProgress: false, net: { peers: null, totals: null, }, }, action.mode), }; } } else { if (state.coin) { const _coinData = checkCoinObjectKeys({ addresses: state.addresses, coin: state.coin, mode: state.mode, balance: state.balance, txhistory: state.txhistory, send: state.send, receive: state.receive, showTransactionInfo: state.showTransactionInfo, <API key>: state.<API key>, activeSection: state.activeSection, lastSendToResponse: state.lastSendToResponse, opids: state.mode === 'native' ? state.opids : null, activeAddress: state.activeAddress, progress: state.mode === 'native' ? state.progress : null, rescanInProgress: state.mode === 'native' ? state.rescanInProgress : false, <API key>: state.mode === 'native' ? state.<API key> : 0, net: state.mode === 'native' ? state.net : {}, }, state.mode); let _coins = state.coins; if (!action.skip && _coins[action.mode]) { _coins[action.mode][state.coin] = _coinData; } return { state, coins: _coins, checkCoinObjectKeys({ coin: action.coin, mode: action.mode, balance: 0, addresses: null, txhistory: 'loading', send: false, receive: false, showTransactionInfo: false, <API key>: null, activeSection: 'default', progress: null, rescanInProgress: false, net: { peers: null, totals: null, }, }, action.mode), }; } else { return { state, checkCoinObjectKeys({ coin: action.coin, mode: action.mode, balance: 0, addresses: null, txhistory: 'loading', send: false, receive: false, showTransactionInfo: false, <API key>: null, activeSection: 'default', progress: null, rescanInProgress: false, net: { peers: null, totals: null, }, }, action.mode), }; } } case <API key>: return { state, balance: action.balance, }; case <API key>: return { state, txhistory: action.txhistory, }; case <API key>: return { state, balance: action.balance, }; case <API key>: return { state, send: action.send, receive: false, }; case <API key>: return { state, send: false, receive: action.receive, }; case <API key>: return { state, send: false, receive: false, }; case <API key>: return { state, addresses: action.addresses, }; case <API key>: return { state, activeSection: action.section, }; case <API key>: return { state, showTransactionInfo: action.showTransactionInfo, <API key>: action.<API key>, }; case <API key>: return { state, balance: action.balance, }; case <API key>: return { state, txhistory: action.txhistory, }; case <API key>: return { state, opids: action.opids, }; case <API key>: return { state, lastSendToResponse: action.lastSendToResponse, }; case <API key>: return { state, activeAddress: action.address, }; case SYNCING_NATIVE_MODE: return { state, progress: state.mode === 'native' ? action.progress : null, <API key>: typeof action.progress === 'string' && action.progress.indexOf('"code":-777') ? state.<API key> + 1 : 0, }; case <API key>: return { state, <API key>: state.<API key> + 1, }; case DASHBOARD_UPDATE: if (state.coin === action.coin) { return { state, opids: action.opids, txhistory: action.txhistory, balance: action.balance, addresses: action.addresses, rescanInProgress: action.rescanInProgress, }; } case <API key>: return { state, net: { peers: action.peers, totals: state.net.totals, }, }; case <API key>: return { state, net: { peers: state.net.peers, totals: action.totals, }, }; case <API key>: return { state, balance: action.balance, }; case <API key>: return { state, txhistory: action.txhistory, }; case <API key>: return { coins: { native: {}, spv: {}, eth: {}, }, coin: null, mode: null, balance: 0, addresses: null, txhistory: 'loading', send: false, receive: false, showTransactionInfo: false, <API key>: null, activeSection: 'default', progress: null, rescanInProgress: false, net: { peers: null, totals: null, }, <API key>: 0, }; default: return state; } } export default ActiveCoin;
#ifndef DATASOURCE_H #define DATASOURCE_H #include <QArray> #include <QVector3D> #include <QColor4ub> #include <QObject> #include <QVector2D> #include <QGLVertexBundle> #include <iostream> #include "databundle.h" using std::cerr; using std::endl; class DataSource : public QObject { Q_OBJECT public: DataSource(QObject *parent = 0); virtual QArray<DataBundle*> *dataBundles() { cerr << "Returning from abstract DataSource." "This should not happen." << endl; return 0; } }; #endif
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <volk_fft/volk_fft_prefs.h> //#if defined(_WIN32) //#include <Windows.h> //#endif void <API key>(char *path) { if (!path) return; const char *suffix = "/.volk_fft/volk_fft_config"; char *home = NULL; if (home == NULL) home = getenv("HOME"); if (home == NULL) home = getenv("APPDATA"); if (home == NULL){ path[0] = 0; return; } strcpy(path, home); strcat(path, suffix); } size_t <API key>(<API key> **prefs_res) { FILE *config_file; char path[512], line[512]; size_t n_arch_prefs = 0; <API key> *prefs = NULL; //get the config path <API key>(path); if (!path[0]) return n_arch_prefs; //no prefs found config_file = fopen(path, "r"); if(!config_file) return n_arch_prefs; //no prefs found //reset the file pointer and write the prefs into volk_fft_arch_prefs while(fgets(line, sizeof(line), config_file) != NULL) { prefs = (<API key> *) realloc(prefs, (n_arch_prefs+1) * sizeof(*prefs)); <API key> *p = prefs + n_arch_prefs; if(sscanf(line, "%s %s %s", p->name, p->impl_a, p->impl_u) == 3 && !strncmp(p->name, "volk_fft_", 5)) { n_arch_prefs++; } } fclose(config_file); *prefs_res = prefs; return n_arch_prefs; }
<!DOCTYPE html PUBLIC "- <html> <head> <title>Singular 2-0-4 Manual: D.6.2 ainvar_lib</title> <meta name="description" content="Singular 2-0-4 Manual: D.6.2 ainvar_lib"> <meta name="keywords" content="Singular 2-0-4 Manual: D.6.2 ainvar_lib"> <meta name="resource-type" content="document"> <meta name="distribution" content="global"> <meta name="Generator" content="texi2html"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <style type="text/css"> <! a.summary-letter {text-decoration: none} blockquote.smallquotation {font-size: smaller} div.display {margin-left: 3.2em} div.example {margin-left: 3.2em} div.lisp {margin-left: 3.2em} div.smalldisplay {margin-left: 3.2em} div.smallexample {margin-left: 3.2em} div.smalllisp {margin-left: 3.2em} pre.display {font-family: serif} pre.format {font-family: serif} pre.menu-comment {font-family: serif} pre.menu-preformatted {font-family: serif} pre.smalldisplay {font-family: serif; font-size: smaller} pre.smallexample {font-size: smaller} pre.smallformat {font-family: serif; font-size: smaller} pre.smalllisp {font-size: smaller} span.nocodebreak {white-space:pre} span.nolinebreak {white-space:pre} span.roman {font-family:serif; font-weight:normal} span.sansserif {font-family:sans-serif; font-weight:normal} ul.no-bullet {list-style: none} </style> </head> <body lang="en" background="../singular_images/Mybg.png"> <a name="ainvar_005flib"></a> <table border="0" cellpadding="0" cellspacing="0"> <tr valign="top"> <td align="left"> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr valign="top" align="left"> <td valign="middle" align="left"> <a href="index.htm"><img src="../singular_images/<API key>.png" width="50" border="0" alt="Top"></a> </td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="<API key>.html#<API key>" title="Previous section in reading order"><img src="../singular_images/a_left.png" border="0" alt="Back: D.6.1.31 image_of_variety" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="invariantRing.html#invariantRing" title="Next section in reading order"><img src="../singular_images/a_right.png" border="0" alt="Forward: D.6.2.1 invariantRing" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="SINGULAR-libraries.html#SINGULAR-libraries" title="Beginning of this chapter or previous chapter"><img src="../singular_images/a_leftdouble.png" border="0" alt="FastBack: Appendix D SINGULAR libraries" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="Release-Notes.html#Release-Notes" title="Next chapter"><img src="../singular_images/a_rightdouble.png" border="0" alt="FastForward: E Release Notes" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="Invariant-theory.html#Invariant-theory" title="Up section"><img src="../singular_images/a_up.png" border="0" alt="Up: D.6 Invariant theory" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="index.htm#Preface" title="Cover (top) of document"><img src="../singular_images/a_top.png" border="0" alt="Top: 1 Preface" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="sing_toc.htm#SEC_Contents" title="Table of contents"><img src="../singular_images/a_tableofcon.png" border="0" alt="Contents: Table of Contents" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="Index.html#Index" title="Index"><img src="../singular_images/a_index.png" border="0" alt="Index: F Index" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="sing_abt.htm#SEC_About" title="About (help)"><img src="../singular_images/a_help.png" border="0" alt="About: About This Document" align="middle"></a></td> </tr> </table> </td> <td align="left"> <a name="ainvar_005flib-1"></a> <h3 class="subsection">D.6.2 ainvar_lib</h3> <a name="<API key>"></a> <a name="<API key>"></a> <dl compact="compact"> <dt><strong>Library:</strong></dt> <dd><p>ainvar.lib </p></dd> <dt><strong>Purpose:</strong></dt> <dd><p> Invariant Rings of the Additive Group </p></dd> <dt><strong>Authors:</strong></dt> <dd><p>Gerhard Pfister (email: pfister@mathematik.uni-kl.de), Gert-Martin Greuel (email: greuel@mathematik.uni-kl.de) </p> </dd> </dl> <p><strong>Procedures:</strong> </p><blockquote><table class="menu" border="0" cellspacing="0"> <tr><td align="left" valign="top"><a href="invariantRing.html#invariantRing">D.6.2.1 invariantRing</a></td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> compute ring of invariants of (K,+)-action given by m </td></tr> <tr><td align="left" valign="top"><a href="derivate.html#derivate">D.6.2.2 derivate</a></td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> derivation of f with respect to the vector field m </td></tr> <tr><td align="left" valign="top"><a href="actionIsProper.html#actionIsProper">D.6.2.3 actionIsProper</a></td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> tests whether action defined by m is proper </td></tr> <tr><td align="left" valign="top"><a href="reduction.html#reduction">D.6.2.4 reduction</a></td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> SAGBI reduction of p in the subring generated by I </td></tr> <tr><td align="left" valign="top"><a href="completeReduction.html#completeReduction">D.6.2.5 completeReduction</a></td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> complete SAGBI reduction </td></tr> <tr><td align="left" valign="top"><a href="localInvar.html#localInvar">D.6.2.6 localInvar</a></td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> invariant polynomial under m computed from p,... </td></tr> <tr><td align="left" valign="top"><a href="furtherInvar.html#furtherInvar">D.6.2.7 furtherInvar</a></td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> compute further invariants of m from the given ones </td></tr> <tr><td align="left" valign="top"><a href="sortier.html#sortier">D.6.2.8 sortier</a></td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> sorts generators of id by increasing leading terms </td></tr> </table></blockquote> </td> </tr> </table> <hr> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr><td valign="middle" align="left"> <a href="index.htm"><img src="../singular_images/<API key>.png" width="50" border="0" alt="Top"></a> </td> <td valign="middle" align="left"><a href="<API key>.html#<API key>" title="Previous section in reading order"><img src="../singular_images/a_left.png" border="0" alt="Back: D.6.1.31 image_of_variety" align="middle"></a></td> <td valign="middle" align="left"><a href="invariantRing.html#invariantRing" title="Next section in reading order"><img src="../singular_images/a_right.png" border="0" alt="Forward: D.6.2.1 invariantRing" align="middle"></a></td> <td valign="middle" align="left"><a href="SINGULAR-libraries.html#SINGULAR-libraries" title="Beginning of this chapter or previous chapter"><img src="../singular_images/a_leftdouble.png" border="0" alt="FastBack: Appendix D SINGULAR libraries" align="middle"></a></td> <td valign="middle" align="left"><a href="Release-Notes.html#Release-Notes" title="Next chapter"><img src="../singular_images/a_rightdouble.png" border="0" alt="FastForward: E Release Notes" align="middle"></a></td> <td valign="middle" align="left"><a href="Invariant-theory.html#Invariant-theory" title="Up section"><img src="../singular_images/a_up.png" border="0" alt="Up: D.6 Invariant theory" align="middle"></a></td> <td valign="middle" align="left"><a href="index.htm#Preface" title="Cover (top) of document"><img src="../singular_images/a_top.png" border="0" alt="Top: 1 Preface" align="middle"></a></td> <td valign="middle" align="left"><a href="sing_toc.htm#SEC_Contents" title="Table of contents"><img src="../singular_images/a_tableofcon.png" border="0" alt="Contents: Table of Contents" align="middle"></a></td> <td valign="middle" align="left"><a href="Index.html#Index" title="Index"><img src="../singular_images/a_index.png" border="0" alt="Index: F Index" align="middle"></a></td> <td valign="middle" align="left"><a href="sing_abt.htm#SEC_About" title="About (help)"><img src="../singular_images/a_help.png" border="0" alt="About: About This Document" align="middle"></a></td> </tr></table> <font size="-1"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; User manual for <a href="http: generated by <a href="http: </font> </body> </html>
package ninja.mbedded.ninjaterm.util.rxProcessing.timeStamp; import javafx.scene.paint.Color; import ninja.mbedded.ninjaterm.JavaFXThreadingRule; import ninja.mbedded.ninjaterm.util.rxProcessing.streamedData.StreamedData; import ninja.mbedded.ninjaterm.util.rxProcessing.streamingFilter.StreamingFilter; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.time.Instant; import java.time.ZoneId; import static org.junit.Assert.assertEquals; public class <API key> { /** * Including this variable in class allows JavaFX objects to be created in tests. */ @Rule public JavaFXThreadingRule javafxRule = new JavaFXThreadingRule(); private TimeStampParser timeStampParser; private StreamedData inputStreamedData; private StreamedData outputStreamedData; @Before public void setUp() throws Exception { timeStampParser = new TimeStampParser("EOL"); inputStreamedData = new StreamedData(); outputStreamedData = new StreamedData(); } @Test public void firstCharTest() throws Exception { inputStreamedData.append("abc"); timeStampParser.parse(inputStreamedData, outputStreamedData); // Check input assertEquals("", inputStreamedData.getText()); // Check output assertEquals("abc", outputStreamedData.getText()); assertEquals(1, outputStreamedData.getTimeStampMarkers().size()); assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos); } @Test public void oneNewLineTest() throws Exception { inputStreamedData.append("abcEOLd"); timeStampParser.parse(inputStreamedData, outputStreamedData); // Check input assertEquals("", inputStreamedData.getText()); // Check output assertEquals("abcEOLd", outputStreamedData.getText()); assertEquals(2, outputStreamedData.getTimeStampMarkers().size()); assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos); assertEquals(6, outputStreamedData.getTimeStampMarkers().get(1).charPos); } @Test public void temporalTest() throws Exception { inputStreamedData.append("abcEOL"); timeStampParser.parse(inputStreamedData, outputStreamedData); // Check input assertEquals("", inputStreamedData.getText()); // Check output assertEquals("abcEOL", outputStreamedData.getText()); assertEquals(1, outputStreamedData.getTimeStampMarkers().size()); assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos); // Sleep enough that the next TimeStamp is guaranteed to be greater than // the first (delay must be larger than the min. LocalDateTime resolution) Thread.sleep(10); inputStreamedData.append("d"); timeStampParser.parse(inputStreamedData, outputStreamedData); // Check input assertEquals("", inputStreamedData.getText()); // Check output assertEquals("abcEOLd", outputStreamedData.getText()); assertEquals(2, outputStreamedData.getTimeStampMarkers().size()); assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos); assertEquals(6, outputStreamedData.getTimeStampMarkers().get(1).charPos); // Check time Instant time0 = outputStreamedData.getTimeStampMarkers().get(0).localDateTime.atZone(ZoneId.systemDefault()).toInstant(); Instant time1 = outputStreamedData.getTimeStampMarkers().get(1).localDateTime.atZone(ZoneId.systemDefault()).toInstant(); assertEquals(true, time1.isAfter(time0)); } @Test public void partialLineTest() throws Exception { inputStreamedData.append("123EO"); timeStampParser.parse(inputStreamedData, outputStreamedData); // Check input assertEquals("EO", inputStreamedData.getText()); // Check output assertEquals("123", outputStreamedData.getText()); assertEquals(1, outputStreamedData.getTimeStampMarkers().size()); assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos); inputStreamedData.append("L456"); timeStampParser.parse(inputStreamedData, outputStreamedData); // Check input assertEquals("", inputStreamedData.getText()); // Check output assertEquals("123EOL456", outputStreamedData.getText()); assertEquals(2, outputStreamedData.getTimeStampMarkers().size()); assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos); assertEquals(6, outputStreamedData.getTimeStampMarkers().get(1).charPos); } // @Test // public void multipleLinesTest() throws Exception { // inputStreamedData.append("abcEOLabcEOLdefEOL"); // inputStreamedData.addNewLineMarkerAt(6); // inputStreamedData.addNewLineMarkerAt(12); // inputStreamedData.addNewLineMarkerAt(18); // streamingFilter.parse(inputStreamedData, outputStreamedData); // // Check input. Since "defEOL" counts as a valid line, but has no match, // // it should be removed from the input // assertEquals("", inputStreamedData.getText()); // assertEquals(0, inputStreamedData.getColourMarkers().size()); // // Check output // assertEquals("abcEOLabcEOL", outputStreamedData.getText()); // assertEquals(0, outputStreamedData.getColourMarkers().size()); // assertEquals(2, outputStreamedData.getNewLineMarkers().size()); // assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue()); // assertEquals(12, outputStreamedData.getNewLineMarkers().get(1).intValue()); // @Test // public void <API key>() throws Exception { // inputStreamedData.append("abcEOLdefEOLabcEOL"); // inputStreamedData.addNewLineMarkerAt(6); // inputStreamedData.addNewLineMarkerAt(12); // inputStreamedData.addNewLineMarkerAt(18); // streamingFilter.parse(inputStreamedData, outputStreamedData); // // Check input. Since "defEOL" counts as a valid line, but has no match, // // it should be removed from the input // assertEquals("", inputStreamedData.getText()); // assertEquals(0, inputStreamedData.getColourMarkers().size()); // // Check output // assertEquals("abcEOLabcEOL", outputStreamedData.getText()); // assertEquals(0, outputStreamedData.getColourMarkers().size()); // assertEquals(2, outputStreamedData.getNewLineMarkers().size()); // assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue()); // assertEquals(12, outputStreamedData.getNewLineMarkers().get(1).intValue()); // @Test // public void streamTest() throws Exception { // inputStreamedData.append("ab"); // streamingFilter.parse(inputStreamedData, outputStreamedData); // assertEquals("", inputStreamedData.getText()); // assertEquals("ab", outputStreamedData.getText()); // inputStreamedData.append("cEOL"); // inputStreamedData.addNewLineMarkerAt(4); // streamingFilter.parse(inputStreamedData, outputStreamedData); // assertEquals("", inputStreamedData.getText()); // assertEquals(0, inputStreamedData.getNewLineMarkers().size()); // // Check output // assertEquals("abcEOL", outputStreamedData.getText()); // assertEquals(1, outputStreamedData.getNewLineMarkers().size()); // assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue()); // @Test // public void <API key>() throws Exception { // inputStreamedData.append("ab"); // streamingFilter.parse(inputStreamedData, outputStreamedData); // // Check input // assertEquals("", inputStreamedData.getText()); // // Check output // assertEquals("ab", outputStreamedData.getText()); // inputStreamedData.append("cEOLde"); // inputStreamedData.addNewLineMarkerAt(4); // streamingFilter.parse(inputStreamedData, outputStreamedData); // // Check input // assertEquals(inputStreamedData.getText(), "de"); // // Check output // assertEquals("abcEOL", outputStreamedData.getText()); // assertEquals(1, outputStreamedData.getNewLineMarkers().size()); // assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue()); // inputStreamedData.append("fEOLa"); // inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length() - 1); // streamingFilter.parse(inputStreamedData, outputStreamedData); // // Check input // assertEquals(inputStreamedData.getText(), ""); // assertEquals(0, inputStreamedData.getNewLineMarkers().size()); // // Check output // assertEquals("abcEOLa", outputStreamedData.getText()); // assertEquals(1, outputStreamedData.getNewLineMarkers().size()); // assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue()); // inputStreamedData.append("bcEOL"); // inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length()); // streamingFilter.parse(inputStreamedData, outputStreamedData); // // Check input // assertEquals(inputStreamedData.getText(), ""); // assertEquals(0, inputStreamedData.getNewLineMarkers().size()); // // Check output // assertEquals("abcEOLabcEOL", outputStreamedData.getText()); // assertEquals(2, outputStreamedData.getNewLineMarkers().size()); // assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue()); // assertEquals(12, outputStreamedData.getNewLineMarkers().get(1).intValue()); // @Test // public void <API key>() throws Exception { // inputStreamedData.append("abcEOL"); // inputStreamedData.addColour(2, Color.RED); // inputStreamedData.addNewLineMarkerAt(6); // streamingFilter.parse(inputStreamedData, outputStreamedData); // // Check output // assertEquals("abcEOL", outputStreamedData.getText()); // assertEquals(1, outputStreamedData.getColourMarkers().size()); // assertEquals(2, outputStreamedData.getColourMarkers().get(0).position); // assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color); // assertEquals(1, outputStreamedData.getNewLineMarkers().size()); // assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue()); // @Test // public void complexNodesTest() throws Exception { // inputStreamedData.append("abcdefEOL"); // inputStreamedData.addColour(2, Color.RED); // inputStreamedData.addColour(3, Color.GREEN); // inputStreamedData.addNewLineMarkerAt(9); // streamingFilter.parse(inputStreamedData, outputStreamedData); // assertEquals("abcdefEOL", outputStreamedData.getText()); // assertEquals(2, outputStreamedData.getColourMarkers().size()); // assertEquals(2, outputStreamedData.getColourMarkers().get(0).position); // assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color); // assertEquals(3, outputStreamedData.getColourMarkers().get(1).position); // assertEquals(Color.GREEN, outputStreamedData.getColourMarkers().get(1).color); // assertEquals(1, outputStreamedData.getNewLineMarkers().size()); // assertEquals(9, outputStreamedData.getNewLineMarkers().get(0).intValue()); // @Test // public void complexNodes2Test() throws Exception { // inputStreamedData.append("abcEOL"); // inputStreamedData.addColour(2, Color.RED); // inputStreamedData.addNewLineMarkerAt(6); // streamingFilter.parse(inputStreamedData, outputStreamedData); // assertEquals("abcEOL", outputStreamedData.getText()); // assertEquals(1, outputStreamedData.getColourMarkers().size()); // assertEquals(2, outputStreamedData.getColourMarkers().get(0).position); // assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color); // assertEquals(1, outputStreamedData.getNewLineMarkers().size()); // assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue()); // inputStreamedData.append("defEOL"); // inputStreamedData.addColour(0, Color.GREEN); // inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length()); // streamingFilter.parse(inputStreamedData, outputStreamedData); // assertEquals("abcEOL", outputStreamedData.getText()); // assertEquals(1, outputStreamedData.getColourMarkers().size()); // assertEquals(2, outputStreamedData.getColourMarkers().get(0).position); // assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color); // assertEquals(1, outputStreamedData.getNewLineMarkers().size()); // assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue()); // @Test // public void bigTest() throws Exception { // streamingFilter.setFilterPattern("d"); // inputStreamedData.append("re"); // inputStreamedData.addColour(0, Color.RED); // streamingFilter.parse(inputStreamedData, outputStreamedData); // assertEquals("", outputStreamedData.getText()); // assertEquals(0, outputStreamedData.getColourMarkers().size()); // inputStreamedData.append("dEOL"); // inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length()); // streamingFilter.parse(inputStreamedData, outputStreamedData); // assertEquals("redEOL", outputStreamedData.getText()); // assertEquals(1, outputStreamedData.getColourMarkers().size()); // assertEquals(0, outputStreamedData.getColourMarkers().get(0).position); // assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color); // streamingFilter.parse(inputStreamedData, outputStreamedData); // // Nothing should of changed // assertEquals("redEOL", outputStreamedData.getText()); // assertEquals(1, outputStreamedData.getColourMarkers().size()); // assertEquals(0, outputStreamedData.getColourMarkers().get(0).position); // assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color); // inputStreamedData.append("greenEOL"); // inputStreamedData.addColour(inputStreamedData.getText().length() - 8, Color.GREEN); // inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length()); // inputStreamedData.append("redEOL"); // inputStreamedData.addColour(inputStreamedData.getText().length() - 6, Color.RED); // inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length()); // inputStreamedData.append("greenEOL"); // inputStreamedData.addColour(inputStreamedData.getText().length() - 8, Color.GREEN); // inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length()); // streamingFilter.parse(inputStreamedData, outputStreamedData); // assertEquals("redEOLredEOL", outputStreamedData.getText()); // assertEquals(2, outputStreamedData.getColourMarkers().size()); // assertEquals(0, outputStreamedData.getColourMarkers().get(0).position); // assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color); // assertEquals(6, outputStreamedData.getColourMarkers().get(1).position); // assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(1).color); }
// urlParams is null when used for embedding window.urlParams = window.urlParams || {}; // isLocalStorage controls access to local storage window.isLocalStorage = window.isLocalStorage || false; // Checks for SVG support window.isSvgBrowser = window.isSvgBrowser || (navigator.userAgent.indexOf('MSIE') < 0 || document.documentMode >= 9); // CUSTOM_PARAMETERS - URLs for save and export window.EXPORT_URL = window.EXPORT_URL || 'https://exp.draw.io/ImageExport4/export'; window.SAVE_URL = window.SAVE_URL || 'save'; window.OPEN_URL = window.OPEN_URL || 'open'; window.PROXY_URL = window.PROXY_URL || 'proxy'; // Paths and files window.SHAPES_PATH = window.SHAPES_PATH || 'shapes'; // Path for images inside the diagram window.GRAPH_IMAGE_PATH = window.GRAPH_IMAGE_PATH || 'img'; window.ICONSEARCH_PATH = window.ICONSEARCH_PATH || (navigator.userAgent.indexOf('MSIE') >= 0 || urlParams['dev']) ? 'iconSearch' : 'https: window.TEMPLATE_PATH = window.TEMPLATE_PATH || '/templates'; // Directory for i18 files and basename for main i18n file window.RESOURCES_PATH = window.RESOURCES_PATH || 'resources'; window.RESOURCE_BASE = window.RESOURCE_BASE || RESOURCES_PATH + '/dia'; // URL for logging window.DRAWIO_LOG_URL = window.DRAWIO_LOG_URL || ''; // Sets the base path, the UI language via URL param and configures the // supported languages to avoid 404s. The loading of all core language // resources is disabled as all required resources are in grapheditor. // properties. Note that in this example the loading of two resource // files (the special bundle and the default bundle) is disabled to // save a GET request. This requires that all resources be present in // the special bundle. window.mxLoadResources = window.mxLoadResources || false; window.mxLanguage = window.mxLanguage || (function() { var lang = (urlParams['offline'] == '1') ? 'en' : urlParams['lang']; // Known issue: No JSON object at this point in quirks in IE8 if (lang == null && typeof(JSON) != 'undefined') { // Cannot use mxSettings here if (isLocalStorage) { try { var value = localStorage.getItem('.drawio-config'); if (value != null) { lang = JSON.parse(value).language || null; } } catch (e) { // cookies are disabled, attempts to use local storage will cause // a DOM error at a minimum on Chrome isLocalStorage = false; } } } return lang; })(); // Add new languages here. First entry is translated to [Automatic] // in the menu defintion in Diagramly.js. window.mxLanguageMap = window.mxLanguageMap || { 'i18n': '', 'id' : 'Bahasa Indonesia', 'ms' : 'Bahasa Melayu', 'bs' : 'Bosanski', 'ca' : 'Català', 'cs' : 'Čeština', 'da' : 'Dansk', 'de' : 'Deutsch', 'et' : 'Eesti', 'en' : 'English', 'es' : 'Español', 'eo' : 'Esperanto', 'fil' : 'Filipino', 'fr' : 'Français', 'it' : 'Italiano', 'hu' : 'Magyar', 'nl' : 'Nederlands', 'no' : 'Norsk', 'pl' : 'Polski', 'pt-br' : 'Português (Brasil)', 'pt' : 'Português (Portugal)', 'ro' : 'Română', 'fi' : 'Suomi', 'sv' : 'Svenska', 'vi' : 'Tiếng Việt', 'tr' : 'Türkçe', 'el' : 'Ελληνικά', 'ru' : 'Русский', 'sr' : 'Српски', 'uk' : 'Українська', 'he' : 'עברית', 'ar' : 'العربية', 'th' : 'ไทย', 'ko' : '', 'ja' : '', 'zh' : '', 'zh-tw' : '' }; if (typeof window.mxBasePath === 'undefined') { window.mxBasePath = 'mxgraph'; } if (window.mxLanguages == null) { window.mxLanguages = []; // Populates the list of supported special language bundles for (var lang in mxLanguageMap) { // Empty means default (ie. browser language), "en" means English (default for unsupported languages) // Since "en" uses no extension this must not be added to the array of supported language bundles. if (lang != 'en') { window.mxLanguages.push(lang); } } } /** * Returns the global UI setting before runngin static draw.io code */ window.uiTheme = window.uiTheme || (function() { var ui = urlParams['ui']; // Known issue: No JSON object at this point in quirks in IE8 if (ui == null && typeof JSON !== 'undefined') { // Cannot use mxSettings here if (isLocalStorage) { try { var value = localStorage.getItem('.drawio-config'); if (value != null) { ui = JSON.parse(value).ui || null; } } catch (e) { // cookies are disabled, attempts to use local storage will cause // a DOM error at a minimum on Chrome isLocalStorage = false; } } } return ui; })(); /** * Global function for loading local files via servlet */ function setCurrentXml(data, filename) { if (window.parent != null && window.parent.openFile != null) { window.parent.openFile.setData(data, filename); } }; /** * Overrides splash URL parameter via local storage */ (function() { // Known issue: No JSON object at this point in quirks in IE8 if (typeof JSON !== 'undefined') { // Cannot use mxSettings here if (isLocalStorage) { try { var value = localStorage.getItem('.drawio-config'); var showSplash = true; if (value != null) { showSplash = JSON.parse(value).showStartScreen; } // Undefined means true if (showSplash == false) { urlParams['splash'] = '0'; } } catch (e) { // ignore } } } })(); // Customizes export URL var ex = urlParams['export']; if (ex != null) { if (ex.substring(0, 7) != 'http: { ex = 'http: } EXPORT_URL = ex; } // Enables offline mode if (urlParams['offline'] == '1' || urlParams['demo'] == '1' || urlParams['stealth'] == '1' || urlParams['local'] == '1') { urlParams['analytics'] = '0'; urlParams['picker'] = '0'; urlParams['gapi'] = '0'; urlParams['db'] = '0'; urlParams['od'] = '0'; urlParams['gh'] = '0'; } // Disables math in offline mode if (urlParams['offline'] == '1' || urlParams['local'] == '1') { urlParams['math'] = '0'; } // Lightbox enabled chromeless mode if (urlParams['lightbox'] == '1') { urlParams['chrome'] = '0'; } // Adds hard-coded logging domain for draw.io domains var host = window.location.host; var searchString = 'draw.io'; var position = host.length - searchString.length; var lastIndex = host.lastIndexOf(searchString, position); if (lastIndex !== -1 && lastIndex === position && host != 'test.draw.io') { // endsWith polyfill window.DRAWIO_LOG_URL = 'https://log.draw.io'; }
<div class="col-lg-6 col-12"> <section widget class="widget <API key>"> <header> <div class="row"> <div class="col-3"> <h6> Total Sales </h6> <p class="value5"> January, 2014 </p> </div> <div class="col-3"> <h5> <small>Best</small> </h5> <p class="value6 fs-sm"> March, 2013 + 1 </p> </div> </div> <div class="widget-controls"> <a href="#"><i class="glyphicon glyphicon-cog"></i></a> <a href="#" data-widgster="close"><i class="glyphicon glyphicon-remove"></i></a> </div> </header> <div class="widget-body"> <div class="chart-stats"> <p class="text-muted fs-mini mt-xs"> <i class="fa fa-map-marker fa-5x pull-left"></i> <span class="fw-semi-bold text-gray-dark">Jess:</span> Seems like statically it's getting impossible to achieve any sort of results in nearest future. The only thing we can hope for is pressing one of these two buttons: </p> <div class="btn-toolbar"> <button class="btn btn-xs btn-success">Accept</button> <button class="btn btn-xs btn-default">Reject</button> </div> </div> <div class="chart bg-body-light"> <div flot-chart [data]="generateRandomData([{ label: 'Visitors', color: configFn.darkenColor(config.settings.colors['gray-lighter'], .05) },{ label: 'Charts', color: config.settings.colors['brand-danger'] }])" class="chart-inner"></div> </div> </div> </section> </div> <div class="col-lg-6 col-12"> <section widget class="widget <API key>"> <header> <h6 class="mb-0"> <span class="fw-semi-bold">Budget</span> <span class="badge badge-pill badge-danger">2017</span> </h6> <span class="text-muted fs-mini">monthly report will be available in <a href="#">6 hours</a></span> <div class="widget-controls"> <a href="#"><i class="glyphicon glyphicon-cog"></i></a> <a href="#" data-widgster="close"><i class="glyphicon glyphicon-remove"></i></a> </div> </header> <div class="widget-body"> <div class="chart-stats"> <div class="row"> <div class="col-md-5"> <div class="clearfix m-t-1"> <h6 class="pull-left text-muted mb-xs"> Income </h6> <p class="pull-right h6 mb-xs"> <span class="fw-semi-bold">$14,595</span> </p> </div> <div class="clearfix"> <h6 class="pull-left m-0 text-muted"> Recent </h6> <p class="pull-right"> <span class="fw-semi-bold">$7,647</span> </p> </div> </div> <div class="col-md-3 text-right m-t-1"> <h6 class="text-muted mb-xs">Inqueries</h6> <p class="fw-semi-bold">73 at 14am</p> </div> <div class="col-md-4 text-right m-t-1"> <h6 class="text-muted mb-xs">Last Updated</h6> <p class="fw-semi-bold">23.06.2013</p> </div> </div> </div> <div class="chart bg-body-light"> <div flot-chart [data] = "generateRandomData([{ label: 'Controllers', color: '#777' },{ label: 'Scopes', color: config.settings.colors['brand-warning'] }])" class="chart-inner"></div> </div> </div> </section> </div>
#include "Worker2.h" #include "Csoft.h" using namespace csoft::mod2; Worker2::Worker2(const csoft::Csoft * csoft) { } Worker2::Worker2(const Worker2& orig) { } Worker2::~Worker2() { } void Worker2::doIt(void) { BOOST_LOG_SEV(lg, boost::log::trivial::info) << __PRETTY_FUNCTION__ << "---> Begin"; BOOST_LOG_SEV(lg, boost::log::trivial::info) << __PRETTY_FUNCTION__ << "<--- End"; }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace YSchool { public class Person { public int id; public string name ; public int gender; public string birthDate;//"1900-00-00T00:00:00" public int mobileNumber; public int altMobileNumber; public string fatherName; public string motherName; public int batchType; } }
var chai = require('chai') , sinon = require('sinon') , sinonChai = require('sinon-chai') , expect = chai.expect , Promise = require('es6-promise').Promise , <API key> = require('../../../platypi-cli/controllers/cli/updatetemplates.controller'); chai.use(sinonChai); describe('TemplateUpdate controller', function () { it('should return a new controller', function (done) { try { var controller = new <API key>({ viewStuff: 'fakeview' }); expect(controller).to.be.an.object; expect(controller.model).to.be.an.object; expect(controller.view).to.be.an.object; expect(controller.view.model).to.equal(controller.model); done(); } catch (e) { done(e); } }); describe('getResponseView method', function () { var sandbox, controller, updateFunc; beforeEach(function (done) { sandbox = sinon.sandbox.create(); controller = new <API key>({ viewStuff: 'fakeview' }); updateFunc = sandbox.stub(controller.__provider, 'update'); done(); }); afterEach(function (done) { sandbox.restore(); done(); }); it('should call the clean method and return the view', function (done) { updateFunc.returns(Promise.resolve('')); controller.getResponseView().then(function (view) { try { expect(updateFunc).to.have.been.called; expect(controller.model.successMessage).not.to.equal(''); expect(view).to.exist; done(); } catch (e) { done(e); } }, function (err) { done(err); }); }); it('should call the update method and throw an error', function (done) { updateFunc.returns(Promise.reject('Err')); controller.getResponseView().then(function (view) { try { expect(updateFunc).to.have.been.called; expect(controller.model.errorMessage).not.to.equal(''); expect(view).to.exist; done(); } catch (e) { done(e); } }, function (err) { done(err); }); }); }); });
""" Class that contains client access to the transformation DB handler. """ __RCSID__ = "$Id$" import types from DIRAC import S_OK, S_ERROR, gLogger from DIRAC.Core.Base.Client import Client from DIRAC.Core.Utilities.List import breakListIntoChunks from DIRAC.Resources.Catalog.FileCatalogueBase import FileCatalogueBase from DIRAC.ConfigurationSystem.Client.Helpers.Operations import Operations rpc = None url = None class <API key>( Client, FileCatalogueBase ): """ Exposes the functionality available in the DIRAC/<API key> This inherits the DIRAC base Client for direct execution of server functionality. The following methods are available (although not visible here). Transformation (table) manipulation <API key>(transName) <API key>(transName,paramNames) <API key>(status) <API key>(transName,paramName,paramValue) <API key>(transName,paramName) TransformationFiles table manipulation <API key>(transName,lfns) <API key>(transName,lfns=[],se='Unknown') <API key>(transName) TransformationTasks table manipulation setTaskStatus(transName, taskID, status) <API key>(transName, taskID, status, taskWmsID) <API key>(transName) deleteTasks(transName, taskMin, taskMax) <API key>( transName, nTasks) getTasksToSubmit(transName,numTasks,site='') <API key> table manipulation <API key>(transName) File/directory manipulation methods (the remainder of the interface can be found below) getFileSummary(lfns) exists(lfns) Web monitoring tools <API key>(attribute, selectDict) <API key>() <API key>() <API key>(selectDict, sortList, startItem, maxItems) """ def __init__( self, **kwargs ): Client.__init__( self, **kwargs ) opsH = Operations() self.maxResetCounter = opsH.getValue( 'Productions/<API key>', 10 ) self.setServer( 'Transformation/<API key>' ) def setServer( self, url ): self.serverURL = url def getCounters( self, table, attrList, condDict, older = None, newer = None, timeStamp = None, rpc = '', url = '' ): rpcClient = self._getRPC( rpc = rpc, url = url ) return rpcClient. getCounters( table, attrList, condDict, older, newer, timeStamp ) def addTransformation( self, transName, description, longDescription, transType, plugin, agentType, fileMask, transformationGroup = 'General', groupSize = 1, inheritedFrom = 0, body = '', maxTasks = 0, eventsPerTask = 0, addFiles = True, rpc = '', url = '', timeout = 1800 ): """ add a new transformation """ rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) return rpcClient.addTransformation( transName, description, longDescription, transType, plugin, agentType, fileMask, transformationGroup, groupSize, inheritedFrom, body, maxTasks, eventsPerTask, addFiles ) def getTransformations( self, condDict = {}, older = None, newer = None, timeStamp = 'CreationDate', orderAttribute = None, limit = 100, extraParams = False, rpc = '', url = '', timeout = None ): """ gets all the transformations in the system, incrementally. "limit" here is just used to determine the offset. """ rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) transformations = [] # getting transformations - incrementally offsetToApply = 0 while True: res = rpcClient.getTransformations( condDict, older, newer, timeStamp, orderAttribute, limit, extraParams, offsetToApply ) if not res['OK']: return res else: gLogger.verbose( "Result for limit %d, offset %d: %d" % ( limit, offsetToApply, len( res['Value'] ) ) ) if res['Value']: transformations = transformations + res['Value'] offsetToApply += limit if len( res['Value'] ) < limit: break return S_OK( transformations ) def getTransformation( self, transName, extraParams = False, rpc = '', url = '', timeout = None ): rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) return rpcClient.getTransformation( transName, extraParams ) def <API key>( self, condDict = {}, older = None, newer = None, timeStamp = 'LastUpdate', orderAttribute = None, limit = 10000, rpc = '', url = '', timeout = 1800 ): """ gets all the transformation files for a transformation, incrementally. "limit" here is just used to determine the offset. """ rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) transformationFiles = [] # getting transformationFiles - incrementally offsetToApply = 0 while True: res = rpcClient.<API key>( condDict, older, newer, timeStamp, orderAttribute, limit, offsetToApply ) if not res['OK']: return res else: gLogger.verbose( "Result for limit %d, offset %d: %d" % ( limit, offsetToApply, len( res['Value'] ) ) ) if res['Value']: transformationFiles = transformationFiles + res['Value'] offsetToApply += limit if len( res['Value'] ) < limit: break return S_OK( transformationFiles ) def <API key>( self, condDict = {}, older = None, newer = None, timeStamp = 'CreationTime', orderAttribute = None, limit = 10000, inputVector = False, rpc = '', url = '', timeout = None ): """ gets all the transformation tasks for a transformation, incrementally. "limit" here is just used to determine the offset. """ rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) transformationTasks = [] # getting transformationFiles - incrementally offsetToApply = 0 while True: res = rpcClient.<API key>( condDict, older, newer, timeStamp, orderAttribute, limit, inputVector, offsetToApply ) if not res['OK']: return res else: gLogger.verbose( "Result for limit %d, offset %d: %d" % ( limit, offsetToApply, len( res['Value'] ) ) ) if res['Value']: transformationTasks = transformationTasks + res['Value'] offsetToApply += limit if len( res['Value'] ) < limit: break return S_OK( transformationTasks ) def cleanTransformation( self, transID, rpc = '', url = '', timeout = None ): """ Clean the transformation, and set the status parameter (doing it here, for easier extensibility) """ # Cleaning rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) res = rpcClient.cleanTransformation( transID ) if not res['OK']: return res # Setting the status return self.<API key>( transID, 'Status', '<API key>' ) def <API key>( self, transDict, resetUnused = True ): """ move files input to a transformation, to the derived one """ prod = transDict['TransformationID'] parentProd = int( transDict.get( 'InheritedFrom', 0 ) ) movedFiles = {} if not parentProd: gLogger.warn( "[None] [%d] .<API key>: Transformation was not derived..." % prod ) return S_OK( ( parentProd, movedFiles ) ) # get the lfns in status Unused/MaxReset of the parent production res = self.<API key>( condDict = {'TransformationID': parentProd, 'Status': [ 'Unused', 'MaxReset' ]} ) if not res['OK']: gLogger.error( "[None] [%d] .<API key>: Error getting Unused files from transformation %s:" % ( prod, parentProd ), res['Message'] ) return res parentFiles = res['Value'] lfns = [lfnDict['LFN'] for lfnDict in parentFiles] if not lfns: gLogger.info( "[None] [%d] .<API key>: No files found to be moved from transformation %d" % ( prod, parentProd ) ) return S_OK( ( parentProd, movedFiles ) ) # get the lfns of the derived production that were Unused/MaxReset in the parent one res = self.<API key>( condDict = { 'TransformationID': prod, 'LFN': lfns} ) if not res['OK']: gLogger.error( "[None] [%d] .<API key>: Error getting files from derived transformation" % prod, res['Message'] ) return res derivedFiles = res['Value'] suffix = '-%d' % parentProd derivedStatusDict = dict( [( derivedDict['LFN'], derivedDict['Status'] ) for derivedDict in derivedFiles] ) newStatusFiles = {} parentStatusFiles = {} force = False for parentDict in parentFiles: lfn = parentDict['LFN'] derivedStatus = derivedStatusDict.get( lfn ) if derivedStatus: parentStatus = parentDict['Status'] if resetUnused and parentStatus == 'MaxReset': status = 'Unused' moveStatus = 'Unused from MaxReset' force = True else: status = parentStatus moveStatus = parentStatus if derivedStatus.endswith( suffix ): # This file is Unused or MaxReset while it was most likely Assigned at the time of derivation parentStatusFiles.setdefault( 'Moved-%s' % str( prod ), [] ).append( lfn ) newStatusFiles.setdefault( ( status, parentStatus ), [] ).append( lfn ) movedFiles[moveStatus] = movedFiles.setdefault( moveStatus, 0 ) + 1 elif parentDict['Status'] == 'Unused': # If the file was Unused already at derivation time, set it NotProcessed parentStatusFiles.setdefault( 'NotProcessed', [] ).append( lfn ) # Set the status in the parent transformation first for status, lfnList in parentStatusFiles.items(): for lfnChunk in breakListIntoChunks( lfnList, 5000 ): res = self.<API key>( parentProd, status, lfnChunk ) if not res['OK']: gLogger.error( "[None] [%d] .<API key>: Error setting status %s for %d files in transformation %d " % ( prod, status, len( lfnList ), parentProd ), res['Message'] ) # Set the status in the new transformation for ( status, oldStatus ), lfnList in newStatusFiles.items(): for lfnChunk in breakListIntoChunks( lfnList, 5000 ): res = self.<API key>( prod, status, lfnChunk, force = force ) if not res['OK']: gLogger.error( "[None] [%d] .<API key>: Error setting status %s for %d files; resetting them %s in transformation %d" % ( prod, status, len( lfnChunk ), oldStatus, parentProd ), res['Message'] ) res = self.<API key>( parentProd, oldStatus, lfnChunk ) if not res['OK']: gLogger.error( "[None] [%d] .<API key>: Error setting status %s for %d files in transformation %d" % ( prod, oldStatus, len( lfnChunk ), parentProd ), res['Message'] ) return S_OK( ( parentProd, movedFiles ) ) def <API key>( self, transName, newLFNsStatus = {}, lfns = [], force = False, rpc = '', url = '', timeout = 120 ): """ sets the file status for LFNs of a transformation For backward compatibility purposes, the status and LFNs can be passed in 2 ways: - newLFNsStatus is a dictionary with the form: {'/this/is/an/lfn1.txt': 'StatusA', '/this/is/an/lfn2.txt': 'StatusB', ... } and at this point lfns is not considered - newLFNStatus is a string, that applies to all the LFNs in lfns """ rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) # create dictionary in case newLFNsStatus is a string if type( newLFNsStatus ) == type( '' ): newLFNsStatus = dict( [( lfn, newLFNsStatus ) for lfn in lfns ] ) # gets status as of today tsFiles = self.<API key>( {'TransformationID':transName, 'LFN': newLFNsStatus.keys()} ) if not tsFiles['OK']: return tsFiles tsFiles = tsFiles['Value'] if tsFiles: # for convenience, makes a small dictionary out of the tsFiles, with the lfn as key tsFilesAsDict = {} for tsFile in tsFiles: tsFilesAsDict[tsFile['LFN']] = [tsFile['Status'], tsFile['ErrorCount'], tsFile['FileID']] # applying the state machine to the proposed status newStatuses = self.<API key>( tsFilesAsDict, newLFNsStatus, force ) if newStatuses: # if there's something to update # must do it for the file IDs... newStatusForFileIDs = dict( [( tsFilesAsDict[lfn][2], newStatuses[lfn] ) for lfn in newStatuses.keys()] ) res = rpcClient.<API key>( transName, newStatusForFileIDs ) if not res['OK']: return res return S_OK( newStatuses ) def <API key>( self, tsFilesAsDict, <API key>, force ): """ For easier extension, here we apply the state machine of the production files. VOs might want to replace the standard here with something they prefer. tsFiles is a dictionary with the lfn as key and as value a list of [Status, ErrorCount, FileID] dictOfNewLFNsStatus is a dictionary with the proposed status force is a boolean It returns a dictionary with the status updates """ newStatuses = {} for lfn in <API key>.keys(): if lfn not in tsFilesAsDict.keys(): continue else: newStatus = <API key>[lfn] # Apply optional corrections if tsFilesAsDict[lfn][0].lower() == 'processed' and <API key>[lfn].lower() != 'processed': if not force: newStatus = 'Processed' elif tsFilesAsDict[lfn][0].lower() == 'maxreset': if not force: newStatus = 'MaxReset' elif <API key>[lfn].lower() == 'unused': errorCount = tsFilesAsDict[lfn][1] # every 10 retries (by default) if errorCount and ( ( errorCount % self.maxResetCounter ) == 0 ): if not force: newStatus = 'MaxReset' if tsFilesAsDict[lfn][0].lower() != newStatus: newStatuses[lfn] = newStatus return newStatuses def <API key>( self, transID, paramName, paramValue, force = False, rpc = '', url = '', timeout = 120 ): """ Sets a transformation parameter. There's a special case when coming to setting the status of a transformation. """ rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) if paramName.lower() == 'status': # get transformation Type transformation = self.getTransformation( transID ) if not transformation['OK']: return transformation transformationType = transformation['Value']['Type'] # get status as of today originalStatus = self.<API key>( transID, 'Status' ) if not originalStatus['OK']: return originalStatus originalStatus = originalStatus['Value'] transIDAsDict = {transID: [originalStatus, transformationType]} <API key> = {transID: paramValue} # applying the state machine to the proposed status value = self.<API key>( transIDAsDict, <API key>, force ) else: value = paramValue return rpcClient.<API key>( transID, paramName, value ) def <API key>( self, transIDAsDict, <API key>, force ): """ For easier extension, here we apply the state machine of the transformation status. VOs might want to replace the standard here with something they prefer. transIDAsDict is a dictionary with the transID as key and as value a list with [Status, Type] <API key> is a dictionary with the proposed status force is a boolean It returns the new status (the standard is just doing nothing: everything is possible) """ return <API key>.values()[0] # These are the file catalog interface methods def isOK( self ): return self.valid def getName( self, DN = '' ): """ Get the file catalog type name """ return self.name def addDirectory( self, path, force = False, rpc = '', url = '', timeout = None ): rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) return rpcClient.addDirectory( path, force ) def getReplicas( self, lfn, rpc = '', url = '', timeout = None ): res = self.<API key>( lfn ) if not res['OK']: return res lfns = res['Value'].keys() rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) return rpcClient.getReplicas( lfns ) def addFile( self, lfn, force = False, rpc = '', url = '', timeout = None ): res = self.<API key>( lfn ) if not res['OK']: return res lfndicts = res['Value'] rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) return rpcClient.addFile( lfndicts, force ) def addReplica( self, lfn, force = False, rpc = '', url = '', timeout = None ): res = self.<API key>( lfn ) if not res['OK']: return res lfndicts = res['Value'] rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) return rpcClient.addReplica( lfndicts, force ) def removeFile( self, lfn, rpc = '', url = '', timeout = None ): res = self.<API key>( lfn ) if not res['OK']: return res lfns = res['Value'].keys() rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) successful = {} failed = {} listOfLists = breakListIntoChunks( lfns, 100 ) for fList in listOfLists: res = rpcClient.removeFile( fList ) if not res['OK']: return res successful.update( res['Value']['Successful'] ) failed.update( res['Value']['Failed'] ) resDict = {'Successful': successful, 'Failed':failed} return S_OK( resDict ) def removeReplica( self, lfn, rpc = '', url = '', timeout = None ): res = self.<API key>( lfn ) if not res['OK']: return res lfndicts = res['Value'] rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) successful = {} failed = {} # as lfndicts is a dict, the breakListIntoChunks will fail. Fake it! listOfDicts = [] localdicts = {} for lfn, info in lfndicts.items(): localdicts.update( { lfn : info } ) if len( localdicts.keys() ) % 100 == 0: listOfDicts.append( localdicts ) localdicts = {} for fDict in listOfDicts: res = rpcClient.removeReplica( fDict ) if not res['OK']: return res successful.update( res['Value']['Successful'] ) failed.update( res['Value']['Failed'] ) resDict = {'Successful': successful, 'Failed':failed} return S_OK( resDict ) def getReplicaStatus( self, lfn, rpc = '', url = '', timeout = None ): res = self.<API key>( lfn ) if not res['OK']: return res lfndict = res['Value'] rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) return rpcClient.getReplicaStatus( lfndict ) def setReplicaStatus( self, lfn, rpc = '', url = '', timeout = None ): res = self.<API key>( lfn ) if not res['OK']: return res lfndict = res['Value'] rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) return rpcClient.setReplicaStatus( lfndict ) def setReplicaHost( self, lfn, rpc = '', url = '', timeout = None ): res = self.<API key>( lfn ) if not res['OK']: return res lfndict = res['Value'] rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) return rpcClient.setReplicaHost( lfndict ) def removeDirectory( self, lfn, rpc = '', url = '', timeout = None ): return self.__returnOK( lfn ) def createDirectory( self, lfn, rpc = '', url = '', timeout = None ): return self.__returnOK( lfn ) def createLink( self, lfn, rpc = '', url = '', timeout = None ): return self.__returnOK( lfn ) def removeLink( self, lfn, rpc = '', url = '', timeout = None ): return self.__returnOK( lfn ) def __returnOK( self, lfn ): res = self.<API key>( lfn ) if not res['OK']: return res successful = {} for lfn in res['Value'].keys(): successful[lfn] = True resDict = {'Successful':successful, 'Failed':{}} return S_OK( resDict ) def <API key>( self, path ): if type( path ) in types.StringTypes: urls = {path:False} elif type( path ) == types.ListType: urls = {} for url in path: urls[url] = False elif type( path ) == types.DictType: urls = path else: return S_ERROR( "<API key>.<API key>: Supplied path is not of the correct format." ) return S_OK( urls )
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include "serial.h" #include "inputprocessor.h" #include "commandsender.h" #include "plothelper.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); void verticalSlider(); void sendmotor(); public slots: void refreshDevices(); private slots: void <API key>(); void <API key>(); void <API key>(); void on_Send_pressed(); void rollPIDPressed(); void pitchPIDPressed(); void yawPIDPressed(); void rollRatePIDPressed(); void pitchRatePIDPressed(); void yawRatePIDPressed(); void rollSliderChanged(); void pitchSliderChanged(); void yawSliderChanged(); void <API key>(); void <API key>(); void <API key>(); void sendRollPIDParam(); void sendPitchPIDParam(); void sendYawPIDParam(); void <API key>(); void <API key>(); void sendYawRatePIDParam(); void <API key>(); void <API key>(); void <API key>(); void <API key>(); void <API key>(); void <API key>(); void <API key>(); void <API key>(); signals: void rollPIDReleased(); void pitchPIDReleased(); void yawPIDReleased(); void rollRatePIDReleased(); void <API key>(); void yawRatePIDReleased(); private: void sendSetPoints(); Ui::MainWindow *ui; Serial serial; InputProcessor *ip; CommandSender *cs; QTimer *timer; PlotHelper controllerLine1, controllerLine2, controllerLine3; PlotHelper grawLine1, grawLine2, grawLine3; PlotHelper arawLine1, arawLine2, arawLine3; PlotHelper filterLine1, filterLine2, filterLine3; }; #endif // MAINWINDOW_H
-- ToME - Tales of Maj'Eyal -- This program is free software: you can redistribute it and/or modify -- (at your option) any later version. -- This program is distributed in the hope that it will be useful, -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- along with this program. If not, see <http: -- Nicolas Casalini "DarkGod" -- darkgod@te4.org load("/data/general/traps/complex.lua") load("/data/general/traps/alarm.lua") load("/data/general/traps/natural_forest.lua")
#ifndef _TIMING_H #define _TIMING_H #include "manta.h" #include <map> namespace Manta { class TimingData { private: TimingData(); public: static TimingData& instance() { static TimingData a; return a; } void print(); void saveMean(const std::string& filename); void start(FluidSolver* parent, const std::string& name); void stop(FluidSolver* parent, const std::string& name); protected: void step(); struct TimingSet { TimingSet() : num(0),updated(false) { cur.clear(); total.clear(); } MuTime cur, total; int num; bool updated; std::string solver; }; bool updated; int num; MuTime mPluginTimer; std::string mLastPlugin; std::map<std::string, std::vector<TimingSet> > mData; }; // Python interface PYTHON() class Timings : public PbClass { public: PYTHON() Timings() : PbClass(0) {} PYTHON() void display() { TimingData::instance().print(); } PYTHON() void saveMean(std::string file) { TimingData::instance().saveMean(file); } }; } #endif
from django.db import models from django.contrib.auth.models import User import MySQLdb # Create your models here. class Comentario(models.Model): """Comentario""" contenido = models.TextField(help_text='Escribe un comentario') fecha_coment = models.DateField(auto_now=True) def __unicode__(self): return self.contenido class Estado(models.Model): """Estado""" nom_estado = models.CharField(max_length=50) def __unicode__(self): return nom_estado class Categoria(models.Model): """Categoria""" nombre = models.CharField(max_length=50) descripcion = models.TextField(help_text='Escribe una descripcion de la categoria') class Entrada(models.Model): """Entrada""" autor = models.ForeignKey(User) comentario = models.ForeignKey(Comentario) estado = models.ForeignKey(Estado) titulo = models.CharField(max_length=100) contenido = models.TextField(help_text='Redacta el contenido') fecha_pub = models.DateField(auto_now=True) def __unicode__(self): return self.titulo class Agregador(models.Model): """agreador""" entrada = models.ForeignKey(Entrada) categoria = models.ManyToManyField(Categoria)
// <API key>: GPL-3.0 /** @file CommonIO.cpp * @author Gav Wood <i@gavwood.com> * @date 2014 */ #include <libsolutil/CommonIO.h> #include <libsolutil/Assertions.h> #include <fstream> #if defined(_WIN32) #include <windows.h> #else #include <unistd.h> #include <termios.h> #endif using namespace std; using namespace solidity::util; namespace { template <typename T> inline T readFile(boost::filesystem::path const& _file) { assertThrow(boost::filesystem::exists(_file), FileNotFound, _file.string()); // ifstream does not always fail when the path leads to a directory. Instead it might succeed // with tellg() returning a nonsensical value so that std::length_error gets raised in resize(). assertThrow(boost::filesystem::is_regular_file(_file), NotAFile, _file.string()); T ret; size_t const c_elementSize = sizeof(typename T::value_type); std::ifstream is(_file.string(), std::ifstream::binary); // Technically, this can still fail even though we checked above because FS content can change at any time. assertThrow(is, FileNotFound, _file.string()); // get length of file: is.seekg(0, is.end); streamoff length = is.tellg(); if (length == 0) return ret; // do not read empty file (MSVC does not like it) is.seekg(0, is.beg); ret.resize((static_cast<size_t>(length) + c_elementSize - 1) / c_elementSize); is.read(const_cast<char*>(reinterpret_cast<char const*>(ret.data())), static_cast<streamsize>(length)); return ret; } } string solidity::util::readFileAsString(boost::filesystem::path const& _file) { return readFile<string>(_file); } string solidity::util::readUntilEnd(istream& _stdin) { ostringstream ss; ss << _stdin.rdbuf(); return ss.str(); } string solidity::util::readBytes(istream& _input, size_t _length) { string output; output.resize(_length); _input.read(output.data(), static_cast<streamsize>(_length)); // If read() reads fewer bytes it sets failbit in addition to eofbit. if (_input.fail()) output.resize(static_cast<size_t>(_input.gcount())); return output; } #if defined(_WIN32) class <API key> { public: <API key>() { m_stdin = GetStdHandle(STD_INPUT_HANDLE); GetConsoleMode(m_stdin, &m_oldMode); SetConsoleMode(m_stdin, m_oldMode & (~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT))); } ~<API key>() { SetConsoleMode(m_stdin, m_oldMode); } private: HANDLE m_stdin; DWORD m_oldMode; }; #else class <API key> { public: <API key>() { tcgetattr(0, &m_termios); m_termios.c_lflag &= ~tcflag_t(ICANON); m_termios.c_lflag &= ~tcflag_t(ECHO); m_termios.c_cc[VMIN] = 1; m_termios.c_cc[VTIME] = 0; tcsetattr(0, TCSANOW, &m_termios); } ~<API key>() { m_termios.c_lflag |= ICANON; m_termios.c_lflag |= ECHO; tcsetattr(0, TCSADRAIN, &m_termios); } private: struct termios m_termios; }; #endif int solidity::util::<API key>() { <API key> <API key>; return cin.get(); } string solidity::util::absolutePath(string const& _path, string const& _reference) { boost::filesystem::path p(_path); // Anything that does not start with `.` is an absolute path. if (p.begin() == p.end() || (*p.begin() != "." && *p.begin() != "..")) return _path; boost::filesystem::path result(_reference); // If filename is "/", then remove_filename() throws. if (result.filename() != boost::filesystem::path("/")) result.remove_filename(); for (boost::filesystem::path::iterator it = p.begin(); it != p.end(); ++it) if (*it == "..") result = result.parent_path(); else if (*it != ".") result /= *it; return result.generic_string(); } string solidity::util::sanitizePath(string const& _path) { return boost::filesystem::path(_path).generic_string(); }
package com.simplecity.amp_library.model; import android.content.Context; import com.simplecity.amp_library.R; import java.io.File; public class ArtworkModel { private static final String TAG = "ArtworkModel"; @ArtworkProvider.Type public int type; public File file; public ArtworkModel(@ArtworkProvider.Type int type, File file) { this.type = type; this.file = file; } public static String getTypeString(Context context, @ArtworkProvider.Type int type) { switch (type) { case ArtworkProvider.Type.MEDIA_STORE: return context.getString(R.string.<API key>); case ArtworkProvider.Type.TAG: return context.getString(R.string.artwork_type_tag); case ArtworkProvider.Type.FOLDER: return "Folder"; case ArtworkProvider.Type.REMOTE: return context.getString(R.string.<API key>); } return null; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ArtworkModel that = (ArtworkModel) o; if (type != that.type) return false; return file != null ? file.equals(that.file) : that.file == null; } @Override public int hashCode() { int result = type; result = 31 * result + (file != null ? file.hashCode() : 0); return result; } }
package com.newppt.android.ui; import com.newppt.android.data.AnimUtils2; import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.ImageView; public class ScaleImage extends ImageView { final private int FLIP_DISTANCE = 30; public ScaleImage(Context context) { super(context); // TODO Auto-generated constructor stub } public ScaleImage(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub } public ScaleImage(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // TODO Auto-generated constructor stub } private int count = 0; private long firClick; private long secClick; private boolean scaleTip = true; private float x; private float y; @Override public boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stub if (MotionEvent.ACTION_DOWN == event.getAction()) { count++; if (count == 1) { firClick = System.currentTimeMillis(); x = event.getX(); y = event.getY(); } else if (count == 2) { secClick = System.currentTimeMillis(); float mx = event.getX(); float my = event.getY(); if (secClick - firClick < 700 && Math.abs(mx - x) < FLIP_DISTANCE && Math.abs(my - y) < FLIP_DISTANCE) { if (scaleTip) { x = event.getX(); y = event.getY(); AnimUtils2 animUtils2 = new AnimUtils2(); animUtils2.imageZoomOut(this, 200, x, y); scaleTip = false; } else { AnimUtils2 animUtils2 = new AnimUtils2(); animUtils2.imageZoomIn(this, 200, x, y); scaleTip = true; } } count = 0; firClick = 0; secClick = 0; } } return true; // return super.onTouchEvent(event); } }
pyVenture - A python text-based adventure game engine This is a generalized framework that allows construction and playing of <API key> worlds. Stores world information in JSON files. This code is licensed under the General Public License Version 3 (http: The following dependencies are required: * Python 2.6+ * Qt4 * PyQt4 * GraphViz * pydot
/* #define DEBUG */ #include <linux/backlight.h> #include <linux/delay.h> #include <linux/fb.h> #include <linux/gpio.h> #include <linux/interrupt.h> #include <linux/jiffies.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/workqueue.h> #include <linux/of_device.h> #include <linux/of_gpio.h> #include <video/omapfb_dss.h> #include <video/mipi_display.h> /* DSI Virtual channel. Hardcoded for now. */ #define TCH 0 #define DCS_READ_NUM_ERRORS 0x05 #define DCS_BRIGHTNESS 0x51 #define DCS_CTRL_DISPLAY 0x53 #define DCS_GET_ID1 0xda #define DCS_GET_ID2 0xdb #define DCS_GET_ID3 0xdc struct panel_drv_data { struct omap_dss_device dssdev; struct omap_dss_device *in; struct omap_video_timings timings; struct platform_device *pdev; struct mutex lock; struct backlight_device *bldev; unsigned long hw_guard_end; /* next value of jiffies when we can * issue the next sleep in/out command */ unsigned long hw_guard_wait; /* max guard time in jiffies */ /* panel HW configuration from DT or platform data */ int reset_gpio; int ext_te_gpio; bool use_dsi_backlight; struct omap_dsi_pin_config pin_config; /* runtime variables */ bool enabled; bool te_enabled; atomic_t do_update; int channel; struct delayed_work te_timeout_work; bool intro_printed; bool ulps_enabled; unsigned ulps_timeout; struct delayed_work ulps_work; }; #define to_panel_data(p) container_of(p, struct panel_drv_data, dssdev) static irqreturn_t dsicm_te_isr(int irq, void *data); static void <API key>(struct work_struct *work); static int _dsicm_enable_te(struct panel_drv_data *ddata, bool enable); static int dsicm_panel_reset(struct panel_drv_data *ddata); static void dsicm_ulps_work(struct work_struct *work); static void hw_guard_start(struct panel_drv_data *ddata, int guard_msec) { ddata->hw_guard_wait = msecs_to_jiffies(guard_msec); ddata->hw_guard_end = jiffies + ddata->hw_guard_wait; } static void hw_guard_wait(struct panel_drv_data *ddata) { unsigned long wait = ddata->hw_guard_end - jiffies; if ((long)wait > 0 && wait <= ddata->hw_guard_wait) { set_current_state(<API key>); schedule_timeout(wait); } } static int dsicm_dcs_read_1(struct panel_drv_data *ddata, u8 dcs_cmd, u8 *data) { struct omap_dss_device *in = ddata->in; int r; u8 buf[1]; r = in->ops.dsi->dcs_read(in, ddata->channel, dcs_cmd, buf, 1); if (r < 0) { return r; } *data = buf[0]; return 0; } static int dsicm_dcs_write_0(struct panel_drv_data *ddata, u8 dcs_cmd) { struct omap_dss_device *in = ddata->in; return in->ops.dsi->dcs_write(in, ddata->channel, &dcs_cmd, 1); } static int dsicm_dcs_write_1(struct panel_drv_data *ddata, u8 dcs_cmd, u8 param) { struct omap_dss_device *in = ddata->in; u8 buf[2] = { dcs_cmd, param }; return in->ops.dsi->dcs_write(in, ddata->channel, buf, 2); } static int dsicm_sleep_in(struct panel_drv_data *ddata) { struct omap_dss_device *in = ddata->in; u8 cmd; int r; hw_guard_wait(ddata); cmd = <API key>; r = in->ops.dsi->dcs_write_nosync(in, ddata->channel, &cmd, 1); if (r) { return r; } hw_guard_start(ddata, 120); usleep_range(5000, 10000); return 0; } static int dsicm_sleep_out(struct panel_drv_data *ddata) { int r; hw_guard_wait(ddata); r = dsicm_dcs_write_0(ddata, <API key>); if (r) { return r; } hw_guard_start(ddata, 120); usleep_range(5000, 10000); return 0; } static int dsicm_get_id(struct panel_drv_data *ddata, u8 *id1, u8 *id2, u8 *id3) { int r; r = dsicm_dcs_read_1(ddata, DCS_GET_ID1, id1); if (r) { return r; } r = dsicm_dcs_read_1(ddata, DCS_GET_ID2, id2); if (r) { return r; } r = dsicm_dcs_read_1(ddata, DCS_GET_ID3, id3); if (r) { return r; } return 0; } static int <API key>(struct panel_drv_data *ddata, u16 x, u16 y, u16 w, u16 h) { struct omap_dss_device *in = ddata->in; int r; u16 x1 = x; u16 x2 = x + w - 1; u16 y1 = y; u16 y2 = y + h - 1; u8 buf[5]; buf[0] = <API key>; buf[1] = (x1 >> 8) & 0xff; buf[2] = (x1 >> 0) & 0xff; buf[3] = (x2 >> 8) & 0xff; buf[4] = (x2 >> 0) & 0xff; r = in->ops.dsi->dcs_write_nosync(in, ddata->channel, buf, sizeof(buf)); if (r) { return r; } buf[0] = <API key>; buf[1] = (y1 >> 8) & 0xff; buf[2] = (y1 >> 0) & 0xff; buf[3] = (y2 >> 8) & 0xff; buf[4] = (y2 >> 0) & 0xff; r = in->ops.dsi->dcs_write_nosync(in, ddata->channel, buf, sizeof(buf)); if (r) { return r; } in->ops.dsi->bta_sync(in, ddata->channel); return r; } static void <API key>(struct panel_drv_data *ddata) { if (ddata->ulps_timeout > 0) <API key>(&ddata->ulps_work, msecs_to_jiffies(ddata->ulps_timeout)); } static void <API key>(struct panel_drv_data *ddata) { cancel_delayed_work(&ddata->ulps_work); } static int dsicm_enter_ulps(struct panel_drv_data *ddata) { struct omap_dss_device *in = ddata->in; int r; if (ddata->ulps_enabled) { return 0; } <API key>(ddata); r = _dsicm_enable_te(ddata, false); if (r) { goto err; } if (gpio_is_valid(ddata->ext_te_gpio)) { disable_irq(gpio_to_irq(ddata->ext_te_gpio)); } in->ops.dsi->disable(in, false, true); ddata->ulps_enabled = true; return 0; err: dev_err(&ddata->pdev->dev, "enter ULPS failed"); dsicm_panel_reset(ddata); ddata->ulps_enabled = false; <API key>(ddata); return r; } static int dsicm_exit_ulps(struct panel_drv_data *ddata) { struct omap_dss_device *in = ddata->in; int r; if (!ddata->ulps_enabled) { return 0; } r = in->ops.dsi->enable(in); if (r) { dev_err(&ddata->pdev->dev, "failed to enable DSI\n"); goto err1; } in->ops.dsi->enable_hs(in, ddata->channel, true); r = _dsicm_enable_te(ddata, true); if (r) { dev_err(&ddata->pdev->dev, "failed to re-enable TE"); goto err2; } if (gpio_is_valid(ddata->ext_te_gpio)) { enable_irq(gpio_to_irq(ddata->ext_te_gpio)); } <API key>(ddata); ddata->ulps_enabled = false; return 0; err2: dev_err(&ddata->pdev->dev, "failed to exit ULPS"); r = dsicm_panel_reset(ddata); if (!r) { if (gpio_is_valid(ddata->ext_te_gpio)) { enable_irq(gpio_to_irq(ddata->ext_te_gpio)); } ddata->ulps_enabled = false; } err1: <API key>(ddata); return r; } static int dsicm_wake_up(struct panel_drv_data *ddata) { if (ddata->ulps_enabled) { return dsicm_exit_ulps(ddata); } <API key>(ddata); <API key>(ddata); return 0; } static int <API key>(struct backlight_device *dev) { struct panel_drv_data *ddata = dev_get_drvdata(&dev->dev); struct omap_dss_device *in = ddata->in; int r; int level; if (dev->props.fb_blank == FB_BLANK_UNBLANK && dev->props.power == FB_BLANK_UNBLANK) { level = dev->props.brightness; } else { level = 0; } dev_dbg(&ddata->pdev->dev, "update brightness to %d\n", level); mutex_lock(&ddata->lock); if (ddata->enabled) { in->ops.dsi->bus_lock(in); r = dsicm_wake_up(ddata); if (!r) { r = dsicm_dcs_write_1(ddata, DCS_BRIGHTNESS, level); } in->ops.dsi->bus_unlock(in); } else { r = 0; } mutex_unlock(&ddata->lock); return r; } static int <API key>(struct backlight_device *dev) { if (dev->props.fb_blank == FB_BLANK_UNBLANK && dev->props.power == FB_BLANK_UNBLANK) { return dev->props.brightness; } return 0; } static const struct backlight_ops dsicm_bl_ops = { .get_brightness = <API key>, .update_status = <API key>, }; static void <API key>(struct omap_dss_device *dssdev, u16 *xres, u16 *yres) { *xres = dssdev->panel.timings.x_res; *yres = dssdev->panel.timings.y_res; } static ssize_t <API key>(struct device *dev, struct device_attribute *attr, char *buf) { struct platform_device *pdev = to_platform_device(dev); struct panel_drv_data *ddata = <API key>(pdev); struct omap_dss_device *in = ddata->in; u8 errors = 0; int r; mutex_lock(&ddata->lock); if (ddata->enabled) { in->ops.dsi->bus_lock(in); r = dsicm_wake_up(ddata); if (!r) r = dsicm_dcs_read_1(ddata, DCS_READ_NUM_ERRORS, &errors); in->ops.dsi->bus_unlock(in); } else { r = -ENODEV; } mutex_unlock(&ddata->lock); if (r) { return r; } return snprintf(buf, PAGE_SIZE, "%d\n", errors); } static ssize_t <API key>(struct device *dev, struct device_attribute *attr, char *buf) { struct platform_device *pdev = to_platform_device(dev); struct panel_drv_data *ddata = <API key>(pdev); struct omap_dss_device *in = ddata->in; u8 id1, id2, id3; int r; mutex_lock(&ddata->lock); if (ddata->enabled) { in->ops.dsi->bus_lock(in); r = dsicm_wake_up(ddata); if (!r) { r = dsicm_get_id(ddata, &id1, &id2, &id3); } in->ops.dsi->bus_unlock(in); } else { r = -ENODEV; } mutex_unlock(&ddata->lock); if (r) { return r; } return snprintf(buf, PAGE_SIZE, "%02x.%02x.%02x\n", id1, id2, id3); } static ssize_t dsicm_store_ulps(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct platform_device *pdev = to_platform_device(dev); struct panel_drv_data *ddata = <API key>(pdev); struct omap_dss_device *in = ddata->in; unsigned long t; int r; r = kstrtoul(buf, 0, &t); if (r) { return r; } mutex_lock(&ddata->lock); if (ddata->enabled) { in->ops.dsi->bus_lock(in); if (t) { r = dsicm_enter_ulps(ddata); } else { r = dsicm_wake_up(ddata); } in->ops.dsi->bus_unlock(in); } mutex_unlock(&ddata->lock); if (r) { return r; } return count; } static ssize_t dsicm_show_ulps(struct device *dev, struct device_attribute *attr, char *buf) { struct platform_device *pdev = to_platform_device(dev); struct panel_drv_data *ddata = <API key>(pdev); unsigned t; mutex_lock(&ddata->lock); t = ddata->ulps_enabled; mutex_unlock(&ddata->lock); return snprintf(buf, PAGE_SIZE, "%u\n", t); } static ssize_t <API key>(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct platform_device *pdev = to_platform_device(dev); struct panel_drv_data *ddata = <API key>(pdev); struct omap_dss_device *in = ddata->in; unsigned long t; int r; r = kstrtoul(buf, 0, &t); if (r) { return r; } mutex_lock(&ddata->lock); ddata->ulps_timeout = t; if (ddata->enabled) { /* dsicm_wake_up will restart the timer */ in->ops.dsi->bus_lock(in); r = dsicm_wake_up(ddata); in->ops.dsi->bus_unlock(in); } mutex_unlock(&ddata->lock); if (r) { return r; } return count; } static ssize_t <API key>(struct device *dev, struct device_attribute *attr, char *buf) { struct platform_device *pdev = to_platform_device(dev); struct panel_drv_data *ddata = <API key>(pdev); unsigned t; mutex_lock(&ddata->lock); t = ddata->ulps_timeout; mutex_unlock(&ddata->lock); return snprintf(buf, PAGE_SIZE, "%u\n", t); } static DEVICE_ATTR(num_dsi_errors, S_IRUGO, <API key>, NULL); static DEVICE_ATTR(hw_revision, S_IRUGO, <API key>, NULL); static DEVICE_ATTR(ulps, S_IRUGO | S_IWUSR, dsicm_show_ulps, dsicm_store_ulps); static DEVICE_ATTR(ulps_timeout, S_IRUGO | S_IWUSR, <API key>, <API key>); static struct attribute *dsicm_attrs[] = { &<API key>.attr, &<API key>.attr, &dev_attr_ulps.attr, &<API key>.attr, NULL, }; static struct attribute_group dsicm_attr_group = { .attrs = dsicm_attrs, }; static void dsicm_hw_reset(struct panel_drv_data *ddata) { if (!gpio_is_valid(ddata->reset_gpio)) { return; } gpio_set_value(ddata->reset_gpio, 1); udelay(10); /* reset the panel */ gpio_set_value(ddata->reset_gpio, 0); /* assert reset */ udelay(10); gpio_set_value(ddata->reset_gpio, 1); /* wait after releasing reset */ usleep_range(5000, 10000); } static int dsicm_power_on(struct panel_drv_data *ddata) { struct omap_dss_device *in = ddata->in; u8 id1, id2, id3; int r; struct omap_dss_dsi_config dsi_config = { .mode = <API key>, .pixel_format = <API key>, .timings = &ddata->timings, .hs_clk_min = 150000000, .hs_clk_max = 300000000, .lp_clk_min = 7000000, .lp_clk_max = 10000000, }; if (ddata->pin_config.num_pins > 0) { r = in->ops.dsi->configure_pins(in, &ddata->pin_config); if (r) { dev_err(&ddata->pdev->dev, "failed to configure DSI pins\n"); goto err0; } } r = in->ops.dsi->set_config(in, &dsi_config); if (r) { dev_err(&ddata->pdev->dev, "failed to configure DSI\n"); goto err0; } r = in->ops.dsi->enable(in); if (r) { dev_err(&ddata->pdev->dev, "failed to enable DSI\n"); goto err0; } dsicm_hw_reset(ddata); in->ops.dsi->enable_hs(in, ddata->channel, false); r = dsicm_sleep_out(ddata); if (r) { goto err; } r = dsicm_get_id(ddata, &id1, &id2, &id3); if (r) { goto err; } r = dsicm_dcs_write_1(ddata, DCS_BRIGHTNESS, 0xff); if (r) { goto err; } r = dsicm_dcs_write_1(ddata, DCS_CTRL_DISPLAY, (1 << 2) | (1 << 5)); /* BL | BCTRL */ if (r) { goto err; } r = dsicm_dcs_write_1(ddata, <API key>, <API key>); if (r) { goto err; } r = dsicm_dcs_write_0(ddata, <API key>); if (r) { goto err; } r = _dsicm_enable_te(ddata, ddata->te_enabled); if (r) { goto err; } r = in->ops.dsi->enable_video_output(in, ddata->channel); if (r) { goto err; } ddata->enabled = 1; if (!ddata->intro_printed) { dev_info(&ddata->pdev->dev, "panel revision %02x.%02x.%02x\n", id1, id2, id3); ddata->intro_printed = true; } in->ops.dsi->enable_hs(in, ddata->channel, true); return 0; err: dev_err(&ddata->pdev->dev, "error while enabling panel, issuing HW reset\n"); dsicm_hw_reset(ddata); in->ops.dsi->disable(in, true, false); err0: return r; } static void dsicm_power_off(struct panel_drv_data *ddata) { struct omap_dss_device *in = ddata->in; int r; in->ops.dsi-><API key>(in, ddata->channel); r = dsicm_dcs_write_0(ddata, <API key>); if (!r) { r = dsicm_sleep_in(ddata); } if (r) { dev_err(&ddata->pdev->dev, "error disabling panel, issuing HW reset\n"); dsicm_hw_reset(ddata); } in->ops.dsi->disable(in, true, false); ddata->enabled = 0; } static int dsicm_panel_reset(struct panel_drv_data *ddata) { dev_err(&ddata->pdev->dev, "performing LCD reset\n"); dsicm_power_off(ddata); dsicm_hw_reset(ddata); return dsicm_power_on(ddata); } static int dsicm_connect(struct omap_dss_device *dssdev) { struct panel_drv_data *ddata = to_panel_data(dssdev); struct omap_dss_device *in = ddata->in; struct device *dev = &ddata->pdev->dev; int r; if (<API key>(dssdev)) { return 0; } r = in->ops.dsi->connect(in, dssdev); if (r) { dev_err(dev, "Failed to connect to video source\n"); return r; } r = in->ops.dsi->request_vc(ddata->in, &ddata->channel); if (r) { dev_err(dev, "failed to get virtual channel\n"); goto err_req_vc; } r = in->ops.dsi->set_vc_id(ddata->in, ddata->channel, TCH); if (r) { dev_err(dev, "failed to set VC_ID\n"); goto err_vc_id; } return 0; err_vc_id: in->ops.dsi->release_vc(ddata->in, ddata->channel); err_req_vc: in->ops.dsi->disconnect(in, dssdev); return r; } static void dsicm_disconnect(struct omap_dss_device *dssdev) { struct panel_drv_data *ddata = to_panel_data(dssdev); struct omap_dss_device *in = ddata->in; if (!<API key>(dssdev)) { return; } in->ops.dsi->release_vc(in, ddata->channel); in->ops.dsi->disconnect(in, dssdev); } static int dsicm_enable(struct omap_dss_device *dssdev) { struct panel_drv_data *ddata = to_panel_data(dssdev); struct omap_dss_device *in = ddata->in; int r; dev_dbg(&ddata->pdev->dev, "enable\n"); mutex_lock(&ddata->lock); if (!<API key>(dssdev)) { r = -ENODEV; goto err; } if (<API key>(dssdev)) { r = 0; goto err; } in->ops.dsi->bus_lock(in); r = dsicm_power_on(ddata); in->ops.dsi->bus_unlock(in); if (r) { goto err; } dssdev->state = <API key>; mutex_unlock(&ddata->lock); return 0; err: dev_dbg(&ddata->pdev->dev, "enable failed\n"); mutex_unlock(&ddata->lock); return r; } static void dsicm_disable(struct omap_dss_device *dssdev) { struct panel_drv_data *ddata = to_panel_data(dssdev); struct omap_dss_device *in = ddata->in; int r; dev_dbg(&ddata->pdev->dev, "disable\n"); mutex_lock(&ddata->lock); <API key>(ddata); in->ops.dsi->bus_lock(in); if (<API key>(dssdev)) { r = dsicm_wake_up(ddata); if (!r) { dsicm_power_off(ddata); } } in->ops.dsi->bus_unlock(in); dssdev->state = <API key>; mutex_unlock(&ddata->lock); } static void dsicm_framedone_cb(int err, void *data) { struct panel_drv_data *ddata = data; struct omap_dss_device *in = ddata->in; dev_dbg(&ddata->pdev->dev, "framedone, err %d\n", err); in->ops.dsi->bus_unlock(ddata->in); } static irqreturn_t dsicm_te_isr(int irq, void *data) { struct panel_drv_data *ddata = data; struct omap_dss_device *in = ddata->in; int old; int r; old = atomic_cmpxchg(&ddata->do_update, 1, 0); if (old) { cancel_delayed_work(&ddata->te_timeout_work); r = in->ops.dsi->update(in, ddata->channel, dsicm_framedone_cb, ddata); if (r) { goto err; } } return IRQ_HANDLED; err: dev_err(&ddata->pdev->dev, "start update failed\n"); in->ops.dsi->bus_unlock(in); return IRQ_HANDLED; } static void <API key>(struct work_struct *work) { struct panel_drv_data *ddata = container_of(work, struct panel_drv_data, te_timeout_work.work); struct omap_dss_device *in = ddata->in; dev_err(&ddata->pdev->dev, "TE not received for 250ms!\n"); atomic_set(&ddata->do_update, 0); in->ops.dsi->bus_unlock(in); } static int dsicm_update(struct omap_dss_device *dssdev, u16 x, u16 y, u16 w, u16 h) { struct panel_drv_data *ddata = to_panel_data(dssdev); struct omap_dss_device *in = ddata->in; int r; dev_dbg(&ddata->pdev->dev, "update %d, %d, %d x %d\n", x, y, w, h); mutex_lock(&ddata->lock); in->ops.dsi->bus_lock(in); r = dsicm_wake_up(ddata); if (r) { goto err; } if (!ddata->enabled) { r = 0; goto err; } /* XXX no need to send this every frame, but dsi break if not done */ r = <API key>(ddata, 0, 0, dssdev->panel.timings.x_res, dssdev->panel.timings.y_res); if (r) { goto err; } if (ddata->te_enabled && gpio_is_valid(ddata->ext_te_gpio)) { <API key>(&ddata->te_timeout_work, msecs_to_jiffies(250)); atomic_set(&ddata->do_update, 1); } else { r = in->ops.dsi->update(in, ddata->channel, dsicm_framedone_cb, ddata); if (r) { goto err; } } /* note: no bus_unlock here. unlock is in framedone_cb */ mutex_unlock(&ddata->lock); return 0; err: in->ops.dsi->bus_unlock(in); mutex_unlock(&ddata->lock); return r; } static int dsicm_sync(struct omap_dss_device *dssdev) { struct panel_drv_data *ddata = to_panel_data(dssdev); struct omap_dss_device *in = ddata->in; dev_dbg(&ddata->pdev->dev, "sync\n"); mutex_lock(&ddata->lock); in->ops.dsi->bus_lock(in); in->ops.dsi->bus_unlock(in); mutex_unlock(&ddata->lock); dev_dbg(&ddata->pdev->dev, "sync done\n"); return 0; } static int _dsicm_enable_te(struct panel_drv_data *ddata, bool enable) { struct omap_dss_device *in = ddata->in; int r; if (enable) { r = dsicm_dcs_write_1(ddata, <API key>, 0); } else { r = dsicm_dcs_write_0(ddata, <API key>); } if (!gpio_is_valid(ddata->ext_te_gpio)) { in->ops.dsi->enable_te(in, enable); } /* possible panel bug */ msleep(100); return r; } static int dsicm_enable_te(struct omap_dss_device *dssdev, bool enable) { struct panel_drv_data *ddata = to_panel_data(dssdev); struct omap_dss_device *in = ddata->in; int r; mutex_lock(&ddata->lock); if (ddata->te_enabled == enable) { goto end; } in->ops.dsi->bus_lock(in); if (ddata->enabled) { r = dsicm_wake_up(ddata); if (r) { goto err; } r = _dsicm_enable_te(ddata, enable); if (r) { goto err; } } ddata->te_enabled = enable; in->ops.dsi->bus_unlock(in); end: mutex_unlock(&ddata->lock); return 0; err: in->ops.dsi->bus_unlock(in); mutex_unlock(&ddata->lock); return r; } static int dsicm_get_te(struct omap_dss_device *dssdev) { struct panel_drv_data *ddata = to_panel_data(dssdev); int r; mutex_lock(&ddata->lock); r = ddata->te_enabled; mutex_unlock(&ddata->lock); return r; } static int dsicm_memory_read(struct omap_dss_device *dssdev, void *buf, size_t size, u16 x, u16 y, u16 w, u16 h) { struct panel_drv_data *ddata = to_panel_data(dssdev); struct omap_dss_device *in = ddata->in; int r; int first = 1; int plen; unsigned buf_used = 0; if (size < w * h * 3) { return -ENOMEM; } mutex_lock(&ddata->lock); if (!ddata->enabled) { r = -ENODEV; goto err1; } size = min(w * h * 3, dssdev->panel.timings.x_res * dssdev->panel.timings.y_res * 3); in->ops.dsi->bus_lock(in); r = dsicm_wake_up(ddata); if (r) { goto err2; } /* plen 1 or 2 goes into short packet. until checksum error is fixed, * use short packets. plen 32 works, but bigger packets seem to cause * an error. */ if (size % 2) { plen = 1; } else { plen = 2; } <API key>(ddata, x, y, w, h); r = in->ops.dsi-><API key>(in, ddata->channel, plen); if (r) { goto err2; } while (buf_used < size) { u8 dcs_cmd = first ? 0x2e : 0x3e; first = 0; r = in->ops.dsi->dcs_read(in, ddata->channel, dcs_cmd, buf + buf_used, size - buf_used); if (r < 0) { dev_err(dssdev->dev, "read error\n"); goto err3; } buf_used += r; if (r < plen) { dev_err(&ddata->pdev->dev, "short read\n"); break; } if (signal_pending(current)) { dev_err(&ddata->pdev->dev, "signal pending, " "aborting memory read\n"); r = -ERESTARTSYS; goto err3; } } r = buf_used; err3: in->ops.dsi-><API key>(in, ddata->channel, 1); err2: in->ops.dsi->bus_unlock(in); err1: mutex_unlock(&ddata->lock); return r; } static void dsicm_ulps_work(struct work_struct *work) { struct panel_drv_data *ddata = container_of(work, struct panel_drv_data, ulps_work.work); struct omap_dss_device *dssdev = &ddata->dssdev; struct omap_dss_device *in = ddata->in; mutex_lock(&ddata->lock); if (dssdev->state != <API key> || !ddata->enabled) { mutex_unlock(&ddata->lock); return; } in->ops.dsi->bus_lock(in); dsicm_enter_ulps(ddata); in->ops.dsi->bus_unlock(in); mutex_unlock(&ddata->lock); } static struct omap_dss_driver dsicm_ops = { .connect = dsicm_connect, .disconnect = dsicm_disconnect, .enable = dsicm_enable, .disable = dsicm_disable, .update = dsicm_update, .sync = dsicm_sync, .get_resolution = <API key>, .get_recommended_bpp = <API key>, .enable_te = dsicm_enable_te, .get_te = dsicm_get_te, .memory_read = dsicm_memory_read, }; static int dsicm_probe_of(struct platform_device *pdev) { struct device_node *node = pdev->dev.of_node; struct panel_drv_data *ddata = <API key>(pdev); struct omap_dss_device *in; int gpio; gpio = of_get_named_gpio(node, "reset-gpios", 0); if (!gpio_is_valid(gpio)) { dev_err(&pdev->dev, "failed to parse reset gpio\n"); return gpio; } ddata->reset_gpio = gpio; gpio = of_get_named_gpio(node, "te-gpios", 0); if (gpio_is_valid(gpio) || gpio == -ENOENT) { ddata->ext_te_gpio = gpio; } else { dev_err(&pdev->dev, "failed to parse TE gpio\n"); return gpio; } in = <API key>(node); if (IS_ERR(in)) { dev_err(&pdev->dev, "failed to find video source\n"); return PTR_ERR(in); } ddata->in = in; /* TODO: ulps, backlight */ return 0; } static int dsicm_probe(struct platform_device *pdev) { struct <API key> props; struct panel_drv_data *ddata; struct backlight_device *bldev = NULL; struct device *dev = &pdev->dev; struct omap_dss_device *dssdev; int r; dev_dbg(dev, "probe\n"); if (!pdev->dev.of_node) { return -ENODEV; } ddata = devm_kzalloc(dev, sizeof(*ddata), GFP_KERNEL); if (!ddata) { return -ENOMEM; } <API key>(pdev, ddata); ddata->pdev = pdev; r = dsicm_probe_of(pdev); if (r) { return r; } ddata->timings.x_res = 864; ddata->timings.y_res = 480; ddata->timings.pixelclock = 864 * 480 * 60; dssdev = &ddata->dssdev; dssdev->dev = dev; dssdev->driver = &dsicm_ops; dssdev->panel.timings = ddata->timings; dssdev->type = <API key>; dssdev->owner = THIS_MODULE; dssdev->panel.dsi_pix_fmt = <API key>; dssdev->caps = <API key> | <API key>; r = <API key>(dssdev); if (r) { dev_err(dev, "Failed to register panel\n"); goto err_reg; } mutex_init(&ddata->lock); atomic_set(&ddata->do_update, 0); if (gpio_is_valid(ddata->reset_gpio)) { r = <API key>(dev, ddata->reset_gpio, GPIOF_OUT_INIT_LOW, "taal rst"); if (r) { dev_err(dev, "failed to request reset gpio\n"); return r; } } if (gpio_is_valid(ddata->ext_te_gpio)) { r = <API key>(dev, ddata->ext_te_gpio, GPIOF_IN, "taal irq"); if (r) { dev_err(dev, "GPIO request failed\n"); return r; } r = devm_request_irq(dev, gpio_to_irq(ddata->ext_te_gpio), dsicm_te_isr, IRQF_TRIGGER_RISING, "taal vsync", ddata); if (r) { dev_err(dev, "IRQ request failed\n"); return r; } <API key>(&ddata->te_timeout_work, <API key>); dev_dbg(dev, "Using GPIO TE\n"); } INIT_DELAYED_WORK(&ddata->ulps_work, dsicm_ulps_work); dsicm_hw_reset(ddata); if (ddata->use_dsi_backlight) { memset(&props, 0, sizeof(struct <API key>)); props.max_brightness = 255; props.type = BACKLIGHT_RAW; bldev = <API key>(dev_name(dev), dev, ddata, &dsicm_bl_ops, &props); if (IS_ERR(bldev)) { r = PTR_ERR(bldev); goto err_reg; } ddata->bldev = bldev; bldev->props.fb_blank = FB_BLANK_UNBLANK; bldev->props.power = FB_BLANK_UNBLANK; bldev->props.brightness = 255; <API key>(bldev); } r = sysfs_create_group(&dev->kobj, &dsicm_attr_group); if (r) { dev_err(dev, "failed to create sysfs files\n"); goto err_sysfs_create; } return 0; err_sysfs_create: if (bldev != NULL) { <API key>(bldev); } err_reg: return r; } static int __exit dsicm_remove(struct platform_device *pdev) { struct panel_drv_data *ddata = <API key>(pdev); struct omap_dss_device *dssdev = &ddata->dssdev; struct backlight_device *bldev; dev_dbg(&pdev->dev, "remove\n"); <API key>(dssdev); dsicm_disable(dssdev); dsicm_disconnect(dssdev); sysfs_remove_group(&pdev->dev.kobj, &dsicm_attr_group); bldev = ddata->bldev; if (bldev != NULL) { bldev->props.power = FB_BLANK_POWERDOWN; <API key>(bldev); <API key>(bldev); } omap_dss_put_device(ddata->in); <API key>(ddata); /* reset, to be sure that the panel is in a valid state */ dsicm_hw_reset(ddata); return 0; } static const struct of_device_id dsicm_of_match[] = { { .compatible = "omapdss,panel-dsi-cm", }, {}, }; MODULE_DEVICE_TABLE(of, dsicm_of_match); static struct platform_driver dsicm_driver = { .probe = dsicm_probe, .remove = __exit_p(dsicm_remove), .driver = { .name = "panel-dsi-cm", .of_match_table = dsicm_of_match, .suppress_bind_attrs = true, }, }; <API key>(dsicm_driver); MODULE_AUTHOR("Tomi Valkeinen <tomi.valkeinen@ti.com>"); MODULE_DESCRIPTION("Generic DSI Command Mode Panel Driver"); MODULE_LICENSE("GPL");
<?php /* oauthcallback.php This script handles the oAuth grant 'code' that is returned from the provider (google/fb/openid), and calls the 'authenticate' method of the PBS_LAAS_Client. That method exchanges the grant 'code' with PBS's endpoints to get access and refresh tokens, uses those to get user info (email, name, etc), and then stores the tokens and userinfo encrypted in session variables. If the 'rememberme' variable was true, those tokens are also stored in an encrypted cookie. */ show_admin_bar(false); remove_all_actions('wp_footer',1); remove_all_actions('wp_header',1); $defaults = get_option('<API key>'); $passport = new <API key>(dirname(__FILE__)); $laas_client = $passport->get_laas_client(); // log any current session out $laas_client->logout(); $login_referrer = !empty($defaults['landing_page_url']) ? $defaults['landing_page_url'] : site_url(); if (!empty($_COOKIE["<API key>"])){ $login_referrer = $_COOKIE["<API key>"]; setcookie( '<API key>', '', 1, '/', $_SERVER['HTTP_HOST']); } $membership_id = false; // where to direct a logged in visitor who isn't a member $not_member_path = 'pbsoauth/userinfo'; if (isset($_GET["state"])){ $state=($_GET["state"]); $jwt = $passport->read_jwt($state); if ($jwt) { $membership_id = !empty($jwt['sub']) ? $jwt['sub'] : false; // allow the jwt to override the current value with a return_path $login_referrer = !empty($jwt['return_path']) ? site_url($jwt['return_path']) : $login_referrer; // allow the jwt to set where the authenticated visitor who is not a member is sent $not_member_path = !empty($jwt['not_member_path']) ? $jwt['not_member_path'] : $not_member_path; } else { // fallback case for older clients when membership_id was passed as a plaintext string $membership_id = (!empty($state) ? $state : false); } } $rememberme = false; if (!empty($_COOKIE["pbsoauth_rememberme"])) { $rememberme = $_COOKIE["pbsoauth_rememberme"]; } // nonce is going to be in the jwt $nonce = false; $errors = array(); if (isset($_GET["code"])){ $code = $_GET["code"]; $userinfo = $laas_client->authenticate($code, $rememberme, $nonce); } // now we either have userinfo or null. if (isset($userinfo["pid"])){ $pbs_uid = $userinfo["pid"]; // now we work with the mvault $mvault_client = $passport->get_mvault_client(); $mvaultinfo = array(); if ($membership_id) { // this is an activation! $mvaultinfo = $mvault_client->get_membership($membership_id); if (isset($mvaultinfo["membership_id"])) { $mvaultinfo = $mvault_client->activate($membership_id, $pbs_uid); } } // is the person activated now? if (!isset($mvaultinfo["membership_id"])) { $mvaultinfo = $mvault_client-><API key>($pbs_uid); if (!isset($mvaultinfo["membership_id"])) { // still not activated, redirect the member as needed $login_referrer = site_url($not_member_path); } } } wp_redirect($login_referrer); exit(); ?>
@ECHO OFF IF EXIST %cd%\fwservice.exe ( c:\windows\microsoft.net\framework\v4.0.30319\installutil.exe %cd%\fwsyslog.exe ) ELSE ( GOTO FNFAbort ) ECHO. ECHO Batch complete. ECHO. GOTO EOB :FNFAbort ECHO. ECHO Batch aborted! File fwsyslog.exe not found in current directory. ECHO. :EOB ECHO ON
CREATE TABLE "<API key>" ( "homepage" text, "about_page" text );
<!doctype html><html><head><title>Easy Image Mapper</title><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1"><link rel="stylesheet" href="easy-mapper.css"> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script><script src="easy-mapper-1.2.0.js"></script></head><body> <div id="dim"></div> <div class="pop" id="pop-local"> <p class="pop-title">LOAD LOCAL IMAGE</p> <div class="pop-content"> <input type="file" id="pop-local-input"> </div> <div class="pop-btn"> <div class="pop-btn-confirm">LOAD</div> <div class="pop-btn-cancel">CANCEL</div> </div> </div> <div class="pop" id="pop-url"> <p class="pop-title">LINK IMAGE URL</p> <div class="pop-content"> <input type="text" id="pop-url-input"> </div> <div class="pop-btn"> <div class="pop-btn-confirm">LINK</div> <div class="pop-btn-cancel">CANCEL</div> </div> </div> <div class="pop" id="pop-code"> <p class="pop-title">CODE GENERATED</p> <div class="pop-btn"> <div class="pop-btn-copy" id="pop-btn-copy-a">SHOW MARKUP AS <em>&lt;A&gt; TAG</em> FORM</div> <div class="pop-btn-copy" id="pop-btn-copy-im">SHOW MARKUP AS <em>IMAGE MAP</em> FORM</div> <div class="pop-btn-cancel _full">CLOSE</div> </div> </div> <div class="pop" id="pop-codegen-a"> <p class="pop-title">&lt;A&gt; TAG FORM</p> <div class="pop-content"> <p></p> </div> <div class="pop-btn-cancel _back">BACK</div> <div class="pop-btn-cancel">CLOSE</div> </div> <div class="pop" id="pop-codegen-im"> <p class="pop-title">IMAGE MAP FORM</p> <div class="pop-content"> <p></p> </div> <div class="pop-btn-cancel _back">BACK</div> <div class="pop-btn-cancel">CLOSE</div> </div> <div class="pop" id="pop-info"> <p class="pop-title">APP INFORMATION</p> <div class="pop-content"> <p> <em class="pop-content-alert">&#9888; This app works on IE10+ only.</em> <strong>Easy Image Mapper (v1.2.0)</strong><br> Author: Inpyo Jeon<br> Contact: inpyoj@gmail.com<br> Website: <a class="_hover-ul" href="https://github.com/1npy0/easy-mapper" target="_blank">GitHub Repository</a> </p> </div> <div class="pop-btn-cancel _full">CLOSE</div> </div> <div class="pop" id="pop-addlink"> <p class="pop-title">ADD URL LINK</p> <div class="pop-content"> <input type="text" id="pop-addlink-input"> <label><input type="radio" name="pop-addlink-target" value="_blank" checked>New Window (target:_blank)</label> <label><input type="radio" name="pop-addlink-target" value="_self">Self Frame (target:_self)</label> <label><input type="radio" name="pop-addlink-target" value="_parent">Parent Frame (target:_parent)</label> <label><input type="radio" name="pop-addlink-target" value="_top">Full Body (target:_top)</label> </div> <div class="pop-btn"> <div class="pop-btn-confirm">ADD LINK</div> <div class="pop-btn-cancel">CANCEL</div> </div> </div> <div id="gnb"> <a id="gnb-title" href="easy-mapper.html" onclick="if (!confirm('Do you want to reset all the changes?')) return false;">&#8635; REFRESH</a> <ul id="gnb-menu"> <li id="gnb-menu-source"> <span>SOURCE &#9662;</span> <ul class="gnb-menu-sub"> <li id="gnb-menu-local">LOCAL</li> <li id="gnb-menu-url">URL</li> </ul> </li> <li id="gnb-menu-measure"> <span>MEASURE &#9662;</span> <ul class="gnb-menu-sub _toggle"> <li id="gnb-menu-drag" class="_active">DRAG<em>&nbsp;&#10003;</em></li> <li id="gnb-menu-click">CLICK<em>&nbsp;&#10003;</em></li> </ul> </li> <li id="gnb-menu-unit"> <span>UNIT &#9662;</span> <ul class="gnb-menu-sub _toggle"> <li id="gnb-menu-pixel" class="_active">PX<em>&nbsp;&#10003;</em></li> <li id="gnb-menu-percent">%<em>&nbsp;&#10003;</em></li> </ul> </li> <li id="gnb-menu-clear"> <span>CLEAR</span> </li> <li id="gnb-menu-generate"> <span>GENERATE</span> </li> <li id="gnb-menu-info"> <span>?</span> </li> </ul> </div> <div id="workspace"> <div id="workspace-ruler"> <div id="workspace-ruler-x"> <div id="workspace-ruler-x-2"></div> <div id="workspace-ruler-x-1"></div> </div> <div id="workspace-ruler-y"> <div id="workspace-ruler-y-2"></div> <div id="workspace-ruler-y-1"></div> </div> </div> <div id="workspace-img-wrap"> <img id="workspace-img" src="sampleimg.png"> <div id="grid-x1" class="grid-1"></div> <div id="grid-y1" class="grid-1"></div> <div id="grid-x2" class="grid-2"></div> <div id="grid-y2" class="grid-2"></div> <span id="grid-coords"></span> </div> </div> </body></html>
/** * 1. Set default font family to sans-serif. * 2. Prevent iOS and IE text size adjust after device orientation change, * without disabling user zoom. */ html { font-family: sans-serif; height: 100%; -ms-text-size-adjust: 100%; -<API key>: 100%; width: 100%; } /** * Remove default margin. */ body { background-color: #e6e7e8; height: 100%; margin: 0; width: 100%; } /** * Correct `block` display not defined for any HTML5 element in IE 8/9. * Correct `block` display not defined for `details` or `summary` in IE 10/11 * and Firefox. * Correct `block` display not defined for `main` in IE 11. */ article, aside, details, figcaption, figure, footer, header, hgroup, main, menu, nav, section, summary { display: block; } /** * 1. Correct `inline-block` display not defined in IE 8/9. * 2. Normalize vertical alignment of `progress` in Chrome, Firefox, and Opera. */ audio, canvas, progress, video { display: inline-block; vertical-align: baseline; } /** * Prevent modern browsers from displaying `audio` without controls. * Remove excess height in iOS 5 devices. */ audio:not([controls]) { display: none; height: 0; } /** * Address `[hidden]` styling not present in IE 8/9/10. * Hide the `template` element in IE 8/9/10/11, Safari, and Firefox < 22. */ [hidden], template { display: none; } /** * Remove the gray background color from active links in IE 10. */ a { background-color: transparent; } /** * Improve readability of focused elements when they are also in an * active/hover state. */ a:active, a:hover { outline: 0; } /** * Address styling not present in IE 8/9/10/11, Safari, and Chrome. */ abbr[title] { border-bottom: 1px dotted; } /** * Address style set to `bolder` in Firefox 4+, Safari, and Chrome. */ b, strong { font-weight: bold; } /** * Address styling not present in Safari and Chrome. */ dfn { font-style: italic; } /** * Address variable `h1` font-size and margin within `section` and `article` * contexts in Firefox 4+, Safari, and Chrome. */ h1 { font-size: 2em; margin: 0.67em 0; } /** * Address styling not present in IE 8/9. */ mark { background: #ff0; color: #000; } /** * Address inconsistent and variable font size in all browsers. */ small { font-size: 80%; } /** * Prevent `sub` and `sup` affecting `line-height` in all browsers. */ sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sup { top: -0.5em; } sub { bottom: -0.25em; } /** * Remove border when inside `a` element in IE 8/9/10. */ img { border: 0; } /** * Correct overflow not hidden in IE 9/10/11. */ svg:not(:root) { overflow: hidden; } /** * Address margin not present in IE 8/9 and Safari. */ figure { margin: 1em 40px; } /** * Address differences between Firefox and other browsers. */ hr { box-sizing: content-box; height: 0; } /** * Contain overflow in all browsers. */ pre { overflow: auto; } /** * Address odd `em`-unit font size rendering in all browsers. */ code, kbd, pre, samp { font-family: monospace, monospace; font-size: 1em; } /** * Known limitation: by default, Chrome and Safari on OS X allow very limited * styling of `select`, unless a `border` property is set. */ /** * 1. Correct color not being inherited. * Known issue: affects color of disabled elements. * 2. Correct font properties not being inherited. * 3. Address margins set differently in Firefox 4+, Safari, and Chrome. */ button, input, optgroup, select, textarea { color: inherit; font: inherit; margin: 0; } /** * Address `overflow` set to `hidden` in IE 8/9/10/11. */ button { overflow: visible; } /** * Address inconsistent `text-transform` inheritance for `button` and `select`. * All other form control elements do not inherit `text-transform` values. * Correct `button` style inheritance in Firefox, IE 8/9/10/11, and Opera. * Correct `select` style inheritance in Firefox. */ button, select { text-transform: none; } /** * 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio` * and `video` controls. * 2. Correct inability to style clickable `input` types in iOS. * 3. Improve usability and consistency of cursor style between image-type * `input` and others. */ button, html input[type="button"], input[type="reset"], input[type="submit"] { -webkit-appearance: button; cursor: pointer; } /** * Re-set default cursor for disabled elements. */ button[disabled], html input[disabled] { cursor: default; } /** * Remove inner padding and border in Firefox 4+. */ button::-moz-focus-inner, input::-moz-focus-inner { border: 0; padding: 0; } /** * Address Firefox 4+ setting `line-height` on `input` using `!important` in * the UA stylesheet. */ input { line-height: normal; } /** * It's recommended that you don't attempt to style these elements. * Firefox's implementation doesn't respect box-sizing, padding, or width. * * 1. Address box sizing set to `content-box` in IE 8/9/10. * 2. Remove excess padding in IE 8/9/10. */ input[type="checkbox"], input[type="radio"] { box-sizing: border-box; padding: 0; } /** * Fix the cursor style for Chrome's increment/decrement buttons. For certain * `font-size` values of the `input`, it causes the cursor style of the * decrement button to change from `default` to `text`. */ input[type="number"]::-<API key>, input[type="number"]::-<API key> { height: auto; } /** * 1. Address `appearance` set to `searchfield` in Safari and Chrome. * 2. Address `box-sizing` set to `border-box` in Safari and Chrome. */ input[type="search"] { -webkit-appearance: textfield; box-sizing: content-box; } /** * Remove inner padding and search cancel button in Safari and Chrome on OS X. * Safari (but not Chrome) clips the cancel button when the search input has * padding (and `textfield` appearance). */ input[type="search"]::-<API key>, input[type="search"]::-<API key> { -webkit-appearance: none; } /** * Define consistent border, margin, and padding. */ fieldset { border: 1px solid #c0c0c0; margin: 0 2px; padding: 0.35em 0.625em 0.75em; } /** * 1. Correct `color` not being inherited in IE 8/9/10/11. * 2. Remove padding so people aren't caught out if they zero out fieldsets. */ legend { border: 0; padding: 0; } /** * Remove default vertical scrollbar in IE 8/9/10/11. */ textarea { overflow: auto; } /** * Don't inherit the `font-weight` (applied by a rule above). * NOTE: the default cannot safely be changed in Chrome and Safari on OS X. */ optgroup { font-weight: bold; } /** * Remove most spacing between table cells. */ table { border-collapse: collapse; border-spacing: 0; } td, th { padding: 0; }
import unittest from itertools import izip import numpy as np from numpy import cos, sin, pi from pele.angleaxis import RBTopology, RigidFragment, RBPotentialWrapper from pele.potentials import LJ from pele.angleaxis._otp_cluster import OTPCluster from pele.thermodynamics import <API key> from pele.utils import rotations from pele.angleaxis._aa_utils import _rot_mat_derivative, _sitedist_grad, _sitedist from pele.angleaxis.aamindist import <API key> _x03 = np.array([2.550757898788, 2.591553038507, 3.696836364193, 2.623281513163, 3.415794212648, 3.310786279789, 1.791383852327, 2.264321752809, 4.306217333671, 0.761945654023, -0.805817782109, 1.166981882601, 0.442065301864, -2.747066418223, -1.784325262714, -1.520905562598, 0.403670860200, -0.729768985400]) _x03_atomistic = np.array([3.064051819556, 2.474533745459, 3.646107658946, 2.412011983074, 2.941152759499, 4.243695098053, 2.176209893734, 2.358972610563, 3.200706335581, 2.786627589565, 3.211876105193, 2.850924310983, 1.962626909252, 3.436918873216, 3.370903763850, 3.120590040673, 3.598587659535, 3.710530764535, 1.697360211099, 2.317229950712, 4.823998989452, 2.283487958310, 1.840698306602, 4.168734267290, 1.393303387573, 2.635037001113, 3.925918744272 ]) class TestOTPExplicit(unittest.TestCase): def make_otp(self): """this constructs a single OTP molecule""" otp = RigidFragment() otp.add_atom("O", np.array([0.0, -2./3 * np.sin( 7.*pi/24.), 0.0]), 1.) otp.add_atom("O", np.array([cos( 7.*pi/24.), 1./3. * sin( 7.* pi/24.), 0.0]), 1.) otp.add_atom("O", np.array([-cos( 7.* pi/24.), 1./3. * sin( 7.*pi/24), 0.0]), 1.) otp.finalize_setup() return otp def setUp(self): nrigid = 3 self.topology = RBTopology() self.topology.add_sites([self.make_otp() for i in xrange(nrigid)]) self.topology.finalize_setup() cartesian_potential = LJ() self.pot = RBPotentialWrapper(self.topology, cartesian_potential) self.x0 = _x03 self.x0 = np.array(self.x0) self.e0 = -17.3387670023 assert nrigid * 6 == self.x0.size self.x0atomistic = _x03_atomistic self.nrigid = nrigid def test_energy(self): e = self.pot.getEnergy(self.x0) self.assertAlmostEqual(e, self.e0, delta=1e-4) def <API key>(self): e = self.pot.getEnergy(self.x0) gnum = self.pot.NumericalDerivative(self.x0) e2, g = self.pot.getEnergyGradient(self.x0) self.assertAlmostEqual(e, e2, delta=1e-4) for i in xrange(g.size): self.assertAlmostEqual(g[i], gnum[i], 2) def test_to_atomistic(self): xatom = self.topology.to_atomistic(self.x0).flatten() for i in xrange(xatom.size): self.assertAlmostEqual(xatom[i], self.x0atomistic[i], 2) def <API key>(self): rf = self.make_otp() p = np.array([1., 2, 3]) p /= np.linalg.norm(p) com = np.array([4., 5, 6]) print "otp to atomistic" print rf.to_atomistic(com, p) print "otp transform grad" g = np.array(range(9), dtype=float).reshape([-1,3]) print g.reshape(-1) print rf.transform_grad(p, g) def test_to_atomistic2(self): x0 = np.array(range(self.nrigid * 6), dtype=float) x2 = x0.reshape([-1,3]) for p in x2[self.nrigid:,:]: p /= np.linalg.norm(p) atomistic = self.topology.to_atomistic(x0).flatten() from pele.potentials import LJ lj = LJ() e, g = lj.getEnergyGradient(atomistic.reshape(-1)) grb = self.topology.transform_gradient(x0, g) rbpot = RBPotentialWrapper(self.topology, lj) print rbpot.getEnergy(x0) class <API key>(TestOTPExplicit): def test_pot_wrapper(self): from pele.angleaxis import _cpp_aa from pele.potentials import LJ rbpot_cpp = _cpp_aa.RBPotentialWrapper(self.topology, LJ()) rbpot = RBPotentialWrapper(self.topology, LJ()) self.assertAlmostEqual(rbpot_cpp.getEnergy(self.x0), rbpot.getEnergy(self.x0), 4) e1, grad1 = rbpot_cpp.getEnergyGradient(self.x0) e2, grad2 = rbpot.getEnergyGradient(self.x0) self.assertAlmostEqual(e1, e2, 4) for g1, g2 in zip(grad1, grad2): self.assertAlmostEqual(g1, g2, 3) # print "energy cpp" # print e1, e2 # print grad1 # print grad2 _x1 = np.array([ 1.9025655 , 0.39575842, 2.70994994, 1.12711741, 0.63413933, 1.99433564, 1.86553644, 1.71434811, 2.22927686, 0.80189315, 1.19513512, 3.02357997, 1.25845172, -0.06244027, 1.27217385, -2.26564485, 0.25537024, 0.66231258, -1.49510664, 0.94428774, -0.04120075, -0.87664883, -0.21441754, 2.05796547]) _x2 = np.array([ 2.01932983, 0.32928065, 2.34949584, 1.12261277, 0.84195098, 2.08827517, 1.42644916, 1.83608794, 2.23147536, 1.12872074, 0.93206141, 3.28789605, 1.73243138, -0.1199651 , 1.02925229, -1.64603729, 0.30701482, 0.90204992, -1.96259809, 0.06557119, 0.11010908, -0.37462588, -0.42374544, 1.97728056]) class TestOTPCluster(unittest.TestCase): def setUp(self): np.random.seed(0) self.nmol = 4 self.system = OTPCluster(self.nmol) pot = self.system.get_potential() self.db = self.system.create_database() self.m1 = self.db.addMinimum(pot.getEnergy(_x1), _x1) self.m2 = self.db.addMinimum(pot.getEnergy(_x2), _x2) def test1(self): pot = self.system.get_potential() self.assertLess(np.linalg.norm(pot.getGradient(self.m1.coords)), .1) self.assertLess(np.linalg.norm(pot.getGradient(self.m2.coords)), .1) def test_basinhopping(self): db = self.system.create_database() bh = self.system.get_basinhopping(db) bh.setPrinting(ostream=None) bh.run(5) self.assertGreaterEqual(db.number_of_minima(), 1) def <API key>(self): connect = self.system.<API key>(self.m1, self.m2, self.db) connect.connect() self.assertTrue(connect.success()) path = connect.returnPath() def test_thermodynamics(self): <API key>(self.system, self.db, nproc=None, recalculate=True) self.assertIsNotNone(self.m1.fvib) mt = self.system.get_metric_tensor(self.m1.coords) print "metric tensor" print mt class TestRBTopologyOTP(unittest.TestCase): def setUp(self): np.random.seed(0) self.nmol = 3 self.system = OTPCluster(self.nmol) # pot = self.system.get_potential() # self.db = self.system.create_database() # self.m1 = self.db.addMinimum(pot.getEnergy(_x1), _x1) # self.m2 = self.db.addMinimum(pot.getEnergy(_x2), _x2) self.x0 = np.array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 0.517892, 0.575435, 0.632979, 0.531891, 0.576215, 0.620539, 0.540562, 0.5766, 0.612637 ]) from pele.angleaxis.aamindist import <API key> self.topology = self.system.aatopology self.transform = <API key>(self.topology) self.p0 = np.array(range(1,4), dtype=float) self.p0 /= np.linalg.norm(self.p0) def <API key>(self): print "\ntest rotate" x = self.x0.copy() p = np.array(range(1,4), dtype=float) p /= np.linalg.norm(p) self.transform.rotate(x, rotations.aa2mx(p)) xnewtrue = np.array([ 0.48757698, 0.61588594, 2.09355038, 2.02484605, 4.76822812, 4.81289924, 3.56211511, 8.92057031, 7.53224809, 0.71469473, 1.23875927, 1.36136748, 0.72426504, 1.24674367, 1.34426835, 0.73015833, 1.25159032, 1.33345003]) for v1, v2 in izip(x, xnewtrue): self.assertAlmostEqual(v1, v2, 5) def test_align_path(self): print "\ntest align_path" x1 = self.x0.copy() x2 = self.x0 + 5 self.topology.align_path([x1, x2]) x2true = np.array([ 5. , 6. , 7. , 8. , 9. , 10. , 11. , 12. , 13. , 1.92786071, 1.94796529, 1.96807021, 1.93320298, 1.94869267, 1.96418236, 1.93645608, 1.94905155, 1.96164668]) for v1, v2 in izip(x1, self.x0): self.assertAlmostEqual(v1, v2, 5) for v1, v2 in izip(x2, x2true): self.assertAlmostEqual(v1, v2, 5) def test_cpp_zero_ev(self): print "\ntest zeroEV cpp" x = self.x0.copy() zev = self.topology._zeroEV_python(x) czev = self.topology.cpp_topology.get_zero_modes(x) self.assertEqual(len(czev), 6) for ev, cev in izip(zev, czev): for v1, v2 in izip(ev, cev): self.assertAlmostEqual(v1, v2, 5) def <API key>(self): print "\ntest site distance squared" c0 = np.zeros(3) c1 = np.ones(3) p0 = self.p0.copy() p1 = p0 + 1 site = self.system.make_otp() d2 = site.distance_squared(c0, p0, c1, p1) d2p = _sitedist(c1-c0, p0, p1, site.S, site.W, site.cog) self.assertAlmostEqual(d2, 10.9548367929, 5) def <API key>(self): print "\ntest distance squared" x1 = self.x0.copy() x2 = self.x0 + 1.1 d2 = self.topology.distance_squared(x1, x2) d3 = self.topology.<API key>(x1, x2) self.assertAlmostEqual(d2, 38.9401810973, 5) self.assertAlmostEqual(d2, d3, 5) def <API key>(self): print "\ntest distance squared grad" x1 = self.x0.copy() x2 = self.x0 + 1.1 grad = self.topology.<API key>(x1, x2) g2 = self.topology.<API key>(x1, x2) gtrue = np.array([-6.6 , -6.6 , -6.6 , -6.6 , -6.6 , -6.6 , -6.6 , -6.6 , -6.6 , -1.21579025, -0.07013805, -1.2988823 , -1.21331786, -0.06984532, -1.28945301, -1.2116105 , -0.06975828, -1.28362943]) for v1, v2 in izip(grad, gtrue): self.assertAlmostEqual(v1, v2, 5) for v1, v2 in izip(grad, g2): self.assertAlmostEqual(v1, v2, 5) def test_measure_align(self): print "\ntest measure align" x1 = self.x0.copy() x2 = self.x0 + 5.1 x2[-1] = x1[-1] + .1 x20 = x2.copy() measure = <API key>(self.topology) measure.align(x1, x2) if __name__ == "__main__": unittest.main()
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace guess_word_game { static class Program { <summary> The main entry point for the application. </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.<API key>(false); Application.Run(new DAOForm()); } } }
# We borrow heavily from the kernel build setup, though we are simpler since # we don't have Kconfig tweaking settings on us. # The implicit make rules have it looking for RCS files, among other things. # We instead explicitly write all the rules we care about. # It's even quicker (saves ~200ms) to pass -r on the command line. MAKEFLAGS=-r # The source directory tree. srcdir := .. abs_srcdir := $(abspath $(srcdir)) # The name of the builddir. builddir_name ?= . # The V=1 flag on command line makes us verbosely print command lines. ifdef V quiet= else quiet=quiet_ endif # Specify BUILDTYPE=Release on the command line for a release build. BUILDTYPE ?= Release # Directory all our build output goes into. # Note that this must be two directories beneath src/ for unit tests to pass, # as they reach into the src/ directory for data with relative paths. builddir ?= $(builddir_name)/$(BUILDTYPE) abs_builddir := $(abspath $(builddir)) depsdir := $(builddir)/.deps # Object output directory. obj := $(builddir)/obj abs_obj := $(abspath $(obj)) # We build up a list of every single one of the targets so we can slurp in the # generated dependency rule Makefiles in one pass. all_deps := # C++ apps need to be linked with g++. # Note: flock is used to seralize linking. Linking is a memory-intensive # process so running parallel links can often lead to thrashing. To disable # the serialization, override LINK via an envrionment variable as follows: # export LINK=g++ # This will allow make to invoke N linker processes as specified in -jN. LINK ?= flock $(builddir)/linker.lock $(CXX) CC.target ?= $(CC) CFLAGS.target ?= $(CFLAGS) CXX.target ?= $(CXX) CXXFLAGS.target ?= $(CXXFLAGS) LINK.target ?= $(LINK) LDFLAGS.target ?= $(LDFLAGS) AR.target ?= $(AR) # TODO(evan): move all cross-compilation logic to gyp-time so we don't need # to replicate this environment fallback in make as well. CC.host ?= gcc CFLAGS.host ?= CXX.host ?= g++ CXXFLAGS.host ?= LINK.host ?= g++ LDFLAGS.host ?= AR.host ?= ar # Define a dir function that can handle spaces. # "leading spaces cannot appear in the text of the first argument as written. # These characters can be put into the argument value by variable substitution." empty := space := $(empty) $(empty) replace_spaces = $(subst $(space),?,$1) unreplace_spaces = $(subst ?,$(space),$1) dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1))) # Flags to make gcc output dependency info. Note that you need to be # careful here to use the flags that ccache and distcc can understand. # We write to a dep file on the side first and then rename at the end # so we can't end up with a broken dep file. depfile = $(depsdir)/$(call replace_spaces,$@).d DEPFLAGS = -MMD -MF $(depfile).raw # We have to fixup the deps output in a few ways. # (1) the file output should mention the proper .o file. # ccache or distcc lose the path to the target, so we convert a rule of # the form: # foobar.o: DEP1 DEP2 # into # path/to/foobar.o: DEP1 DEP2 # (2) we want missing files not to cause us to fail to build. # We want to rewrite # foobar.o: DEP1 DEP2 \ # DEP3 # DEP1: # DEP2: # DEP3: # so if the files are missing, they're just considered phony rules. # We have to do some pretty insane escaping to get those backslashes # and dollar signs past make, the shell, and sed at the same time. # Doesn't work with spaces, but that's fine: .d files have spaces in # their names replaced with other characters. define fixup_dep # The depfile may not exist if the input file didn't have any #includes. touch $(depfile).raw # Fixup path as in (1). sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile) # Add extra rules as in (2). # We remove slashes and replace spaces with new lines; # remove blank lines; # delete the first line and append a colon to the remaining lines. sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ grep -v '^$$' |\ sed -e 1d -e 's|$$|:|' \ >> $(depfile) rm $(depfile).raw endef # Command definitions: # - cmd_foo is the actual command to run; # - quiet_cmd_foo is the brief-output summary of the command. quiet_cmd_cc = CC($(TOOLSET)) $@ cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_cxx = CXX($(TOOLSET)) $@ cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_touch = TOUCH $@ cmd_touch = touch $@ quiet_cmd_copy = COPY $@ # send stderr to /dev/null to ignore messages when linking directories. cmd_copy = rm -rf "$@" && cp -af "$<" "$@" quiet_cmd_alink = AR($(TOOLSET)) $@ cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^) <API key> = AR($(TOOLSET)) $@ cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^) # Due to circular dependencies between libraries :(, we wrap the # special "figure out circular dependencies" flags around the entire # input list during linking. quiet_cmd_link = LINK($(TOOLSET)) $@ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS) # We support two kinds of shared objects (.so): # 1) shared_library, which is just bundling together many dependent libraries # into a link line. # 2) loadable_module, which is generating a module intended for dlopen(). # They differ only slightly: # In the former case, we want to package all dependent code into the .so. # In the latter case, we want to package just the API exposed by the # outermost module. # This means shared_library uses --whole-archive, while loadable_module doesn't. # (Note that --whole-archive is incompatible with the --start-group used in # normal linking.) # Other shared-object link notes: # - Set SONAME to the library filename so our binaries don't reference # the local, absolute paths used on the link command-line. quiet_cmd_solink = SOLINK($(TOOLSET)) $@ cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS) <API key> = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS) # Define an escape_quotes function to escape single quotes. # This allows us to handle quotes properly as long as we always use # use single quotes and escape_quotes. escape_quotes = $(subst ','\'',$(1)) # This comment is here just to include a ' to unconfuse syntax highlighting. # Define an escape_vars function to escape '$' variable syntax. # This allows us to read/write command lines with shell variables (e.g. # $LD_LIBRARY_PATH), without triggering make substitution. escape_vars = $(subst $$,$$$$,$(1)) # Helper that expands to a shell command to echo a string exactly as it is in # make. This uses printf instead of echo because printf's behaviour with respect # to escape sequences is more portable than echo's across different shells # (e.g., dash, bash). exact_echo = printf '%s\n' '$(call escape_quotes,$(1))' # Helper to compare the command we're about to run against the command # we logged the last time we ran the command. Produces an empty # string (false) when the commands match. # Tricky point: Make has no string-equality test function. # The kernel uses the following, but it seems like it would have false # positives, where one string reordered its arguments. # arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \ # $(filter-out $(cmd_$@), $(cmd_$(1)))) # We instead substitute each for the empty string into the other, and # say they're equal if both substitutions produce the empty string. # .d files contain ? instead of spaces, take that into account. command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\ $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) # Helper that is non-empty when a prerequisite changes. # Normally make does this implicitly, but we force rules to always run # so we can check their command lines. # $? -- new prerequisites # $| -- order-only dependencies prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) # Helper that executes all postbuilds, and deletes the output file when done # if any of the postbuilds failed. define do_postbuilds @E=0;\ for p in $(POSTBUILDS); do\ eval $$p;\ F=$$?;\ if [ $$F -ne 0 ]; then\ E=$$F;\ fi;\ done;\ if [ $$E -ne 0 ]; then\ rm -rf "$@";\ exit $$E;\ fi endef # do_cmd: run a command via the above cmd_foo names, if necessary. # Should always run for a given target to handle command-line changes. # Second argument, if non-zero, makes it do asm/C/C++ dependency munging. # Third argument, if non-zero, makes it do POSTBUILDS processing. # Note: We intentionally do NOT call dirx for depfile, since it contains ? for # spaces already and dirx strips the ? characters. define do_cmd $(if $(or $(command_changed),$(prereq_changed)), @$(call exact_echo, $($(quiet)cmd_$(1))) @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" $(if $(findstring flock,$(word 1,$(cmd_$1))), @$(cmd_$(1)) @echo " $(quiet_cmd_$(1)): Finished", @$(cmd_$(1)) ) @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) @$(if $(2),$(fixup_dep)) $(if $(and $(3), $(POSTBUILDS)), $(call do_postbuilds) ) ) endef # Declare the "all" target first so it is the default, # even though we don't have the deps yet. .PHONY: all all: # make looks for ways to re-generate included makefiles, but in our case, we # don't have a direct way. Explicitly telling make that it has nothing to do # for them makes it go faster. %.d: ; # Use FORCE_DO_CMD to force a target to run. Should be coupled with # do_cmd. .PHONY: FORCE_DO_CMD FORCE_DO_CMD: TOOLSET := target # Suffix rules, putting all outputs into $(obj). $(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD @$(call do_cmd,cc,1) # Try building from generated source, too. $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD @$(call do_cmd,cc,1) ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ $(findstring $(join ^,$(prefix)),\ $(join ^,bson.target.mk)))),) include bson.target.mk endif <API key> = ACTION Regenerating $@ cmd_regen_makefile = /usr/lib/nodejs/npm/node_modules/node-gyp/gyp/gyp -fmake --ignore-environment "--toplevel-dir=." -I/home/madateam/RNC/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/config.gypi -I/usr/lib/nodejs/npm/node_modules/node-gyp/addon.gypi -I/home/madateam/.node-gyp/0.8.23/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/home/madateam/.node-gyp/0.8.23" "-Dmodule_root_dir=/home/madateam/RNC/node_modules/mongoose/node_modules/mongodb/node_modules/bson" binding.gyp Makefile: $(srcdir)/../../../../../../../../../usr/lib/nodejs/npm/node_modules/node-gyp/addon.gypi $(srcdir)/../../../../../../../.node-gyp/0.8.23/common.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp $(call do_cmd,regen_makefile) # "all" is a concatenation of the "all" targets from all the included # sub-makefiles. This is just here to clarify. all: # Add in dependency-tracking rules. $(all_deps) is the list of every single # target in our tree. Only consider the ones with .d (dependency) info: d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) ifneq ($(d_files),) include $(d_files) endif
// tinygettext - A gettext replacement that works directly on .po files // This program is free software; you can redistribute it and/or // as published by the Free Software Foundation; either version 2 // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include <assert.h> #include "log_stream.hpp" #include "dictionary.hpp" namespace tinygettext { Dictionary::Dictionary(const std::string& charset_) : entries(), ctxt_entries(), charset(charset_), plural_forms() { m_has_fallback = false; } Dictionary::~Dictionary() { } std::string Dictionary::get_charset() const { return charset; } void Dictionary::set_plural_forms(const PluralForms& plural_forms_) { plural_forms = plural_forms_; } PluralForms Dictionary::get_plural_forms() const { return plural_forms; } std::string Dictionary::translate_plural(const std::string& msgid, const std::string& msgid_plural, int num) { return translate_plural(entries, msgid, msgid_plural, num); } std::string Dictionary::translate_plural(const Entries& dict, const std::string& msgid, const std::string& msgid_plural, int count) { Entries::const_iterator i = dict.find(msgid); const std::vector<std::string>& msgstrs = i->second; if (i != dict.end()) { unsigned int n = 0; n = plural_forms.get_plural(count); assert(/*n >= 0 &&*/ n < msgstrs.size()); if (!msgstrs[n].empty()) return msgstrs[n]; else if (count == 1) // default to english rules return msgid; else return msgid_plural; } else { //log_info << "Couldn't translate: " << msgid << std::endl; //log_info << "Candidates: " << std::endl; //for (i = dict.begin(); i != dict.end(); ++i) // log_info << "'" << i->first << "'" << std::endl; if (count == 1) // default to english rules return msgid; else return msgid_plural; } } std::string Dictionary::translate(const std::string& msgid) { return translate(entries, msgid); } std::string Dictionary::translate(const Entries& dict, const std::string& msgid) { Entries::const_iterator i = dict.find(msgid); if (i != dict.end() && !i->second.empty()) { return i->second[0]; } else { //log_info << "Couldn't translate: " << msgid << std::endl; if (m_has_fallback) return m_fallback->translate(msgid); else return msgid; } } std::string Dictionary::translate_ctxt(const std::string& msgctxt, const std::string& msgid) { CtxtEntries::iterator i = ctxt_entries.find(msgctxt); if (i != ctxt_entries.end()) { return translate(i->second, msgid); } else { //log_info << "Couldn't translate: " << msgid << std::endl; return msgid; } } std::string Dictionary::<API key>(const std::string& msgctxt, const std::string& msgid, const std::string& msgidplural, int num) { CtxtEntries::iterator i = ctxt_entries.find(msgctxt); if (i != ctxt_entries.end()) { return translate_plural(i->second, msgid, msgidplural, num); } else { //log_info << "Couldn't translate: " << msgid << std::endl; if (num != 1) // default to english return msgidplural; else return msgid; } } void Dictionary::add_translation(const std::string& msgid, const std::string& , const std::vector<std::string>& msgstrs) { // Do we need msgid2 for anything? its after all supplied to the // translate call, so we just throw it away here entries[msgid] = msgstrs; } void Dictionary::add_translation(const std::string& msgid, const std::string& msgstr) { std::vector<std::string>& vec = entries[msgid]; if (vec.empty()) { vec.push_back(msgstr); } else { log_warning << "collision in add_translation: '" << msgid << "' -> '" << msgstr << "' vs '" << vec[0] << "'" << std::endl; vec[0] = msgstr; } } void Dictionary::add_translation(const std::string& msgctxt, const std::string& msgid, const std::string& msgid_plural, const std::vector<std::string>& msgstrs) { std::vector<std::string>& vec = ctxt_entries[msgctxt][msgid]; if (vec.empty()) { vec = msgstrs; } else { log_warning << "collision in add_translation(\"" << msgctxt << "\", \"" << msgid << "\", \"" << msgid_plural << "\")" << std::endl; vec = msgstrs; } } void Dictionary::add_translation(const std::string& msgctxt, const std::string& msgid, const std::string& msgstr) { std::vector<std::string>& vec = ctxt_entries[msgctxt][msgid]; if (vec.empty()) { vec.push_back(msgstr); } else { log_warning << "collision in add_translation(\"" << msgctxt << "\", \"" << msgid << "\")" << std::endl; vec[0] = msgstr; } } } // namespace tinygettext /* EOF */
#include <tap/basic.h> #include <string.h> #include <stdlib.h> #include "libknot/internal/mempattern.h" #include "libknot/internal/mempool.h" #include "libknot/errcode.h" #include "knot/nameserver/query_module.h" #include "libknot/packet/pkt.h" /* Universal processing stage. */ int state_visit(int state, knot_pkt_t *pkt, struct query_data *qdata, void *ctx) { /* Visit current state */ bool *state_map = ctx; state_map[state] = true; return state + 1; } int main(int argc, char *argv[]) { plan(4); /* Create processing context. */ mm_ctx_t mm; mm_ctx_mempool(&mm, MM_DEFAULT_BLKSIZE); /* Create a map of expected steps. */ bool state_map[QUERY_PLAN_STAGES] = { false }; /* Prepare query plan. */ struct query_plan *plan = query_plan_create(&mm); ok(plan != NULL, "query_plan: create"); /* Register all stage visits. */ int ret = KNOT_EOK; for (unsigned stage = QPLAN_BEGIN; stage < QUERY_PLAN_STAGES; ++stage) { ret = query_plan_step(plan, stage, state_visit, state_map); if (ret != KNOT_EOK) { break; } } ok(ret == KNOT_EOK, "query_plan: planned all steps"); /* Execute the plan. */ int state = 0, next_state = 0; for (unsigned stage = QPLAN_BEGIN; stage < QUERY_PLAN_STAGES; ++stage) { struct query_step *step = NULL; WALK_LIST(step, plan->stage[stage]) { next_state = step->process(state, NULL, NULL, step->ctx); if (next_state != state + 1) { break; } state = next_state; } } ok(state == QUERY_PLAN_STAGES, "query_plan: executed all steps"); /* Verify if all steps executed their callback. */ for (state = 0; state < QUERY_PLAN_STAGES; ++state) { if (state_map[state] == false) { break; } } ok(state == QUERY_PLAN_STAGES, "query_plan: executed all callbacks"); /* Free the query plan. */ query_plan_free(plan); /* Cleanup. */ mp_delete((struct mempool *)mm.ctx); return 0; }
#include <gtk/gtk.h> #include "llib_tpm.h" #include "llib_opt.h" #include "llib_print.h" #include "llib_gtk.h" #include "gtpm_mgr.h" #include "gtpm_ui.h" #include "gtpm_tpm.h" #include "gtpm_uio.h" static void gtpm_mgr_reset_vars(gtpm_config_t* gmgr) { llib_data_free(&gmgr->args.output); llib_data_free(&gmgr->args.data); llib_data_free(&gmgr->args.data2); llib_data_free(&gmgr->args.encdata); gmgr->args.set = 0; <API key>(gmgr->args.keystore); } /* run a command from the label of the clicked item */ void gtpm_mgr_run (gtpm_config_t* gmgr, const char* label) { lbool res; const struct gtpm_menu_action_t* entry = &<API key>[0]; /* find the command from the label */ while (entry && entry->label && entry->job) { if (llib_str_equ(entry->label, label,0)) break; entry++; } if (!entry || !entry->label || !entry->job) { gmgr->tpm.last_error = <API key>; llib_tpm_uio_error (&gmgr->args, "Unable to run command"); llib_print_f(2, "[gtpm-mgr] unknown command label '%s'\n", label); return; } /* get descriptor */ gmgr->args.desc = <API key> (entry->job); if (!gmgr->args.desc) { gmgr->tpm.last_error = <API key>; llib_tpm_uio_error (&gmgr->args, "Unable to run command"); llib_print_f(2, "[gtpm-mgr] unknown descriptor '%s'\n", gmgr->args.desc); return; } /* set standard output if no other choice */ if ((gmgr->args.desc->in & LLIB_TPM_FOUTPUT) && !gmgr->args.cargs->output && !(gmgr->args.desc->sin & <API key>)) { gmgr->args.output = <API key>(); if (!gmgr->args.output) { llib_tpm_uio_printf (&gmgr->args, LLIB_TPM_UIO_ERR, "unable to open standard output\n"); return; } gmgr->args.set |= LLIB_TPM_FOUTPUT; } /* run the command */ <API key> (GTK_WIDGET(gmgr->ui.gWindow), GDK_CIRCLE); <API key> (); if (llib_tpm_run (&gmgr->tpm, entry->job, &gmgr->args, &res) && res) { <API key> (GTK_WIDGET(gmgr->ui.gWindow), GDK_ARROW); <API key> (gmgr->args.keystore); if (gmgr->args.output && (gmgr->args.output->type == <API key>) && (llib_buffer_type(&gmgr->args.output->data.buffer) == LLIB_BUFFER_TEXT)) { gtpmuio_output_text (&gmgr->args, "command result", &gmgr->args.output->data.buffer); } } else { <API key> (GTK_WIDGET(gmgr->ui.gWindow), GDK_ARROW); llib_tpm_uio_error (&gmgr->args, "Unable to run command"); } gtpm_mgr_reset_vars(gmgr); <API key>(GTK_WIDGET(gmgr->ui.gWindow), GDK_ARROW); } static void gtpm_mgr_clean(gtpm_config_t* gmgr) { llib_tpm_free(&gmgr->tpm); llib_tpm_store_free(gmgr->args.store); <API key>(gmgr->args.keystore); llib_tpm_uio_free(&gmgr->uio); } int main(int argc, char* argv[]) { gtpm_config_t gmgr; int retcode = EXIT_FAILURE; char c; char* arg = NULL; char* devpath = NULL; llib_mem_zero(&gmgr, sizeof(gtpm_config_t)); gmgr.args.cargs = &gmgr.cargs; gmgr.args.store = gmgr.cargs.store = &gmgr.cargs.st.store; llib_tpm_key_init(&gmgr.cargs.st.store_key); llib_tpm_store_init(gmgr.args.store, &gmgr.tpm, NULL); gmgr.cargs.st.store.key = &gmgr.cargs.st.store_key; gmgr.args.uio = &gmgr.uio; gmgr.cargs.st.ui = &gmgr.ui; gmgr.args.tpm = &gmgr.tpm; gmgr.args.keystore = &gmgr.cargs.st.keystore; gmgr.args.o = gmgr.cargs.o = &gmgr.cargs.st.o; <API key>(gmgr.args.o, NULL, NULL); gtpmuio_init(&gmgr.uio, &gmgr.args); <API key>(gmgr.args.keystore); llib_print_f(1, "gtpm-mgr v" VERSION "\n"); llib_print_f(1, "usage: [-dtpm|store|all (debug)] [-v (verbose)] " "[-tTPM_DEV_PATH (default is /dev/tpm0)]\n"); while ((c = llib_opt_get_short(argc, argv, "vd::t::", &arg)) != -1) { switch (c) { case 'v': gmgr.args.verbose = TRUE; break; case 'd': if (llib_str_equ(arg, "all", 0) || llib_str_equ(arg, "store", 0)) { gmgr.args.debug = TRUE; gmgr.args.store->debug = TRUE; } if (llib_str_equ(arg, "all", 0) || llib_str_equ(arg, "tpm",0)) gmgr.tpm.debug = TRUE; break; case 't': if (!arg) { llib_print_f(2, "[gtpm-mgr] FATAL: missing TPM device path\n"); return EXIT_FAILURE; } devpath = llib_str_dup(arg); llib_print_f(2, "[gtpm-mgr] using TPM at %s\n", arg); break; } llib_str_release(&arg); } gtk_init(&argc, &argv); if (!gtpm_ui_build(&gmgr)) { llib_print_f(2, "[gtpm-mgr] FATAL: unable to build graphical " "interface, aborting\n"); } else { if (!llib_tpm_init(&gmgr.tpm, devpath, 30, gmgr.tpm.debug)) llib_tpm_uio_error(&gmgr.args, "TPM initialization error"); else { gtk_widget_show_all(GTK_WIDGET(gmgr.ui.gWindow)); gtk_main(); retcode = EXIT_SUCCESS; } } llib_mem_free(devpath); gtpm_mgr_clean(&gmgr); return retcode; }
package algores.holonet.core.events; import algores.holonet.core.<API key>; import algores.holonet.core.Network; import algores.holonet.core.Node; import algores.holonet.core.RequestPair; import algores.holonet.core.api.Address; import algores.holonet.core.api.Key; import algores.holonet.core.api.tier1.delivery.LookupService; import com.google.common.base.Optional; import org.akraievoy.cnet.gen.vo.EntropySource; import java.util.Collection; /** * Lookup entry event. */ public class EventNetLookup extends Event<EventNetLookup> { protected int retries = 1; public Result executeInternal(final Network network, final EntropySource eSource) { Result aggregateResult = Result.PASSIVE; for (int sequentialIndex = 0; sequentialIndex < retries; sequentialIndex++) { Optional<RequestPair> optRequest = network.generateRequestPair(eSource); if (!optRequest.isPresent()) { if (sequentialIndex > 0) { throw new <API key>( "request model became empty amid request generation streak?" ); } break; } RequestPair request = optRequest.get(); Collection<Key> serverKeys = request.server.getServices().getStorage().getKeys(); final Key mapping = serverKeys.isEmpty() ? // we may also pull other keys from the range, not only the greatest one request.server.getServices().getRouting().ownRoute().getRange().getRKey().prev() : eSource.randomElement(serverKeys); final LookupService lookupSvc = request.client.getServices().getLookup(); final Address address; try { address = lookupSvc.lookup( mapping.getKey(), true, LookupService.Mode.GET, Optional.of(request.server.getAddress()) ); } catch (<API key> e) { if (!aggregateResult.equals(Result.FAILURE)) { aggregateResult = handleEventFailure(e, null); } continue; } final Node lookupResult = network.getEnv().getNode(address); if ( !lookupResult.equals(request.server) ) { network.getInterceptor().<API key>(LookupService.Mode.GET); } aggregateResult = Result.SUCCESS; } return aggregateResult; } public void setRetries(int retryCount) { this.retries = retryCount; } public EventNetLookup withRetries(int retryCount) { setRetries(retryCount); return this; } }
var path = require('path'); var Q = require('q'); var fs = require('fs'); var mv = require('mv'); var Upload = require('./upload.model'); exports.upload = function (req, res) { var tmpPath = req.files[0].path; var newFileName = Math.random().toString(36).substring(7)+path.extname(tmpPath); var targetPath = path.resolve(process.env.UPLOAD_PATH, newFileName); var defer = Q.defer(); mv(tmpPath, targetPath, function (err) { if (err) { return nextIteration.reject(err); } targetPath = targetPath.substring(targetPath.indexOf('upload')); Upload.createUpload(targetPath).then(function(upload) { defer.resolve(upload); }, function(err) { defer.reject(err); }); }); defer.promise.then(function (upload) { res.json({ status: true, data: upload._id }); }, function(err) { console.log(err); res.json({ status: false, reason: err.toString() }); }); };
/* NOTE: This file is auto-generated by pdbgen.pl */ #include "config.h" #include "gimp.h" /** * SECTION: gimplayer * @title: gimplayer * @short_description: Operations on a single layer. * * Operations on a single layer. **/ /** * _gimp_layer_new: * @image_ID: The image to which to add the layer. * @width: The layer width. * @height: The layer height. * @type: The layer type. * @name: The layer name. * @opacity: The layer opacity. * @mode: The layer combination mode. * * Create a new layer. * * This procedure creates a new layer with the specified width, height, * and type. Name, opacity, and mode are also supplied parameters. The * new layer still needs to be added to the image, as this is not * automatic. Add the new layer with the <API key>() * command. Other attributes such as layer mask modes, and offsets * should be set with explicit procedure calls. * * Returns: The newly created layer. **/ gint32 _gimp_layer_new (gint32 image_ID, gint width, gint height, GimpImageType type, const gchar *name, gdouble opacity, <API key> mode) { GimpParam *return_vals; gint nreturn_vals; gint32 layer_ID = -1; return_vals = gimp_run_procedure ("gimp-layer-new", &nreturn_vals, GIMP_PDB_IMAGE, image_ID, GIMP_PDB_INT32, width, GIMP_PDB_INT32, height, GIMP_PDB_INT32, type, GIMP_PDB_STRING, name, GIMP_PDB_FLOAT, opacity, GIMP_PDB_INT32, mode, GIMP_PDB_END); if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS) layer_ID = return_vals[1].data.d_layer; gimp_destroy_params (return_vals, nreturn_vals); return layer_ID; } /** * <API key>: * @image_ID: The source image from where the content is copied. * @dest_image_ID: The destination image to which to add the layer. * @name: The layer name. * * Create a new layer from what is visible in an image. * * This procedure creates a new layer from what is visible in the given * image. The new layer still needs to be added to the destination * image, as this is not automatic. Add the new layer with the * <API key>() command. Other attributes such as layer * mask modes, and offsets should be set with explicit procedure calls. * * Returns: The newly created layer. * * Since: GIMP 2.6 **/ gint32 <API key> (gint32 image_ID, gint32 dest_image_ID, const gchar *name) { GimpParam *return_vals; gint nreturn_vals; gint32 layer_ID = -1; return_vals = gimp_run_procedure ("<API key>", &nreturn_vals, GIMP_PDB_IMAGE, image_ID, GIMP_PDB_IMAGE, dest_image_ID, GIMP_PDB_STRING, name, GIMP_PDB_END); if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS) layer_ID = return_vals[1].data.d_layer; gimp_destroy_params (return_vals, nreturn_vals); return layer_ID; } /** * <API key>: * @drawable_ID: The source drawable from where the new layer is copied. * @dest_image_ID: The destination image to which to add the layer. * * Create a new layer by copying an existing drawable. * * This procedure creates a new layer as a copy of the specified * drawable. The new layer still needs to be added to the image, as * this is not automatic. Add the new layer with the * <API key>() command. Other attributes such as layer * mask modes, and offsets should be set with explicit procedure calls. * * Returns: The newly copied layer. **/ gint32 <API key> (gint32 drawable_ID, gint32 dest_image_ID) { GimpParam *return_vals; gint nreturn_vals; gint32 layer_copy_ID = -1; return_vals = gimp_run_procedure ("<API key>", &nreturn_vals, GIMP_PDB_DRAWABLE, drawable_ID, GIMP_PDB_IMAGE, dest_image_ID, GIMP_PDB_END); if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS) layer_copy_ID = return_vals[1].data.d_layer; gimp_destroy_params (return_vals, nreturn_vals); return layer_copy_ID; } /** * <API key>: * @image_ID: The image to which to add the layer group. * * Create a new layer group. * * This procedure creates a new layer group. Attributes such as layer * mode and opacity should be set with explicit procedure calls. Add * the new layer group (which is a kind of layer) with the * <API key>() command. * * Returns: The newly created layer group. * * Since: GIMP 2.8 **/ gint32 <API key> (gint32 image_ID) { GimpParam *return_vals; gint nreturn_vals; gint32 layer_group_ID = -1; return_vals = gimp_run_procedure ("<API key>", &nreturn_vals, GIMP_PDB_IMAGE, image_ID, GIMP_PDB_END); if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS) layer_group_ID = return_vals[1].data.d_layer; gimp_destroy_params (return_vals, nreturn_vals); return layer_group_ID; } /** * _gimp_layer_copy: * @layer_ID: The layer to copy. * @add_alpha: Add an alpha channel to the copied layer. * * Copy a layer. * * This procedure copies the specified layer and returns the copy. The * newly copied layer is for use within the original layer's image. It * should not be subsequently added to any other image. The copied * layer can optionally have an added alpha channel. This is useful if * the background layer in an image is being copied and added to the * same image. * * Returns: The newly copied layer. **/ gint32 _gimp_layer_copy (gint32 layer_ID, gboolean add_alpha) { GimpParam *return_vals; gint nreturn_vals; gint32 layer_copy_ID = -1; return_vals = gimp_run_procedure ("gimp-layer-copy", &nreturn_vals, GIMP_PDB_LAYER, layer_ID, GIMP_PDB_INT32, add_alpha, GIMP_PDB_END); if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS) layer_copy_ID = return_vals[1].data.d_layer; gimp_destroy_params (return_vals, nreturn_vals); return layer_copy_ID; } /** * <API key>: * @layer_ID: The layer. * * Add an alpha channel to the layer if it doesn't already have one. * * This procedure adds an additional component to the specified layer * if it does not already possess an alpha channel. An alpha channel * makes it possible to clear and erase to transparency, instead of the * background color. This transforms layers of type RGB to RGBA, GRAY * to GRAYA, and INDEXED to INDEXEDA. * * Returns: TRUE on success. **/ gboolean <API key> (gint32 layer_ID) { GimpParam *return_vals; gint nreturn_vals; gboolean success = TRUE; return_vals = gimp_run_procedure ("<API key>", &nreturn_vals, GIMP_PDB_LAYER, layer_ID, GIMP_PDB_END); success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS; gimp_destroy_params (return_vals, nreturn_vals); return success; } /** * gimp_layer_flatten: * @layer_ID: The layer. * * Remove the alpha channel from the layer if it has one. * * This procedure removes the alpha channel from a layer, blending all * (partially) transparent pixels in the layer against the background * color. This transforms layers of type RGBA to RGB, GRAYA to GRAY, * and INDEXEDA to INDEXED. * * Returns: TRUE on success. * * Since: GIMP 2.4 **/ gboolean gimp_layer_flatten (gint32 layer_ID) { GimpParam *return_vals; gint nreturn_vals; gboolean success = TRUE; return_vals = gimp_run_procedure ("gimp-layer-flatten", &nreturn_vals, GIMP_PDB_LAYER, layer_ID, GIMP_PDB_END); success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS; gimp_destroy_params (return_vals, nreturn_vals); return success; } /** * gimp_layer_scale: * @layer_ID: The layer. * @new_width: New layer width. * @new_height: New layer height. * @local_origin: Use a local origin (as opposed to the image origin). * * Scale the layer using the default interpolation method. * * This procedure scales the layer so that its new width and height are * equal to the supplied parameters. The 'local-origin' parameter * specifies whether to scale from the center of the layer, or from the * image origin. This operation only works if the layer has been added * to an image. The interpolation method used can be set with * <API key>(). * * Returns: TRUE on success. **/ gboolean gimp_layer_scale (gint32 layer_ID, gint new_width, gint new_height, gboolean local_origin) { GimpParam *return_vals; gint nreturn_vals; gboolean success = TRUE; return_vals = gimp_run_procedure ("gimp-layer-scale", &nreturn_vals, GIMP_PDB_LAYER, layer_ID, GIMP_PDB_INT32, new_width, GIMP_PDB_INT32, new_height, GIMP_PDB_INT32, local_origin, GIMP_PDB_END); success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS; gimp_destroy_params (return_vals, nreturn_vals); return success; } /** * <API key>: * @layer_ID: The layer. * @new_width: New layer width. * @new_height: New layer height. * @local_origin: Use a local origin (as opposed to the image origin). * @interpolation: Type of interpolation. * * Deprecated: Use gimp_layer_scale() instead. * * Returns: TRUE on success. * * Since: GIMP 2.6 **/ gboolean <API key> (gint32 layer_ID, gint new_width, gint new_height, gboolean local_origin, <API key> interpolation) { GimpParam *return_vals; gint nreturn_vals; gboolean success = TRUE; return_vals = gimp_run_procedure ("<API key>", &nreturn_vals, GIMP_PDB_LAYER, layer_ID, GIMP_PDB_INT32, new_width, GIMP_PDB_INT32, new_height, GIMP_PDB_INT32, local_origin, GIMP_PDB_INT32, interpolation, GIMP_PDB_END); success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS; gimp_destroy_params (return_vals, nreturn_vals); return success; } /** * gimp_layer_resize: * @layer_ID: The layer. * @new_width: New layer width. * @new_height: New layer height. * @offx: x offset between upper left corner of old and new layers: (old - new). * @offy: y offset between upper left corner of old and new layers: (old - new). * * Resize the layer to the specified extents. * * This procedure resizes the layer so that its new width and height * are equal to the supplied parameters. Offsets are also provided * which describe the position of the previous layer's content. This * operation only works if the layer has been added to an image. * * Returns: TRUE on success. **/ gboolean gimp_layer_resize (gint32 layer_ID, gint new_width, gint new_height, gint offx, gint offy) { GimpParam *return_vals; gint nreturn_vals; gboolean success = TRUE; return_vals = gimp_run_procedure ("gimp-layer-resize", &nreturn_vals, GIMP_PDB_LAYER, layer_ID, GIMP_PDB_INT32, new_width, GIMP_PDB_INT32, new_height, GIMP_PDB_INT32, offx, GIMP_PDB_INT32, offy, GIMP_PDB_END); success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS; gimp_destroy_params (return_vals, nreturn_vals); return success; } /** * <API key>: * @layer_ID: The layer to resize. * * Resize a layer to the image size. * * This procedure resizes the layer so that it's new width and height * are equal to the width and height of its image container. * * Returns: TRUE on success. **/ gboolean <API key> (gint32 layer_ID) { GimpParam *return_vals; gint nreturn_vals; gboolean success = TRUE; return_vals = gimp_run_procedure ("<API key>", &nreturn_vals, GIMP_PDB_LAYER, layer_ID, GIMP_PDB_END); success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS; gimp_destroy_params (return_vals, nreturn_vals); return success; } /** * <API key>: * @layer_ID: The layer. * @offx: Offset in x direction. * @offy: Offset in y direction. * * Translate the layer by the specified offsets. * * This procedure translates the layer by the amounts specified in the * x and y arguments. These can be negative, and are considered offsets * from the current position. This command only works if the layer has * been added to an image. All additional layers contained in the image * which have the linked flag set to TRUE w ill also be translated by * the specified offsets. * * Returns: TRUE on success. **/ gboolean <API key> (gint32 layer_ID, gint offx, gint offy) { GimpParam *return_vals; gint nreturn_vals; gboolean success = TRUE; return_vals = gimp_run_procedure ("<API key>", &nreturn_vals, GIMP_PDB_LAYER, layer_ID, GIMP_PDB_INT32, offx, GIMP_PDB_INT32, offy, GIMP_PDB_END); success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS; gimp_destroy_params (return_vals, nreturn_vals); return success; } /** * <API key>: * @layer_ID: The layer. * @offx: Offset in x direction. * @offy: Offset in y direction. * * Set the layer offsets. * * This procedure sets the offsets for the specified layer. The offsets * are relative to the image origin and can be any values. This * operation is valid only on layers which have been added to an image. * * Returns: TRUE on success. **/ gboolean <API key> (gint32 layer_ID, gint offx, gint offy) { GimpParam *return_vals; gint nreturn_vals; gboolean success = TRUE; return_vals = gimp_run_procedure ("<API key>", &nreturn_vals, GIMP_PDB_LAYER, layer_ID, GIMP_PDB_INT32, offx, GIMP_PDB_INT32, offy, GIMP_PDB_END); success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS; gimp_destroy_params (return_vals, nreturn_vals); return success; } /** * <API key>: * @layer_ID: The layer to which to add the mask. * @mask_type: The type of mask. * * Create a layer mask for the specified layer. * * This procedure creates a layer mask for the specified layer. Layer * masks serve as an additional alpha channel for a layer. A number of * different types of masks are allowed for initialisation: completely * white masks (which will leave the layer fully visible), completely * black masks (which will give the layer complete transparency, the * layer's already existing alpha channel (which will leave the layer * fully visible, but which may be more useful than a white mask), the * current selection or a grayscale copy of the layer. The layer mask * still needs to be added to the layer. This can be done with a call * to gimp_layer_add_mask(). * * Returns: The newly created mask. **/ gint32 <API key> (gint32 layer_ID, GimpAddMaskType mask_type) { GimpParam *return_vals; gint nreturn_vals; gint32 mask_ID = -1; return_vals = gimp_run_procedure ("<API key>", &nreturn_vals, GIMP_PDB_LAYER, layer_ID, GIMP_PDB_INT32, mask_type, GIMP_PDB_END); if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS) mask_ID = return_vals[1].data.d_layer_mask; gimp_destroy_params (return_vals, nreturn_vals); return mask_ID; } /** * gimp_layer_get_mask: * @layer_ID: The layer. * * Get the specified layer's mask if it exists. * * This procedure returns the specified layer's mask, or -1 if none * exists. * * Returns: The layer mask. **/ gint32 gimp_layer_get_mask (gint32 layer_ID) { GimpParam *return_vals; gint nreturn_vals; gint32 mask_ID = -1; return_vals = gimp_run_procedure ("gimp-layer-get-mask", &nreturn_vals, GIMP_PDB_LAYER, layer_ID, GIMP_PDB_END); if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS) mask_ID = return_vals[1].data.d_layer_mask; gimp_destroy_params (return_vals, nreturn_vals); return mask_ID; } /** * <API key>: * @mask_ID: Mask for which to return the layer. * * Get the specified mask's layer. * * This procedure returns the specified mask's layer , or -1 if none * exists. * * Returns: The mask's layer. * * Since: GIMP 2.2 **/ gint32 <API key> (gint32 mask_ID) { GimpParam *return_vals; gint nreturn_vals; gint32 layer_ID = -1; return_vals = gimp_run_procedure ("<API key>", &nreturn_vals, GIMP_PDB_CHANNEL, mask_ID, GIMP_PDB_END); if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS) layer_ID = return_vals[1].data.d_layer; gimp_destroy_params (return_vals, nreturn_vals); return layer_ID; } /** * gimp_layer_add_mask: * @layer_ID: The layer to receive the mask. * @mask_ID: The mask to add to the layer. * * Add a layer mask to the specified layer. * * This procedure adds a layer mask to the specified layer. Layer masks * serve as an additional alpha channel for a layer. This procedure * will fail if a number of prerequisites aren't met. The layer cannot * already have a layer mask. The specified mask must exist and have * the same dimensions as the layer. The layer must have been created * for use with the specified image and the mask must have been created * with the procedure '<API key>'. * * Returns: TRUE on success. **/ gboolean gimp_layer_add_mask (gint32 layer_ID, gint32 mask_ID) { GimpParam *return_vals; gint nreturn_vals; gboolean success = TRUE; return_vals = gimp_run_procedure ("gimp-layer-add-mask", &nreturn_vals, GIMP_PDB_LAYER, layer_ID, GIMP_PDB_CHANNEL, mask_ID, GIMP_PDB_END); success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS; gimp_destroy_params (return_vals, nreturn_vals); return success; } /** * <API key>: * @layer_ID: The layer from which to remove mask. * @mode: Removal mode. * * Remove the specified layer mask from the layer. * * This procedure removes the specified layer mask from the layer. If * the mask doesn't exist, an error is returned. * * Returns: TRUE on success. **/ gboolean <API key> (gint32 layer_ID, GimpMaskApplyMode mode) { GimpParam *return_vals; gint nreturn_vals; gboolean success = TRUE; return_vals = gimp_run_procedure ("<API key>", &nreturn_vals, GIMP_PDB_LAYER, layer_ID, GIMP_PDB_INT32, mode, GIMP_PDB_END); success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS; gimp_destroy_params (return_vals, nreturn_vals); return success; } /** * <API key>: * @layer_ID: The layer. * * Is the specified layer a floating selection? * * This procedure returns whether the layer is a floating selection. * Floating selections are special cases of layers which are attached * to a specific drawable. * * Returns: TRUE if the layer is a floating selection. **/ gboolean <API key> (gint32 layer_ID) { GimpParam *return_vals; gint nreturn_vals; gboolean is_floating_sel = FALSE; return_vals = gimp_run_procedure ("<API key>", &nreturn_vals, GIMP_PDB_LAYER, layer_ID, GIMP_PDB_END); if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS) is_floating_sel = return_vals[1].data.d_int32; gimp_destroy_params (return_vals, nreturn_vals); return is_floating_sel; } /** * <API key>: * @layer_ID: The layer. * * Get the lock alpha channel setting of the specified layer. * * This procedure returns the specified layer's lock alpha channel * setting. * * Returns: The layer's lock alpha channel setting. **/ gboolean <API key> (gint32 layer_ID) { GimpParam *return_vals; gint nreturn_vals; gboolean lock_alpha = FALSE; return_vals = gimp_run_procedure ("<API key>", &nreturn_vals, GIMP_PDB_LAYER, layer_ID, GIMP_PDB_END); if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS) lock_alpha = return_vals[1].data.d_int32; gimp_destroy_params (return_vals, nreturn_vals); return lock_alpha; } /** * <API key>: * @layer_ID: The layer. * @lock_alpha: The new layer's lock alpha channel setting. * * Set the lock alpha channel setting of the specified layer. * * This procedure sets the specified layer's lock alpha channel * setting. * * Returns: TRUE on success. **/ gboolean <API key> (gint32 layer_ID, gboolean lock_alpha) { GimpParam *return_vals; gint nreturn_vals; gboolean success = TRUE; return_vals = gimp_run_procedure ("<API key>", &nreturn_vals, GIMP_PDB_LAYER, layer_ID, GIMP_PDB_INT32, lock_alpha, GIMP_PDB_END); success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS; gimp_destroy_params (return_vals, nreturn_vals); return success; } /** * <API key>: * @layer_ID: The layer. * * Get the apply mask setting of the specified layer. * * This procedure returns the specified layer's apply mask setting. If * the value is TRUE, then the layer mask for this layer is currently * being composited with the layer's alpha channel. * * Returns: The layer's apply mask setting. **/ gboolean <API key> (gint32 layer_ID) { GimpParam *return_vals; gint nreturn_vals; gboolean apply_mask = FALSE; return_vals = gimp_run_procedure ("<API key>", &nreturn_vals, GIMP_PDB_LAYER, layer_ID, GIMP_PDB_END); if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS) apply_mask = return_vals[1].data.d_int32; gimp_destroy_params (return_vals, nreturn_vals); return apply_mask; } /** * <API key>: * @layer_ID: The layer. * @apply_mask: The new layer's apply mask setting. * * Set the apply mask setting of the specified layer. * * This procedure sets the specified layer's apply mask setting. This * controls whether the layer's mask is currently affecting the alpha * channel. If there is no layer mask, this function will return an * error. * * Returns: TRUE on success. **/ gboolean <API key> (gint32 layer_ID, gboolean apply_mask) { GimpParam *return_vals; gint nreturn_vals; gboolean success = TRUE; return_vals = gimp_run_procedure ("<API key>", &nreturn_vals, GIMP_PDB_LAYER, layer_ID, GIMP_PDB_INT32, apply_mask, GIMP_PDB_END); success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS; gimp_destroy_params (return_vals, nreturn_vals); return success; } /** * <API key>: * @layer_ID: The layer. * * Get the show mask setting of the specified layer. * * This procedure returns the specified layer's show mask setting. This * controls whether the layer or its mask is visible. TRUE indicates * that the mask should be visible. If the layer has no mask, then this * function returns an error. * * Returns: The layer's show mask setting. **/ gboolean <API key> (gint32 layer_ID) { GimpParam *return_vals; gint nreturn_vals; gboolean show_mask = FALSE; return_vals = gimp_run_procedure ("<API key>", &nreturn_vals, GIMP_PDB_LAYER, layer_ID, GIMP_PDB_END); if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS) show_mask = return_vals[1].data.d_int32; gimp_destroy_params (return_vals, nreturn_vals); return show_mask; } /** * <API key>: * @layer_ID: The layer. * @show_mask: The new layer's show mask setting. * * Set the show mask setting of the specified layer. * * This procedure sets the specified layer's show mask setting. This * controls whether the layer or its mask is visible. TRUE indicates * that the mask should be visible. If there is no layer mask, this * function will return an error. * * Returns: TRUE on success. **/ gboolean <API key> (gint32 layer_ID, gboolean show_mask) { GimpParam *return_vals; gint nreturn_vals; gboolean success = TRUE; return_vals = gimp_run_procedure ("<API key>", &nreturn_vals, GIMP_PDB_LAYER, layer_ID, GIMP_PDB_INT32, show_mask, GIMP_PDB_END); success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS; gimp_destroy_params (return_vals, nreturn_vals); return success; } /** * <API key>: * @layer_ID: The layer. * * Get the edit mask setting of the specified layer. * * This procedure returns the specified layer's edit mask setting. If * the value is TRUE, then the layer mask for this layer is currently * active, and not the layer. * * Returns: The layer's edit mask setting. **/ gboolean <API key> (gint32 layer_ID) { GimpParam *return_vals; gint nreturn_vals; gboolean edit_mask = FALSE; return_vals = gimp_run_procedure ("<API key>", &nreturn_vals, GIMP_PDB_LAYER, layer_ID, GIMP_PDB_END); if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS) edit_mask = return_vals[1].data.d_int32; gimp_destroy_params (return_vals, nreturn_vals); return edit_mask; } /** * <API key>: * @layer_ID: The layer. * @edit_mask: The new layer's edit mask setting. * * Set the edit mask setting of the specified layer. * * This procedure sets the specified layer's edit mask setting. This * controls whether the layer or it's mask is currently active for * editing. If the specified layer has no layer mask, then this * procedure will return an error. * * Returns: TRUE on success. **/ gboolean <API key> (gint32 layer_ID, gboolean edit_mask) { GimpParam *return_vals; gint nreturn_vals; gboolean success = TRUE; return_vals = gimp_run_procedure ("<API key>", &nreturn_vals, GIMP_PDB_LAYER, layer_ID, GIMP_PDB_INT32, edit_mask, GIMP_PDB_END); success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS; gimp_destroy_params (return_vals, nreturn_vals); return success; } /** * <API key>: * @layer_ID: The layer. * * Get the opacity of the specified layer. * * This procedure returns the specified layer's opacity. * * Returns: The layer opacity. **/ gdouble <API key> (gint32 layer_ID) { GimpParam *return_vals; gint nreturn_vals; gdouble opacity = 0.0; return_vals = gimp_run_procedure ("<API key>", &nreturn_vals, GIMP_PDB_LAYER, layer_ID, GIMP_PDB_END); if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS) opacity = return_vals[1].data.d_float; gimp_destroy_params (return_vals, nreturn_vals); return opacity; } /** * <API key>: * @layer_ID: The layer. * @opacity: The new layer opacity. * * Set the opacity of the specified layer. * * This procedure sets the specified layer's opacity. * * Returns: TRUE on success. **/ gboolean <API key> (gint32 layer_ID, gdouble opacity) { GimpParam *return_vals; gint nreturn_vals; gboolean success = TRUE; return_vals = gimp_run_procedure ("<API key>", &nreturn_vals, GIMP_PDB_LAYER, layer_ID, GIMP_PDB_FLOAT, opacity, GIMP_PDB_END); success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS; gimp_destroy_params (return_vals, nreturn_vals); return success; } /** * gimp_layer_get_mode: * @layer_ID: The layer. * * Get the combination mode of the specified layer. * * This procedure returns the specified layer's combination mode. * * Returns: The layer combination mode. **/ <API key> gimp_layer_get_mode (gint32 layer_ID) { GimpParam *return_vals; gint nreturn_vals; <API key> mode = 0; return_vals = gimp_run_procedure ("gimp-layer-get-mode", &nreturn_vals, GIMP_PDB_LAYER, layer_ID, GIMP_PDB_END); if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS) mode = return_vals[1].data.d_int32; gimp_destroy_params (return_vals, nreturn_vals); return mode; } /** * gimp_layer_set_mode: * @layer_ID: The layer. * @mode: The new layer combination mode. * * Set the combination mode of the specified layer. * * This procedure sets the specified layer's combination mode. * * Returns: TRUE on success. **/ gboolean gimp_layer_set_mode (gint32 layer_ID, <API key> mode) { GimpParam *return_vals; gint nreturn_vals; gboolean success = TRUE; return_vals = gimp_run_procedure ("gimp-layer-set-mode", &nreturn_vals, GIMP_PDB_LAYER, layer_ID, GIMP_PDB_INT32, mode, GIMP_PDB_END); success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS; gimp_destroy_params (return_vals, nreturn_vals); return success; }
// Karma configuration // Generated on Thu Jul 24 2014 18:11:41 GMT-0700 (PDT) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ 'bower_components/angular/angular.js', 'bower_components/angular-mocks/angular-mocks.js', 'bower_components/angular-resource/angular-resource.js',
package br.ifrn.meutcc.visao; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import br.ifrn.meutcc.modelo.Aluno; import br.ifrn.meutcc.modelo.Orientador; @WebServlet("/ViewAlunoCandidatou") public class ViewAlunoCandidatou extends HttpServlet { private static final long serialVersionUID = 1L; public ViewAlunoCandidatou() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); int idCandidato = 2; int idTema = -1; try { idTema = Integer.parseInt(id); } catch (<API key> nfex) { nfex.printStackTrace(); } Orientador a = new Orientador(); Orientador orientador = a.<API key>(idTema); Aluno logic = new Aluno(); logic.registraObserver(orientador); boolean aluno = logic.addCandidato(idTema, idCandidato); request.setAttribute("candidatou", logic.getStatus()); request.setAttribute("aluno", aluno); request.<API key>("viewAluno.jsp").forward(request, response); } }
/* Template filled out by CMake */ #ifndef <API key> #error Please include PdfDefines.h instead #endif #define <API key> 0 #define <API key> 9 #define <API key> 0 /* PoDoFo configuration options */ #define PODOFO_MULTI_THREAD /* somewhat platform-specific headers */ #define <API key> 1 #define <API key> 1 /* #undef <API key> */ /* #undef PODOFO_HAVE_MEM_H */ /* #undef PODOFO_HAVE_CTYPE_H */ /* Integer types - headers */ #define <API key> 1 /* #undef <API key> */ #define <API key> 1 /* Integer types - type names */ #define PDF_INT8_TYPENAME int8_t #define PDF_INT16_TYPENAME int16_t #define PDF_INT32_TYPENAME int32_t #define PDF_INT64_TYPENAME int64_t #define PDF_UINT8_TYPENAME uint8_t #define PDF_UINT16_TYPENAME uint16_t #define PDF_UINT32_TYPENAME uint32_t #define PDF_UINT64_TYPENAME uint64_t /* Endianness */ /* #undef TEST_BIG */ /* Libraries */ #define <API key> #define PODOFO_HAVE_PNG_LIB #define <API key> #define <API key> #define PODOFO_HAVE_LUA /* #undef PODOFO_HAVE_BOOST */ #define PODOFO_HAVE_CPPUNIT /* Platform quirks */ #define <API key>
<?php class <API key> extends bas_frmx_cardframe{ public function __construct($id, $tabs='', $grid=array('width'=>4,'height'=>4)) { parent::__construct($id,$tabs,$grid); //addComponent($tab, $x, $y, $width, $height, $field); //construct FIELD ($id,$type,$name, $caption, $editable, $value,$visible). ##Nota: el campo type deberia quitarse. $width=2; $height = 1; $this->SetMode("edit"); $this->tabs = array("Primera","Segunda","Tercera","Cuarta"); $this->query = new bas_sqlx_querydef(); $this->query->add("concepto","test"); $this->query->setkey(array('idconcepto')); $this->query->order= array("idconcepto"=>"asc"); $this->query->addcol("idconcepto", "Concepto","concepto" ,true,'test'); $this->query->addcol("descripcion", "Descripción","concepto" ,false,'test',"upload"); $this->query->addcol("caption", "Caption","concepto" ,false,'test'); $this->query->addcol("tipo", "Tipo:","concepto" ,false,'test',"enum"); $this->setAttr("tipo","enum",array('editable'=>'editable','fijo'=>'fijo','calculado'=>'calculado')); $this->setAttr('idconcepto','lookup','frmx_cardframe_form'); $this->addComponent("Primera", 1, 1, $width, $height,"idconcepto",'test'); $this->addComponent("Primera", 1, 2, $width, $height, "descripcion",'test'); $this->addComponent("Primera", 1, 3, $width, $height,"caption",'test'); $this->addComponent("Primera", 1, 4, $width, $height,"tipo",'test'); $this->query->addcol("formato", "Tipo:","concepto" ,false,'test',"enum"); $this->query->addcol("opcionstring", "Opciones","concepto" ,false,'test'); $this->query->addcol("imagenstring", "Nombre de la imagen","concepto" ,false,'test'); $this->query->addcol("datomultiple", "Dato multiple ","concepto" ,false,'test'); $this->setAttr("formato","enum",array('numérico'=>'numérico','moneda'=>'moneda','booleano'=>'booleano','opción'=>'opción')); $this->addComponent("Segunda", 2, 1, $width, $height,"formato"); $this->addComponent("Segunda", 2, 2, $width, $height,"opcionstring"); $this->addComponent("Segunda", 3, 3, $width, $height,"imagenstring"); $this->addComponent("Segunda", 3, 4, $width, $height,"datomultiple"); $this->query->addcol("valor", "Valor","concepto" ,false,'test'); $this->query->addcol("calcorden", "Cálculo del orden","concepto" ,false,'test'); $this->query->addcol("distribuirvalor", "Valor del distibuidor","concepto" ,false,'test'); $this->query->addcol("sumarizeoper", "aritmética","concepto" ,false,'test',"enum"); $this->setAttr("sumarizeoper","enum",array('media'=>'media','suma'=>'suma','mínimo'=>'mínimo','máximo'=>'máximo','moda'=>'moda')); $this->addComponent("Tercera", 1, 1, 1, $height, "valor"); $this->addComponent("Tercera", 1, 2, $width, $height,"calcorden"); $this->addComponent("Tercera", 3, 1, $width, $height,"distribuirvalor"); $this->addComponent("Tercera", 3, 2, $width, $height,"sumarizeoper"); /* fechavalor enum('fecha inicio periodo','fecha factura') DEFAULT NULL, alerta int(11) NOT NULL DEFAULT '0', alertimage int(11) NOT NULL DEFAULT '0', alertmincount int(11) NOT NULL DEFAULT '1', */ $this->query->addcol("fechavalor", "Fecha","concepto" ,false,'test'); $this->query->addcol("alerta", "alerta","concepto" ,false,'test'); $this->query->addcol("alertimage", "alertimage","concepto" ,false,'test'); $this->query->addcol("alertmincount", "alertmincount","concepto" ,false,'test',"enum"); $this->setAttr("alertmincount","enum",array('fecha inicio periodo'=>'fecha inicio periodo','fecha factura'=>'fecha factura')); $this->addComponent("Cuarta", 1, 1, 1, $height, "fechavalor"); $this->addComponent("Cuarta", 2, 1, $width, $height, "alerta"); $this->addComponent("Cuarta", 3, 1, $width, $height,"alertimage"); $this->addComponent("Cuarta", 1, 2, $width, $height,"alertmincount"); $this->setRecord(); } } /* alertrepe int(11) DEFAULT NULL, dynclass varchar(20) DEFAULT NULL, */ ?>
package com.idega.development.presentation; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWMainApplication; import com.idega.presentation.IWContext; import com.idega.presentation.Image; import com.idega.presentation.Layer; import com.idega.presentation.PresentationObject; import com.idega.presentation.Table; import com.idega.presentation.text.HorizontalRule; import com.idega.presentation.text.Text; import com.idega.presentation.ui.IFrame; import com.idega.repository.data.<API key>; public class IWDeveloper extends com.idega.presentation.app.IWApplication { private static final String localizerParameter = "iw_localizer"; private static final String <API key> = "iw_localeswitcher"; private static final String <API key> = "iw_bundlecreator"; private static final String <API key> = "<API key>"; private static final String <API key> = "<API key>"; private static final String <API key> = "<API key>"; public static final String actionParameter = "iw_developer_action"; public static final String <API key> = "<API key>"; public static final String <API key> = "iw_update_manager"; public static final String frameName = "iwdv_rightFrame"; public static final String <API key> = "iwdv_class_name"; public IWDeveloper() { super("idegaWeb Developer"); add(IWDeveloper.IWDevPage.class); super.setResizable(true); super.setScrollbar(true); super.setScrolling(1, true); super.setWidth(800); super.setHeight(600); //super.setOnLoad("moveTo(0,0);"); } public static class IWDevPage extends com.idega.presentation.ui.Window { public IWDevPage() { this.setStatus(true); } private Table mainTable; private Table objectTable; private IFrame rightFrame; private int count = 1; public void main(IWContext iwc) throws Exception { IWBundle iwbCore = getBundle(iwc); if (iwc.isIE()) { getParentPage().setBackgroundColor("#B0B29D"); } Layer topLayer = new Layer(Layer.DIV); topLayer.setZIndex(3); topLayer.setPositionType(Layer.FIXED); topLayer.setTopPosition(0); topLayer.setLeftPosition(0); topLayer.setBackgroundColor("#0E2456"); topLayer.setWidth(Table.HUNDRED_PERCENT); topLayer.setHeight(25); add(topLayer); Table headerTable = new Table(); headerTable.setCellpadding(0); headerTable.setCellspacing(0); headerTable.setWidth(Table.HUNDRED_PERCENT); headerTable.setAlignment(2,1,Table.<API key>); topLayer.add(headerTable); Image idegaweb = iwbCore.getImage("/editorwindow/idegaweb.gif","idegaWeb"); headerTable.add(idegaweb,1,1); Text adminTitle = new Text("idegaWeb Developer"); adminTitle.setStyleAttribute("color:#FFFFFF;font-family:Arial,Helvetica,sans-serif;font-size:12px;font-weight:bold;margin-right:5px;"); headerTable.add(adminTitle,2,1); Layer leftLayer = new Layer(Layer.DIV); leftLayer.setZIndex(2); leftLayer.setPositionType(Layer.FIXED); leftLayer.setTopPosition(25); leftLayer.setLeftPosition(0); leftLayer.setPadding(5); leftLayer.setBackgroundColor("#B0B29D"); leftLayer.setWidth(180); leftLayer.setHeight(Table.HUNDRED_PERCENT); add(leftLayer); DeveloperList list = new DeveloperList(); leftLayer.add(list); Layer rightLayer = new Layer(Layer.DIV); rightLayer.setZIndex(1); rightLayer.setPositionType(Layer.ABSOLUTE); rightLayer.setTopPosition(25); rightLayer.setPadding(5); if (iwc.isIE()) { rightLayer.setBackgroundColor("#FFFFFF"); rightLayer.setWidth(Table.HUNDRED_PERCENT); rightLayer.setHeight(Table.HUNDRED_PERCENT); rightLayer.setLeftPosition(180); } else { rightLayer.setLeftPosition(190); } add(rightLayer); if (iwc.isParameterSet(<API key>)) { String className = IWMainApplication.decryptClassName(iwc.getParameter(<API key>)); PresentationObject obj = (PresentationObject) <API key>.getInstance().newInstance(className, this.getClass()); rightLayer.add(obj); } else { rightLayer.add(new Localizer()); } } } public static Table getTitleTable(String displayString, Image image) { Table titleTable = new Table(1, 2); titleTable.setCellpadding(0); titleTable.setCellspacing(0); titleTable.setWidth("100%"); Text headline = getText(displayString); headline.setFontSize(Text.FONT_SIZE_14_HTML_4); headline.setFontColor("#0E2456"); if (image != null) { image.<API key>(5); titleTable.add(image, 1, 1); } titleTable.add(headline, 1, 1); titleTable.add(new HorizontalRule("100%", 2, "color: #FF9310", true), 1, 2); return titleTable; } public static Table getTitleTable(String displayString) { return getTitleTable(displayString, null); } public static Table getTitleTable(Class classToUse, Image image) { return getTitleTable(classToUse.getName().substring(classToUse.getName().lastIndexOf(".") + 1), image); } public static Table getTitleTable(Class classToUse) { return getTitleTable(classToUse, null); } public static Text getText(String text) { Text T = new Text(text); T.setBold(); T.setFontFace(Text.FONT_FACE_VERDANA); T.setFontSize(Text.FONT_SIZE_10_HTML_2); return T; } }
package itaf.WsCartItemService; import java.math.BigDecimal; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "<API key>", propOrder = { "<API key>", "receivableAmount", "actualAmount", "distributionAmount" }) public class <API key> extends OperateDto { protected <API key> <API key>; protected BigDecimal receivableAmount; protected BigDecimal actualAmount; protected BigDecimal distributionAmount; public <API key> <API key>() { return <API key>; } public void <API key>(<API key> value) { this.<API key> = value; } public BigDecimal getReceivableAmount() { return receivableAmount; } public void setReceivableAmount(BigDecimal value) { this.receivableAmount = value; } public BigDecimal getActualAmount() { return actualAmount; } public void setActualAmount(BigDecimal value) { this.actualAmount = value; } public BigDecimal <API key>() { return distributionAmount; } public void <API key>(BigDecimal value) { this.distributionAmount = value; } }
# -*- coding: utf8 -*- SQL = """select SQL_CALC_FOUND_ROWS * FROM doc_view order by `name` asc limit %(offset)d,%(limit)d ;""" FOUND_ROWS = True ROOT = "doc_view_list" ROOT_PREFIX = "<doc_view_edit />" ROOT_POSTFIX= None XSL_TEMPLATE = "data/af-web.xsl" EVENT = None WHERE = () PARAM = None TITLE="Список видов документов" MESSAGE="ошибка получения списка видов документов" ORDER = None
Trying to figure out: * Why two hierarchies? * How do they differ? * Do they share any entities? Approach: Make a XE db and have a look.
package org.schabi.newpipe.util; import android.animation.Animator; import android.animation.<API key>; import android.animation.ArgbEvaluator; import android.animation.ValueAnimator; import android.content.res.ColorStateList; import android.util.Log; import android.view.View; import android.widget.TextView; import androidx.annotation.ColorInt; import androidx.annotation.FloatRange; import androidx.core.view.ViewCompat; import androidx.interpolator.view.animation.<API key>; import org.schabi.newpipe.MainActivity; public final class AnimationUtils { private static final String TAG = "AnimationUtils"; private static final boolean DEBUG = MainActivity.DEBUG; private AnimationUtils() { } public static void animateView(final View view, final boolean enterOrExit, final long duration) { animateView(view, Type.ALPHA, enterOrExit, duration, 0, null); } public static void animateView(final View view, final boolean enterOrExit, final long duration, final long delay) { animateView(view, Type.ALPHA, enterOrExit, duration, delay, null); } public static void animateView(final View view, final boolean enterOrExit, final long duration, final long delay, final Runnable execOnEnd) { animateView(view, Type.ALPHA, enterOrExit, duration, delay, execOnEnd); } public static void animateView(final View view, final Type animationType, final boolean enterOrExit, final long duration) { animateView(view, animationType, enterOrExit, duration, 0, null); } public static void animateView(final View view, final Type animationType, final boolean enterOrExit, final long duration, final long delay) { animateView(view, animationType, enterOrExit, duration, delay, null); } /** * Animate the view. * * @param view view that will be animated * @param animationType {@link Type} of the animation * @param enterOrExit true to enter, false to exit * @param duration how long the animation will take, in milliseconds * @param delay how long the animation will wait to start, in milliseconds * @param execOnEnd runnable that will be executed when the animation ends */ public static void animateView(final View view, final Type animationType, final boolean enterOrExit, final long duration, final long delay, final Runnable execOnEnd) { if (DEBUG) { String id; try { id = view.getResources().<API key>(view.getId()); } catch (final Exception e) { id = view.getId() + ""; } final String msg = String.format("%8s → [%s:%s] [%s %s:%s] execOnEnd=%s", enterOrExit, view.getClass().getSimpleName(), id, animationType, duration, delay, execOnEnd); Log.d(TAG, "animateView()" + msg); } if (view.getVisibility() == View.VISIBLE && enterOrExit) { if (DEBUG) { Log.d(TAG, "animateView() view was already visible > view = [" + view + "]"); } view.animate().setListener(null).cancel(); view.setVisibility(View.VISIBLE); view.setAlpha(1f); if (execOnEnd != null) { execOnEnd.run(); } return; } else if ((view.getVisibility() == View.GONE || view.getVisibility() == View.INVISIBLE) && !enterOrExit) { if (DEBUG) { Log.d(TAG, "animateView() view was already gone > view = [" + view + "]"); } view.animate().setListener(null).cancel(); view.setVisibility(View.GONE); view.setAlpha(0f); if (execOnEnd != null) { execOnEnd.run(); } return; } view.animate().setListener(null).cancel(); view.setVisibility(View.VISIBLE); switch (animationType) { case ALPHA: animateAlpha(view, enterOrExit, duration, delay, execOnEnd); break; case SCALE_AND_ALPHA: <API key>(view, enterOrExit, duration, delay, execOnEnd); break; case <API key>: <API key>(view, enterOrExit, duration, delay, execOnEnd); break; case SLIDE_AND_ALPHA: <API key>(view, enterOrExit, duration, delay, execOnEnd); break; case <API key>: <API key>(view, enterOrExit, duration, delay, execOnEnd); break; } } /** * Animate the background color of a view. * * @param view the view to animate * @param duration the duration of the animation * @param colorStart the background color to start with * @param colorEnd the background color to end with */ public static void <API key>(final View view, final long duration, @ColorInt final int colorStart, @ColorInt final int colorEnd) { if (DEBUG) { Log.d(TAG, "<API key>() called with: " + "view = [" + view + "], duration = [" + duration + "], " + "colorStart = [" + colorStart + "], colorEnd = [" + colorEnd + "]"); } final int[][] empty = {new int[0]}; final ValueAnimator <API key> = ValueAnimator .ofObject(new ArgbEvaluator(), colorStart, colorEnd); <API key>.setInterpolator(new <API key>()); <API key>.setDuration(duration); <API key>.addUpdateListener(animation -> ViewCompat.<API key>(view, new ColorStateList(empty, new int[]{(int) animation.getAnimatedValue()}))); <API key>.addListener(new <API key>() { @Override public void onAnimationEnd(final Animator animation) { ViewCompat.<API key>(view, new ColorStateList(empty, new int[]{colorEnd})); } @Override public void onAnimationCancel(final Animator animation) { onAnimationEnd(animation); } }); <API key>.start(); } /** * Animate the text color of any view that extends {@link TextView} (Buttons, EditText...). * * @param view the text view to animate * @param duration the duration of the animation * @param colorStart the text color to start with * @param colorEnd the text color to end with */ public static void animateTextColor(final TextView view, final long duration, @ColorInt final int colorStart, @ColorInt final int colorEnd) { if (DEBUG) { Log.d(TAG, "animateTextColor() called with: " + "view = [" + view + "], duration = [" + duration + "], " + "colorStart = [" + colorStart + "], colorEnd = [" + colorEnd + "]"); } final ValueAnimator <API key> = ValueAnimator .ofObject(new ArgbEvaluator(), colorStart, colorEnd); <API key>.setInterpolator(new <API key>()); <API key>.setDuration(duration); <API key>.addUpdateListener(animation -> view.setTextColor((int) animation.getAnimatedValue())); <API key>.addListener(new <API key>() { @Override public void onAnimationEnd(final Animator animation) { view.setTextColor(colorEnd); } @Override public void onAnimationCancel(final Animator animation) { view.setTextColor(colorEnd); } }); <API key>.start(); } public static ValueAnimator animateHeight(final View view, final long duration, final int targetHeight) { final int height = view.getHeight(); if (DEBUG) { Log.d(TAG, "animateHeight: duration = [" + duration + "], " + "from " + height + " to → " + targetHeight + " in: " + view); } final ValueAnimator animator = ValueAnimator.ofFloat(height, targetHeight); animator.setInterpolator(new <API key>()); animator.setDuration(duration); animator.addUpdateListener(animation -> { final float value = (float) animation.getAnimatedValue(); view.getLayoutParams().height = (int) value; view.requestLayout(); }); animator.addListener(new <API key>() { @Override public void onAnimationEnd(final Animator animation) { view.getLayoutParams().height = targetHeight; view.requestLayout(); } @Override public void onAnimationCancel(final Animator animation) { view.getLayoutParams().height = targetHeight; view.requestLayout(); } }); animator.start(); return animator; } public static void animateRotation(final View view, final long duration, final int targetRotation) { if (DEBUG) { Log.d(TAG, "animateRotation: duration = [" + duration + "], " + "from " + view.getRotation() + " to → " + targetRotation + " in: " + view); } view.animate().setListener(null).cancel(); view.animate() .rotation(targetRotation).setDuration(duration) .setInterpolator(new <API key>()) .setListener(new <API key>() { @Override public void onAnimationCancel(final Animator animation) { view.setRotation(targetRotation); } @Override public void onAnimationEnd(final Animator animation) { view.setRotation(targetRotation); } }).start(); } private static void animateAlpha(final View view, final boolean enterOrExit, final long duration, final long delay, final Runnable execOnEnd) { if (enterOrExit) { view.animate().setInterpolator(new <API key>()).alpha(1f) .setDuration(duration).setStartDelay(delay) .setListener(new <API key>() { @Override public void onAnimationEnd(final Animator animation) { if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } else { view.animate().setInterpolator(new <API key>()).alpha(0f) .setDuration(duration).setStartDelay(delay) .setListener(new <API key>() { @Override public void onAnimationEnd(final Animator animation) { view.setVisibility(View.GONE); if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } } /*////////////////////////////////////////////////////////////////////////// // Internals ///////////////////////////////////////////////////////////////////////*/ private static void <API key>(final View view, final boolean enterOrExit, final long duration, final long delay, final Runnable execOnEnd) { if (enterOrExit) { view.setScaleX(.8f); view.setScaleY(.8f); view.animate() .setInterpolator(new <API key>()) .alpha(1f).scaleX(1f).scaleY(1f) .setDuration(duration).setStartDelay(delay) .setListener(new <API key>() { @Override public void onAnimationEnd(final Animator animation) { if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } else { view.setScaleX(1f); view.setScaleY(1f); view.animate() .setInterpolator(new <API key>()) .alpha(0f).scaleX(.8f).scaleY(.8f) .setDuration(duration).setStartDelay(delay) .setListener(new <API key>() { @Override public void onAnimationEnd(final Animator animation) { view.setVisibility(View.GONE); if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } } private static void <API key>(final View view, final boolean enterOrExit, final long duration, final long delay, final Runnable execOnEnd) { if (enterOrExit) { view.setAlpha(.5f); view.setScaleX(.95f); view.setScaleY(.95f); view.animate() .setInterpolator(new <API key>()) .alpha(1f).scaleX(1f).scaleY(1f) .setDuration(duration).setStartDelay(delay) .setListener(new <API key>() { @Override public void onAnimationEnd(final Animator animation) { if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } else { view.setAlpha(1f); view.setScaleX(1f); view.setScaleY(1f); view.animate() .setInterpolator(new <API key>()) .alpha(0f).scaleX(.95f).scaleY(.95f) .setDuration(duration).setStartDelay(delay) .setListener(new <API key>() { @Override public void onAnimationEnd(final Animator animation) { view.setVisibility(View.GONE); if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } } private static void <API key>(final View view, final boolean enterOrExit, final long duration, final long delay, final Runnable execOnEnd) { if (enterOrExit) { view.setTranslationY(-view.getHeight()); view.setAlpha(0f); view.animate() .setInterpolator(new <API key>()).alpha(1f).translationY(0) .setDuration(duration).setStartDelay(delay) .setListener(new <API key>() { @Override public void onAnimationEnd(final Animator animation) { if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } else { view.animate() .setInterpolator(new <API key>()) .alpha(0f).translationY(-view.getHeight()) .setDuration(duration).setStartDelay(delay) .setListener(new <API key>() { @Override public void onAnimationEnd(final Animator animation) { view.setVisibility(View.GONE); if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } } private static void <API key>(final View view, final boolean enterOrExit, final long duration, final long delay, final Runnable execOnEnd) { if (enterOrExit) { view.setTranslationY(-view.getHeight() / 2.0f); view.setAlpha(0f); view.animate() .setInterpolator(new <API key>()).alpha(1f).translationY(0) .setDuration(duration).setStartDelay(delay) .setListener(new <API key>() { @Override public void onAnimationEnd(final Animator animation) { if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } else { view.animate().setInterpolator(new <API key>()) .alpha(0f).translationY(-view.getHeight() / 2.0f) .setDuration(duration).setStartDelay(delay) .setListener(new <API key>() { @Override public void onAnimationEnd(final Animator animation) { view.setVisibility(View.GONE); if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } } public static void slideUp(final View view, final long duration, final long delay, @FloatRange(from = 0.0f, to = 1.0f) final float translationPercent) { final int translationY = (int) (view.getResources().getDisplayMetrics().heightPixels * (translationPercent)); view.animate().setListener(null).cancel(); view.setAlpha(0f); view.setTranslationY(translationY); view.setVisibility(View.VISIBLE); view.animate() .alpha(1f) .translationY(0) .setStartDelay(delay) .setDuration(duration) .setInterpolator(new <API key>()) .start(); } public enum Type { ALPHA, SCALE_AND_ALPHA, <API key>, SLIDE_AND_ALPHA, <API key> } }
My Dotfiles - Lasciate ogne speranza, voi ch'intrate ===== ## TODO - [ ] Improve `setup.sh` for easy installation.
import {Component, OnInit} from '@angular/core'; import {EvaluationService} from '../service/evaluation.service'; @Component({ selector: 'app-evaluation', templateUrl: './evaluation.component.html', styleUrls: ['./evaluation.component.css'] }) export class EvaluationComponent implements OnInit { public result: number[]; private quadrantWith = 200; constructor(public evaluationService: EvaluationService) { } ngOnInit() { this.result = this.evaluationService.evaluate(); } calc(points: number): number { const value = 1 / 30 * (points - 10) * this.quadrantWith return (value < 0) ? 0 : value; } }
#control-menu { position: fixed; background-color: #E9F2F5; border: solid 1px #d3d3d3; display: flex; justify-content: space-between; align-items: center; z-index: 100000 } #control-menu * { font-size: 13px; font-weight: bold; } #control-menu .user { display: block; margin: 0 8px 0 0; padding: 8px; background-color: #235c96; color: #fff; } #control-menu .right { display: flex; justify-content: flex-end; } #control-menu .right a { width: 20px; height: 18px; display: block; padding: 8px; } #control-menu .right a:hover { background-color: #D5E7ED; } #control-menu .about { background: transparent url(about.png) no-repeat center center; } #control-menu .help { background: transparent url(help.png) no-repeat center center; } #control-menu .logout { background: transparent url(logout.png) no-repeat center center; } #control-menu ul { display: flex; justify-content: flex-start; flex-grow: 1; margin: 0; padding: 0; } #control-menu ul li { display: block; list-style: none; margin: 0; position: relative; } #control-menu ul li a { display: block; padding: 8px; cursor: pointer; color: #00576d; text-decoration: none; } #control-menu ul li a:hover { background-color: #D5E7ED; } #control-menu ul li ul { position: absolute; left: 0; bottom: 32px; display: none; background-color: #E9F2F5; padding: 5px; width: 200px; border-top: solid 1px #d3d3d3; border-left: solid 1px #d3d3d3; border-right: solid 1px #d3d3d3; -<API key>: 5px; -<API key>: 5px; -<API key>: 5px; -<API key>: 5px; <API key>: 5px; <API key>: 5px; } #control-menu ul li ul li { display: block; margin: 0; padding: 0; } #control-menu ul li ul li a { display: block; border-bottom: dotted 1px #d3d3d3; color: #00576d; text-decoration: none; } #control-menu ul li ul li a:hover { background-color: #df7500; color: #fff; } #control-menu .view { display: none; } #control-menu .view a { display: inline-block; cursor: pointer; width: 20px; height: 20px; padding: 5px 8px 5px 8px; background: transparent url(options.png) no-repeat center center; } #control-menu-mobile { display: none; position: fixed; background-color: #E9F2F5; z-index: 100000; overflow: scroll; padding: 10px; box-sizing: border-box; opacity: 0.9; } #control-menu-mobile a { color: #00576d; } #control-menu-mobile .close { text-align: right; } #control-menu-mobile .close a { font-weight: bold; display: inline-block; padding: 10px 10px 0 10px; font-size: 24px; cursor: pointer; } #control-menu-mobile ul { margin: 0; padding: 0; } #control-menu-mobile ul li { list-style: none; } #control-menu-mobile > ul > li { margin-bottom: 15px; } #control-menu-mobile > ul > li > a { font-size: 24px; margin-bottom: 10px; } #control-menu-mobile ul li a { display: block; } #control-menu-mobile ul ul li a { padding-left: 20px; display: block; padding: 7px; border-bottom: dotted 1px #d3d3d3; } #control-menu-mobile ul ul li a:hover { background-color: #df7500; color: #fff; } @media all and (max-width: 800px) { #control-menu ul { display: none; } #control-menu .view { display: block; flex-grow: 1; text-align: left; } }
package com.sun.electric.tool.generator.layout.fill; import com.sun.electric.database.geometry.EPoint; import com.sun.electric.database.hierarchy.Cell; import com.sun.electric.database.hierarchy.Library; import com.sun.electric.database.prototype.PortProto; import com.sun.electric.database.topology.NodeInst; import com.sun.electric.database.topology.PortInst; import com.sun.electric.technology.ArcProto; import com.sun.electric.technology.PrimitiveNode; import com.sun.electric.tool.Job; import com.sun.electric.tool.JobException; import com.sun.electric.tool.Tool; import com.sun.electric.tool.generator.layout.Gallery; import com.sun.electric.tool.generator.layout.LayoutLib; import com.sun.electric.tool.generator.layout.TechType; import java.lang.reflect.Constructor; import java.util.*; abstract class MetalFloorplanBase extends Floorplan { /** width Vdd wires */ public double vddWidth; /** width Gnd wires */ public double gndWidth; MetalFloorplanBase(double cellWidth, double cellHeight, boolean horiz) { super(cellWidth, cellHeight, horiz); vddWidth = gndWidth = 0; } } // Similar to Metalfloor but number of power/gnd lines is determined by cell size class MetalFloorplanFlex extends MetalFloorplanBase { public final double minWidth, space, vddReserve, gndReserve; MetalFloorplanFlex(double cellWidth, double cellHeight, double vddReserve, double gndReserve, double space, double vddW, double gndW, boolean horiz) { super(cellWidth, cellHeight, horiz); this.vddWidth = vddW; this.gndWidth = gndW; this.space = space; this.vddReserve = vddReserve; this.gndReserve = gndReserve; minWidth = vddReserve + gndReserve + 2*space + 2*gndWidth + 2*vddWidth; } } // Floor plan: // half of Gnd reserved // <API key> // wide space // <API key> // Vdd reserved // <API key> // wide space // <API key> // half of Gnd reserved class MetalFloorplan extends MetalFloorplanBase { /** no gap between Vdd wires */ public final boolean mergedVdd; /** if horizontal then y coordinate of top Vdd wire * if vertical then x coordinate of right Vdd wire */ public final double vddCenter; /** if horizontal then y coordinate of top Gnd wire * if vertical then x coordinate of right Gnd wire */ public final double gndCenter; public final double coverage; private double roundDownOneLambda(double x) { return Math.floor(x); } // Round metal widths down to multiples of 1 lambda resolution. // Then metal center can be on 1/2 lambda grid without problems. MetalFloorplan(double cellWidth, double cellHeight, double vddReserve, double gndReserve, double space, boolean horiz) { super(cellWidth, cellHeight, horiz); mergedVdd = vddReserve==0; double cellSpace = horiz ? cellHeight : cellWidth; double metalSpace = cellSpace - 2*space - vddReserve - gndReserve; // gnd is always in two pieces gndWidth = roundDownOneLambda(metalSpace / 4); gndCenter = cellSpace/2 - gndReserve/2 - gndWidth/2; // vdd may be one or two pieces if (mergedVdd) { vddWidth = gndWidth*2; vddCenter = 0; } else { vddWidth = gndWidth; vddCenter = vddReserve/2 + vddWidth/2; } // compute coverage statistics double cellArea = cellWidth * cellHeight; double strapLength = horiz ? cellWidth : cellHeight; double vddArea = (mergedVdd ? 1 : 2) * vddWidth * strapLength; double gndArea = 2 * gndWidth * strapLength; coverage = (vddArea + gndArea)/cellArea; } // Save this code in case I need to replicate LoCo FillCell exactly // MetalFloorplan(double cellWidth, double cellHeight, // double vddReserve, double gndReserve, // double space, boolean horiz) { // super(cellWidth, cellHeight, horiz); // mergedVdd = vddReserve==0; // double cellSpace = horiz ? cellHeight : cellWidth; // if (mergedVdd) { // double w = cellSpace/2 - space - vddReserve; // vddWidth = roundDownOneLambda(w); // vddCenter = 0; // } else { // double w = (cellSpace/2 - space - vddReserve) / 2; // vddWidth = roundDownOneLambda(w); // vddCenter = vddReserve/2 + vddWidth/2; // double vddEdge = vddCenter + vddWidth/2; // double w = cellSpace/2 - vddEdge - space - gndReserve/2; // gndWidth = roundDownOneLambda(w); // gndCenter = vddEdge + space + gndWidth/2; // // compute coverage statistics // double cellArea = cellWidth * cellHeight; // double strapLength = horiz ? cellWidth : cellHeight; // double vddArea = (mergedVdd ? 1 : 2) * vddWidth * strapLength; // double gndArea = 2 * gndWidth * strapLength; // coverage = (vddArea + gndArea)/cellArea; } class ExportBar { PortInst[] ports = null; Double center = null; ExportBar(PortInst p1, PortInst p2, double c) { ports = new PortInst[2]; ports[0] = p1; ports[1] = p2; center = (c); // autoboxing } } class MetalLayer extends VddGndStraps { protected MetalFloorplanBase plan; protected int layerNum; protected PrimitiveNode pin; protected ArcProto metal; protected ArrayList<ExportBar> vddBars = new ArrayList<ExportBar>(); protected ArrayList<ExportBar> gndBars = new ArrayList<ExportBar>(); public boolean addExtraArc() { return true; } private void buildGnd(Cell cell) { double pinX, pinY; MetalFloorplan plan = (MetalFloorplan)this.plan; if (plan.horizontal) { pinX = plan.cellWidth/2; // - plan.gndWidth/2; pinY = plan.gndCenter; } else { pinX = plan.gndCenter; pinY = plan.cellHeight/2; // - plan.gndWidth/2; } PortInst tl = LayoutLib.newNodeInst(pin, -pinX, pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst tr = LayoutLib.newNodeInst(pin, pinX, pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst bl = LayoutLib.newNodeInst(pin, -pinX, -pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst br = LayoutLib.newNodeInst(pin, pinX, -pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); if (plan.horizontal) { G.noExtendArc(metal, plan.gndWidth, tl, tr); G.noExtendArc(metal, plan.gndWidth, bl, br); gndBars.add(new ExportBar(bl, br, -plan.gndCenter)); gndBars.add(new ExportBar(tl, tr, plan.gndCenter)); } else { G.noExtendArc(metal, plan.gndWidth, bl, tl); G.noExtendArc(metal, plan.gndWidth, br, tr); gndBars.add(new ExportBar(bl, tl, -plan.gndCenter)); gndBars.add(new ExportBar(br, tr, plan.gndCenter)); } } private void buildVdd(Cell cell) { double pinX, pinY; MetalFloorplan plan = (MetalFloorplan)this.plan; if (plan.horizontal) { pinX = plan.cellWidth/2; // - plan.vddWidth/2; pinY = plan.vddCenter; } else { pinX = plan.vddCenter; pinY = plan.cellHeight/2; // - plan.vddWidth/2; } if (plan.mergedVdd) { PortInst tr = LayoutLib.newNodeInst(pin, pinX, pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst bl = LayoutLib.newNodeInst(pin, -pinX, -pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); G.noExtendArc(metal, plan.vddWidth, bl, tr); vddBars.add(new ExportBar(bl, tr, plan.vddCenter)); } else { PortInst tl = LayoutLib.newNodeInst(pin, -pinX, pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst tr = LayoutLib.newNodeInst(pin, pinX, pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst bl = LayoutLib.newNodeInst(pin, -pinX, -pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst br = LayoutLib.newNodeInst(pin, pinX, -pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); if (plan.horizontal) { G.noExtendArc(metal, plan.vddWidth, tl, tr); G.noExtendArc(metal, plan.vddWidth, bl, br); vddBars.add(new ExportBar(bl, br, -plan.vddCenter)); vddBars.add(new ExportBar(tl, tr, plan.vddCenter)); } else { G.noExtendArc(metal, plan.vddWidth, bl, tl); G.noExtendArc(metal, plan.vddWidth, br, tr); vddBars.add(new ExportBar(bl, tl, -plan.vddCenter)); vddBars.add(new ExportBar(br, tr, plan.vddCenter)); } } } /** It has to be protected to be overwritten by sub classes */ protected void buildGndAndVdd(Cell cell) { buildGnd(cell); buildVdd(cell); } public MetalLayer(TechType t, int layerNum, Floorplan plan, Cell cell) { super(t); this.plan = (MetalFloorplanBase)plan; this.layerNum = layerNum; metal = METALS[layerNum]; pin = PINS[layerNum]; buildGndAndVdd(cell); } public boolean isHorizontal() {return plan.horizontal;} public int numVdd() {return vddBars.size();} public double getVddCenter(int n) { return (vddBars.get(n).center); // autoboxing } public PortInst getVdd(int n, int pos) {return vddBars.get(n).ports[pos];} public double getVddWidth(int n) {return plan.vddWidth;} public int numGnd() {return gndBars.size();} public double getGndCenter(int n) { return (gndBars.get(n).center); // autoboxing } public PortInst getGnd(int n, int pos) {return gndBars.get(n).ports[pos];} public double getGndWidth(int n) {return (plan).gndWidth;} public PrimitiveNode getPinType() {return pin;} public ArcProto getMetalType() {return metal;} public double getCellWidth() {return plan.cellWidth;} public double getCellHeight() {return plan.cellHeight;} public int getLayerNumber() {return layerNum;} } class MetalLayerFlex extends MetalLayer { public MetalLayerFlex(TechType t, int layerNum, Floorplan plan, Cell cell) { super(t, layerNum, plan, cell); } public boolean addExtraArc() { return false; } // For automatic fill generator no extra arcs are wanted. protected void buildGndAndVdd(Cell cell) { double pinX, pinY; double limit = 0; MetalFloorplanFlex plan = (MetalFloorplanFlex)this.plan; if (plan.horizontal) { limit = plan.cellHeight/2; } else { limit = plan.cellWidth/2; } double position = 0; int i = 0; while (position < limit) { boolean even = (i%2==0); double maxDelta = 0, pos = 0; if (even) { maxDelta = plan.vddReserve/2 + plan.vddWidth; pos = plan.vddReserve/2 + plan.vddWidth/2 + position; } else { maxDelta = plan.gndReserve/2 + plan.gndWidth; pos = plan.gndReserve/2 + plan.gndWidth/2 + position; } if (position + maxDelta > limit) return; // border was reached if (plan.horizontal) { pinY = pos; pinX = plan.cellWidth/2; } else { pinX = pos; pinY = plan.cellHeight/2; } // Vdd if even, gnd if odd if (!even) addBars(cell, pinX, pinY, plan.gndWidth, gndBars); else addBars(cell, pinX, pinY, plan.vddWidth, vddBars); if (even) { maxDelta = plan.vddReserve/2 + plan.vddWidth + plan.space + plan.gndWidth; pos = plan.vddReserve/2 + plan.vddWidth + plan.space + plan.gndWidth/2 + position; } else { maxDelta = plan.gndReserve/2 + plan.gndWidth + plan.space + plan.vddWidth; pos = plan.gndReserve/2 + plan.gndWidth + plan.space + plan.vddWidth/2 + position; } if (position + maxDelta > limit) return; // border was reached if (plan.horizontal) pinY = pos; else pinX = pos; // Gnd if even, vdd if odd if (!even) { addBars(cell, pinX, pinY, plan.vddWidth, vddBars); position = ((plan.horizontal)?pinY:pinX) + plan.vddWidth/2 + plan.vddReserve/2; } else { addBars(cell, pinX, pinY, plan.gndWidth, gndBars); position = ((plan.horizontal)?pinY:pinX) + plan.gndWidth/2 + plan.gndReserve/2; } i++; } } private void addBars(Cell cell, double pinX, double pinY, double width, ArrayList<ExportBar> bars) { PortInst tl = LayoutLib.newNodeInst(pin, -pinX, pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst tr = LayoutLib.newNodeInst(pin, pinX, pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst bl = LayoutLib.newNodeInst(pin, -pinX, -pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst br = LayoutLib.newNodeInst(pin, pinX, -pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); double center = 0; if (plan.horizontal) { G.noExtendArc(metal, width, tl, tr); G.noExtendArc(metal, width, bl, br); center = pinY; bars.add(new ExportBar(bl, br, -center)); bars.add(new ExportBar(tl, tr, center)); } else { G.noExtendArc(metal, width, bl, tl); G.noExtendArc(metal, width, br, tr); center = pinX; bars.add(new ExportBar(bl, tl, -center)); bars.add(new ExportBar(br, tr, center)); } } } class CapLayer extends VddGndStraps { private CapCell capCell; private NodeInst capCellInst; private CapFloorplan plan; public boolean addExtraArc() { return true; } public CapLayer(TechType t, CapFloorplan plan, CapCell capCell, Cell cell) { super(t); this.plan = plan; this.capCell = capCell; double angle = plan.horizontal ? 0 : 90; if (capCell != null) capCellInst = LayoutLib.newNodeInst(capCell.getCell(), 0, 0, G.DEF_SIZE, G.DEF_SIZE, angle, cell); } public boolean isHorizontal() {return plan.horizontal;} public int numVdd() {return (capCell != null) ? capCell.numVdd() : 0;} public PortInst getVdd(int n, int pos) { return capCellInst.findPortInst(FillCell.VDD_NAME+"_"+n); } public double getVddCenter(int n) { EPoint center = getVdd(n, 0).getCenter(); return plan.horizontal ? center.getY() : center.getX(); } public double getVddWidth(int n) {return capCell.getVddWidth();} public int numGnd() {return (capCell != null) ? capCell.numGnd() : 0;} public PortInst getGnd(int n, int pos) { return capCellInst.findPortInst(FillCell.GND_NAME+"_"+n); } public double getGndCenter(int n) { EPoint center = getGnd(n, 0).getCenter(); return plan.horizontal ? center.getY() : center.getX(); } public double getGndWidth(int n) {return capCell.getGndWidth();} public PrimitiveNode getPinType() {return tech.m1pin();} public ArcProto getMetalType() {return tech.m1();} public double getCellWidth() {return plan.cellWidth;} public double getCellHeight() {return plan.cellHeight;} public int getLayerNumber() {return 1;} } class FillRouter { private HashMap<String,List<PortInst>> portMap = new HashMap<String,List<PortInst>>(); private TechType tech; private String makeKey(PortInst pi) { EPoint center = pi.getCenter(); String x = ""+center.getX(); // LayoutLib.roundCenterX(pi); String y = ""+center.getY(); // LayoutLib.roundCenterY(pi); return x+"x"+y; } // private boolean bothConnect(ArcProto a, PortProto pp1, PortProto pp2) { // return pp1.connectsTo(a) && pp2.connectsTo(a); private ArcProto findCommonArc(PortInst p1, PortInst p2) { ArcProto[] metals = {tech.m6(), tech.m5(), tech.m4(), tech.m3(), tech.m2(), tech.m1()}; PortProto pp1 = p1.getPortProto(); PortProto pp2 = p2.getPortProto(); for (int i=0; i<metals.length; i++) { if (pp1.connectsTo(metals[i]) && pp2.connectsTo(metals[i])) { return metals[i]; } } return null; } private void connectPorts(List<PortInst> ports) { for (Iterator<PortInst> it=ports.iterator(); it.hasNext(); ) { PortInst first = it.next(); double width = LayoutLib.widestWireWidth(first); it.remove(); for (PortInst pi : ports) { ArcProto a = findCommonArc(first, pi); if (a!=null) LayoutLib.newArcInst(a, width, first, pi); } } } private FillRouter(TechType t, ArrayList<PortInst> ports) { tech = t; for (PortInst pi : ports) { String key = makeKey(pi); List<PortInst> l = portMap.get(key); if (l==null) { l = new LinkedList<PortInst>(); portMap.put(key, l); } l.add(pi); } // to guarantee deterministic results List<String> keys = new ArrayList<String>(); keys.addAll(portMap.keySet()); Collections.sort(keys); for (String str : keys) { connectPorts(portMap.get(str)); } } public static void connectCoincident(TechType t, ArrayList<PortInst> ports) { new FillRouter(t, ports); } } /** * Object for building fill libraries */ public class FillGeneratorTool extends Tool { public FillGenConfig config; protected Library lib; private boolean libInitialized; public List<Cell> masters; protected CapCell capCell; protected Floorplan[] plans; /** the fill generator tool. */ private static FillGeneratorTool tool = getTool(); // Depending on generator plugin available public static FillGeneratorTool getTool() { if (tool != null) return tool; FillGeneratorTool tool; try { Class<?> extraClass = Class.forName("com.sun.electric.plugins.generator.FillCellTool"); Constructor instance = extraClass.<API key>(); // varags Object obj = instance.newInstance(); // varargs; tool = (FillGeneratorTool)obj; } catch (Exception e) { if (Job.getDebug()) System.out.println("GNU Release can't find Fill Cell Generator plugin"); tool = new FillGeneratorTool(); } return tool; } public FillGeneratorTool() { super("Fill Generator"); } public void setConfig(FillGenConfig config) { this.config = config; this.libInitialized = false; } public enum Units {NONE, LAMBDA, TRACKS} protected boolean getOrientation() {return plans[plans.length-1].horizontal;} /** Reserve space in the middle of the Vdd and ground straps for signals. * @param layer the layer number. This may be 2, 3, 4, 5, or 6. The layer * number 1 is reserved to mean "capacitor between Vdd and ground". * @param reserved space to reserve in the middle of the central * strap in case of Vdd. The value 0 makes the Vdd strap one large strap instead of two smaller * adjacent straps. * Space to reserve between the ground strap of this * cell and the ground strap of the adjacent fill cell. The value 0 means * that these two ground straps should abut to form a single large strap * instead of two smaller adjacent straps. * */ private double reservedToLambda(int layer, double reserved, Units units) { if (units==LAMBDA) return reserved; double nbTracks = reserved; if (nbTracks==0) return 0; return config.getTechType().reservedToLambda(layer, nbTracks); } private Floorplan[] makeFloorplans(boolean metalFlex, boolean hierFlex) { Job.error(config.width==Double.NaN, "width hasn't been specified. use setWidth()"); Job.error(config.height==Double.NaN, "height hasn't been specified. use setHeight()"); double w = config.width; double h = config.height; int numLayers = config.getTechType().getNumMetals() + 1; // one extra for the cap double[] vddRes = new double[numLayers]; //{0,0,0,0,0,0,0}; double[] gndRes = new double[numLayers]; //{0,0,0,0,0,0,0}; double[] vddW = new double[numLayers]; //{0,0,0,0,0,0,0}; double[] gndW = new double[numLayers]; //{0,0,0,0,0,0,0}; // set given values for (FillGenConfig.ReserveConfig c : config.reserves) { vddRes[c.layer] = reservedToLambda(c.layer, c.vddReserved, c.vddUnits); gndRes[c.layer] = reservedToLambda(c.layer, c.gndReserved, c.gndUnits); if (c.vddWUnits != Units.NONE) vddW[c.layer] = reservedToLambda(c.layer, c.vddWidth, c.vddWUnits); if (c.gndWUnits != Units.NONE) gndW[c.layer] = reservedToLambda(c.layer, c.gndWidth, c.gndWUnits); } boolean evenHor = config.<API key>; boolean alignedMetals = true; double[] spacing = new double[numLayers]; for (int i = 0; i < numLayers; i++) spacing[i] = config.drcSpacingRule; // {config.drcSpacingRule,config.drcSpacingRule, // config.drcSpacingRule,config.drcSpacingRule, // config.drcSpacingRule,config.drcSpacingRule,config.drcSpacingRule}; if (alignedMetals) { double maxVddRes = 0, maxGndRes = 0, maxSpacing = 0, maxVddW = 0, maxGndW = 0; for (int i = 0; i < vddRes.length; i++) { boolean vddOK = false, gndOK = false; if (vddRes[i] > 0) { vddOK = true; if (maxVddRes < vddRes[i]) maxVddRes = vddRes[i]; } if (gndRes[i] > 0) { gndOK = true; if (maxGndRes < gndRes[i]) maxGndRes = gndRes[i]; } if (gndOK || vddOK) // checking max spacing rule { if (maxSpacing < config.drcSpacingRule) maxSpacing = config.drcSpacingRule; //drcRules[i]; } if (maxVddW < vddW[i]) maxVddW = vddW[i]; if (maxGndW < gndW[i]) maxGndW = gndW[i]; } // correct the values for (int i = 0; i < vddRes.length; i++) { vddRes[i] = maxVddRes; gndRes[i] = maxGndRes; spacing[i] = maxSpacing; vddW[i] = maxVddW; gndW[i] = maxGndW; } } Floorplan[] thePlans = new Floorplan[numLayers]; // 0 is always null thePlans[1] = new CapFloorplan(w, h, !evenHor); if (metalFlex) { if (!hierFlex) { for (int i = 2; i < numLayers; i++) { boolean horiz = (i%2==0); thePlans[i] = new MetalFloorplanFlex(w, h, vddRes[i], gndRes[i], spacing[i], vddW[i], gndW[i], horiz); } return thePlans; } w = config.width = config.minTileSizeX; h = config.height = config.minTileSizeY; } for (int i = 2; i < numLayers; i++) { boolean horiz = (i%2==0); thePlans[i] = new MetalFloorplan(w, h, vddRes[i], gndRes[i], spacing[i], horiz); } return thePlans; } private void printCoverage(Floorplan[] plans) { for (int i=2; i<plans.length; i++) { System.out.println("metal-"+i+" coverage: "+ ((MetalFloorplan)plans[i]).coverage); } } private static CapCell getCMOS90CapCell(Library lib, CapFloorplan plan) { CapCell c = null; try { Class<?> cmos90Class = Class.forName("com.sun.electric.plugins.tsmc.fill90nm.CapCellCMOS90"); Constructor capCellC = cmos90Class.<API key>(Library.class, CapFloorplan.class); // varargs Object cell = capCellC.newInstance(lib, plan); c = (CapCell)cell; } catch (Exception e) { assert(false); // runtime error } return c; } protected void initFillParameters(boolean metalFlex, boolean hierFlex) { if (libInitialized) return; Job.error(config.fillLibName==null, "no library specified. Use setFillLibrary()"); Job.error((config.width==Double.NaN || config.width<=0), "no width specified. Use setFillCellWidth()"); Job.error((config.height==Double.NaN || config.height<=0), "no height specified. Use setFillCellHeight()"); plans = makeFloorplans(metalFlex, hierFlex); if (!metalFlex) printCoverage(plans); lib = LayoutLib.openLibForWrite(config.fillLibName); if (!metalFlex) // don't do transistors { if (config.is180Tech()) { capCell = new CapCellMosis(lib, (CapFloorplan) plans[1], config.getTechType()); } else { capCell = getCMOS90CapCell(lib, (CapFloorplan) plans[1]); } } libInitialized = true; } private void makeTiledCells(Cell cell, Floorplan[] plans, Library lib, int[] tiledSizes) { if (tiledSizes==null) return; for (int num : tiledSizes) { TiledCell.makeTiledCell(num, num, cell, plans, lib); } } public static Cell makeFillCell(Library lib, Floorplan[] plans, int botLayer, int topLayer, CapCell capCell, TechType tech, ExportConfig expCfg, boolean metalFlex, boolean hierFlex) { FillCell fc = new FillCell(tech); return fc.makeFillCell1(lib, plans, botLayer, topLayer, capCell, expCfg, metalFlex, hierFlex); } /** * Method to create standard set of tiled cells. */ private Cell <API key>(Library lib, Floorplan[] plans, int lowLay, int hiLay, CapCell capCell, TechType tech, ExportConfig expCfg, int[] tiledSizes, boolean metalFlex) { Cell master = makeFillCell(lib, plans, lowLay, hiLay, capCell, tech, expCfg, metalFlex, false); masters = new ArrayList<Cell>(); masters.add(master); makeTiledCells(master, plans, lib, tiledSizes); return master; } public static final Units LAMBDA = Units.LAMBDA; public static final Units TRACKS = Units.TRACKS; //public static final PowerType POWER = PowerType.POWER; //public static final PowerType VDD = PowerType.VDD; public static final ExportConfig PERIMETER = ExportConfig.PERIMETER; public static final ExportConfig <API key> = ExportConfig.<API key>; /** Reserve space in the middle of the Vdd and ground straps for signals. * @param layer the layer number. This may be 2, 3, 4, 5, or 6. The layer * number 1 is reserved to mean "capacitor between Vdd and ground". * @param vddReserved space to reserve in the middle of the central Vdd * strap. * The value 0 makes the Vdd strap one large strap instead of two smaller * adjacent straps. * @param vddUnits LAMBDA or TRACKS * @param gndReserved space to reserve between the ground strap of this * cell and the ground strap of the adjacent fill cell. The value 0 means * that these two ground straps should abut to form a single large strap * instead of two smaller adjacent straps. * @param gndUnits LAMBDA or TRACKS * param tiledSizes an array of sizes. The default value is null. The * value null means don't generate anything. */ // public void reserveSpaceOnLayer(int layer, // double vddReserved, Units vddUnits, // double gndReserved, Units gndUnits) { // LayoutLib.error(layer<2 || layer>6, // "Bad layer. Layers must be between 2 and 6 inclusive: "+ // layer); // this.vddReserved[layer] = reservedToLambda(layer, vddReserved, vddUnits); // this.gndReserved[layer] = reservedToLambda(layer, gndReserved, gndUnits); /** Create a fill cell using the current library, fill cell width, fill cell * height, layer orientation, and reserved spaces for each layer. Then * generate larger fill cells by tiling that fill cell according to the * current tiled cell sizes. * @param loLayer the lower layer. This may be 1 through 6. Layer 1 means * build a capacitor using MOS transistors between Vdd and ground. * @param hiLayer the upper layer. This may be 2 through 6. Note that hiLayer * must be >= loLayer. * @param exportConfig may be PERIMETER in which case exports are * placed along the perimeter of the cell for the top two layers. Otherwise * exportConfig must be <API key> in which case exports are * placed inside the perimeter of the cell for the bottom layer. * @param tiledSizes Array specifying composite Cells we should build by * concatonating fill cells. For example int[] {2, 4, 7} means we should * */ public Cell <API key>(int loLayer, int hiLayer, TechType tech, ExportConfig exportConfig, int[] tiledSizes, boolean metalFlex) { initFillParameters(metalFlex, false); Job.error(loLayer<1, "loLayer must be >=1"); int maxNumMetals = config.getTechType().getNumMetals(); Job.error(hiLayer>maxNumMetals, "hiLayer must be <=" + maxNumMetals); Job.error(loLayer>hiLayer, "loLayer must be <= hiLayer"); Cell cell = null; cell = <API key>(lib, plans, loLayer, hiLayer, capCell, tech, exportConfig, tiledSizes, metalFlex); return cell; } public void makeGallery() { Gallery.makeGallery(lib); } public void writeLibrary(int backupScheme) throws JobException { LayoutLib.writeLibrary(lib, backupScheme); } public enum FillTypeEnum {INVALID,TEMPLATE,CELL} }
<!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <title>MetaDataInfo xref</title> <link type="text/css" rel="stylesheet" href="../../../stylesheet.css" /> </head> <body> <div id="overview"><a href="../../../../apidocs/fspotcloud/shared/admin/MetaDataInfo.html">View Javadoc</a></div><pre> <a class="jxr_linenumber" name="1" href="#1">1</a> <strong class="jxr_keyword">package</strong> fspotcloud.shared.admin; <a class="jxr_linenumber" name="2" href="#2">2</a> <a class="jxr_linenumber" name="3" href="#3">3</a> <strong class="jxr_keyword">import</strong> java.util.Date; <a class="jxr_linenumber" name="4" href="#4">4</a> <a class="jxr_linenumber" name="5" href="#5">5</a> <strong class="jxr_keyword">import</strong> com.google.gwt.user.client.rpc.IsSerializable; <a class="jxr_linenumber" name="6" href="#6">6</a> <a class="jxr_linenumber" name="7" href="#7">7</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">class</strong> <a href="../../../fspotcloud/shared/admin/MetaDataInfo.html">MetaDataInfo</a> <strong class="jxr_keyword">implements</strong> IsSerializable { <a class="jxr_linenumber" name="8" href="#8">8</a> <a class="jxr_linenumber" name="9" href="#9">9</a> <strong class="jxr_keyword">private</strong> Date created; <a class="jxr_linenumber" name="10" href="#10">10</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">int</strong> peerPhotoCount; <a class="jxr_linenumber" name="11" href="#11">11</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">int</strong> tagCount; <a class="jxr_linenumber" name="12" href="#12">12</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">int</strong> pendingCommandCount; <a class="jxr_linenumber" name="13" href="#13">13</a> <strong class="jxr_keyword">private</strong> Date peerLastSeen; <a class="jxr_linenumber" name="14" href="#14">14</a> <strong class="jxr_keyword">private</strong> String instanceName; <a class="jxr_linenumber" name="15" href="#15">15</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">long</strong> photoCount; <a class="jxr_linenumber" name="16" href="#16">16</a> <strong class="jxr_keyword">private</strong> Date photosLastCounted; <a class="jxr_linenumber" name="17" href="#17">17</a> <a class="jxr_linenumber" name="18" href="#18">18</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">long</strong> getPhotoCount() { <a class="jxr_linenumber" name="19" href="#19">19</a> <strong class="jxr_keyword">return</strong> photoCount; <a class="jxr_linenumber" name="20" href="#20">20</a> } <a class="jxr_linenumber" name="21" href="#21">21</a> <a class="jxr_linenumber" name="22" href="#22">22</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> setPhotoCount(<strong class="jxr_keyword">long</strong> photoCount) { <a class="jxr_linenumber" name="23" href="#23">23</a> <strong class="jxr_keyword">this</strong>.photoCount = photoCount; <a class="jxr_linenumber" name="24" href="#24">24</a> } <a class="jxr_linenumber" name="25" href="#25">25</a> <a class="jxr_linenumber" name="26" href="#26">26</a> <strong class="jxr_keyword">public</strong> Date <API key>() { <a class="jxr_linenumber" name="27" href="#27">27</a> <strong class="jxr_keyword">return</strong> photosLastCounted; <a class="jxr_linenumber" name="28" href="#28">28</a> } <a class="jxr_linenumber" name="29" href="#29">29</a> <a class="jxr_linenumber" name="30" href="#30">30</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> <API key>(Date photosLastCounted) { <a class="jxr_linenumber" name="31" href="#31">31</a> <strong class="jxr_keyword">this</strong>.photosLastCounted = photosLastCounted; <a class="jxr_linenumber" name="32" href="#32">32</a> } <a class="jxr_linenumber" name="33" href="#33">33</a> <a class="jxr_linenumber" name="34" href="#34">34</a> <strong class="jxr_keyword">public</strong> <a href="../../../fspotcloud/shared/admin/MetaDataInfo.html">MetaDataInfo</a>() { <a class="jxr_linenumber" name="35" href="#35">35</a> created = <strong class="jxr_keyword">new</strong> Date(); <a class="jxr_linenumber" name="36" href="#36">36</a> } <a class="jxr_linenumber" name="37" href="#37">37</a> <a class="jxr_linenumber" name="38" href="#38">38</a> <strong class="jxr_keyword">public</strong> Date getCreated() { <a class="jxr_linenumber" name="39" href="#39">39</a> <strong class="jxr_keyword">return</strong> created; <a class="jxr_linenumber" name="40" href="#40">40</a> } <a class="jxr_linenumber" name="41" href="#41">41</a> <a class="jxr_linenumber" name="42" href="#42">42</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">int</strong> getPeerPhotoCount() { <a class="jxr_linenumber" name="43" href="#43">43</a> <strong class="jxr_keyword">return</strong> peerPhotoCount; <a class="jxr_linenumber" name="44" href="#44">44</a> } <a class="jxr_linenumber" name="45" href="#45">45</a> <a class="jxr_linenumber" name="46" href="#46">46</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> setPeerPhotoCount(<strong class="jxr_keyword">int</strong> peerPhotoCount) { <a class="jxr_linenumber" name="47" href="#47">47</a> <strong class="jxr_keyword">this</strong>.peerPhotoCount = peerPhotoCount; <a class="jxr_linenumber" name="48" href="#48">48</a> } <a class="jxr_linenumber" name="49" href="#49">49</a> <a class="jxr_linenumber" name="50" href="#50">50</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">int</strong> getTagCount() { <a class="jxr_linenumber" name="51" href="#51">51</a> <strong class="jxr_keyword">return</strong> tagCount; <a class="jxr_linenumber" name="52" href="#52">52</a> } <a class="jxr_linenumber" name="53" href="#53">53</a> <a class="jxr_linenumber" name="54" href="#54">54</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> setTagCount(<strong class="jxr_keyword">int</strong> tagCount) { <a class="jxr_linenumber" name="55" href="#55">55</a> <strong class="jxr_keyword">this</strong>.tagCount = tagCount; <a class="jxr_linenumber" name="56" href="#56">56</a> } <a class="jxr_linenumber" name="57" href="#57">57</a> <a class="jxr_linenumber" name="58" href="#58">58</a> <strong class="jxr_keyword">public</strong> Date getPeerLastSeen() { <a class="jxr_linenumber" name="59" href="#59">59</a> <strong class="jxr_keyword">return</strong> peerLastSeen; <a class="jxr_linenumber" name="60" href="#60">60</a> } <a class="jxr_linenumber" name="61" href="#61">61</a> <a class="jxr_linenumber" name="62" href="#62">62</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> setPeerLastSeen(Date peerLastSeen) { <a class="jxr_linenumber" name="63" href="#63">63</a> <strong class="jxr_keyword">this</strong>.peerLastSeen = peerLastSeen; <a class="jxr_linenumber" name="64" href="#64">64</a> } <a class="jxr_linenumber" name="65" href="#65">65</a> <a class="jxr_linenumber" name="66" href="#66">66</a> <strong class="jxr_keyword">public</strong> String getInstanceName() { <a class="jxr_linenumber" name="67" href="#67">67</a> <strong class="jxr_keyword">return</strong> instanceName; <a class="jxr_linenumber" name="68" href="#68">68</a> } <a class="jxr_linenumber" name="69" href="#69">69</a> <a class="jxr_linenumber" name="70" href="#70">70</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> setInstanceName(String instanceName) { <a class="jxr_linenumber" name="71" href="#71">71</a> <strong class="jxr_keyword">this</strong>.instanceName = instanceName; <a class="jxr_linenumber" name="72" href="#72">72</a> } <a class="jxr_linenumber" name="73" href="#73">73</a> <a class="jxr_linenumber" name="74" href="#74">74</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> <API key>(<strong class="jxr_keyword">int</strong> pendingCommandCount) { <a class="jxr_linenumber" name="75" href="#75">75</a> <strong class="jxr_keyword">this</strong>.pendingCommandCount = pendingCommandCount; <a class="jxr_linenumber" name="76" href="#76">76</a> } <a class="jxr_linenumber" name="77" href="#77">77</a> <a class="jxr_linenumber" name="78" href="#78">78</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">int</strong> <API key>() { <a class="jxr_linenumber" name="79" href="#79">79</a> <strong class="jxr_keyword">return</strong> pendingCommandCount; <a class="jxr_linenumber" name="80" href="#80">80</a> } <a class="jxr_linenumber" name="81" href="#81">81</a> <a class="jxr_linenumber" name="82" href="#82">82</a> } </pre> <hr/><div id="footer">This page was automatically generated by <a href="http://maven.apache.org/">Maven</a></div></body> </html>
#include "session.h" // This file is part of MCI_Host. // MCI_Host is free software: you can redistribute it and/or modify // (at your option) any later version. // MCI_Host is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Session::Session(uint sesId, qintptr newPtr, QObject *parent) : QTcpSocket(0) { timer = new QTimer(); bits = 0; flags = 0; dSize = 0; sessionId = 0; slotId = 0; baseSlot = 0; rdHash = 0; wrHash = 0; cmdListMode = 0; <API key> = false; cmdListenabled = false; keyOk = false; verOk = false; onBaseSlot = false; timer->setSingleShot(true); timer->setInterval(6000); // the timer object provides a 6sec timeout for the client to send the // header before the session is forced closed. connect(this, SIGNAL(readyRead()), this, SLOT(dataFromClient())); connect(this, SIGNAL(destroyed()), timer, SLOT(deleteLater())); connect(timer, SIGNAL(timeout()), this, SLOT(sessionTimeout())); connect(parent, SIGNAL(destroyed()), this, SLOT(deleteLater())); setSocketDescriptor(newPtr); if (inBanList(peerAddress().toString())) { // any session that still has a session id of zero after running the // contructor is considered a blocked ip so the session will get killed // externally at Server::incomingConnection(). sessionEnding = true; addIpAction(tr("IP address blocked"), peerAddress().toString()); } else { // Session represents the TCP connection with the client. it provides the // xOR encryption, version negotiation and an interface for CmdHub objects. // it starts in it's own thread from within the contructor and kills // itself when the client disconnects but does not kill the CmdHub it's // currently connected to. addIpAction(tr("Connected, assigned session id: ") + QString::number(sesId), peerAddress().toString()); sessionEnding = false; sessionId = sesId; QThread *thr = new QThread(); connect(thr, SIGNAL(finished()), thr, SLOT(deleteLater())); connect(thr, SIGNAL(started()), timer, SLOT(start())); connect(this, SIGNAL(destroyed()), thr, SLOT(quit())); connect(this, SIGNAL(disconnected()), this, SLOT(clientDisconnected())); timer->moveToThread(thr); moveToThread(thr); thr->start(); } } bool Session::loadProfile(const QString &proName, QByteArray &key) { // this function runs 3 database queries to read the following profile // data: // keyHash - this is used in the Hash object to setup encryption. // groupName - this indicates what group the profile belongs to. // the group can contain host privileges that profile // is allowed to do. // <API key> - indicates if the profileCmdList is casesSensitive. // cmdListenabled - indicates if the profileCmdList is enabled. // cmdListMode - indicates what the profileCmdList does when the // sent in command line is matched. // baseSlot - this indicates the fallback slot in cases when the // the slot the session is currently connected is // killed. // profileCmdList - this is the group command line list that is used // allowed or disallow certain commands depending // on what is loaded into cmdListMode or // <API key>. bool ret = false; Query db(this); db.setType(Query::PULL, TABLE_PROFILES); db.addColumn(COLUMN_PRONAME); db.addColumn(COLUMN_PROKEY); db.addColumn(COLUMN_GRNAME); db.addCondition(COLUMN_PRONAME, proName); db.exec(); if (db.rows()) { ret = true; profileName = db.getData(COLUMN_PRONAME).toString(); groupName = db.getData(COLUMN_GRNAME).toString(); key = db.getData(COLUMN_PROKEY).toByteArray(); db.setType(Query::PULL, TABLE_GROUPS); db.addColumn(COLUMN_CS); db.addColumn(COLUMN_LS_MODE); db.addColumn(COLUMN_LS_STATE); db.addColumn(COLUMN_BASE_SL); db.addCondition(COLUMN_GRNAME, groupName); db.exec(); <API key> = db.getData(COLUMN_CS).toBool(); cmdListenabled = db.getData(COLUMN_LS_STATE).toBool(); cmdListMode = db.getData(COLUMN_LS_MODE).toUInt(); baseSlot = db.getData(COLUMN_BASE_SL).toUInt(); profileCmdList.clear(); db.setType(Query::PULL, TABLE_CMD_LIST); db.addColumn(COLUMN_CMD_LINE); db.addCondition(COLUMN_GRNAME, groupName); db.exec(); for (int i = 0; i < db.rows(); ++i) { profileCmdList.append(db.getData(COLUMN_CMD_LINE, i).toString()); } } return ret; } bool Session::inBanList(const QString &ip) { // simple database select query with the provided ip address in the where // clause. if a row is found, that indicates that the ip address is in // the ban list. Query db(this); db.setType(Query::PULL, TABLE_IPBANS); db.addColumn(COLUMN_IPADDR); db.addCondition(COLUMN_IPADDR, ip); db.exec(); return db.rows(); } void Session::addIpAction(const QString &action, const QString &ip) { // insert database query for the ip address action log (ip_hist). Query db(this); db.setType(Query::PUSH, TABLE_IPHIST); db.addColumn(COLUMN_IPADDR, ip); db.addColumn(COLUMN_LOGENTRY, action); db.exec(); } uint Session::id() { return sessionId; } void Session::slotClosed() { // this function is connected to CmdHub::destroyed() as a way to catch if the currently // connected command interperter has been killed. command interperters (CmdHub) running in the // background are considered slots in this application so when a command interperter dies, its // the same as a slot getting closed so the session will attempt to re-create or re-attach to // the base slot defined in the profile when this happens. this behavior should not be allowed // if the session is closing so sessionEnding is checked. if (!sessionEnding) { textFromCmd(sessionId, true, tr(" ")); textFromCmd(sessionId, true, tr("<300> Slot id: ") + QString::number(slotId) + tr(" was killed. falling back to slot id: ") + QString::number(baseSlot) + tr(".")); emit createSlot(sessionId, 0, baseSlot); } } void Session::<API key>(const QString &grpName, uint id) { if (grpName.toLower() == groupName.toLower()) { if (onBaseSlot) { // force the session to create or attach to the new base slot if currently connected // to the old base slot. emit createSlot(sessionId, baseSlot, id); } baseSlot = id; } } void Session::groupCmdListChanged(const QString &grpName, const QStringList &ls) { if (grpName.toLower() == groupName.toLower()) { profileCmdList = ls; } } void Session::groupCSListChanged(const QString &grpName, bool cs) { if (grpName.toLower() == groupName.toLower()) { <API key> = cs; } } void Session::<API key>(const QString &grpName, bool state) { if (grpName.toLower() == groupName.toLower()) { cmdListenabled = state; } } void Session::<API key>(const QString &grpName, uint mode) { if (grpName.toLower() == groupName.toLower()) { cmdListMode = mode; } } void Session::profileGroupChanged(const QString &proName) { if (profileName.toLower() == proName.toLower()) { QByteArray unused; loadProfile(profileName, unused); <API key>(groupName, baseSlot); } } void Session::profileNameChanged(const QString &oldName, const QString &newName) { if (profileName.toLower() == oldName.toLower()) { profileName = newName; textFromCmd(sessionId, true, tr(" ")); textFromCmd(sessionId, true, tr("<301> Your current profile name was changed to: ") + newName); } } void Session::groupRenamed(const QString &oldName, const QString &newName) { if (groupName.toLower() == oldName.toLower()) { groupName = newName; } } void Session::profileDeleted(const QString &proName) { if (profileName.toLower() == proName.toLower()) { textFromCmd(sessionId, true, tr(" ")); textFromCmd(sessionId, true, tr("<302> Your current profile got deleted, ending this session.")); sessionEnding = true; emit deleteSession(sessionId); } } void Session::sessionSlotChanged(uint sesId, uint slId) { // this should be connected to the Server object's sessionSlotChanged() signal to help this // object keep track of the slotId it is currently connected to. if (sesId == sessionId) { textFromCmd(sessionId, true, tr(" ")); textFromCmd(sessionId, true, tr("<201> Connected to slot id: ") + QString::number(slId) + tr(".")); slotId = slId; onBaseSlot = (slotId == baseSlot); } } void Session::clientDisconnected() { addIpAction(tr("Disconnected"), peerAddress().toString()); if (!sessionEnding) { sessionEnding = true; emit deleteSession(sessionId); } } void Session::sessionTimeout() { sessionEnding = true; emit deleteSession(sessionId); } void Session::requestedToClose(uint sesId) { if (sesId == 0) { sessionEnding = true; emit deleteSession(sessionId); } else if (sesId == sessionId) { emit okToDelete(sesId); close(); } } void Session::dataToClient(const QByteArray &data, uint exclude, uchar flgs) { if (keyOk && (exclude != sessionId)) { // data format: [num_of_bits][flags][data_size][data] // it's very important that the data is sent in this format and encrypted to avoid // undefined behavior. QByteArray lenBa = wrInt(data.size()); QByteArray flagsBa = QByteArray(1, flgs); QByteArray bitsBa = QByteArray(1, (uchar) lenBa.size() * 8); write(wrHash->xOR(Hash::ENCODE, bitsBa + flagsBa + lenBa + data)); } } void Session::textFromCmd(uint sesId, bool cr, const QString &line) { QTextCodec *codec = QTextCodec::codecForName("UTF-16LE"); if (cr) dataToClient(codec->fromUnicode(line), 0, TEXT_CH); else dataToClient(codec->fromUnicode(line), sesId, TEXT_CH); } void Session::textFromServer(uint sesId, const QString &line) { if ((sesId == sessionId) || (sesId == 0)) { textFromCmd(sessionId, true, line); } } void Session::binFromCmd(uint sesId, bool cr, bool priv, const QByteArray &bin) { if (priv) { if (sesId == sessionId) { dataToClient(bin, 0, BIN_CH); } } else { if (cr) dataToClient(bin, 0, BIN_CH); else dataToClient(bin, sesId, BIN_CH); } } void Session::dataFilter(const QByteArray &data, uchar flgs) { // this take the decrypted data from dataFromClient() and converts it to a // QString if the flgs TEXT_CH is present or reads the command name from // the raw data if BIN_CH is present. the the command name or full command // line is then checked with profileAllowedCmd() at this point. QString line; if (flgs & TEXT_CH) { line = QTextCodec::codecForName("UTF-16LE")->toUnicode(data); if (profileAllowedCmd(line)) { emit textToCmd(sessionId, &profileName, line); } } else if (flgs & BIN_CH) { if (activeHook) { emit binToCmd(sessionId, &profileName, data); } else { bool found = false; for (int i = 0; i < data.size(); i += 2) { QByteArray chrPair(data.mid(i, 2)); if (chrPair.size() == 2) { if ((chrPair[0] == (char) 0) && (chrPair[1] == (char) 0)) { line = QTextCodec::codecForName("UTF-16LE")->toUnicode(data.left(i)); if (profileAllowedCmd(line)) { emit binToCmd(sessionId, &profileName, data); } found = true; break; } } } if (!found) { textFromCmd(sessionId, true, tr("<105> Call to binary command has no terminator.")); } } } } void Session::setHookState(bool state) { // this is used in Server::attach() to make this class aware of the // hook state of the currently connected CmdHub. activeHook = state; } bool Session::profileAllowedCmd(const QString &line) { // this take in the sent in command line from the client and attempts // the match it with the patterns defined in the profileCmdList if the // list is enabled. empty lines are allowed no matter what. bool ret = true; // command filtering need to be completely bypassed if there is an // active hook on the currently attached CmdHub. if (!activeHook) { if (cmdListenabled && !line.isEmpty()) { bool matched = false; for (int i = 0; (i < profileCmdList.size()) && !matched; ++i) { QRegExp regEx(profileCmdList[i]); regEx.setPatternSyntax(QRegExp::Wildcard); if (<API key>) regEx.setCaseSensitivity(Qt::CaseSensitive); else regEx.setCaseSensitivity(Qt::CaseInsensitive); matched = regEx.exactMatch(line); } // matched == true at this point indicate that a pattern was found // of cmdListMode is checked to determine if the command should be // allowed to run or not. if (matched && (cmdListMode == <API key>)) { textFromCmd(sessionId, true, tr(" ")); textFromCmd(sessionId, true, tr("<108> Command rejected by the host.")); ret = false; } else if (!matched && (cmdListMode == <API key>)) { textFromCmd(sessionId, true, tr(" ")); textFromCmd(sessionId, true, tr("<108> Command rejected by the host.")); ret = false; } else if (matched && (cmdListMode != <API key>)) { textFromCmd(sessionId, true, tr(" ")); textFromCmd(sessionId, true, tr("<108> host bug! - command list mode not recognized. mode: ") + QString::number(cmdListMode)); ret = false; } } } return ret; } void Session::dataFromClient() { if (keyOk && !sessionEnding) { if (dSize) //stage 5 { if (bytesAvailable() >= dSize) { dataFilter(rdHash->xOR(Hash::DECODE, read(dSize)), flags); dSize = 0; bits = 0; flags = 0; dataFromClient(); } } else if (bits) //stage 4 { if (bytesAvailable() >= bits / 8) { dSize = rdInt(rdHash->xOR(Hash::DECODE, read(bits / 8))); if (dSize) { dataFromClient(); } else if (flags & TEXT_CH) { // 0 on dSize at this point assumes empty text was sent to the // host so this code will actually locally create empty text // and send it through dataFilter(). dataFilter(QTextCodec::codecForName("UTF-16LE")->fromUnicode(tr("")), flags); flags = 0; bits = 0; } else { // just like above, this will locally create an empty QByteArray() // to send through dataFilter(). dataFilter(QByteArray(), flags); flags = 0; bits = 0; } } } else if (bytesAvailable() >= 2) //stage 3 { QByteArray data = rdHash->xOR(Hash::DECODE, read(2)); bits = (uchar) data[0]; flags = (uchar) data[1]; if ((bits > MAX_BITS) || (bits < 8)) { bits = 0; flags = 0; addIpAction(tr("Out-of-sync event (int bits over maximum or < 8)"), peerAddress().toString()); // the client will must likely end up de-synced with the server // at this point. the best way to recover will be to re-start // a new session. (<API key>) } else { dataFromClient(); } } } else if (verOk) //stage 2 { // SHA3-512 == 64 bytes. if (bytesAvailable() >= 64) { if (rdHash->passHash() == rdHash->xOR(Hash::DECODE, read(64))) { // numeric value 1 indicates that the passHash matches with // the host and will unlock stage 3-5 until the session closes. // a successful match also resets the ban increment. keyOk = true; write(wrInt(1, 8)); waitForBytesWritten(); emit createSlot(sessionId, 0, baseSlot); emit clearIPBanCount(peerAddress().toString()); } else { // numeric value 2 indicates that the passHash sent in from the // client is invalid. clients are free to make more attempts at this // stage but keep in mind that the ban increment will only grow with // each failed attempt. addIpAction(tr("Client passHash missmatch"), peerAddress().toString()); write(wrInt(2, 8)); emit incrementIPBan(sessionId, peerAddress().toString()); } } } else { if ((bytesAvailable() >= CLIENT_HEADER_LEN) && !sessionEnding) //stage 1 { // client header format: [3bytes(tag)][2bytes(major)][2bytes(minor)][2bytes(patch)][58bytes(profile)] // tag = 0x4D, 0x43, 0x49 (MCI) // major = 16bit little endian int // minor = 16bit little endian int // patch = 16bit little endian int // profile = UTF-16LE string (padded with white spaces to fill 29 max chars) // note: profile names in this app are case insensitive. timer->stop(); if (read(3) == QByteArray(SERVER_HEADER_TAG)) { clientMajor = rdInt(read(2)); clientMinor = rdInt(read(2)); clientPatch = rdInt(read(2)); QByteArray servHeader; QByteArray reply; QByteArray key; QByteArray proName = read(60); addIpAction(tr("Client version: ") + QString::number(clientMajor) + "." + QString::number(clientMinor) + "." + QString::number(clientPatch), peerAddress().toString()); if ((clientMajor >= 1) && (clientMinor > 0)) { QString proStr = QTextCodec::codecForName("UTF-16LE")->toUnicode(proName).trimmed(); addIpAction(tr("Profile name: ") + proStr, peerAddress().toString()); if (loadProfile(proStr, key)) { reply = wrInt(1, 8); verOk = true; addIpAction(tr("Client version and profile ok"), peerAddress().toString()); } else { reply = wrInt(2, 8); addIpAction(tr("Profile not found"), peerAddress().toString()); } } else { reply = wrInt(3, 8); addIpAction(tr("Client version rejected"), peerAddress().toString()); } QStringList ver = QApplication::applicationVersion().split('.'); servHeader.append(reply); servHeader.append(wrInt(ver[0].toShort(), 16)); servHeader.append(wrInt(ver[1].toShort(), 16)); servHeader.append(wrInt(ver[2].toShort(), 16)); if (verOk) { rdHash = new Hash(key + TO_SERV_SALT, sessionId, this); wrHash = new Hash(key + FROM_SERV_SALT, sessionId, this); servHeader.append(rdHash->seqBytes()); servHeader.append(wrHash->seqBytes()); servHeader.append(rdHash->sessionIdBytes()); if (servHeader.size() != SERVER_HEADER_LEN) { addIpAction(tr("Host bug! - header len != ") + QString::number(SERVER_HEADER_LEN), peerAddress().toString()); } write(servHeader); } else { servHeader.append(QByteArray(NUM_OF_SEQ + 4, 0)); write(servHeader); waitForBytesWritten(); sessionEnding = true; emit deleteSession(sessionId); } } else { addIpAction(tr("Invalid tag"), peerAddress().toString()); sessionEnding = true; emit deleteSession(sessionId); } } } }
class UsersController < <API key> def index users = User.all render json: users end end
export * from './results.handler';
using System; using System.IO; using System.Collections.Generic; using System.Text; using Kontract.IO; namespace Kontract.Compression { public class LZSSVLE { public static byte[] Decompress(Stream input, bool leaveOpen = false) { using (var br = new BinaryReader(input, Encoding.Default, leaveOpen)) { Tuple<int, int> GetNibbles(byte b) => new Tuple<int, int>(b >> 4, b & 0xF); int ReadVLC(int seed = 0) { while (true) { var b = br.ReadByte(); seed = (seed << 7) | (b / 2); if (b % 2 != 0) return seed; } } var filesize = ReadVLC(); var unk1 = ReadVLC(); // filetype maybe??? var unk2 = ReadVLC(); // compression type = 1 (LZSS?) var buffer = new List<byte>(); while (buffer.Count < filesize) { // literal var copiesSize = GetNibbles(br.ReadByte()); var copies = copiesSize.Item1; var size = copiesSize.Item2; if (size == 0) size = ReadVLC(); if (copies == 0) copies = ReadVLC(); buffer.AddRange(br.ReadBytes(size)); // copy stuff while (copies { var lengthOffset = GetNibbles(br.ReadByte()); var length = lengthOffset.Item1; var offset = lengthOffset.Item2; if (offset % 2 == 0) offset = ReadVLC(offset / 2) * 2; else offset >>= 1; if (length == 0) length = ReadVLC(length); while (length-- >= 0) buffer.Add(buffer[buffer.Count - offset / 2 - 1]); } } return buffer.ToArray(); } } } }
<? if($this->uri->segment(3,'add') == 'add'): ?> <h2>Create user</h2> <? else: ?> <h2>Edit user "<?= $member->full_name; ?>"</h2> <? endif; ?> <?=form_open($this->uri->uri_string()); ?> <fieldset> <legend>Details</legend> <div class="field"> <label for="first_name">First Name</label> <?= form_input('first_name', $member->first_name, 'class="text"'); ?> </div> <div class="field"> <label for="first_name">Surname</label> <?= form_input('last_name', $member->last_name, 'class="text"'); ?> </div> <div class="field"> <label for="email">E-mail</label> <?= form_input('email', $member->email, 'class="text"'); ?> </div> <div class="field"> <label for="active">Activate</label> <?= form_checkbox('is_active', 1, $member->is_active == 1); ?> </div> </fieldset> <fieldset> <legend>Password</legend> <div class="field"> <label for="password">Password</label> <?= form_password('password', '', 'class="text"'); ?> </div> <div class="field"> <label for="confirm_password">Confirm Password</label> <?= form_password('confirm_password', '', 'class="text"'); ?> </div> </fieldset> <? $this->load->view('admin/layout_fragments/table_buttons', array('buttons' => array('save', 'cancel') )); ?> <?=form_close(); ?>
#ifndef <API key> #define <API key> #include <QDialog> #include <QDebug> #include <QComboBox> #include <QLineEdit> #include <QVBoxLayout> #include <QHBoxLayout> #include <QScrollBar> #include <QWidget> #include "setvariablewidget.h" namespace Ui { class <API key>; } class <API key> : public QDialog { Q_OBJECT public: struct UniformAttachment { QString uniformName; QString programName; QString variableName; }; public: explicit <API key>(QWidget *parent = 0); ~<API key>(); void setUniformSettings(QList<UniformAttachment> list); QList<UniformAttachment> getUniformSettings(); QList<UniformAttachment> getRemovedSettings(); private: void customConnect(); private: Ui::<API key> *ui; const int layerIncY; int layerY; QVBoxLayout* vbox; QList<SetVariableWidget*> lines; QList<UniformAttachment> removed; private slots: void <API key>(); void <API key>(QWidget* widget); }; #endif // <API key>
#include <<API key>/plugin_aggregators/world_model.h> namespace <API key> { WorldModel::WorldModel() : <API key><WorldModel, <API key>>("WorldModel") { } void WorldModel::loadPlugins(bool print_warning) { <API key><WorldModel, <API key>>::loadPlugins(print_warning); // get terrain model vigir_pluginlib::PluginManager::getPlugin(terrain_model_); if (terrain_model_) { ROS_INFO("[WorldModel] Found terrain model:"); ROS_INFO(" %s (%s)", terrain_model_->getName().c_str(), terrain_model_->getTypeClass().c_str()); } } bool WorldModel::loadParams(const <API key>::ParameterSet& params) { bool result = <API key><WorldModel, <API key>>::loadParams(params); if (terrain_model_) result &= terrain_model_->loadParams(params); return result; } void WorldModel::resetPlugins() { <API key><WorldModel, <API key>>::resetPlugins(); if (terrain_model_) terrain_model_->reset(); } bool WorldModel::isAccessible(const State& s) const { for (<API key>::Ptr plugin : getPlugins()) { if (plugin && plugin-><API key>() && !plugin->isAccessible(s)) return false; } return true; } bool WorldModel::isAccessible(const State& next, const State& current) const { for (<API key>::Ptr plugin : getPlugins()) { if (plugin && plugin-><API key>() && !plugin->isAccessible(next, current)) return false; } return true; } void WorldModel::useTerrainModel(bool enabled) { use_terrain_model_ = enabled; } bool WorldModel::<API key>() const { return terrain_model_ && terrain_model_-><API key>(); } TerrainModelPlugin::ConstPtr WorldModel::getTerrainModel() const { return terrain_model_; } bool WorldModel::getHeight(double x, double y, double& height) const { if (!use_terrain_model_ || !<API key>()) return true; return terrain_model_->getHeight(x, y, height); } bool WorldModel::update3DData(State& s) const { if (!use_terrain_model_ || !<API key>()) return true; return terrain_model_->update3DData(s); } }
# -*- encoding: utf-8 -*- # OpenERP, Open Source Management Solution # This program is free software: you can redistribute it and/or modify # published by the Free Software Foundation, either version 3 of the # This program is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the import logging from openerp.osv import osv, fields _logger = logging.getLogger(__name__) class res_users(osv.osv): _inherit = "res.users" _columns = { '<API key>': fields.integer('XIS external user', required=True), }
<?php include_once 'CommunityApi.php'; use Illuminate\Foundation\Testing\<API key>; class <API key> extends CommunityApi { use <API key>; public function setUp() { parent::setUp(); } //////////////////////////////////////////////////////// CORRECT RESPONSES public function <API key>() { $this->signInAsRole('administrator'); $community = factory(App\Community::class)->create(); $this->delete('/api/community/'.$community->slug) -><API key>(200); } //////////////////////////////////////////////////////// INCORRECT RESPONSES }
/*global require,module,console,angular */ require("angular/angular"); require("angular-route/angular-route"); angular.module("RegistrationApp", ["ngRoute"]); angular.module("RegistrationApp").controller("RegistrationCtrl", require("./components/registration/controller")); angular.module("RegistrationApp").directive("myRegistration", require("./components/registration/directive")); angular.module("MainApp", [ "RegistrationApp" ]); angular.module("MainApp").config(["$routeProvider", "$locationProvider", require("./app.routes")]);
package com.lizardtech.djvubean.outline; import java.awt.Color; import java.awt.Component; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.ListCellRenderer; import javax.swing.UIManager; public class <API key> implements ListCellRenderer { public Component <API key>(JList jlist, Object value, int cellIndex, boolean isSelected, boolean cellHasFocus) { if (value instanceof JPanel) { Component component = (Component) value; component.setForeground (Color.white); component.setBackground (isSelected ? UIManager.getColor("Table.focusCellForeground") : Color.white); return component; } else { // TODO - I get one String here when the JList is first rendered; proper way to deal with this? //System.out.println("Got something besides a JPanel: " + value.getClass().getCanonicalName()); return new JLabel("???"); } }}
<!DOCTYPE html PUBLIC "- <html> <head> <title>Singular 2-0-4 Manual: D.5.5.15 newtonpoly</title> <meta name="description" content="Singular 2-0-4 Manual: D.5.5.15 newtonpoly"> <meta name="keywords" content="Singular 2-0-4 Manual: D.5.5.15 newtonpoly"> <meta name="resource-type" content="document"> <meta name="distribution" content="global"> <meta name="Generator" content="texi2html"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <style type="text/css"> <! @import "sing_tex4ht_tex.css"; a.summary-letter {text-decoration: none} blockquote.smallquotation {font-size: smaller} div.display {margin-left: 3.2em} div.example {margin-left: 3.2em} div.lisp {margin-left: 3.2em} div.smalldisplay {margin-left: 3.2em} div.smallexample {margin-left: 3.2em} div.smalllisp {margin-left: 3.2em} pre.display {font-family: serif} pre.format {font-family: serif} pre.menu-comment {font-family: serif} pre.menu-preformatted {font-family: serif} pre.smalldisplay {font-family: serif; font-size: smaller} pre.smallexample {font-size: smaller} pre.smallformat {font-family: serif; font-size: smaller} pre.smalllisp {font-size: smaller} span.nocodebreak {white-space:pre} span.nolinebreak {white-space:pre} span.roman {font-family:serif; font-weight:normal} span.sansserif {font-family:sans-serif; font-weight:normal} ul.no-bullet {list-style: none} </style> </head> <body lang="en" background="../singular_images/Mybg.png"> <a name="newtonpoly"></a> <table border="0" cellpadding="0" cellspacing="0"> <tr valign="top"> <td align="left"> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr valign="top" align="left"> <td valign="middle" align="left"> <a href="index.htm"><img src="../singular_images/<API key>.png" width="50" border="0" alt="Top"></a> </td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="delta.html#delta" title="Previous section in reading order"><img src="../singular_images/a_left.png" border="0" alt="Back: D.5.5.14 delta" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="is_005fNND.html#is_005fNND" title="Next section in reading order"><img src="../singular_images/a_right.png" border="0" alt="Forward: D.5.5.16 is_NND" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="SINGULAR-libraries.html#SINGULAR-libraries" title="Beginning of this chapter or previous chapter"><img src="../singular_images/a_leftdouble.png" border="0" alt="FastBack: Appendix D SINGULAR libraries" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="Release-Notes.html#Release-Notes" title="Next chapter"><img src="../singular_images/a_rightdouble.png" border="0" alt="FastForward: E Release Notes" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="hnoether_005flib.html#hnoether_005flib" title="Up section"><img src="../singular_images/a_up.png" border="0" alt="Up: D.5.5 hnoether_lib" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="index.htm#Preface" title="Cover (top) of document"><img src="../singular_images/a_top.png" border="0" alt="Top: 1 Preface" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="sing_toc.htm#SEC_Contents" title="Table of contents"><img src="../singular_images/a_tableofcon.png" border="0" alt="Contents: Table of Contents" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="Index.html#Index" title="Index"><img src="../singular_images/a_index.png" border="0" alt="Index: F Index" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="sing_abt.htm#SEC_About" title="About (help)"><img src="../singular_images/a_help.png" border="0" alt="About: About This Document" align="middle"></a></td> </tr> </table> </td> <td align="left"> <a name="newtonpoly-1"></a> <h4 class="subsubsection">D.5.5.15 newtonpoly</h4> <a name="index-newtonpoly"></a> <p>Procedure from library <code>hnoether.lib</code> (see <a href="hnoether_005flib.html#hnoether_005flib">hnoether_lib</a>). </p> <dl compact="compact"> <dt><strong>Usage:</strong></dt> <dd><p>newtonpoly(f); f poly </p> </dd> <dt><strong>Assume:</strong></dt> <dd><p>basering has exactly two variables; <br> f is convenient, that is, f(x,0) != 0 != f(0,y). </p> </dd> <dt><strong>Return:</strong></dt> <dd><p>list of intvecs (= coordinates x,y of the Newton polygon of f). </p> </dd> <dt><strong>Note:</strong></dt> <dd><p>Procedure uses <code>execute</code>; this can be avoided by calling <code>newtonpoly(f,1)</code> if the ordering of the basering is <code>ls</code>. </p> <a name="<API key>"></a> </dd> </dl> <p><strong>Example:</strong> </p><div class="smallexample"> <pre class="smallexample">LIB &quot;hnoether.lib&quot;; ring r=0,(x,y),ls; poly f=x5+2x3y-x2y2+3xy5+y6-y7; newtonpoly(f); &rarr; [1]: &rarr; 0,6 &rarr; [2]: &rarr; 2,2 &rarr; [3]: &rarr; 3,1 &rarr; [4]: &rarr; 5,0 </pre></div> </td> </tr> </table> <hr> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr><td valign="middle" align="left"> <a href="index.htm"><img src="../singular_images/<API key>.png" width="50" border="0" alt="Top"></a> </td> <td valign="middle" align="left"><a href="delta.html#delta" title="Previous section in reading order"><img src="../singular_images/a_left.png" border="0" alt="Back: D.5.5.14 delta" align="middle"></a></td> <td valign="middle" align="left"><a href="is_005fNND.html#is_005fNND" title="Next section in reading order"><img src="../singular_images/a_right.png" border="0" alt="Forward: D.5.5.16 is_NND" align="middle"></a></td> <td valign="middle" align="left"><a href="SINGULAR-libraries.html#SINGULAR-libraries" title="Beginning of this chapter or previous chapter"><img src="../singular_images/a_leftdouble.png" border="0" alt="FastBack: Appendix D SINGULAR libraries" align="middle"></a></td> <td valign="middle" align="left"><a href="Release-Notes.html#Release-Notes" title="Next chapter"><img src="../singular_images/a_rightdouble.png" border="0" alt="FastForward: E Release Notes" align="middle"></a></td> <td valign="middle" align="left"><a href="hnoether_005flib.html#hnoether_005flib" title="Up section"><img src="../singular_images/a_up.png" border="0" alt="Up: D.5.5 hnoether_lib" align="middle"></a></td> <td valign="middle" align="left"><a href="index.htm#Preface" title="Cover (top) of document"><img src="../singular_images/a_top.png" border="0" alt="Top: 1 Preface" align="middle"></a></td> <td valign="middle" align="left"><a href="sing_toc.htm#SEC_Contents" title="Table of contents"><img src="../singular_images/a_tableofcon.png" border="0" alt="Contents: Table of Contents" align="middle"></a></td> <td valign="middle" align="left"><a href="Index.html#Index" title="Index"><img src="../singular_images/a_index.png" border="0" alt="Index: F Index" align="middle"></a></td> <td valign="middle" align="left"><a href="sing_abt.htm#SEC_About" title="About (help)"><img src="../singular_images/a_help.png" border="0" alt="About: About This Document" align="middle"></a></td> </tr></table> <font size="-1"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; User manual for <a href="http: generated by <a href="http: </font> </body> </html>
#pragma once // Structures shared between both RCT1 and RCT2. #include "../common.h" #include "../object/Object.h" #include <string> #include <string_view> constexpr const uint8_t <API key> = 255; constexpr const uint8_t RCT12_MAX_AWARDS = 4; constexpr const uint8_t <API key> = 61; constexpr const uint8_t <API key> = 4; constexpr const uint8_t <API key> = 2; constexpr const uint8_t <API key> = 4; // The number of elements in the patrol_areas array per staff member. Every bit in the array represents a 4x4 square. // In RCT1, that's an 8-bit array. 8 * 128 = 1024 bits, which is also the number of 4x4 squares on a 128x128 map. // For RCT2, it's a 32-bit array. 32 * 128 = 4096 bits, which is also the number of 4x4 squares on a 256x256 map. constexpr const uint8_t <API key> = 128; constexpr const uint8_t <API key> = 4; constexpr const uint8_t <API key> = 4; constexpr const uint8_t <API key> = 32; constexpr const uint8_t RCT12_SOUND_ID_NULL = 0xFF; constexpr const uint8_t <API key> = 16; constexpr const uint8_t <API key> = 14; constexpr const uint8_t <API key> = 128; constexpr const uint16_t <API key> = 1024; constexpr const uint8_t <API key> = 32; constexpr const uint8_t <API key> = 5; constexpr const uint8_t RCT12_RIDE_ID_NULL = 255; constexpr const uint16_t <API key> = 4800; constexpr uint16_t const <API key> = 31; constexpr uint16_t const <API key> = 31; constexpr uint16_t const RCT12_MAX_HELICES = 31; constexpr uint8_t <API key> = std::numeric_limits<uint8_t>::max(); constexpr const uint8_t <API key> = 0xE0; // in RCT12TileElement.properties.surface.slope constexpr const uint8_t <API key> = 0x1F; // in RCT12TileElement.properties.surface.terrain constexpr const uint8_t <API key> = 0xE0; // in RCT12TileElement.properties.surface.terrain constexpr const uint16_t <API key> = 0x3FF; constexpr uint16_t const RCT12_XY8_UNDEFINED = 0xFFFF; using <API key> = uint8_t; constexpr const <API key> <API key> = 255; // Everything before this point has been researched constexpr const uint32_t <API key> = 0xFFFFFFFF; // Everything before this point and after separator still requires research constexpr const uint32_t <API key> = 0xFFFFFFFE; // Extra end of list entry. Leftover from RCT1. constexpr const uint32_t <API key> = 0xFFFFFFFD; constexpr const uint8_t <API key> = 255; constexpr const uint16_t <API key> = 0xFFFF; enum class <API key> : uint8_t { TD4, TD4_AA, TD6, unknown }; enum { <API key> = (1 << 4), <API key> = (1 << 5), <API key> = (1 << 5), <API key> = (1 << 6), <API key> = (1 << 6), <API key> = (1 << 6), <API key> = (1 << 7) }; enum { <API key> = 1 << 7, }; enum { <API key> = 0b01110000, <API key> = 0b00001111, <API key> = 0b11110000, }; enum { // Not anything to do with colour but uses // that field in the tile element // Used for multi-dimension coaster <API key> = (1 << 2), // Used for giga coaster <API key> = (1 << 3), <API key> = 0b00011100, <API key> = 0b11100000, }; // Masks and flags for values stored in TileElement.properties.path.type enum { <API key> = (1 << 0) | (1 << 1), <API key> = (1 << 2), <API key> = (1 << 3), <API key> = (1 << 4) | (1 << 5) | (1 << 6) | (1 << 7), }; // Masks and flags for values stored in in RCT12TileElement.properties.path.additions enum { <API key> = (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3), // The most significant bit in this mask will always be zero, since rides can only have 4 stations <API key> = (1 << 4) | (1 << 5) | (1 << 6), <API key> = (1 << 7), }; enum { <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, // Added by OpenRCT2 }; #pragma pack(push, 1) struct RCT12xy8 { union { struct { uint8_t x, y; }; uint16_t xy; }; bool isNull() const { return xy == RCT12_XY8_UNDEFINED; } void setNull() { xy = RCT12_XY8_UNDEFINED; } }; assert_struct_size(RCT12xy8, 2); /* Maze Element entry size: 0x04 */ struct <API key> { union { uint32_t all; struct { int8_t x; int8_t y; union { uint16_t maze_entry; struct { uint8_t direction; uint8_t type; }; }; }; }; }; assert_struct_size(<API key>, 0x04); /* Track Element entry size: 0x02 */ struct <API key> { uint8_t type; // 0x00 uint8_t flags; // 0x01 }; assert_struct_size(<API key>, 0x02); struct rct12_award { uint16_t time; uint16_t type; }; assert_struct_size(rct12_award, 4); /** * A single news item / message. * size: 0x10C */ struct rct12_news_item { uint8_t Type; uint8_t Flags; uint32_t Assoc; uint16_t Ticks; uint16_t MonthYear; uint8_t Day; uint8_t pad_0B; char Text[256]; }; assert_struct_size(rct12_news_item, 0x10C); struct rct12_xyzd8 { uint8_t x, y, z, direction; }; assert_struct_size(rct12_xyzd8, 4); struct rct12_peep_spawn { uint16_t x; uint16_t y; uint8_t z; uint8_t direction; }; assert_struct_size(rct12_peep_spawn, 6); enum class <API key> : uint8_t { Surface = (0 << 2), Path = (1 << 2), Track = (2 << 2), SmallScenery = (3 << 2), Entrance = (4 << 2), Wall = (5 << 2), LargeScenery = (6 << 2), Banner = (7 << 2), Corrupt = (8 << 2), EightCarsCorrupt14 = (14 << 2), EightCarsCorrupt15 = (15 << 2), }; struct RCT12SurfaceElement; struct RCT12PathElement; struct RCT12TrackElement; struct <API key>; struct <API key>; struct RCT12WallElement; struct <API key>; struct RCT12BannerElement; struct RCT12CorruptElement; struct <API key>; struct <API key>; struct <API key> { uint8_t type; uint8_t flags; // 1. Upper nibble: flags. Lower nibble: occupied quadrants (one bit per quadrant). uint8_t base_height; uint8_t clearance_height; uint8_t GetType() const; uint8_t GetDirection() const; void SetDirection(uint8_t direction); uint8_t <API key>() const; void <API key>(uint8_t quadrants); bool IsLastForTile() const; void SetLastForTile(bool on); bool IsGhost() const; void SetGhost(bool isGhost); }; /** * Map element structure * size: 0x08 */ struct RCT12TileElement : public <API key> { uint8_t pad_04[4]; template<typename TType, <API key> TClass> TType* as() const { return static_cast<<API key>>(GetType()) == TClass ? reinterpret_cast<TType*>(const_cast<RCT12TileElement*>(this)) : nullptr; } RCT12SurfaceElement* AsSurface() const { return as<RCT12SurfaceElement, <API key>::Surface>(); } RCT12PathElement* AsPath() const { return as<RCT12PathElement, <API key>::Path>(); } RCT12TrackElement* AsTrack() const { return as<RCT12TrackElement, <API key>::Track>(); } <API key>* AsSmallScenery() const { return as<<API key>, <API key>::SmallScenery>(); } <API key>* AsLargeScenery() const { return as<<API key>, <API key>::LargeScenery>(); } RCT12WallElement* AsWall() const { return as<RCT12WallElement, <API key>::Wall>(); } <API key>* AsEntrance() const { return as<<API key>, <API key>::Entrance>(); } RCT12BannerElement* AsBanner() const { return as<RCT12BannerElement, <API key>::Banner>(); } void ClearAs(uint8_t newType); uint8_t GetBannerIndex(); }; assert_struct_size(RCT12TileElement, 8); struct RCT12SurfaceElement : <API key> { private: uint8_t slope; // 4 0xE0 Edge Style, 0x1F Slope uint8_t terrain; // 5 0xE0 Terrain Style, 0x1F Water height uint8_t grass_length; uint8_t ownership; public: uint8_t GetSlope() const; uint32_t GetSurfaceStyle() const; uint32_t GetEdgeStyle() const; uint8_t GetGrassLength() const; uint8_t GetOwnership() const; uint32_t GetWaterHeight() const; uint8_t GetParkFences() const; bool <API key>() const; void SetSlope(uint8_t newSlope); void SetSurfaceStyle(uint32_t newStyle); void SetEdgeStyle(uint32_t newStyle); void SetGrassLength(uint8_t newLength); void SetOwnership(uint8_t newOwnership); void SetWaterHeight(uint32_t newWaterHeight); void SetParkFences(uint8_t newParkFences); void <API key>(bool on); }; assert_struct_size(RCT12SurfaceElement, 8); struct RCT12PathElement : <API key> { private: uint8_t entryIndex; // 4, 0xF0 Path type, 0x08 Ride sign, 0x04 Set when path is sloped, 0x03 Rotation uint8_t additions; // 5, 0bGSSSAAAA: G = Ghost, S = station index, A = addition (0 means no addition) uint8_t edges; union { uint8_t additionStatus; uint8_t rideIndex; }; public: <API key> GetEntryIndex() const; uint8_t <API key>() const; bool IsSloped() const; uint8_t GetSlopeDirection() const; uint8_t GetRideIndex() const; uint8_t GetStationIndex() const; bool IsWide() const; bool IsQueue() const; bool HasQueueBanner() const; uint8_t GetEdges() const; uint8_t GetCorners() const; uint8_t GetAddition() const; bool AdditionIsGhost() const; uint8_t GetAdditionStatus() const; uint8_t GetRCT1PathType() const; uint8_t GetRCT1SupportType() const; void SetPathEntryIndex(<API key> newIndex); void <API key>(uint8_t direction); void SetSloped(bool isSloped); void SetSlopeDirection(uint8_t newSlope); void SetRideIndex(uint8_t newRideIndex); void SetStationIndex(uint8_t newStationIndex); void SetWide(bool isWide); void SetIsQueue(bool isQueue); void SetHasQueueBanner(bool hasQueueBanner); void SetEdges(uint8_t newEdges); void SetCorners(uint8_t newCorners); void SetAddition(uint8_t newAddition); void SetAdditionIsGhost(bool isGhost); void SetAdditionStatus(uint8_t newStatus); bool IsBroken() const; void SetIsBroken(bool isBroken); bool IsBlockedByVehicle() const; void <API key>(bool isBlocked); }; assert_struct_size(RCT12PathElement, 8); struct RCT12TrackElement : <API key> { private: uint8_t trackType; union { struct { // The lower 4 bits are the track sequence. // The upper 4 bits are either station bits or on-ride photo bits. // Station bits: // - Bit 8 marks green light // - Bit 5-7 are station index. // On-ride photo bits: // - Bits 7 and 8 are never set // - Bits 5 and 6 are set when a vehicle triggers the on-ride photo and act like a countdown from 3. // - If any of the bits 5-8 are set, the game counts it as a photo being taken. uint8_t sequence; uint8_t colour; }; uint16_t mazeEntry; }; uint8_t rideIndex; public: uint8_t GetTrackType() const; uint8_t GetSequenceIndex() const; uint8_t GetRideIndex() const; uint8_t GetColourScheme() const; uint8_t GetStationIndex() const; bool HasChain() const; bool HasCableLift() const; bool IsInverted() const; uint8_t <API key>() const; bool HasGreenLight() const; uint8_t GetSeatRotation() const; uint16_t GetMazeEntry() const; uint8_t GetPhotoTimeout() const; // Used in RCT1, will be reintroduced at some point. uint8_t GetDoorAState() const; uint8_t GetDoorBState() const; void SetTrackType(uint8_t newEntryIndex); void SetSequenceIndex(uint8_t newSequenceIndex); void SetRideIndex(uint8_t newRideIndex); void SetColourScheme(uint8_t newColourScheme); void SetStationIndex(uint8_t newStationIndex); void SetHasChain(bool on); void SetHasCableLift(bool on); void SetInverted(bool inverted); bool BlockBrakeClosed() const; void SetBlockBrakeClosed(bool isClosed); void <API key>(uint8_t speed); void SetHasGreenLight(uint8_t greenLight); void SetSeatRotation(uint8_t newSeatRotation); void SetMazeEntry(uint16_t newMazeEntry); void SetPhotoTimeout(uint8_t newValue); bool IsIndestructible() const; void SetIsIndestructible(bool isIndestructible); }; assert_struct_size(RCT12TrackElement, 8); struct <API key> : <API key> { private: uint8_t entryIndex; uint8_t age; uint8_t colour_1; uint8_t colour_2; public: <API key> GetEntryIndex() const; uint8_t GetAge() const; uint8_t GetSceneryQuadrant() const; colour_t GetPrimaryColour() const; colour_t GetSecondaryColour() const; bool NeedsSupports() const; void SetEntryIndex(<API key> newIndex); void SetAge(uint8_t newAge); void SetSceneryQuadrant(uint8_t newQuadrant); void SetPrimaryColour(colour_t colour); void SetSecondaryColour(colour_t colour); void SetNeedsSupports(); }; assert_struct_size(<API key>, 8); struct <API key> : <API key> { private: uint16_t entryIndex; uint8_t colour[2]; public: uint32_t GetEntryIndex() const; uint16_t GetSequenceIndex() const; colour_t GetPrimaryColour() const; colour_t GetSecondaryColour() const; uint8_t GetBannerIndex() const; void SetEntryIndex(uint32_t newIndex); void SetSequenceIndex(uint16_t sequence); void SetPrimaryColour(colour_t colour); void SetSecondaryColour(colour_t colour); void SetBannerIndex(uint8_t newIndex); }; assert_struct_size(<API key>, 8); struct RCT12WallElement : <API key> { private: uint8_t entryIndex; union { uint8_t colour_3; uint8_t banner_index; }; uint8_t colour_1; // 6 0b_2221_1111 2 = colour_2 (uses flags for rest of colour2), 1 = colour_1 uint8_t animation; // 7 0b_dfff_ft00 d = direction, f = frame num, t = across track flag (not used) public: <API key> GetEntryIndex() const; uint8_t GetSlope() const; colour_t GetPrimaryColour() const; colour_t GetSecondaryColour() const; colour_t GetTertiaryColour() const; uint8_t GetAnimationFrame() const; uint8_t GetBannerIndex() const; bool IsAcrossTrack() const; bool <API key>() const; uint32_t <API key>() const; int32_t GetRCT1WallType(int32_t edge) const; colour_t GetRCT1WallColour() const; void SetEntryIndex(<API key> newIndex); void SetSlope(uint8_t newslope); void SetPrimaryColour(colour_t newColour); void SetSecondaryColour(colour_t newColour); void SetTertiaryColour(colour_t newColour); void SetAnimationFrame(uint8_t frameNum); void SetBannerIndex(uint8_t newIndex); void SetAcrossTrack(bool acrossTrack); void <API key>(bool isBackwards); }; assert_struct_size(RCT12WallElement, 8); struct <API key> : <API key> { private: uint8_t entranceType; uint8_t index; // 5. 0bUSSS????, S = station index. uint8_t pathType; uint8_t rideIndex; public: uint8_t GetEntranceType() const; uint8_t GetRideIndex() const; uint8_t GetStationIndex() const; uint8_t GetSequenceIndex() const; uint8_t GetPathType() const; void SetEntranceType(uint8_t newType); void SetRideIndex(uint8_t newRideIndex); void SetStationIndex(uint8_t stationIndex); void SetSequenceIndex(uint8_t newSequenceIndex); void SetPathType(uint8_t newPathType); }; assert_struct_size(<API key>, 8); struct RCT12BannerElement : <API key> { private: uint8_t index; uint8_t position; uint8_t flags; #pragma clang diagnostic push #pragma clang diagnostic ignored "-<API key>" uint8_t unused; #pragma clang diagnostic pop public: uint8_t GetIndex() const; uint8_t GetPosition() const; uint8_t GetAllowedEdges() const; void SetIndex(uint8_t newIndex); void SetPosition(uint8_t newPosition); void SetAllowedEdges(uint8_t newEdges); }; assert_struct_size(RCT12BannerElement, 8); struct RCT12CorruptElement : <API key> { uint8_t pad[4]; }; assert_struct_size(RCT12CorruptElement, 8); struct <API key> : <API key> { uint8_t pad[4]; }; assert_struct_size(<API key>, 8); struct <API key> : <API key> { uint8_t pad[4]; }; assert_struct_size(<API key>, 8); struct RCT12SpriteBase { uint8_t sprite_identifier; // 0x00 uint8_t type; // 0x01 uint16_t next_in_quadrant; // 0x02 uint16_t next; // 0x04 uint16_t previous; // 0x06 uint8_t <API key>; // 0x08 uint8_t <API key>; // 0x09 uint16_t sprite_index; // 0x0A uint16_t flags; // 0x0C int16_t x; // 0x0E int16_t y; // 0x10 int16_t z; // 0x12 uint8_t sprite_width; // 0x14 uint8_t <API key>; // 0x15 int16_t sprite_left; // 0x16 int16_t sprite_top; // 0x18 int16_t sprite_right; // 0x1A int16_t sprite_bottom; // 0x1C uint8_t sprite_direction; // 0x1E }; assert_struct_size(RCT12SpriteBase, 0x1F); struct RCT12SpriteBalloon : RCT12SpriteBase { uint8_t pad_1F[0x24 - 0x1F]; uint16_t popped; // 0x24 uint8_t time_to_move; // 0x26 uint8_t frame; // 0x27 uint8_t pad_28[4]; uint8_t colour; // 0x2C }; assert_struct_size(RCT12SpriteBalloon, 0x2D); struct RCT12SpriteDuck : RCT12SpriteBase { uint8_t pad_1F[0x26 - 0x1F]; uint16_t frame; // 0x26 uint8_t pad_28[0x30 - 0x28]; int16_t target_x; // 0x30 int16_t target_y; // 0x32 uint8_t pad_34[0x14]; uint8_t state; // 0x48 }; assert_struct_size(RCT12SpriteDuck, 0x49); struct RCT12SpriteLitter : RCT12SpriteBase { uint8_t pad_1F[0x24 - 0x1F]; uint32_t creationTick; // 0x24 }; assert_struct_size(RCT12SpriteLitter, 0x28); struct RCT12SpriteParticle : RCT12SpriteBase { uint8_t pad_1F[0x26 - 0x1F]; uint16_t frame; // 0x26 }; assert_struct_size(RCT12SpriteParticle, 0x28); struct <API key> : RCT12SpriteBase { uint8_t pad_1F[0x26 - 0x1F]; uint8_t num_ticks_alive; // 0x26 uint8_t frame; // 0x27 uint8_t pad_28[0x2F - 0x28]; uint8_t fountain_flags; // 0x2F int16_t target_x; // 0x30 int16_t target_y; // 0x32 uint8_t pad_34[0x46 - 0x34]; uint16_t iteration; // 0x46 }; assert_struct_size(<API key>, 0x48); struct <API key> : RCT12SpriteBase { uint8_t pad_1F[0x24 - 0x1F]; uint16_t move_delay; // 0x24 uint8_t num_movements; // 0x26 uint8_t vertical; money32 value; // 0x28 uint8_t pad_2C[0x44 - 0x2C]; int16_t offset_x; // 0x44 uint16_t wiggle; // 0x46 }; assert_struct_size(<API key>, 0x48); struct <API key> : RCT12SpriteBase { uint8_t pad_1F[0x24 - 0x1F]; uint16_t time_to_live; // 0x24 uint16_t frame; // 0x26 uint8_t pad_28[0x2C - 0x28]; uint8_t colour[2]; // 0x2C uint16_t crashed_sprite_base; // 0x2E int16_t velocity_x; // 0x30 int16_t velocity_y; // 0x32 int16_t velocity_z; // 0x34 uint8_t pad_36[0x38 - 0x36]; int32_t acceleration_x; // 0x38 int32_t acceleration_y; // 0x3C int32_t acceleration_z; // 0x40 }; assert_struct_size(<API key>, 0x44); struct <API key> : RCT12SpriteBase { uint8_t pad_1F[0x26 - 0x1F]; uint16_t frame; // 0x26 }; assert_struct_size(<API key>, 0x28); struct <API key> : RCT12SpriteBase { uint8_t pad_1F[0x24 - 0x1F]; uint16_t time_to_move; // 0x24 uint16_t frame; // 0x26 }; assert_struct_size(<API key>, 0x28); struct RCT12PeepThought { uint8_t type; uint8_t item; uint8_t freshness; uint8_t fresh_timeout; }; assert_struct_size(RCT12PeepThought, 4); struct <API key> { uint8_t ride_index; // 0x0000 uint8_t flags; // 0x0001 uint32_t last_use_tick; // 0x0002 uint16_t num_items; // 0x0006 uint16_t current_item; // 0x0008 uint8_t vehicle_index; // 0x000A uint8_t current_station; // 0x000B int8_t vertical[<API key>]; // 0x000C int8_t lateral[<API key>]; // 0x12CC uint8_t velocity[<API key>]; // 0x258C uint8_t altitude[<API key>]; // 0x384C }; assert_struct_size(<API key>, 0x4B0C); struct RCT12Banner { <API key> type; uint8_t flags; // 0x01 rct_string_id string_idx; // 0x02 union { uint8_t colour; // 0x04 uint8_t ride_index; // 0x04 }; uint8_t text_colour; // 0x05 uint8_t x; // 0x06 uint8_t y; // 0x07 }; assert_struct_size(RCT12Banner, 8); struct RCT12MapAnimation { uint8_t baseZ; uint8_t type; uint16_t x; uint16_t y; }; assert_struct_size(RCT12MapAnimation, 6); struct RCT12ResearchItem { // Bit 16 (0: scenery entry, 1: ride entry) union { uint32_t rawValue; struct { <API key> entryIndex; uint8_t baseRideType; uint8_t type; // 0: scenery entry, 1: ride entry uint8_t flags; }; }; uint8_t category; bool IsInventedEndMarker() const; bool IsRandomEndMarker() const; bool <API key>() const; }; assert_struct_size(RCT12ResearchItem, 5); #pragma pack(pop) ObjectEntryIndex <API key>(const <API key> index); <API key> <API key>(const ObjectEntryIndex index);
package pl.nkg.brq.android.ui; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import pl.nkg.brq.android.R; import pl.nkg.brq.android.events.SensorsRecord; import pl.nkg.brq.android.events.SensorsServiceState; import pl.nkg.brq.android.services.SensorsService; public class MainActivity extends AppCompatActivity { private static final int <API key> = 29; @Bind(R.id.button_on) Button mButtonOn; @Bind(R.id.button_off) Button mButtonOff; @Bind(R.id.speedTextView) TextView mSpeedTextView; @Bind(R.id.altitudeTextView) TextView mAltitudeTextView; @Bind(R.id.shakeTextView) TextView mShakeTextView; @Bind(R.id.noiseTextView) TextView mNoiseTextView; @Bind(R.id.distanceTextView) TextView mDistanceTextView; @Bind(R.id.warningTextView) TextView mWarningTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (Build.VERSION.SDK_INT >= 23) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.<API key>) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.<API key>) != PackageManager.PERMISSION_GRANTED) { Log.w("BleActivity", "Location access not granted!"); ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.<API key>, Manifest.permission.<API key>, Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.BLUETOOTH}, <API key>); } } ButterKnife.bind(this); } @Override protected void onStart() { super.onStart(); EventBus.getDefault().register(this); } @Override protected void onStop() { super.onStop(); EventBus.getDefault().unregister(this); } @OnClick(R.id.button_on) public void onButtonOnClick() { startService(new Intent(MainActivity.this, SensorsService.class)); } @OnClick(R.id.button_off) public void onButtonOffClick() { stopService(new Intent(MainActivity.this, SensorsService.class)); } @Subscribe(threadMode = ThreadMode.MAIN) public void onEventMainThread(SensorsServiceState state) { } @Subscribe(threadMode = ThreadMode.MAIN) public void onEventMainThread(SensorsRecord record) { mSpeedTextView.setText((int) (record.speed * 3.6) + " km/h"); mAltitudeTextView.setText((int) record.altitude + " m n.p.m."); mShakeTextView.setText((int) (record.shake * 100) / 100.0 + " m/s²"); mNoiseTextView.setText((int) record.soundNoise + " db"); mDistanceTextView.setText((double) record.distance / 100.0 + " m"); if (record.distance < 120 && record.distance != 0) { mWarningTextView.setVisibility(View.VISIBLE); mWarningTextView.setText((double) record.distance / 100.0 + " m"); mWarningTextView.setTextSize(Math.min(5000 / record.distance, 100)); } else { mWarningTextView.setVisibility(View.GONE); } } }
package com.malak.yaim.model; import java.util.List; public class FlickrFeed { private String title; private String link; private String description; private String modified; private String generator; private List<Item> items = null; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getModified() { return modified; } public void setModified(String modified) { this.modified = modified; } public String getGenerator() { return generator; } public void setGenerator(String generator) { this.generator = generator; } public List<Item> getItems() { return items; } public void setItems(List<Item> items) { this.items = items; } }
import json import re def <API key>(data): """Return the root input type from JSON formatted string.""" return parse_format(json.loads(data)) def parse_format(data): """Returns root input type from data.""" input_types = {} data = data['ist_nodes'] root_id = data[0]['id'] # set root type for item in data: input_type = _get_input_type(item) if input_type is not None: input_types[input_type['id']] = input_type # register by id <API key>(input_types) return input_types[root_id] SCALAR = ['Integer', 'Double', 'Bool', 'String', 'Selection', 'FileName'] def is_scalar(input_type): """Returns True if input_type is scalar.""" return input_type['base_type'] in SCALAR RE_PARAM = re.compile('^<([a-zA-Z][a-zA-Z0-9_]*)>$') def is_param(value): """Determine whether given value is a parameter string.""" if not isinstance(value, str): return False return RE_PARAM.match(value) def <API key>(input_types): """Replaces ids or type names with python object references.""" input_type = {} def <API key>(): """Replaces implementation ids with input_types.""" impls = {} for id_ in input_type['implementations']: type_ = input_types[id_] impls[type_['name']] = type_ input_type['implementations'] = impls def <API key>(): """Replaces default descendant id with input_type.""" id_ = input_type.get('default_descendant', None) if id_ is not None: input_type['default_descendant'] = input_types[id_] def <API key>(): """Replaces key type with input_type.""" # pylint: disable=unused-variable, invalid-name for __, value in input_type['keys'].items(): value['type'] = input_types[value['type']] # pylint: disable=unused-variable, invalid-name for __, input_type in input_types.items(): if input_type['base_type'] == 'Array': input_type['subtype'] = input_types[input_type['subtype']] elif input_type['base_type'] == 'Abstract': <API key>() <API key>() elif input_type['base_type'] == 'Record': <API key>() def _get_input_type(data): """Returns the input_type data structure that defines an input type and its constraints for validation.""" if 'id' not in data or 'input_type' not in data: return None input_type = dict( id=data['id'], base_type=data['input_type'] ) input_type['name'] = data.get('name', '') input_type['full_name'] = data.get('full_name', '') input_type['description'] = data.get('description', '') input_type['attributes'] = data.get('attributes', {}) if input_type['base_type'] in ['Double', 'Integer']: input_type.update(_parse_range(data)) elif input_type['base_type'] == 'Array': input_type.update(_parse_range(data)) if input_type['min'] < 0: input_type['min'] = 0 input_type['subtype'] = data['subtype'] elif input_type['base_type'] == 'FileName': input_type['file_mode'] = data['file_mode'] elif input_type['base_type'] == 'Selection': input_type['values'] = _list_to_dict(data['values'], 'name') elif input_type['base_type'] == 'Record': input_type['keys'] = _list_to_dict(data['keys']) input_type['implements'] = data.get('implements', []) input_type['reducible_to_key'] = data.get('reducible_to_key', None) elif input_type['base_type'] == 'Abstract': input_type['implementations'] = data['implementations'] input_type['default_descendant'] = data.get('default_descendant', None) return input_type def _parse_range(data): """Parses the format range properties - min, max.""" input_type = {} try: input_type['min'] = data['range'][0] except (KeyError, TypeError): # set default value input_type['min'] = float('-inf') try: input_type['max'] = data['range'][1] except (KeyError, TypeError): # set default value input_type['max'] = float('inf') return input_type def _list_to_dict(list_, key_label='key'): """ Transforms a list of dictionaries into a dictionary of dictionaries. Original dictionaries are assigned key specified in each of them by key_label. """ dict_ = {} for item in list_: dict_[item[key_label]] = item return dict_
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEditor; using System.IO; public class Serializer : MonoBehaviour { //save defaults are only used to set the data used when initializing that map the next time. string saveFile; string loadFile; string fileName; public string saveData; public string defaults; <API key> player; // Use this for initialization void Start () { player = Globals.playerScript; //save on disc saveData = Path.Combine(Application.persistentDataPath, "SaveData"); // defaults included in project defaults = "Assets/Resources/Defaults/"; CreateDirectories(); } // Update is called once per frame void Update () { } void CreateDirectories() { if(!Directory.Exists(saveData)) { Directory.CreateDirectory(saveData); } /*if(!Directory.Exists(defaults)) { Directory.CreateDirectory(defaults); }*/ } public void SavePlayerData() { PlayerSaveData playerData = new PlayerSaveData() { level = player.level, statPoints = player.statPoints, skillPoints = player.skillPoints, spentStatPoints = player.spentStatPoints, spentSkillPoints = player.spentSkillPoints, currentHealth = player.currentHealth, maxHealth = player.maxHealth, currentXP = player.currentXP, xpToLevel = player.xpToLevel, atk = player.atk, atkItemBonus = player.atkItemBonus, statAtk = player.statAtk, def = player.def, defItemBonus = player.defItemBonus, statDef = player.statDef, skill1Lvl = player.skills[0].level, skill2Lvl = player.skills[1].level, skill3Lvl = player.skills[2].level, skill4Lvl = player.skills[3].level, lookingX = (int)player.looking.x, lookingY = (int)player.looking.y, direction = player.direction, bronzeKeys = player.bronzeKeys, silverKeys = player.silverKeys, goldKeys = player.goldKeys, currentMap = Globals.currentMap, redOrbState = player.redOrbState, blueOrbState = player.blueOrbState, storyProgress = player.storyProgress, sideQuests = new List<PlayerSaveData.PlayerQuests>() }; foreach(Quest q in player.quests) { PlayerSaveData.PlayerQuests quest = new PlayerSaveData.PlayerQuests(); quest.questName = q.questName; quest.description = q.description; quest.complete = q.complete; quest.progress = q.progress; playerData.sideQuests.Add(quest); } string json = JsonUtility.ToJson(playerData); string fileName = Path.Combine(saveData, "player.json"); if(File.Exists(fileName)) { File.Delete(fileName); } File.WriteAllText(fileName, json); SavePlayerInventory(); //Debug.Log(json); Debug.Log(fileName); } public void SavePlayerInventory() { PlayerInventory playerInventory = new PlayerInventory(); try { foreach (InventoryItemBase i in player.inventory) { playerInventory.inventoryItems.Add(i); } } catch { Debug.Log("Empty Inventory"); } string json = JsonUtility.ToJson(playerInventory); string fileName = Path.Combine(saveData, "inventory.json"); if (File.Exists(fileName)) { File.Delete(fileName); } File.WriteAllText(fileName, json); } public void LoadPlayerInventory() { try { fileName = Path.Combine(saveData, "inventory.json"); loadFile = File.ReadAllText(fileName); PlayerInventory load = JsonUtility.FromJson<PlayerInventory>(loadFile); if (load.inventoryItems.Count > 0) { player.inventory.Clear(); foreach (InventoryItemBase i in load.inventoryItems) { player.inventory.Add(i); } } } catch { Debug.Log("Problem loading inventory"); } } public void LoadPlayerData() { fileName = Path.Combine(saveData, "player.json"); loadFile = File.ReadAllText(fileName); PlayerSaveData load = JsonUtility.FromJson<PlayerSaveData>(loadFile); //Debug.Log(load.level+ "" + load.statPoints+""+ load.skillPoints+ "" +load.currentMap); player.level = load.level; player.statPoints = load.statPoints; player.skillPoints = load.skillPoints; player.spentStatPoints = load.spentStatPoints; player.spentSkillPoints = load.spentSkillPoints; player.maxHealth = load.maxHealth; player.currentHealth = load.currentHealth; player.xpToLevel = load.xpToLevel; player.currentXP = load.currentXP; player.atk = load.atk; player.statAtk = load.statAtk; player.atkItemBonus = load.atkItemBonus; player.def = load.def; player.statDef = load.statDef; player.defItemBonus = load.defItemBonus; player.skills[0].level = load.skill1Lvl; player.skills[1].level = load.skill2Lvl; player.skills[2].level = load.skill3Lvl; player.skills[3].level = load.skill4Lvl; player.looking = new Vector2(load.lookingX, load.lookingY); player.direction = load.direction; player.bronzeKeys = load.bronzeKeys; player.silverKeys = load.silverKeys; player.goldKeys = load.goldKeys; player.redOrbState = load.redOrbState; player.blueOrbState = load.blueOrbState; player.storyProgress = load.storyProgress; //for (int x = 0; x < load.sideQuests.Count; x++) // Debug.Log(load.sideQuests[x].questName); // Debug.Log(load.sideQuests[x].description); // Debug.Log(load.sideQuests[x].complete); // Debug.Log(load.sideQuests[x].progress); // player.quests.Add(new Quest(load.sideQuests[x].questName, load.sideQuests[x].description, load.sideQuests[x].complete, load.sideQuests[0].progress)); foreach (PlayerSaveData.PlayerQuests q in load.sideQuests) { //Debug.Log(q.questName); //Debug.Log(q.description); //Debug.Log(q.complete); //Debug.Log(q.progress); player.quests.Add(new Quest(q.questName, q.description, q.complete, q.progress)); //Debug.Log(player.quests[0].questName); } LoadPlayerInventory(); } public string SavedFloor() { //used to load in saved floor fileName = Path.Combine(saveData, "player.json"); loadFile = File.ReadAllText(fileName); PlayerSaveData load = JsonUtility.FromJson<PlayerSaveData>(loadFile); return load.currentMap; } //public void SaveMap(int x, int y) // MapSaveData mapData = new MapSaveData() // returnPointX = x, // returnPointY = y // string json = JsonUtility.ToJson(mapData); // string fileName = Path.Combine(saveData, SceneManager.GetActiveScene().name + ".json"); // if (File.Exists(fileName)) // File.Delete(fileName); // File.WriteAllText(fileName, json); //public void LoadMap(string nextMap) // fileName = Path.Combine(saveData, nextMap + ".json"); // loadFile = File.ReadAllText(fileName); // MapSaveData load = JsonUtility.FromJson<MapSaveData>(loadFile); // player.gameObject.transform.position = new Vector2(load.returnPointX + .5f, load.returnPointY-.5f); /*public void SaveEnemies() { try { EnemiesOnMap mapEnemies = new EnemiesOnMap { mapEnemyInfo = new List<EnemiesOnMap.EnemyInfo>() }; foreach (GameObject enemy in GameObject.<API key>("Enemy")) { EnemyBase currentEnemy = enemy.GetComponent<EnemyBase>(); EnemiesOnMap.EnemyInfo newInfo = new EnemiesOnMap.EnemyInfo(); { newInfo.enemyName = currentEnemy.enemyName.ToString(); newInfo.posX = (int)currentEnemy.transform.position.x; newInfo.posY = (int)currentEnemy.transform.position.y; newInfo.alive = currentEnemy.alive; newInfo.heldItem = currentEnemy.heldItem; } mapEnemies.mapEnemyInfo.Add(newInfo); } string json = JsonUtility.ToJson(mapEnemies); string fileName = Path.Combine(saveData, Globals.currentMap + "enemies.json"); if (File.Exists(fileName)) { File.Delete(fileName); } File.WriteAllText(fileName, json); } catch { Debug.Log("No Enemies here"); } } public void SaveEnemiesDefault() { try { EnemiesOnMap mapEnemies = new EnemiesOnMap { mapEnemyInfo = new List<EnemiesOnMap.EnemyInfo>() }; foreach (GameObject enemy in GameObject.<API key>("Enemy")) { EnemyBase currentEnemy = enemy.GetComponent<EnemyBase>(); EnemiesOnMap.EnemyInfo newInfo = new EnemiesOnMap.EnemyInfo(); { newInfo.enemyName = currentEnemy.enemyName.ToString(); newInfo.posX = (int)currentEnemy.transform.position.x; newInfo.posY = (int)currentEnemy.transform.position.y; newInfo.alive = currentEnemy.alive; newInfo.heldItem = currentEnemy.heldItem; } mapEnemies.mapEnemyInfo.Add(newInfo); Destroy(enemy); } string json = JsonUtility.ToJson(mapEnemies); string fileName = Path.Combine(defaults, Globals.currentMap + "defaultenemies.json"); if (File.Exists(fileName)) { File.Delete(fileName); } File.WriteAllText(fileName, json); } catch { Debug.Log("No Enemies here"); } } public void LoadEnemies() {try { StartCoroutine(LoadEnemiesDelay()); } catch { Debug.Log("No Enemies Loaded"); } } public IEnumerator LoadEnemiesDelay() { yield return new WaitForSeconds(.5f); if (File.Exists(Path.Combine(saveData, Globals.currentMap + "enemies.json"))) { fileName = Path.Combine(saveData, Globals.currentMap + "enemies.json"); } else { fileName = Path.Combine(defaults, Globals.currentMap + "defaultenemies.json"); } Debug.Log("loading enemies from " + fileName); loadFile = File.ReadAllText(fileName); EnemiesOnMap load = JsonUtility.FromJson<EnemiesOnMap>(loadFile); Container enemyContainer = GameObject.FindWithTag("Container").GetComponent<Container>(); //foreach (EnemiesOnMap.EnemyInfo info in load.mapEnemyInfo) //{ // //load into a list. // //enemyContainer.CreateEnemy(info.enemyName, info.posX, info.posY, info.alive); //} for(int x = load.mapEnemyInfo.Count -1; x>-1; x--) { //start new enemy //set its info to load[x] //create from container //clear entry from list EnemiesOnMap.EnemyInfo e = load.mapEnemyInfo[x]; enemyContainer.CreateEnemy(e.enemyName, e.posX, e.posY, e.alive,e.heldItem); load.mapEnemyInfo.RemoveAt(x); } yield return null; } public void SaveItems() { try { ItemsOnMap mapItems = new ItemsOnMap { mapItemInfo = new List<ItemsOnMap.ItemInfo>() }; foreach (GameObject item in GameObject.<API key>("Item")) { ItemBase currentItem = item.GetComponent<ItemBase>(); ItemsOnMap.ItemInfo newInfo = new ItemsOnMap.ItemInfo(); { newInfo.itemName = currentItem.itemName.ToString(); newInfo.value = currentItem.value; newInfo.posX = (int)currentItem.transform.position.x; newInfo.posY = (int)currentItem.transform.position.y; //newInfo.active = currentItem.active; } mapItems.mapItemInfo.Add(newInfo); } string json = JsonUtility.ToJson(mapItems); string fileName = Path.Combine(saveData, Globals.currentMap + "items.json"); if (File.Exists(fileName)) { File.Delete(fileName); } File.WriteAllText(fileName, json); } catch { Debug.Log("No Items Here"); } } public void SaveItemsDefault() { try { ItemsOnMap mapItems = new ItemsOnMap { mapItemInfo = new List<ItemsOnMap.ItemInfo>() }; foreach (GameObject item in GameObject.<API key>("Item")) { ItemBase currentItem = item.GetComponent<ItemBase>(); ItemsOnMap.ItemInfo newInfo = new ItemsOnMap.ItemInfo(); { newInfo.itemName = currentItem.itemName.ToString(); newInfo.value = currentItem.value; newInfo.posX = (int)currentItem.transform.position.x; newInfo.posY = (int)currentItem.transform.position.y; //newInfo.active = currentItem.active; } mapItems.mapItemInfo.Add(newInfo); Destroy(item); } string json = JsonUtility.ToJson(mapItems); string fileName = Path.Combine(defaults, Globals.currentMap + "defaultitems.json"); if (File.Exists(fileName)) { File.Delete(fileName); } File.WriteAllText(fileName, json); } catch { Debug.Log("No Items Here"); } } public void LoadItems() { try { StartCoroutine(LoadItemsDelay()); } catch { Debug.Log("No items loaded"); } } public IEnumerator LoadItemsDelay() { yield return new WaitForSeconds(.5f); if (File.Exists(Path.Combine(saveData, Globals.currentMap + "items.json"))) { fileName = Path.Combine(saveData, Globals.currentMap + "items.json"); } else { fileName = Path.Combine(defaults, Globals.currentMap + "defaultitems.json"); } Debug.Log("loading items from " + fileName); loadFile = File.ReadAllText(fileName); ItemsOnMap load = JsonUtility.FromJson<ItemsOnMap>(loadFile); Container itemContainer = GameObject.FindWithTag("Container").GetComponent<Container>(); //foreach (ItemsOnMap.ItemInfo info in load.mapItemInfo) //{ // Debug.Log(info.itemName); // itemContainer.CreateItem(info.itemName, info.value, info.posX, info.posY, info.active); //} for (int x = load.mapItemInfo.Count - 1; x > -1; x--) { ItemsOnMap.ItemInfo i = load.mapItemInfo[x]; itemContainer.CreateItem(i.itemName,i.value, i.posX, i.posY); load.mapItemInfo.RemoveAt(x); } yield return null; } public void SaveDoors() { try { DoorsOnMap mapDoors = new DoorsOnMap { mapDoorInfo = new List<DoorsOnMap.DoorInfo>() }; foreach (GameObject item in GameObject.<API key>("Door")) { DoorBase currentItem = item.GetComponent<DoorBase>(); DoorsOnMap.DoorInfo newInfo = new DoorsOnMap.DoorInfo(); { newInfo.doorType = currentItem.doorType.ToString(); newInfo.doorName = currentItem.doorName; newInfo.posX = (int)currentItem.transform.position.x; newInfo.posY = (int)currentItem.transform.position.y; } mapDoors.mapDoorInfo.Add(newInfo); } string json = JsonUtility.ToJson(mapDoors); string fileName = Path.Combine(saveData, Globals.currentMap + "doors.json"); if (File.Exists(fileName)) { File.Delete(fileName); } File.WriteAllText(fileName, json); } catch { Debug.Log("No Doors Here"); } } public void SaveDoorsDefault() { try { DoorsOnMap mapDoors = new DoorsOnMap { mapDoorInfo = new List<DoorsOnMap.DoorInfo>() }; foreach (GameObject item in GameObject.<API key>("Door")) { DoorBase currentItem = item.GetComponent<DoorBase>(); DoorsOnMap.DoorInfo newInfo = new DoorsOnMap.DoorInfo(); { newInfo.doorType = currentItem.doorType.ToString(); newInfo.doorName = currentItem.doorName; newInfo.posX = (int)currentItem.transform.position.x; newInfo.posY = (int)currentItem.transform.position.y; } mapDoors.mapDoorInfo.Add(newInfo); Destroy(item); } string json = JsonUtility.ToJson(mapDoors); string fileName = Path.Combine(defaults, Globals.currentMap + "defaultdoors.json"); if (File.Exists(fileName)) { File.Delete(fileName); } File.WriteAllText(fileName, json); } catch { Debug.Log("No Doors Here"); } } public void LoadDoors() { StartCoroutine(LoadDoorsDelay()); } public IEnumerator LoadDoorsDelay() { yield return new WaitForSeconds(.5f); try { if (File.Exists(Path.Combine(saveData, Globals.currentMap + "doors.json"))) { fileName = Path.Combine(saveData, Globals.currentMap + "doors.json"); } else { fileName = Path.Combine(defaults, Globals.currentMap + "defaultdoors.json"); } Debug.Log("loading doors from " + fileName); loadFile = File.ReadAllText(fileName); DoorsOnMap load = JsonUtility.FromJson<DoorsOnMap>(loadFile); Container itemContainer = GameObject.FindWithTag("Container").GetComponent<Container>(); //foreach (DoorsOnMap.DoorInfo info in load.mapDoorInfo) //{ // itemContainer.CreateDoor(info.doorType, info.posX, info.posY); //} try { for (int x = load.mapDoorInfo.Count - 1; x > -1; x--) { DoorsOnMap.DoorInfo d = load.mapDoorInfo[x]; itemContainer.CreateDoor(d.doorType, d.doorName, d.posX, d.posY); load.mapDoorInfo.RemoveAt(x); } } catch { for (int x = load.mapDoorInfo.Count - 1; x > -1; x--) { DoorsOnMap.DoorInfo d = load.mapDoorInfo[x]; itemContainer.CreateDoor(d.doorType, d.posX, d.posY); load.mapDoorInfo.RemoveAt(x); } } } catch { } yield return null; }*/ public void SaveMapData(bool d) { //true = default; false = other fileName = ""; MapData mapData = new MapData { mapDoorInfo = new List<MapData.Door>(), mapEnemyInfo = new List<MapData.Enemy>(), mapItemInfo = new List<MapData.Item>(), mapBinaryObjectInfo = new List<MapData.BinaryObject>() }; //Save Doors try { foreach (GameObject door in GameObject.<API key>("Door")) { DoorBase currentItem = door.GetComponent<DoorBase>(); MapData.Door newInfo = new MapData.Door(); { //newInfo.doorType = currentItem.doorType.ToString(); newInfo.doorName = currentItem.doorName; newInfo.posX = (int)currentItem.transform.position.x; newInfo.posY = (int)currentItem.transform.position.y; } mapData.mapDoorInfo.Add(newInfo); Destroy(door); } } catch { Debug.Log("problem saving doors"); } //Save Items try { foreach (GameObject item in GameObject.<API key>("Item")) { ItemBase currentItem = item.GetComponent<ItemBase>(); MapData.Item newInfo = new MapData.Item(); { newInfo.itemName = currentItem.itemName.ToString(); newInfo.value = currentItem.value; newInfo.posX = (int)currentItem.transform.position.x; newInfo.posY = (int)currentItem.transform.position.y; //newInfo.active = currentItem.active; } mapData.mapItemInfo.Add(newInfo); Destroy(item); } } catch { Debug.Log("problem saving items"); } //Save Enemies try { foreach (GameObject enemy in GameObject.<API key>("Enemy")) { EnemyBase currentEnemy = enemy.GetComponent<EnemyBase>(); MapData.Enemy newInfo = new MapData.Enemy(); { newInfo.enemyName = currentEnemy.enemyName.ToString(); newInfo.posX = (int)currentEnemy.transform.position.x; newInfo.posY = (int)currentEnemy.transform.position.y; newInfo.alive = currentEnemy.alive; newInfo.heldItem = currentEnemy.heldItem; } mapData.mapEnemyInfo.Add(newInfo); Destroy(enemy); } } catch { Debug.Log("problem saving enemies"); } //Save BinaryItems try { foreach(GameObject binary in GameObject.<API key>("Button")) { BinaryObject currentObject = binary.GetComponent<BinaryObject>(); MapData.BinaryObject newObject = new MapData.BinaryObject(); { newObject.objectName = currentObject.objectName.ToString(); newObject.buttonState = currentObject.buttonState; newObject.objectState = currentObject.objectState; newObject.buttonX = (int)currentObject.transform.position.x; newObject.buttonY = (int)currentObject.transform.position.y; newObject.objectX = currentObject.objectLocationX; newObject.objectY = currentObject.objectLocationY; newObject.canToggle = currentObject.canToggle; } } } catch { //nothing to save } string json = JsonUtility.ToJson(mapData); if(d == true) { fileName = Path.Combine(defaults, Globals.currentMap + ".json"); Debug.Log(d); } else { fileName = Path.Combine(saveData, Globals.currentMap + ".json"); Debug.Log(d); } if (File.Exists(fileName)) { File.Delete(fileName); } File.WriteAllText(fileName, json); Debug.Log("save complete" + fileName); } public IEnumerator LoadMapData() { yield return new WaitForSeconds(.5f); Debug.Log("loading map data"); try { if (File.Exists(Path.Combine(saveData, Globals.currentMap + ".json"))) { fileName = Path.Combine(saveData, Globals.currentMap + ".json"); } else { fileName = Path.Combine(defaults, Globals.currentMap + ".json"); } Debug.Log("loading from " + fileName); loadFile = File.ReadAllText(fileName); MapData load = JsonUtility.FromJson<MapData>(loadFile); Container itemContainer = GameObject.FindWithTag("Container").GetComponent<Container>(); try { for (int x = load.mapDoorInfo.Count - 1; x > -1; x { MapData.Door d = load.mapDoorInfo[x]; itemContainer.CreateDoor(d.doorName, d.posX, d.posY); load.mapDoorInfo.RemoveAt(x); } } catch { Debug.Log("problem loading doors"); } try { for (int x = load.mapItemInfo.Count - 1; x > -1; x { MapData.Item i = load.mapItemInfo[x]; itemContainer.CreateItem(i.itemName, i.value, i.posX, i.posY); load.mapItemInfo.RemoveAt(x); } } catch { } try { for (int x = load.mapEnemyInfo.Count - 1; x > -1; x { MapData.Enemy e = load.mapEnemyInfo[x]; itemContainer.CreateEnemy(e.enemyName, e.posX, e.posY,e.alive,e.heldItem); load.mapEnemyInfo.RemoveAt(x); } } catch { } try { for (int x = load.mapBinaryObjectInfo.Count - 1; x > -1; x { MapData.BinaryObject o = load.mapBinaryObjectInfo[x]; itemContainer.CreateBinaryObject(o.objectName, o.buttonState, o.objectState, o.buttonX, o.buttonY, o.objectX, o.objectY, o.canToggle); load.mapBinaryObjectInfo.RemoveAt(x); } } catch { } } catch { } yield return null; } }
package grid; import java.util.Comparator; import world.World; /** * A <code>Location</code> object represents the row and column of a location * in a two-dimensional grid. <br /> * The API of this class is testable on the AP CS A and AB exams. */ public class Location implements Comparable { private int row; // row location in grid private int col; // column location in grid /** * The turn angle for turning 90 degrees to the left. */ public static final int LEFT = -90; /** * The turn angle for turning 90 degrees to the right. */ public static final int RIGHT = 90; /** * The turn angle for turning 45 degrees to the left. */ public static final int HALF_LEFT = -45; /** * The turn angle for turning 45 degrees to the right. */ public static final int HALF_RIGHT = 45; /** * The turn angle for turning a full circle. */ public static final int FULL_CIRCLE = 360; /** * The turn angle for turning a half circle. */ public static final int HALF_CIRCLE = 180; /** * The turn angle for making no turn. */ public static final int AHEAD = 0; /** * The compass direction for north. */ public static final int NORTH = 0; /** * The compass direction for northeast. */ public static final int NORTHEAST = 45; /** * The compass direction for east. */ public static final int EAST = 90; /** * The compass direction for southeast. */ public static final int SOUTHEAST = 135; /** * The compass direction for south. */ public static final int SOUTH = 180; /** * The compass direction for southwest. */ public static final int SOUTHWEST = 225; /** * The compass direction for west. */ public static final int WEST = 270; /** * The compass direction for northwest. */ public static final int NORTHWEST = 315; /** * Constructs a location with given row and column coordinates. * @param r the row * @param c the column */ public Location(int r, int c) { row = r; col = c; } /** * Gets the row coordinate. * @return the row of this location */ public int getRow() { return row; } /** * Gets the column coordinate. * @return the column of this location */ public int getCol() { return col; } /** * Gets the adjacent location in any one of the eight compass directions. * @param direction the direction in which to find a neighbor location * @return the adjacent location in the direction that is closest to * <tt>direction</tt> */ public Location getAdjacentLocation(int direction) { // reduce mod 360 and round to closest multiple of 45 int adjustedDirection = (direction + HALF_RIGHT / 2) % FULL_CIRCLE; if (adjustedDirection < 0) adjustedDirection += FULL_CIRCLE; adjustedDirection = (adjustedDirection / HALF_RIGHT) * HALF_RIGHT; int dc = 0; int dr = 0; if (adjustedDirection == EAST) dc = 1; else if (adjustedDirection == SOUTHEAST) { dc = 1; dr = 1; } else if (adjustedDirection == SOUTH) dr = 1; else if (adjustedDirection == SOUTHWEST) { dc = -1; dr = 1; } else if (adjustedDirection == WEST) dc = -1; else if (adjustedDirection == NORTHWEST) { dc = -1; dr = -1; } else if (adjustedDirection == NORTH) dr = -1; else if (adjustedDirection == NORTHEAST) { dc = 1; dr = -1; } return new Location(getRow() + dr, getCol() + dc); } /** * Returns the direction from this location toward another location. The * direction is rounded to the nearest compass direction. * @param target a location that is different from this location * @return the closest compass direction from this location toward * <code>target</code> */ public int getDirectionToward(Location target) { int dx = target.getCol() - getCol(); int dy = target.getRow() - getRow(); // y axis points opposite to mathematical orientation int angle = (int) Math.toDegrees(Math.atan2(-dy, dx)); // mathematical angle is counterclockwise from x-axis, // compass angle is clockwise from y-axis int compassAngle = RIGHT - angle; // prepare for truncating division by 45 degrees compassAngle += HALF_RIGHT / 2; // wrap negative angles if (compassAngle < 0) compassAngle += FULL_CIRCLE; // round to nearest multiple of 45 return (compassAngle / HALF_RIGHT) * HALF_RIGHT; } /** * Indicates whether some other <code>Location</code> object is "equal to" * this one. * @param other the other location to test * @return <code>true</code> if <code>other</code> is a * <code>Location</code> with the same row and column as this location; * <code>false</code> otherwise */ public boolean equals(Object other) { if (!(other instanceof Location)) return false; Location otherLoc = (Location) other; return getRow() == otherLoc.getRow() && getCol() == otherLoc.getCol(); } /** * Generates a hash code. * @return a hash code for this location */ public int hashCode() { return getRow() * 3737 + getCol(); } /** * Compares this location to <code>other</code> for ordering. Returns a * negative integer, zero, or a positive integer as this location is less * than, equal to, or greater than <code>other</code>. Locations are * ordered in row-major order. <br /> * (Precondition: <code>other</code> is a <code>Location</code> object.) * @param other the other location to test * @return a negative integer if this location is less than * <code>other</code>, zero if the two locations are equal, or a positive * integer if this location is greater than <code>other</code> */ public int compareTo(Object other) { Location otherLoc = (Location) other; if (getRow() < otherLoc.getRow()) return -1; if (getRow() > otherLoc.getRow()) return 1; if (getCol() < otherLoc.getCol()) return -1; if (getCol() > otherLoc.getCol()) return 1; return 0; } /** * (Added for RatBots) Calculates the distance to another location. * The distance is reported as the sum of the x and y distances * and therefore doesn't consider diagonal movement. * @param other the location that the distance is calculated to * @return the distance */ public int distanceTo(Location other) { int dx = Math.abs(row - other.getRow()); int dy = Math.abs(col - other.getCol()); return dx+dy; } public boolean isValidLocation() { if(this.getRow() < 0 || this.getRow() >= World.DEFAULT_ROWS) return false; if(this.getCol() < 0 || this.getCol() >= World.DEFAULT_COLS) return false; return true; } /** * Creates a string that describes this location. * @return a string with the row and column of this location, in the format * (row, col) */ public String toString() { return "(r:" + getRow() + ", c:" + getCol() + ")"; } }
package de.topobyte.livecg.ui.geometryeditor.preferences; import java.awt.Component; import javax.swing.JComboBox; import javax.swing.JList; import javax.swing.UIManager; import javax.swing.UIManager.LookAndFeelInfo; import javax.swing.plaf.basic.<API key>; import de.topobyte.livecg.preferences.Configuration; public class LAFSelector extends JComboBox { private static final long serialVersionUID = <API key>; public LAFSelector(Configuration configuration) { super(buildValues()); setRenderer(new Renderer()); setEditable(false); String lookAndFeel = configuration.<API key>(); setSelectedIndex(-1); for (int i = 0; i < getModel().getSize(); i++) { LookAndFeelInfo info = (LookAndFeelInfo) getModel().getElementAt(i); if (info.getClassName().equals(lookAndFeel)) { setSelectedIndex(i); break; } } } private static LookAndFeelInfo[] buildValues() { LookAndFeelInfo[] lafs = UIManager.<API key>(); return lafs; } private class Renderer extends <API key> { private static final long serialVersionUID = 1L; @Override public Component <API key>(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.<API key>(list, value, index, isSelected, cellHasFocus); if (value != null) { LookAndFeelInfo item = (LookAndFeelInfo) value; setText(item.getName()); } else { setText("default"); } return this; } } }
$DBversion = 'XXX'; # will be replaced by the RM if( CheckVersion( $DBversion ) ) { $dbh->do(" CREATE TABLE action_logs_cache ( action_id int(11) NOT NULL auto_increment, timestamp timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, user int(11) NOT NULL default 0, module text, action text, object int(11) default NULL, info text, interface VARCHAR(30) DEFAULT NULL, PRIMARY KEY (action_id), KEY timestamp_idx (timestamp), KEY user_idx (user), KEY module_idx (module(255)), KEY action_idx (action(255)), KEY object_idx (object), KEY info_idx (info(255)), KEY interface (interface) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; "); # Always end with this (adjust the bug info) SetVersion( $DBversion ); print "Upgrade to $DBversion done (KD 2990 - MongoDB datawarehouse for storing the logging data.)\n"; }
package com.yoavst.quickapps.calendar; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.provider.CalendarContract; import android.provider.CalendarContract.Events; import com.yoavst.quickapps.Preferences_; import com.yoavst.quickapps.R; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.TimeZone; import static android.provider.CalendarContract.Events.ALL_DAY; import static android.provider.CalendarContract.Events.DISPLAY_COLOR; import static android.provider.CalendarContract.Events.DTEND; import static android.provider.CalendarContract.Events.DTSTART; import static android.provider.CalendarContract.Events.DURATION; import static android.provider.CalendarContract.Events.EVENT_LOCATION; import static android.provider.CalendarContract.Events.RRULE; import static android.provider.CalendarContract.Events.TITLE; import static android.provider.CalendarContract.Events._ID; public class CalendarUtil { private CalendarUtil() { } private static final SimpleDateFormat dayFormatter = new SimpleDateFormat( "EEE, MMM d, yyyy"); private static final SimpleDateFormat dateFormatter = new SimpleDateFormat( "EEE, MMM d, HH:mm"); private static final SimpleDateFormat hourFormatter = new SimpleDateFormat("HH:mm"); private static final SimpleDateFormat fullDateFormat = new SimpleDateFormat("EEE, MMM d"); private static final SimpleDateFormat otherDayFormatter = new SimpleDateFormat("MMM d, HH:mm"); private static final TimeZone timezone = Calendar.getInstance().getTimeZone(); public static ArrayList<Event> getCalendarEvents(Context context) { CalendarResources.init(context); boolean showRepeating = new Preferences_(context).showRepeatingEvents().get(); ArrayList<Event> events = new ArrayList<>(); String selection = "((" + DTSTART + " >= ?) OR (" + DTEND + " >= ?))"; String milli = String.valueOf(System.currentTimeMillis()); String[] selectionArgs = new String[]{milli, milli}; Cursor cursor = context.getContentResolver() .query( Events.CONTENT_URI, new String[]{_ID, TITLE, DTSTART, DTEND, EVENT_LOCATION, ALL_DAY, DISPLAY_COLOR, RRULE, DURATION}, selection, selectionArgs, null ); cursor.moveToFirst(); int count = cursor.getCount(); if (count != 0) { //<editor-fold desc="Future Events"> for (int i = 0; i < count; i++) { int id = cursor.getInt(0); String title = cursor.getString(1); long startDate = Long.parseLong(cursor.getString(2)); String endDateString = cursor.getString(3); String location = cursor.getString(4); boolean isAllDay = cursor.getInt(5) != 0; int color = cursor.getInt(6); String rRule = cursor.getString(7); String duration = cursor.getString(8); if (!isAllDay) { // If the event not repeat itself - regular event if (rRule == null) { long endDate = endDateString == null || endDateString.equals("null") ? 0 : Long.parseLong(endDateString); if (endDate == 0) events.add(new Event(id, title, dayFormatter.format(new Date(startDate - timezone.getOffset(startDate))), location).setColor(color)); else events.add(new Event(id, title, startDate, endDate, location).setColor(color)); } else if (showRepeating) { // Event that repeat itself events = addEvents(events, <API key>(context, rRule, startDate, duration, location, color, title, id, false)); } } else { if (rRule == null) { // One day event probably if (endDateString == null || Long.parseLong(endDateString) == 0) events.add(new Event(id, title, dayFormatter.format(new Date(startDate - timezone.getOffset(startDate))), location).setColor(color)); else if (showRepeating) { int offset = timezone.getOffset(startDate); long newTime = startDate - offset; long endTime = Long.parseLong(endDateString) - offset; events.add(new Event(id, title, newTime, endTime, location, true).setColor(color)); } } else if (showRepeating) { // Repeat all day event, god why?!? events = addEvents(events, <API key>(context, rRule, startDate - timezone.getOffset(startDate), duration, location, color, title, id, true)); } } cursor.moveToNext(); } //</editor-fold> } cursor.close(); if (showRepeating) { String repeatingSections = "((" + DURATION + " IS NOT NULL) AND (" + RRULE + " IS NOT NULL) AND ((" + DTSTART + " < ?) OR (" + DTEND + " < ?)))"; Cursor repeatingCursor = context.getContentResolver() .query( Events.CONTENT_URI, new String[]{_ID, TITLE, DTSTART, EVENT_LOCATION, ALL_DAY, DISPLAY_COLOR, RRULE, DURATION}, repeatingSections, selectionArgs, null ); repeatingCursor.moveToFirst(); int repeatingCount = repeatingCursor.getCount(); if (repeatingCount != 0) { //<editor-fold desc="repeating past Events"> for (int i = 0; i < repeatingCount; i++) { int id = repeatingCursor.getInt(0); String title = repeatingCursor.getString(1); long startDate = Long.parseLong(repeatingCursor.getString(2)); String location = repeatingCursor.getString(3); boolean isAllDay = repeatingCursor.getInt(4) != 0; int color = repeatingCursor.getInt(5); String rRule = repeatingCursor.getString(6); String duration = repeatingCursor.getString(7); if (!isAllDay) { ArrayList<Event> repeatingEvents = <API key>(context, rRule, startDate, duration, location, color, title, id, false); events = addEvents(events, repeatingEvents); } else { ArrayList<Event> repeatingEvents = <API key>(context, rRule, startDate - timezone.getOffset(startDate), duration, location, color, title, id, true); events = addEvents(events, repeatingEvents); } repeatingCursor.moveToNext(); } //</editor-fold> repeatingCursor.close(); } } Collections.sort(events, new Comparator<Event>() { @Override //an integer < 0 if lhs is less than rhs, 0 if they are equal, and > 0 if lhs is greater than rhs. public int compare(Event lhs, Event rhs) { int first = (lhs.getStartDate() - rhs.getStartDate()) < 0 ? -1 : lhs.getStartDate() == rhs.getStartDate() ? 0 : 1; int second = (lhs.getEndDate() - rhs.getEndDate()) < 0 ? -1 : lhs.getEndDate() == rhs.getEndDate() ? 0 : 1; return first != 0 ? first : second; } }); return events; } private static ArrayList<Event> addEvents(ArrayList<Event> list, ArrayList<Event> toAdd) { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, 6); long milli = DateUtils.clearTime(calendar).getTimeInMillis(); long now = System.currentTimeMillis(); for (Event event : toAdd) { if (event.getEndDate() <= milli && event.getEndDate() >= now) list.add(event); } return list; } private static ArrayList<Event> <API key>(Context context, String rRule, long startDate, String duration, String location, int color, String title, int id, boolean isAllDay) { ArrayList<Event> events = new ArrayList<>(); final String[] INSTANCE_PROJECTION = new String[]{ CalendarContract.Instances.EVENT_ID, CalendarContract.Instances.BEGIN, CalendarContract.Instances.END }; Calendar endTime = Calendar.getInstance(); endTime.add(Calendar.MONTH, 6); String selection = CalendarContract.Instances.EVENT_ID + " = ?"; Uri.Builder builder = CalendarContract.Instances.CONTENT_URI.buildUpon(); ContentUris.appendId(builder, System.currentTimeMillis()); ContentUris.appendId(builder, endTime.getTimeInMillis()); Cursor cursor = context.getContentResolver().query(builder.build(), INSTANCE_PROJECTION, selection, new String[]{Integer.toString(id)}, null); if (cursor.moveToFirst()) { do { events.add(new Event(id, title, cursor.getLong(1) - (isAllDay ? timezone.getOffset(startDate) : 0), cursor.getLong(2) - (isAllDay ? timezone.getOffset(startDate) : 0), location, isAllDay).setColor(color)); } while (cursor.moveToNext()); } return events; } public static String getDateFromEvent(Event event) { if (event.getDate() != null) return event.getDate(); else if (event.isAllDay()) { Calendar startPlusOneDay = Calendar.getInstance(); startPlusOneDay.setTimeInMillis(event.getStartDate()); startPlusOneDay.add(Calendar.DAY_OF_YEAR, 1); Calendar endTime = Calendar.getInstance(); endTime.setTimeInMillis(event.getEndDate()); if (DateUtils.isSameDay(startPlusOneDay, endTime)) { startPlusOneDay.add(Calendar.DAY_OF_YEAR, -1); if (DateUtils.isToday(startPlusOneDay)) return CalendarResources.today + " " + CalendarResources.allDay; else if (DateUtils.isTomorrow(startPlusOneDay)) return CalendarResources.tomorrow + " " + CalendarResources.allDay; return dayFormatter.format(new Date(event.getStartDate())); } else { endTime.add(Calendar.DAY_OF_YEAR, -1); startPlusOneDay.add(Calendar.DAY_OF_YEAR, -1); if (DateUtils.isToday(startPlusOneDay)) { if (DateUtils.isTomorrow(endTime)) return CalendarResources.today + " - " + CalendarResources.tomorrow; else return CalendarResources.today + " " + CalendarResources.allDay + " - " + fullDateFormat.format(endTime.getTime()); } else if (DateUtils.isTomorrow(startPlusOneDay)) return CalendarResources.tomorrow + " - " + fullDateFormat.format(endTime.getTime()); return fullDateFormat.format(new Date(event.getStartDate())) + " - " + fullDateFormat.format(endTime.getTime()); } } else { String text; Date first = new Date(event.getStartDate()); Date end = new Date(event.getEndDate()); if (DateUtils.isSameDay(first, end)) { if (DateUtils.isToday(first)) text = CalendarResources.today + " " + hourFormatter.format(first) + " - " + hourFormatter.format(end); else if (DateUtils.isWithinDaysFuture(first, 1)) text = CalendarResources.tomorrow + " " + hourFormatter.format(first) + " - " + hourFormatter.format(end); else text = dateFormatter.format(first) + " - " + hourFormatter.format(end); } else if (DateUtils.isToday(first)) { text = CalendarResources.today + hourFormatter.format(first) + " - " + otherDayFormatter.format(end); } else { text = otherDayFormatter.format(first) + " - " + otherDayFormatter.format(end); } return text; } } public static Intent launchEventById(long id) { Intent intent = new Intent(Intent.ACTION_VIEW); Uri.Builder uri = Events.CONTENT_URI.buildUpon(); uri.appendPath(Long.toString(id)); intent.setData(uri.build()); return intent; } public static String getTimeToEvent(Event event) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(event.getStartDate()); Calendar now = Calendar.getInstance(); now.set(Calendar.SECOND, 0); now.set(Calendar.MILLISECOND, 0); if (calendar.getTimeInMillis() <= now.getTimeInMillis()) return CalendarResources.now; else { long secondsLeft = (calendar.getTimeInMillis() - now.getTimeInMillis()) / 1000; if (secondsLeft < 60) return CalendarResources.in + " 1 " + CalendarResources.minute; long minutesLeft = secondsLeft / 60; if (minutesLeft < 60) return CalendarResources.in + " " + minutesLeft + " " + (minutesLeft > 1 ? CalendarResources.minutes : CalendarResources.minute); long hoursLeft = minutesLeft / 50; if (hoursLeft < 24) return CalendarResources.in + " " + hoursLeft + " " + (hoursLeft > 1 ? CalendarResources.hours : CalendarResources.hour); int days = (int) (hoursLeft / 24); if (days < 30) return CalendarResources.in + " " + days + " " + (days > 1 ? CalendarResources.days : CalendarResources.day); int months = days / 30; if (months < 12) return CalendarResources.in + " " + months + " " + (months > 1 ? CalendarResources.months : CalendarResources.month); else return CalendarResources.moreThenAYearLeft; } } public static class CalendarResources { public static String today; public static String tomorrow; public static String allDay; public static String now; public static String in; public static String minute; public static String minutes; public static String hour; public static String hours; public static String day; public static String days; public static String week; public static String weeks; public static String month; public static String months; public static String moreThenAYearLeft; public static void init(Context context) { if (today == null || moreThenAYearLeft == null) { today = context.getString(R.string.today); tomorrow = context.getString(R.string.tomorrow); allDay = context.getString(R.string.all_day); now = context.getString(R.string.now); in = context.getString(R.string.in); String[] min = context.getString(R.string.minute_s).split("/"); minute = min[0]; minutes = min[1]; String[] hoursArray = context.getString(R.string.hour_s).split("/"); hour = hoursArray[0]; hours = hoursArray[1]; String[] dayArray = context.getString(R.string.day_s).split("/"); day = dayArray[0]; days = dayArray[1]; String[] weekArray = context.getString(R.string.week_s).split("/"); week = weekArray[0]; weeks = weekArray[1]; String[] monthArray = context.getString(R.string.month_s).split("/"); month = monthArray[0]; months = monthArray[1]; moreThenAYearLeft = context.getString(R.string.more_then_year); } } } }
# Filename: rgss.rb # Developer: Raku (rakudayo@gmail.com) # Description: This is the core file to include to enable loading and dumping # of RMXP's .rxdata files. require_relative 'rgss_internal' require_relative 'rgss_rpg' require_relative 'rgss_mod'
#ifndef BUNDLE_H_ #define BUNDLE_H_ int bundle(int argc, char *argv[], int command_index); #endif // BUNDLE_H_
local render2d = ... or _G.render2d do local X, Y, W, H = 0,0 function render2d.SetScissor(x, y, w, h) X = x Y = y W = w or render.GetWidth() H = h or render.GetHeight() if not x then X = 0 Y = 0 render.SetScissor() else x, y = render2d.ScreenToWorld(-x, -y) render.SetScissor(-x, -y, w, h) end end function render2d.GetScissor() return X, Y, W, H end utility.MakePushPopFunction(render2d, "Scissor") end do function render2d.SetStencilState(tbl) if tbl.function_ then end end local function stencil_pass(func, ref) if func == "never" then return false end if func == "equal" then return pixel == ref end end local stencil_pass = stencil_pass(func, ref) local depth_pass = depth_pass() if depth_pass and stencil_pass then elseif not depth_pass and stencil_pass then elseif not stencil_pass then if op == "incr" then pixel = pixel + ref end end 1: 000000000 -- clear 2: 000111110 -- draw stencil rect 2: 000112210 -- draw stencil rect 2: 000111110 -- draw stencil rect ]] local i = 0 local X,Y,W,H function render2d.PushStencilRect(x,y,w,h, i_override) render.StencilFunction("never", 1) render.StencilOperation("increase", "keep", "zero") render2d.PushTexture() render.SetColorMask(0,0,0,0) render2d.DrawRect(x,y,w,h) render.SetColorMask(1,1,1,1) render2d.PopTexture() render.StencilFunction("equal", i) i = i + 1 X,Y,W,H = x,y,w,h end function render2d.PopStencilRect() render.StencilFunction("never", 1) render.StencilOperation("decrease", "keep", "zero") render2d.PushTexture() render.SetColorMask(0,0,0,0) render2d.DrawRect(X,Y,W,H) render.SetColorMask(1,1,1,1) render2d.PopTexture() if i >= 4 then i = 0 end end local i = 0 local X,Y,W,H function render2d.PushStencilRect2(x,y,w,h, i_override) render.StencilFunction("never", 1) render.StencilOperation("increase", "keep", "zero") render2d.PushTexture() render2d.DrawRect(x,y,w,h) render2d.PopTexture() render.StencilFunction("equal", i) i = i + 1 X,Y,W,H = x,y,w,h end function render2d.PopStencilRect2() render.StencilFunction("never", 1) render.StencilOperation("decrease", "keep", "zero") render2d.PushTexture() render2d.DrawRect(X,Y,W,H) render2d.PopTexture() if i >= 4 then i = 0 end end end do local X, Y, W, H function render2d.EnableClipRect(x, y, w, h, i) i = i or 1 render.SetStencil(true) render.GetFrameBuffer():ClearStencil(0) -- out = 0 render.StencilOperation("keep", "replace", "replace") -- if true then stencil = 33 return true end render.StencilFunction("always", i) -- on fail, keep zero value -- on success replace it with 33 -- write to the stencil buffer -- on fail is probably never reached render2d.PushTexture() render.SetColorMask(0,0,0,0) render2d.DrawRect(x, y, w, h) render.SetColorMask(1,1,1,1) render2d.PopTexture() -- if stencil == 33 then stencil = 33 return true else return false end render.StencilFunction("equal", i) X = x Y = y W = w H = h end function render2d.GetClipRect() return X or 0, Y or 0, W or render.GetWidth(), H or render.GetHeight() end function render2d.DisableClipRect() render.SetStencil(false) end end
package uk.tim740.skUtilities.util; import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.SkriptParser; import ch.njol.skript.lang.util.SimpleExpression; import ch.njol.util.Kleenean; import org.bukkit.event.Event; import uk.tim740.skUtilities.skUtilities; import javax.annotation.Nullable; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; public class ExprTimeInTimeZone extends SimpleExpression<String> { private Expression<String> str; @Override @Nullable protected String[] get(Event e) { String s = str.getSingle(e); String[] sl = new String[0]; try { BufferedReader br = new BufferedReader(new FileReader(new File("plugins/Skript/config.sk").getAbsoluteFile())); sl = br.lines().toArray(String[]::new); br.close(); } catch (Exception x) { skUtilities.prSysE(x.getMessage(), getClass().getSimpleName(), x); } String sf = ""; for (String aSl : sl) { if (aSl.contains("date format: ")) { sf = aSl.replaceFirst("date format: ", ""); } } String ff; if (sf.equalsIgnoreCase("default")) { ff = new SimpleDateFormat().toPattern(); } else { ff = sf; } return new String[]{ZonedDateTime.ofInstant(Instant.now(), ZoneId.of(s)).format(DateTimeFormatter.ofPattern(ff))}; } @SuppressWarnings("unchecked") @Override public boolean init(Expression<?>[] e, int i, Kleenean k, SkriptParser.ParseResult p) { str = (Expression<String>) e[0]; return true; } @Override public Class<? extends String> getReturnType() { return String.class; } @Override public boolean isSingle() { return true; } @Override public String toString(@Nullable Event e, boolean b) { return getClass().getName(); } }
-- Erase all reading notes for this VMeasurementID CREATE OR REPLACE FUNCTION cpgdb.ClearReadingNotes( tblVMeasurement.VMeasurementID%TYPE -- the vmeasurement to tie this to ) RETURNS integer AS $_$ DECLARE _VMID ALIAS FOR $1; VMOp text; ret integer; BEGIN -- Get the VMeasurementOp SELECT op.name INTO VMOp FROM tblVMeasurement INNER JOIN tlkpVMeasurementOp op USING (vmeasurementOpID) WHERE vmeasurementID=_VMID; IF NOT FOUND THEN RAISE EXCEPTION 'Invalid/nonexistent vmeasurement %', _VMID; END IF; -- Just delete all the notes! IF VMOp = 'Direct' THEN DELETE FROM <API key> WHERE ReadingID IN (SELECT readingID FROM tblVMeasurement INNER JOIN tblMeasurement USING (measurementID) INNER JOIN tblReading USING (measurementID) INNER JOIN <API key> USING (readingID) WHERE VMeasurementID=_VMID); ELSE DELETE FROM <API key> WHERE VMeasurementID=_VMID; END IF; GET DIAGNOSTICS ret = ROW_COUNT; RETURN ret; END; $_$ LANGUAGE PLPGSQL VOLATILE; -- Add a reading note to this vmeasurement CREATE OR REPLACE FUNCTION cpgdb.AddReadingNote( tblVMeasurement.VMeasurementID%TYPE, -- the vmeasurement to tie this to int, -- The year to bind this note to (relative, starts at zero) int, -- The reading note ID to add boolean) -- Is this a force disabled override (only for non-direct, MUST BE NULL for direct) RETURNS void AS $_$ DECLARE _VMID ALIAS FOR $1; _RelYear ALIAS FOR $2; _ReadingNoteID ALIAS FOR $3; _Override ALIAS FOR $4; VMOp text; myReadingID tblReading.ReadingID%TYPE; myOverride boolean; VMReadingCount int; BEGIN -- Get the VMeasurementOp SELECT op.name INTO VMOp FROM tblVMeasurement INNER JOIN tlkpVMeasurementOp op USING (vmeasurementOpID) WHERE vmeasurementID=_VMID; IF NOT FOUND THEN RAISE EXCEPTION 'Invalid/nonexistent vmeasurement %', _VMID; END IF; -- Direct VM -> Attach to Reading IF VMOp = 'Direct' THEN IF _Override IS NOT NULL THEN RAISE EXCEPTION 'Override must not be set for Direct VMs'; END IF; SELECT readingID INTO myReadingID FROM tblVMeasurement INNER JOIN tblMeasurement USING (measurementID) INNER JOIN tblReading USING (measurementID) WHERE VMeasurementID=_VMID AND RelYear=_RelYear; IF NOT FOUND THEN RAISE EXCEPTION 'No reading found for relyear % on vmeasurementid %. Year must exist.', _RelYear, _VMID; END IF; INSERT INTO <API key> (ReadingID, ReadingNoteID) VALUES (myReadingID, _ReadingNoteID); ELSE -- Derived VM -> Attach to vmeasurement myOverride := _Override; -- null override means false IF myOverride IS NULL THEN myOverride := FALSE; END IF; -- Validate relyear SELECT readingCount INTO VMReadingCount FROM <API key> WHERE VMeasurementID=_VMID; IF NOT FOUND OR VMReadingCount <= _RelYear THEN RAISE EXCEPTION 'VMeasurement % does not exist, is malformed, or relyear % is out of range.', _VMID, _RelYear; END IF; INSERT INTO <API key> (VMeasurementID, RelYear, ReadingNoteID, DisabledOverride) VALUES (_VMID, _RelYear, _ReadingNoteID, myOverride); END IF; END; $_$ LANGUAGE PLPGSQL VOLATILE; -- Add a CUSTOM reading note to this vmeasurement -- Tries to find an existing match first CREATE OR REPLACE FUNCTION cpgdb.<API key>( tblVMeasurement.VMeasurementID%TYPE, -- the vmeasurement to tie this to int, -- The year to bind this note to (relative, starts at zero) text) -- The custom reading note to add RETURNS tlkpReadingNote AS $_$ DECLARE _VMID ALIAS FOR $1; _RelYear ALIAS FOR $2; _NoteText ALIAS FOR $3; VMOp text; myReadingID tblReading.ReadingID%TYPE; myOverride boolean; VMReadingCount int; myReadingNoteID tlkpReadingNote.ReadingNoteID%TYPE; myVMRYRN <API key>.<API key>%TYPE; outrow tlkpReadingNote%ROWTYPE; BEGIN -- Look for existing vocabulary case insensitively SELECT ReadingNoteID INTO myReadingNoteID FROM tlkpReadingNote WHERE note ILIKE _NoteText; IF FOUND THEN PERFORM cpgdb.AddReadingNote(_VMID, _RelYear, myReadingNoteID, null); SELECT * INTO outrow FROM tlkpReadingNote WHERE ReadingNoteID=myReadingNoteID; RETURN outrow; END IF; -- Get the VMeasurementOp SELECT op.name INTO VMOp FROM tblVMeasurement INNER JOIN tlkpVMeasurementOp op USING (vmeasurementOpID) WHERE vmeasurementID=_VMID; IF NOT FOUND THEN RAISE EXCEPTION 'Invalid/nonexistent vmeasurement %', _VMID; END IF; -- Create a new reading note myReadingNoteID := nextval('<API key>'::regclass); -- Direct VM -> Attach to Reading IF VMOp = 'Direct' THEN IF _Override IS NOT NULL THEN RAISE EXCEPTION 'Override must not be set for Direct VMs'; END IF; SELECT readingID INTO myReadingID FROM tblVMeasurement INNER JOIN tblMeasurement USING (measurementID) INNER JOIN tblReading USING (measurementID) WHERE VMeasurementID=_VMID AND RelYear=_RelYear; IF NOT FOUND THEN RAISE EXCEPTION 'No reading found for relyear % on vmeasurementid %. Year must exist.', _RelYear, _VMID; END IF; INSERT INTO tlkpReadingNote(ReadingNoteID, note, vocabularyid, parentReadingID) VALUES (myReadingNoteID, _NoteText, 0, myReadingID); INSERT INTO <API key> (<API key>, ReadingID, ReadingNoteID) VALUES (myRRNID, myReadingID, _ReadingNoteID); ELSE -- Validate relyear SELECT readingCount INTO VMReadingCount FROM <API key> WHERE VMeasurementID=_VMID; IF NOT FOUND OR VMReadingCount <= _RelYear THEN RAISE EXCEPTION 'VMeasurement % does not exist, is malformed, or relyear % is out of range.', _VMID, _RelYear; END IF; -- Complicated circular reference here :< -- First, insert the new readingNote INSERT INTO tlkpReadingNote(ReadingNoteID, note, vocabularyid) VALUES (myReadingNoteID, _NoteText, 0); -- Now, insert a new <API key> row myVMRYRN := nextval('<API key>'::regclass); INSERT INTO <API key> (<API key>, VMeasurementID, RelYear, ReadingNoteID) VALUES (myVMRYRN, _VMID, _RelYear, myReadingNoteID); -- Now, tie the readingNote directly to the new row UPDATE tlkpReadingNote SET <API key>=myVMRYRN WHERE ReadingNoteID=myReadingNoteID; END IF; SELECT * INTO outrow FROM tlkpReadingNote WHERE ReadingNoteID=myReadingNoteID; RETURN outrow; END; $_$ LANGUAGE PLPGSQL VOLATILE; -- Remove a reading note from this vmeasurement CREATE OR REPLACE FUNCTION cpgdb.RemoveReadingNote( tblVMeasurement.VMeasurementID%TYPE, -- the vmeasurement to tie this to int, -- The year to bind this note to (relative, starts at zero) int) -- The reading note ID to add RETURNS integer AS $_$ DECLARE _VMID ALIAS FOR $1; _RelYear ALIAS FOR $2; _ReadingNoteID ALIAS FOR $3; VMOp text; myReadingID tblReading.ReadingID%TYPE; ret integer; BEGIN -- Get the VMeasurementOp SELECT op.name INTO VMOp FROM tblVMeasurement INNER JOIN tlkpVMeasurementOp op USING (vmeasurementOpID) WHERE vmeasurementID=_VMID; IF NOT FOUND THEN RAISE EXCEPTION 'Invalid/nonexistent vmeasurement %', _VMID; END IF; -- Direct VM -> Remove from Reading IF VMOp = 'Direct' THEN SELECT readingID INTO myReadingID FROM tblVMeasurement INNER JOIN tblMeasurement USING (measurementID) INNER JOIN tblReading USING (measurementID) WHERE VMeasurementID=_VMID AND RelYear=_RelYear; IF NOT FOUND THEN RAISE EXCEPTION 'No reading found for relyear % on vmeasurementid %. Year must exist.', _RelYear, _VMID; END IF; DELETE FROM <API key> WHERE ReadingID=myReadingID AND ReadingNoteID=_ReadingNoteID; ELSE -- Remove from RelYearReadingNote DELETE FROM <API key> WHERE VMeasurementID=_VMID AND RelYear=_RelYear AND ReadingNoteID=_ReadingNoteID; END IF; GET DIAGNOSTICS ret = ROW_COUNT; RETURN ret; END; $_$ LANGUAGE PLPGSQL VOLATILE; -- Param 1: Vocabulary name -- Param 2: Note text CREATE OR REPLACE FUNCTION cpgdb.GetNote(text, text) RETURNS tlkpReadingNote AS $_$ DECLARE noterec tlkpReadingNote; BEGIN SELECT rnote.* INTO noterec FROM tlkpReadingNote rnote LEFT JOIN tlkpVocabulary voc USING (vocabularyid) WHERE voc.name=$1 AND rnote.note=$2; IF NOT FOUND THEN RAISE EXCEPTION 'Note "%" not found for vocabulary "%"', $2, $1; END IF; RETURN noterec; END; $_$ LANGUAGE PLPGSQL STABLE;
""" Page view class """ import os from Server.Importer import ImportFromModule class PageView(ImportFromModule("Server.PageViewBase", "PageViewBase")): """ Page view class. """ _PAGE_TITLE = "Python Web Framework" def __init__(self, htmlToLoad): """ Constructor. - htmlToLoad : HTML to load """ self.SetPageTitle(self._PAGE_TITLE) self.AddMetaData("charset=\"UTF-8\"") self.AddMetaData("name=\"viewport\" content=\"width=device-width, initial-scale=1\"") self.AddStyleSheet("/css/styles.css") self.AddJavaScript("/js/http.js") self.LoadHtml(os.path.join(os.path.dirname(__file__), "%s.html" % htmlToLoad)) self.SetPageData({ "PageTitle" : self._PAGE_TITLE })
package uapi.service; import uapi.<API key>; import uapi.helper.ArgumentChecker; import java.util.HashMap; import java.util.Map; /** * Define response code */ public abstract class ResponseCode { private final Map<String, String> _codeMsgKeyMapping = new HashMap<>(); private final MessageExtractor _msgExtractor = new MessageExtractor(this.getClass().getClassLoader()); public void init() { getMessageLoader().registerExtractor(this._msgExtractor); } protected abstract MessageLoader getMessageLoader(); public String getMessageKey(final String code) { ArgumentChecker.required(code, "code"); return this._codeMsgKeyMapping.get("code"); } protected void <API key>(String code, String messageKey) { ArgumentChecker.required(code, "code"); ArgumentChecker.required(messageKey, "messageKey"); if (this._codeMsgKeyMapping.containsKey(code)) { throw new <API key>("Overwrite existing code message key is not allowed - {}", code); } this._codeMsgKeyMapping.put(code, messageKey); this._msgExtractor.addDefinedKeys(messageKey); } }
<?php namespace SHC\Event; //Imports use RWF\Date\DateTime; use RWF\Util\StringUtils; use SHC\Condition\Condition; use SHC\Condition\ConditionEditor; use SHC\Core\SHC; use SHC\Switchable\Switchable; use SHC\Switchable\SwitchableEditor; class EventEditor { /** * Ereignis Luftfeuchte steigt * * @var Integer */ const <API key> = 1; /** * Ereignis Luftfeuchte faellt * * @var Integer */ const <API key> = 2; /** * Ereignis Eingang wechselt von LOW auf HIGH * * @var Integer */ const EVENT_INPUT_HIGH = 4; /** * Ereignis EIngang wechselt von HIGH auf LOW * * @var Integer */ const EVENT_INPUT_LOW = 8; /** * Ereignis Lichtstaerke steigt * * @var Integer */ const <API key> = 16; /** * Ereignis Lichtsaerke faellt * * @var Integer */ const <API key> = 32; /** * Ereignis Feuchtigkeit steigt * * @var Integer */ const <API key> = 64; /** * Ereignis Feuchtigkeit steigt * * @var Integer */ const <API key> = 128; /** * Ereignis Temperatur steigt * * @var Integer */ const <API key> = 256; /** * Ereignis Temperatur faellt * * @var Integer */ const <API key> = 512; /** * Ereignis Benutzer kommt nach Hause * * @var Integer */ const <API key> = 1024; /** * Ereignis Benutzer verlaesst das Haus * * @var Integer */ const <API key> = 2048; /** * Ereignis Sonnenaufgang * * @var Integer */ const EVENT_SUNRISE = 4096; /** * Ereignis Sonnenuntergang * * @var Integer */ const EVENT_SUNSET = 8192; /** * Ereignis Datei erstellt * * @var Integer */ const EVENT_FILE_CREATE = 16384; /** * Ereignis Datei geloescht * * @var Integer */ const EVENT_FILE_DELETE = 32768; /** * nach ID sortieren * * @var String */ const SORT_BY_ID = 'id'; /** * nach Namen sortieren * * @var String */ const SORT_BY_NAME = 'name'; /** * nicht sortieren * * @var String */ const SORT_NOTHING = 'unsorted'; /** * Ereignisse * * @var Array */ protected $events = array(); /** * Singleton Instanz * * @var \SHC\Event\EventEditor */ protected static $instance = null; /** * name der HashMap * * @var String */ protected static $tableName = 'shc:events'; protected function __construct() { $this->loadData(); } /** * laedt die Ereignisse aus den XML Daten und erzeugt die Objekte */ public function loadData() { //Daten Vorbereiten $oldEvents = $this->events; $this->events = array(); $events = SHC::getDatabase()->hGetAllArray(self::$tableName); //Daten einlesen foreach ($events as $event) { //Variablen Vorbereiten $class = (string) $event['class']; $data = array(); foreach ($event as $index => $value) { if (!in_array($index, array('id', 'name', 'class', 'enabled', 'conditions', 'lastExecute', 'switchable'))) { $data[$index] = $value; } } /* @var $eventObj \SHC\Event\Event */ $eventObj = new $class( (int) $event['id'], (string) $event['name'], $data, ((int) $event['enabled'] == true ? true : false), DateTime::<API key>((string) $event['lastExecute']) ); //Bedingungen anhaengen foreach ($event['conditions'] as $conditionId) { $condition = ConditionEditor::getInstance()->getConditionByID($conditionId); if ($condition instanceof Condition) { $eventObj->addCondition($condition); } } //schaltbare Elemente Hinzufuegen if(isset($event['switchable'])) { foreach ($event['switchable'] as $switchable) { $switchableObject = SwitchableEditor::getInstance()->getElementById((int) $switchable['id']); if ($switchableObject instanceof Switchable) { $eventObj->addSwitchable($switchableObject, (int) $switchable['command']); } } } if(isset($oldEvents[(int) $event['id']])) { /* @var $eventObj \SHC\Event\Event */ $eventObj->setState($oldEvents[(int) $event['id']]->getState()); if($oldEvents[(int) $event['id']]->getTime() instanceof DateTime) { $eventObj->setTime($oldEvents[(int) $event['id']]->getTime()); } } $this->events[(int) $event['id']] = $eventObj; } } /** * gibt das Ereignis mit der IOD zurueck * * @param int $id Ereignis ID * @return \SHC\Event\Event */ public function getEventById($id) { if (isset($this->events[$id])) { return $this->events[$id]; } return null; } /** * prueft ob der Name des Events schon verwendet wird * * @param String $name Name * @return Boolean */ public function <API key>($name) { foreach ($this->events as $event) { /* @var $condition \SHC\Event\Event */ if (StringUtils::toLower($event->getName()) == StringUtils::toLower($name)) { return false; } } return true; } /** * gibt eine Liste mit allen Bedingungen zurueck * * @param String $orderBy Art der Sortierung ( * id => nach ID sorieren, * name => nach Namen sortieren, * unsorted => unsortiert * ) * @return Array */ public function listEvents($orderBy = 'id') { if ($orderBy == 'id') { //nach ID sortieren $events = $this->events; ksort($events, SORT_NUMERIC); return $events; } elseif ($orderBy == 'name') { //nach Namen sortieren $events = $this->events; //Sortierfunktion $orderFunction = function($a, $b) { if ($a->getName() == $b->getName()) { return 0; } if ($a->getName() < $b->getName()) { return -1; } return 1; }; usort($events, $orderFunction); return $events; } return $this->events; } /** * erstellt ein Event * * @param String $class Klassenname * @param String $name Name * @param Boolean $enabled Aktiv * @param Array $data Zusatzdaten * @param Array $conditions Liste der Bedingunen * @return Boolean * @throws \Exception */ protected function addEvent($class, $name, array $data = array(), $enabled = true, array $conditions) { //Ausnahme wenn Name des Events schon belegt if (!$this-><API key>($name)) { throw new \Exception('Der Name des Events ist schon vergeben', 1502); } $db = SHC::getDatabase(); $index = $db->autoIncrement(self::$tableName); $newEvent = array( 'id' => $index, 'class' => $class, 'name' => $name, 'enabled' => ($enabled == true ? true : false), 'conditions' => $conditions, 'lastExecute' => '2000-01-01 00:00:00', 'switchable' => array() ); foreach ($data as $tag => $value) { if (!in_array($tag, array('id', 'name', 'class', 'enabled', 'conditions', 'lastExecute', 'switchable'))) { $newEvent[$tag] = $value; } } if($db->hSetNxArray(self::$tableName, $index, $newEvent) == 0) { return false; } return true; } /** * bearbeitet ein Event * * @param Integer $id ID * @param String $name Name * @param Array $data Zusatzdaten * @param Boolean $enabled Aktiv * @param Array $conditions Liste der Bedingunen * @return Boolean * @throws \Exception */ protected function editEvent($id, $name = null, array $data = null, $enabled = null, array $conditions = null) { $db = SHC::getDatabase(); //pruefen ob Datensatz existiert if($db->hExists(self::$tableName, $id)) { $event = $db->hGetArray(self::$tableName, $id); //Name if ($name !== null) { //Ausnahme wenn Name der Bedingung schon belegt if ((string) $event['name'] != $name && !$this-><API key>($name)) { throw new \Exception('Der Name der Bedingung ist schon vergeben', 1502); } $event['name'] = $name; } //Aktiv if ($enabled !== null) { $event['enabled'] = ($enabled == true ? 1 : 0); } //Bedingungen if($conditions !== null) { $event['conditions'] = implode(',', $conditions); } //Zusatzdaten foreach($data as $tag => $value) { if (!in_array($tag, array('id', 'name', 'class', 'enabled', 'conditions', 'lastExecute', 'switchable'))) { if($value !== null) { $event[$tag] = $value; } } } if($db->hSetArray(self::$tableName, $id, $event) == 0) { return true; } } return false; } /** * Speichert den Zeitpunkt der letzten Ausfuehrung fuer ein Ereignis * * @param Integer $id Ereignis ID * @param \RWF\Date\DateTime $lastExecute letzte Ausfuehrung * @return Boolean */ public function updateLastExecute($id, DateTime $lastExecute) { $db = SHC::getDatabase(); //pruefen ob Datensatz existiert if($db->hExists(self::$tableName, $id)) { $event = $db->hGetArray(self::$tableName, $id); if(isset($event['id']) && $event['id'] == $id) { $event['lastExecute'] = $lastExecute->getDatabaseDateTime(); if($db->hSetArray(self::$tableName, $id, $event) == 0) { return true; } } else { //Datensatz nicht mehr vorhanden return false; } } return false; } /** * erstellt ein Luftfeuchte Event * * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert (Prozent) * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function <API key>($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->addEvent('\SHC\Event\Events\HumidityClimbOver', $name, $data, $enabled, $conditions); } /** * bearbeitet ein Luftfeuchte Event * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert (Prozent) * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function <API key>($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->editEvent($id, $name, $data, $enabled, $conditions); } /** * erstellt ein Luftfeuchte Event * * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert (Prozent) * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function <API key>($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->addEvent('\SHC\Event\Events\HumidityFallsBelow', $name, $data, $enabled, $conditions); } /** * bearbeitet ein Luftfeuchte Event * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert (Prozent) * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function <API key>($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->editEvent($id, $name, $data, $enabled, $conditions); } /** * erstellt ein Lichtstaerke Event * * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert (Prozent) * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function <API key>($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->addEvent('\SHC\Event\Events\<API key>', $name, $data, $enabled, $conditions); } /** * bearbeitet ein Lichtstaerke Event * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert (Prozent) * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function <API key>($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->editEvent($id, $name, $data, $enabled, $conditions); } /** * erstellt ein Lichtstaerke Event * * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert (Prozent) * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function <API key>($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->addEvent('\SHC\Event\Events\<API key>', $name, $data, $enabled, $conditions); } /** * bearbeitet ein Lichtstaerke Event * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert (Prozent) * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function <API key>($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->editEvent($id, $name, $data, $enabled, $conditions); } /** * erstellt ein Feuchtigkeits Event * * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert (Prozent) * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function <API key>($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->addEvent('\SHC\Event\Events\MoistureClimbOver', $name, $data, $enabled, $conditions); } /** * bearbeitet ein Feuchtigkeits Event * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert (Prozent) * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function <API key>($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->editEvent($id, $name, $data, $enabled, $conditions); } /** * erstellt ein Feuchtigkeits Event * * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert (Prozent) * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function <API key>($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->addEvent('\SHC\Event\Events\MoistureFallsBelow', $name, $data, $enabled, $conditions); } /** * bearbeitet ein Feuchtigkeits Event * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert (Prozent) * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function <API key>($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->editEvent($id, $name, $data, $enabled, $conditions); } /** * erstellt ein Temperatur Event * * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function <API key>($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->addEvent('\SHC\Event\Events\<API key>', $name, $data, $enabled, $conditions); } /** * bearbeitet ein Temperatur Event * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function <API key>($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->editEvent($id, $name, $data, $enabled, $conditions); } /** * erstellt ein Temperatur Event * * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function <API key>($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->addEvent('\SHC\Event\Events\<API key>', $name, $data, $enabled, $conditions); } /** * bearbeitet ein Temperatur Event * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function <API key>($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->editEvent($id, $name, $data, $enabled, $conditions); } /** * erstellt ein Eingangsevent * * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $inputs Eingaenge * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function addInputHighEvent($name, $enabled, array $inputs, $interval, array $conditions = array()) { //Daten vorbereiten $data = array( 'inputs' => implode(',', $inputs), 'interval' => $interval ); //Speichern return $this->addEvent('\SHC\Event\Events\InputHigh', $name, $data, $enabled, $conditions); } /** * bearbeitet ein Eingangsevent * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $inputs Eingaenge * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function editInputHighEvent($id, $name = null, $enabled = null, array $inputs = null, $interval = null, array $conditions = null) { //Daten vorbereiten $data = array( 'inputs' => implode(',', $inputs), 'interval' => $interval ); //Speichern return $this->editEvent($id, $name, $data, $enabled, $conditions); } /** * erstellt ein Eingangsevent * * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $inputs Eingaenge * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function addInputLowEvent($name, $enabled, array $inputs, $interval, array $conditions = array()) { //Daten vorbereiten $data = array( 'inputs' => implode(',', $inputs), 'interval' => $interval ); //Speichern return $this->addEvent('\SHC\Event\Events\InputLow', $name, $data, $enabled, $conditions); } /** * bearbeitet ein Eingangsevent * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $inputs Eingaenge * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function editInputLowEvent($id, $name = null, $enabled = null, array $inputs = null, $interval = null, array $conditions = null) { //Daten vorbereiten $data = array( 'inputs' => implode(',', $inputs), 'interval' => $interval ); //Speichern return $this->editEvent($id, $name, $data, $enabled, $conditions); } /** * erstellt ein Benutzerevent * * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $users benutzer zu Hause * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function <API key>($name, $enabled, array $users, $interval, array $conditions = array()) { //Daten vorbereiten $data = array( 'users' => implode(',', $users), 'interval' => $interval ); //Speichern return $this->addEvent('\SHC\Event\Events\UserComesHome', $name, $data, $enabled, $conditions); } /** * bearbeitet ein Benutzerevent * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $users benutzer zu Hause * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function <API key>($id, $name = null, $enabled = null, array $users = null, $interval = null, array $conditions = null) { //Daten vorbereiten $data = array( 'users' => implode(',', $users), 'interval' => $interval ); //Speichern return $this->editEvent($id, $name, $data, $enabled, $conditions); } /** * erstellt ein Benutzerevent * * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $users benutzer zu Hause * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function <API key>($name, $enabled, array $users, $interval, array $conditions = array()) { //Daten vorbereiten $data = array( 'users' => implode(',', $users), 'interval' => $interval ); //Speichern return $this->addEvent('\SHC\Event\Events\UserLeavesHome', $name, $data, $enabled, $conditions); } /** * bearbeitet ein Benutzerevent * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $users benutzer zu Hause * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function <API key>($id, $name = null, $enabled = null, array $users = null, $interval = null, array $conditions = null) { //Daten vorbereiten $data = array( 'users' => implode(',', $users), 'interval' => $interval ); //Speichern return $this->editEvent($id, $name, $data, $enabled, $conditions); } /** * erstellt ein neuen Event Sonnenaufgang * * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $conditions Liste der Bedingunen */ public function addSunriseEvent($name, $enabled, array $conditions = null) { //Speichern return $this->addEvent('\SHC\Event\Events\Sunrise', $name, array(), $enabled, $conditions); } /** * bearbeitet ein Event Sonnenaufgang * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $conditions Liste der Bedingunen */ public function editSunriseEvent($id, $name = null, $enabled = null, array $conditions = null) { //Speichern return $this->editEvent($id, $name, array(), $enabled, $conditions); } /** * erstellt ein neuen Event Sonnenuntergang * * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $conditions Liste der Bedingunen */ public function addSunsetEvent($name, $enabled, array $conditions = null) { //Speichern return $this->addEvent('\SHC\Event\Events\Sunset', $name, array(), $enabled, $conditions); } /** * bearbeitet ein Event Sonnenuntergang * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $conditions Liste der Bedingunen */ public function editSunsetEvent($id, $name = null, $enabled = null, array $conditions = null) { //Speichern return $this->editEvent($id, $name, array(), $enabled, $conditions); } /** * erstellt ein Datei erstellt Event * * @param String $name Name * @param Boolean $enabled Aktiviert * @param String $file Datei * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function addFileCreateEvent($name, $enabled, $file, $interval, array $conditions = array()) { //Daten vorbereiten $data = array( 'file' => $file, 'interval' => $interval ); //Speichern return $this->addEvent('\SHC\Event\Events\FileCreate', $name, $data, $enabled, $conditions); } /** * bearbeitet ein Datei erstellt Event * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param String $file Datei * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function editFileCreateEvent($id, $name = null, $enabled = null, $file = null, $interval = null, array $conditions = null) { //Daten vorbereiten $data = array( 'file' => $file, 'interval' => $interval ); //Speichern return $this->editEvent($id, $name, $data, $enabled, $conditions); } /** * erstellt ein Datei geloescht Event * * @param String $name Name * @param Boolean $enabled Aktiviert * @param String $file Datei * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function addFileDeleteEvent($name, $enabled, $file, $interval, array $conditions = array()) { //Daten vorbereiten $data = array( 'file' => $file, 'interval' => $interval ); //Speichern return $this->addEvent('\SHC\Event\Events\FileDelete', $name, $data, $enabled, $conditions); } /** * bearbeitet ein Datei geloescht Event * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param String $file Datei * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function editFileDeleteEvent($id, $name = null, $enabled = null, $file = null, $interval = null, array $conditions = null) { //Daten vorbereiten $data = array( 'file' => $file, 'interval' => $interval ); //Speichern return $this->editEvent($id, $name, $data, $enabled, $conditions); } /** * loascht ein Event * * @param Integer $id ID * @return Boolean */ public function removeEvent($id) { $db = SHC::getDatabase(); //pruefen ob Datensatz existiert if($db->hExists(self::$tableName, $id)) { if($db->hDel(self::$tableName, $id)) { return true; } } return false; } /** * fuegt einem Event eine Bedingung hinzu * * @param Integer $eventId ID des Events * @param Integer $conditionId ID der Bedingung * @return Boolean */ public function addConditionToEvent($eventId, $conditionId) { $db = SHC::getDatabase(); //pruefen ob Datensatz existiert if($db->hExists(self::$tableName, $eventId)) { $event = $db->hGetArray(self::$tableName, $eventId); $event['conditions'][] = $conditionId; if($db->hSetArray(self::$tableName, $eventId, $event) == 0) { return true; } } return false; } /** * entfernt eine Bedingung aus einem Event * * @param Integer $eventId ID des Events * @param Integer $conditionId ID der Bedingung * @return Boolean */ public function <API key>($eventId, $conditionId) { $db = SHC::getDatabase(); //pruefen ob Datensatz existiert if($db->hExists(self::$tableName, $eventId)) { $event = $db->hGetArray(self::$tableName, $eventId); $event['conditions'] = array_diff($event['conditions'], array($conditionId)); if($db->hSetArray(self::$tableName, $eventId, $event) == 0) { return true; } } return false; } /** * fuegt einem Event ein Schaltbares Element hinzu * * @param Integer $eventId ID des Events * @param Integer $switchableId ID des Schaltbaren Elements * @param Integer $command Befehl * @return Boolean */ public function <API key>($eventId, $switchableId, $command) { $db = SHC::getDatabase(); //pruefen ob Datensatz existiert if($db->hExists(self::$tableName, $eventId)) { $event = $db->hGetArray(self::$tableName, $eventId); $event['switchable'][] = array('id' => $switchableId, 'command' => $command); if($db->hSetArray(self::$tableName, $eventId, $event) == 0) { return true; } } return false; } /** * setzt den Befehl eines Schaltbaren Elements in einem Event * * @param Integer $eventId ID des Events * @param Integer $switchableId ID des Schaltbaren Elements * @param Integer $command Befehl * @return Boolean */ public function <API key>($eventId, $switchableId, $command) { $db = SHC::getDatabase(); //pruefen ob Datensatz existiert if($db->hExists(self::$tableName, $eventId)) { $event = $db->hGetArray(self::$tableName, $eventId); foreach($event['switchable'] as $index => $switchable) { if($switchable['id'] == $switchableId) { $event['switchable'][$index]['command'] = $command; break; } } if($db->hSetArray(self::$tableName, $eventId, $event) == 0) { return true; } } return false; } /** * entfernt ein Schaltbares Element von einem Event * * @param Integer $eventId ID des Events * @param Integer $switchableId ID des Schaltbaren Elements * @return Boolean */ public function <API key>($eventId, $switchableId) { $db = SHC::getDatabase(); //pruefen ob Datensatz existiert if($db->hExists(self::$tableName, $eventId)) { $event = $db->hGetArray(self::$tableName, $eventId); foreach($event['switchable'] as $index => $switchable) { if($switchable['id'] == $switchableId) { unset($event['switchable'][$index]); break; } } if($db->hSetArray(self::$tableName, $eventId, $event) == 0) { return true; } } return false; } /** * geschuetzt wegen Singleton */ private function __clone() { } /** * gibt den Ereignis Editor Editor zurueck * * @return \SHC\Event\EventEditor */ public static function getInstance() { if (self::$instance === null) { self::$instance = new EventEditor(); } return self::$instance; } }
#include <iostream> using namespace std; #define FLOAT(name, value) float name = value #define CONST_FLOAT(name, value) const FLOAT(name, value) #define VAR_FLOAT(name) FLOAT(name, 0) #define VAR_INT(name) int name = 0 #define <API key>(n)\ VAR_FLOAT(a VAR_FLOAT(b VAR_FLOAT(c #define READ(input) cin >> input #define <API key>(diff) ((diff < EPSILON) && (diff > -EPSILON)) #define <API key>(n)\ READ(a READ(b READ(c #define IS_ZERO(value) <API key>(value) #define IS_NOT_ZERO(value) (!<API key>(value)) #define IS_NOT_ZERO_LINE(line) (IS_NOT_ZERO(a##line) || IS_NOT_ZERO(b##line) || IS_NOT_ZERO(c##line)) #define SOLUTION_PART_1(n, divisor) c##n / divisor##n #define SOLUTION_PART_2(n, multiplier, found, divisor) (c##n - (multiplier##n * found)) / divisor##n #define ONE_SOLUTION() solution = One #define NO_SOLUTION() solution = No #define GAUSE(n1, n2, n3, cnt , calc)\ CONST_FLOAT(k##n1, (-cnt##n2) / cnt##n1);\ CONST_FLOAT(calc##n3, (calc##n1 * k##n1) + calc##n2);\ CONST_FLOAT(c##n3, (c##n1 * k##n1) + c##n2)\ #define <API key>(zero, first, second, divisor1, divisor2, n1, n2)\ if(IS_ZERO(zero) && (solution == Many)) {\ if IS_ZERO(divisor1 NO_SOLUTION();\ } else {\ first = SOLUTION_PART_1(n1, divisor1);\ second = SOLUTION_PART_2(n2, divisor1, first, divisor2);\ ONE_SOLUTION();\ }\ }\ #define FIND_SOLUTION(n, first, second, k, divisor1, divisor2)\ CONST_FLOAT(first##n, SOLUTION_PART_1(k, divisor1));\ CONST_FLOAT(second##n, SOLUTION_PART_2(n, divisor1, first##n, divisor2))\ #define DIFF(F, f) CONST_FLOAT(DIFF_##F, f##1 - f##2) #define PRINT(value) cout << value #define PRINT_CASE(what, message)\ case what:\ PRINT(message);\ break\ #define <API key>(a, b, m)\ if((absWholePart >= a) && (absWholePart < b)) {\ multiplier = m;\ }\ #define FORMAT(num)\ sign = (num <= -EPSILON ? -1 : 1);\ wholePart = num + (sign * EPSILON);\ multiplier = 1;\ absWholePart = sign * wholePart;\ <API key>(0, 10, 10000)\ <API key>(10, 100, 1000)\ <API key>(100, 1000, 100)\ <API key>(1000, 10000, 10)\ floatPart = (int)((num + (sign * EPSILON)) * multiplier) - (wholePart * multiplier);\ num = ((float)floatPart / multiplier) + wholePart\ /* @begin */ enum Solution { No, One, Many }; CONST_FLOAT(EPSILON, 0.00001); int main() { <API key>(1); <API key>(2); VAR_FLOAT(x); VAR_FLOAT(y); Solution solution = Many; <API key>(1); <API key>(2); if(IS_NOT_ZERO_LINE(1) && IS_NOT_ZERO_LINE(2)) { <API key>(a1, y, x, b, a, 1, 2) <API key>(a2, y, x, b, a, 2, 1) <API key>(b1, x, y, a, b, 1, 2) <API key>(b2, x, y, a, b, 2, 1) if(solution == Many) { GAUSE(1, 2, 3, a, b); GAUSE(2, 1, 4, b, a); if((IS_ZERO(b3) && IS_NOT_ZERO(c3)) || (IS_ZERO(a4) && IS_NOT_ZERO(c4))) { NO_SOLUTION(); } else { FIND_SOLUTION(1, y, x, 3, b, a); FIND_SOLUTION(2, x, y, 4, a, b); DIFF(X, x); DIFF(Y, y); if(<API key>(DIFF_X) && <API key>(DIFF_Y)) { x = x1; y = y1; ONE_SOLUTION(); } } } } switch(solution) { PRINT_CASE(No, "No solution"); PRINT_CASE(Many, "Many solutions"); case One: VAR_INT(sign); VAR_INT(wholePart); VAR_INT(absWholePart); VAR_INT(floatPart); VAR_INT(multiplier); FORMAT(x); FORMAT(y); PRINT(x) << ' ' << y; break; } PRINT('\n'); return 0; }
package org.smssecure.smssecure.recipients; import android.content.Context; import android.support.annotation.NonNull; import android.text.TextUtils; import org.smssecure.smssecure.contacts.avatars.ContactPhotoFactory; import org.smssecure.smssecure.database.<API key>; import org.smssecure.smssecure.util.Util; import org.whispersystems.libaxolotl.util.guava.Optional; import java.util.LinkedList; import java.util.List; import java.util.StringTokenizer; public class RecipientFactory { private static final RecipientProvider provider = new RecipientProvider(); public static Recipients getRecipientsForIds(Context context, String recipientIds, boolean asynchronous) { if (TextUtils.isEmpty(recipientIds)) return new Recipients(); return getRecipientsForIds(context, Util.split(recipientIds, " "), asynchronous); } public static Recipients getRecipientsFor(Context context, List<Recipient> recipients, boolean asynchronous) { long[] ids = new long[recipients.size()]; int i = 0; for (Recipient recipient : recipients) { ids[i++] = recipient.getRecipientId(); } return provider.getRecipients(context, ids, asynchronous); } public static Recipients getRecipientsFor(Context context, Recipient recipient, boolean asynchronous) { long[] ids = new long[1]; ids[0] = recipient.getRecipientId(); return provider.getRecipients(context, ids, asynchronous); } public static Recipient getRecipientForId(Context context, long recipientId, boolean asynchronous) { return provider.getRecipient(context, recipientId, asynchronous); } public static Recipients getRecipientsForIds(Context context, long[] recipientIds, boolean asynchronous) { return provider.getRecipients(context, recipientIds, asynchronous); } public static Recipients <API key>(Context context, @NonNull String rawText, boolean asynchronous) { StringTokenizer tokenizer = new StringTokenizer(rawText, ","); List<String> ids = new LinkedList<>(); while (tokenizer.hasMoreTokens()) { Optional<Long> id = <API key>(context, tokenizer.nextToken()); if (id.isPresent()) { ids.add(String.valueOf(id.get())); } } return getRecipientsForIds(context, ids, asynchronous); } private static Recipients getRecipientsForIds(Context context, List<String> idStrings, boolean asynchronous) { long[] ids = new long[idStrings.size()]; int i = 0; for (String id : idStrings) { ids[i++] = Long.parseLong(id); } return provider.getRecipients(context, ids, asynchronous); } private static Optional<Long> <API key>(Context context, String number) { number = number.trim(); if (number.isEmpty()) return Optional.absent(); if (hasBracketedNumber(number)) { number = <API key>(number); } return Optional.of(<API key>.getInstance(context).<API key>(number)); } private static boolean hasBracketedNumber(String recipient) { int openBracketIndex = recipient.indexOf('<'); return (openBracketIndex != -1) && (recipient.indexOf('>', openBracketIndex) != -1); } private static String <API key>(String recipient) { int begin = recipient.indexOf('<'); int end = recipient.indexOf('>', begin); String value = recipient.substring(begin + 1, end); return value; } public static void clearCache() { provider.clearCache(); } }
package ai.grakn.generator; import ai.grakn.concept.Label; import ai.grakn.graql.admin.RelationPlayer; import ai.grakn.graql.admin.VarPatternAdmin; import static ai.grakn.graql.Graql.var; /** * @author Felix Chapman */ public class RelationPlayers extends AbstractGenerator<RelationPlayer> { public RelationPlayers() { super(RelationPlayer.class); } @Override public RelationPlayer generate() { if (random.nextBoolean()) { return RelationPlayer.of(gen(VarPatternAdmin.class)); } else { VarPatternAdmin varPattern; if (random.nextBoolean()) { varPattern = var().label(gen(Label.class)).admin(); } else { varPattern = gen(VarPatternAdmin.class); } return RelationPlayer.of(varPattern, gen(VarPatternAdmin.class)); } } }
package org.janus.miniforth; import org.janus.data.DataContext; public class Compare extends WordImpl { public enum Comp { EQ, NEQ, LT, GT, LEQ, GEQ } Comp comp; public Compare(Comp comp) { super(-1); this.comp = comp; } @Override public void perform(DataContext context) { super.perform(context); MiniForthContext withStack = (MiniForthContext) context; Comparable a = (Comparable) withStack.pop(); Comparable b = (Comparable) withStack.pop(); boolean result = false; if (a.getClass().equals(b.getClass())) { result = compare(a, b); } else { throw new <API key>("Vergleich nicht möglich"); } withStack.pushBoolean(result); } private boolean compare(Comparable a, Comparable b) { int c = a.compareTo(b); if (c == 0) { if (comp.equals(Comp.NEQ)) { return false; } else { return comp.equals(Comp.EQ) || comp.equals(Comp.LEQ) || comp.equals(Comp.GEQ); } } else { if (c > 0) { return comp.equals(Comp.NEQ) || comp.equals(Comp.LEQ) || comp.equals(Comp.LT); } else { return comp.equals(Comp.NEQ) || comp.equals(Comp.GEQ) || comp.equals(Comp.GT); } } } }
#ifndef <API key> #define <API key> #include "tokens.hpp" #include <QSyntaxHighlighter> #include <QVector> namespace ScIDE { namespace Settings { class Manager; } class Main; enum SyntaxFormat { PlainFormat, ClassFormat, KeywordFormat, BuiltinFormat, PrimitiveFormat, SymbolFormat, StringFormat, CharFormat, NumberFormat, EnvVarFormat, CommentFormat, FormatCount }; struct SyntaxRule { SyntaxRule(): type(Token::Unknown) {} SyntaxRule( Token::Type t, const QString &s ): type(t), expr(s) {} Token::Type type; QRegExp expr; }; class <API key> : public QObject { Q_OBJECT public: <API key>( Main *, Settings::Manager * settings ); inline const QTextCharFormat * formats() const { return mFormats; } inline const QTextCharFormat & format( SyntaxFormat type ) const { return mFormats[type]; } inline static const <API key> * instance() { Q_ASSERT(mInstance); return mInstance; } public Q_SLOTS: void applySettings( Settings::Manager * ); Q_SIGNALS: void <API key>(); private: friend class SyntaxHighlighter; void initSyntaxRules(); void initKeywords(); void initBuiltins(); void applySettings( Settings::Manager*, const QString &key, SyntaxFormat ); QTextCharFormat mFormats[FormatCount]; QVector<SyntaxRule> mInCodeRules; QRegExp mInSymbolRegexp, mInStringRegexp; static <API key> *mInstance; }; class SyntaxHighlighter: public QSyntaxHighlighter { Q_OBJECT static const int inCode = 0; static const int inString = 1; static const int inSymbol = 2; static const int inComment = 100; // NOTE: Integers higher than inComment are reserved for multi line comments, // and indicate the comment nesting level! public: SyntaxHighlighter(QTextDocument *parent = 0); private: void highlightBlock(const QString &text); void <API key>(const QString& text, int & currentIndex, int & currentState); void <API key>(const QString& text, int & currentIndex, int & currentState); void <API key>(const QString& text, int & currentIndex, int & currentState); void <API key>(const QString& text, int & currentIndex, int & currentState); Token::Type findMatchingRule(QString const & text, int & currentIndex, int & lengthOfMatch); const <API key> *mGlobals; }; } #endif
package service import ( "encoding/json" "errors" log "github.com/cihub/seelog" "github.com/mysteriumnetwork/node/communication" "github.com/mysteriumnetwork/node/identity" "github.com/mysteriumnetwork/node/market" "github.com/mysteriumnetwork/node/session" ) var ( // ErrorLocation error indicates that action (i.e. disconnect) ErrorLocation = errors.New("failed to detect service location") // <API key> indicates that manager tried to create an unsupported service type <API key> = errors.New("unsupported service type") ) // Service interface represents pluggable Mysterium service type Service interface { Serve(providerID identity.Identity) error Stop() error ProvideConfig(publicKey json.RawMessage) (session.<API key>, session.DestroyCallback, error) } // DialogWaiterFactory initiates communication channel which waits for incoming dialogs type DialogWaiterFactory func(providerID identity.Identity, serviceType string) (communication.DialogWaiter, error) // <API key> initiates instance which is able to handle incoming dialogs type <API key> func(market.ServiceProposal, session.ConfigNegotiator) communication.DialogHandler // DiscoveryFactory initiates instance which is able announce service discoverability type DiscoveryFactory func() Discovery // Discovery registers the service to the discovery api periodically type Discovery interface { Start(ownIdentity identity.Identity, proposal market.ServiceProposal) Stop() Wait() } // NewManager creates new instance of pluggable instances manager func NewManager( serviceRegistry *Registry, dialogWaiterFactory DialogWaiterFactory, <API key> <API key>, discoveryFactory DiscoveryFactory, ) *Manager { return &Manager{ serviceRegistry: serviceRegistry, servicePool: NewPool(), dialogWaiterFactory: dialogWaiterFactory, <API key>: <API key>, discoveryFactory: discoveryFactory, } } // Manager entrypoint which knows how to start pluggable Mysterium instances type Manager struct { dialogWaiterFactory DialogWaiterFactory <API key> <API key> serviceRegistry *Registry servicePool *Pool discoveryFactory DiscoveryFactory } // Start starts an instance of the given service type if knows one in service registry. // It passes the options to the start method of the service. // If an error occurs in the underlying service, the error is then returned. func (manager *Manager) Start(providerID identity.Identity, serviceType string, options Options) (id ID, err error) { service, proposal, err := manager.serviceRegistry.Create(serviceType, options) if err != nil { return id, err } dialogWaiter, err := manager.dialogWaiterFactory(providerID, serviceType) if err != nil { return id, err } providerContact, err := dialogWaiter.Start() if err != nil { return id, err } proposal.SetProviderContact(providerID, providerContact) dialogHandler := manager.<API key>(proposal, service) if err = dialogWaiter.ServeDialogs(dialogHandler); err != nil { return id, err } discovery := manager.discoveryFactory() discovery.Start(providerID, proposal) instance := Instance{ state: Starting, options: options, service: service, proposal: proposal, dialogWaiter: dialogWaiter, discovery: discovery, } id, err = manager.servicePool.Add(&instance) if err != nil { return id, err } go func() { instance.state = Running serveErr := service.Serve(providerID) if serveErr != nil { log.Error("Service serve failed: ", serveErr) } instance.state = NotRunning stopErr := manager.servicePool.Stop(id) if stopErr != nil { log.Error("Service stop failed: ", stopErr) } discovery.Wait() }() return id, nil } // List returns array of running service instances. func (manager *Manager) List() map[ID]*Instance { return manager.servicePool.List() } // Kill stops all services. func (manager *Manager) Kill() error { return manager.servicePool.StopAll() } // Stop stops the service. func (manager *Manager) Stop(id ID) error { return manager.servicePool.Stop(id) } // Service returns a service instance by requested id. func (manager *Manager) Service(id ID) *Instance { return manager.servicePool.Instance(id) }
<!DOCTYPE html > <html> <head> <title>IndexRange - ScalaFX API 8.0.0-R4 - scalafx.scene.control.IndexRange</title> <meta name="description" content="IndexRange - ScalaFX API 8.0.0 - R4 - scalafx.scene.control.IndexRange" /> <meta name="keywords" content="IndexRange ScalaFX API 8.0.0 R4 scalafx.scene.control.IndexRange" /> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" /> <link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" /> <script type="text/javascript" src="../../../lib/jquery.js" id="jquery-js"></script> <script type="text/javascript" src="../../../lib/jquery-ui.js"></script> <script type="text/javascript" src="../../../lib/template.js"></script> <script type="text/javascript" src="../../../lib/tools.tooltip.js"></script> <script type="text/javascript"> if(top === self) { var url = '../../../index.html'; var hash = 'scalafx.scene.control.IndexRange$'; var anchor = window.location.hash; var anchor_opt = ''; if (anchor.length >= 1) anchor_opt = '@' + anchor.substring(1); window.location.href = url + '#' + hash + anchor_opt; } </script> </head> <body class="value"> <div id="definition"> <a href="IndexRange.html" title="Go to companion"><img src="../../../lib/object_to_class_big.png" /></a> <p id="owner"><a href="../../package.html" class="extype" name="scalafx">scalafx</a>.<a href="../package.html" class="extype" name="scalafx.scene">scene</a>.<a href="package.html" class="extype" name="scalafx.scene.control">control</a></p> <h1><a href="IndexRange.html" title="Go to companion">IndexRange</a></h1> </div> <h4 id="signature" class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">object</span> </span> <span class="symbol"> <span class="name">IndexRange</span> </span> </h4> <div id="comment" class="fullcommenttop"><div class="toggleContainer block"> <span class="toggle">Linear Supertypes</span> <div class="superTypes hiddenContent"><span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div> </div></div> <div id="mbrsel"> <div id="textfilter"><span class="pre"></span><span class="input"><input id="mbrsel-input" type="text" accesskey="/" /></span><span class="post"></span></div> <div id="order"> <span class="filtertype">Ordering</span> <ol> <li class="alpha in"><span>Alphabetic</span></li> <li class="inherit out"><span>By inheritance</span></li> </ol> </div> <div id="ancestors"> <span class="filtertype">Inherited<br /> </span> <ol id="linearization"> <li class="in" name="scalafx.scene.control.IndexRange"><span>IndexRange</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li> </ol> </div><div id="ancestors"> <span class="filtertype"></span> <ol> <li class="hideall out"><span>Hide All</span></li> <li class="showall in"><span>Show all</span></li> </ol> <a href="http://docs.scala-lang.org/overviews/scaladoc/usage.html#members" target="_blank">Learn more about member selection</a> </div> <div id="visbl"> <span class="filtertype">Visibility</span> <ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol> </div> </div> <div id="template"> <div id="allMembers"> <div id="values" class="values members"> <h3>Value Members</h3> <ol><li name="scala.AnyRef#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="!=(x$1:Any):Boolean"></a> <a id="!=(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef###" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="##():Int"></a> <a id="##():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="==(x$1:Any):Boolean"></a> <a id="==(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scalafx.scene.control.IndexRange#VALUE_DELIMITER" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped"> <a id="VALUE_DELIMITER:String"></a> <a id="VALUE_DELIMITER:String"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">val</span> </span> <span class="symbol"> <span class="name">VALUE_DELIMITER</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span> </span> </h4> <p class="shortcomment cmt">Index range value delimiter.</p> </li><li name="scala.Any#asInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="asInstanceOf[T0]:T0"></a> <a id="asInstanceOf[T0]:T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#clone" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="clone():Object"></a> <a id="clone():AnyRef"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.<API key>]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#eq" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="eq(x$1:AnyRef):Boolean"></a> <a id="eq(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#equals" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="equals(x$1:Any):Boolean"></a> <a id="equals(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">equals</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#finalize" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="finalize():Unit"></a> <a id="finalize():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="symbol">classOf[java.lang.Throwable]</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#getClass" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getClass():Class[_]"></a> <a id="getClass():Class[_]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#hashCode" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="hashCode():Int"></a> <a id="hashCode():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">hashCode</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.Any#isInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="isInstanceOf[T0]:Boolean"></a> <a id="isInstanceOf[T0]:Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#ne" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="ne(x$1:AnyRef):Boolean"></a> <a id="ne(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scalafx.scene.control.IndexRange#normalize" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped"> <a id="normalize(v1:Int,v2:Int):scalafx.scene.control.IndexRange"></a> <a id="normalize(Int,Int):IndexRange"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">normalize</span><span class="params">(<span name="v1">v1: <span class="extype" name="scala.Int">Int</span></span>, <span name="v2">v2: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <a href="IndexRange.html" class="extype" name="scalafx.scene.control.IndexRange">IndexRange</a></span> </span> </h4> <p class="shortcomment cmt">Convenience method to create an IndexRange instance that has the smaller value as the start index, and the larger value as the end index.</p> </li><li name="scala.AnyRef#notify" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notify():Unit"></a> <a id="notify():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notifyAll" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notifyAll():Unit"></a> <a id="notifyAll():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scalafx.scene.control.IndexRange#sfxIndexRange" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped"> <a id="sfxIndexRange(r:scalafx.scene.control.IndexRange):javafx.scene.control.IndexRange"></a> <a id="sfxIndexRange(IndexRange):javafx.scene.control.IndexRange"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">implicit </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">sfxIndexRange</span><span class="params">(<span name="r">r: <a href="IndexRange.html" class="extype" name="scalafx.scene.control.IndexRange">IndexRange</a></span>)</span><span class="result">: <span class="extype" name="javafx.scene.control.IndexRange">javafx.scene.control.IndexRange</span></span> </span> </h4> </li><li name="scala.AnyRef#synchronized" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="synchronized[T0](x$1:=&gt;T0):T0"></a> <a id="synchronized[T0](⇒T0):T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#toString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="toString():String"></a> <a id="toString():String"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scalafx.scene.control.IndexRange#valueOf" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped"> <a id="valueOf(value:String):scalafx.scene.control.IndexRange"></a> <a id="valueOf(String):IndexRange"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">valueOf</span><span class="params">(<span name="value">value: <span class="extype" name="scala.Predef.String">String</span></span>)</span><span class="result">: <a href="IndexRange.html" class="extype" name="scalafx.scene.control.IndexRange">IndexRange</a></span> </span> </h4> <p class="shortcomment cmt">Convenience method to parse in a String of the form '2,6', which will create an IndexRange instance with a start value of 2, and an end value of 6.</p> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait():Unit"></a> <a id="wait():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.<API key>]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long,x$2:Int):Unit"></a> <a id="wait(Long,Int):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.<API key>]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long):Unit"></a> <a id="wait(Long):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.<API key>]">...</span> </span>)</span> </dd></dl></div> </li></ol> </div> </div> <div id="inheritedMembers"> <div class="parent" name="scala.AnyRef"> <h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3> </div><div class="parent" name="scala.Any"> <h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3> </div> </div> <div id="groupedMembers"> <div class="group" name="Ungrouped"> <h3>Ungrouped</h3> </div> </div> </div> <div id="tooltip"></div> <div id="footer"> </div> </body> </html>
package com.trackit.business.domain; import java.util.ArrayList; import java.util.List; import com.trackit.business.exception.TrackItException; import com.trackit.presentation.event.Event; import com.trackit.presentation.event.EventManager; import com.trackit.presentation.event.EventPublisher; public class Folder extends TrackItBaseType implements DocumentItem { private String name; private List<GPSDocument> documents; public Folder(String name) { super(); this.name = name; documents = new ArrayList<GPSDocument>(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<GPSDocument> getDocuments() { return documents; } public void add(GPSDocument document) { documents.add(document); } public void remove(GPSDocument document) { documents.remove(document); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Folder other = (Folder) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { return String.format("Folder [name=%s]", name); } @Override public void <API key>(EventPublisher publisher) { EventManager.getInstance().publish(publisher, Event.FOLDER_SELECTED, this); } @Override public void accept(Visitor visitor) throws TrackItException { visitor.visit(this); } }
#!/bin/bash # SLURM batch script to launch BLAST #SBATCH -p nbi-medium # partition (queue) #SBATCH -N 1 # number of nodes #SBATCH -n 1 # number of cores #SBATCH --mem 30000 # memory pool for all cores #SBATCH -t 2-00:00 # time (D-HH:MM) #SBATCH -o /nbi/Research-Groups/NBI/Cristobal-Uauy/PB_AFLF/control_timecourse/TF_analysis/slurm_output/extractNAC.%N.%j.out # STDOUT #SBATCH -e /nbi/Research-Groups/NBI/Cristobal-Uauy/PB_AFLF/control_timecourse/TF_analysis/slurm_output/extractNAC.%N.%j.err # STDERR #SBATCH -J extractNAC #SBATCH --mail-type=END,FAIL # notifications for job done & fail #SBATCH --mail-user=philippa.borrill\@jic.ac.uk # send-to address source perl-5.22.1 cd /nbi/Research-Groups/NBI/Cristobal-Uauy/PB_AFLF/control_timecourse/TF_analysis/ perl /nbi/Research-Groups/NBI/Cristobal-Uauy/PB_AFLF/control_timecourse/scripts/<API key>.pl -r -p "|NAC|" <API key>.fas > <API key>.fa
Namespace Items.Standard <Item(615, "Fossilized Dino")> Public Class FossilizedDino Inherits FossilItem Public Overrides ReadOnly Property Description As String = "The fossil of an ancient Pokémon that once lived in the sea. What it looked like is a mystery." Public Sub New() _textureRectangle = New Rectangle(24, 72, 24, 24) End Sub End Class End Namespace
<?php namespace eduTrac\Classes\Models; if ( ! defined('BASE_PATH') ) exit('No direct script access allowed'); use \eduTrac\Classes\Core\DB; use \eduTrac\Classes\Libraries\Util; class ProfileModel { private $_auth; public function __construct() { $this->_auth = new \eduTrac\Classes\Libraries\Cookies; } public function index() {} public function runProfile($data) { $update1 = [ "fname" => $data['fname'],"lname" => $data['lname'], "mname" => Util::_trim($data['mname']),"email" => Util::_trim($data['email']), "ssn" => Util::_trim($data['ssn']),"dob" => $data['dob'] ]; $bind = [ ":personID" => $this->_auth->getPersonField('personID') ]; $q = DB::inst()->update("person",$update1,"personID = :personID",$bind); if(!empty($data['password'])) { $update2 = ["password" => et_hash_password($data['password'])]; DB::inst()->update("person",$update2,"personID = :personID",$bind); } redirect( BASE_URL . 'profile/' ); } public function __destruct() { DB::inst()->close(); } }
using System; namespace UnstuckMeLoggers { public enum ERR_TYPES_SERVER { // if you add one of these please add it in the switch statement to be handled SERVER_GUI_LOGIN, SERVER_GUI_LOGOUT, <API key>, <API key>, SERVER_START, SERVER_STOP, <API key>, <API key> } internal class ErrContainerServer { string i_ErrorMsg; // the error message string contained by the thrown exception string i_ErrTypeStartMark; // the xml like tag that defines the start of the error string i_ErrTypeEndMark; // the xml like tag that defines the end of the error string i_ErrorTime; // the string representaition of the time the errors occurance string i_AdditionalInfo; // a string that holds any additional info you would like logged such as what caused the error internal ErrContainerServer(string ErrorMsg, string ErrTypeStartMark, string ErrTypeEndMark, string ErrorTime, string AdditionalInfo = null) { i_ErrorMsg = ErrorMsg; i_ErrTypeStartMark = ErrTypeStartMark; i_ErrTypeEndMark = ErrTypeEndMark; i_ErrorTime = ErrorTime; i_AdditionalInfo = AdditionalInfo; } public override string ToString() { string temp = i_ErrTypeStartMark + Environment.NewLine + "\t" + "<ErrMsg=" + i_ErrorMsg + "/>"; if (i_AdditionalInfo != null) temp = temp + Environment.NewLine + "<AdditionalInfo=" + i_AdditionalInfo + "/>"; temp = temp + Environment.NewLine + "\t" + "<ErrTime=" + i_ErrorTime + "/>" + Environment.NewLine + i_ErrTypeEndMark; return temp; } } }
import discord import asyncio import datetime import time import aiohttp import threading import glob import re import json import os import urllib.request from discord.ext import commands from random import randint from random import choice as randchoice from random import choice as rndchoice from random import shuffle from .utils.dataIO import fileIO from .utils import checks from bs4 import BeautifulSoup class Runescapecompare: """Runescape-relate commands""" def __init__(self, bot): self.bot = bot @commands.group(name="compare", pass_context=True) async def _compare(self, ctx): if ctx.invoked_subcommand is None: await self.bot.say("Please, choose a skill to compare!") @_compare.command(name="overall", pass_context=True) async def compare_overall(self, ctx, name1 : str, name2 : str): address1 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name1 address2 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name2 try: website1 = urllib.request.urlopen(address1) website2 = urllib.request.urlopen(address2) website_html1 = website1.read().decode(website1.headers.get_content_charset()) website_html2 = website2.read().decode(website2.headers.get_content_charset()) stats1 = website_html1.split("\n") stats2 = website_html2.split("\n") stat1 = stats1[0].split(",") stat2= stats2[0].split(",") if stat1[2] > stat2[2]: comparerank = int(stat2[0]) - int(stat1[0]) comparelvl = int(stat1[1]) - int(stat2[1]) comparexp = int(stat1[2]) - int(stat2[2]) await self.bot.say("```" + name1 + "'s ranking is " + str(comparerank) + " ranks higher than " + name2 + "'s rank.\n" + name1 + "'s level is " + str(comparelvl) + " levels higher than " + name2 + "'s.\n" + name1 + "'s total experience is " + str(comparexp) + " higher than " + name2 + "'s.```") if stat2[2] > stat1[2]: comparerank = stat2[0] - stat1[0] comparelvl = stat2[1] - stat1[1] comparexp = stat2[2] - stat1[2] await self.bot.say("```" + name2 + "'s ranking is " + str(comparerank) + " ranks higher than " + name1 + "'s rank.\n" + name2 + "'s level is " + str(comparelvl) + " levels higher than " + name1 + "'s.\n" + name2 + "'s total experience is " + str(comparexp) + " higher than " + name1 + "'s.```") except: await self.bot.say("Sorry... Something went wrong there. Did you type the name correctly?") def setup(bot): n = Runescapecompare(bot) bot.add_cog(n)
package com.snail.webgame.game.protocal.relation.getRequest; import org.epilot.ccf.config.Resource; import org.epilot.ccf.core.processor.ProtocolProcessor; import org.epilot.ccf.core.processor.Request; import org.epilot.ccf.core.processor.Response; import org.epilot.ccf.core.protocol.Message; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.snail.webgame.game.common.GameMessageHead; import com.snail.webgame.game.common.util.Command; import com.snail.webgame.game.protocal.relation.service.<API key>; public class <API key> extends ProtocolProcessor{ private static Logger logger = LoggerFactory.getLogger("logs"); private <API key> <API key>; public void <API key>(<API key> <API key>) { this.<API key> = <API key>; } @Override public void execute(Request request, Response response) { Message msg = request.getMessage(); GameMessageHead header = (GameMessageHead) msg.getHeader(); header.setMsgType(Command.<API key>); int roleId = header.getUserID0(); GetAddRequestReq req = (GetAddRequestReq) msg.getBody(); GetAddRequestResp resp = <API key>.<API key>(roleId, req); msg.setHeader(header); msg.setBody(resp); response.write(msg); if(logger.isInfoEnabled()){ logger.info(Resource.getMessage("game", "<API key>") + ": result=" + resp.getResult() + ",roleId=" + roleId); } } }
'use strict'; var ParameterDef = function(object) { this.id = object.id; this.summary = object.summary; this.description = object.description; this.type = object.type; this.mandatory = object.mandatory; this.defaultValue = object.defaultValue; }; module.exports = ParameterDef;
package org.eclipse.jdt.internal.core; import java.util.ArrayList; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IInitializer; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IModuleDescription; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IType; /** * @see <API key> */ @SuppressWarnings({ "rawtypes", "unchecked" }) public class <API key> implements <API key> { /** * True if this requestor no longer wants to receive * results from its <code><API key></code>. */ protected boolean canceled= false; /** * A collection of the resulting fields, or <code>null</code> * if no field results have been received. */ protected ArrayList fields= null; /** * A collection of the resulting initializers, or <code>null</code> * if no initializer results have been received. */ protected ArrayList initializers= null; /** * A collection of the resulting member types, or <code>null</code> * if no member type results have been received. */ protected ArrayList memberTypes= null; /** * A collection of the resulting methods, or <code>null</code> * if no method results have been received. */ protected ArrayList methods= null; /** * A collection of the resulting package fragments, or <code>null</code> * if no package fragment results have been received. */ protected ArrayList packageFragments= null; /** * A collection of the resulting types, or <code>null</code> * if no type results have been received. */ protected ArrayList types= null; /** * A collection of the resulting modules, or <code>null</code> * if no module results have been received */ protected ArrayList<IModuleDescription> modules = null; /** * Empty arrays used for efficiency */ protected static final IField[] EMPTY_FIELD_ARRAY= new IField[0]; protected static final IInitializer[] <API key>= new IInitializer[0]; protected static final IType[] EMPTY_TYPE_ARRAY= new IType[0]; protected static final IPackageFragment[] <API key>= new IPackageFragment[0]; protected static final IMethod[] EMPTY_METHOD_ARRAY= new IMethod[0]; protected static final IModuleDescription[] EMPTY_MODULE_ARRAY= new IModuleDescription[0]; /** * @see <API key> */ @Override public void acceptField(IField field) { if (this.fields == null) { this.fields= new ArrayList(); } this.fields.add(field); } /** * @see <API key> */ @Override public void acceptInitializer(IInitializer initializer) { if (this.initializers == null) { this.initializers= new ArrayList(); } this.initializers.add(initializer); } /** * @see <API key> */ @Override public void acceptMemberType(IType type) { if (this.memberTypes == null) { this.memberTypes= new ArrayList(); } this.memberTypes.add(type); } /** * @see <API key> */ @Override public void acceptMethod(IMethod method) { if (this.methods == null) { this.methods = new ArrayList(); } this.methods.add(method); } /** * @see <API key> */ @Override public void <API key>(IPackageFragment packageFragment) { if (this.packageFragments== null) { this.packageFragments= new ArrayList(); } this.packageFragments.add(packageFragment); } /** * @see <API key> */ @Override public void acceptType(IType type) { if (this.types == null) { this.types= new ArrayList(); } this.types.add(type); } /** * @see <API key> */ @Override public void acceptModule(IModuleDescription module) { if (this.modules == null) { this.modules= new ArrayList(); } this.modules.add(module); } /** * @see <API key> */ public IField[] getFields() { if (this.fields == null) { return EMPTY_FIELD_ARRAY; } int size = this.fields.size(); IField[] results = new IField[size]; this.fields.toArray(results); return results; } /** * @see <API key> */ public IInitializer[] getInitializers() { if (this.initializers == null) { return <API key>; } int size = this.initializers.size(); IInitializer[] results = new IInitializer[size]; this.initializers.toArray(results); return results; } /** * @see <API key> */ public IType[] getMemberTypes() { if (this.memberTypes == null) { return EMPTY_TYPE_ARRAY; } int size = this.memberTypes.size(); IType[] results = new IType[size]; this.memberTypes.toArray(results); return results; } /** * @see <API key> */ public IMethod[] getMethods() { if (this.methods == null) { return EMPTY_METHOD_ARRAY; } int size = this.methods.size(); IMethod[] results = new IMethod[size]; this.methods.toArray(results); return results; } /** * @see <API key> */ public IPackageFragment[] getPackageFragments() { if (this.packageFragments== null) { return <API key>; } int size = this.packageFragments.size(); IPackageFragment[] results = new IPackageFragment[size]; this.packageFragments.toArray(results); return results; } /** * @see <API key> */ public IType[] getTypes() { if (this.types== null) { return EMPTY_TYPE_ARRAY; } int size = this.types.size(); IType[] results = new IType[size]; this.types.toArray(results); return results; } /** * @see <API key> */ public IModuleDescription[] getModules() { if (this.modules == null) { return EMPTY_MODULE_ARRAY; } int size = this.modules.size(); IModuleDescription[] results = new IModuleDescription[size]; this.modules.toArray(results); return results; } /** * @see <API key> */ @Override public boolean isCanceled() { return this.canceled; } /** * Reset the state of this requestor. */ public void reset() { this.canceled = false; this.fields = null; this.initializers = null; this.memberTypes = null; this.methods = null; this.packageFragments = null; this.types = null; } /** * Sets the #isCanceled state of this requestor to true or false. */ public void setCanceled(boolean b) { this.canceled= b; } }
import string import ast from state_machine import PSM, Source class SpecialPattern: individual_chars = ('t', 'n', 'v', 'f', 'r', '0') range_chars = ('d', 'D', 'w', 'W', 's', 'S') special_chars = ('^', '$', '[', ']', '(', ')', '{', '}', '\\', '.', '*', '?', '+', '|', '.') <API key> = ('\\', '[', ']') posix_classes = ("alnum", "alpha", "blank", "cntrl", "digit", "graph", "lower", "print", "punct", "space", "upper", "xdigit", "d", "w", "s") min_len_posix_class = 1 # Group class WrappedGroup: def __init__(self): self.group = ast.Group() self.is_alt = False def add(self, other): if self.is_alt: last_alt = self.alt.parts[-1] + (other,) self.alt.parts = self.alt.parts[:-1] + (last_alt,) else: self.group.seq = self.group.seq + (other,) @property def alt(self) -> ast.Alternative: assert self.is_alt return self.group.seq[0] def collapse_alt(self): if self.is_alt: self.alt.parts = self.alt.parts + ((),) else: self.is_alt = True first_alt_elems = self.group.seq self.group.seq = (ast.Alternative(),) self.alt.parts = (first_alt_elems,()) class OpeningOfGroup: def __init__(self, parent: None, initial: bool=False): self.is_initial = initial self.parent = parent # OpeningOfGroup or ContentOfGroup self.g = WrappedGroup() self.content_of_initial = None # forward of function self.add = self.g.add # if this group is the initial, their is no parent but we must refer # to itself as the returning state # but if it is a nested group, it must be added into its global group if self.is_initial: self.content_of_initial = ContentOfGroup(self, initial) else: self.parent.add(self.g.group) def next(self, psm: PSM): if not self.is_initial and psm.char == "?": return FirstOptionOfGroup(self) elif psm.char == ")": if self.is_initial: psm.error = 'unexpected ")"' else: return self.parent elif psm.char == "(": return OpeningOfGroup(self) elif self.is_initial: return self.content_of_initial.next(psm) else: t = ContentOfGroup(self) return t.next(psm) class FirstOptionOfGroup: def __init__(self, parent: OpeningOfGroup): self.parent = parent def next(self, psm: PSM): if psm.char == ":": self.parent.g.group.ignored = True return ContentOfGroup(self.parent) elif psm.char == "!": self.parent.g.group.lookhead = ast.Group.NegativeLookhead return ContentOfGroup(self.parent) elif psm.char == "=": self.parent.g.group.lookhead = ast.Group.PositiveLookhead return ContentOfGroup(self.parent) elif psm.char == "<": self.parent.g.group.name = "" return NameOfGroup(self.parent) else: psm.error = 'expected ":", "!", "<" or "="' class NameOfGroup: def __init__(self, parent: OpeningOfGroup): self.parent = parent def next(self, psm: PSM): if psm.char.isalpha() or psm.char == "_": self.parent.g.group.name += psm.char return self elif psm.char == ">": return self.parent else: psm.error = 'expected a letter, "_" or ">"' class ContentOfGroup: NotQuantified = 0 Quantified = 1 UngreedyQuantified = 2 def __init__(self, parent: OpeningOfGroup, initial: bool=False): self.parent = parent self.is_initial = initial self.limited_prev = parent if initial else self self.quantified = ContentOfGroup.NotQuantified # forward of function self.add = self.parent.add def next(self, psm: PSM): quantified = self.quantified self.quantified = ContentOfGroup.NotQuantified if psm.char == ")": if self.is_initial: psm.error = "unbalanced parenthesis" else: return self.parent.parent elif psm.char == "(": return OpeningOfGroup(self.limited_prev) elif psm.char == "^": self.add(ast.MatchBegin()) return self.limited_prev elif psm.char == "$": self.add(ast.MatchEnd()) return self.limited_prev elif psm.char == ".": t = ast.PatternChar() t.pattern = psm.char self.add(t) return self.limited_prev elif psm.char == "\\": return EscapedChar(self.limited_prev, as_single_chars=SpecialPattern.special_chars) elif psm.char == "[": return CharClass(self.limited_prev) elif psm.char == "|": self.parent.g.collapse_alt() return self.limited_prev # >>> Quantifiers elif psm.char == "?" and quantified == ContentOfGroup.NotQuantified: self.quantified = ContentOfGroup.Quantified last = self._last_or_fail(psm) if last: last.quantifier = ast.NoneOrOnce() return self.limited_prev elif psm.char == "*" and quantified == ContentOfGroup.NotQuantified: self.quantified = ContentOfGroup.Quantified last = self._last_or_fail(psm) if last: last.quantifier = ast.NoneOrMore() return self.limited_prev elif psm.char == "+" and quantified == ContentOfGroup.NotQuantified: self.quantified = ContentOfGroup.Quantified last = self._last_or_fail(psm) if last: last.quantifier = ast.OneOrMore() return self.limited_prev elif psm.char == "{" and quantified == ContentOfGroup.NotQuantified: self.quantified = ContentOfGroup.Quantified t = MinimumOfRepetition(self.limited_prev) last = self._last_or_fail(psm) if last: last.quantifier = t.between return t elif psm.char == "?" and quantified == ContentOfGroup.Quantified: self.quantified = ContentOfGroup.UngreedyQuantified last = self._last_or_fail(psm) if last: last.quantifier.greedy = False return self.limited_prev elif quantified == ContentOfGroup.Quantified: psm.error = "unexpected quantifier" elif quantified == ContentOfGroup.UngreedyQuantified: psm.error = "quantifier repeated" # <<< Quantifier else: t = ast.SingleChar() t.char = psm.char self.add(t) return self.limited_prev def _last_or_fail(self, psm: PSM): if self.parent.g.group.seq: return self.parent.g.group.seq[-1] else: psm.error = "nothing to repeat" class MinimumOfRepetition: def __init__(self, parent: ContentOfGroup): self.parent = parent self.between = ast.Between() self.min = [] def next(self, psm: PSM): if psm.char.isdigit(): self.min.append(psm.char) return self elif psm.char == ",": self._interpret() return MaximumOfRepetition(self) elif psm.char == "}": self._interpret() return self.parent else: psm.error = 'expected digit, "," or "}"' def _interpret(self): if not self.min: return try: count = int("".join(self.min)) except ValueError: assert False, "internal error: cannot convert to number minimum of repetition" self.between.min = count class MaximumOfRepetition: def __init__(self, repeat: MinimumOfRepetition): self.repeat = repeat self.max = [] def next(self, psm: PSM): if psm.char.isdigit(): self.max.append(psm.char) return self elif psm.char == "}": self._interpret() return self.repeat.parent else: psm.error = 'expected digit, "," or "}"' def _interpret(self): if not self.max: return try: count = int("".join(self.max)) except ValueError: assert False, "internal error: cannot convert to number maximum of repetition" self.repeat.between.max = count # Escaping class EscapedChar: def __init__(self, prev, as_single_chars=(), as_pattern_chars=()): self.prev = prev # ContentOfGroup or CharClass self.single_chars = as_single_chars self.pattern_chars = as_pattern_chars def next(self, psm: PSM): if psm.char in SpecialPattern.individual_chars \ or psm.char in SpecialPattern.range_chars \ or psm.char in self.pattern_chars: t = ast.PatternChar() t.pattern = psm.char self.prev.add(t) return self.prev elif psm.char in self.single_chars: t = ast.SingleChar() t.char = psm.char self.prev.add(t) return self.prev elif psm.char == "x": return AsciiChar(self.prev) elif psm.char == "u": return UnicodeChar(self.prev) else: psm.error = "unauthorized escape of {}".format(psm.char) class AsciiChar: def __init__(self, prev): self.prev = prev # ContentOfGroup or CharClass self.pattern = ast.PatternChar() self.pattern.type = ast.PatternChar.Ascii self.prev.add(self.pattern) def next(self, psm: PSM): if psm.char in string.hexdigits: self.pattern.pattern += psm.char count = len(self.pattern.pattern) return self.prev if count >= 2 else self else: psm.error = "expected ASCII hexadecimal character" class UnicodeChar: def __init__(self, prev): self.prev = prev # ContentOfGroup or CharClass self.pattern = ast.PatternChar() self.pattern.type = ast.PatternChar.Unicode self.prev.add(self.pattern) def next(self, psm: PSM): if psm.char in string.hexdigits: self.pattern.pattern += psm.char count = len(self.pattern.pattern) return self.prev if count >= 4 else self else: psm.error = "expected ASCII hexadecimal character" # Character class class WrappedCharClass: def __init__(self): # ast is CharClass or may be changed to PatternClass in one case self.ast = ast.CharClass() def add(self, other): assert isinstance(self.ast, ast.CharClass) self.ast.elems = self.ast.elems + (other,) def pop(self): assert isinstance(self.ast, ast.CharClass) last = self.ast.elems[-1] self.ast.elems = self.ast.elems[:-1] return last class CharClass: def __init__(self, prev): self.prev = prev # ContentOfGroup or CharClass self.q = WrappedCharClass() # forward function self.add = self.q.add self.next_is_range = False self.empty = True self.can_mutate = True def next(self, psm: PSM): <API key> = self.next_is_range self.next_is_range = False this_is_empty = self.empty self.empty = False if psm.char == "\\": self.can_mutate = False self.next_is_range = <API key> return EscapedChar(self, as_single_chars=SpecialPattern.<API key>) elif <API key> and psm.char != "]": assert isinstance(self.q.ast, ast.CharClass) assert len(self.q.ast.elems) >= 1 self.next_is_range = False t = ast.Range() t.begin = self.q.pop() t.end = ast.SingleChar() t.end.char = psm.char self.q.add(t) return self elif psm.char == "^": # if at the begining, it has a special meaning if this_is_empty: self.can_mutate = False self.q.ast.negate = True else: t = ast.SingleChar() t.char = psm.char self.q.add(t) return self elif psm.char == "]": if <API key>: t = ast.SingleChar() t.char = "-" self.q.add(t) else: self.<API key>() self.prev.add(self.q.ast) return self.prev elif psm.char == "[": return CharClass(self) elif psm.char == "-" and len(self.q.ast.elems) >= 1: self.next_is_range = True return self else: t = ast.SingleChar() t.char = psm.char self.q.add(t) return self def <API key>(self): """ Change from character class to pattern char if the content is matching POSIX-like classe. """ assert isinstance(self.q.ast, ast.CharClass) # put in this variable everything that had happen but not saved into # the single char object # because mutation is only possible if the exact string of the content # match a pre-definied list, so if an unlogged char is consumed, it # must prevent mutation if not self.can_mutate: return if len(self.q.ast.elems) < SpecialPattern.min_len_posix_class + 2: return opening = self.q.ast.elems[0] if not isinstance(opening, ast.SingleChar) or opening.char != ":": return closing = self.q.ast.elems[-1] if not isinstance(closing, ast.SingleChar) or closing.char != ":": return is_only_ascii = lambda x: (isinstance(x, ast.SingleChar) and len(x.char) == 1 and x.char.isalpha()) class_may_be_a_word = not any( not is_only_ascii(x) for x in self.q.ast.elems[1:-1]) if not class_may_be_a_word: return word = "".join(s.char for s in self.q.ast.elems[1:-1]) if word not in SpecialPattern.posix_classes: return t = ast.PatternChar() t.pattern = word t.type = ast.PatternChar.Posix self.q.ast = t def parse(expr, **kw): sm = PSM() sm.source = Source(expr) sm.starts_with(OpeningOfGroup(parent=None, initial=True)) sm.pre_action = kw.get("pre_action", None) sm.post_action = kw.get("post_action", None) sm.parse() return sm.state.g.group
{ am_pm_abbreviated => [ "Munkyo", "Eigulo" ], available_formats => { E => "ccc", EHm => "E HH:mm", EHms => "E HH:mm:ss", Ed => "d, E", Ehm => "E h:mm a", Ehms => "E h:mm:ss a", Gy => "G y", GyMMM => "G y MMM", GyMMMEd => "G y MMM d, E", GyMMMd => "G y MMM d", H => "HH", Hm => "HH:mm", Hms => "HH:mm:ss", Hmsv => "HH:mm:ss v", Hmv => "HH:mm v", M => "L", MEd => "E, M/d", MMM => "LLL", MMMEd => "E, MMM d", MMMMEd => "E, MMMM d", "MMMMW-count-other" => "'week' W 'of' MMMM", MMMMd => "MMMM d", MMMd => "MMM d", Md => "M/d", d => "d", h => "h a", hm => "h:mm a", hms => "h:mm:ss a", hmsv => "h:mm:ss a v", hmv => "h:mm a v", ms => "mm:ss", y => "y", yM => "M/y", yMEd => "E, M/d/y", yMMM => "MMM y", yMMMEd => "E, MMM d, y", yMMMM => "MMMM y", yMMMd => "y MMM d", yMd => "y-MM-dd", yQQQ => "QQQ y", yQQQQ => "QQQQ y", "yw-count-other" => "'week' w 'of' y" }, code => "xog", date_format_full => "EEEE, d MMMM y", date_format_long => "d MMMM y", date_format_medium => "d MMM y", date_format_short => "dd/MM/y", <API key> => "{1} {0}", <API key> => "{1} {0}", <API key> => "{1} {0}", <API key> => "{1} {0}", <API key> => [ "Bala", "Kubi", "Kusa", "Kuna", "Kuta", "Muka", "Sabi" ], day_format_narrow => [ "B", "B", "S", "K", "K", "M", "S" ], day_format_wide => [ "Balaza", "Owokubili", "Owokusatu", "Olokuna", "Olokutaanu", "Olomukaaga", "Sabiiti" ], <API key> => [ "Bala", "Kubi", "Kusa", "Kuna", "Kuta", "Muka", "Sabi" ], <API key> => [ "B", "B", "S", "K", "K", "M", "S" ], <API key> => [ "Balaza", "Owokubili", "Owokusatu", "Olokuna", "Olokutaanu", "Olomukaaga", "Sabiiti" ], era_abbreviated => [ "AZ", "AF" ], era_narrow => [ "AZ", "AF" ], era_wide => [ "Kulisto nga azilawo", "Kulisto nga affile" ], first_day_of_week => 1, glibc_date_1_format => "%a %b %e %H:%M:%S %Z %Y", glibc_date_format => "%m/%d/%y", <API key> => "%a %b %e %H:%M:%S %Y", <API key> => "%I:%M:%S %p", glibc_time_format => "%H:%M:%S", language => "Soga", <API key> => [ "Jan", "Feb", "Mar", "Apu", "Maa", "Juu", "Jul", "Agu", "Seb", "Oki", "Nov", "Des" ], month_format_narrow => [ "J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D" ], month_format_wide => [ "Janwaliyo", "Febwaliyo", "Marisi", "Apuli", "Maayi", "Juuni", "Julaayi", "Agusito", "Sebuttemba", "Okitobba", "Novemba", "Desemba" ], <API key> => [ "Jan", "Feb", "Mar", "Apu", "Maa", "Juu", "Jul", "Agu", "Seb", "Oki", "Nov", "Des" ], <API key> => [ "J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D" ], <API key> => [ "Janwaliyo", "Febwaliyo", "Marisi", "Apuli", "Maayi", "Juuni", "Julaayi", "Agusito", "Sebuttemba", "Okitobba", "Novemba", "Desemba" ], name => "Soga", native_language => "Olusoga", native_name => "Olusoga", native_script => undef, native_territory => undef, native_variant => undef, <API key> => [ "Q1", "Q2", "Q3", "Q4" ], <API key> => [ 1, 2, 3, 4 ], quarter_format_wide => [ "Ebisera ebyomwaka ebisoka", "Ebisera ebyomwaka ebyokubiri", "Ebisera ebyomwaka ebyokusatu", "Ebisera ebyomwaka ebyokuna" ], <API key> => [ "Q1", "Q2", "Q3", "Q4" ], <API key> => [ 1, 2, 3, 4 ], <API key> => [ "Ebisera ebyomwaka ebisoka", "Ebisera ebyomwaka ebyokubiri", "Ebisera ebyomwaka ebyokusatu", "Ebisera ebyomwaka ebyokuna" ], script => undef, territory => undef, time_format_full => "HH:mm:ss zzzz", time_format_long => "HH:mm:ss z", time_format_medium => "HH:mm:ss", time_format_short => "HH:mm", variant => undef, version => 31 }
package org.egov.search.service; import org.egov.search.domain.entities.Address; import org.egov.search.domain.entities.Person; import org.json.simple.JSONObject; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import static com.jayway.jsonassert.JsonAssert.with; public class <API key> { private String json; @Before public void before() { Person person = Person.newInstance(); ResourceGenerator<Person> resourceGenerator = new ResourceGenerator<>(Person.class, person); JSONObject resource = resourceGenerator.generate(); json = resource.toJSONString(); } @Test public void withMultipleFields() { with(json).assertEquals("$.searchable.citizen", true); with(json).assertEquals("$.searchable.age", 37); with(json).assertEquals("$.clauses.status", "ACTIVE"); with(json).assertNotDefined("$.searchable.role"); } @Test public void <API key>() { with(json).assertEquals("$.searchable.citizen_name", "Elzan"); } @Test public void withAListField() { with(json).assertEquals("$.searchable.jobs", Arrays.asList("Job One", "Job Two")); } @Test public void withAMapField() { with(json).assertEquals("$.searchable.serviceHistory.company1", "Job One"); with(json).assertEquals("$.searchable.serviceHistory.company2", "Job Two"); } @Test public void shouldGroupFields() { Address address = new Address("street1", "560001"); ResourceGenerator<Address> resourceGenerator = new ResourceGenerator<>(Address.class, address); JSONObject resource = resourceGenerator.generate(); String json = resource.toJSONString(); with(json).assertEquals("$.searchable.street", "street1"); with(json).assertEquals("$.searchable.pincode", "560001"); with(json).assertNotDefined("$.clauses"); with(json).assertNotDefined("$.common"); } }
Fox.define('views/email/fields/from-email-address', 'views/fields/link', function (Dep) { return Dep.extend({ listTemplate: 'email/fields/from-email-address/detail', detailTemplate: 'email/fields/from-email-address/detail', }); });