text
stringlengths 1
1.05M
|
|---|
<gh_stars>1-10
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.heartBroken = void 0;
var heartBroken = {
"viewBox": "0 0 16 16",
"children": [{
"name": "path",
"attribs": {
"fill": "#000000",
"d": "M11.8 1c2.318 0 4.2 1.882 4.2 4.2 0 4.566-4.935 5.982-8 10.616-3.243-4.663-8-5.9-8-10.616 0-2.319 1.882-4.2 4.2-4.2 0.943 0 1.812 0.43 2.512 1.060l-1.213 1.94 3.5 2-2 5 5.5-6-3.5-2 0.967-1.451c0.553-0.34 1.175-0.549 1.833-0.549z"
}
}]
};
exports.heartBroken = heartBroken;
|
package main
import (
"YouComic-Nano/config"
"YouComic-Nano/datasource"
"YouComic-Nano/debug"
"YouComic-Nano/generate"
"YouComic-Nano/router"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"os"
)
func main() {
var err error
// debug mode
debugMode := len(os.Getenv("DEBUG")) != 0
rootPath := "./"
if debugMode && len(os.Getenv(debug.DEBUG_GENERATE_PATH)) != 0 {
rootPath = os.Getenv(debug.DEBUG_GENERATE_PATH)
}
if debugMode {
logrus.SetLevel(logrus.DebugLevel)
}
// log
config.SetupLogConfig()
config.RootPath = rootPath
//clear up
//err = generate.ClearUp()
//if err != nil {
// logrus.Fatal(err)
//}
// load application config
err = config.SetupApplicationConfig()
if err != nil {
logrus.Fatal(err)
}
// load cache
if config.ApplicationConfig.GetBool(config.ACTIVE_COVER_THUMBNAIL) {
err = config.SetupCache()
if err != nil {
logrus.Fatal(err)
}
}
// first library
if generate.CheckIsNewLibrary(rootPath) {
logrus.Info("build library ...")
err := generate.SetupLibrary(rootPath)
if err != nil {
logrus.Fatal(err)
}
}
err = config.LoadConfig(rootPath)
if err != nil {
logrus.Fatal(err)
}
datasource.InitDataSource()
r := gin.New()
router.SetRouter(r)
gin.SetMode(gin.DebugMode)
err = r.Run("0.0.0.0:8880")
if err != nil {
logrus.Fatal(err)
}
}
|
#!/bin/sh
#
# This file was produced by running the Configure script. It holds all the
# definitions figured out by Configure. Should you modify one of these values,
# do not forget to propagate your changes by running "Configure -der". You may
# instead choose to run each of the .SH files by yourself, or "Configure -S".
#
# Package name : perl5
# Source directory : .
# Configuration time: Mon Sep 22 17:02:13 CEST 2014
# Configured by : chris
# Target system : linux venus 3.16.0 #14 smp preempt fri aug 29 22:26:32 cest 2014 armv7l gnulinux
: Configure command line arguments.
config_arg0='./Configure'
config_args='-des -Dusethreads -Duseshrplib -Dprefix=/usr -Dvendorprefix=/usr -Dprivlib=/usr/share/perl5/core_perl -Darchlib=/usr/lib/perl5/core_perl -Dsitelib=/usr/share/perl5/site_perl -Dsitearch=/usr/lib/perl5/site_perl -Dvendorlib=/usr/share/perl5/vendor_perl -Dvendorarch=/usr/lib/perl5/vendor_perl -Dscriptdir=/usr/bin -Dvendorscript=/usr/bin -Dinc_version_list=none -Dman1ext=1p -Dman3ext=3p -Dman1dir=/usr/share/man/man1 -Dman3dir=/usr/share/man/man3 -Dcccdlflags=-fPIC -Doptimize=-O2 @@XBPS_CROSS_CFLAGS@@'
config_argc=20
config_arg1='-des'
config_arg2='-Dusethreads'
config_arg3='-Duseshrplib'
config_arg4='-Dprefix=/usr'
config_arg5='-Dvendorprefix=/usr'
config_arg6='-Dprivlib=/usr/share/perl5/core_perl'
config_arg7='-Darchlib=/usr/lib/perl5/core_perl'
config_arg8='-Dsitelib=/usr/share/perl5/site_perl'
config_arg9='-Dsitearch=/usr/lib/perl5/site_perl'
config_arg10='-Dvendorlib=/usr/share/perl5/vendor_perl'
config_arg11='-Dvendorarch=/usr/lib/perl5/vendor_perl'
config_arg12='-Dscriptdir=/usr/bin'
config_arg13='-Dvendorscript=/usr/bin'
config_arg14='-Dinc_version_list=none'
config_arg15='-Dman1ext=1p'
config_arg16='-Dman3ext=3p'
config_arg17='-Dman1dir=/usr/share/man/man1'
config_arg18='-Dman3dir=/usr/share/man/man3'
config_arg19='-Dcccdlflags=-fPIC'
config_arg20='-Doptimize=-O2 @@XBPS_CROSS_CFLAGS@@'
Author=''
Date='$Date'
Header=''
Id='$Id'
Locker=''
Log='$Log'
RCSfile='$RCSfile'
Revision='$Revision'
Source=''
State=''
_a='.a'
_exe=''
_o='.o'
afs='false'
afsroot='/afs'
alignbytes='8'
ansi2knr=''
aphostname='/usr/bin/hostname'
api_revision='5'
api_subversion='0'
api_version='20'
api_versionstring='5.20.0'
ar='ar'
archlib='/usr/lib/perl5/core_perl'
archlibexp='/usr/lib/perl5/core_perl'
archname64=''
archname='@@XBPS_CROSS_ARCH@@-linux-thread-multi'
archobjs=''
asctime_r_proto='REENTRANT_PROTO_B_SB'
awk='awk'
baserev='5.0'
bash=''
bin='/usr/bin'
bin_ELF='define'
binexp='/usr/bin'
bison='bison'
bootstrap_charset='undef'
byacc='byacc'
byteorder='1234'
c=''
castflags='1'
cat='cat'
cc='@@XBPS_CROSS_TRIPLET@@-gcc'
cccdlflags='-fPIC'
ccdlflags='-Wl,-E -Wl,-rpath,/usr/lib/perl5/core_perl/CORE'
ccflags='-D_REENTRANT -D_GNU_SOURCE -fwrapv -fno-strict-aliasing -pipe -fstack-protector -I/usr/local/include -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64'
ccflags_uselargefiles='-D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64'
ccname='gcc'
ccsymbols=''
ccversion=''
cf_by='chris'
cf_email='chris@venus.nonet'
cf_time='Mon Sep 22 17:02:13 CEST 2014'
charbits='8'
charsize='1'
chgrp=''
chmod='chmod'
chown=''
clocktype='clock_t'
comm='comm'
compress=''
contains='grep'
cp='cp'
cpio=''
cpp='cpp'
cpp_stuff='42'
cppccsymbols=''
cppflags='-D_REENTRANT -D_GNU_SOURCE -fwrapv -fno-strict-aliasing -pipe -fstack-protector -I/usr/local/include'
cpplast='-'
cppminus='-'
cpprun='cc -E'
cppstdin='cc -E'
cppsymbols='__ACCUM_EPSILON__=0x1P-15K __ACCUM_FBIT__=15 __ACCUM_IBIT__=16 __ACCUM_MAX__=0X7FFFFFFFP-15K __ACCUM_MIN__=(-0X1P15K-0X1P15K) __APCS_32__=1 __arm__=1 __ARM_32BIT_STATE=1 __ARM_ARCH=7 __ARM_ARCH_7A__=1 __ARM_ARCH_ISA_ARM=1 __ARM_ARCH_ISA_THUMB=2 __ARM_ARCH_PROFILE=65 __ARM_EABI__=1 __ARMEL__=1 __ARM_FEATURE_CLZ=1 __ARM_FEATURE_DSP=1 __ARM_FEATURE_LDREX=15 __ARM_FEATURE_QBIT=1 __ARM_FEATURE_SAT=1 __ARM_FEATURE_SIMD32=1 __ARM_FEATURE_UNALIGNED=1 __ARM_FP=12 __ARM_NEON_FP=4 __ARM_PCS_VFP=1 __ARM_SIZEOF_MINIMAL_ENUM=4 __ARM_SIZEOF_WCHAR_T=32 __ATOMIC_ACQ_REL=4 __ATOMIC_ACQUIRE=2 __ATOMIC_CONSUME=1 __ATOMIC_RELAXED=0 __ATOMIC_RELEASE=3 __ATOMIC_SEQ_CST=5 __BIGGEST_ALIGNMENT__=8 __BYTE_ORDER__=1234 __CHAR16_TYPE__=short\ unsigned\ int __CHAR32_TYPE__=unsigned\ int __CHAR_BIT__=8 __CHAR_UNSIGNED__=1 __DA_FBIT__=31 __DA_IBIT__=32 __DBL_DECIMAL_DIG__=17 __DBL_DENORM_MIN__=((double)4.9406564584124654e-324L) __DBL_DIG__=15 __DBL_EPSILON__=((double)2.2204460492503131e-16L) __DBL_HAS_DENORM__=1 __DBL_HAS_INFINITY__=1 __DBL_HAS_QUIET_NAN__=1 __DBL_MANT_DIG__=53 __DBL_MAX_10_EXP__=308 __DBL_MAX__=((double)1.7976931348623157e+308L) __DBL_MAX_EXP__=1024 __DBL_MIN_10_EXP__=(-307) __DBL_MIN__=((double)2.2250738585072014e-308L) __DBL_MIN_EXP__=(-1021) __DEC128_EPSILON__=1E-33DL __DEC128_MANT_DIG__=34 __DEC128_MAX__=9.999999999999999999999999999999999E6144DL __DEC128_MAX_EXP__=6145 __DEC128_MIN__=1E-6143DL __DEC128_MIN_EXP__=(-6142) __DEC128_SUBNORMAL_MIN__=0.000000000000000000000000000000001E-6143DL __DEC32_EPSILON__=1E-6DF __DEC32_MANT_DIG__=7 __DEC32_MAX__=9.999999E96DF __DEC32_MAX_EXP__=97 __DEC32_MIN__=1E-95DF __DEC32_MIN_EXP__=(-94) __DEC32_SUBNORMAL_MIN__=0.000001E-95DF __DEC64_EPSILON__=1E-15DD __DEC64_MANT_DIG__=16 __DEC64_MAX__=9.999999999999999E384DD __DEC64_MAX_EXP__=385 __DEC64_MIN__=1E-383DD __DEC64_MIN_EXP__=(-382) __DEC64_SUBNORMAL_MIN__=0.000000000000001E-383DD __DEC_EVAL_METHOD__=2 __DECIMAL_DIG__=17 __DQ_FBIT__=63 __DQ_IBIT__=0 __ELF__=1 _FILE_OFFSET_BITS=64 __FINITE_MATH_ONLY__=0 __FLOAT_WORD_ORDER__=1234 __FLT_DECIMAL_DIG__=9 __FLT_DENORM_MIN__=1.4012984643248171e-45F __FLT_DIG__=6 __FLT_EPSILON__=1.1920928955078125e-7F __FLT_EVAL_METHOD__=0 __FLT_HAS_DENORM__=1 __FLT_HAS_INFINITY__=1 __FLT_HAS_QUIET_NAN__=1 __FLT_MANT_DIG__=24 __FLT_MAX_10_EXP__=38 __FLT_MAX__=3.4028234663852886e+38F __FLT_MAX_EXP__=128 __FLT_MIN_10_EXP__=(-37) __FLT_MIN__=1.1754943508222875e-38F __FLT_MIN_EXP__=(-125) __FLT_RADIX__=2 __FRACT_EPSILON__=0x1P-15R __FRACT_FBIT__=15 __FRACT_IBIT__=0 __FRACT_MAX__=0X7FFFP-15R __FRACT_MIN__=(-0.5R-0.5R) __GCC_ATOMIC_BOOL_LOCK_FREE=2 __GCC_ATOMIC_CHAR16_T_LOCK_FREE=2 __GCC_ATOMIC_CHAR32_T_LOCK_FREE=2 __GCC_ATOMIC_CHAR_LOCK_FREE=2 __GCC_ATOMIC_INT_LOCK_FREE=2 __GCC_ATOMIC_LLONG_LOCK_FREE=2 __GCC_ATOMIC_LONG_LOCK_FREE=2 __GCC_ATOMIC_POINTER_LOCK_FREE=2 __GCC_ATOMIC_SHORT_LOCK_FREE=2 __GCC_ATOMIC_TEST_AND_SET_TRUEVAL=1 __GCC_ATOMIC_WCHAR_T_LOCK_FREE=2 __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1=1 __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2=1 __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4=1 __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8=1 __GCC_IEC_559=2 __GCC_IEC_559_COMPLEX=2 __GLIBC__=2 __GLIBC_MINOR__=20 __GNUC__=4 __GNUC_GNU_INLINE__=1 __GNUC_MINOR__=9 __GNUC_PATCHLEVEL__=1 __GNU_LIBRARY__=6 __gnu_linux__=1 _GNU_SOURCE=1 __GXX_ABI_VERSION=1002 __GXX_TYPEINFO_EQUALITY_INLINE=0 __HA_FBIT__=7 __HA_IBIT__=8 __HQ_FBIT__=15 __HQ_IBIT__=0 __INT16_C=__INT16_C __INT16_MAX__=32767 __INT16_TYPE__=short\ int __INT32_C=__INT32_C __INT32_MAX__=2147483647 __INT32_TYPE__=int __INT64_C=__INT64_C __INT64_MAX__=9223372036854775807LL __INT64_TYPE__=long\ long\ int __INT8_C=__INT8_C __INT8_MAX__=127 __INT8_TYPE__=signed\ char __INT_FAST16_MAX__=2147483647 __INT_FAST16_TYPE__=int __INT_FAST32_MAX__=2147483647 __INT_FAST32_TYPE__=int __INT_FAST64_MAX__=9223372036854775807LL __INT_FAST64_TYPE__=long\ long\ int __INT_FAST8_MAX__=127 __INT_FAST8_TYPE__=signed\ char __INT_LEAST16_MAX__=32767 __INT_LEAST16_TYPE__=short\ int __INT_LEAST32_MAX__=2147483647 __INT_LEAST32_TYPE__=int __INT_LEAST64_MAX__=9223372036854775807LL __INT_LEAST64_TYPE__=long\ long\ int __INT_LEAST8_MAX__=127 __INT_LEAST8_TYPE__=signed\ char __INT_MAX__=2147483647 __INTMAX_C=__INTMAX_C __INTMAX_MAX__=9223372036854775807LL __INTMAX_TYPE__=long\ long\ int __INTPTR_MAX__=2147483647 __INTPTR_TYPE__=int __LACCUM_EPSILON__=0x1P-31LK __LACCUM_FBIT__=31 __LACCUM_IBIT__=32 __LACCUM_MAX__=0X7FFFFFFFFFFFFFFFP-31LK __LACCUM_MIN__=(-0X1P31LK-0X1P31LK) _LARGEFILE64_SOURCE=1 _LARGEFILE_SOURCE=1 __LDBL_DENORM_MIN__=4.9406564584124654e-324L __LDBL_DIG__=15 __LDBL_EPSILON__=2.2204460492503131e-16L __LDBL_HAS_DENORM__=1 __LDBL_HAS_INFINITY__=1 __LDBL_HAS_QUIET_NAN__=1 __LDBL_MANT_DIG__=53 __LDBL_MAX_10_EXP__=308 __LDBL_MAX__=1.7976931348623157e+308L __LDBL_MAX_EXP__=1024 __LDBL_MIN_10_EXP__=(-307) __LDBL_MIN__=2.2250738585072014e-308L __LDBL_MIN_EXP__=(-1021) __LFRACT_EPSILON__=0x1P-31LR __LFRACT_FBIT__=31 __LFRACT_IBIT__=0 __LFRACT_MAX__=0X7FFFFFFFP-31LR __LFRACT_MIN__=(-0.5LR-0.5LR) __linux=1 __linux__=1 linux=1 __LLACCUM_EPSILON__=0x1P-31LLK __LLACCUM_FBIT__=31 __LLACCUM_IBIT__=32 __LLACCUM_MAX__=0X7FFFFFFFFFFFFFFFP-31LLK __LLACCUM_MIN__=(-0X1P31LLK-0X1P31LLK) __LLFRACT_EPSILON__=0x1P-63LLR __LLFRACT_FBIT__=63 __LLFRACT_IBIT__=0 __LLFRACT_MAX__=0X7FFFFFFFFFFFFFFFP-63LLR __LLFRACT_MIN__=(-0.5LLR-0.5LLR) __LONG_LONG_MAX__=9223372036854775807LL __LONG_MAX__=2147483647L __ORDER_BIG_ENDIAN__=4321 __ORDER_LITTLE_ENDIAN__=1234 __ORDER_PDP_ENDIAN__=3412 _POSIX_C_SOURCE=200809L _POSIX_SOURCE=1 __PRAGMA_REDEFINE_EXTNAME=1 __PTRDIFF_MAX__=2147483647 __PTRDIFF_TYPE__=int __QQ_FBIT__=7 __QQ_IBIT__=0 _REENTRANT=1 __REGISTER_PREFIX__= __SACCUM_EPSILON__=0x1P-7HK __SACCUM_FBIT__=7 __SACCUM_IBIT__=8 __SACCUM_MAX__=0X7FFFP-7HK __SACCUM_MIN__=(-0X1P7HK-0X1P7HK) __SA_FBIT__=15 __SA_IBIT__=16 __SCHAR_MAX__=127 __SFRACT_EPSILON__=0x1P-7HR __SFRACT_FBIT__=7 __SFRACT_IBIT__=0 __SFRACT_MAX__=0X7FP-7HR __SFRACT_MIN__=(-0.5HR-0.5HR) __SHRT_MAX__=32767 __SIG_ATOMIC_MAX__=2147483647 __SIG_ATOMIC_MIN__=(-2147483647\ -\ 1) __SIG_ATOMIC_TYPE__=int __SIZE_MAX__=4294967295U __SIZEOF_DOUBLE__=8 __SIZEOF_FLOAT__=4 __SIZEOF_INT__=4 __SIZEOF_LONG__=4 __SIZEOF_LONG_DOUBLE__=8 __SIZEOF_LONG_LONG__=8 __SIZEOF_POINTER__=4 __SIZEOF_PTRDIFF_T__=4 __SIZEOF_SHORT__=2 __SIZEOF_SIZE_T__=4 __SIZEOF_WCHAR_T__=4 __SIZEOF_WINT_T__=4 __SIZE_TYPE__=unsigned\ int __SQ_FBIT__=31 __SQ_IBIT__=0 __STDC__=1 __STDC_HOSTED__=1 __STDC_IEC_559__=1 __STDC_IEC_559_COMPLEX__=1 __STDC_ISO_10646__=201103L __STDC_NO_THREADS__=1 _STDC_PREDEF_H=1 __TA_FBIT__=63 __TA_IBIT__=64 __THUMB_INTERWORK__=1 __TQ_FBIT__=127 __TQ_IBIT__=0 __UACCUM_EPSILON__=0x1P-16UK __UACCUM_FBIT__=16 __UACCUM_IBIT__=16 __UACCUM_MAX__=0XFFFFFFFFP-16UK __UACCUM_MIN__=0.0UK __UDA_FBIT__=32 __UDA_IBIT__=32 __UDQ_FBIT__=64 __UDQ_IBIT__=0 __UFRACT_EPSILON__=0x1P-16UR __UFRACT_FBIT__=16 __UFRACT_IBIT__=0 __UFRACT_MAX__=0XFFFFP-16UR __UFRACT_MIN__=0.0UR __UHA_FBIT__=8 __UHA_IBIT__=8 __UHQ_FBIT__=16 __UHQ_IBIT__=0 __UINT16_C=__UINT16_C __UINT16_MAX__=65535 __UINT16_TYPE__=short\ unsigned\ int __UINT32_C=__UINT32_C __UINT32_MAX__=4294967295U __UINT32_TYPE__=unsigned\ int __UINT64_C=__UINT64_C __UINT64_MAX__=18446744073709551615ULL __UINT64_TYPE__=long\ long\ unsigned\ int __UINT8_C=__UINT8_C __UINT8_MAX__=255 __UINT8_TYPE__=unsigned\ char __UINT_FAST16_MAX__=4294967295U __UINT_FAST16_TYPE__=unsigned\ int __UINT_FAST32_MAX__=4294967295U __UINT_FAST32_TYPE__=unsigned\ int __UINT_FAST64_MAX__=18446744073709551615ULL __UINT_FAST64_TYPE__=long\ long\ unsigned\ int __UINT_FAST8_MAX__=255 __UINT_FAST8_TYPE__=unsigned\ char __UINT_LEAST16_MAX__=65535 __UINT_LEAST16_TYPE__=short\ unsigned\ int __UINT_LEAST32_MAX__=4294967295U __UINT_LEAST32_TYPE__=unsigned\ int __UINT_LEAST64_MAX__=18446744073709551615ULL __UINT_LEAST64_TYPE__=long\ long\ unsigned\ int __UINT_LEAST8_MAX__=255 __UINT_LEAST8_TYPE__=unsigned\ char __UINTMAX_C=__UINTMAX_C __UINTMAX_MAX__=18446744073709551615ULL __UINTMAX_TYPE__=long\ long\ unsigned\ int __UINTPTR_MAX__=4294967295U __UINTPTR_TYPE__=unsigned\ int __ULACCUM_EPSILON__=0x1P-32ULK __ULACCUM_FBIT__=32 __ULACCUM_IBIT__=32 __ULACCUM_MAX__=0XFFFFFFFFFFFFFFFFP-32ULK __ULACCUM_MIN__=0.0ULK __ULFRACT_EPSILON__=0x1P-32ULR __ULFRACT_FBIT__=32 __ULFRACT_IBIT__=0 __ULFRACT_MAX__=0XFFFFFFFFP-32ULR __ULFRACT_MIN__=0.0ULR __ULLACCUM_EPSILON__=0x1P-32ULLK __ULLACCUM_FBIT__=32 __ULLACCUM_IBIT__=32 __ULLACCUM_MAX__=0XFFFFFFFFFFFFFFFFP-32ULLK __ULLACCUM_MIN__=0.0ULLK __ULLFRACT_EPSILON__=0x1P-64ULLR __ULLFRACT_FBIT__=64 __ULLFRACT_IBIT__=0 __ULLFRACT_MAX__=0XFFFFFFFFFFFFFFFFP-64ULLR __ULLFRACT_MIN__=0.0ULLR __unix=1 __unix__=1 unix=1 __UQQ_FBIT__=8 __UQQ_IBIT__=0 __USACCUM_EPSILON__=0x1P-8UHK __USACCUM_FBIT__=8 __USACCUM_IBIT__=8 __USACCUM_MAX__=0XFFFFP-8UHK __USACCUM_MIN__=0.0UHK __USA_FBIT__=16 __USA_IBIT__=16 __USE_FILE_OFFSET64=1 __USE_GNU=1 __USE_LARGEFILE=1 __USE_LARGEFILE64=1 __USE_MISC=1 __USE_POSIX=1 __USE_POSIX199309=1 __USE_POSIX199506=1 __USE_POSIX2=1 __USE_REENTRANT=1 __USER_LABEL_PREFIX__= __USE_UNIX98=1 __USE_XOPEN=1 __USE_XOPEN_EXTENDED=1 __USFRACT_EPSILON__=0x1P-8UHR __USFRACT_FBIT__=8 __USFRACT_IBIT__=0 __USFRACT_MAX__=0XFFP-8UHR __USFRACT_MIN__=0.0UHR __USQ_FBIT__=32 __USQ_IBIT__=0 __UTA_FBIT__=64 __UTA_IBIT__=64 __UTQ_FBIT__=128 __UTQ_IBIT__=0 __VERSION__="4.9.1" __VFP_FP__=1 __WCHAR_MAX__=4294967295U __WCHAR_MIN__=0U __WCHAR_TYPE__=unsigned\ int __WINT_MAX__=4294967295U __WINT_MIN__=0U __WINT_TYPE__=unsigned\ int _XOPEN_SOURCE=700 _XOPEN_SOURCE_EXTENDED=1'
crypt_r_proto='REENTRANT_PROTO_B_CCS'
cryptlib=''
csh='csh'
ctermid_r_proto='0'
ctime_r_proto='REENTRANT_PROTO_B_SB'
d_Gconvert='gcvt((x),(n),(b))'
d_PRIEUldbl='define'
d_PRIFUldbl='define'
d_PRIGUldbl='define'
d_PRIXU64='define'
d_PRId64='define'
d_PRIeldbl='define'
d_PRIfldbl='define'
d_PRIgldbl='define'
d_PRIi64='define'
d_PRIo64='define'
d_PRIu64='define'
d_PRIx64='define'
d_SCNfldbl='define'
d__fwalk='undef'
d_access='define'
d_accessx='undef'
d_aintl='undef'
d_alarm='define'
d_archlib='define'
d_asctime64='undef'
d_asctime_r='define'
d_atolf='undef'
d_atoll='define'
d_attribute_deprecated='define'
d_attribute_format='define'
d_attribute_malloc='define'
d_attribute_nonnull='define'
d_attribute_noreturn='define'
d_attribute_pure='define'
d_attribute_unused='define'
d_attribute_warn_unused_result='define'
d_bcmp='define'
d_bcopy='define'
d_bsd='undef'
d_bsdgetpgrp='undef'
d_bsdsetpgrp='undef'
d_builtin_choose_expr='define'
d_builtin_expect='define'
d_bzero='define'
d_c99_variadic_macros='define'
d_casti32='define'
d_castneg='undef'
d_charvspr='undef'
d_chown='define'
d_chroot='define'
d_chsize='undef'
d_class='undef'
d_clearenv='define'
d_closedir='define'
d_cmsghdr_s='define'
d_const='define'
d_copysignl='define'
d_cplusplus='undef'
d_crypt='define'
d_crypt_r='define'
d_csh='undef'
d_ctermid='define'
d_ctermid_r='undef'
d_ctime64='undef'
d_ctime_r='define'
d_cuserid='define'
d_dbl_dig='define'
d_dbminitproto='define'
d_difftime64='undef'
d_difftime='define'
d_dir_dd_fd='undef'
d_dirfd='define'
d_dirnamlen='undef'
d_dlerror='define'
d_dlopen='define'
d_dlsymun='undef'
d_dosuid='undef'
d_drand48_r='define'
d_drand48proto='define'
d_dup2='define'
d_eaccess='define'
d_endgrent='define'
d_endgrent_r='undef'
d_endhent='define'
d_endhostent_r='undef'
d_endnent='define'
d_endnetent_r='undef'
d_endpent='define'
d_endprotoent_r='undef'
d_endpwent='define'
d_endpwent_r='undef'
d_endsent='define'
d_endservent_r='undef'
d_eofnblk='define'
d_eunice='undef'
d_faststdio='undef'
d_fchdir='define'
d_fchmod='define'
d_fchown='define'
d_fcntl='define'
d_fcntl_can_lock='define'
d_fd_macros='define'
d_fd_set='define'
d_fds_bits='define'
d_fgetpos='define'
d_finite='define'
d_finitel='define'
d_flexfnam='define'
d_flock='define'
d_flockproto='define'
d_fork='define'
d_fp_class='undef'
d_fpathconf='define'
d_fpclass='undef'
d_fpclassify='undef'
d_fpclassl='undef'
d_fpos64_t='undef'
d_frexpl='define'
d_fs_data_s='undef'
d_fseeko='define'
d_fsetpos='define'
d_fstatfs='define'
d_fstatvfs='define'
d_fsync='define'
d_ftello='define'
d_ftime='undef'
d_futimes='define'
d_gdbm_ndbm_h_uses_prototypes='undef'
d_gdbmndbm_h_uses_prototypes='define'
d_getaddrinfo='define'
d_getcwd='define'
d_getespwnam='undef'
d_getfsstat='undef'
d_getgrent='define'
d_getgrent_r='define'
d_getgrgid_r='define'
d_getgrnam_r='define'
d_getgrps='define'
d_gethbyaddr='define'
d_gethbyname='define'
d_gethent='define'
d_gethname='define'
d_gethostbyaddr_r='define'
d_gethostbyname_r='define'
d_gethostent_r='define'
d_gethostprotos='define'
d_getitimer='define'
d_getlogin='define'
d_getlogin_r='define'
d_getmnt='undef'
d_getmntent='define'
d_getnameinfo='define'
d_getnbyaddr='define'
d_getnbyname='define'
d_getnent='define'
d_getnetbyaddr_r='define'
d_getnetbyname_r='define'
d_getnetent_r='define'
d_getnetprotos='define'
d_getpagsz='define'
d_getpbyname='define'
d_getpbynumber='define'
d_getpent='define'
d_getpgid='define'
d_getpgrp2='undef'
d_getpgrp='define'
d_getppid='define'
d_getprior='define'
d_getprotobyname_r='define'
d_getprotobynumber_r='define'
d_getprotoent_r='define'
d_getprotoprotos='define'
d_getprpwnam='undef'
d_getpwent='define'
d_getpwent_r='define'
d_getpwnam_r='define'
d_getpwuid_r='define'
d_getsbyname='define'
d_getsbyport='define'
d_getsent='define'
d_getservbyname_r='define'
d_getservbyport_r='define'
d_getservent_r='define'
d_getservprotos='define'
d_getspnam='define'
d_getspnam_r='define'
d_gettimeod='define'
d_gmtime64='undef'
d_gmtime_r='define'
d_gnulibc='define'
d_grpasswd='define'
d_hasmntopt='define'
d_htonl='define'
d_ilogbl='define'
d_inc_version_list='undef'
d_index='undef'
d_inetaton='define'
d_inetntop='define'
d_inetpton='define'
d_int64_t='define'
d_ip_mreq='define'
d_ip_mreq_source='define'
d_ipv6_mreq='define'
d_ipv6_mreq_source='undef'
d_isascii='define'
d_isblank='define'
d_isfinite='undef'
d_isinf='define'
d_isnan='define'
d_isnanl='define'
d_killpg='define'
d_lchown='define'
d_ldbl_dig='define'
d_libm_lib_version='define'
d_libname_unique='undef'
d_link='define'
d_localtime64='undef'
d_localtime_r='define'
d_localtime_r_needs_tzset='define'
d_locconv='define'
d_lockf='define'
d_longdbl='define'
d_longlong='define'
d_lseekproto='define'
d_lstat='define'
d_madvise='define'
d_malloc_good_size='undef'
d_malloc_size='undef'
d_mblen='define'
d_mbstowcs='define'
d_mbtowc='define'
d_memchr='define'
d_memcmp='define'
d_memcpy='define'
d_memmove='define'
d_memset='define'
d_mkdir='define'
d_mkdtemp='define'
d_mkfifo='define'
d_mkstemp='define'
d_mkstemps='define'
d_mktime64='undef'
d_mktime='define'
d_mmap='define'
d_modfl='define'
d_modfl_pow32_bug='undef'
d_modflproto='define'
d_mprotect='define'
d_msg='define'
d_msg_ctrunc='define'
d_msg_dontroute='define'
d_msg_oob='define'
d_msg_peek='define'
d_msg_proxy='define'
d_msgctl='define'
d_msgget='define'
d_msghdr_s='define'
d_msgrcv='define'
d_msgsnd='define'
d_msync='define'
d_munmap='define'
d_mymalloc='undef'
d_ndbm='define'
d_ndbm_h_uses_prototypes='define'
d_nice='define'
d_nl_langinfo='define'
d_nv_preserves_uv='define'
d_nv_zero_is_allbits_zero='define'
d_off64_t='define'
d_old_pthread_create_joinable='undef'
d_oldpthreads='undef'
d_oldsock='undef'
d_open3='define'
d_pathconf='define'
d_pause='define'
d_perl_otherlibdirs='undef'
d_phostname='undef'
d_pipe='define'
d_poll='define'
d_portable='define'
d_prctl='define'
d_prctl_set_name='define'
d_printf_format_null='define'
d_procselfexe='define'
d_pseudofork='undef'
d_pthread_atfork='define'
d_pthread_attr_setscope='define'
d_pthread_yield='define'
d_pwage='undef'
d_pwchange='undef'
d_pwclass='undef'
d_pwcomment='undef'
d_pwexpire='undef'
d_pwgecos='define'
d_pwpasswd='define'
d_pwquota='undef'
d_qgcvt='define'
d_quad='define'
d_random_r='define'
d_readdir64_r='define'
d_readdir='define'
d_readdir_r='define'
d_readlink='define'
d_readv='define'
d_recvmsg='define'
d_rename='define'
d_rewinddir='define'
d_rmdir='define'
d_safebcpy='undef'
d_safemcpy='undef'
d_sanemcmp='define'
d_sbrkproto='define'
d_scalbnl='define'
d_sched_yield='define'
d_scm_rights='define'
d_seekdir='define'
d_select='define'
d_sem='define'
d_semctl='define'
d_semctl_semid_ds='define'
d_semctl_semun='define'
d_semget='define'
d_semop='define'
d_sendmsg='define'
d_setegid='define'
d_seteuid='define'
d_setgrent='define'
d_setgrent_r='undef'
d_setgrps='define'
d_sethent='define'
d_sethostent_r='undef'
d_setitimer='define'
d_setlinebuf='define'
d_setlocale='define'
d_setlocale_r='undef'
d_setnent='define'
d_setnetent_r='undef'
d_setpent='define'
d_setpgid='define'
d_setpgrp2='undef'
d_setpgrp='define'
d_setprior='define'
d_setproctitle='undef'
d_setprotoent_r='undef'
d_setpwent='define'
d_setpwent_r='undef'
d_setregid='define'
d_setresgid='define'
d_setresuid='define'
d_setreuid='define'
d_setrgid='undef'
d_setruid='undef'
d_setsent='define'
d_setservent_r='undef'
d_setsid='define'
d_setvbuf='define'
d_shm='define'
d_shmat='define'
d_shmatprototype='define'
d_shmctl='define'
d_shmdt='define'
d_shmget='define'
d_sigaction='define'
d_signbit='define'
d_sigprocmask='define'
d_sigsetjmp='define'
d_sin6_scope_id='define'
d_sitearch='define'
d_snprintf='define'
d_sockaddr_in6='define'
d_sockaddr_sa_len='undef'
d_sockatmark='define'
d_sockatmarkproto='define'
d_socket='define'
d_socklen_t='define'
d_sockpair='define'
d_socks5_init='undef'
d_sprintf_returns_strlen='define'
d_sqrtl='define'
d_srand48_r='define'
d_srandom_r='define'
d_sresgproto='define'
d_sresuproto='define'
d_statblks='define'
d_statfs_f_flags='define'
d_statfs_s='define'
d_static_inline='define'
d_statvfs='define'
d_stdio_cnt_lval='undef'
d_stdio_ptr_lval='undef'
d_stdio_ptr_lval_nochange_cnt='undef'
d_stdio_ptr_lval_sets_cnt='undef'
d_stdio_stream_array='undef'
d_stdiobase='undef'
d_stdstdio='undef'
d_strchr='define'
d_strcoll='define'
d_strctcpy='define'
d_strerrm='strerror(e)'
d_strerror='define'
d_strerror_r='define'
d_strftime='define'
d_strlcat='undef'
d_strlcpy='undef'
d_strtod='define'
d_strtol='define'
d_strtold='define'
d_strtoll='define'
d_strtoq='define'
d_strtoul='define'
d_strtoull='define'
d_strtouq='define'
d_strxfrm='define'
d_suidsafe='undef'
d_symlink='define'
d_syscall='define'
d_syscallproto='define'
d_sysconf='define'
d_sysernlst=''
d_syserrlst='define'
d_system='define'
d_tcgetpgrp='define'
d_tcsetpgrp='define'
d_telldir='define'
d_telldirproto='define'
d_time='define'
d_timegm='define'
d_times='define'
d_tm_tm_gmtoff='define'
d_tm_tm_zone='define'
d_tmpnam_r='define'
d_truncate='define'
d_ttyname_r='define'
d_tzname='define'
d_u32align='undef'
d_ualarm='define'
d_umask='define'
d_uname='define'
d_union_semun='undef'
d_unordered='undef'
d_unsetenv='define'
d_usleep='define'
d_usleepproto='define'
d_ustat='define'
d_vendorarch='define'
d_vendorbin='define'
d_vendorlib='define'
d_vendorscript='define'
d_vfork='undef'
d_void_closedir='undef'
d_voidsig='define'
d_voidtty=''
d_volatile='define'
d_vprintf='define'
d_vsnprintf='define'
d_wait4='define'
d_waitpid='define'
d_wcstombs='define'
d_wctomb='define'
d_writev='define'
d_xenix='undef'
date='date'
db_hashtype='u_int32_t'
db_prefixtype='size_t'
db_version_major='5'
db_version_minor='3'
db_version_patch='28'
direntrytype='struct dirent'
dlext='so'
dlsrc='dl_dlopen.xs'
doublesize='8'
drand01='Perl_drand48()'
drand48_r_proto='REENTRANT_PROTO_I_ST'
dtrace=''
dynamic_ext='arybase attributes B Compress/Raw/Bzip2 Compress/Raw/Zlib Cwd Data/Dumper DB_File Devel/Peek Devel/PPPort Digest/MD5 Digest/SHA Encode Fcntl File/DosGlob File/Glob Filter/Util/Call GDBM_File Hash/Util Hash/Util/FieldHash I18N/Langinfo IO IPC/SysV List/Util Math/BigInt/FastCalc MIME/Base64 mro NDBM_File ODBM_File Opcode PerlIO/encoding PerlIO/mmap PerlIO/scalar PerlIO/via POSIX re SDBM_File Socket Storable Sys/Hostname Sys/Syslog threads threads/shared Tie/Hash/NamedCapture Time/HiRes Time/Piece Unicode/Collate Unicode/Normalize XS/APItest XS/Typemap'
eagain='EAGAIN'
ebcdic='undef'
echo='echo'
egrep='egrep'
emacs=''
endgrent_r_proto='0'
endhostent_r_proto='0'
endnetent_r_proto='0'
endprotoent_r_proto='0'
endpwent_r_proto='0'
endservent_r_proto='0'
eunicefix=':'
exe_ext=''
expr='expr'
extensions='arybase attributes B Compress/Raw/Bzip2 Compress/Raw/Zlib Cwd Data/Dumper DB_File Devel/Peek Devel/PPPort Digest/MD5 Digest/SHA Encode Fcntl File/DosGlob File/Glob Filter/Util/Call GDBM_File Hash/Util Hash/Util/FieldHash I18N/Langinfo IO IPC/SysV List/Util Math/BigInt/FastCalc MIME/Base64 mro NDBM_File ODBM_File Opcode PerlIO/encoding PerlIO/mmap PerlIO/scalar PerlIO/via POSIX re SDBM_File Socket Storable Sys/Hostname Sys/Syslog threads threads/shared Tie/Hash/NamedCapture Time/HiRes Time/Piece Unicode/Collate Unicode/Normalize XS/APItest XS/Typemap Archive/Tar Attribute/Handlers autodie AutoLoader autouse base B/Debug bignum Carp CGI Config/Perl/V constant CPAN CPAN/Meta CPAN/Meta/Requirements CPAN/Meta/YAML Devel/SelfStubber Digest Dumpvalue encoding/warnings Env Errno experimental Exporter ExtUtils/CBuilder ExtUtils/Command ExtUtils/Constant ExtUtils/Install ExtUtils/MakeMaker ExtUtils/Manifest ExtUtils/Miniperl ExtUtils/ParseXS FileCache File/Fetch File/Find File/Path File/Temp Filter/Simple Getopt/Long HTTP/Tiny I18N/Collate I18N/LangTags if IO/Compress IO/Socket/IP IO/Zlib IPC/Cmd IPC/Open3 JSON/PP lib libnet Locale/Codes Locale/Maketext Locale/Maketext/Simple Math/BigInt Math/BigRat Math/Complex Memoize Module/Build Module/CoreList Module/Load Module/Load/Conditional Module/Loaded Module/Metadata Net/Ping NEXT Package/Constants Params/Check parent Parse/CPAN/Meta perlfaq PerlIO/via/QuotedPrint Perl/OSType Pod/Checker Pod/Escapes Pod/Functions Pod/Html podlators Pod/Parser Pod/Perldoc Pod/Simple Pod/Usage Safe Search/Dict SelfLoader Term/ANSIColor Term/Cap Term/Complete Term/ReadLine Test Test/Harness Test/Simple Text/Abbrev Text/Balanced Text/ParseWords Text/Tabs Thread/Queue Thread/Semaphore Tie/File Tie/Memoize Tie/RefHash Time/Local version XSLoader'
extern_C='extern'
extras=''
fflushNULL='define'
fflushall='undef'
find=''
firstmakefile='makefile'
flex=''
fpossize='16'
fpostype='fpos_t'
freetype='void'
from=':'
full_ar='/usr/bin/ar'
full_csh='csh'
full_sed='/usr/bin/sed'
gccansipedantic=''
gccosandvers=''
gccversion='4.9.1'
getgrent_r_proto='REENTRANT_PROTO_I_SBWR'
getgrgid_r_proto='REENTRANT_PROTO_I_TSBWR'
getgrnam_r_proto='REENTRANT_PROTO_I_CSBWR'
gethostbyaddr_r_proto='REENTRANT_PROTO_I_TsISBWRE'
gethostbyname_r_proto='REENTRANT_PROTO_I_CSBWRE'
gethostent_r_proto='REENTRANT_PROTO_I_SBWRE'
getlogin_r_proto='REENTRANT_PROTO_I_BW'
getnetbyaddr_r_proto='REENTRANT_PROTO_I_uISBWRE'
getnetbyname_r_proto='REENTRANT_PROTO_I_CSBWRE'
getnetent_r_proto='REENTRANT_PROTO_I_SBWRE'
getprotobyname_r_proto='REENTRANT_PROTO_I_CSBWR'
getprotobynumber_r_proto='REENTRANT_PROTO_I_ISBWR'
getprotoent_r_proto='REENTRANT_PROTO_I_SBWR'
getpwent_r_proto='REENTRANT_PROTO_I_SBWR'
getpwnam_r_proto='REENTRANT_PROTO_I_CSBWR'
getpwuid_r_proto='REENTRANT_PROTO_I_TSBWR'
getservbyname_r_proto='REENTRANT_PROTO_I_CCSBWR'
getservbyport_r_proto='REENTRANT_PROTO_I_ICSBWR'
getservent_r_proto='REENTRANT_PROTO_I_SBWR'
getspnam_r_proto='REENTRANT_PROTO_I_CSBWR'
gidformat='"lu"'
gidsign='1'
gidsize='4'
gidtype='gid_t'
glibpth='/usr/shlib /lib /usr/lib /usr/lib/386 /lib/386 /usr/ccs/lib /usr/ucblib /usr/local/lib '
gmake='gmake'
gmtime_r_proto='REENTRANT_PROTO_S_TS'
gnulibc_version='2.20'
grep='grep'
groupcat='cat /etc/group'
groupstype='gid_t'
gzip='gzip'
h_fcntl='false'
h_sysfile='true'
hint='recommended'
hostcat='cat /etc/hosts'
hostgenerate=''
hostosname=''
hostperl='/usr/bin/perl'
html1dir=' '
html1direxp=''
html3dir=' '
html3direxp=''
i16size='2'
i16type='short'
i32size='4'
i32type='long'
i64size='8'
i64type='long long'
i8size='1'
i8type='signed char'
i_arpainet='define'
i_assert='define'
i_bsdioctl=''
i_crypt='define'
i_db='define'
i_dbm='define'
i_dirent='define'
i_dlfcn='define'
i_fcntl='undef'
i_float='define'
i_fp='undef'
i_fp_class='undef'
i_gdbm='define'
i_gdbm_ndbm='undef'
i_gdbmndbm='define'
i_grp='define'
i_ieeefp='undef'
i_inttypes='define'
i_langinfo='define'
i_libutil='undef'
i_limits='define'
i_locale='define'
i_machcthr='undef'
i_malloc='define'
i_mallocmalloc='undef'
i_math='define'
i_memory='undef'
i_mntent='define'
i_ndbm='define'
i_netdb='define'
i_neterrno='undef'
i_netinettcp='define'
i_niin='define'
i_poll='define'
i_prot='undef'
i_pthread='define'
i_pwd='define'
i_rpcsvcdbm='undef'
i_sgtty='undef'
i_shadow='define'
i_socks='undef'
i_stdarg='define'
i_stdbool='define'
i_stddef='define'
i_stdlib='define'
i_string='define'
i_sunmath='undef'
i_sysaccess='undef'
i_sysdir='define'
i_sysfile='define'
i_sysfilio='undef'
i_sysin='undef'
i_sysioctl='define'
i_syslog='define'
i_sysmman='define'
i_sysmode='undef'
i_sysmount='define'
i_sysndir='undef'
i_sysparam='define'
i_syspoll='define'
i_sysresrc='define'
i_syssecrt='undef'
i_sysselct='define'
i_syssockio='undef'
i_sysstat='define'
i_sysstatfs='define'
i_sysstatvfs='define'
i_systime='define'
i_systimek='undef'
i_systimes='define'
i_systypes='define'
i_sysuio='define'
i_sysun='define'
i_sysutsname='define'
i_sysvfs='define'
i_syswait='define'
i_termio='undef'
i_termios='define'
i_time='define'
i_unistd='define'
i_ustat='define'
i_utime='define'
i_values='define'
i_varargs='undef'
i_varhdr='stdarg.h'
i_vfork='undef'
ignore_versioned_solibs='y'
inc_version_list=' '
inc_version_list_init='0'
incpth='/usr/@@XBPS_CROSS_TRIPLET@@/usr/include'
inews=''
initialinstalllocation='/usr/bin'
installarchlib='/usr/lib/perl5/core_perl'
installbin='/usr/bin'
installhtml1dir=''
installhtml3dir=''
installman1dir='/usr/share/man/man1'
installman3dir='/usr/share/man/man3'
installprefix='/usr'
installprefixexp='/usr'
installprivlib='/usr/share/perl5/core_perl'
installscript='/usr/bin'
installsitearch='/usr/lib/perl5/site_perl'
installsitebin='/usr/bin'
installsitehtml1dir=''
installsitehtml3dir=''
installsitelib='/usr/share/perl5/site_perl'
installsiteman1dir='/usr/share/man/man1'
installsiteman3dir='/usr/share/man/man3'
installsitescript='/usr/bin'
installstyle='lib/perl5'
installusrbinperl='undef'
installvendorarch='/usr/lib/perl5/vendor_perl'
installvendorbin='/usr/bin'
installvendorhtml1dir=''
installvendorhtml3dir=''
installvendorlib='/usr/share/perl5/vendor_perl'
installvendorman1dir='/usr/share/man/man1'
installvendorman3dir='/usr/share/man/man3'
installvendorscript='/usr/bin'
intsize='4'
issymlink='test -h'
ivdformat='"ld"'
ivsize='4'
ivtype='long'
known_extensions='Archive/Tar arybase Attribute/Handlers attributes autodie AutoLoader autouse B base B/Debug bignum Carp CGI Compress/Raw/Bzip2 Compress/Raw/Zlib Config/Perl/V constant CPAN CPAN/Meta CPAN/Meta/Requirements CPAN/Meta/YAML Cwd Data/Dumper DB_File Devel/Peek Devel/PPPort Devel/SelfStubber Digest Digest/MD5 Digest/SHA Dumpvalue Encode encoding/warnings Env Errno experimental Exporter ExtUtils/CBuilder ExtUtils/Command ExtUtils/Constant ExtUtils/Install ExtUtils/MakeMaker ExtUtils/Manifest ExtUtils/Miniperl ExtUtils/ParseXS Fcntl FileCache File/DosGlob File/Fetch File/Find File/Glob File/Path File/Temp Filter/Simple Filter/Util/Call GDBM_File Getopt/Long Hash/Util Hash/Util/FieldHash HTTP/Tiny I18N/Collate I18N/Langinfo I18N/LangTags if IO IO/Compress IO/Socket/IP IO/Zlib IPC/Cmd IPC/Open3 IPC/SysV JSON/PP lib libnet List/Util Locale/Codes Locale/Maketext Locale/Maketext/Simple Math/BigInt Math/BigInt/FastCalc Math/BigRat Math/Complex Memoize MIME/Base64 Module/Build Module/CoreList Module/Load Module/Load/Conditional Module/Loaded Module/Metadata mro NDBM_File Net/Ping NEXT ODBM_File Opcode Package/Constants Params/Check parent Parse/CPAN/Meta perlfaq PerlIO/encoding PerlIO/mmap PerlIO/scalar PerlIO/via PerlIO/via/QuotedPrint Perl/OSType Pod/Checker Pod/Escapes Pod/Functions Pod/Html podlators Pod/Parser Pod/Perldoc Pod/Simple Pod/Usage POSIX re Safe SDBM_File Search/Dict SelfLoader Socket Storable Sys/Hostname Sys/Syslog Term/ANSIColor Term/Cap Term/Complete Term/ReadLine Test Test/Harness Test/Simple Text/Abbrev Text/Balanced Text/ParseWords Text/Tabs Thread/Queue threads Thread/Semaphore threads/shared Tie/File Tie/Hash/NamedCapture Tie/Memoize Tie/RefHash Time/HiRes Time/Local Time/Piece Unicode/Collate Unicode/Normalize version VMS/DCLsym VMS/Filespec VMS/Stdio Win32 Win32API/File Win32CORE XS/APItest XSLoader XS/Typemap '
ksh=''
ld='@@XBPS_CROSS_TRIPLET@@-gcc'
ld_can_script='define'
lddlflags='-shared @@XBPS_CROSS_CFLAGS@@ -L/usr/@@XBPS_CROSS_TRIPLET@@/usr/lib -fstack-protector'
ldflags=' -fstack-protector -L/usr/@@XBPS_CROSS_TRIPLET@@/usr/lib'
ldflags_uselargefiles=''
ldlibpthname='LD_LIBRARY_PATH'
less='less'
lib_ext='.a'
libc='/usr/@@XBPS_CROSS_TRIPLET@@/usr/lib/libc-2.20.so'
libperl='libperl.so'
libpth='/usr/@@XBPS_CROSS_TRIPLET@@/usr/lib /usr/local/lib /usr/lib'
libs='-lnsl -lgdbm -ldb -ldl -lm -lcrypt -lutil -lpthread -lc -lgdbm_compat'
libsdirs=' /usr/@@XBPS_CROSS_TRIPLET@@/usr/lib'
libsfiles=' libnsl.so libgdbm.so libdb.so libdl.so libm.so libcrypt.so libutil.so libpthread.so libc.so libgdbm_compat.so'
libsfound=' /usr/@@XBPS_CROSS_TRIPLET@@/usr/lib/libnsl.so /usr/@@XBPS_CROSS_TRIPLET@@/usr/lib/libgdbm.so /usr/@@XBPS_CROSS_TRIPLET@@/usr/lib/libdb.so /usr/@@XBPS_CROSS_TRIPLET@@/usr/lib/libdl.so /usr/@@XBPS_CROSS_TRIPLET@@/usr/lib/libm.so /usr/@@XBPS_CROSS_TRIPLET@@/usr/lib/libcrypt.so /usr/@@XBPS_CROSS_TRIPLET@@/usr/lib/libutil.so /usr/@@XBPS_CROSS_TRIPLET@@/usr/lib/libpthread.so /usr/@@XBPS_CROSS_TRIPLET@@/usr/lib/libc.so /usr/@@XBPS_CROSS_TRIPLET@@/usr/lib/libgdbm_compat.so'
libspath=' /usr/@@XBPS_CROSS_TRIPLET@@/usr/lib /usr/lib'
libswanted='sfio socket inet nsl nm ndbm gdbm dbm db malloc dl dld ld sun m crypt sec util pthread c cposix posix ucb BSD gdbm_compat'
libswanted_uselargefiles=''
line=''
lint=''
lkflags=''
ln='ln'
lns='/usr/bin/ln -s'
localtime_r_proto='REENTRANT_PROTO_S_TS'
locincpth='/usr/local/include /opt/local/include /usr/gnu/include /opt/gnu/include /usr/GNU/include /opt/GNU/include'
loclibpth='/usr/local/lib /opt/local/lib /usr/gnu/lib /opt/gnu/lib /usr/GNU/lib /opt/GNU/lib'
longdblsize='8'
longlongsize='8'
longsize='4'
lp=''
lpr=''
ls='ls'
lseeksize='8'
lseektype='off_t'
mad='undef'
madlyh=''
madlyobj=''
madlysrc=''
mail=''
mailx=''
make='make'
make_set_make='#'
mallocobj=''
mallocsrc=''
malloctype='void *'
man1dir='/usr/share/man/man1'
man1direxp='/usr/share/man/man1'
man1ext='1p'
man3dir='/usr/share/man/man3'
man3direxp='/usr/share/man/man3'
man3ext='3p'
mips_type=''
mistrustnm=''
mkdir='mkdir'
mmaptype='void *'
modetype='mode_t'
more='more'
multiarch='undef'
mv=''
myarchname='armv6l-linux'
mydomain='.nonet'
myhostname='venus'
myuname='linux venus 3.16.0 #14 smp preempt fri aug 29 22:26:32 cest 2014 armv7l gnulinux '
n='-n'
need_va_copy='undef'
netdb_hlen_type='size_t'
netdb_host_type='const void *'
netdb_name_type='const char *'
netdb_net_type='in_addr_t'
nm='nm'
nm_opt=''
nm_so_opt='--dynamic'
nonxs_ext='Archive/Tar Attribute/Handlers autodie AutoLoader autouse base B/Debug bignum Carp CGI Config/Perl/V constant CPAN CPAN/Meta CPAN/Meta/Requirements CPAN/Meta/YAML Devel/SelfStubber Digest Dumpvalue encoding/warnings Env Errno experimental Exporter ExtUtils/CBuilder ExtUtils/Command ExtUtils/Constant ExtUtils/Install ExtUtils/MakeMaker ExtUtils/Manifest ExtUtils/Miniperl ExtUtils/ParseXS FileCache File/Fetch File/Find File/Path File/Temp Filter/Simple Getopt/Long HTTP/Tiny I18N/Collate I18N/LangTags if IO/Compress IO/Socket/IP IO/Zlib IPC/Cmd IPC/Open3 JSON/PP lib libnet Locale/Codes Locale/Maketext Locale/Maketext/Simple Math/BigInt Math/BigRat Math/Complex Memoize Module/Build Module/CoreList Module/Load Module/Load/Conditional Module/Loaded Module/Metadata Net/Ping NEXT Package/Constants Params/Check parent Parse/CPAN/Meta perlfaq PerlIO/via/QuotedPrint Perl/OSType Pod/Checker Pod/Escapes Pod/Functions Pod/Html podlators Pod/Parser Pod/Perldoc Pod/Simple Pod/Usage Safe Search/Dict SelfLoader Term/ANSIColor Term/Cap Term/Complete Term/ReadLine Test Test/Harness Test/Simple Text/Abbrev Text/Balanced Text/ParseWords Text/Tabs Thread/Queue Thread/Semaphore Tie/File Tie/Memoize Tie/RefHash Time/Local version XSLoader'
nroff='nroff'
nvEUformat='"E"'
nvFUformat='"F"'
nvGUformat='"G"'
nv_overflows_integers_at='256.0*256.0*256.0*256.0*256.0*256.0*2.0*2.0*2.0*2.0*2.0'
nv_preserves_uv_bits='32'
nveformat='"e"'
nvfformat='"f"'
nvgformat='"g"'
nvsize='8'
nvtype='double'
o_nonblock='O_NONBLOCK'
obj_ext='.o'
old_pthread_create_joinable=''
optimize='-O2 @@XBPS_CROSS_CFLAGS@@'
orderlib='false'
osname='linux'
osvers='3.10.18_4'
otherlibdirs=' '
package='perl5'
pager='/usr/bin/less -R'
passcat='cat /etc/passwd'
patchlevel='20'
path_sep=':'
perl5='/usr/bin/perl'
perl='perl'
perl_patchlevel=''
perl_static_inline='static __inline__'
perladmin='juan@void-rpi.nonet'
perllibs='-lnsl -ldl -lm -lcrypt -lutil -lpthread -lc'
perlpath='/usr/bin/perl'
pg='pg'
phostname='hostname'
pidtype='pid_t'
plibpth='/lib/@@XBPS_CROSS_TRIPLET@@/4.7.3 /lib /usr/lib/@@XBPS_CROSS_TRIPLET@@/4.7.3 /usr/lib'
pmake=''
pr=''
prefix='/usr'
prefixexp='/usr'
privlib='/usr/share/perl5/core_perl'
privlibexp='/usr/share/perl5/core_perl'
procselfexe='"/proc/self/exe"'
prototype='define'
ptrsize='4'
quadkind='3'
quadtype='long long'
randbits='48'
randfunc='Perl_drand48'
random_r_proto='REENTRANT_PROTO_I_St'
randseedtype='U32'
ranlib=':'
rd_nodata='-1'
readdir64_r_proto='REENTRANT_PROTO_I_TSR'
readdir_r_proto='REENTRANT_PROTO_I_TSR'
revision='5'
rm='rm'
rm_try='/usr/bin/rm -f try try a.out .out try.[cho] try..o core core.try* try.core*'
rmail=''
run=''
runnm='false'
sGMTIME_max='2147483647'
sGMTIME_min='-2147483648'
sLOCALTIME_max='2147483647'
sLOCALTIME_min='-2147483648'
sPRIEUldbl='"E"'
sPRIFUldbl='"F"'
sPRIGUldbl='"G"'
sPRIXU64='"LX"'
sPRId64='"Ld"'
sPRIeldbl='"e"'
sPRIfldbl='"f"'
sPRIgldbl='"g"'
sPRIi64='"Li"'
sPRIo64='"Lo"'
sPRIu64='"Lu"'
sPRIx64='"Lx"'
sSCNfldbl='"f"'
sched_yield='sched_yield()'
scriptdir='/usr/bin'
scriptdirexp='/usr/bin'
sed='sed'
seedfunc='Perl_drand48_init'
selectminbits='32'
selecttype='fd_set *'
sendmail=''
setgrent_r_proto='0'
sethostent_r_proto='0'
setlocale_r_proto='0'
setnetent_r_proto='0'
setprotoent_r_proto='0'
setpwent_r_proto='0'
setservent_r_proto='0'
sh='/bin/sh'
shar=''
sharpbang='#!'
shmattype='void *'
shortsize='2'
shrpenv=''
shsharp='true'
sig_count='65'
sig_name='ZERO HUP INT QUIT ILL TRAP ABRT BUS FPE KILL USR1 SEGV USR2 PIPE ALRM TERM STKFLT CHLD CONT STOP TSTP TTIN TTOU URG XCPU XFSZ VTALRM PROF WINCH IO PWR SYS NUM32 NUM33 RTMIN NUM35 NUM36 NUM37 NUM38 NUM39 NUM40 NUM41 NUM42 NUM43 NUM44 NUM45 NUM46 NUM47 NUM48 NUM49 NUM50 NUM51 NUM52 NUM53 NUM54 NUM55 NUM56 NUM57 NUM58 NUM59 NUM60 NUM61 NUM62 NUM63 RTMAX IOT CLD POLL UNUSED '
sig_name_init='"ZERO", "HUP", "INT", "QUIT", "ILL", "TRAP", "ABRT", "BUS", "FPE", "KILL", "USR1", "SEGV", "USR2", "PIPE", "ALRM", "TERM", "STKFLT", "CHLD", "CONT", "STOP", "TSTP", "TTIN", "TTOU", "URG", "XCPU", "XFSZ", "VTALRM", "PROF", "WINCH", "IO", "PWR", "SYS", "NUM32", "NUM33", "RTMIN", "NUM35", "NUM36", "NUM37", "NUM38", "NUM39", "NUM40", "NUM41", "NUM42", "NUM43", "NUM44", "NUM45", "NUM46", "NUM47", "NUM48", "NUM49", "NUM50", "NUM51", "NUM52", "NUM53", "NUM54", "NUM55", "NUM56", "NUM57", "NUM58", "NUM59", "NUM60", "NUM61", "NUM62", "NUM63", "RTMAX", "IOT", "CLD", "POLL", "UNUSED", 0'
sig_num='0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 6 17 29 31 '
sig_num_init='0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 6, 17, 29, 31, 0'
sig_size='69'
signal_t='void'
sitearch='/usr/lib/perl5/site_perl'
sitearchexp='/usr/lib/perl5/site_perl'
sitebin='/usr/bin'
sitebinexp='/usr/bin'
sitehtml1dir=''
sitehtml1direxp=''
sitehtml3dir=''
sitehtml3direxp=''
sitelib='/usr/share/perl5/site_perl'
sitelib_stem='/usr/share/perl5/site_perl'
sitelibexp='/usr/share/perl5/site_perl'
siteman1dir='/usr/share/man/man1'
siteman1direxp='/usr/share/man/man1'
siteman3dir='/usr/share/man/man3'
siteman3direxp='/usr/share/man/man3'
siteprefix='/usr'
siteprefixexp='/usr'
sitescript='/usr/bin'
sitescriptexp='/usr/bin'
sizesize='4'
sizetype='size_t'
sleep=''
smail=''
so='so'
sockethdr=''
socketlib=''
socksizetype='socklen_t'
sort='sort'
spackage='Perl5'
spitshell='cat'
srand48_r_proto='REENTRANT_PROTO_I_LS'
srandom_r_proto='REENTRANT_PROTO_I_TS'
src='.'
ssizetype='ssize_t'
st_ino_sign='1'
st_ino_size='8'
startperl='#!/usr/bin/perl'
startsh='#!/bin/sh'
static_ext=' '
stdchar='char'
stdio_base='((fp)->_IO_read_base)'
stdio_bufsiz='((fp)->_IO_read_end - (fp)->_IO_read_base)'
stdio_cnt='((fp)->_IO_read_end - (fp)->_IO_read_ptr)'
stdio_filbuf=''
stdio_ptr='((fp)->_IO_read_ptr)'
stdio_stream_array=''
strerror_r_proto='REENTRANT_PROTO_B_IBW'
strings='/usr/include/string.h'
submit=''
subversion='@@PERL_SUBVERSION@@'
sysman='/usr/share/man/man1'
tail=''
tar=''
targetarch=''
targetdir=''
targetenv=''
targethost=''
targetmkdir=''
targetport=''
targetsh='/bin/sh'
tbl=''
tee=''
test='test'
timeincl='/usr/include/sys/time.h /usr/include/time.h '
timetype='time_t'
tmpnam_r_proto='REENTRANT_PROTO_B_B'
to=':'
touch='touch'
tr='tr'
trnl='\n'
troff=''
ttyname_r_proto='REENTRANT_PROTO_I_IBW'
u16size='2'
u16type='unsigned short'
u32size='4'
u32type='unsigned long'
u64size='8'
u64type='unsigned long long'
u8size='1'
u8type='unsigned char'
uidformat='"lu"'
uidsign='1'
uidsize='4'
uidtype='uid_t'
uname='uname'
uniq='uniq'
uquadtype='unsigned long long'
use5005threads='undef'
use64bitall='undef'
use64bitint='undef'
usecrosscompile='undef'
usedevel='undef'
usedl='define'
usedtrace='undef'
usefaststdio='undef'
useithreads='define'
usekernprocpathname='undef'
uselargefiles='define'
uselongdouble='undef'
usemallocwrap='define'
usemorebits='undef'
usemultiplicity='define'
usemymalloc='n'
usenm='false'
usensgetexecutablepath='undef'
useopcode='true'
useperlio='define'
useposix='true'
usereentrant='undef'
userelocatableinc='undef'
usesfio='false'
useshrplib='true'
usesitecustomize='undef'
usesocks='undef'
usethreads='define'
usevendorprefix='define'
useversionedarchname='undef'
usevfork='false'
usrinc='/usr/include'
uuname=''
uvXUformat='"lX"'
uvoformat='"lo"'
uvsize='4'
uvtype='unsigned long'
uvuformat='"lu"'
uvxformat='"lx"'
vaproto='define'
vendorarch='/usr/lib/perl5/vendor_perl'
vendorarchexp='/usr/lib/perl5/vendor_perl'
vendorbin='/usr/bin'
vendorbinexp='/usr/bin'
vendorhtml1dir=' '
vendorhtml1direxp=''
vendorhtml3dir=' '
vendorhtml3direxp=''
vendorlib='/usr/share/perl5/vendor_perl'
vendorlib_stem='/usr/share/perl5/vendor_perl'
vendorlibexp='/usr/share/perl5/vendor_perl'
vendorman1dir='/usr/share/man/man1'
vendorman1direxp='/usr/share/man/man1'
vendorman3dir='/usr/share/man/man3'
vendorman3direxp='/usr/share/man/man3'
vendorprefix='/usr'
vendorprefixexp='/usr'
vendorscript='/usr/bin'
vendorscriptexp='/usr/bin'
version='@@PERL_VERSION@@'
version_patchlevel_string='@@PERL_VERSION@@'
versiononly='undef'
vi=''
voidflags='15'
xlibpth='/usr/lib/386 /lib/386'
yacc='yacc'
yaccflags=''
zcat=''
zip='zip'
PERL_REVISION=5
PERL_VERSION=20
PERL_SUBVERSION=1
PERL_API_REVISION=5
PERL_API_VERSION=20
PERL_API_SUBVERSION=0
PERL_PATCHLEVEL=''
PERL_CONFIG_SH=true
: Variables propagated from previous config.sh file.
libdb_needs_pthread='N'
|
#!/bin/bash
if [ "$#" -lt 2 ];
then
echo "Usage: <nworkers> <path_in_HDFS> [param=val]"
exit -1
fi
# put the local training file to HDFS
hadoop fs -rm -r -f $2/mushroom.fm.model
hadoop fs -put ../data/agaricus.txt.train $2/data
hadoop fs -put ../data/agaricus.txt.test $2/data
# submit to hadoop
../../dmlc-core/tracker/dmlc_yarn.py -n $1 --vcores 2 ./fm.dmlc data=hdfs://$2/data/agaricus.txt.train val_data=hdfs://$2/data/agaricus.txt.test model_out=hdfs://$2/mushroom.fm.model max_lbfgs_iter=50 nfactor=8 early_stop=10 "${*:3}"
# get the final model file
hadoop fs -get $2/mushroom.fm.model ./fm.model
../../dmlc-core/yarn/run_hdfs_prog.py ./fm.dmlc data=../data/agaricus.txt.test task=pred model_in=fm.model
../../dmlc-core/yarn/run_hdfs_prog.py ./fm.dmlc task=dump model_in=fm.model name_dump=weight.txt
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.filing = void 0;
var filing = {
"viewBox": "0 0 512 512",
"children": [{
"name": "g",
"attribs": {},
"children": [{
"name": "path",
"attribs": {
"d": "M381,128.6H132.1c-12.1,0-19.5,0-19.5,20.4v28.1h288V149C400.6,128.6,393.2,128.6,381,128.6z"
},
"children": [{
"name": "path",
"attribs": {
"d": "M381,128.6H132.1c-12.1,0-19.5,0-19.5,20.4v28.1h288V149C400.6,128.6,393.2,128.6,381,128.6z"
},
"children": []
}]
}, {
"name": "path",
"attribs": {
"d": "M333,96.5H180c-13.1,0-19.5,0.3-19.5,18.7h192C352.4,96.8,346.1,96.5,333,96.5z"
},
"children": [{
"name": "path",
"attribs": {
"d": "M333,96.5H180c-13.1,0-19.5,0.3-19.5,18.7h192C352.4,96.8,346.1,96.5,333,96.5z"
},
"children": []
}]
}, {
"name": "path",
"attribs": {
"d": "M432.4,169.6l-15.9-9.4v32.3h-321v-32.3l-15.2,9.4c-14.3,8.9-17.8,15.3-15,40.9l17.5,184.8c3.7,20.7,15.9,21.2,24,21.2\r\n\t\th299.9c8.1,0,20.2-0.5,23.9-21.2l17.2-184.4C450.1,186.5,445.8,178.1,432.4,169.6z"
},
"children": [{
"name": "path",
"attribs": {
"d": "M432.4,169.6l-15.9-9.4v32.3h-321v-32.3l-15.2,9.4c-14.3,8.9-17.8,15.3-15,40.9l17.5,184.8c3.7,20.7,15.9,21.2,24,21.2\r\n\t\th299.9c8.1,0,20.2-0.5,23.9-21.2l17.2-184.4C450.1,186.5,445.8,178.1,432.4,169.6z"
},
"children": []
}]
}]
}]
};
exports.filing = filing;
|
#!/bin/bash
# This script tests the basic behavior of record-minmax
#
# HOW TO USE
#
# ./test_record_minmax.sh <path/to/test.config> <path/to/work_dir> <TEST 1> <TEST 2> ...
# test.config : set ${RECORD_MINMAX_PATH} and ${CIRCLE2CIRCLE_PATH}
# work_dir : build directory of quantization-value-test (ex: build/compiler/quantization-value-test)
SOURCE_PATH="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
GEN_SCRIPT_PATH="${SOURCE_PATH}/gen_h5_explicit_inputs.py"
COMPARE_SCRIPT_PATH="${SOURCE_PATH}/compare_tensors.py"
CONFIG_PATH="$1"; shift
BIN_PATH=$(dirname "${CONFIG_PATH}")
TEST_INPUT_PATH="${SOURCE_PATH}/test_inputs"
WORKDIR="$1"; shift
VIRTUALENV="${WORKDIR}/venv_1_13_2"
source "${CONFIG_PATH}"
echo "-- Found RECORD-MINMAX: ${RECORD_MINMAX_PATH}"
echo "-- Found CIRCLE_TENSORDUMP: ${CIRCLE_TENSORDUMP_PATH}"
echo "-- Found workdir: ${WORKDIR}"
TESTED=()
PASSED=()
FAILED=()
pushd "${WORKDIR}"
while [ "$1" != "" ]; do
MODELNAME=$1; shift
GRANULARITY=$1; shift
DTYPE=$1; shift
TESTCASE="${MODELNAME}.${GRANULARITY}.${DTYPE}"
TESTED+=("${TESTCASE}")
TESTCASE_FILE="${WORKDIR}/${TESTCASE}"
TEST_RESULT_FILE="${BIN_PATH}/${TESTCASE}"
PASSED_TAG="${TEST_RESULT_FILE}.record_minmax.passed"
rm -f "${PASSED_TAG}"
cat > "${TEST_RESULT_FILE}_record_minmax.log" <(
exec 2>&1
set -ex
# Generate h5 input data
source "${VIRTUALENV}/bin/activate"
"${VIRTUALENV}/bin/python" "${GEN_SCRIPT_PATH}" \
--model "${WORKDIR}/${MODELNAME}.tflite" \
--input "${TEST_INPUT_PATH}/${MODELNAME}/${GRANULARITY}/${DTYPE}" \
--output "${TESTCASE_FILE}.input.h5"
if [[ $? -ne 0 ]]; then
echo "FAILED TO GENERATE INPUT"
continue
fi
# Run record-minmax
"${RECORD_MINMAX_PATH}" \
"${TEST_RESULT_FILE}.fake_quantized.circle" \
"${TEST_RESULT_FILE}.input.h5" \
"${TEST_RESULT_FILE}.minmax_recorded.circle"
# Dump min/max values (circle-tensordump)
"${CIRCLE_TENSORDUMP_PATH}" \
"${TEST_RESULT_FILE}.minmax_recorded.circle" \
--tensors_to_hdf5 "${TEST_RESULT_FILE}.minmax_recorded.circle.h5"
# Compare result
"${VIRTUALENV}/bin/python" "${COMPARE_SCRIPT_PATH}" \
--input_h5 "${TEST_RESULT_FILE}.minmax_recorded.circle.h5" \
--expect_dir "${SOURCE_PATH}/expected_outputs/${MODELNAME}/${GRANULARITY}/${DTYPE}/record_minmax" \
--mode record_minmax
if [[ $? -eq 0 ]]; then
touch "${PASSED_TAG}"
fi
)
if [[ -f "${PASSED_TAG}" ]]; then
PASSED+=("$TESTCASE")
else
FAILED+=("$TESTCASE")
fi
done
popd
if [[ ${#TESTED[@]} -ne ${#PASSED[@]} ]]; then
echo "FAILED"
for TEST in "${FAILED[@]}"
do
echo "- ${TEST}"
done
exit 255
fi
echo "PASSED"
exit 0
|
export default function(html) {
var script = '\nif (html) html.innerHTML = `' + html.replace(/`/g, '\\`').replace(/\${/g, '\\${') + '`;\n\n';
script += `
const scripts = [...html.getElementsByTagName('script')];
var hasUnknownType = false;
for (var idx in scripts) {
const script = scripts[idx];
var tag = document.createElement("script");
script.getAttributeNames().forEach(function(name) {
if (name != 'id') tag.setAttribute(name, script.getAttribute(name));
});
if (script.src || script.type == 'module') {
if (script.type == 'module')
tag.innerHTML = script.innerHTML + ';hal9ScriptLoaded();';
else
tag.src = script.src;
script.remove();
const loaded = new Promise((resolve, reject) => {
const errorHandler = function(e) {
window.removeEventListener('error', errorHandler);
reject(e.message);
}
const loadHandler = function() {
window.removeEventListener('error', errorHandler);
resolve();
}
window.addEventListener('error', errorHandler);
window.hal9ScriptLoaded = loadHandler;
tag.addEventListener('load', loadHandler);
tag.addEventListener('error', errorHandler);
tag.addEventListener('abort', errorHandler);
});
html.appendChild(tag);
await loaded;
}
else if (!script.type || script.type == 'text/javascript' || script.type == 'text/jsx' || script.type == 'text/jsx' || script.type == 'text/babel') {
var code = script.innerHTML;
if (script.type == 'text/jsx' || script.type == 'text/babel')
code = Babel.transform(code, { presets: ['env', 'react'] }).code;
const fn = new Function(Object.keys(_hal9_params), code);
fn(...Object.values(_hal9_params));
}
else {
hasUnknownType = true;
}
};
if (hasUnknownType) {
window.dispatchEvent(new Event('DOMContentLoaded'));
}
`;
return script;
}
|
<filename>20_debugging/01_debugging.py<gh_stars>0
#!/usr/bin/python3
'''
Atencao
A maioria dos codigos desse arquivo estao comentados pois os mesmos geram
exececoes para executados utilizado o atalho no Code de Ctrl+Alt+N
'''
'''
Podemos gerar nossas próprias execocoes pno codigo
Gerar uma excecao e uma maneira de dizer "Pare de executar o codigo dessa
funcao e passe a executar do programa para a instrucao except"
As exceoes sao geradas com uma instrucao raise. No codigo uma instrucao raise
é constuitda das seguintes partes:
- a palavra-chave raise;
- uma chamada a funcao Exception();
- Uma string com uma mensagem de erro conveniente passada para a funcao
Exception()
Se nao houver nenhuma instrucao try e except para cuidar da instrucao raise
que gerou a execao, o programar simplesmente falhara e exibira a mensagem de
erro da excecao
'''
# Exemplo
# raise Exception ('this is the erro message')
print('Executar o script 02_boxprint.py que tem mais detalhes')
'''
Obetendo o traceback com uma string
O traceback inclui:
a mensagem de erro
o número da linha que provocou o erro e
a sequencia de chamadas de funcao que resultou o erro
Esse sequencia de chamadas se chama pilha de chamada (call stack)
'''
print('Executar o script 03_errorExample_v1.py que tem mais detalhes')
'''
O Traceback é exibido pelo python sempre que uma exececao gerada nao é tratada
Porem tambem podemos obtelo como uma string chamando traceback.format_exc().
Essa funcao será útill se quisermos obter informacoes do traceback de uma
execacao, mas também quisermos que uma instrucao execept trate a execacao de
modo elegante
Por exemplo, em vez de fazer o programa falha assim que uma excecao ocorrer,
podemos gravar as informações de traceback em um arquivo de log e manter o
programa funcionando.
'''
print('Executar o script 03_errorExample_v2.py que tem mais detalhes')
'''
Assercoes
'''
# Fonte
# Livro Automatiando tarefas maçantes com python, capitulo 10
|
import { getRepository } from 'typeorm';
import AppError from '@shared/errors/AppError';
import Group from '@modules/groups/infra/typeorm/models/Group';
import ICreateGroupRepository from '../repositories/groups'
import {inject,injectable} from 'tsyringe';
interface Request {
type: string;
description: string;
cm1: string;
cm1u: string;
cm1r1: string;
cm1r2: string;
cm1e: string;
cm2: string;
cm2c: string;
cm2e: string;
cm2r: string;
cm2u: string;
cm2d: string;
cm3: string;
cm3a1: string;
cm3a2: string;
cm3a3: string;
cm4: string;
cm4a1: string;
cm4a2: string;
cm4a3: string;
cm5: string;
cm5a1: string;
cm5a1c: string;
cm5a1e: string;
cm5a1r: string;
cm5a1u: string;
cm5a1d:string;
cm5a2:string;
cm5a2c:string;
cm5a2e:string;
cm5a2r:string;
cm5a2u:string;
cm5a2d:string;
cm5a3:string;
cm6:string;
cm6a1:string;
cm6a1u:string;
cm6a2:string;
cm6a2c:string;
cm6a2u:string;
cm6a3:string;
cm6a3u1:string;
cm6a3u2:string;
cm6a4:string;
cm6a4c1:string;
cm6a4c2:string;
cm6a4c3:string;
cm6a5:string;
cm6a5u1:string;
cm6a5u2:string;
cm7:string;
cm7a1:string;
cm7a2:string;
cm8:string;
cm8a1:string;
cm8a2:string;
am1:string;
am1r1:string;
am1r2:string;
am1r3:string;
am1r4:string;
am1r5:string;
am1c1:string;
am1e:string;
am2:string;
am2a1:string;
am2a1c:string;
am2a1te:string;
AM2A2:string;
AM2A2C:string;
AM2A2U:string;
AM2A2D:string;
AM2A3:string;
AM2A3U:string;
AM3:string;
AM3A1:string;
AM3A1C:string;
AM3A1R:string;
AM3A1E:string;
AM3A2:string;
AM3A2R:string;
AM3A2E:string;
AM4:string;
AM4A1:string;
AM4A1C:string;
AM4A1E:string;
AM4A1R:string;
AM4A2:string;
AM4A2C:string;
AM4A2U:string;
AM4A2R:string;
AM4A2E:string;
AM5:string;
AM6:string;
AM6U1:string;
AM6U2:string;
AM6U3:string;
AM6U4:string;
}
@injectable()
class UpdateGroupService {
constructor(
@inject('GroupRepository')
private GroupRepository:ICreateGroupRepository){}
public async execute({
type,
description,
cm1,
cm1u,
cm1r1,
cm1r2,
cm1e,
cm2,
cm2c,
cm2e,
cm2r,
cm2u,
cm2d,
cm3,
cm3a1,
cm3a2,
cm3a3,
cm4,
cm4a1,
cm4a2,
cm4a3,
cm5,
cm5a1,
cm5a1c,
cm5a1e,
cm5a1r,
cm5a1u,
cm5a1d,
cm5a2,
cm5a2c,
cm5a2e,
cm5a2r,
cm5a2u,
cm5a2d,
cm5a3,
cm6,
cm6a1,
cm6a1u,
cm6a2,
cm6a2c,
cm6a2u,
cm6a3,
cm6a3u1,
cm6a3u2,
cm6a4,
cm6a4c1,
cm6a4c2,
cm6a4c3,
cm6a5,
cm6a5u1,
cm6a5u2,
cm7,
cm7a1,
cm7a2,
cm8,
cm8a1,
cm8a2,
am1,
am1r1,
am1r2,
am1r3,
am1r4,
am1r5,
am1c1,
am1e,
am2,
am2a1,
am2a1c,
am2a1te,
AM2A2,
AM2A2C,
AM2A2U,
AM2A2D,
AM2A3,
AM2A3U,
AM3,
AM3A1,
AM3A1C,
AM3A1R,
AM3A1E,
AM3A2,
AM3A2R,
AM3A2E,
AM4,
AM4A1,
AM4A1C,
AM4A1E,
AM4A1R,
AM4A2,
AM4A2C,
AM4A2U,
AM4A2R,
AM4A2E,
AM5,
AM6,
AM6U1,
AM6U2,
AM6U3,
AM6U4,
}: Request): Promise<Group> {
const checkGroupExists = await this.GroupRepository.findByType(
type
);
if (!checkGroupExists) {
throw new AppError('Group does not exists');
}
checkGroupExists.type=type;
checkGroupExists.description=description;
checkGroupExists.cm1=cm1;
checkGroupExists.cm1u=cm1u;
checkGroupExists.cm1r1=cm1r1;
checkGroupExists.cm1r2=cm1r2;
checkGroupExists.cm1e=cm1e;
checkGroupExists.cm2=cm2;
checkGroupExists.cm2c=cm2c;
checkGroupExists.cm2e=cm2e;
checkGroupExists.cm2r=cm2r;
checkGroupExists.cm2u=cm2u;
checkGroupExists.cm2d=cm2d;
checkGroupExists.cm3=cm3;
checkGroupExists. cm3a1= cm3a1;
checkGroupExists. cm3a2= cm3a2;
checkGroupExists. cm3a3= cm3a3;
checkGroupExists. cm4= cm4;
checkGroupExists. cm4a1= cm4a1;
checkGroupExists. cm4a2= cm4a2;
checkGroupExists.cm4a3= cm4a3;
checkGroupExists. cm5= cm5;
checkGroupExists. cm5a1= cm5a1;
checkGroupExists.cm5a1c=cm5a1c;
checkGroupExists.cm5a1e=cm5a1e;
checkGroupExists.cm5a1r=cm5a1r;
checkGroupExists.cm5a1u=cm5a1u;
checkGroupExists. cm5a1d=cm5a1d;
checkGroupExists .cm5a2=cm5a2;
checkGroupExists .cm5a2c=cm5a2c;
checkGroupExists .cm5a2e=cm5a2e;
checkGroupExists .cm5a2r=cm5a2r;
checkGroupExists .cm5a2u=cm5a2u;
checkGroupExists .cm5a2d=cm5a2d;
checkGroupExists .cm5a3=cm5a3;
checkGroupExists. cm6= cm6;
checkGroupExists. cm6a1= cm6a1;
checkGroupExists. cm6a1u= cm6a1u;
checkGroupExists. cm6a2= cm6a2;
checkGroupExists. cm6a2c= cm6a2c;
checkGroupExists. cm6a2u= cm6a2u;
checkGroupExists. cm6a3= cm6a3;
checkGroupExists.cm6a3u1=cm6a3u1;
checkGroupExists.cm6a3u2=cm6a3u2;
checkGroupExists. cm6a4= cm6a4;
checkGroupExists.cm6a4c1=cm6a4c1;
checkGroupExists.cm6a4c2=cm6a4c2;
checkGroupExists.cm6a4c3=cm6a4c3;
checkGroupExists. cm6a5= cm6a5;
checkGroupExists.cm6a5u1=cm6a5u1;
checkGroupExists.cm6a5u2=cm6a5u2;
checkGroupExists. cm7= cm7;
checkGroupExists. cm7a1= cm7a1;
checkGroupExists. cm7a2= cm7a2;
checkGroupExists. cm8= cm8;
checkGroupExists. cm8a1= cm8a1;
checkGroupExists. cm8a2= cm8a2;
checkGroupExists. am1= am1;
checkGroupExists. am1r1= am1r1;
checkGroupExists. am1r2= am1r2;
checkGroupExists. am1r3= am1r3;
checkGroupExists. am1r4= am1r4;
checkGroupExists. am1r5= am1r5;
checkGroupExists. am1c1= am1c1;
checkGroupExists. am1e= am1e;
checkGroupExists. am2= am2;
checkGroupExists. am2a1= am2a1;
checkGroupExists. am2a1c= am2a1c;
checkGroupExists.am2a1te=am2a1te;
checkGroupExists. AM2A2= AM2A2;
checkGroupExists. AM2A2C= AM2A2C;
checkGroupExists. AM2A2U= AM2A2U;
checkGroupExists. AM2A2D= AM2A2D;
checkGroupExists. AM2A3= AM2A3;
checkGroupExists. AM2A3U= AM2A3U;
checkGroupExists. AM3= AM3;
checkGroupExists. AM3A1= AM3A1;
checkGroupExists. AM3A1C= AM3A1C;
checkGroupExists. AM3A1R= AM3A1R;
checkGroupExists. AM3A1E= AM3A1E;
checkGroupExists. AM3A2= AM3A2;
checkGroupExists. AM3A2R= AM3A2R;
checkGroupExists. AM3A2E= AM3A2E;
checkGroupExists. AM4= AM4;
checkGroupExists. AM4A1= AM4A1;
checkGroupExists. AM4A1C= AM4A1C;
checkGroupExists. AM4A1E= AM4A1E;
checkGroupExists. AM4A1R= AM4A1R;
checkGroupExists. AM4A2= AM4A2;
checkGroupExists. AM4A2C= AM4A2C;
checkGroupExists. AM4A2U= AM4A2U;
checkGroupExists. AM4A2R= AM4A2R;
checkGroupExists. AM4A2E= AM4A2E;
checkGroupExists. AM5= AM5;
checkGroupExists. AM6= AM6;
checkGroupExists. AM6U1= AM6U1;
checkGroupExists. AM6U2= AM6U2;
checkGroupExists. AM6U3= AM6U3;
checkGroupExists. AM6U4= AM6U4;
return this.GroupRepository.save(checkGroupExists)
}
}
export default UpdateGroupService;
|
console.log('app launched')
|
<gh_stars>1-10
#pragma once
#include "AutoGC.h"
#define accuracy double
#define arrtype accuracy *
#define create_arrayp(size, ...) new accuracy[size]{__VA_ARGS__}
#define Matrixp Matrix *
#define create_matrixp(...) new Matrix( __VA_ARGS__ )
#define Vectorp Vector *
#define create_verctorp(...) new Vector( __VA_ARGS__ )
#define create_verctorp_by_array(size, ...) new Vector(size, create_arrayp(size, __VA_ARGS__ ))
#define display_accuracy 3
namespace cpp_speech_features {
class Vector;
class Matrix
{
public:
Matrix(int col, int row);
Matrix(int col, int row, arrtype data);
Matrix(Matrixp b);
~Matrix();
accuracy get(int x);
accuracy get(int y, int x);
void set(int x, accuracy v);
void set(int y, int x, accuracy v);
int getColumn();
int getRow();
arrtype getData();
Vectorp getRow(int row);
void setRow(int row, Vectorp r);
Matrixp multiply(Matrixp b);
Matrixp multiply(accuracy b);
Matrixp divide(accuracy b);
Matrixp subtract(Matrixp b);
Matrixp add(Matrixp b);
Matrixp add(accuracy b);
Matrixp square();
Matrixp takeRow(int r1, int r2);
Matrixp logarithms();
Matrixp concatenate(Matrixp b);
Matrixp T();
Matrixp reshape(int row, int col);
Matrixp map(accuracy(*func)(int, int, accuracy));
Matrixp mapRow(Vectorp(*func)(int, Vectorp r));
void print(const char * tag= "");
protected:
arrtype pArray;
void createZerosArray(int size);
private:
int column;
int row;
};
}
|
/* CS261- Assignment 1 - Q. 0*/
/* Name: <NAME>
* Date: 07/01/2018
* Solution description:
*
* 1. In the main() function, declare an integer, x. Then assign it to a random integer value in
* the interval [0, 10]. Then print the value and address (using the address of operator) of x.
*
* 2. In fooA(int * iptr) function, print the value of the integer pointed to by iptr and the
* address pointed to by iptr. Change the value of the integer pointed to by iptr as instructed
* in the skeleton code. Print the address of iptr itself at the end.
*
* 3. In the main() function, following the call to fooA(..), print the value of x. Answer the
* following question in a comment right after printing the value of x.
* ** Is the value of x
* ** different than the value that was printed at first? Why or why not?
*
*
* 4. In fooB(int * jptr) function, print the value of the integer pointed to by jptr and the
* address pointed to by jptr. Then change the address stored in the pointer variable jptr
* as instructed in the skeleton code. Print the address of jptr itself at the end.
*
* 5. In the main function, following the call to fooB(..), print the value and address of x.
* Answer the following question in a comment right after printing the value and address of x:
*
* ** Are the value and address of x different than the value and address that were printed
* ** before the call to fooB(..)? Why or why not?
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void fooA(int* iptr){
/*Print the value and address of the integer pointed to by iptr*/
printf("Value of the integer pointed to by iptr* : %d. (In fooA func) \n", *iptr);
printf("Address of the integer pointed to by iptr* : %p. (In fooA func) \n", iptr);
/*Increment the value of the integer pointed to by iptr by 5*/
*iptr += 5;
/*Print the address of iptr itself*/
printf("Address of iptr itseld %p. (In fooA func) \n", &iptr);
}
void fooB(int* jptr){
/*Print the value and address of the integer pointed to by jptr*/
printf("Value of the integer pointed to by jptr* : %d. (In fooB func) \n", *jptr);
printf("Address of the integer pointed to by jptr* : %p. (In fooB func) \n", jptr);
/*Decrement jptr by 1*/
*jptr -= 1;
/*Print the address of jptr itself*/
printf("Address of jptr itseld %p. (In fooB func) \n", &jptr);
}
int main(){
/* Use current time as seet for random generator */
srand(time(0));
/*Declare an integer x and initialize it randomly to a value in [0,10] */
int x = rand() % 11;
/*Print the value and address of x*/
printf("Value of the integer of x : %d. (In main func) \n", x);
printf("Address of the integer of x : %p. (In main func) \n", &x);
/*Call fooA() with the address of x*/
fooA(&x);
/* Is the value of x different than the value that was printed at first? Why or why not? */
/* Yes. The value of x was changed when we called the fooA function. Since we passed the address
of integer x into the functino and used a pointer to point to its address and then deferenced
the address to modify content inside that memory stored, thus the acutal value in that specified
address was changed and when we call that address out by print the value of integer x, we got the
different x */
/*Print the value of x*/
printf("Value of the integer of x : %d. (In main func) \n", x);
/*Call fooB() with the address of x*/
fooB(&x);
/*Print the value and address of x*/
printf("Value of the integer of x : %d. (In main func) \n", x);
printf("Address of the integer of x : %p. (In main func) \n", &x);
/* Are the value and address of x different than the value and address that were
printed before the call to fooB(..)? Why or why not? */
/* Value changed from 11 to 10 since we passed the address of x into the function and modify the value
by deferencing the pointer but the actual address didn't change. Reason why the address kept the same
is because we didn't create a new space in memeory to store any new interger or value */
return 0;
}
|
<filename>test/misc/parse_datetime_test.rb<gh_stars>100-1000
require 'test_helper'
require 'active_scaffold_config_mock'
class DateTimeModel < ActiveRecord::Base
include ActiveScaffold::ActiveRecordPermissions::ModelUserAccess::Model
def self.columns
@columns ||= [ColumnMock.new('id', '', 'int(11)'), ColumnMock.new('run_at', '', 'datetime')]
end
def self.columns_hash
@columns_hash ||= Hash[columns.map { |c| [c.name, c] }]
end
def self.load_schema!
columns_hash.each do |name, column|
define_attribute(
name,
connection.lookup_cast_type_from_column(column),
default: column.default
)
end
end
end
class ParseDatetimeTest < MiniTest::Test
include ActiveScaffoldConfigMock
include ActiveScaffold::AttributeParams
include ActiveScaffold::Finder
def setup
DateTimeModel.load_schema! if Rails.version >= '5.0'
spanish = {
time: {
formats: {picker: '%a, %d %b %Y %H:%M:%S'}
},
date: {
day_names: %w[Domingo Lunes Martes Miércoles Jueves Viernes Sábado],
abbr_day_names: %w[Dom Lun Mar Mié Jue Vie Sáb],
month_names: [nil, 'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
abbr_month_names: [nil, 'Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
formats: {default: '%Y-%m-%d', long: '%d de %B de %Y'}
}
}
I18n.backend.store_translations :es, spanish
@config = config_for('date_time_model')
end
def teardown
I18n.locale = :en
end
def test_translate_to_english
I18n.locale = :es
assert_equal 'Mon, 03 Apr 2017 16:30:26', translate_datetime('Lun, 03 Abr 2017 16:30:26')
assert_equal 'Fri, 24 Mar 2017 16:30:26', translate_datetime('Vie, 24 Mar 2017 16:30:26')
assert_equal 'Tue, 28 Mar 2017 16:30:26', translate_datetime('Mar, 28 Mar 2017 16:30:26')
end
def test_translate_to_english_with_different_order
I18n.locale = :es
format = '%d %b %Y, %a, %H:%M:%S'
assert_equal '03 Apr 2017, Mon, 16:30:26', translate_datetime('03 Abr 2017, Lun, 16:30:26', format)
assert_equal '24 Mar 2017, Fri, 16:30:26', translate_datetime('24 Mar 2017, Vie, 16:30:26', format)
assert_equal '28 Mar 2017, Tue, 16:30:26', translate_datetime('28 Mar 2017, Mar, 16:30:26', format)
end
def test_translate_to_english_with_words
I18n.locale = :es
format = '%A, %d de %B %Y, %H:%M:%S'
assert_equal 'Monday, 03 de April de 2017, 16:30:26', translate_datetime('Lunes, 03 de Abril de 2017, 16:30:26', format)
assert_equal 'Friday, 24 de March de 2017, 16:30:26', translate_datetime('Viernes, 24 de Marzo de 2017, 16:30:26', format)
assert_equal 'Tuesday, 28 de March de 2017, 16:30:26', translate_datetime('Martes, 28 de Marzo de 2017, 16:30:26', format)
end
def test_condition_for_spanish_datetime
with_js_framework :jquery do
I18n.locale = :es
assert_equal Time.zone.local(2017, 4, 3, 16, 30, 26), condition_value('Lun, 03 Abr 2017 16:30:26')
assert_equal Time.zone.local(2017, 3, 24, 16, 30, 26), condition_value('Vie, 24 Mar 2017 16:30:26')
assert_equal Time.zone.local(2017, 3, 28, 16, 30, 26), condition_value('Mar, 28 Mar 2017 16:30:26')
end
end
def test_condition_for_english_datetime
with_js_framework :jquery do
assert_equal Time.zone.local(2017, 4, 3, 16, 30, 26), condition_value('Mon, 03 Apr 2017 16:30:26')
assert_equal Time.zone.local(2017, 3, 24, 16, 30, 26), condition_value('Fri, 24 Mar 2017 16:30:26')
assert_equal Time.zone.local(2017, 3, 28, 16, 30, 26), condition_value('Tue, 28 Mar 2017 16:30:26')
end
end
def test_condition_for_english_datetime_without_time
with_js_framework :jquery do
assert_equal Time.zone.local(2017, 4, 3, 0, 0, 0), condition_value('Mon, 03 Apr 2017')
assert_equal Time.zone.local(2017, 3, 24, 0, 0, 0), condition_value('Fri, 24 Mar 2017')
assert_equal Time.zone.local(2017, 3, 28, 0, 0, 0), condition_value('Tue, 28 Mar 2017')
end
end
def test_condition_for_default_datetime_without_time
assert_equal Time.zone.local(2017, 4, 3, 0, 0, 0), condition_value('2017-04-03')
assert_equal Time.zone.local(2017, 3, 24, 0, 0, 0), condition_value('2017-03-24')
assert_equal Time.zone.local(2017, 3, 28, 0, 0, 0), condition_value('2017-03-28')
end
def test_condition_for_english_datetime_without_seconds
with_js_framework :jquery do
assert_equal Time.zone.local(2017, 4, 3, 16, 30), condition_value('Mon, 03 Apr 2017 16:30')
assert_equal Time.zone.local(2017, 3, 24, 16, 30), condition_value('Fri, 24 Mar 2017 16:30')
assert_equal Time.zone.local(2017, 3, 28, 16, 30), condition_value('Tue, 28 Mar 2017 16:30')
end
end
def test_condition_for_default_datetime_without_seconds
assert_equal Time.zone.local(2017, 4, 3, 16, 30, 0), condition_value('2017-04-03 16:30')
assert_equal Time.zone.local(2017, 3, 24, 16, 30, 0), condition_value('2017-03-24 16:30')
assert_equal Time.zone.local(2017, 3, 28, 16, 30, 0), condition_value('2017-03-28 16:30')
end
def test_condition_for_time
assert_equal Time.current.change(hour: 16, min: 30), condition_value('16:30')
assert_equal Time.current.change(hour: 16, min: 30, sec: 26), condition_value('16:30:26')
end
def test_condition_for_datetime_with_zone
assert_equal ActiveSupport::TimeZone[3].local(2017, 4, 8, 16, 30, 0), condition_value('2017-04-08 16:30 +0300')
end
def test_condition_for_spanish_date
@config.columns[:run_at].options[:format] = :long
I18n.locale = :es
assert_equal Date.new(2017, 4, 3), condition_value('03 de Abril de 2017', :to_date)
assert_equal Date.new(2017, 3, 24), condition_value('24 de Marzo de 2017', :to_date)
assert_equal Date.new(2017, 3, 28), condition_value('28 de Marzo de 2017', :to_date)
end
def test_condition_for_english_date
@config.columns[:run_at].options[:format] = :long
assert_equal Date.new(2017, 4, 3), condition_value('April 03, 2017', :to_date)
assert_equal Date.new(2017, 3, 24), condition_value('March 24, 2017', :to_date)
assert_equal Date.new(2017, 3, 28), condition_value('March 28, 2017', :to_date)
end
private
def translate_datetime(value, format = nil)
format ||= I18n.t('time.formats.picker')
self.class.translate_days_and_months(value, format)
end
def condition_value(value, conversion = nil)
self.class.condition_value_for_datetime(@config.columns[:run_at], value, conversion || :to_time)
end
def params_hash?(value)
value.is_a? Hash
end
end
|
import React, { useState } from 'react';
import {
Grid,
InputAdornment,
Dialog,
Button,
TextField
} from '@material-ui/core';
import MailOutlineTwoToneIcon from '@material-ui/icons/MailOutlineTwoTone';
import people2 from '../../../assets/images/stock-photos/people-1.jpg';
import people1 from '../../../assets/images/stock-photos/people-1.jpg';
export default function LivePreviewExample() {
const [modal1, setModal1] = useState(false);
const [modal2, setModal2] = useState(false);
const toggle1 = () => setModal1(!modal1);
const toggle2 = () => setModal2(!modal2);
return (
<>
<div className="d-flex align-items-center justify-content-center flex-wrap">
<Button onClick={toggle1} className="btn-primary m-2">
Horizontal Recover Modal
</Button>
<Dialog
scroll="body"
maxWidth="lg"
open={modal1}
onClose={toggle1}
classes={{
paper: 'w-100 rounded border-0 shadow-sm-dark bg-white p-3 p-xl-0'
}}>
<Grid container spacing={0}>
<Grid item xl={6}>
<div className="hero-wrapper bg-composed-wrapper bg-second h-100 rounded br-xl-right-0">
<div className="flex-grow-1 w-100 d-flex align-items-center">
<div
className="bg-composed-wrapper--image rounded br-xl-right-0 opacity-4"
style={{ backgroundImage: 'url(' + people2 + ')' }}
/>
<div className="bg-composed-wrapper--bg bg-slick-carbon opacity-4 rounded br-xl-right-0" />
<div className="bg-composed-wrapper--content justify-content-center text-center text-xl-left p-5">
<div className="text-white text-center">
<h1 className="display-4 my-3 font-weight-bold">
Recover Password
</h1>
<p className="font-size-lg mb-0 px-4 text-white-50">
View any of the 5+ live previews we've set up to
learn why this dashboard template is the last one
you'll ever need!
</p>
</div>
</div>
</div>
</div>
</Grid>
<Grid item xl={6}>
<Grid item lg={8} xl={10} className="p-0 py-xl-5 mx-auto">
<div className="bg-white p-5 rounded">
<div>
<label className="font-weight-bold mb-2">
Email address
</label>
<TextField
fullWidth
variant="outlined"
id="textfield-email"
InputProps={{
startAdornment: (
<InputAdornment position="start">
<MailOutlineTwoToneIcon />
</InputAdornment>
)
}}
/>
</div>
<div className="text-center">
<Button
fullWidth
className="text-uppercase font-weight-bold font-size-sm mt-4 btn-primary">
Send password
</Button>
</div>
</div>
</Grid>
</Grid>
</Grid>
</Dialog>
<Button onClick={toggle2} className="btn-primary m-2">
Vertical Recover Modal
</Button>
<Dialog
scroll="body"
maxWidth="sm"
open={modal2}
onClose={toggle2}
classes={{ paper: 'w-100 rounded shadow-sm-dark border-0 bg-white' }}>
<div className="hero-wrapper bg-composed-wrapper bg-primary h-100 rounded-top">
<div className="flex-grow-1 w-100 d-flex align-items-center">
<div
className="bg-composed-wrapper--image rounded-top opacity-3"
style={{ backgroundImage: 'url(' + people1 + ')' }}
/>
<div className="bg-composed-wrapper--content text-center pt-5">
<div className="text-white">
<h1 className="display-3 my-3 font-weight-bold">
Recover Password
</h1>
<p className="font-size-lg mb-0 px-4 text-white-50">
View any of the 5+ live previews we've set up to learn
why this dashboard template is the last one you'll ever
need!
</p>
</div>
<div className="shape-container-top-1" style={{ margin: 0 }}>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 1440 320">
<path
fill="var(--white)"
fillOpacity="1"
d="M0,32L48,69.3C96,107,192,181,288,186.7C384,192,480,128,576,106.7C672,85,768,107,864,112C960,117,1056,107,1152,101.3C1248,96,1344,96,1392,96L1440,96L1440,320L1392,320C1344,320,1248,320,1152,320C1056,320,960,320,864,320C768,320,672,320,576,320C480,320,384,320,288,320C192,320,96,320,48,320L0,320Z"></path>
</svg>
</div>
</div>
</div>
</div>
<div
className="bg-white d-flex justify-content-center align-items-center flex-column rounded pt-4 pt-lg-0"
style={{ marginTop: '-80px' }}>
<Grid item lg={10} xl={9} className="z-over py-5 mx-auto">
<div className="px-2 py-3 py-lg-5">
<div>
<label className="font-weight-bold mb-2">Email address</label>
<TextField
fullWidth
variant="outlined"
id="textfield-email"
InputProps={{
startAdornment: (
<InputAdornment position="start">
<MailOutlineTwoToneIcon />
</InputAdornment>
)
}}
/>
</div>
<div className="text-center">
<Button
fullWidth
className="text-uppercase font-weight-bold font-size-sm mt-4 btn-primary">
Send password
</Button>
</div>
</div>
</Grid>
</div>
</Dialog>
</div>
</>
);
}
|
<reponame>eSCT/oppfin
package com.searchbox.engine.es;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.elasticsearch.action.search.MultiSearchResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import com.searchbox.core.dm.Collection;
import com.searchbox.core.dm.FieldAttribute;
import com.searchbox.core.dm.FieldAttribute.USE;
import com.searchbox.core.engine.AbstractSearchEngine;
import com.searchbox.core.engine.ManagedSearchEngine;
import com.searchbox.engine.FieldMappingSearchEngine;
public class ElasticSearch extends
AbstractSearchEngine<SearchRequestBuilder, MultiSearchResponse> implements
ManagedSearchEngine, FieldMappingSearchEngine {
protected ElasticSearch() {
super(SearchRequestBuilder.class, MultiSearchResponse.class);
}
protected ElasticSearch(String name) {
super(name, SearchRequestBuilder.class, MultiSearchResponse.class);
}
@Override
public MultiSearchResponse execute(Collection collection, SearchRequestBuilder query) {
// TODO Auto-generated method stub
return null;
}
@Override
public String getKeyForField(FieldAttribute fieldAttribute) {
// TODO Auto-generated method stub
return null;
}
@Override
public String getKeyForField(FieldAttribute fieldAttribute, USE operation) {
// TODO Auto-generated method stub
return null;
}
@Override
public Set<String> getAllKeysForField(FieldAttribute fieldAttribute) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean indexFile(Collection collection, File file) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean indexMap(Collection collection, Map<String, Object> fields) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean updateDataModel(Collection collection,
List<FieldAttribute> fieldAttributes) {
// TODO Auto-generated method stub
return false;
}
@Override
public void reloadEngine(Collection collection) {
// TODO Auto-generated method stub
}
@Override
public void register(Collection collection) {
// TODO Auto-generated method stub
}
@Override
public void reloadPlugins(Collection collection) {
// TODO Auto-generated method stub
}
@Override
public SearchRequestBuilder newQuery(Collection collection) {
// TODO Auto-generated method stub
return null;
}
}
|
SELECT *
FROM customers
ORDER BY date_of_birth DESC
LIMIT 1;
|
// wrapping_sub.rs
pub fn wrapping_sub(a: i32, b: i32) -> i32 {
a.wrapping_sub(b)
}
|
<reponame>weltam/idylfin
/**
* Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.financial.credit.schedulegeneration;
import java.util.NavigableSet;
import java.util.Set;
import java.util.TreeSet;
import javax.time.calendar.ZonedDateTime;
import com.opengamma.analytics.financial.credit.cds.ISDACurve;
import com.opengamma.analytics.financial.credit.creditdefaultswap.definition.CreditDefaultSwapDefinition;
import com.opengamma.analytics.financial.credit.creditdefaultswap.definition.LegacyCreditDefaultSwapDefinition;
import com.opengamma.analytics.financial.credit.hazardratemodel.HazardRateCurve;
import com.opengamma.analytics.util.time.TimeCalculator;
import com.opengamma.financial.convention.daycount.DayCount;
import com.opengamma.financial.convention.daycount.DayCountFactory;
import com.opengamma.util.ArgumentChecker;
/**
* Class to generate the integration schedules for instrument legs which require a numerical integration
* (for example the contingent and accrued legs of a CDS require numerical evaluation of integrals)
*/
public class GenerateCreditDefaultSwapIntegrationSchedule {
// -------------------------------------------------------------------------------------------
private static final DayCount dayCount = DayCountFactory.INSTANCE.getDayCount("ACT/365");
// -------------------------------------------------------------------------------------------
// TODO : The integration schedules are returned as doubles. Should we return ZonedDateTime's instead (and then convert back to doubles internally)?
// TODO : Add check that startTime < endTime in schedule generation routine
// -------------------------------------------------------------------------------------------
// Method to calculate the time nodes used to approximate the integral in the accrued leg calculation
public double[] constructCreditDefaultSwapAccruedLegIntegrationSchedule(LegacyCreditDefaultSwapDefinition cds, ISDACurve yieldCurve, HazardRateCurve hazardRateCurve) {
// Check input objects are not null
ArgumentChecker.notNull(cds, "CDS");
ArgumentChecker.notNull(yieldCurve, "Yield Curve");
ArgumentChecker.notNull(hazardRateCurve, "Hazard Rate Curve");
// Do we want to include the CDS premium leg cashflow schedule as points
boolean includeSchedule = true;
// Get the start time of the CDS with respect to the current valuation date (can obviously be negative)
double startTime = calculateCreditDefaultSwapStartTime(cds, dayCount);
// Get the (offset) maturity of the CDS
double offsetMaturityTime = calculateCreditDefaultSwapOffsetMaturity(cds, dayCount);
// Calculate the schedule of integration timenodes for the accrued leg calculation
double[] timeNodes = constructISDACompliantIntegrationSchedule(cds, yieldCurve, hazardRateCurve, startTime, offsetMaturityTime, includeSchedule);
return timeNodes;
}
// -------------------------------------------------------------------------------------------
// Method to calculate the time nodes used to approximate the integral in the contingent leg calculation
public double[] constructCreditDefaultSwapContingentLegIntegrationSchedule(LegacyCreditDefaultSwapDefinition cds, ISDACurve yieldCurve, HazardRateCurve hazardRateCurve) {
// Check input objects are not null
ArgumentChecker.notNull(cds, "CDS");
ArgumentChecker.notNull(yieldCurve, "Yield Curve");
ArgumentChecker.notNull(hazardRateCurve, "Hazard Rate Curve");
// Do we want to include the CDS premium leg cashflow schedule as points
boolean includeSchedule = false;
// Calculate the time at which protection starts
double protectionStartTime = calculateProtectionStartTime(cds, dayCount);
// Calculate the maturity of the CDS with respect to the valuation date
double maturity = calculateCreditDefaultSwapMaturity(cds, dayCount);
// Calculate the schedule of integration timenodes for the contingent leg calculation
double[] timeNodes = constructISDACompliantIntegrationSchedule(cds, yieldCurve, hazardRateCurve, protectionStartTime, maturity, includeSchedule);
return timeNodes;
}
// -------------------------------------------------------------------------------------------
// Method to construct a set of timenodes compliant with the ISDA model (adapted from the RiskCare implementation)
private double[] constructISDACompliantIntegrationSchedule(CreditDefaultSwapDefinition cds, ISDACurve yieldCurve, HazardRateCurve hazardRateCurve,
double startTime, double endTime, boolean includeSchedule) {
// ------------------------------------------------
// Check input arguments are not null
ArgumentChecker.notNull(cds, "CDS");
ArgumentChecker.notNull(yieldCurve, "Yield curve");
ArgumentChecker.notNull(hazardRateCurve, "Hazard rate curve");
ArgumentChecker.notNull(startTime, "Start time");
ArgumentChecker.notNull(endTime, "End time");
// ------------------------------------------------
double offset = 0.0;
GenerateCreditDefaultSwapPremiumLegSchedule premiumLegCashflowSchedule = new GenerateCreditDefaultSwapPremiumLegSchedule();
ZonedDateTime[] cashflowSchedule = premiumLegCashflowSchedule.constructCreditDefaultSwapPremiumLegSchedule(cds);
double[] cashflowScheduleAsDoubles = premiumLegCashflowSchedule.convertTenorsToDoubles(cashflowSchedule, cds.getValuationDate(), dayCount);
NavigableSet<Double> allTimePoints = new TreeSet<Double>();
Set<Double> timePointsInRange;
double[] x = yieldCurve.getTimePoints();
// ------------------------------------------------
for (int i = 0; i < x.length; i++) {
allTimePoints.add(new Double(x[i]));
}
x = hazardRateCurve.getShiftedTimePoints();
for (int i = 0; i < x.length; i++) {
allTimePoints.add(new Double(x[i]));
}
allTimePoints.add(new Double(startTime));
allTimePoints.add(new Double(endTime));
// ------------------------------------------------
if (includeSchedule) {
if (cds.getProtectionStart()) {
offset = cds.getProtectionOffset();
}
double offsetStartTime = TimeCalculator.getTimeBetween(cds.getValuationDate(), cashflowSchedule[1], dayCount) - offset;
allTimePoints.add(new Double(offsetStartTime));
double periodEndTime = 0.0;
for (int i = 0; i < cashflowSchedule.length; i++) {
if (i < cashflowSchedule.length - 1) {
periodEndTime = cashflowScheduleAsDoubles[i] - offset;
} else {
periodEndTime = cashflowScheduleAsDoubles[i];
}
allTimePoints.add(new Double(periodEndTime));
}
timePointsInRange = allTimePoints.subSet(new Double(offsetStartTime), true, new Double(endTime), true);
} else {
timePointsInRange = allTimePoints.subSet(new Double(startTime), true, new Double(endTime), true);
}
// ------------------------------------------------
Double[] boxed = new Double[timePointsInRange.size()];
timePointsInRange.toArray(boxed);
double[] timePoints = new double[boxed.length];
for (int i = 0; i < boxed.length; ++i) {
timePoints[i] = boxed[i].doubleValue();
}
// ------------------------------------------------
return timePoints;
}
// -------------------------------------------------------------------------------------------
public double calculateCreditDefaultSwapStartTime(LegacyCreditDefaultSwapDefinition cds, DayCount dayCount) {
double startTime = TimeCalculator.getTimeBetween(cds.getValuationDate(), cds.getStartDate(), dayCount);
return startTime;
}
// -------------------------------------------------------------------------------------------------
// Calculate the step in time for the CDS (the point at which protection coverage starts)
public double calculateCreditDefaultSwapStepinTime(LegacyCreditDefaultSwapDefinition cds, DayCount dayCount) {
double stepInTime = TimeCalculator.getTimeBetween(cds.getValuationDate(), cds.getValuationDate().plusDays(1), dayCount);
return stepInTime;
}
// -------------------------------------------------------------------------------------------------
// Calculate the offset step in time for the CDS
public double calculateCreditDefaultSwapOffsetStepinTime(LegacyCreditDefaultSwapDefinition cds, DayCount dayCount) {
double offset = 0.0;
double stepinTime = calculateCreditDefaultSwapStepinTime(cds, dayCount);
if (cds.getProtectionStart()) {
offset = cds.getProtectionOffset();
}
double offsetStepinTime = stepinTime - offset;
return offsetStepinTime;
}
// -------------------------------------------------------------------------------------------------
// Calculate the start time of the CDS contract with respect to the valuation date (can be negative obviously)
public double calculateProtectionStartTime(LegacyCreditDefaultSwapDefinition cds, DayCount dayCount) {
double startTime = calculateCreditDefaultSwapStartTime(cds, dayCount);
double stepInTime = calculateCreditDefaultSwapStepinTime(cds, dayCount);
double offsetPricingTime = -cds.getProtectionOffset();
double offsetStepinTime = stepInTime - cds.getProtectionOffset();
double protectionStartTime = Math.max(Math.max(startTime, offsetStepinTime), offsetPricingTime);
return protectionStartTime;
}
// -------------------------------------------------------------------------------------------------
// Calculate the maturity of the CDS with respect to the valuation date
public double calculateCreditDefaultSwapMaturity(LegacyCreditDefaultSwapDefinition cds, DayCount dayCount) {
double maturity = TimeCalculator.getTimeBetween(cds.getValuationDate(), cds.getMaturityDate(), dayCount);
return maturity;
}
// -------------------------------------------------------------------------------------------------
// Calculate the offset maturity for the CDS contract
public double calculateCreditDefaultSwapOffsetMaturity(LegacyCreditDefaultSwapDefinition cds, DayCount dayCount) {
double offset = 0.0;
double maturity = TimeCalculator.getTimeBetween(cds.getValuationDate(), cds.getMaturityDate(), dayCount);
if (cds.getProtectionStart()) {
offset = cds.getProtectionOffset();
}
double offsetMaturity = maturity + offset;
return offsetMaturity;
}
// -------------------------------------------------------------------------------------------------
}
|
// import IDistantVOBase from '../../IDistantVOBase';
// export default interface ICheckPointDep extends IDistantVOBase {
// checkpoint_id: number;
// dependson_id: number;
// }
|
#!/bin/bash
set -e
function retry() {
for i in {1..10}; do
sleep 1
if "$@"; then
return 0
fi
echo "retry"
done
return $?
}
export VAULT_ADDR=http://172.30.0.13:8200
export VAULT_TOKEN=cybozu
# wait for preparation of vault
retry curl ${VAULT_ADDR}/v1/sys/health
res=$(curl ${VAULT_ADDR}/v1/sys/health)
initialized=$(echo ${res} | jq -r .initialized)
sealed=$(echo ${res} | jq -r .sealed)
if [ ${initialized} = "true" ]; then
if [ ${sealed} = "true" ]; then
# if vault is initialized and sealed, only unseal
unseal_key=$(etcdctl --endpoints=http://172.30.0.14:2379 get --print-value-only boot/vault-unseal-key)
curl -XPUT http://172.30.0.13:8200/v1/sys/unseal -d "{\"key\": ${unseal_key}}"
fi
exit 0
fi
# initialize vault
res=$(vault operator init -format=json -key-shares=1 -key-threshold=1)
unseal_key=$(echo ${res} | jq .unseal_keys_b64[0])
root_token=$(echo ${res} | jq -r .root_token)
export VAULT_TOKEN=${root_token}
# store unseal key and root token to etcd
etcdctl --endpoints=http://172.30.0.14:2379 put boot/vault-unseal-key ${unseal_key}
etcdctl --endpoints=http://172.30.0.14:2379 put boot/vault-root-token ${root_token}
# unseal vault
curl -XPUT http://172.30.0.13:8200/v1/sys/unseal -d "{\"key\": ${unseal_key}}"
# setup vault
vault audit enable file file_path=stdout
vault policy write admin /opt/setup/admin-policy.hcl
vault policy write cke /opt/setup/cke-policy.hcl
vault auth enable approle
# setup approle for cke
vault write auth/approle/role/cke policies=cke period=1h
r=$(vault read -format=json auth/approle/role/cke/role-id)
s=$(vault write -f -format=json auth/approle/role/cke/secret-id)
role_id=$(echo ${r} | jq -r .data.role_id)
secret_id=$(echo ${s} | jq -r .data.secret_id)
a=$(vault write -f -format=json auth/approle/login role_id=${role_id} secret_id=${secret_id})
approle_token=$(echo ${a} | jq -r .auth.client_token)
# register information for connecting to vault to CKE
echo "{\"endpoint\": \"http://172.30.0.13:8200\", \"role-id\": \"${role_id}\", \"secret-id\": \"${secret_id}\"}" | ckecli vault config -
ckecli vault init
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.fhwa.c2cri.ntcip2306v109.operations;
import org.fhwa.c2cri.ntcip2306v109.messaging.NTCIP2306Message;
/**
* The listener interface for receiving operation events.
* The class that is interested in processing a operation
* event implements this interface. When
* the operation event occurs, that object's appropriate
* method is invoked.
*
* @see OperationEvent
*/
public interface OperationListener {
/**
* External request update.
*
* Pre-Conditions: N/A
* Post-Conditions: N/A
*
* @param operationId the operation id
* @param em the em
*/
public void externalRequestUpdate(OperationIdentifier operationId, NTCIP2306Message em);
/**
* External response update.
*
* Pre-Conditions: N/A
* Post-Conditions: N/A
*
* @param operationId the operation id
* @param em the em
*/
public void externalResponseUpdate(OperationIdentifier operationId, NTCIP2306Message em);
/**
* Operation results update.
*
* Pre-Conditions: N/A
* Post-Conditions: N/A
*
* @param operationId the operation id
* @param opResults the op results
*/
public void OperationResultsUpdate(OperationIdentifier operationId, OperationResults opResults);
}
|
class Genre < ApplicationRecord
has_many :movies, dependent: :destroy
validates :name, presence: true, uniqueness: true
before_validation :titlecase
private
def titlecase
self.name = self.name.titleize
end
end
|
<filename>apps/invoiceservice-go/main.go
//go:generate go run $GOPATH/src/github.com/TIBCOSoftware/flogo-lib/flogo/gen/gen.go $GOPATH
package main
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"strconv"
"github.com/TIBCOSoftware/flogo-contrib/activity/log"
"github.com/TIBCOSoftware/flogo-contrib/activity/rest"
rt "github.com/TIBCOSoftware/flogo-contrib/trigger/rest"
"github.com/TIBCOSoftware/flogo-lib/core/data"
"github.com/TIBCOSoftware/flogo-lib/engine"
"github.com/TIBCOSoftware/flogo-lib/flogo"
"github.com/TIBCOSoftware/flogo-lib/logger"
"github.com/retgits/flogo-components/activity/randomnumber"
)
var (
httpport = os.Getenv("HTTPPORT")
paymentservice = os.Getenv("PAYMENTSERVICE")
)
func main() {
// Create a new Flogo app
app := appBuilder()
e, err := flogo.NewEngine(app)
if err != nil {
logger.Error(err)
return
}
engine.RunEngine(e)
}
func appBuilder() *flogo.App {
app := flogo.NewApp()
// Convert the HTTPPort to an integer
port, err := strconv.Atoi(httpport)
if err != nil {
logger.Error(err)
}
// Register the HTTP trigger
trg := app.NewTrigger(&rt.RestTrigger{}, map[string]interface{}{"port": port})
trg.NewFuncHandler(map[string]interface{}{"method": "GET", "path": "/api/invoices/:id"}, handler)
trg.NewFuncHandler(map[string]interface{}{"method": "GET", "path": "/swaggerspec"}, SwaggerSpec)
return app
}
// SwaggerSpec is the function that gets executedto retrieve the SwaggerSpec
func SwaggerSpec(ctx context.Context, inputs map[string]*data.Attribute) (map[string]*data.Attribute, error) {
// The return message is a map[string]*data.Attribute which we'll have to construct
response := make(map[string]interface{})
ret := make(map[string]*data.Attribute)
fileData, err := ioutil.ReadFile("swagger.json")
if err != nil {
ret["code"], _ = data.NewAttribute("code", data.TypeInteger, 500)
response["msg"] = err.Error()
} else {
ret["code"], _ = data.NewAttribute("code", data.TypeInteger, 200)
var data map[string]interface{}
if err := json.Unmarshal(fileData, &data); err != nil {
panic(err)
}
response = data
}
ret["data"], _ = data.NewAttribute("data", data.TypeAny, response)
return ret, nil
}
func handler(ctx context.Context, inputs map[string]*data.Attribute) (map[string]*data.Attribute, error) {
// Get the ID from the path
id := inputs["pathParams"].Value().(map[string]string)["id"]
// Execute the log activity
in := map[string]interface{}{"message": id, "flowInfo": "true", "addToFlow": "true"}
_, err := flogo.EvalActivity(&log.LogActivity{}, in)
if err != nil {
return nil, err
}
// Generate a random number for the amount
// There are definitely better ways to do this with Go, but this keeps the flow consistent with the UI version
in = map[string]interface{}{"min": 1000, "max": 2000}
out, err := flogo.EvalActivity(&randomnumber.MyActivity{}, in)
if err != nil {
return nil, err
}
amount := strconv.Itoa(out["result"].Value().(int))
// Instead of using the combine activity we'll concat the strings together
ref := fmt.Sprintf("INV-%v", id)
// Generate a random number for the balance
// There are definitely better ways to do this with Go, but this keeps the flow consistent with the UI version
in = map[string]interface{}{"min": 0, "max": 2000}
out, err = flogo.EvalActivity(&randomnumber.MyActivity{}, in)
if err != nil {
return nil, err
}
balance := strconv.Itoa(out["result"].Value().(int))
// Call out to another service
in = map[string]interface{}{"method": "GET", "uri": fmt.Sprintf("%s%s", paymentservice, id)}
logger.Info(in)
out, err = flogo.EvalActivity(&rest.RESTActivity{}, in)
if err != nil {
return nil, err
}
expectedDate := out["result"].Value().(map[string]interface{})["expectedDate"].(string)
// The return message is a map[string]*data.Attribute which we'll have to construct
response := make(map[string]interface{})
response["id"] = id
response["ref"] = ref
response["amount"] = amount
response["balance"] = balance
response["expectedPaymentDate"] = expectedDate
response["currency"] = "USD"
ret := make(map[string]*data.Attribute)
ret["code"], _ = data.NewAttribute("code", data.TypeInteger, 200)
ret["data"], _ = data.NewAttribute("data", data.TypeAny, response)
return ret, nil
}
|
import subprocess
# Command to create VXLAN interface
create_vxlan_cmd = "sudo ip link add vxlan0 type vxlan id 42 dstport 4789 dev eth0"
# Command to maintain bridge FDB
bridge_fdb_cmd = "sudo bridge fdb append 00:00:00:00:00:00 dev vxlan0 dst 192.168.8.101"
# Execute commands using subprocess
try:
subprocess.run(create_vxlan_cmd, shell=True, check=True)
subprocess.run(bridge_fdb_cmd, shell=True, check=True)
print("VXLAN interface and bridge FDB entry configured successfully")
except subprocess.CalledProcessError as e:
print(f"Error occurred: {e}")
|
#!/bin/bash
mkdir -p raw_tlc_data
createdb nyc-ecommerce-analysis
psql nyc-ecommerce-analysis -c "CREATE EXTENSION IF NOT EXISTS postgis;"
shp2pgsql -s 102718:4326 -I shapefiles/taxi_zones/taxi_zones.shp | psql -d nyc-ecommerce-analysis
shp2pgsql -s 102718:4326 -I shapefiles/nyct2010_20d/nyct2010.prj | psql -d nyc-ecommerce-analysis
psql nyc-ecommerce-analysis -c "CREATE INDEX ON taxi_zones (locationid);"
psql nyc-ecommerce-analysis -f setup_files/create_schema.sql
|
MININIX_PKG_HOMEPAGE=https://sourceware.org/libffi/
MININIX_PKG_DESCRIPTION="Library providing a portable, high level programming interface to various calling conventions"
MININIX_PKG_VERSION=3.2.1
MININIX_PKG_REVISION=2
MININIX_PKG_SRCURL=ftp://sourceware.org/pub/libffi/libffi-${MININIX_PKG_VERSION}.tar.gz
MININIX_PKG_SHA256=d06ebb8e1d9a22d19e38d63fdb83954253f39bedc5d46232a05645685722ca37
MININIX_PKG_EXTRA_CONFIGURE_ARGS="--disable-multi-os-directory"
MININIX_PKG_RM_AFTER_INSTALL="lib/libffi-${MININIX_PKG_VERSION}/include"
mininix_step_pre_configure () {
if [ $MININIX_ARCH = arm ]; then
CFLAGS+=" -fno-integrated-as"
fi
}
|
var elixir = require('laravel-elixir');
var paths={
'chartsjs':'./node_modules/chart.js/Chart.js'
}
elixir(function(mix) {
mix.sass('app.scss')
.scripts(['components/*.js','app.js'],'public/js/all.js')
.scripts([paths.chartsjs],'public/js/charts.js');
});
|
// --------------------------------------------------------- //
// HOME-NODE - Sorts the coherent transactions //
// --------------------------------------------------------- //
#ifndef _ACE_HOME_H_
#define _ACE_HOME_H_
#include "systemc.h"
#include "nvhls_connections.h"
#include "../include/ace.h"
#include "../include/flit_ace.h"
#include "../include/duth_fun.h"
// --- HOME NODE ---
// All coherent transactions are serialized to a HOME NODE.
// HOME generates the apropriate Snoop requests and gathers their responses
// Regarding the responses of the snooped masters, HOME decides if access to
// a main memory (i.e. Slave) is required for the transaction completion
template <typename cfg>
SC_MODULE(ace_home) {
typedef typename ace::ace5<axi::cfg::ace> ace5_;
typedef typename ace::ACE_Encoding enc_;
typedef flit_dnp<cfg::RREQ_PHITS> rreq_flit_t;
typedef flit_dnp<cfg::RRESP_PHITS> rresp_flit_t;
typedef flit_dnp<cfg::WREQ_PHITS> wreq_flit_t;
typedef flit_dnp<cfg::WRESP_PHITS> wresp_flit_t;
typedef flit_dnp<cfg::CREQ_PHITS> creq_flit_t;
typedef flit_dnp<cfg::CRESP_PHITS> cresp_flit_t;
typedef flit_ack ack_flit_t;
typedef sc_uint< clog2<cfg::RRESP_PHITS>::val > cnt_phit_rresp_t;
typedef sc_uint< clog2<cfg::WRESP_PHITS>::val > cnt_phit_wresp_t;
const unsigned char LOG_RD_M_LANES = nvhls::log2_ceil<cfg::RD_LANES>::val;
const unsigned char LOG_WR_M_LANES = nvhls::log2_ceil<cfg::WR_LANES>::val;
sc_in_clk clk;
sc_in <bool> rst_n;
sc_in < sc_uint<(dnp::ace::AH_W+dnp::ace::AL_W)> > addr_map[cfg::SLAVE_NUM][2];
sc_in< sc_uint<dnp::S_W> > THIS_ID;
// NoC Side Channels
Connections::Out<creq_flit_t> INIT_S1(cache_req);
Connections::In<cresp_flit_t> INIT_S1(cache_resp);
Connections::In<rreq_flit_t> INIT_S1(rd_from_master);
Connections::Out<rresp_flit_t> INIT_S1(rd_to_master);
Connections::Out<rreq_flit_t> INIT_S1(rd_to_slave);
Connections::In<rresp_flit_t> INIT_S1(rd_from_slave);
Connections::In<wreq_flit_t> INIT_S1(wr_from_master);
Connections::Out<wresp_flit_t> INIT_S1(wr_to_master);
Connections::Out<wreq_flit_t> INIT_S1(wr_to_slave);
Connections::In<wresp_flit_t> INIT_S1(wr_from_slave);
Connections::In<ack_flit_t> INIT_S1(ack_from_master);
// Constructor
SC_HAS_PROCESS(ace_home);
ace_home(sc_module_name name_="ace_home")
:
sc_module (name_)
{
SC_THREAD(req_check);
sensitive << clk.pos();
async_reset_signal_is(rst_n, false);
}
void req_check () {
cache_req.Reset();
cache_resp.Reset();
rd_from_master.Reset();
rd_to_master.Reset();
rd_to_slave.Reset();
rd_from_slave.Reset();
wr_from_master.Reset();
wr_to_master.Reset();
wr_to_slave.Reset();
wr_from_slave.Reset();
//-- End of Reset ---//
while(1) {
wait();
// Initial Request
// Wait until a read or write request is received
rreq_flit_t flit_req_rcv;
bool got_new_req = false;
do {
if (!got_new_req) got_new_req = wr_from_master.PopNB(flit_req_rcv);
if (!got_new_req) got_new_req = rd_from_master.PopNB(flit_req_rcv);
wait();
} while (!got_new_req);
// Check who initiated the transaction the the type of transaction
ace5_::AddrPayload cur_req;
unsigned initiator = flit_req_rcv.get_src();
bool is_read = (flit_req_rcv.get_type() == dnp::PACK_TYPE__RD_REQ);
bool is_write = (flit_req_rcv.get_type() == dnp::PACK_TYPE__WR_REQ);
NVHLS_ASSERT_MSG(is_read ^ is_write , "ERROR : Home got request of wrong type.");
flit_req_rcv.get_rd_req(cur_req);
#ifndef __SYNTHESIS__
if(is_read) std::cout << "[HOME "<< THIS_ID <<"] Got RD from " << initiator << " : " << cur_req << " @" << sc_time_stamp() << "\n";
else std::cout << "[HOME "<< THIS_ID <<"] Got WR from " << initiator << " : " << cur_req << " @" << sc_time_stamp() << "\n";
#endif
NVHLS_ASSERT_MSG(((flit_req_rcv.data[0].to_uint() >> dnp::D_PTR) & ((1<<dnp::D_W)-1)) == (THIS_ID.read().to_uint()), "Flit misrouted!");
// Build the appropriate Snoop request for the cached FULL ACE Masters, depending the coherent access
ace5_::AC snoop_req;
snoop_req.addr = cur_req.addr;
snoop_req.snoop = is_read ? ace::rd_2_snoop(cur_req.snoop) : ace::wr_2_snoop(cur_req.snoop);
snoop_req.prot = initiator;
creq_flit_t flit_snoop;
flit_snoop.type = SINGLE; // Entire request fits in single flits thus SINGLE
flit_snoop.set_network(THIS_ID, 0, 0, (is_read ? dnp::PACK_TYPE__RD_REQ : dnp::PACK_TYPE__WR_REQ), 0);
flit_snoop.set_snoop_req(snoop_req);
// Send the Snoop requests to the masters. This can exploit multicast capabilities of the routers
for (int i=cfg::SLAVE_NUM; i<cfg::SLAVE_NUM+cfg::FULL_MASTER_NUM; ++i) {
if(i!=initiator) {
flit_snoop.set_dst(i);
cache_req.Push(flit_snoop);
wait();
}
}
// Depending the initiating master (Lite or Full Ace) different number of request/repsonses are expected
bool init_is_full = (initiator<(cfg::SLAVE_NUM+cfg::FULL_MASTER_NUM));
unsigned resp_wait = init_is_full ? cfg::FULL_MASTER_NUM-1 : cfg::FULL_MASTER_NUM;
// Wait until all responses are received
cresp_flit_t snoop_resp_data;
ace5_::CR::Resp resp_accum = 0;
bool got_data = false;
bool got_dirty = false;
while (resp_wait) {
cresp_flit_t flit_rcv_snoop_resp = cache_resp.Pop();
NVHLS_ASSERT_MSG((flit_rcv_snoop_resp.type == HEAD || flit_rcv_snoop_resp.type == SINGLE), "Snoop Responce Must be at HEAD/SINGLE flit.");
// Each response is checked if it contains data and accumulate the response to conclude to an action
ace5_::CR::Resp cur_snoop_resp;
cur_snoop_resp = (flit_rcv_snoop_resp.data[0] >> dnp::ace::cresp::C_RESP_PTR) & ((1<<dnp::ace::C_RESP_W)-1);
bool has_data = cur_snoop_resp & 0x1;
bool has_dirty = cur_snoop_resp & 0x4;
if (has_data) {
if (has_dirty || !got_data) {
snoop_resp_data = cache_resp.Pop(); // Get data
NVHLS_ASSERT_MSG((snoop_resp_data.type == TAIL), "Currently a single flit cache line is supported!");
} else {
cresp_flit_t drop_data = cache_resp.Pop(); // Already got Data, thus drop any other
NVHLS_ASSERT_MSG((drop_data.type == TAIL), "Currently a single flit cache line is supported!" );
}
}
resp_accum |= cur_snoop_resp;
got_dirty |= cur_snoop_resp & 0x4;
got_data |= cur_snoop_resp & 0x1;
resp_wait--;
}
// If initiator demands clean, update Mem in case of dirty line
bool update_mem = req_denies_dirty(cur_req.snoop, is_read);
if (got_dirty && update_mem) {
unsigned mem_to_write = addr_lut(cur_req.addr);
wreq_flit_t mem_upd_flit;
mem_upd_flit.type = HEAD;
mem_upd_flit.data[0] = flit_req_rcv.data[0];
mem_upd_flit.data[1] = flit_req_rcv.data[1];
mem_upd_flit.data[2] = flit_req_rcv.data[2];
mem_upd_flit.set_network(THIS_ID, mem_to_write, 0, dnp::PACK_TYPE__C_WR_REQ, 0);
wr_to_slave.Push(mem_upd_flit);
#pragma hls_unroll yes
for (int i=0; i<cfg::WREQ_PHITS; ++i) {
mem_upd_flit.data[i] = snoop_resp_data.data[i] | (((sc_uint<dnp::PHIT_W>)3) << dnp::ace::wdata::E0_PTR);
}
mem_upd_flit.type = TAIL;
wr_to_slave.Push(mem_upd_flit);
wr_from_slave.Pop(); // ToDo : Maybe error handling
resp_accum = resp_accum & 0x1B; // Drop Pass Dirty bit as it got writen in Mem
}
if (is_read) {
bool data_are_expected = req_expects_data(cur_req.snoop, is_read);
// After responces are gathered, either respond to initiating master, or ask Main_mem/LLC
if (data_are_expected) {
// After responces are gathered, either respond to initiating master, or ask Main_mem/LLC
if (!got_data) { // Didn't get data response, thus ask memory
// Didn't get data response, thus ask memory
unsigned mem_to_req = addr_lut(cur_req.addr);
flit_req_rcv.set_network(THIS_ID, mem_to_req, 0, dnp::PACK_TYPE__C_RD_REQ, 0);
rd_to_slave.Push(flit_req_rcv);
rd_from_slave.Pop(); // Drop the header
snoop_resp_data = rd_from_slave.Pop();
resp_accum = ((snoop_resp_data.data[0] >> dnp::ace::rdata::RE_PTR) & 0x3) | (resp_accum & 0xC);
} else {
resp_accum = resp_accum & 0xE; // MASK WasUnique and HasData. Easily creating the R resp from CR resp
}
#pragma hls_unroll yes
for (int i=0; i<cfg::RRESP_PHITS; ++i) {
snoop_resp_data.data[i] |= snoop_resp_data.data[i] | (((sc_uint<dnp::PHIT_W>)resp_accum) << dnp::ace::rdata::RE_PTR);
}
} else {
// Master does not expect Data, thus build empty data+response And write any data received to Mem
resp_accum = resp_accum & 0xE; // MASK WasUnique and HasData. Easily creating the R resp from CR resp
#pragma hls_unroll yes
for (int i=0; i<cfg::RRESP_PHITS; ++i) {
snoop_resp_data.data[i] = (((sc_uint<dnp::PHIT_W>) resp_accum) << dnp::ace::rdata::RE_PTR);
}
snoop_resp_data.type = TAIL;
}
// Build and send reponse packet
rresp_flit_t flit_resp_to_init;
flit_resp_to_init.type = HEAD;
flit_resp_to_init.set_network(THIS_ID, initiator, 0, dnp::PACK_TYPE__C_RD_RESP, 0);
flit_resp_to_init.set_rd_resp(cur_req);
rd_to_master.Push(flit_resp_to_init); // Send Header flit
rd_to_master.Push(snoop_resp_data); // Send Data. IsSHared and IsDirty are expected to be 0
} else {
// Init transaction is a Write thus resolbe Mem to write and send the Write transaction
unsigned mem_to_write = addr_lut(cur_req.addr);
flit_req_rcv.set_network(THIS_ID, mem_to_write, 0, dnp::PACK_TYPE__C_WR_REQ, 0);
wr_to_slave.Push(flit_req_rcv); // Send Head
wreq_flit_t data_to_update;
while(!wr_from_master.PopNB(data_to_update)) {
wait();
}
wr_to_slave.Push(data_to_update);
// transfer the response to the init Master
wresp_flit_t mv_wr_resp = wr_from_slave.Pop();
mv_wr_resp.set_src(THIS_ID); // Set the HOME src to receive the response
mv_wr_resp.set_dst(initiator); // Set the initiator as a recipient src to receive the response
wr_to_master.Push(mv_wr_resp);
}
// Wait for the final ack from the Init Master that signifies that the cache has been completed the transaction
// Only a Full Master responds with an Ack
if (init_is_full) {
ack_flit_t rcv_ack = ack_from_master.Pop();
NVHLS_ASSERT_MSG( (rcv_ack.is_rack()&&is_read) || (rcv_ack.is_wack()&&(!is_read)), "ACK does not match the responce (i.e. RD/WR)");
#ifndef __SYNTHESIS__
if(is_read) std::cout << "[HOME "<< THIS_ID <<"] Got RD ACK from " << rcv_ack.get_src() << " : " << cur_req << " @" << sc_time_stamp() << "\n";
else std::cout << "[HOME "<< THIS_ID <<"] Got WR AK from " << rcv_ack.get_src() << " : " << cur_req << " @" << sc_time_stamp() << "\n";
#endif
}
} // End of while(1)
}; // End of HOME Node
// Transactions that do not accept Dirty data, thus the interconnects is responsible for to handle them
inline bool req_denies_dirty(NVUINTW(enc_::ARSNOOP::_WIDTH) &request_in, bool is_read ) {
if (is_read) {
if ((request_in == enc_::ARSNOOP::RD_ONCE) ||
(request_in == enc_::ARSNOOP::RD_CLEAN) ||
(request_in == enc_::ARSNOOP::RD_NOT_SHARED_DIRTY) ||
(request_in == enc_::ARSNOOP::CLEAN_UNIQUE) ||
(request_in == enc_::ARSNOOP::MAKE_UNIQUE) ||
(request_in == enc_::ARSNOOP::CLEAN_SHARED) ||
(request_in == enc_::ARSNOOP::CLEAN_INVALID) ||
(request_in == enc_::ARSNOOP::MAKE_INVALID) )
{
return true;
}
} else { // request is a write, thus any dirty must be sent to Mem
return true;
}
return false;
};
// When data are required, HOME must access Mem when all snoops where missed
inline bool req_expects_data(NVUINTW(enc_::ARSNOOP::_WIDTH) &request_in, bool is_read ) {
if (is_read) {
if ((request_in == enc_::ARSNOOP::RD_ONCE) ||
(request_in == enc_::ARSNOOP::RD_CLEAN) ||
(request_in == enc_::ARSNOOP::RD_NOT_SHARED_DIRTY) ||
(request_in == enc_::ARSNOOP::RD_SHARED) ||
(request_in == enc_::ARSNOOP::RD_UNIQUE) )
{
return true;
}
}
return false;
};
// Memory map resolving
inline unsigned char addr_lut(const ace5_::Addr addr) {
for (int i=0; i<2; ++i) {
if (addr>=addr_map[i][0].read() && addr <= addr_map[i][1].read()) return i;
}
return 0; // Or send 404
};
}; // End of Home module
#endif // _ACE_HOME_H_
|
<gh_stars>100-1000
// ==UserScript==
// @name Amazon-RefreshNoBot
// @include https://www.amazon.com/*
// @include http://localhost:800*
// @version v2.0
// @description This aint bot, its RefreshNoBot
// @author <NAME>
// @grant window.close
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_xmlhttpRequest
// Version Changelog
// 1.0-beta - Runs only Testmode.
// - Code is not complete commented.
// - No support for Amazon Captcha (Soft Ban) - Future support with local flask server
// - Dog Pages are not handled
// 1.1-beta - Fixed Sellers Loop
// - When in Sellers, Used items are not checked for
// - Still No support for Amazon Captcha (Soft Ban) & Dog Pages
// - More code commented
// 2.0 - Fully Functional Bot with Local Gunicorn Server
// - Using flask, gunicorn and amazoncapcha; we solve Amazon Captcha (Soft Ban)
// - Faster page reload on seller pages (4 Seconds)
// - When cart is disabled with Dog Pages, it will refresh cart every 10 second
// - When resellers are disabled, bot will show 0 items and refresh
// - No autocheckout yet. Will be released as minor update later.
// - More code commented
// ==/UserScript==
/*
█████╗ ███╗ ███╗ █████╗ ███████╗ ██████╗ ███╗ ██╗ ██████╗ ██████╗ ████████╗
██╔══██╗████╗ ████║██╔══██╗╚══███╔╝██╔═══██╗████╗ ██║ ██╔══██╗██╔═══██╗╚══██╔══╝
███████║██╔████╔██║███████║ ███╔╝ ██║ ██║██╔██╗ ██║ ██████╔╝██║ ██║ ██║
██╔══██║██║╚██╔╝██║██╔══██║ ███╔╝ ██║ ██║██║╚██╗██║ ██╔══██╗██║ ██║ ██║
██║ ██║██║ ╚═╝ ██║██║ ██║███████╗╚██████╔╝██║ ╚████║ ██████╔╝╚██████╔╝ ██║
╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═════╝ ╚═╝
“Make it work, make it right, make it fast.” – <NAME>
*/
"use strict";
//________________________________________________________________________
// CONSTANTS
// [ Do not add/remove quotation marks when updating]
//________________________________________________________________________
//____ REQUIRED FLAGS : AMAZON ID & PRICE CUTOFF _________________________
let PRODUCT_ARRAY = ["B08WM28PVH", "B096YM573B", "B096WM6JFS", "B096YMW2FS", "B09B1DGRH4"];
const CUTOFF_ARRAY = [500, 500, 500, 500, 500]; // No quotes
//____ REQUIRED FLAGS : TESTMODE OR BUY MODE _____________________________
const TESTMODE = "Yes" // This flag is unused. Will be implemented in next release
//________________________________________________________________________
// MAIN CODE : DO NOT CHANGE
//________________________________________________________________________
const PRODUCT_URL = document.URL
const delay = ms => new Promise(res => setTimeout(res, ms));
const NUMERIC_REGEXP = /[-]{0,1}[\d]*[.]{0,1}[\d]+/g;
const RETRY_COUNT = 1
//________________________________________________________________________
// MAIN CODE : CAPTCHA PAGES
//________________________________________________________________________
if (document.getElementsByClassName("a-box a-alert a-alert-info a-spacing-base").length > 0) {
console.log(document.getElementsByClassName("a-box a-alert a-alert-info a-spacing-base"))
console.log('CAPCTHA PAGE')
var Oh_No_Its_Some_Captcha = new Audio("https://github.com/kkapuria3/BestBuy-GPU-Bot/blob/dev-v2.5-mem_leak_fix/resources/alert.mp3?raw=true");
Oh_No_Its_Some_Captcha.play()
//"\n<img src=\"https://images-na.ssl-images-amazon.com/captcha/dddfleoy/Captcha_lkdgslujsl.jpg\">\n
var IMAGE_URL = document.getElementsByClassName("a-row a-text-center")[1].innerHTML.split('captcha/')[1]
var FIRST_ELEMENT = IMAGE_URL.split('/')[0]
var SECOND_ELEMENT_Raw = IMAGE_URL.split('/')[1]
var SECOND_ELEMENT = SECOND_ELEMENT_Raw.split('">')[0]
console.log(SECOND_ELEMENT)
const CAPTCHA_URL = 'http://localhost:8000/url/' + FIRST_ELEMENT + '/' + SECOND_ELEMENT
console.log(CAPTCHA_URL)
GM_xmlhttpRequest({
method: "POST",
url: CAPTCHA_URL,
onload: function(response) {
console.log(response.response);
GM_setValue(CAPTCHA_URL, response.response);
}
})
setTimeout(function() {
const SOLUTION = GM_getValue(CAPTCHA_URL);
document.getElementById("captchacharacters").value = SOLUTION
document.getElementsByClassName('a-button-text')[0].click()
}, 9000)
}
//________________________________________________________________________
// MAIN CODE : ITEM PAGE OPERATIONS
//________________________________________________________________________
for (let i = 0; i < PRODUCT_ARRAY.length; i++) {
const AMAZON_PRODUCT_ID = PRODUCT_ARRAY[i]
const CUTOFF_PRICE = CUTOFF_ARRAY[i]
//____ BLACK ELEMENT : ______
function createFloatingBadge(mode, status, ht = 160) {
const iconUrl = "https://kkapuria3.github.io/images/KK.png";
const iconUrl1 = "https://i.pinimg.com/600x315/cd/28/16/cd28168e19f7fdf9c666edd083921129.jpg"
const iconUrl2 = "https://brandlogovector.com/wp-content/uploads/2020/07/Discord-Logo-Icon-Small.png"
const iconUrl3 = "https://img.icons8.com/cotton/2x/source-code.png"
const script = document.createElement('script');
const $container = document.createElement("div");
const $bg = document.createElement("div");
const $link = document.createElement("a");
const $link1 = document.createElement("a");
const $link2 = document.createElement("a");
const $link3 = document.createElement("a");
const $img = document.createElement("img");
const $img1 = document.createElement("img");
const $img2 = document.createElement("img");
const $img3 = document.createElement("img");
const $text = document.createElement("P");
const $BAGDE_BORDER = document.createElement("P");
const $mode = document.createElement("P");
const $status1 = document.createElement("P");
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', 'https://cdn.jsdelivr.net/npm/brython@3.9.5/brython.min.js');
$link.setAttribute("href", "https://github.com/kkapuria3");
$link.setAttribute("target", "_blank");
$link.setAttribute("title", "RefreshNoBot");
$link1.setAttribute("href", "https://www.buymeacoffee.com/kapuriakaran");
$link1.setAttribute("target", "_blank");
$link1.setAttribute("title", "Buy Dev a Coffee");
$link2.setAttribute("href", "https://discord.gg/UcxcyxS5X8");
$link2.setAttribute("target", "_blank");
$link2.setAttribute("title", "Join Discord");
$link3.setAttribute("href", "https://www.buymeacoffee.com/kapuriakaran");
$link3.setAttribute("target", "_blank");
$link3.setAttribute("title", "View Source Code");
$img.setAttribute("src", iconUrl);
$img1.setAttribute("src", iconUrl1);
$img2.setAttribute("src", iconUrl2);
$img3.setAttribute("src", iconUrl3);
var MAIN_TITLE = ("Open Source Amazon-Bot v2.0 ◻️ TESTMODE: " + TESTMODE + " ◻️ ITEM KEYWORD: " + AMAZON_PRODUCT_ID + " ◻️ CUTOFF PRICE : " + CUTOFF_PRICE);
$BAGDE_BORDER.innerText = ("------------------------------------------------------------------------------------------------------------------------------------ ");
$text.innerText = MAIN_TITLE;
$mode.innerText = mode;
$status1.innerText = status;
$container.style.cssText = "position:fixed;left:0;bottom:0;width:950px;height:" + ht + "px;background: black; border: 1px solid #FFF";
$bg.style.cssText = "position:absolute;left:-100%;top:0;width:60px;height:350px;background:#1111;box-shadow: 0px 0 10px #060303; border: 1px solid #FFF;";
$link.style.cssText = "position:absolute;display:block;top:11px;left: 10px; z-index:10;width: 30px;height:30px;border-radius: 1px;overflow:hidden;";
$link1.style.cssText = "position:absolute;display:block;top:40px;left: 0px; z-index:10;width: 50px;height:50px;border-radius: 0px;overflow:hidden;";
$link2.style.cssText = "position:absolute;display:block;top:70px;left: 0px; z-index:10;width: 50px;height:50px;border-radius: 0px;overflow:hidden;";
$link3.style.cssText = "position:absolute;display:block;top:118px;left: 12px; z-index:10;width: 25px;height:25px;border-radius: 0px;overflow:hidden;";
$img.style.cssText = "display:block;width:100%";
$img1.style.cssText = "display:block;width:100%";
$img2.style.cssText = "display:block;width:100%";
$img3.style.cssText = "display:block;width:100%";
$text.style.cssText = "position:absolute;display:block;top:3px;left: 50px;background: transperant; color: white;";
$BAGDE_BORDER.style.cssText = "position:absolute;display:block;top:22px;left: 50px;background: transperant; color: green;";
$mode.style.cssText = "position:absolute;display:block;top:43px;left: 50px;background: transperant; color: white;";
$status1.style.cssText = "position:absolute;display:block;top:64px;left: 50px;background: transperant; color: white;";
//
//
$link.appendChild($img);
$link1.appendChild($img1);
$link2.appendChild($img2);
$link3.appendChild($img3);
$container.appendChild(script);
$container.appendChild($bg);
$container.appendChild($link);
$container.appendChild($link1);
$container.appendChild($link2);
$container.appendChild($link3);
$container.appendChild($text);
$container.appendChild($BAGDE_BORDER);
$container.appendChild($mode);
$container.appendChild($status1)
return $container;
}
//____ LOGIC : ______
// If your product URL has the AMAZON_PRODUCT_ID, we will run this logic. Simple.
if (PRODUCT_URL.includes(AMAZON_PRODUCT_ID)) {
//____ BADGE UPDATE : ______
var $badge = createFloatingBadge("Starting ..", "Init..");
document.body.appendChild($badge);
$badge.style.transform = "translate(0, 0)"
//____ DEBUG : ______
console.log('Detected Product ID: ' + AMAZON_PRODUCT_ID);
console.log('Cutoff Price: ' + CUTOFF_PRICE);
//____ Get Product Title : ______
var Product_Title = document.getElementsByClassName("a-size-large product-title-word-break");
console.log(Product_Title[0].innerHTML)
// If URL contains 'aod_redir', means we are checking for Extra Sellers, we will try to parse extra sellers in here
if (location.href.includes('aod_redir')) {
//____ BADGE UPDATE : ______
const $badge = createFloatingBadge('Extra Seller Offers Fetched | Checking offers ..', "Add to cart if price is below CUTOFF_PRICE ");
document.body.appendChild($badge);
$badge.style.transform = "translate(0, 0)"
const PRICES_BADGE = [];
console.log('START CHECKING SELLERS NOW ..')
//____ TIMEOUT : _____
setTimeout(function() {
console.log('Open extra sellers')
//console.log(New_Sellers)
// We are directly parsing all the sellers ADD TO CART BUTTONS
var Seller_Buttons = document.getElementsByClassName("a-button-input");
// We will loop over all the found buttons and then try to get ATC button where SELLER_PRICE is lower than CUTOFF_PRICE
for (var i = 0; i < Seller_Buttons.length; i++) {
// Getting Seller Button Data
var SELLER_BUTTON_DATA = Seller_Buttons.item(i)
// Getting Seller Price from Outter HTML of button
var SELLER_PRICE = Seller_Buttons[i].outerHTML.match(NUMERIC_REGEXP).join('')
//console.log(SELLER_PRICE)
// If SELLER_PRICE is less than CUTOFF_PRICE and SELLER_PRICE is Greater than 0 (to eliminate pseudo buttons)
if (SELLER_PRICE < CUTOFF_PRICE && SELLER_PRICE > 0) {
const $badge = createFloatingBadge('PRICE MATCH FOUND..', SELLER_PRICE);
document.body.appendChild($badge);
setTimeout(function() {
window.open("https://www.amazon.com/gp/cart/view.html", '_blank');
window.close()
}, 2000)
// BUY WILL BE TRIGGERED HERE
console.log('LOW Price: ' + SELLER_PRICE + ' | ButtonID : ' + SELLER_BUTTON_DATA + ' | Button Number : ' + i + ' | Button TimeStamp' + Date.now() + '\n')
Seller_Buttons[i].click();
// If SELLER_PRICE IS HIGHER than CUTOFF_PRICE | Print the details to badge and move forward
} else if (SELLER_PRICE > CUTOFF_PRICE && SELLER_PRICE > 0 && SELLER_PRICE < (CUTOFF_PRICE + 2000)) {
//refresh
console.log('HIGH Price: ' + SELLER_PRICE + ' | ButtonID : ' + SELLER_BUTTON_DATA + ' | Button Number : ' + i + ' | Button TimeStamp' + Date.now() + '\n')
//console.log('Price is High')
var BADGE_SELLER_DETAILS = ' PRICE HIGHER | $:' + SELLER_PRICE + ' | BUTTON DATA : ' + SELLER_BUTTON_DATA + ' | BUTTON NUMBER : ' + i + ' | TIMESTAMP : ' + Date.now() + '◻️ ◻️ ◻️ ◻️ ◻️'
PRICES_BADGE.push(BADGE_SELLER_DETAILS)
}
// Count Total Valid SELLER_BUTTON
const TOTAL_ITEMS = 'Total Items : ' + PRICES_BADGE.length
// Change hieght of badge based on total items retrieved
if (i >= 11) {
const $badge = createFloatingBadge(TOTAL_ITEMS, PRICES_BADGE, 330);
document.body.appendChild($badge);
$badge.style.transform = "translate(0, 0)"
} else if (i > 6) {
const $badge = createFloatingBadge(TOTAL_ITEMS, PRICES_BADGE, 250);
document.body.appendChild($badge);
$badge.style.transform = "translate(0, 0)"
} else {
const $badge = createFloatingBadge(TOTAL_ITEMS, PRICES_BADGE);
document.body.appendChild($badge);
$badge.style.transform = "translate(0, 0)"
}
}
}, 4000)
setTimeout(function() {
location.href = "https://www.amazon.com/dp/" + AMAZON_PRODUCT_ID + "/"
}, 6000)
// MAIN PRODUCT PAGE OPERATIONS
// If price exists in MAIN BUY BOX or NEW BUY BOX then check if its less than CUTOFF or else go to sellers page
} else if (document.getElementById("price_inside_buybox") || document.getElementById("newBuyBoxPrice")) {
if (document.getElementById("price_inside_buybox")) {
var Title_Price = document.getElementById("price_inside_buybox").innerHTML;
}
if (document.getElementById("newBuyBoxPrice")) {
Title_Price = document.getElementById("newBuyBoxPrice").innerHTML;
}
// Parse the Title Price
Title_Price = Title_Price.match(NUMERIC_REGEXP).join('')
//console.log(Title_Price)
var Title_Price1 = 'Title Price : ' + Title_Price
const $badge = createFloatingBadge(Title_Price1, 'We will check resellers now ...');
document.body.appendChild($badge);
$badge.style.transform = "translate(0, 0)"
if (Title_Price <= CUTOFF_PRICE) {
console.log('Buy Trigger')
document.getElementsByClassName("a-button-input attach-dss-atc")[0].click();
setTimeout(function() {
var soundData = new Audio("https://github.com/kkapuria3/BestBuy-GPU-Bot/blob/dev-v2.5-mem_leak_fix/resources/alert.mp3?raw=true");
soundData.play()
document.getElementsByClassName("a-button-input")[1].click();
}, 1000)
} else {
setTimeout(function() {
window.open("https://www.amazon.com/gp/offer-listing/" + AMAZON_PRODUCT_ID + "/ref=dp_olp_unknown_mbc", '_blank');
window.close()
}, 3000)
}
} else {
const $badge = createFloatingBadge('Title Price Empty', "Lets check Resellers");
document.body.appendChild($badge);
$badge.style.transform = "translate(0, 0)"
setTimeout(function() {
console.log('timeout1');
location.href = "https://www.amazon.com/gp/offer-listing/" + AMAZON_PRODUCT_ID + "/ref=dp_olp_unknown_mbc";
}, 3000)
}
if (document.getElementById("outOfStock") && document.getElementsByClassName("aod-message-component") == null) {
const $badge = createFloatingBadge('Title Price Empty', "Refreshing...");
document.body.appendChild($badge);
$badge.style.transform = "translate(0, 0)"
setTimeout(function() {
console.log('timeoutNull')
setTimeout(function() {
console.log('timeout2');
location.href = "https://www.amazon.com/gp/offer-listing/" + AMAZON_PRODUCT_ID + "/"
}, 2000)
var Message = document.getElementsByClassName("a-text-bold aod-no-offer-normal-font")[0].innerHTML;
console.log(Message)
const $badge = createFloatingBadge('Checking Resellers', Message);
document.body.appendChild($badge);
$badge.style.transform = "translate(0, 0)"
}, 5000)
}
// When no title price is found
if (document.getElementById("outOfStock") && document.getElementsByClassName("aod-message-component")) {
const $badge = createFloatingBadge('Title Price Empty', "Refreshing...");
document.body.appendChild($badge);
$badge.style.transform = "translate(0, 0)"
setTimeout(function() {
console.log('timeout1')
var Message = document.getElementsByClassName("a-text-bold aod-no-offer-normal-font")[0].innerHTML;
console.log(Message)
const $badge = createFloatingBadge('Checking Resellers', Message);
document.body.appendChild($badge);
$badge.style.transform = "translate(0, 0)"
}, 5000)
}
}
}
//________________________________________________________________________
// MAIN CODE : LOCAL HOST TESTING
//________________________________________________________________________
// If on http://localhost:8000/, then play the sound and send test request. Check solution for test request in your terminal
if (document.URL.includes('http://localhost:8000/')) {
var DA_TA_DA = new Audio("https://github.com/kkapuria3/Best-Amazon-Bot/blob/dev-v2.0/resources/dramatic-sound-effect.wav?raw=true");
DA_TA_DA.play()
GM_xmlhttpRequest({
method: "POST",
url: "http://localhost:8000/url/dddfleoy/Captcha_lkdgslujsl.jpg",
onload: function(response) {
console.log(response.response);
GM_setValue('TEST_RESPONSE', response.response);
}
})
}
//________________________________________________________________________
// MAIN CODE : DOG PAGES
//________________________________________________________________________
else if (document.getElementById('d').alt.includes('Dogs')) {
console.log('Dogs of Amazon')
setTimeout(function() {
location.href = 'https://www.amazon.com/gp/cart/view.html'
}, 10000)
}
//________________________________________________________________________
// MAIN CODE : FINAL CHECKOUT PAGE
//________________________________________________________________________
// If Page is in Final Checkout Play the sound
else if (document.URL.includes('/gp/buy/spc/handlers/')) {
var soundData1 = new Audio("https://github.com/kkapuria3/BestBuy-GPU-Bot/blob/dev-v2.5-mem_leak_fix/resources/alert.mp3?raw=true");
soundData1.play()
setTimeout(function() {
}, 10000)
}
// On Cart Page, check if any item in cart. It can be any item. Page will redirect to Final Checkout.
else if (document.URL.includes('/gp/cart/')) {
setTimeout(function() {
if (document.getElementsByClassName("a-size-medium a-color-base sc-price sc-white-space-nowrap").length > 0) {
location.href = 'https://www.amazon.com/gp/buy/spc/handlers/display.html?hasWorkingJavascript=1'
} else if (document.getElementById("g").innerHTML.includes('ref=cs_503_link') == true) {
console.log('Amazon 503 Cart error. Lets try cart again in 5 seconds')
setTimeout(function() {
location.href = 'https://www.amazon.com/gp/cart/view.html'
}, 5000)
} else {
console.log('Empty Cart')
}
}, 10000)
}
// On Pseudo Cart Page from Title Price ATC, check if any item in cart. It can be any item. Page will redirect to Final Checkout.
else if (document.URL.includes('huc')) {
console.log(document.URL)
var soundData = new Audio("https://github.com/kkapuria3/BestBuy-GPU-Bot/blob/dev-v2.5-mem_leak_fix/resources/alert.mp3?raw=true");
soundData.play()
setTimeout(function() {
}, 3000)
}
|
<gh_stars>0
package org.rs2server.rs2.model.npc.pc;
import org.rs2server.rs2.model.player.Player;
import org.rs2server.rs2.model.player.pc.PestControlInstance;
import org.rs2server.rs2.tickable.StoppingTick;
/**
* A tick that enables a {@link PestControlPortal} to be attacked.
* Each player in the {@link PestControlInstance} also gets notified.
* @author twelve
*/
public class ShieldDownTick extends StoppingTick {
private final PestControlPortal portal;
private final PestControlInstance instance;
public ShieldDownTick(int ticks, PestControlInstance instance, PestControlPortal portal) {
super(ticks);
this.instance = instance;
this.portal = portal;
}
@Override
public void executeAndStop() {
if (instance.isDestroyed()) {
stop();
return;
}
PortalCardinality cardinality = portal.getCardinality();
portal.setAttackable(true);
instance.stream().map(Player::getActionSender).forEach(a -> {
a.sendMessage("The " + portal.getCardinality().getName() + ", " + cardinality.getDirection() + " portal shield has dropped!");
a.sendInterfaceConfig(408, cardinality.getShieldChild(), true);
});
}
}
|
#!/bin/bash
for filename in ./data/simulated/n-*; do
[ -e "$filename" ] || continue
DATASET=$(basename ${filename})
echo "dataset: ${DATASET}"
echo ""
docker run \
-v "$(pwd)/data":/data \
-v "$(pwd)/python/random_cluster":/usr/app/random_cluster \
clustering/random_cluster \
--data /data \
--simulated ${DATASET} \
-k 100
done
|
// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/runtime/renderer/xwalk_content_renderer_client.h"
#include "base/command_line.h"
#include "base/strings/utf_string_conversions.h"
#include "components/nacl/renderer/ppb_nacl_private_impl.h"
#include "components/visitedlink/renderer/visitedlink_slave.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_frame_observer.h"
#include "content/public/renderer/render_frame_observer_tracker.h"
#include "content/public/renderer/render_thread.h"
#include "grit/xwalk_application_resources.h"
#include "grit/xwalk_sysapps_resources.h"
#include "third_party/WebKit/public/platform/WebString.h"
#include "third_party/WebKit/public/platform/WebURLRequest.h"
#include "third_party/WebKit/public/web/WebDocument.h"
#include "third_party/WebKit/public/web/WebSecurityPolicy.h"
#include "xwalk/application/common/constants.h"
#include "xwalk/application/renderer/application_native_module.h"
#include "xwalk/extensions/common/xwalk_extension_switches.h"
#include "xwalk/extensions/renderer/xwalk_js_module.h"
#include "xwalk/runtime/common/xwalk_localized_error.h"
#include "xwalk/runtime/renderer/isolated_file_system.h"
#include "xwalk/runtime/renderer/pepper/pepper_helper.h"
#if defined(OS_ANDROID)
#include "xwalk/runtime/browser/android/net/url_constants.h"
#include "xwalk/runtime/renderer/android/xwalk_permission_client.h"
#include "xwalk/runtime/renderer/android/xwalk_render_process_observer.h"
#include "xwalk/runtime/renderer/android/xwalk_render_view_ext.h"
#else
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#endif
#if defined(OS_TIZEN)
#include "xwalk/runtime/common/xwalk_common_messages.h"
#endif
#if defined(OS_TIZEN_MOBILE)
#include "xwalk/runtime/renderer/tizen/xwalk_content_renderer_client_tizen.h"
#endif
#if defined(OS_TIZEN)
#include "xwalk/runtime/renderer/tizen/xwalk_render_view_ext_tizen.h"
#endif
#if !defined(DISABLE_NACL)
#include "components/nacl/renderer/nacl_helper.h"
#endif
namespace xwalk {
namespace {
xwalk::XWalkContentRendererClient* g_renderer_client;
class XWalkFrameHelper
: public content::RenderFrameObserver,
public content::RenderFrameObserverTracker<XWalkFrameHelper> {
public:
XWalkFrameHelper(
content::RenderFrame* render_frame,
extensions::XWalkExtensionRendererController* extension_controller)
: content::RenderFrameObserver(render_frame),
content::RenderFrameObserverTracker<XWalkFrameHelper>(render_frame),
extension_controller_(extension_controller) {}
virtual ~XWalkFrameHelper() {}
// RenderFrameObserver implementation.
void WillReleaseScriptContext(v8::Handle<v8::Context> context,
int world_id) override {
if (extension_controller_)
extension_controller_->WillReleaseScriptContext(
render_frame()->GetWebFrame(), context);
}
#if defined(OS_TIZEN)
void DidCommitProvisionalLoad(bool is_new_navigation) override {
blink::WebLocalFrame* frame = render_frame()->GetWebFrame();
GURL url(frame->document().url());
if (url.SchemeIs(application::kApplicationScheme)) {
blink::WebSecurityOrigin origin = frame->document().securityOrigin();
origin.grantLoadLocalResources();
}
}
#endif
private:
extensions::XWalkExtensionRendererController* extension_controller_;
DISALLOW_COPY_AND_ASSIGN(XWalkFrameHelper);
};
} // namespace
XWalkContentRendererClient* XWalkContentRendererClient::Get() {
return g_renderer_client;
}
XWalkContentRendererClient::XWalkContentRendererClient() {
DCHECK(!g_renderer_client);
g_renderer_client = this;
}
XWalkContentRendererClient::~XWalkContentRendererClient() {
g_renderer_client = NULL;
}
void XWalkContentRendererClient::RenderThreadStarted() {
CommandLine* cmd_line = CommandLine::ForCurrentProcess();
if (!cmd_line->HasSwitch(switches::kXWalkDisableExtensions))
extension_controller_.reset(
new extensions::XWalkExtensionRendererController(this));
blink::WebString application_scheme(
base::ASCIIToUTF16(application::kApplicationScheme));
blink::WebSecurityPolicy::registerURLSchemeAsSecure(application_scheme);
blink::WebSecurityPolicy::registerURLSchemeAsCORSEnabled(application_scheme);
content::RenderThread* thread = content::RenderThread::Get();
xwalk_render_process_observer_.reset(new XWalkRenderProcessObserver);
thread->AddObserver(xwalk_render_process_observer_.get());
#if defined(OS_ANDROID)
blink::WebString content_scheme(
base::ASCIIToUTF16(xwalk::kContentScheme));
blink::WebSecurityPolicy::registerURLSchemeAsLocal(content_scheme);
visited_link_slave_.reset(new visitedlink::VisitedLinkSlave);
thread->AddObserver(visited_link_slave_.get());
#endif
}
void XWalkContentRendererClient::RenderFrameCreated(
content::RenderFrame* render_frame) {
new XWalkFrameHelper(render_frame, extension_controller_.get());
#if defined(OS_ANDROID)
new XWalkPermissionClient(render_frame);
#endif
#if defined(ENABLE_PLUGINS)
new PepperHelper(render_frame);
#endif
#if !defined(DISABLE_NACL)
new nacl::NaClHelper(render_frame);
#endif
}
void XWalkContentRendererClient::RenderViewCreated(
content::RenderView* render_view) {
#if defined(OS_ANDROID)
XWalkRenderViewExt::RenderViewCreated(render_view);
#elif defined(OS_TIZEN)
XWalkRenderViewExtTizen::RenderViewCreated(render_view);
#endif
}
void XWalkContentRendererClient::DidCreateScriptContext(
blink::WebFrame* frame, v8::Handle<v8::Context> context,
int extension_group, int world_id) {
if (extension_controller_)
extension_controller_->DidCreateScriptContext(frame, context);
}
void XWalkContentRendererClient::DidCreateModuleSystem(
extensions::XWalkModuleSystem* module_system) {
scoped_ptr<extensions::XWalkNativeModule> app_module(
new application::ApplicationNativeModule());
module_system->RegisterNativeModule("application", app_module.Pass());
scoped_ptr<extensions::XWalkNativeModule> isolated_file_system_module(
new extensions::IsolatedFileSystem());
module_system->RegisterNativeModule("isolated_file_system",
isolated_file_system_module.Pass());
module_system->RegisterNativeModule("sysapps_common",
extensions::CreateJSModuleFromResource(IDR_XWALK_SYSAPPS_COMMON_API));
module_system->RegisterNativeModule("sysapps_promise",
extensions::CreateJSModuleFromResource(
IDR_XWALK_SYSAPPS_COMMON_PROMISE_API));
module_system->RegisterNativeModule("widget_common",
extensions::CreateJSModuleFromResource(
IDR_XWALK_APPLICATION_WIDGET_COMMON_API));
}
const void* XWalkContentRendererClient::CreatePPAPIInterface(
const std::string& interface_name) {
#if defined(ENABLE_PLUGINS) && !defined(DISABLE_NACL)
if (interface_name == PPB_NACL_PRIVATE_INTERFACE)
return nacl::GetNaClPrivateInterface();
#endif
return NULL;
}
bool XWalkContentRendererClient::IsExternalPepperPlugin(
const std::string& module_name) {
// TODO(bbudge) remove this when the trusted NaCl plugin has been removed.
// We must defer certain plugin events for NaCl instances since we switch
// from the in-process to the out-of-process proxy after instantiating them.
return module_name == "Native Client";
}
#if defined(OS_ANDROID)
unsigned long long XWalkContentRendererClient::VisitedLinkHash( // NOLINT
const char* canonical_url, size_t length) {
return visited_link_slave_->ComputeURLFingerprint(canonical_url, length);
}
bool XWalkContentRendererClient::IsLinkVisited(unsigned long long link_hash) { // NOLINT
return visited_link_slave_->IsVisited(link_hash);
}
#endif
bool XWalkContentRendererClient::WillSendRequest(blink::WebFrame* frame,
ui::PageTransition transition_type,
const GURL& url,
const GURL& first_party_for_cookies,
GURL* new_url) {
#if defined(OS_ANDROID)
return false;
#else
if (!xwalk_render_process_observer_->IsWarpMode()
#if defined(OS_TIZEN)
&& !xwalk_render_process_observer_->IsCSPMode()
#endif
)
return false;
GURL origin_url(frame->document().url());
GURL app_url(xwalk_render_process_observer_->app_url());
#if defined(OS_TIZEN)
// if under CSP mode.
if (xwalk_render_process_observer_->IsCSPMode()) {
if (url.GetOrigin() != app_url.GetOrigin() &&
origin_url != first_party_for_cookies &&
!first_party_for_cookies.is_empty() &&
first_party_for_cookies.GetOrigin() != app_url.GetOrigin() &&
!blink::WebSecurityOrigin::create(app_url).canRequest(url)) {
LOG(INFO) << "[BLOCK] allow-navigation: " << url.spec();
content::RenderThread::Get()->Send(new ViewMsg_OpenLinkExternal(url));
*new_url = GURL();
return true;
}
return false;
}
#endif
// if under WARP mode.
if (url.GetOrigin() == app_url.GetOrigin() ||
xwalk_render_process_observer_->CanRequest(app_url, url)) {
DLOG(INFO) << "[PASS] " << origin_url.spec() << " request " << url.spec();
return false;
}
LOG(INFO) << "[BLOCK] " << origin_url.spec() << " request " << url.spec();
#if defined(OS_TIZEN)
if (url.GetOrigin() != app_url.GetOrigin() &&
origin_url != first_party_for_cookies &&
first_party_for_cookies.GetOrigin() != app_url.GetOrigin())
content::RenderThread::Get()->Send(new ViewMsg_OpenLinkExternal(url));
#endif
*new_url = GURL();
return true;
#endif
}
void XWalkContentRendererClient::GetNavigationErrorStrings(
content::RenderView* render_view,
blink::WebFrame* frame,
const blink::WebURLRequest& failed_request,
const blink::WebURLError& error,
std::string* error_html,
base::string16* error_description) {
bool is_post = EqualsASCII(failed_request.httpMethod(), "POST");
// TODO(guangzhen): Check whether error_html is needed in xwalk runtime.
if (error_description) {
*error_description = LocalizedError::GetErrorDetails(error, is_post);
}
}
} // namespace xwalk
|
<reponame>andibateeq/mm-module
var should = require('should');
var helper = require('../helper');
var validate = require('mm-models').validator.core;
var generateCode = require('../../src/utils/code-generator');
var manager;
function getData() {
var Account = require('mm-models').core.Account;
var account = new Account();
var code = generateCode('UnitTest');
account.username = `<EMAIL>`;
account.password ='<PASSWORD>';// `${code}`;
return account;
}
before('#00. connect db', function(done) {
helper.getDb()
.then(db => {
var AccountManager = require('../../src/managers/core/account-manager');
manager = new AccountManager(db, {
username: 'unit-test'
});
done();
})
.catch(e => {
done(e);
})
});
var data = getData();
var createdId;
it('#01. should success when create new data', function(done) {
manager.create(data)
.then(id => {
id.should.be.Object();
createdId = id;
done();
})
.catch(e => {
done(e);
})
});
var createdData;
it(`#02. should success when get created data with id`, function(done) {
manager.getSingleByQuery({
_id: createdId
})
.then(data => {
validate.account(data);
createdData = data;
done();
})
.catch(e => {
done(e);
})
});
it(`#03. should success when update created data`, function(done) {
manager.update(createdData)
.then(id => {
createdId.toString().should.equal(id.toString());
done();
})
.catch(e => {
done(e);
});
});
it(`#04. should success when get updated data with id`, function(done) {
manager.getSingleByQuery({
_id: createdId
})
.then(data => {
validate.account(data);
data.username.should.equal(createdData.username);
// data.password.should.equal(createdData.password);
done();
})
.catch(e => {
done(e);
});
});
it('#05. get account using username and password', function(done) {
manager.getByUsernameAndPassword(data.username, data.password)
.then(account => {
validate.account(account);
done();
})
.catch(e => {
done(e);
});
});
it(`#06. should success when delete data`, function(done) {
manager.delete(createdData)
.then(id => {
createdId.toString().should.equal(id.toString());
done();
})
.catch(e => {
done(e);
});
});
it(`#07. should _deleted=true`, function(done) {
manager.getSingleByQuery({
_id: createdId
})
.then(data => {
validate.account(data);
data._deleted.should.be.Boolean();
data._deleted.should.equal(true);
done();
})
.catch(e => {
done(e);
})
});
it('#08. should error when create new data with same username', function(done) {
var data = Object.assign({}, createdData);
delete data._id;
manager.create(data)
.then(id => {
id.should.be.Object();
createdId = id;
done("Should not be able to create data with same username");
})
.catch(e => {
try {
e.errors.should.have.property('username');
done();
}
catch (e) {
done(e);
}
})
});
it('#09. should error with property username and password ', function(done) {
manager.create({})
.then(id => {
done("Should not be error with property username and password");
})
.catch(e => {
try {
e.errors.should.have.property('username');
e.errors.should.have.property('password');
done();
}
catch (ex) {
done(ex);
}
})
});
|
<gh_stars>1-10
#pragma once
#include <SplayLibrary/Core/types.hpp>
#include <SplayLibrary/Core/Framebuffer.hpp>
namespace spl
{
class DefaultFramebuffer : public Framebuffer
{
public:
DefaultFramebuffer() = delete;
DefaultFramebuffer(const DefaultFramebuffer& framebuffer) = delete;
DefaultFramebuffer(DefaultFramebuffer&& framebuffer) = delete;
DefaultFramebuffer& operator=(const DefaultFramebuffer& framebuffer) = delete;
DefaultFramebuffer& operator=(DefaultFramebuffer&& framebuffer) = delete;
private:
DefaultFramebuffer(Window* window);
using Framebuffer::createNewTextureAttachment;
using Framebuffer::getTextureAttachment;
using Framebuffer::createNewRenderBufferAttachment;
using Framebuffer::getRenderBufferAttachment;
using Framebuffer::removeAttachment;
~DefaultFramebuffer() = default;
friend class Window;
};
}
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe ActivityGroup, type: :model do
describe 'validations' do
subject { described_class.new }
it { is_expected.to validate_presence_of(:project) }
it { is_expected.to validate_presence_of(:duration) }
it { is_expected.to validate_presence_of(:description) }
end
describe '.generate' do
subject(:instance) { described_class.generate(Activity.all) }
context 'when activity is not empty' do
let(:project) { create(:project) }
before do
create_list(
:activity, 2,
user: project.user,
project: project,
description: 'Review code',
started_at: Date.new(2019, 1, 1),
stopped_at: Date.new(2019, 1, 2)
)
end
it { expect(instance.size).to eq(1) }
it { expect(instance.first.project).to eq(project) }
it { expect(instance.first.description).to eq('Review code') }
it { expect(instance.first.duration).to eq(172_800) }
end
context 'when activity is empty' do
let(:activities) { [] }
it { expect(instance).to be_empty }
end
end
end
|
export { default } from 'ember-medium-editor/components/me-toolbar';
|
<filename>docs/html/search/enumvalues_11.js<gh_stars>1-10
var searchData=
[
['unknown',['unknown',['../class_smol_dock_1_1_amino_acid.html#a08692b12e7f53812c5258bd8b805875daad921d60486366258809553a3db49a4a',1,'SmolDock::AminoAcid::unknown()'],['../class_smol_dock_1_1_atom.html#a57e9a532fd04e1846c0d83edebb9fd41aad921d60486366258809553a3db49a4a',1,'SmolDock::Atom::unknown()']]]
];
|
<gh_stars>1-10
/*
*
*/
package net.community.apps.common;
import java.awt.Component;
import org.w3c.dom.Element;
import net.community.chest.ui.helpers.XmlDocumentComponentInitializer;
/**
* <P>Copyright 2009 as per GPLv2</P>
*
* @author <NAME>.
* @since Aug 5, 2009 11:12:02 AM
*/
public interface BaseMainComponent
extends XmlDocumentComponentInitializer,
FileLoadComponent{
Component getMainFrame ();
public static final String MANIFEST_SECTION_NAME="show-manifest-dialog";
Element getManifestDialogElement ();
void showManifest (Object anchor, Element dlgElem) throws Exception;
void showManifest () throws Exception;
void exitApplication ();
}
|
class ProbabilityProcessor:
def __init__(self, application_type, parameters):
self.param = {'application': application_type, 'params': parameters}
def process_probabilities(self, raw_probabilities):
if self.param['application'] == 'binary':
probability_of_one = raw_probabilities
probability_of_zero = 1 - probability_of_one
return probability_of_one, probability_of_zero
else:
return raw_probabilities
|
use std::collections::BTreeMap;
struct Specification {
type_: fn() -> Type,
config: fn() -> Config,
}
struct Type {
to_string: fn() -> String,
}
struct Config {
env: fn() -> Option<BTreeMap<String, String>>,
}
fn process_environment(spec: Specification) -> BTreeMap<String, String> {
let type_string = (spec.type_().to_string)();
let env_config = (spec.config().env)();
let mut result_map = BTreeMap::new();
if let Some(env_map) = env_config {
for (key, value) in env_map {
result_map.insert(key, value);
}
}
result_map
}
|
#!/bin/bash
set -o errexit -o pipefail
if [[ ${target_platform} =~ linux.* ]] || [[ ${target_platform} == win-32 ]] || [[ ${target_platform} == win-64 ]] || [[ ${target_platform} == osx-64 ]]; then
export DISABLE_AUTOBREW=1
${R} CMD INSTALL --build .
else
mkdir -p "${PREFIX}"/lib/R/library/DOT
mv ./* "${PREFIX}"/lib/R/library/DOT
if [[ ${target_platform} == osx-64 ]]; then
pushd "${PREFIX}"
for libdir in lib/R/lib lib/R/modules lib/R/library lib/R/bin/exec sysroot/usr/lib; do
pushd "${libdir}" || exit 1
while IFS= read -r -d '' SHARED_LIB
do
echo "fixing SHARED_LIB ${SHARED_LIB}"
install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5.0-MRO/Resources/lib/libR.dylib "${PREFIX}"/lib/R/lib/libR.dylib "${SHARED_LIB}" || true
install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libR.dylib "${PREFIX}"/lib/R/lib/libR.dylib "${SHARED_LIB}" || true
install_name_tool -change /usr/local/clang4/lib/libomp.dylib "${PREFIX}"/lib/libomp.dylib "${SHARED_LIB}" || true
install_name_tool -change /usr/local/gfortran/lib/libgfortran.3.dylib "${PREFIX}"/lib/libgfortran.3.dylib "${SHARED_LIB}" || true
install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libquadmath.0.dylib "${PREFIX}"/lib/libquadmath.0.dylib "${SHARED_LIB}" || true
install_name_tool -change /usr/local/gfortran/lib/libquadmath.0.dylib "${PREFIX}"/lib/libquadmath.0.dylib "${SHARED_LIB}" || true
install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libgfortran.3.dylib "${PREFIX}"/lib/libgfortran.3.dylib "${SHARED_LIB}" || true
install_name_tool -change /usr/lib/libgcc_s.1.dylib "${PREFIX}"/lib/libgcc_s.1.dylib "${SHARED_LIB}" || true
install_name_tool -change /usr/lib/libiconv.2.dylib "${PREFIX}"/sysroot/usr/lib/libiconv.2.dylib "${SHARED_LIB}" || true
install_name_tool -change /usr/lib/libncurses.5.4.dylib "${PREFIX}"/sysroot/usr/lib/libncurses.5.4.dylib "${SHARED_LIB}" || true
install_name_tool -change /usr/lib/libicucore.A.dylib "${PREFIX}"/sysroot/usr/lib/libicucore.A.dylib "${SHARED_LIB}" || true
install_name_tool -change /usr/lib/libexpat.1.dylib "${PREFIX}"/lib/libexpat.1.dylib "${SHARED_LIB}" || true
install_name_tool -change /usr/lib/libcurl.4.dylib "${PREFIX}"/lib/libcurl.4.dylib "${SHARED_LIB}" || true
install_name_tool -change /usr/lib/libc++.1.dylib "${PREFIX}"/lib/libc++.1.dylib "${SHARED_LIB}" || true
install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libc++.1.dylib "${PREFIX}"/lib/libc++.1.dylib "${SHARED_LIB}" || true
done < <(find . \( -type f -iname "*.dylib" -or -iname "*.so" -or -iname "R" \) -print0)
popd
done
popd
fi
fi
|
# Copyright 2021 ISP RAS
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
################################################################################
#!/bin/bash -eu
# Build libFuzzer targets.
mkdir build
cd build
cmake -D STATIC=ON -D TESTS=OFF \
-DCMAKE_CXX_COMPILER=clang++ \
-DCMAKE_CXX_FLAGS="-g -fsanitize=fuzzer-no-link,address,bounds,integer,undefined,null,float-divide-by-zero" \
..
CMAKE_BUILD_PARALLEL_LEVEL=$(nproc) cmake --build .
CXX="clang++"
CXXFLAGS="-g -fsanitize=fuzzer,address,integer,bounds,null,undefined,float-divide-by-zero"
$CXX $CXXFLAGS -I/xlnt/include -I/xlnt/third-party/libstudxml -O2 -o load_fuzzer.o -c ../load_fuzzer.cc
$CXX $CXXFLAGS load_fuzzer.o ./source/libxlnt.a -o /load_fuzzer
cd .. && rm -rf build && mkdir build && cd build
# Build Sydr targets.
cmake -DSTATIC=ON -D TESTS=OFF \
-DCMAKE_CXX_COMPILER=clang++ \
-DCMAKE_CXX_FLAGS=-g \
..
CMAKE_BUILD_PARALLEL_LEVEL=$(nproc) cmake --build .
CXX="clang++"
CXXFLAGS="-g"
$CXX $CXXFLAGS -I/xlnt/include -I/xlnt/third-party/libstudxml -O2 -o load_sydr.o -c ../load_sydr.cc
$CXX $CXXFLAGS load_sydr.o ./source/libxlnt.a -o /load_sydr
# Build cov targets.
cmake -DSTATIC=ON -D TESTS=OFF \
-DCMAKE_CXX_COMPILER=clang++ \
-DCMAKE_CXX_FLAGS="-fprofile-instr-generate -fcoverage-mapping" \
..
CMAKE_BUILD_PARALLEL_LEVEL=$(nproc) cmake --build .
CXX="clang++"
CXXFLAGS="-fprofile-instr-generate -fcoverage-mapping"
LDFLAGS="-fprofile-instr-generate"
$CXX $CXXFLAGS -I/xlnt/include -I/xlnt/third-party/libstudxml -O2 -o load_cov.o -c ../load_sydr.cc
$CXX $CXXFLAGS load_cov.o ./source/libxlnt.a -o /load_cov
|
/*!
* Module dependencies.
*/
var util = require('util'),
utils = require('keystone-utils'),
super_ = require('../field');
/**
* TextArray FieldType Constructor
* @extends Field
* @api public
*/
function textarray(list, path, options) {
this._nativeType = [String];
this._underscoreMethods = ['crop'];
textarray.super_.call(this, list, path, options);
}
/*!
* Inherit from Field
*/
util.inherits(textarray, super_);
/**
* Crops the string to the specifed length.
*
* @api public
*/
textarray.prototype.crop = function(item, length, append, preserveWords) {
return utils.cropString(item.get(this.path), length, append, preserveWords);
};
/**
* Updates the value for this field in the item from a data object
*
* @api public
*/
textarray.prototype.updateItem = function(item, data) {
if ( data[this.path] === undefined ) {
item.set(this.path, []);
} else {
item.set(this.path, data[this.path]);
}
}
/*!
* Export class
*/
exports = module.exports = textarray;
|
<filename>packages/hyphenated/src/parseText.js
const whiteSpaceRegex = /\s|\u0085/u;
const separatorRegex = /(?!['@_])[\s\p{P}]/u;
const getSpacesAndFragments = text => {
const fragments = [];
let fragment = '';
let space = '';
const addFragment = () => {
if (fragment.length > 0) {
fragments.push(fragment);
fragment = '';
}
};
const addSpace = () => {
if (space.length > 0) {
fragments.push(space);
space = '';
}
};
for (let charIndex = 0; charIndex < text.length; charIndex++) {
const char = text.charAt(charIndex);
if (whiteSpaceRegex.test(char)) {
addFragment();
space += char;
} else {
addSpace();
fragment += char;
}
}
addFragment();
addSpace();
return fragments;
};
const getWordsAndCharacters = fragment => {
let wordStartIndex = null;
let charIndex;
const words = [];
const addCharacter = char => words.push(char);
const addWord = characterIndex => {
if (wordStartIndex !== null) {
const word = fragment.slice(wordStartIndex, characterIndex);
wordStartIndex = null;
words.push(word);
}
};
for (charIndex = 0; charIndex < fragment.length; charIndex++) {
const char = fragment.charAt(charIndex);
const isSeparator = separatorRegex.test(char);
if (isSeparator) {
addWord(charIndex);
addCharacter(char);
} else {
if (wordStartIndex === null) {
wordStartIndex = charIndex;
}
}
}
addWord(fragment.length);
return words;
};
export const parseText = (text = '') => {
const allFragments = [];
const spacesAndFragments = getSpacesAndFragments(text);
if (spacesAndFragments.length) {
let isSpace = whiteSpaceRegex.test(spacesAndFragments[0]);
for (const fragment of spacesAndFragments) {
if (isSpace) {
allFragments.push(fragment);
} else {
const wordsAndCharacters = getWordsAndCharacters(fragment);
allFragments.push(...wordsAndCharacters);
}
isSpace = !isSpace;
}
}
return allFragments;
};
|
import { Injectable, EventEmitter } from '@angular/core';
@Injectable()
export class NavbarService {
static changeEvent = new EventEmitter();
static setSearch(data: any) {
console.log('setSearch');
this.changeEvent.emit({search: data});
}
}
|
<gh_stars>1-10
import { Container } from 'inversify';
import TYPES from './types';
import IConfig from './config/interface';
import NconfImpl from './config/nconf/impl';
import ILogger from './logger/i-logger';
import ConsoleLogger from './logger/console-logger';
import IAssignmentService from './service/assignment/interface';
import AssignmentService from './service/assignment/impl';
import { interfaces, TYPE } from 'inversify-restify-utils';
import { AssignmentController } from './controller/assignment';
import { RpcModule, NconfModule } from './interfaces';
import * as rpcModule from '@nazar910/rpc-module';
import * as nconf from 'nconf';
import IRpcClient from './rpc/client/interface';
import RpcClient from './rpc/client/impl';
import UserController from './controller/user';
import IUserService from './service/user/interface';
import UserService from './service/user/impl';
const container = new Container();
container.bind<NconfModule>(TYPES.NconfModule).toConstantValue(nconf);
container.bind<IConfig>(TYPES.Config).to(NconfImpl).inSingletonScope();
container.bind<ILogger>(TYPES.Logger).to(ConsoleLogger);
container.bind<RpcModule>(TYPES.RpcModule).toConstantValue(rpcModule);
container.bind<IRpcClient>(TYPES.RpcClient).to(RpcClient).inSingletonScope();
container.bind<interfaces.Controller>(TYPE.Controller).to(UserController).whenTargetNamed('UserController');
container.bind<IUserService>(TYPES.UserService).to(UserService);
container.bind<interfaces.Controller>(TYPE.Controller).to(AssignmentController).whenTargetNamed('AssignmentController');
container.bind<IAssignmentService>(TYPES.AssignmentService).to(AssignmentService);
export default container;
|
require 'pronto'
require_relative 'clang_tidy/diagnostic'
require_relative 'clang_tidy/offence'
require_relative 'clang_tidy/parser'
Diagnostic = ::Pronto::ClangTidy::Diagnostic
Offence = ::Pronto::ClangTidy::Offence
Parser = ::Pronto::ClangTidy::Parser
module Pronto
class ClangTidyRunner < Runner
def run
offences = Parser.new(clang_tidy_output_file).read_clang_tidy_output
return [] if no_patches? || offences.length.zero?
# loop through all offences in clang-tidy output
offences.map do |offence|
build_message_for(offence)
# Header warnings are repeated for every compilation unit that includes
# them. Use uniq to ignore repeated messages
end.flatten.compact.uniq
end
private
def no_patches?
!@patches || @patches.count.zero?
end
# creates a new pronto message for offence
def build_message_for(offence)
# find the line for the main diag in the current offence
main_line = find_line_for_diag(offence.main)
# if the main diagnostic in the offence points to a changed line
if main_line
new_message(main_line, offence.main.level, offence.main_message)
else
# try to find a note from the offence that belongs to changed a line
note_line = find_first_line_for_diags(offence.notes)
new_message(note_line, offence.main.level, offence.note_message)
end
end
# searches through patches for the diagnostic's line and returns it
# returns nil if the line was not changed
def find_line_for_diag(diag)
file_patch = @patches.find do |patch|
patch.new_file_full_path == Pathname.new(diag.filename)
end
return nil if file_patch.nil?
file_patch.added_lines.find do |added_line|
added_line.new_lineno == diag.line_no
end
end
# searches through the diags_array to find a diag that points to a changed
# line and returns that line
# returns nil when none of the diags point to a changed line
def find_first_line_for_diags(diags_array)
diags_array.map { |diag| find_line_for_diag(diag) }
.compact.first
end
def new_message(line, offence_level, offence_message)
return nil if line.nil?
path = line.patch.delta.new_file[:path]
Message.new(path, line, pronto_level(offence_level),
offence_message, nil, self.class)
end
def pronto_level(clang_level)
case clang_level
when :warning
:warning
when :error
:error
when :fatal
:fatal
else
:info
end
end
def clang_tidy_output_file
ENV['PRONTO_CLANG_TIDY_OUTFILE'] || 'clang-tidy.out'
end
end
end
|
package slice
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestAddRemove1(t *testing.T) {
s := []string{}
s = AddUnique(s, "hello")
require.Equal(t, []string{"hello"}, s)
s = AddUnique(s, "hello")
require.Equal(t, []string{"hello"}, s)
s = AddUnique(s, "there")
require.Equal(t, []string{"hello", "there"}, s)
s = AddUnique(s, "there")
require.Equal(t, []string{"hello", "there"}, s)
s = AddUnique(s, "general")
require.Equal(t, []string{"general", "hello", "there"}, s)
s = AddUnique(s, "general")
require.Equal(t, []string{"general", "hello", "there"}, s)
s = AddUnique(s, "kenobi")
require.Equal(t, []string{"general", "hello", "kenobi", "there"}, s)
s = AddUnique(s, "kenobi")
require.Equal(t, []string{"general", "hello", "kenobi", "there"}, s)
s = Remove(s, "general")
require.Equal(t, []string{"hello", "kenobi", "there"}, s)
s = Remove(s, "there")
require.Equal(t, []string{"hello", "kenobi"}, s)
}
func TestAddRemove2(t *testing.T) {
s := []string{}
s = AddUnique(s, "first")
require.Equal(t, []string{"first"}, s)
s = AddUnique(s, "second")
require.Equal(t, []string{"first", "second"}, s)
s = AddUnique(s, "third")
require.Equal(t, []string{"first", "second", "third"}, s)
s = AddUnique(s, "fourth")
require.Equal(t, []string{"first", "fourth", "second", "third"}, s)
s = AddUnique(s, "another first")
require.Equal(t, []string{"another first", "first", "fourth", "second", "third"}, s)
s = AddUnique(s, "very last")
require.Equal(t, []string{"another first", "first", "fourth", "second", "third", "very last"}, s)
s = AddUnique(s, "middle")
require.Equal(t, []string{"another first", "first", "fourth", "middle", "second", "third", "very last"}, s)
s = Remove(s, "missing element")
require.Equal(t, []string{"another first", "first", "fourth", "middle", "second", "third", "very last"}, s)
s = Remove(s, "another first")
require.Equal(t, []string{"first", "fourth", "middle", "second", "third", "very last"}, s)
s = Remove(s, "very last")
require.Equal(t, []string{"first", "fourth", "middle", "second", "third"}, s)
s = Remove(s, "middle")
require.Equal(t, []string{"first", "fourth", "second", "third"}, s)
s = Remove(s, "not in there")
require.Equal(t, []string{"first", "fourth", "second", "third"}, s)
s = Remove(s, "fourth")
require.Equal(t, []string{"first", "second", "third"}, s)
s = Remove(s, "third")
require.Equal(t, []string{"first", "second"}, s)
s = Remove(s, "first")
require.Equal(t, []string{"second"}, s)
s = Remove(s, "missing element")
require.Equal(t, []string{"second"}, s)
s = Remove(s, "second")
require.Equal(t, []string{}, s)
s = Remove(s, "first")
require.Equal(t, []string{}, s)
}
func TestAddRemove3(t *testing.T) {
s := []string{}
s = AddUnique(s, "Hello", "There", "General", "Kenobi")
require.Equal(t, []string{"General", "Hello", "Kenobi", "There"}, s)
}
func TestIdentical(t *testing.T) {
{
a := []string{"one", "two", "three"}
b := []string{"one", "two", "three"}
c := []string{"one", "two"}
d := []string{"one", "three", "two"}
e := []string{"one", "two", "three", "four"}
require.True(t, Identical(a, b))
require.False(t, Identical(a, c))
require.False(t, Identical(a, d))
require.False(t, Identical(a, e))
}
}
|
import {prisma} from "../../../../database/prismaClient"
interface IUpdateEndDate {
id_delivery: string
id_deliveryman: string
}
export class UpdateEndDateUseCase {
async execute({id_delivery, id_deliveryman}: IUpdateEndDate){
const result = await prisma.deliveries.updateMany({
where: {
id: id_delivery,
id_deliveryman
},
data: {
end_at: new Date()
}
})
return result
}
}
|
<filename>bin/superhero/fs/index.js
const fs = require('fs')
class Fs
{
/**
* @param {string} wd Working directory
* @param {string} cli Command line interface
*/
constructor(wd, cli)
{
this.wd = wd
this.cli = cli
}
mkdir(dir)
{
this.cli.write(' Creating path: ' + dir, 'green')
const path = this.wd + '/' + dir
fs.mkdirSync(path, { recursive: true })
}
writeFile(file, content)
{
const
path = this.wd + '/' + file,
file_exists = fs.existsSync(path)
if(file_exists)
{
this.cli.write(' Existing file: ' + file, 'red')
}
else
{
this.cli.write(' Creating file: ' + file, 'green')
fs.writeFileSync(path, content)
}
}
}
module.exports = Fs
|
import { TIME_SUB, TIME_U_DAY, TIME_U_HOUR, TIME_U_MICRO, TIME_U_MIN, TIME_U_MS, TIME_U_SEC } from '../unit'
import Base from './Base'
export default class Time extends Base {
#idx = {}
constructor () {
super(TIME_SUB)
this.#idx = {
micro: super.index(TIME_U_MICRO),
ms: super.index(TIME_U_MS),
sec: super.index(TIME_U_SEC),
min: super.index(TIME_U_MIN),
hour: super.index(TIME_U_HOUR),
day: super.index(TIME_U_DAY)
}
}
selectMicro (number) {
super.input(number)
let result = []
// micro
result[this.#idx.micro] = number
// ms
result[this.#idx.ms] = super.quotient(1000)
// sec
const sec = 1000 * 1000
result[this.#idx.sec] = super.quotient(sec)
// min
const min = sec * 60
result[this.#idx.min] = super.quotient(min)
// hour
const hour = min * 60
result[this.#idx.hour] = super.quotient(hour)
// day
const day = hour * 24
result[this.#idx.day] = super.quotient(day)
return result
}
selectMs (number) {
super.input(number)
let result = []
// micro
result[this.#idx.micro] = super.product(1000)
// ms
result[this.#idx.ms] = number
// sec
result[this.#idx.sec] = super.quotient(1000)
// min
const min = 1000 * 60
result[this.#idx.min] = super.quotient(min)
// hour
const hour = min * 60
result[this.#idx.hour] = super.quotient(hour)
// day
const day = hour * 24
result[this.#idx.day] = super.quotient(day)
return result
}
selectSec (number) {
super.input(number)
let result = []
// micro
result[this.#idx.micro] = super.product(Math.pow(10, 6))
// ms
result[this.#idx.ms] = super.product(1000)
// sec
result[this.#idx.sec] = number
// min
result[this.#idx.min] = super.quotient(60)
// hour
const hour = 60 * 60
result[this.#idx.hour] = super.quotient(hour)
// day
const day = hour * 24
result[this.#idx.day] = super.quotient(day)
return result
}
selectMin (number) {
super.input(number)
let result = []
// min
result[this.#idx.min] = number
// hour
result[this.#idx.hour] = super.quotient(60)
// day
result[this.#idx.day] = super.quotient(60 * 24)
// sec
result[this.#idx.sec] = super.product(60)
// ms
result[this.#idx.ms] = super.product(60 * 1000)
// micro
result[this.#idx.micro] = super.product(60 * Math.pow(10, 6))
return result
}
selectHour (number) {
super.input(number)
let result = []
// hour
result[this.#idx.hour] = number
// day
result[this.#idx.day] = super.quotient(24)
// min
result[this.#idx.min] = super.product(60)
// sec
const sec = 60 * 60
result[this.#idx.sec] = super.product(sec)
// ms
const ms = sec * 1000
result[this.#idx.ms] = super.product(ms)
// micro
const micro = ms * 1000
result[this.#idx.micro] = super.product(micro)
return result
}
selectDay (number) {
super.input(number)
let result = []
// day
result[this.#idx.day] = number
// hour
result[this.#idx.hour] = super.product(24)
// min
const min = 24 * 60
result[this.#idx.min] = super.product(min)
// sec
const sec = min * 60
result[this.#idx.sec] = super.product(sec)
// ms
const ms = sec * 1000
result[this.#idx.ms] = super.product(ms)
// micro
const micro = ms * 1000
result[this.#idx.micro] = super.product(micro)
return result
}
}
|
"use strict";
var crypto = require('crypto');
var wsse = require('wsse');
var validPasswordTypes = ['PasswordDigest', 'PasswordText'];
function WSSecurity(username, password, options) {
options = options || {};
this._username = username;
this._password = password;
this._token = wsse({
username: username,
password: password
});
if (typeof options === 'string') {
this._passwordType = options ?
options :
'PasswordText';
options = {};
} else {
this._passwordType = options.passwordType ?
options.passwordType :
'PasswordText';
}
if (validPasswordTypes.indexOf(this._passwordType) === -1) {
this._passwordType = 'PasswordText';
}
this._hasTimeStamp = options.hasTimeStamp || typeof options.hasTimeStamp === 'boolean' ? !!options.hasTimeStamp : true;
if (options.hasNonce != null) {
this._hasNonce = !!options.hasNonce;
}
this._hasTokenCreated = options.hasTokenCreated || typeof options.hasTokenCreated === 'boolean' ? !!options.hasTokenCreated : true;
if (options.actor != null) {
this._actor = options.actor;
}
if (options.mustUnderstand != null) {
this._mustUnderstand = !!options.mustUnderstand;
}
}
WSSecurity.prototype.toXML = function() {
function getDate(d) {
function pad(n) {
return n < 10 ? '0' + n : n;
}
return d.getUTCFullYear() + '-'
+ pad(d.getUTCMonth() + 1) + '-'
+ pad(d.getUTCDate()) + 'T'
+ pad(d.getUTCHours()) + ':'
+ pad(d.getUTCMinutes()) + ':'
+ pad(d.getUTCSeconds()) + 'Z';
}
var now = new Date(this._token.getCreated());
var created = this._token.getCreated();
var timeStampXml = '';
if (this._hasTimeStamp) {
var expires = getDate( new Date(now.getTime() + (1000 * 600)) );
timeStampXml = "<wsu:Timestamp wsu:Id=\"Timestamp-"+created+"\">" +
"<wsu:Created>"+created+"</wsu:Created>" +
"<wsu:Expires>"+expires+"</wsu:Expires>" +
"</wsu:Timestamp>";
}
var password, nonce;
if (this._hasNonce || this._passwordType !== 'PasswordText') {
var nHash = crypto.createHash('sha1');
nHash.update(created + Math.random());
nonce = nHash.digest('base64');
}
if (this._passwordType === 'PasswordText') {
password = "<wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">" + this._password + "</wsse:Password>";
if (nonce) {
password += "<wsse:Nonce EncodingType=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary\">" + nonce + "</wsse:Nonce>";
}
} else {
password = "<wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest\">" + this._token.getPasswordDigest() + "</wsse:Password>" +
"<wsse:Nonce EncodingType=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary\">" + this._token.getNonceBase64() + "</wsse:Nonce>";
}
return "<wsse:Security " + (this._actor ? "soap:actor=\"" + this._actor + "\" " : "") +
(this._mustUnderstand ? "soap:mustUnderstand=\"1\" " : "") +
"xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">" +
timeStampXml +
"<wsse:UsernameToken wsu:Id=\"UsernameToken-" + created +"\">"+
"<wsse:Username>" + this._username + "</wsse:Username>" +
password +
(this._hasTokenCreated ? "<wsu:Created>" + created + "</wsu:Created>" : "") +
"</wsse:UsernameToken>" +
"</wsse:Security>";
};
module.exports = WSSecurity;
|
<filename>Utilities/VisItBridge/avt/Pipeline/Sources/avtOriginatingSource.h
/*****************************************************************************
*
* Copyright (c) 2000 - 2010, Lawrence Livermore National Security, LLC
* Produced at the Lawrence Livermore National Laboratory
* LLNL-CODE-400124
* All rights reserved.
*
* This file is part of VisIt. For details, see https://visit.llnl.gov/. The
* full copyright notice is contained in the file COPYRIGHT located at the root
* of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the disclaimer below.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the disclaimer (as noted below) in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of the LLNS/LLNL nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY,
* LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
*****************************************************************************/
// ************************************************************************* //
// avtOriginatingSource.h //
// ************************************************************************* //
#ifndef AVT_ORIGINATING_SOURCE_H
#define AVT_ORIGINATING_SOURCE_H
#include <pipeline_exports.h>
#include <void_ref_ptr.h>
#include <avtQueryableSource.h>
#include <avtDataRequest.h>
#include <avtContract.h>
class avtInlinePipelineSource;
class avtMetaData;
typedef avtDataRequest_p (*LoadBalanceFunction)(void *,
avtContract_p);
typedef bool (*StreamingCheckFunction)(void *,
avtContract_p);
typedef void (*InitializeProgressCallback)(void *, int);
// ****************************************************************************
// Class: avtOriginatingSource
//
// Purpose:
// This is the originator of a pipeline's update/execute cycle. As such,
// it owns the actual pipeline object.
//
// Programmer: <NAME>
// Creation: May 23, 2001
//
// Modifications:
//
// <NAME>, Thu Sep 20 01:01:49 PDT 2001
// Added dynamic checker callback function so it can make determinations
// about the network it will execute.
//
// <NAME>, Thu Oct 25 16:44:24 PDT 2001
// Add a virtual function for whether or not this source permits dynamic
// load balancing.
//
// <NAME>, Fri Nov 15 09:07:36 PST 2002
// Added virtual method Query.
//
// <NAME>, Mon Jul 28 16:33:34 PDT 2003
// Derived from avtQueryableSource instead of avtDataObjectSource.
//
// <NAME>, Wed Nov 12 18:26:21 PST 2003
// Added virtual method FindElementForPoint.
//
// <NAME>, Mon Dec 22 14:48:57 PST 2003
// Added virtual method GetDomainName.
//
// <NAME>, Tue May 25 16:16:25 PDT 2004
// Add virtual method 'QueryZoneCenter'.
//
// <NAME>, Wed Jun 9 09:13:39 PDT 2004
// Added species aux data.
//
// <NAME>, Thu Jun 10 18:31:22 PDT 2004
// Renamed QueryZoneCenter to QueryCoords, added bool arg.
//
// <NAME>, Thu Dec 16 17:16:33 PST 2004
// Added another bool arg to QueryCoords.
//
// <NAME>, Mon Jan 3 13:40:42 PST 2005
// Added GetSIL method.
//
// <NAME>, Tue Jan 25 07:59:28 PST 2005
// Added const char *arg to QueryCoords.
//
// <NAME>, Wed Feb 7 13:18:28 PST 2007
// Add support for progress from time queries.
//
// <NAME>, Tue Feb 19 19:45:43 PST 2008
// Rename "dynamic" to "streaming", since we really care about whether we
// are streaming, not about whether we are doing dynamic load balancing.
// And the two are no longer synonymous.
//
// <NAME>, Thu Jun 12 16:12:38 PDT 2008
// Add method CanDoStreaming.
//
// ****************************************************************************
class PIPELINE_API avtOriginatingSource : virtual public avtQueryableSource
{
friend class avtInlinePipelineSource;
public:
avtOriginatingSource();
virtual ~avtOriginatingSource();
virtual avtOriginatingSource *GetOriginatingSource(void) { return this;};
avtMetaData *GetMetaData(void) { return metadata; };
void GetMeshAuxiliaryData(const char *type,
void *args, avtContract_p,
VoidRefList &);
void GetVariableAuxiliaryData(const char *type,
void *args, avtContract_p,
VoidRefList &);
void GetMaterialAuxiliaryData(const char *type,
void *args, avtContract_p,
VoidRefList &);
void GetSpeciesAuxiliaryData(const char *type,
void *args, avtContract_p,
VoidRefList &);
virtual bool Update(avtContract_p);
virtual bool CanDoStreaming(avtContract_p) {return true;}
static void SetLoadBalancer(LoadBalanceFunction,void *);
static void SetStreamingChecker(StreamingCheckFunction,
void *);
static void RegisterInitializeProgressCallback(
InitializeProgressCallback, void *);
void SetNumberOfExecutions(int numEx)
{ numberOfExecutions = numEx;
haveIssuedProgress = false; };
virtual avtDataRequest_p GetFullDataRequest(void);
avtContract_p GetGeneralContract(void);
// Define this so derived types don't have to.
virtual void Query(PickAttributes *){;};
virtual avtSIL *GetSIL(int timestep){return NULL;};
virtual bool FindElementForPoint(const char*, const int,
const int, const char*, double[3], int &)
{ return false;};
virtual void GetDomainName(const std::string &, const int,
const int, std::string &) {;};
virtual bool QueryCoords(const std::string &, const int,
const int, const int, double[3],
const bool, const bool = false, const char *mn=NULL)
{ return false;};
protected:
avtMetaData *metadata;
static InitializeProgressCallback
initializeProgressCallback;
static void *initializeProgressCallbackArgs;
virtual bool FetchData(avtDataRequest_p) = 0;
virtual void FetchMeshAuxiliaryData(const char *type,
void *args, avtDataRequest_p,
VoidRefList &);
virtual void FetchVariableAuxiliaryData(const char *type,
void *args, avtDataRequest_p,
VoidRefList &);
virtual void FetchMaterialAuxiliaryData(const char *type,
void *args, avtDataRequest_p,
VoidRefList &);
virtual void FetchSpeciesAuxiliaryData(const char *type,
void *args, avtDataRequest_p,
VoidRefList &);
avtDataRequest_p BalanceLoad(avtContract_p);
virtual bool UseLoadBalancer(void) { return true; };
virtual bool ArtificialPipeline(void) { return false; };
virtual int NumStagesForFetch(avtDataRequest_p);
private:
static LoadBalanceFunction loadBalanceFunction;
static void *loadBalanceFunctionArgs;
static StreamingCheckFunction streamingCheckFunction;
static void *streamingCheckFunctionArgs;
void InitPipeline(avtContract_p);
virtual bool CanDoStreaming(void);
// These data members are important when there are multiple executions, like
// with the time loop filter. This information is important to keep track
// of progress.
int numberOfExecutions;
bool haveIssuedProgress;
};
#endif
|
<gh_stars>10-100
import numpy as np
def getTransFromRp(R,p):
T = np.vstack((np.hstack((R, np.array([[p[0]],[p[1]],[p[2]]]))), np.array([0,0,0,1])))
return T
def getRotationRoll(theta):
R = np.array([[1,0,0], [0,np.cos(theta),-np.sin(theta)],[0,np.sin(theta),np.cos(theta)]])
return R
def getRotationPitch(theta):
R = np.array([[np.cos(theta),0,np.sin(theta)], [0,1,0],[-np.sin(theta),0,np.cos(theta)]])
return R
def getRotationYaw(theta):
R = np.array([[np.cos(theta),-np.sin(theta),0],[np.sin(theta),np.cos(theta),0],[0,0,1]])
return R
def getPositionFromT(T):
p = T[0:3,3]
return p
def getRotationFromT(T):
R = T[0:3,0:3]
return R
def getRotationAndPositionFromT(T):
p = T[0:3,3]
R = T[0:3,0:3]
return R, p
def getRollPitchYawFromR(R):
pitch = np.arcsin(-R[2,0])
yaw = np.arctan2(R[1,0], R[0,0])
roll = np.arctan2(R[2,1],R[2,2])
return np.array([roll, pitch, yaw])
def skewSymmetricMatrix(v):
matrix = np.array([[0, -v[2], v[1]],
[v[2], 0, -v[0]],
[-v[1], v[0], 0]])
return matrix
def skewSymmetricMatrixInv(m):
vector = np.zeros(3)
vector[0] = m[2,1]
vector[1] = m[0,2]
vector[2] = m[1,0]
return vector
def roadriguesEquation(E, a, theta):
a_h = skewSymmetricMatrix(a)
return E + a_h * np.sin(theta) + a_h.dot(a_h) * (1-np.cos(theta))
|
#!/bin/bash
pass=$1
log_setup=$HOME/ubuntu-setup.log
projects=$HOME/projects
cd
chmod +x install-apps-snap.sh
./install-apps-snap.sh $pass
#backup do log no syslog do linux
logger -p user.info -t "setup-apps" -f $log_setup
|
/* GENERATED FILE */
import { html, svg, define } from "hybrids";
const PhLaptop = {
color: "currentColor",
size: "1em",
weight: "regular",
mirrored: false,
render: ({ color, size, weight, mirrored }) => html`
<svg
xmlns="http://www.w3.org/2000/svg"
width="${size}"
height="${size}"
fill="${color}"
viewBox="0 0 256 256"
transform=${mirrored ? "scale(-1, 1)" : null}
>
${weight === "bold" &&
svg`<path d="M40,168V72A16,16,0,0,1,56,56H200a16,16,0,0,1,16,16v96" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="24"/>
<path d="M24,168H232a0,0,0,0,1,0,0v24a16,16,0,0,1-16,16H40a16,16,0,0,1-16-16V168a0,0,0,0,1,0,0Z" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="24"/>
<line x1="144" y1="96" x2="112" y2="96" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="24"/>`}
${weight === "duotone" &&
svg`<path d="M40,176V72A16,16,0,0,1,56,56H200a16,16,0,0,1,16,16V176Z" opacity="0.2"/>
<path d="M40,176V72A16,16,0,0,1,56,56H200a16,16,0,0,1,16,16V176" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/>
<path d="M24,176H232a0,0,0,0,1,0,0v16a16,16,0,0,1-16,16H40a16,16,0,0,1-16-16V176A0,0,0,0,1,24,176Z" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/>
<line x1="144" y1="88" x2="112" y2="88" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/>`}
${weight === "fill" &&
svg`<path d="M232,168h-8V72a24.0275,24.0275,0,0,0-24-24H56A24.0275,24.0275,0,0,0,32,72v96H24a8.00008,8.00008,0,0,0-8,8v16a24.0275,24.0275,0,0,0,24,24H216a24.0275,24.0275,0,0,0,24-24V176A8.00008,8.00008,0,0,0,232,168ZM112,72h32a8,8,0,0,1,0,16H112a8,8,0,0,1,0-16ZM224,192a8.00917,8.00917,0,0,1-8,8H40a8.00917,8.00917,0,0,1-8-8v-8H224Z"/>`}
${weight === "light" &&
svg`<path d="M40,176V72A16,16,0,0,1,56,56H200a16,16,0,0,1,16,16V176" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="12"/>
<path d="M24,176H232a0,0,0,0,1,0,0v16a16,16,0,0,1-16,16H40a16,16,0,0,1-16-16V176A0,0,0,0,1,24,176Z" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="12"/>
<line x1="144" y1="88" x2="112" y2="88" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="12"/>`}
${weight === "thin" &&
svg`<path d="M40,176V72A16,16,0,0,1,56,56H200a16,16,0,0,1,16,16V176" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="8"/>
<path d="M24,176H232a0,0,0,0,1,0,0v16a16,16,0,0,1-16,16H40a16,16,0,0,1-16-16V176A0,0,0,0,1,24,176Z" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="8"/>
<line x1="144" y1="88" x2="112" y2="88" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="8"/>`}
${weight === "regular" &&
svg`<path d="M40,176V72A16,16,0,0,1,56,56H200a16,16,0,0,1,16,16V176" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/>
<path d="M24,176H232a0,0,0,0,1,0,0v16a16,16,0,0,1-16,16H40a16,16,0,0,1-16-16V176A0,0,0,0,1,24,176Z" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/>
<line x1="144" y1="88" x2="112" y2="88" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/>`}
</svg>
`,
};
define("ph-laptop", PhLaptop);
export default PhLaptop;
|
def pred(email):
emails = email.split('\n')
x_list = []
y_list = []
for email in emails:
features = extract_features(email)
x_list.append(features)
if is_spam(email):
y_list.append(1)
else:
y_list.append(0)
x = np.array(x_list)
y = np.array(y_list)
model = build_model(x, y)
return model.predict(email)
|
<filename>speed-typer/source_ui/result_window.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'resultWindow.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_resultWindow(object):
def setupUi(self, resultWindow):
resultWindow.setObjectName("resultWindow")
resultWindow.resize(625, 478)
resultWindow.setAcceptDrops(True)
self.horizontalLayout = QtWidgets.QHBoxLayout(resultWindow)
self.horizontalLayout.setObjectName("horizontalLayout")
self.scrollArea = QtWidgets.QScrollArea(resultWindow)
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName("scrollArea")
self.scrollAreaWidgetContents = QtWidgets.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 603, 456))
self.scrollAreaWidgetContents.setMinimumSize(QtCore.QSize(600, 450))
self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
self.horizontalLayout_4 = QtWidgets.QHBoxLayout(self.scrollAreaWidgetContents)
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_4.addItem(spacerItem)
self.verticalLayout_2 = QtWidgets.QVBoxLayout()
self.verticalLayout_2.setContentsMargins(-1, -1, 0, -1)
self.verticalLayout_2.setObjectName("verticalLayout_2")
spacerItem1 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout_2.addItem(spacerItem1)
self.labelHighscoreSet = QtWidgets.QLabel(self.scrollAreaWidgetContents)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.labelHighscoreSet.sizePolicy().hasHeightForWidth())
self.labelHighscoreSet.setSizePolicy(sizePolicy)
self.labelHighscoreSet.setMinimumSize(QtCore.QSize(470, 0))
font = QtGui.QFont()
font.setPointSize(24)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.labelHighscoreSet.setFont(font)
self.labelHighscoreSet.setStyleSheet("")
self.labelHighscoreSet.setAlignment(QtCore.Qt.AlignCenter)
self.labelHighscoreSet.setWordWrap(True)
self.labelHighscoreSet.setObjectName("labelHighscoreSet")
self.verticalLayout_2.addWidget(self.labelHighscoreSet)
spacerItem2 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
self.verticalLayout_2.addItem(spacerItem2)
self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
self.horizontalLayout_3.setContentsMargins(-1, 30, -1, -1)
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_3.addItem(spacerItem3)
self.labelSpeed = QtWidgets.QLabel(self.scrollAreaWidgetContents)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.labelSpeed.sizePolicy().hasHeightForWidth())
self.labelSpeed.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(24)
self.labelSpeed.setFont(font)
self.labelSpeed.setStyleSheet("")
self.labelSpeed.setWordWrap(True)
self.labelSpeed.setObjectName("labelSpeed")
self.horizontalLayout_3.addWidget(self.labelSpeed)
spacerItem4 = QtWidgets.QSpacerItem(50, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_3.addItem(spacerItem4)
self.labelAccuracy = QtWidgets.QLabel(self.scrollAreaWidgetContents)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.labelAccuracy.sizePolicy().hasHeightForWidth())
self.labelAccuracy.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(24)
self.labelAccuracy.setFont(font)
self.labelAccuracy.setStyleSheet("")
self.labelAccuracy.setWordWrap(True)
self.labelAccuracy.setObjectName("labelAccuracy")
self.horizontalLayout_3.addWidget(self.labelAccuracy)
spacerItem5 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_3.addItem(spacerItem5)
self.verticalLayout_2.addLayout(self.horizontalLayout_3)
spacerItem6 = QtWidgets.QSpacerItem(20, 50, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
self.verticalLayout_2.addItem(spacerItem6)
self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
self.horizontalLayout_2.setContentsMargins(-1, 0, -1, -1)
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
spacerItem7 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem7)
self.buttonMainMenu = QtWidgets.QPushButton(self.scrollAreaWidgetContents)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.buttonMainMenu.sizePolicy().hasHeightForWidth())
self.buttonMainMenu.setSizePolicy(sizePolicy)
self.buttonMainMenu.setMinimumSize(QtCore.QSize(0, 40))
self.buttonMainMenu.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.buttonMainMenu.setAutoDefault(True)
self.buttonMainMenu.setObjectName("buttonMainMenu")
self.horizontalLayout_2.addWidget(self.buttonMainMenu)
spacerItem8 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem8)
self.buttonNext = QtWidgets.QPushButton(self.scrollAreaWidgetContents)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.buttonNext.sizePolicy().hasHeightForWidth())
self.buttonNext.setSizePolicy(sizePolicy)
self.buttonNext.setMinimumSize(QtCore.QSize(0, 40))
font = QtGui.QFont()
font.setPointSize(8)
self.buttonNext.setFont(font)
self.buttonNext.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.buttonNext.setAutoDefault(False)
self.buttonNext.setDefault(True)
self.buttonNext.setObjectName("buttonNext")
self.horizontalLayout_2.addWidget(self.buttonNext)
spacerItem9 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem9)
self.verticalLayout_2.addLayout(self.horizontalLayout_2)
spacerItem10 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout_2.addItem(spacerItem10)
self.horizontalLayout_4.addLayout(self.verticalLayout_2)
spacerItem11 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_4.addItem(spacerItem11)
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.horizontalLayout.addWidget(self.scrollArea)
self.retranslateUi(resultWindow)
QtCore.QMetaObject.connectSlotsByName(resultWindow)
def retranslateUi(self, resultWindow):
_translate = QtCore.QCoreApplication.translate
resultWindow.setWindowTitle(_translate("resultWindow", "Result"))
self.labelHighscoreSet.setText(_translate("resultWindow", "You set an all time highscore!"))
self.labelSpeed.setText(_translate("resultWindow", "50 WPM"))
self.labelAccuracy.setText(_translate("resultWindow", "100%"))
self.buttonMainMenu.setText(_translate("resultWindow", "Main Menu"))
self.buttonNext.setText(_translate("resultWindow", "Next"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
resultWindow = QtWidgets.QWidget()
ui = Ui_resultWindow()
ui.setupUi(resultWindow)
resultWindow.show()
sys.exit(app.exec_())
|
<filename>.eslintrc.js
module.exports = {
env: { browser: true, es6: true, node: true },
extends: [
'eslint:recommended',
'plugin:nuxt/recommended',
'plugin:vue/recommended'
],
}
|
#!/bin/bash
source ../../setup/setenv.sh
echo "Enter your password for the Apigee Enterprise organization $org, followed by [ENTER]:"
read -s password
curl -X POST -H "Content-type:text/xml" -d @paginationCache.xml https://api.enterprise.apigee.com/v1/o/$org/environments/$env/caches -u $username:$password
echo Deploying $proxy to $env on $url using $username and $org
../../tools/deploy.py -n pagination -u $username:$password -o $org -h $url -e $env -p / -d ../pagination
echo "If 'State: deployed', then your API Proxy is ready to be invoked."
echo "Run 'invoke.sh'"
|
<reponame>erraa/aciexporter
package aci
import "encoding/json"
type FaultInst struct {
ImData []IMDATA `json:"imdata"`
TotalCount string `json:"totalCount"`
}
func (faultinst *FaultInst) UnmarshalJson(data []byte) error {
err := json.Unmarshal(data, &faultinst)
if err != nil {
return err
}
return nil
}
func (faultinst *FaultInst) Class() string {
return "faultInst"
}
func (faultinst *FaultInst) GetTotalCount() string {
return faultinst.TotalCount
}
func (faultinst *FaultInst) GetImData() []IMDATA {
return faultinst.ImData
}
func (faultinst *FaultInst) GetAll() ([]map[string]string, error) {
returnSlice := []map[string]string{}
for _, obj := range faultinst.ImData {
jsonAttr := map[string]string{}
attr, _ := json.Marshal(obj.FaultInst.Attributes)
err := json.Unmarshal(attr, &jsonAttr)
if err != nil {
return nil, err
}
returnSlice = append(returnSlice, jsonAttr)
}
return returnSlice, nil
}
type FAULTINST struct {
Attributes struct {
Ack string `json:"ack"`
Cause string `json:"cause"`
ChangeSet string `json:"changeSet"`
ChildAction string `json:"childAction"`
Code string `json:"code"`
Created string `json:"created"`
Delegated string `json:"delegated"`
Descr string `json:"descr"`
Dn string `json:"dn"`
Domain string `json:"domain"`
HighestSeverity string `json:"highestSeverity"`
LastTransition string `json:"lastTransition"`
Lc string `json:"lc"`
Occur string `json:"occur"`
OrigSeverity string `json:"origSeverity"`
PrevSeverity string `json:"prevSeverity"`
Rule string `json:"rule"`
Severity string `json:"severity"`
Status string `json:"status"`
Subject string `json:"subject"`
Type string `json:"type"`
} `json:"attributes"`
}
|
<gh_stars>1-10
import os
import signal
import argparse
import sys
import subprocess
import shlex
import Queue as Queue
from threading import Thread
from time import sleep
import logging
logging.basicConfig()
logger = logging.getLogger(__name__)
STOP=False
SUBPROCESS_FAILED_EXIT=1
def run_subprocess(
command, tool, stdout=None,
stderr=None, stdoutlog=False,
working_dir=None,with_queue=False):
""" Runs a command on the system shell and forks a new process
also creates a file for stderr and stdout if needed
to avoid deadlock.
"""
print(command)
command = shlex.split(command)
# Very dirty hack
# logger.info(tool + ' command = ' + ' '.join(command))
if (working_dir is None):
working_dir = '.'
if(tool == 'selection_pipeline'):
stderr = working_dir+'/selection_stderr.tmp'
stdout = working_dir+ '/selection_stdout.tmp'
if(stderr is None):
stderr = 'stderr.tmp'
standard_err = open(stderr, 'w')
else:
standard_err = open(stderr, 'w')
try:
if(stdout is None):
standard_out = open('stdout.tmp', 'w')
exit_code = subprocess.Popen(
command, stderr=standard_out, stdout=standard_err,cwd=working_dir)
else:
# find out what kind of exception to try here
if(hasattr(stdout, 'read')):
exit_code = subprocess.Popen(
command, stdout=stdout, stderr=standard_err,cwd=working_dir)
else:
stdout = open(stdout, 'w')
exit_code = subprocess.Popen(
command, stdout=stdout, stderr=standard_err,cwd=working_dir)
standard_out = stdout
except:
logger.error(tool + " failed to run " + ' '.join(command))
standard_err = open(stderr, 'r')
while True:
line = standard_err.readline()
if not line:
break
logger.info(tool + " STDERR: " + line.strip())
standard_err.close()
sys.exit(SUBPROCESS_FAILED_EXIT)
try:
while(exit_code.poll() is None):
sleep(0.2)
if(STOP == True):
exit_code.send_signal(signal.SIGINT)
if (with_queue) :
return
else:
sys.exit(SUBPROCESS_FAILED_EXIT)
except (KeyboardInterrupt, SystemExit):
exit_code.send_signal(signal.SIGINT)
global STOP
STOP = True
if( with_queue) :
return
else:
sys.exit(SUBPROCESS_FAILED_EXIT)
standard_err.close()
standard_out.close()
standard_err = open(stderr, 'r')
if(exit_code.returncode != 0):
logger.error(tool + " failed to run " + ' '.join(command))
while True:
line = standard_err.readline()
if not line:
break
logger.info(tool + " STDERR: " + line.strip())
sys.exit(SUBPROCESS_FAILED_EXIT)
stdout_log = False
if(stdout is None):
standard_out = open('stdout.tmp', 'r')
stdout_log = True
elif(stdoutlog):
if(hasattr(stdout, 'write')):
standard_out = open(stdout.name, 'r')
else:
standard_out = open(stdout, 'r')
stdout_log = True
if(stdout_log):
while True:
line = standard_out.readline()
if not line:
break
logger.info(tool + " STDOUT: " + line.strip())
standard_out.close()
while True:
line = standard_err.readline()
if not line:
break
logger.info(tool + " STDERR: " + line.strip())
logger.info("Finished tool " + tool)
logger.debug("command = " + ' '.join(command))
standard_err.close()
standard_out.close()
# Removed stdout if it either was not specified
# or the log was specified.
if(stdout is None or stdout is 'selection_stdout.tmp'):
os.remove('stdout.tmp')
elif(stdoutlog):
os.remove(standard_out.name)
os.remove(stderr)
def __queue_worker__(q, tool_name):
while True:
queue_item = q.get()
try:
cmd = queue_item[0]
stdout = queue_item[1]
stdoutlog = queue_item[2]
stderr = queue_item[3]
folder_names = queue_item[4]
except IndexError:
cmd = queue_item[0]
stdout = queue_item[1]
stdoutlog = False
stderr = None
folder_names = '.'
try:
run_subprocess(
cmd, tool_name, stdout=stdout,
stdoutlog=stdoutlog, stderr=stderr, working_dir=folder_names,with_queue=True)
except SystemExit:
global STOP
STOP = True
logger.error(tool_name + ": Failed to run in thread")
q.task_done()
def queue_jobs(commands, tool_name, threads, stdouts=None, folder_names=None):
""" Creates a queue for running jobs
Using a synchronized queue to spawn jobs equal
to the number of cores specified to the user.
The method blocks until all tasks are complete
"""
q = Queue.Queue()
thread_L = []
print(threads)
for i in range(int(threads)):
t = Thread(target=__queue_worker__, args=[q, tool_name])
t.daemon = True
thread_L.append(t)
t.start()
for i, cmd in enumerate(commands):
stderr = 'stderr' + str(i) + '.tmp'
if(folder_names is None):
folder_name = '.'
else:
folder_name = folder_names[i]
if (stdouts is not None):
q.put([cmd, stdouts[i], False, stderr, folder_name])
else:
stdout = 'stdout' + str(i) + '.tmp'
q.put([cmd, stdout, True, stderr, folder_name])
q.join()
if (STOP == True):
sys.exit(SUBPROCESS_FAILED_EXIT)
|
#!/bin/sh
# Jason Filice
# jfilice@csumb.edu
# Technology Support Services in IT
# California State University, Monterey Bay
# https://csumb.edu/it
# This script downloads and installs the current "Download for IT Admin" Zoom Client for Meetings from zoom.us.
# Run it with no arguments.
#
# For best results, copy it to the Mac and run it as postinstall script in a PKG installer.
# Change History:
# 2020/06/04: Creation.
# 2021/06/09: Added flag -allow to installer
#
SCRIPTNAME=`/usr/bin/basename "$0"`
SCRIPTPATH=`/usr/bin/dirname "$0"`
# Jamf JSS Parameters 1 through 3 are predefined as mount point, computer name, and username
pathToScript=$0
mountPoint=$1
computerName=$2
userName=$3
shift 3
# Shift off the $1 $2 $3 parameters passed by the JSS so that parameter 4 is now $1
echo pathToScript=$pathToScript
echo mountPoint=$mountPoint
echo computerName=$computerName
echo userName=$userName
# set alias for PlistBuddy and several others so I don't have to specify full path.
# Prefix sudo path because I'm using it here for all commands.
# If I want to run a command without the alias, then specify the full path.
alias PlistBuddy="/usr/libexec/PlistBuddy"
alias chown="/usr/sbin/chown"
alias chmod="/bin/chmod"
alias ditto="/usr/bin/ditto"
alias defaults="/usr/bin/defaults"
alias rm="/bin/rm"
alias cp="/bin/cp"
alias mkdir="/bin/mkdir"
alias sudo=/usr/bin/sudo
echo "Start $SCRIPTNAME"
# set -x
PKGfile="ZoomInstallerIT.pkg"
PKG_URL="https://zoom.us/client/latest/ZoomInstallerIT.pkg"
if [ -e /tmp/"$PKGfile" ]; then
rm -fR /tmp/"$PKGfile"
fi
# Download vendor pkg file into /tmp/
/usr/bin/curl "$PKG_URL" --location --create-dirs --output /tmp/"$PKGfile"
sleep 1
# Install
/usr/sbin/installer -allow -pkg "/tmp/$PKGfile" -target /
sleep 1
# Remove the downloaded pkg
if [[ -e /tmp/"$PKGfile" ]]; then
rm -fR /tmp/"$PKGfile"
fi
echo "End $SCRIPTNAME"
|
const express = require("express");
const router = express.Router();
// API Routing
const users = require('./api/users');
const posts = require('./api/posts');
router.get('/', (req, res) => {
res.json({
msg: 'In routes.js!!'
});
});
router.use('/users', users);
router.use('/posts', posts);
module.exports = router
|
export function incToNanoAmount(amount, decimals) {
return Number(amount) * (10 ** (Number.parseInt(decimals) || 0));
}
export function incToUIAmount(amount, decimals) {
return Number.parseFloat(amount) / (10 ** (Number.parseInt(decimals) || 0));
}
|
#!/bin/bash
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===========================================================================
export RANK_SIZE=$1
export CUDA_VISIBLE_DEVICES="$2"
if [ $# != 3 ]
then
echo "run as scripts/run_train_gpu.sh [DEVICE_NUM] [CUDA_VISIBLE_DEVICES] [TRAIN_FEAT_DIR]"
exit 1
fi
rm -rf train_gpu
mkdir train_gpu
cp -r ./src ./train_gpu
cp -r ./scripts ./train_gpu
cp ./*.py ./train_gpu
cp ./*yaml ./train_gpu
cd ./train_gpu || exit
if [ $1 -gt 1 ]
then
echo "start distributed trainning network"
mpirun --allow-run-as-root -n $RANK_SIZE --output-filename log_output --merge-stderr-to-stdout \
python train.py --is_distributed=1 --device_target="GPU" --train_feat_dir=$3 > train.log 2>&1 &
else
echo "start trainning network"
python train.py --train_feat_dir=$3 --device_target='GPU' > train.log 2>&1 &
fi
cd ..
|
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/512+512+512-ST/model --tokenizer_name model-configs/1536-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/512+512+512-ST/1024+0+512-N-VB-ADJ-first-256 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function remove_all_but_nouns_verbs_and_adjectives_first_two_thirds_sixth --eval_function penultimate_sixth_eval
|
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const User = require("../model/user");
module.exports.adminLogin = async (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
return res
.status(400)
.json({ success: false, message: "Missing Username or Password" });
}
await User.findOne({ username: username })
.then((user) => {
if (user.role === "admin") {
if (!bcrypt.compareSync(password, user.password)) {
return res.status(400).json({
success: false,
message: "Incorrect Username or Password 3",
});
} else {
const accessToken = jwt.sign(
{ _id: user._id, username: user.username },
process.env.ACCESS_TOKEN_SECRET,
{ algorithm: "HS256" }
);
res.status(200).json({
success: true,
message: "Login Successfully",
accessToken,
user,
});
}
} else {
res
.status(400)
.json({ success: false, message: "Incorrect Username or Password" });
}
})
.catch((err) => {
console.log(err);
res.status(400).json({ success: false, message: "Incorrect username" });
});
};
module.exports.addAdminAccount = async (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
return res
.status(400)
.json({ success: false, message: "Missing Username or Passwod" });
}
try {
const userCheck = await User.findOne({ username: username });
if (userCheck) {
return res
.status(400)
.json({ success: false, message: "Username already taken" });
}
const hashedPassword = await bcrypt.hash(password, 10);
const user = new User({
username,
password: <PASSWORD>,
email: req.body.email,
name: {
firstname: req.body.name.firstname,
lastname: req.body.name.lastname,
},
address: {
city: req.body.address.city,
street: req.body.address.street,
number: req.body.address.number,
},
phone: req.body.phone,
role: "admin",
});
await user.save();
res.status(200).json({ success: true, message: "Insert Successfully" });
} catch (e) {
console.log(e);
res.status(500).json({ success: false, message: "Internal Server Error" });
}
};
|
from abc import ABC, abstractmethod
# Base Test class with abstract doTest method
class Test(ABC):
@abstractmethod
def doTest(self):
pass
# Subclass for testing the Shape module
class TestShape(Test):
def doTest(self):
# Implement tests for the Shape module
pass
# Subclass for testing the Slice module
class TestSlice(Test):
def doTest(self):
# Implement tests for the Slice module
pass
# Subclass for testing the Timer module
class TestTimer(Test):
def doTest(self):
# Implement tests for the Timer module
pass
# Subclass for testing the Utils module
class TestUtils(Test):
def doTest(self):
# Implement tests for the Utils module
pass
# Subclass for testing the DtypeInfo module
class TestDtypeInfo(Test):
def doTest(self):
# Implement tests for the DtypeInfo module
pass
# Subclass for testing the NdArray module
class TestNdArray(Test):
def doTest(self):
# Implement tests for the NdArray module
pass
# Subclass for testing the Methods module
class TestMethods(Test):
def doTest(self):
# Implement tests for the Methods module
pass
# Subclass for testing the Coordinates module
class TestCoordinates(Test):
def doTest(self):
# Implement tests for the Coordinates module
pass
# Subclass for testing the Constants module
class TestConstants(Test):
def doTest(self):
# Implement tests for the Constants module
pass
# Subclass for testing the Linalg module
class TestLinalg(Test):
def doTest(self):
# Implement tests for the Linalg module
pass
# Subclass for testing the Random module
class TestRandom(Test):
def doTest(self):
# Implement tests for the Random module
pass
# Subclass for testing the Rotations module
class TestRotations(Test):
def doTest(self):
# Implement tests for the Rotations module
pass
# Subclass for testing the Filters module
class TestFilters(Test):
def doTest(self):
# Implement tests for the Filters module
pass
# Subclass for testing the Polynomial module
class TestPolynomial(Test):
def doTest(self):
# Implement tests for the Polynomial module
pass
# Subclass for testing the FFT module
class TestFFT(Test):
def doTest(self):
# Implement tests for the FFT module
pass
|
<filename>cours/ensg-asi-2015/src/gulpfile.js
var gulp = require('gulp'),
connect = require('gulp-connect'),
watch = require('gulp-watch'),
less = require('gulp-less'),
minifyCSS = require('gulp-minify-css'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
clean = require('gulp-clean'),
coffee = require('gulp-coffee'),
w3cjs = require('gulp-w3cjs')
rubanComponents = [
'bower_components/normalize-css/normalize.css',
'bower_components/font-awesome/css/font-awesome.min.css',
'bower_components/highlightjs/styles/tomorrow.css',
'bower_components/jquery/jquery.min.js',
'bower_components/jquery/jquery.min.map',
'bower_components/keymaster/keymaster.js',
'bower_components/hammerjs/hammer.min.js',
'bower_components/hammerjs/hammer.min.map',
'bower_components/highlightjs/highlight.pack.js'
];
rubanFonts = [
'bower_components/font-awesome/fonts/*'
]
gulp.task('webserver', function() {
connect.server({
livereload: true,
root: ['.tmp']
});
});
gulp.task('livereload', function() {
gulp.src('.tmp/**/*')
.pipe(watch())
.pipe(connect.reload());
});
gulp.task('less', function() {
gulp.src('less/*.less')
.pipe(less())
.pipe(gulp.dest('.tmp/styles'));
});
gulp.task('coffee', function() {
gulp.src('coffee/*.coffee')
.pipe(coffee())
.pipe(gulp.dest('.tmp/scripts'));
});
gulp.task('images', function() {
gulp.src('images/**/*')
.pipe(gulp.dest('.tmp/images'));
});
gulp.task('html', function() {
gulp.src('*.html')
.pipe(gulp.dest('.tmp'));
});
gulp.task('ruban-components',function() {
gulp.src(rubanComponents)
.pipe(gulp.dest('.tmp/components'));
});
gulp.task('ruban-fonts', function() {
gulp.src(rubanFonts)
.pipe(gulp.dest('.tmp/fonts'));
});
gulp.task('watch', function() {
gulp.watch('less/*.less', ['less']);
gulp.watch('coffee/*.coffee', ['coffee']);
gulp.watch('images/*', ['images']);
gulp.watch('*.html', ['html']);
})
gulp.task('dist', function() {
gulp.src('.tmp/**')
.pipe(gulp.dest('../'));
});
/******* Main tasks *******/
gulp.task('clean', function() {
gulp.src('.tmp', {read: false})
.pipe(clean({force: true}));
});
gulp.task('validate', function () {
gulp.src('*.html')
.pipe(w3cjs());
});
gulp.task('build', [
'less',
'coffee',
'ruban-components',
'ruban-fonts',
'images',
'html'
]);
gulp.task('publish', [
'validate',
'build',
'dist'
]);
gulp.task('default', [
'build',
'webserver',
'livereload',
'watch'
]);
|
<reponame>fmitra/authenticator-client<gh_stars>0
import { h } from 'preact';
import { Header } from '@authenticator/ui/components';
const ContactHeader = (): JSX.Element => (
<Header
title={
<span class='title'>Add Address</span>
}
subtitle={
<span class='subtitle'>Add your new phone number or email address below</span>
}
/>
);
export default ContactHeader;
|
#!/usr/bin/env python3
# This program is a basic calculator that can take in two values and an operator
# The corresponding operations when the operator input is given
operations = {
"+": lambda x, y: x + y,
"-": lambda x, y: x - y,
"*": lambda x, y: x * y,
"/": lambda x, y: x / y
}
# Take in the values and operator from the user
num1 = int(input("Enter the first number: "))
operator = input("Enter the operator: ")
num2 = int(input("Enter the second number: "))
# Assert that the operator is valid
assert operator in operations, f"The given operator {operator} is not a valid operator"
# Calculate the result
result = operations[operator](num1, num2)
print(f"Result: {num1} {operator} {num2} = {result}")
|
import fs from 'fs-extra';
import Logger from '../utils/logger.utils';
class Clear {
static async clearFolder(name: string): Promise<void> {
return new Promise((resolve, reject) => {
Logger.showClear(`./${name}`);
fs.emptyDir(`./${name}`)
.then(() => {
Logger.showSuccess(`./${name} is cleared.`, true);
resolve();
})
.catch((err) => {
Logger.showError(err);
reject();
});
});
}
}
export default Clear;
|
#!/bin/bash
set -o errexit
set -o nounset
set -o pipefail
OS_ROOT=$(dirname "${BASH_SOURCE}")/../..
source "${OS_ROOT}/hack/lib/init.sh"
os::log::stacktrace::install
trap os::test::junit::reconcile_output EXIT
# Cleanup cluster resources created by this test
(
set +e
oc delete all,templates --all
oc delete template/ruby-helloworld-sample -n openshift
oc delete project test-template-project
wait_for_command '! oc get project test-template-project'
exit 0
) &>/dev/null
os::test::junit::declare_suite_start "cmd/templates"
# This test validates template commands
os::test::junit::declare_suite_start "cmd/templates/basic"
os::cmd::expect_success 'oc get templates'
os::cmd::expect_success 'oc create -f examples/sample-app/application-template-dockerbuild.json'
os::cmd::expect_success 'oc get templates'
os::cmd::expect_success 'oc get templates ruby-helloworld-sample'
os::cmd::expect_success 'oc get template ruby-helloworld-sample -o json | oc process -f -'
os::cmd::expect_success 'oc process ruby-helloworld-sample'
os::cmd::expect_success_and_text 'oc describe templates ruby-helloworld-sample' "BuildConfig.*ruby-sample-build"
os::cmd::expect_success 'oc delete templates ruby-helloworld-sample'
os::cmd::expect_success 'oc get templates'
# TODO: create directly from template
echo "templates: ok"
os::test::junit::declare_suite_end
os::test::junit::declare_suite_start "cmd/templates/config"
os::cmd::expect_success 'oc process -f test/templates/testdata/guestbook.json -l app=guestbook | oc create -f -'
os::cmd::expect_success_and_text 'oc status' 'frontend-service'
echo "template+config: ok"
os::test::junit::declare_suite_end
os::test::junit::declare_suite_start "cmd/templates/parameters"
# Joined parameter values are honored
os::cmd::expect_success_and_text 'oc process -f test/templates/testdata/guestbook.json -v ADMIN_USERNAME=myuser,ADMIN_PASSWORD=mypassword' '"myuser"'
os::cmd::expect_success_and_text 'oc process -f test/templates/testdata/guestbook.json -v ADMIN_USERNAME=myuser,ADMIN_PASSWORD=mypassword' '"mypassword"'
# Individually specified parameter values are honored
os::cmd::expect_success_and_text 'oc process -f test/templates/testdata/guestbook.json -v ADMIN_USERNAME=myuser -v ADMIN_PASSWORD=mypassword' '"myuser"'
os::cmd::expect_success_and_text 'oc process -f test/templates/testdata/guestbook.json -v ADMIN_USERNAME=myuser -v ADMIN_PASSWORD=mypassword' '"mypassword"'
# Argument values are honored
os::cmd::expect_success_and_text 'oc process ADMIN_USERNAME=myuser ADMIN_PASSWORD=mypassword -f test/templates/testdata/guestbook.json' '"myuser"'
os::cmd::expect_success_and_text 'oc process -f test/templates/testdata/guestbook.json ADMIN_USERNAME=myuser ADMIN_PASSWORD=mypassword' '"mypassword"'
# Argument values with commas are honored
os::cmd::expect_success 'oc create -f examples/sample-app/application-template-stibuild.json'
os::cmd::expect_success_and_text 'oc process ruby-helloworld-sample MYSQL_USER=myself MYSQL_PASSWORD=my,1%pass' '"myself"'
os::cmd::expect_success_and_text 'oc process MYSQL_USER=myself MYSQL_PASSWORD=my,1%pass ruby-helloworld-sample' '"my,1%pass"'
os::cmd::expect_success 'oc delete template ruby-helloworld-sample'
echo "template+parameters: ok"
os::test::junit::declare_suite_end
os::test::junit::declare_suite_start "cmd/templates/data-precision"
# Run as cluster-admin to allow choosing any supplemental groups we want
# Ensure large integers survive unstructured JSON creation
os::cmd::expect_success 'oc create -f test/testdata/template-type-precision.json'
# ... and processing
os::cmd::expect_success_and_text 'oc process template-type-precision' '1000030003'
os::cmd::expect_success_and_text 'oc process template-type-precision' '2147483647'
os::cmd::expect_success_and_text 'oc process template-type-precision' '9223372036854775807'
# ... and re-encoding as structured resources
os::cmd::expect_success 'oc process template-type-precision | oc create -f -'
# ... and persisting
os::cmd::expect_success_and_text 'oc get pod/template-type-precision -o json' '1000030003'
os::cmd::expect_success_and_text 'oc get pod/template-type-precision -o json' '2147483647'
os::cmd::expect_success_and_text 'oc get pod/template-type-precision -o json' '9223372036854775807'
# Ensure patch computation preserves data
patch='{"metadata":{"annotations":{"comment":"patch comment"}}}'
os::cmd::expect_success "oc patch pod template-type-precision -p '${patch}'"
os::cmd::expect_success_and_text 'oc get pod/template-type-precision -o json' '9223372036854775807'
os::cmd::expect_success_and_text 'oc get pod/template-type-precision -o json' 'patch comment'
os::cmd::expect_success 'oc delete template/template-type-precision'
os::cmd::expect_success 'oc delete pod/template-type-precision'
echo "template data precision: ok"
os::test::junit::declare_suite_end
os::test::junit::declare_suite_start "cmd/templates/different-namespaces"
os::cmd::expect_success 'oc create -f examples/sample-app/application-template-dockerbuild.json -n openshift'
os::cmd::expect_success 'oc policy add-role-to-user admin test-user'
new="$(mktemp -d)/tempconfig"
os::cmd::expect_success "oc config view --raw > ${new}"
export KUBECONFIG=${new}
os::cmd::expect_success 'oc login -u test-user -p password'
os::cmd::expect_success 'oc new-project test-template-project'
# make sure the permissions on the new project are set up
os::cmd::try_until_success 'oc get templates'
os::cmd::expect_success 'oc create -f examples/sample-app/application-template-dockerbuild.json'
os::cmd::expect_success 'oc process template/ruby-helloworld-sample'
os::cmd::expect_success 'oc process templates/ruby-helloworld-sample'
os::cmd::expect_success 'oc process openshift//ruby-helloworld-sample'
os::cmd::expect_success 'oc process openshift/template/ruby-helloworld-sample'
echo "processing templates in different namespace: ok"
os::test::junit::declare_suite_end
os::test::junit::declare_suite_end
|
/*
* Generated by @medplum/generator
* Do not edit manually.
*/
import { CodeableConcept } from './CodeableConcept';
import { Extension } from './Extension';
import { Identifier } from './Identifier';
import { Meta } from './Meta';
import { Money } from './Money';
import { Narrative } from './Narrative';
import { Period } from './Period';
import { Quantity } from './Quantity';
import { Reference } from './Reference';
import { Resource } from './Resource';
/**
* Financial instrument which may be used to reimburse or pay for health
* care products and services. Includes both insurance and self-payment.
*/
export interface Coverage {
/**
* This is a Coverage resource
*/
readonly resourceType: 'Coverage';
/**
* The logical id of the resource, as used in the URL for the resource.
* Once assigned, this value never changes.
*/
readonly id?: string;
/**
* The metadata about the resource. This is content that is maintained by
* the infrastructure. Changes to the content might not always be
* associated with version changes to the resource.
*/
readonly meta?: Meta;
/**
* A reference to a set of rules that were followed when the resource was
* constructed, and which must be understood when processing the content.
* Often, this is a reference to an implementation guide that defines the
* special rules along with other profiles etc.
*/
readonly implicitRules?: string;
/**
* The base language in which the resource is written.
*/
readonly language?: string;
/**
* A human-readable narrative that contains a summary of the resource and
* can be used to represent the content of the resource to a human. The
* narrative need not encode all the structured data, but is required to
* contain sufficient detail to make it "clinically safe" for a human to
* just read the narrative. Resource definitions may define what content
* should be represented in the narrative to ensure clinical safety.
*/
readonly text?: Narrative;
/**
* These resources do not have an independent existence apart from the
* resource that contains them - they cannot be identified independently,
* and nor can they have their own independent transaction scope.
*/
readonly contained?: Resource[];
/**
* May be used to represent additional information that is not part of
* the basic definition of the resource. To make the use of extensions
* safe and manageable, there is a strict set of governance applied to
* the definition and use of extensions. Though any implementer can
* define an extension, there is a set of requirements that SHALL be met
* as part of the definition of the extension.
*/
readonly extension?: Extension[];
/**
* May be used to represent additional information that is not part of
* the basic definition of the resource and that modifies the
* understanding of the element that contains it and/or the understanding
* of the containing element's descendants. Usually modifier elements
* provide negation or qualification. To make the use of extensions safe
* and manageable, there is a strict set of governance applied to the
* definition and use of extensions. Though any implementer is allowed to
* define an extension, there is a set of requirements that SHALL be met
* as part of the definition of the extension. Applications processing a
* resource are required to check for modifier extensions.
*
* Modifier extensions SHALL NOT change the meaning of any elements on
* Resource or DomainResource (including cannot change the meaning of
* modifierExtension itself).
*/
readonly modifierExtension?: Extension[];
/**
* A unique identifier assigned to this coverage.
*/
readonly identifier?: Identifier[];
/**
* The status of the resource instance.
*/
readonly status?: string;
/**
* The type of coverage: social program, medical plan, accident coverage
* (workers compensation, auto), group health or payment by an individual
* or organization.
*/
readonly type?: CodeableConcept;
/**
* The party who 'owns' the insurance policy.
*/
readonly policyHolder?: Reference;
/**
* The party who has signed-up for or 'owns' the contractual relationship
* to the policy or to whom the benefit of the policy for services
* rendered to them or their family is due.
*/
readonly subscriber?: Reference;
/**
* The insurer assigned ID for the Subscriber.
*/
readonly subscriberId?: string;
/**
* The party who benefits from the insurance coverage; the patient when
* products and/or services are provided.
*/
readonly beneficiary?: Reference;
/**
* A unique identifier for a dependent under the coverage.
*/
readonly dependent?: string;
/**
* The relationship of beneficiary (patient) to the subscriber.
*/
readonly relationship?: CodeableConcept;
/**
* Time period during which the coverage is in force. A missing start
* date indicates the start date isn't known, a missing end date means
* the coverage is continuing to be in force.
*/
readonly period?: Period;
/**
* The program or plan underwriter or payor including both insurance and
* non-insurance agreements, such as patient-pay agreements.
*/
readonly payor?: Reference[];
/**
* A suite of underwriter specific classifiers.
*/
readonly class?: CoverageClass[];
/**
* The order of applicability of this coverage relative to other
* coverages which are currently in force. Note, there may be gaps in the
* numbering and this does not imply primary, secondary etc. as the
* specific positioning of coverages depends upon the episode of care.
*/
readonly order?: number;
/**
* The insurer-specific identifier for the insurer-defined network of
* providers to which the beneficiary may seek treatment which will be
* covered at the 'in-network' rate, otherwise 'out of network' terms and
* conditions apply.
*/
readonly network?: string;
/**
* A suite of codes indicating the cost category and associated amount
* which have been detailed in the policy and may have been included on
* the health card.
*/
readonly costToBeneficiary?: CoverageCostToBeneficiary[];
/**
* When 'subrogation=true' this insurance instance has been included not
* for adjudication but to provide insurers with the details to recover
* costs.
*/
readonly subrogation?: boolean;
/**
* The policy(s) which constitute this insurance coverage.
*/
readonly contract?: Reference[];
}
/**
* Financial instrument which may be used to reimburse or pay for health
* care products and services. Includes both insurance and self-payment.
*/
export interface CoverageClass {
/**
* Unique id for the element within a resource (for internal references).
* This may be any string value that does not contain spaces.
*/
readonly id?: string;
/**
* May be used to represent additional information that is not part of
* the basic definition of the element. To make the use of extensions
* safe and manageable, there is a strict set of governance applied to
* the definition and use of extensions. Though any implementer can
* define an extension, there is a set of requirements that SHALL be met
* as part of the definition of the extension.
*/
readonly extension?: Extension[];
/**
* May be used to represent additional information that is not part of
* the basic definition of the element and that modifies the
* understanding of the element in which it is contained and/or the
* understanding of the containing element's descendants. Usually
* modifier elements provide negation or qualification. To make the use
* of extensions safe and manageable, there is a strict set of governance
* applied to the definition and use of extensions. Though any
* implementer can define an extension, there is a set of requirements
* that SHALL be met as part of the definition of the extension.
* Applications processing a resource are required to check for modifier
* extensions.
*
* Modifier extensions SHALL NOT change the meaning of any elements on
* Resource or DomainResource (including cannot change the meaning of
* modifierExtension itself).
*/
readonly modifierExtension?: Extension[];
/**
* The type of classification for which an insurer-specific class label
* or number and optional name is provided, for example may be used to
* identify a class of coverage or employer group, Policy, Plan.
*/
readonly type?: CodeableConcept;
/**
* The alphanumeric string value associated with the insurer issued
* label.
*/
readonly value?: string;
/**
* A short description for the class.
*/
readonly name?: string;
}
/**
* Financial instrument which may be used to reimburse or pay for health
* care products and services. Includes both insurance and self-payment.
*/
export interface CoverageCostToBeneficiary {
/**
* Unique id for the element within a resource (for internal references).
* This may be any string value that does not contain spaces.
*/
readonly id?: string;
/**
* May be used to represent additional information that is not part of
* the basic definition of the element. To make the use of extensions
* safe and manageable, there is a strict set of governance applied to
* the definition and use of extensions. Though any implementer can
* define an extension, there is a set of requirements that SHALL be met
* as part of the definition of the extension.
*/
readonly extension?: Extension[];
/**
* May be used to represent additional information that is not part of
* the basic definition of the element and that modifies the
* understanding of the element in which it is contained and/or the
* understanding of the containing element's descendants. Usually
* modifier elements provide negation or qualification. To make the use
* of extensions safe and manageable, there is a strict set of governance
* applied to the definition and use of extensions. Though any
* implementer can define an extension, there is a set of requirements
* that SHALL be met as part of the definition of the extension.
* Applications processing a resource are required to check for modifier
* extensions.
*
* Modifier extensions SHALL NOT change the meaning of any elements on
* Resource or DomainResource (including cannot change the meaning of
* modifierExtension itself).
*/
readonly modifierExtension?: Extension[];
/**
* The category of patient centric costs associated with treatment.
*/
readonly type?: CodeableConcept;
/**
* The amount due from the patient for the cost category.
*/
readonly valueQuantity?: Quantity;
/**
* The amount due from the patient for the cost category.
*/
readonly valueMoney?: Money;
/**
* A suite of codes indicating exceptions or reductions to patient costs
* and their effective periods.
*/
readonly exception?: CoverageException[];
}
/**
* Financial instrument which may be used to reimburse or pay for health
* care products and services. Includes both insurance and self-payment.
*/
export interface CoverageException {
/**
* Unique id for the element within a resource (for internal references).
* This may be any string value that does not contain spaces.
*/
readonly id?: string;
/**
* May be used to represent additional information that is not part of
* the basic definition of the element. To make the use of extensions
* safe and manageable, there is a strict set of governance applied to
* the definition and use of extensions. Though any implementer can
* define an extension, there is a set of requirements that SHALL be met
* as part of the definition of the extension.
*/
readonly extension?: Extension[];
/**
* May be used to represent additional information that is not part of
* the basic definition of the element and that modifies the
* understanding of the element in which it is contained and/or the
* understanding of the containing element's descendants. Usually
* modifier elements provide negation or qualification. To make the use
* of extensions safe and manageable, there is a strict set of governance
* applied to the definition and use of extensions. Though any
* implementer can define an extension, there is a set of requirements
* that SHALL be met as part of the definition of the extension.
* Applications processing a resource are required to check for modifier
* extensions.
*
* Modifier extensions SHALL NOT change the meaning of any elements on
* Resource or DomainResource (including cannot change the meaning of
* modifierExtension itself).
*/
readonly modifierExtension?: Extension[];
/**
* The code for the specific exception.
*/
readonly type?: CodeableConcept;
/**
* The timeframe during when the exception is in force.
*/
readonly period?: Period;
}
|
import PdfList from './index'
import renderer from 'react-test-renderer'
describe('PdfList', () => {
test('renders correctly', () => {
const tree = renderer.create(<PdfList />).toJSON()
expect(tree).toEqual(expect.any(Object))
expect(tree).toMatchSnapshot()
})
})
|
#!/usr/bin/env python3
from mirobot import Mirobot
with Mirobot() as m:
m.home_simultaneous()
|
/*
* Copyright 2017-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.opencord.aaa.impl;
import static org.slf4j.LoggerFactory.getLogger;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.onlab.packet.MacAddress;
import org.onosproject.net.ConnectPoint;
import org.opencord.aaa.AuthenticationEvent;
import org.opencord.aaa.StateMachineDelegate;
import org.slf4j.Logger;
import com.google.common.collect.Maps;
/**
* AAA Finite State Machine.
*/
class StateMachine {
// INDEX to identify the state in the transition table
static final int STATE_IDLE = 0;
static final int STATE_STARTED = 1;
static final int STATE_PENDING = 2;
static final int STATE_AUTHORIZED = 3;
static final int STATE_UNAUTHORIZED = 4;
// Defining the states where timeout can happen
static final Set<Integer> TIMEOUT_ELIGIBLE_STATES = new HashSet();
static {
TIMEOUT_ELIGIBLE_STATES.add(STATE_STARTED);
TIMEOUT_ELIGIBLE_STATES.add(STATE_PENDING);
}
// INDEX to identify the transition in the transition table
static final int TRANSITION_START = 0; // --> started
static final int TRANSITION_REQUEST_ACCESS = 1;
static final int TRANSITION_AUTHORIZE_ACCESS = 2;
static final int TRANSITION_DENY_ACCESS = 3;
static final int TRANSITION_LOGOFF = 4;
private static int identifier = 1;
private byte challengeIdentifier;
private byte[] challengeState;
private byte[] username;
private byte[] requestAuthenticator;
// Supplicant connectivity info
private ConnectPoint supplicantConnectpoint;
private MacAddress supplicantAddress;
private short vlanId;
private byte priorityCode;
// Boolean flag indicating whether response is pending from AAA Server.
// Used for counting timeout happening for AAA Sessions due to no response.
private boolean waitingForRadiusResponse;
private static int cleanupTimerTimeOutInMins;
private String sessionId = null;
private final Logger log = getLogger(getClass());
private State[] states = {new Idle(), new Started(), new Pending(), new Authorized(), new Unauthorized() };
// Cleanup Timer instance created for this session
private java.util.concurrent.ScheduledFuture<?> cleanupTimer = null;
// TimeStamp of last EAPOL or RADIUS message received.
private long lastPacketReceivedTime = 0;
// State transition table
/*
*
* state IDLE | STARTED | PENDING | AUTHORIZED | UNAUTHORIZED //// input
* -----------------------------------------------------------------------------
* -----------------------
*
* START STARTED | _ | _ | STARTED | STARTED
*
* REQUEST_ACCESS _ | PENDING | _ | _ | _
*
* AUTHORIZE_ACCESS _ | _ | AUTHORIZED | _ | _
*
* DENY_ACCESS _ | - | UNAUTHORIZED | _ | _
*
* LOGOFF _ | _ | _ | IDLE | IDLE
*/
private int[] idleTransition = {STATE_STARTED, STATE_IDLE, STATE_IDLE, STATE_IDLE, STATE_IDLE };
private int[] startedTransition = {STATE_STARTED, STATE_PENDING, STATE_STARTED, STATE_STARTED, STATE_STARTED };
private int[] pendingTransition = {STATE_PENDING, STATE_PENDING, STATE_AUTHORIZED, STATE_UNAUTHORIZED,
STATE_PENDING };
private int[] authorizedTransition = {STATE_STARTED, STATE_AUTHORIZED, STATE_AUTHORIZED, STATE_AUTHORIZED,
STATE_IDLE };
private int[] unauthorizedTransition = {STATE_STARTED, STATE_UNAUTHORIZED, STATE_UNAUTHORIZED, STATE_UNAUTHORIZED,
STATE_IDLE };
// THE TRANSITION TABLE
private int[][] transition = {idleTransition, startedTransition, pendingTransition, authorizedTransition,
unauthorizedTransition };
private int currentState = STATE_IDLE;
// Maps of state machines. Each state machine is represented by an
// unique identifier on the switch: dpid + port number
private static Map<String, StateMachine> sessionIdMap;
private static Map<Integer, StateMachine> identifierMap;
private static StateMachineDelegate delegate;
public static void initializeMaps() {
sessionIdMap = Maps.newConcurrentMap();
identifierMap = Maps.newConcurrentMap();
identifier = 1;
}
public static void destroyMaps() {
sessionIdMap = null;
identifierMap = null;
}
public static void setDelegate(StateMachineDelegate delegate) {
StateMachine.delegate = delegate;
}
public static void setcleanupTimerTimeOutInMins(int cleanupTimerTimeoutInMins) {
cleanupTimerTimeOutInMins = cleanupTimerTimeoutInMins;
}
public static void unsetDelegate(StateMachineDelegate delegate) {
if (StateMachine.delegate == delegate) {
StateMachine.delegate = null;
}
}
public static Map<String, StateMachine> sessionIdMap() {
return sessionIdMap;
}
public static StateMachine lookupStateMachineById(byte identifier) {
return identifierMap.get((int) identifier);
}
public static StateMachine lookupStateMachineBySessionId(String sessionId) {
return sessionIdMap.get(sessionId);
}
public static void deleteStateMachineId(String sessionId) {
sessionIdMap.remove(sessionId);
}
public static void deleteStateMachineMapping(StateMachine machine) {
identifierMap.entrySet().removeIf(e -> e.getValue().equals(machine));
if (machine.cleanupTimer != null) {
machine.cleanupTimer.cancel(false);
machine.cleanupTimer = null;
}
}
public java.util.concurrent.ScheduledFuture<?> getCleanupTimer() {
return cleanupTimer;
}
public boolean isWaitingForRadiusResponse() {
return waitingForRadiusResponse;
}
public void setWaitingForRadiusResponse(boolean waitingForRadiusResponse) {
this.waitingForRadiusResponse = waitingForRadiusResponse;
}
public void setCleanupTimer(java.util.concurrent.ScheduledFuture<?> cleanupTimer) {
this.cleanupTimer = cleanupTimer;
}
/**
* Deletes authentication state machine records for a given MAC address.
*
* @param mac mac address of the suppliant who's state machine should be removed
*/
public static void deleteByMac(MacAddress mac) {
// Walk the map from session IDs to state machines looking for a MAC match
for (Map.Entry<String, StateMachine> e : sessionIdMap.entrySet()) {
// If a MAC match is found then delete the entry from the session ID
// and identifier map as well as call delete identifier to clean up
// the identifier bit set.
if (e.getValue() != null && e.getValue().supplicantAddress != null
&& e.getValue().supplicantAddress.equals(mac)) {
sessionIdMap.remove(e.getValue().sessionId);
if (e.getValue().identifier != 1) {
deleteStateMachineMapping(e.getValue());
}
break;
}
}
}
/**
* Creates a new StateMachine with the given session ID.
*
* @param sessionId session Id represented by the switch dpid + port number
*/
public StateMachine(String sessionId) {
log.info("Creating a new state machine for {}", sessionId);
this.sessionId = sessionId;
sessionIdMap.put(sessionId, this);
}
/**
* Gets the connect point for the supplicant side.
*
* @return supplicant connect point
*/
public ConnectPoint supplicantConnectpoint() {
return supplicantConnectpoint;
}
/**
* Sets the supplicant side connect point.
*
* @param supplicantConnectpoint supplicant select point.
*/
public void setSupplicantConnectpoint(ConnectPoint supplicantConnectpoint) {
this.supplicantConnectpoint = supplicantConnectpoint;
}
/**
* Gets the MAC address of the supplicant.
*
* @return supplicant MAC address
*/
public MacAddress supplicantAddress() {
return supplicantAddress;
}
/**
* Sets the supplicant MAC address.
*
* @param supplicantAddress new supplicant MAC address
*/
public void setSupplicantAddress(MacAddress supplicantAddress) {
this.supplicantAddress = supplicantAddress;
}
/**
* Sets the lastPacketReceivedTime.
*
* @param lastPacketReceivedTime timelastPacket was received
*/
public void setLastPacketReceivedTime(long lastPacketReceivedTime) {
this.lastPacketReceivedTime = lastPacketReceivedTime;
}
/**
* Gets the lastPacketReceivedTime.
*
* @return lastPacketReceivedTime
*/
public long getLastPacketReceivedTime() {
return lastPacketReceivedTime;
}
/**
* Gets the client's Vlan ID.
*
* @return client vlan ID
*/
public short vlanId() {
return vlanId;
}
/**
* Sets the client's vlan ID.
*
* @param vlanId new client vlan ID
*/
public void setVlanId(short vlanId) {
this.vlanId = vlanId;
}
/**
* Gets the client's priority Code.
*
* @return client Priority code
*/
public byte priorityCode() {
return priorityCode;
}
/**
* Sets the client's priority Code.
*
* @param priorityCode new client priority Code
*/
public void setPriorityCode(byte priorityCode) {
this.priorityCode = priorityCode;
}
/**
* Gets the client id that is requesting for access.
*
* @return The client id.
*/
public String sessionId() {
return this.sessionId;
}
/**
* Set the challenge identifier and the state issued by the RADIUS.
*
* @param challengeIdentifier The challenge identifier set into the EAP packet
* from the RADIUS message.
* @param challengeState The challenge state from the RADIUS.
*/
protected void setChallengeInfo(byte challengeIdentifier, byte[] challengeState) {
this.challengeIdentifier = challengeIdentifier;
this.challengeState = challengeState;
}
/**
* Set the challenge identifier issued by the RADIUS on the access challenge
* request.
*
* @param challengeIdentifier The challenge identifier set into the EAP packet
* from the RADIUS message.
*/
protected void setChallengeIdentifier(byte challengeIdentifier) {
log.info("Set Challenge Identifier to {}", challengeIdentifier);
this.challengeIdentifier = challengeIdentifier;
}
/**
* Gets the challenge EAP identifier set by the RADIUS.
*
* @return The challenge EAP identifier.
*/
protected byte challengeIdentifier() {
return this.challengeIdentifier;
}
/**
* Set the challenge state info issued by the RADIUS.
*
* @param challengeState The challenge state from the RADIUS.
*/
protected void setChallengeState(byte[] challengeState) {
log.info("Set Challenge State");
this.challengeState = challengeState;
}
/**
* Gets the challenge state set by the RADIUS.
*
* @return The challenge state.
*/
protected byte[] challengeState() {
return this.challengeState;
}
/**
* Set the username.
*
* @param username The username sent to the RADIUS upon access request.
*/
protected void setUsername(byte[] username) {
this.username = username;
}
/**
* Gets the username.
*
* @return The requestAuthenticator.
*/
protected byte[] requestAuthenticator() {
return this.requestAuthenticator;
}
/**
* Sets the authenticator.
*
* @param authenticator The username sent to the RADIUS upon access request.
*/
protected void setRequestAuthenticator(byte[] authenticator) {
this.requestAuthenticator = authenticator;
}
/**
* Gets the username.
*
* @return The username.
*/
protected byte[] username() {
return this.username;
}
/**
* Return the identifier of the state machine.
*
* @return The state machine identifier.
*/
public synchronized byte identifier() {
//identifier 0 is for statusServerrequest
//identifier 1 is for fake accessRequest
identifier = (identifier + 1) % 253;
identifierMap.put((identifier + 2), this);
return (byte) (identifier + 2);
}
/**
* Move to the next state.
*
* @param msg message
*/
private void next(int msg) {
currentState = transition[currentState][msg];
log.info("Current State " + currentState);
}
/**
* Client has requested the start action to allow network access.
*
* @throws StateMachineException if authentication protocol is violated
*/
public void start() throws StateMachineException {
states[currentState].start();
delegate.notify(new AuthenticationEvent(AuthenticationEvent.Type.STARTED, supplicantConnectpoint));
// move to the next state
next(TRANSITION_START);
identifier = this.identifier();
}
/**
* An Identification information has been sent by the supplicant. Move to the
* next state if possible.
*
* @throws StateMachineException if authentication protocol is violated
*/
public void requestAccess() throws StateMachineException {
states[currentState].requestAccess();
delegate.notify(new AuthenticationEvent(AuthenticationEvent.Type.REQUESTED, supplicantConnectpoint));
// move to the next state
next(TRANSITION_REQUEST_ACCESS);
}
/**
* RADIUS has accepted the identification. Move to the next state if possible.
*
* @throws StateMachineException if authentication protocol is violated
*/
public void authorizeAccess() throws StateMachineException {
states[currentState].radiusAccepted();
// move to the next state
next(TRANSITION_AUTHORIZE_ACCESS);
delegate.notify(new AuthenticationEvent(AuthenticationEvent.Type.APPROVED, supplicantConnectpoint));
// Clear mapping
deleteStateMachineMapping(this);
}
/**
* RADIUS has denied the identification. Move to the next state if possible.
*
* @throws StateMachineException if authentication protocol is violated
*/
public void denyAccess() throws StateMachineException {
states[currentState].radiusDenied();
// move to the next state
next(TRANSITION_DENY_ACCESS);
delegate.notify(new AuthenticationEvent(AuthenticationEvent.Type.DENIED, supplicantConnectpoint));
// Clear mappings
deleteStateMachineMapping(this);
}
/**
* Logoff request has been requested. Move to the next state if possible.
*
* @throws StateMachineException if authentication protocol is violated
*/
public void logoff() throws StateMachineException {
states[currentState].logoff();
// move to the next state
next(TRANSITION_LOGOFF);
}
/**
* Gets the current state.
*
* @return The current state. Could be STATE_IDLE, STATE_STARTED, STATE_PENDING,
* STATE_AUTHORIZED, STATE_UNAUTHORIZED.
*/
public int state() {
return currentState;
}
@Override
public String toString() {
return ("sessionId: " + this.sessionId) + "\t" + ("identifier: " + this.identifier) + "\t"
+ ("state: " + this.currentState);
}
abstract class State {
private final Logger log = getLogger(getClass());
private String name = "State";
public void start() throws StateMachineInvalidTransitionException {
log.warn("START transition from this state is not allowed.");
}
public void requestAccess() throws StateMachineInvalidTransitionException {
log.warn("REQUEST ACCESS transition from this state is not allowed.");
}
public void radiusAccepted() throws StateMachineInvalidTransitionException {
log.warn("AUTHORIZE ACCESS transition from this state is not allowed.");
}
public void radiusDenied() throws StateMachineInvalidTransitionException {
log.warn("DENY ACCESS transition from this state is not allowed.");
}
public void logoff() throws StateMachineInvalidTransitionException {
log.warn("LOGOFF transition from this state is not allowed.");
}
}
/**
* Idle state: supplicant is logged of from the network.
*/
class Idle extends State {
private final Logger log = getLogger(getClass());
private String name = "IDLE_STATE";
@Override
public void start() {
log.info("Moving from IDLE state to STARTED state.");
}
}
/**
* Started state: supplicant has entered the network and informed the
* authenticator.
*/
class Started extends State {
private final Logger log = getLogger(getClass());
private String name = "STARTED_STATE";
@Override
public void requestAccess() {
log.info("Moving from STARTED state to PENDING state.");
}
}
/**
* Pending state: supplicant has been identified by the authenticator but has
* not access yet.
*/
class Pending extends State {
private final Logger log = getLogger(getClass());
private String name = "PENDING_STATE";
@Override
public void radiusAccepted() {
log.info("Moving from PENDING state to AUTHORIZED state.");
}
@Override
public void radiusDenied() {
log.info("Moving from PENDING state to UNAUTHORIZED state.");
}
}
/**
* Authorized state: supplicant port has been accepted, access is granted.
*/
class Authorized extends State {
private final Logger log = getLogger(getClass());
private String name = "AUTHORIZED_STATE";
@Override
public void start() {
log.info("Moving from AUTHORIZED state to STARTED state.");
}
@Override
public void logoff() {
log.info("Moving from AUTHORIZED state to IDLE state.");
}
}
/**
* Unauthorized state: supplicant port has been rejected, access is denied.
*/
class Unauthorized extends State {
private final Logger log = getLogger(getClass());
private String name = "UNAUTHORIZED_STATE";
@Override
public void start() {
log.info("Moving from UNAUTHORIZED state to STARTED state.");
}
@Override
public void logoff() {
log.info("Moving from UNAUTHORIZED state to IDLE state.");
}
}
/**
* Class for cleaning the StateMachine for those session for which no response
* is coming--implementing timeout.
*/
class CleanupTimerTask implements Runnable {
private final Logger log = getLogger(getClass());
private String sessionId;
private AaaManager aaaManager;
CleanupTimerTask(String sessionId, AaaManager aaaManager) {
this.sessionId = sessionId;
this.aaaManager = aaaManager;
}
@Override
public void run() {
StateMachine stateMachine = StateMachine.lookupStateMachineBySessionId(sessionId);
if (null != stateMachine) {
// Asserting if last packet received for this stateMachine session was beyond half of timeout period.
// StateMachine is considered eligible for cleanup when no packets has been exchanged by it with AAA
// Server or RG during a long period (half of timeout period). For example, when cleanup timer has
// been configured as 10 minutes, StateMachine would be cleaned up at the end of 10 minutes if
// the authentication is still pending and no packet was exchanged for this session during last 5
// minutes.
boolean noTrafficWithinThreshold = (System.currentTimeMillis()
- stateMachine.getLastPacketReceivedTime()) > ((cleanupTimerTimeOutInMins * 60 * 1000) / 2);
if ((TIMEOUT_ELIGIBLE_STATES.contains(stateMachine.state())) && noTrafficWithinThreshold) {
log.info("Deleting StateMachineMapping for sessionId: {}", sessionId);
cleanupTimer = null;
if (stateMachine.state() == STATE_PENDING && stateMachine.isWaitingForRadiusResponse()) {
aaaManager.aaaStatisticsManager.getAaaStats().increaseTimedOutPackets();
}
deleteStateMachineId(sessionId);
deleteStateMachineMapping(stateMachine);
// If StateMachine is not eligible for cleanup yet, reschedule cleanupTimer further.
} else {
aaaManager.scheduleStateMachineCleanupTimer(sessionId, stateMachine);
}
} else {
// This statement should not be logged; cleanupTimer should be cancelled for stateMachine
// instances which have been authenticated successfully.
log.warn("state-machine not found for sessionId: {}", sessionId);
}
}
}
}
|
#!/bin/bash
# Require env
# GITHUB_TOKEN
# GITHUB_EVENT_PATH=/tmp/abc.json
# GITHUB_REPOSITORY=ibuler/koko
generate_create_pr_data()
{
cat <<EOF
{
"title": "${PR_TITLE}",
"body": "${PR_BODY}",
"head": "${PR_HEAD}",
"base": "${PR_BASE}"
}
EOF
}
# 当push了 PR Request分支(分支名称 pr@${TO_BRANCH}@other)
on_push_pr_branch() {
CREATED=$(jq -r .created < "${GITHUB_EVENT_PATH}")
if [[ "${CREATED}" != "true" ]];then
echo "Not a new create branch, pass"
return 0
fi
PR_REF=$(jq -r .ref < "${GITHUB_EVENT_PATH}")
PR_HEAD=$(basename "${PR_REF}")
PR_BASE=$(echo "${PR_HEAD}" | awk -F@ '{ print $2 }')
if ! echo "${PR_HEAD}" | grep -E '^pr@[a-zA-Z0-9.]+@.+';then
echo "Not a pr request branch, should be pr_BRANCH_other: ${PR_HEAD}"
return 0
fi
# 应该是pr@${TO_BRANCH}@other
if [[ -z "${PR_BASE}" ]];then
echo "Unexepect error occur"
return 0
fi
PR_TITLE=$(jq -r .head_commit.message < "${GITHUB_EVENT_PATH}" | head -1)
if [[ -z "${PR_TITLE}" ]];then
echo "No commit found, exit"
exit 1
fi
BASE_BRANCH_DETAIL_URL=$(jq -r .repository.git_refs_url < "${GITHUB_EVENT_PATH}" | sed "s@{.*}@/heads/${PR_BASE}@g")
curl \
--fail \
-X GET \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer ${GITHUB_TOKEN}" \
"${BASE_BRANCH_DETAIL_URL}" | jq '.ref' || return 1
PR_BODY=$(jq -r '.commits|map(.message)|join("<br>")' < "${GITHUB_EVENT_PATH}" | tr '\n' ' ')
PR_URL=$(jq -r '.repository.pulls_url' < "${GITHUB_EVENT_PATH}"|sed 's@{.*}@@g')
curl \
--fail \
-X POST \
--data "$(generate_create_pr_data)" \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer ${GITHUB_TOKEN}" \
"${PR_URL}" > /dev/null
}
function add_remote_github() {
# Clone仓库
AUTHOR_NAME=$(jq -r .head_commit.author.name < "${GITHUB_EVENT_PATH}")
AUTHOR_EMAIL=$(jq -r .head_commit.author.email < "${GITHUB_EVENT_PATH}")
git config --global user.name "${AUTHOR_NAME}"
git config --global user.email "${AUTHOR_EMAIL}"
remote_url="https://${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}"
rm -rf GITHUB_REPO
git clone "${remote_url}" "GITHUB_REPO" && cd "GITHUB_REPO" || exit 2
git status
git fetch origin
git remote -v
}
function clean_remote_github() {
cd ..
rm -rf "GITHUB_REPO"
}
# 当push了 PR Request分支(分支名称 repr@TO_BRANCHES@REBASE_START@OTHER)
# example: repr@master_v1.0_v2.0@7f01ed8d6f1@fix-some-bug
rebase_branch_and_push_pr_branch() {
PR_REF=$(jq -r .ref < "${GITHUB_EVENT_PATH}")
PR_HEAD=$(basename "${PR_REF}")
PR_BASES=$(echo "${PR_HEAD}" | awk -F@ '{ print $2 }')
PR_REBASE_START=$(echo "${PR_HEAD}" | awk -F@ '{ print $3 }')
PR_OTHER=$(echo "${PR_HEAD}" | awk -F@ '{ print $4 }')
if ! echo "${PR_HEAD}" | grep -E '^repr@[a-zA-Z0-9._]+@[a-z0-9]+@.+';then
echo "Not a pr request branch, should be repr@TO_BRANCHES@REBASE_START@OTHER: ${PR_HEAD}"
return 0
fi
# 应该是master_v1.0_v2.0
if [[ -z "${PR_BASES}" ]];then
echo "Unexpect error occur"
return 0
fi
# 切换成可迭代的
PR_BASES=$(echo "${PR_BASES}" | tr "_" "\n")
# 添加github认证
add_remote_github
for b in $PR_BASES;do
echo -e "\n>>> Start process $b"
new_pr_branch_name="pr@${b}@${PR_OTHER}"
remote_branch_name="origin/$b"
git checkout "${PR_HEAD}" || echo ""
git branch -D "${new_pr_branch_name}" &> /dev/null || echo ""
git checkout -b "${new_pr_branch_name}"
git rebase "${PR_REBASE_START}" --onto="${remote_branch_name}"
ret="$?"
if [[ "${ret}" != "0" ]];then
echo "Rebase failed ${ret}: ${remote_branch_name}"
git rebase --abort || echo ""
continue
fi
git push -f origin "${new_pr_branch_name}:${new_pr_branch_name}"
done
git checkout "${PR_HEAD}" || echo ""
git branch | grep 'pr'
# 清理掉这个分支, 再清理本地仓库
git push origin :"${PR_HEAD}"
clean_remote_github
}
if [[ "${GITHUB_EVENT_NAME}" != "push" ]];then
exit 0
fi
on_push_pr_branch
rebase_branch_and_push_pr_branch
|
<?hh
namespace Waffle\Tests\Container\ServiceProvider;
use type Facebook\HackTest\HackTest;
use type Waffle\Container\Container;
use type Waffle\Container\Exception\ContainerException;
use type Waffle\Tests\Container\Asset\FakeServiceProvider;
use type Waffle\Container\ServiceProvider\ServiceProviderAggregate;
use function Facebook\FBExpect\expect;
class ServiceProviderAggregateTest extends HackTest
{
/**
* Return a service provider fake
*
* @return \Waffle\Container\ServiceProvider\ServiceProviderInterface
*/
protected function getServiceProvider(): FakeServiceProvider
{
return new FakeServiceProvider();
}
/**
* Asserts that the aggregate adds a class name service provider.
*/
public function testAggregateAddsClassNameServiceProvider()
{
$container = new Container();
$aggregate = (new ServiceProviderAggregate())->setContainer($container);
$aggregate->add($this->getServiceProvider());
expect($aggregate->provides('SomeService'))->toBeTrue();
expect($aggregate->provides('AnotherService'))->toBeTrue();
}
/**
* Asserts that an exception is thrown when adding a service provider that
* does not exist.
*/
public function testAggregateThrowsWhenCannotResolveServiceProvider()
{
expect(() ==> {
$container = new Container();
$aggregate = (new ServiceProviderAggregate())->setContainer($container);
$aggregate->add('NonExistentClass');
})->toThrow(ContainerException::class);
}
/**
* Asserts that an exception is thrown when attempting to invoke the register
* method of a service provider that has not been provided.
*/
public function testAggregateThrowsWhenRegisteringForServiceThatIsNotAdded()
{
expect(() ==> {
$container = new Container();
$aggregate = (new ServiceProviderAggregate())->setContainer($container);
$aggregate->register('SomeService');
})->toThrow(ContainerException::class);
}
/**
* Asserts that resgister method is only invoked once per service provider.
*/
public function testAggregateInvokesCorrectRegisterMethodOnlyOnce()
{
$container = new Container();
$aggregate = (new ServiceProviderAggregate())->setContainer($container);
$provider = $this->getServiceProvider();
$aggregate->add($provider);
$aggregate->register('SomeService');
$aggregate->register('AnotherService');
if ($provider is FakeServiceProvider) {
expect($provider->registered)->toBeSame(1);
} else {
static::fail('Expected ServiceProviderAggregate to return FakeServiceProvider.');
}
}
}
|
#!/usr/bin/env bash
if [ -z "$1" ]; then
exit 1;
fi
failed_cmd="$1"
# Environment variables should be loaded under all conditions.
if [ -z "${TWLIGHT_HOME}" ]
then
exit 1
fi
# Report failed command via email.
echo "$failed_cmd failed. Please check the logs." | mail -a "From: Wikipedia Library Card Platform <noreply@wikipedialibrary.wmflabs.org>" -s "task failed for $(hostname -f)" ${TWLIGHT_ERROR_MAILTO}
|
import React from 'react';
import styles from './styles.css';
import Breadcrumb from './breadcrumb';
import MyPrototype from './myPrototype';
import Examples from './examples';
const Dashboard = ({
createNewPrototype,
uploadPrototypeImage,
pushToast,
dashboard,
clonePrototype,
retrieveDashboard,
retrievePrototypeTemplates,
}) => (
<div>
<div className={styles.base}>
<Breadcrumb />
<MyPrototype
createNewPrototype={createNewPrototype}
uploadPrototypeImage={uploadPrototypeImage}
clonePrototype={clonePrototype}
userPrototypes={dashboard.userPrototypes}
retrieveDashboard={retrieveDashboard}
retrievePrototypeTemplates={retrievePrototypeTemplates}
templates={dashboard.templates}
pushToast={pushToast}
/>
<Examples
clonePrototype={clonePrototype}
uploadPrototypeImage={uploadPrototypeImage}
createNewPrototype={createNewPrototype}
templates={dashboard.templates}
retrieveDashboard={retrieveDashboard}
pushToast={pushToast}
/>
</div>
</div>
);
export default Dashboard;
|
from typing import List
def temperature_analysis(temperatures: List[int], threshold: int) -> str:
count_exceeding_threshold = sum(1 for temp in temperatures if temp > threshold)
if count_exceeding_threshold > 100:
return 'Steam'
elif 50 <= count_exceeding_threshold <= 100:
return 'High'
elif 10 <= count_exceeding_threshold <= 49:
return 'Moderate'
else:
return 'Low'
|
for key in list(item.keys()):
bcalias = source['alias']
lc = 0
if key in ['name', 'sources', 'schema', 'photometry']:
# Perform operations based on the keys
|
#!/bin/bash
set -euo pipefail
# Bazel uses `-debug-prefix-map` to strip the bazel build directory from the
# paths embedded in debug info. This means the debug info contains _project
# relative_ paths instead of Bazel absolute paths.
#
# However, Xcode sets breakpoints via _project absolute_ paths, which are not
# the paths in the debug info. This lldb setting ensures that _project relative_
# paths are remapped to _project absolute_ paths.
#
# The platform settings one points the current working directory (cwd) to workspace root.
# This is needed for features relying on lldb remote debugging, such as `oso_prefix_is_pwd`.
cat > $BAZEL_LLDB_INIT_FILE <<-END
platform settings -w "$BAZEL_WORKSPACE_ROOT/"
settings set target.source-map ./ "$BAZEL_WORKSPACE_ROOT/"
settings set target.sdk-path $SDKROOT
settings set target.swift-framework-search-paths $FRAMEWORK_SEARCH_PATHS
END
if [[ -n ${BAZEL_LLDB_SWIFT_EXTRA_CLANG_FLAGS:-} ]]
then
cat >> $BAZEL_LLDB_INIT_FILE <<-END
settings set -- target.swift-extra-clang-flags $BAZEL_LLDB_SWIFT_EXTRA_CLANG_FLAGS
END
fi
BAZEL_EXTERNAL_DIRNAME="$BAZEL_WORKSPACE_ROOT/bazel-$(basename "$BAZEL_WORKSPACE_ROOT")/external"
if [ -d "$BAZEL_EXTERNAL_DIRNAME" ]
then
cat >> $BAZEL_LLDB_INIT_FILE <<-END
settings append target.source-map ./external/ "$BAZEL_EXTERNAL_DIRNAME"
END
fi
|
<filename>App/src/main/java/com/honyum/elevatorMan/receiver/JPushMsgReceiver.java
package com.honyum.elevatorMan.receiver;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;
import com.baidu.navisdk.util.common.StringUtils;
import com.honyum.elevatorMan.R;
import com.honyum.elevatorMan.activity.common.ChatActivity;
import com.honyum.elevatorMan.activity.maintenance.MyLiftActivity;
import com.honyum.elevatorMan.activity.property.AlarmTraceActivity;
import com.honyum.elevatorMan.activity.repair.RepairLiftActivity;
import com.honyum.elevatorMan.activity.repair.RepairListActivity;
import com.honyum.elevatorMan.activity.workOrder.WorkOrderListActivity;
import com.honyum.elevatorMan.activity.worker.WorkerActivity;
import com.honyum.elevatorMan.base.BaseFragmentActivity;
import com.honyum.elevatorMan.base.Config;
import com.honyum.elevatorMan.base.MyApplication;
import com.honyum.elevatorMan.constant.Constant;
import com.honyum.elevatorMan.data.AlarmNotify;
import com.honyum.elevatorMan.net.NotifyFeedbackRequest;
import com.honyum.elevatorMan.net.base.NetConstant;
import com.honyum.elevatorMan.net.base.NetTaskNew;
import com.honyum.elevatorMan.net.base.RequestBean;
import com.honyum.elevatorMan.net.base.RequestHead;
import com.honyum.elevatorMan.utils.Utils;
import cn.jpush.android.api.JPushInterface;
public class JPushMsgReceiver extends BroadcastReceiver {
public static final String TAG = "JPUSH";
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle bundle = intent.getExtras();
if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
processNotify(context, bundle);
} else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
}
}
/**
* 处理推送消息
*
* @param context
* @param bundle
*/
private void processNotify(Context context, Bundle bundle) {
//if(bundle!=null&&bundle.getS)
setNotification(context, bundle);
}
/**
* 通知消息
*
* @param context
* @param bundle
*/
private void setNotification(Context context, Bundle bundle) {
//通知携带的额外信息
String extraMsg = bundle.getString(JPushInterface.EXTRA_EXTRA);
String msg = bundle.getString(JPushInterface.EXTRA_MESSAGE);
String msgId = bundle.getString(JPushInterface.EXTRA_MSG_ID);
Log.i("push", "extra msg:" + extraMsg);
Log.i("push", "msg:" + msg);
Log.i("push", "msgId:" + msgId);
AlarmNotify alarmNotify = AlarmNotify.getAlarmNotify(extraMsg);
//获取通知的类型
String notifyType = alarmNotify.getNotifyType();
Log.d("push", "notifyType ==>> " + notifyType);
//过滤接收到的消息是否为有效消息
if (StringUtils.isEmpty(notifyType)) {
return;
}
//接收到通知后,反馈给服务器接收成功标记
SharedPreferences preferences = context.getSharedPreferences("config", Context.MODE_PRIVATE);
// String region = preferences.getString("region", Constant.SHANGHAI);
//
// String server = Constant.SERVER_LIST.get(region);
//
// if (StringUtils.isEmpty(server)) {
// server = Constant.SERVER_LIST.get(Constant.CHINA);
// }
NetTaskNew task = new NetTaskNew(context, Config.baseUrl+"/mobile" + NetConstant.URL_NOTIFY_FEEDBACK,
getRequestBean(context, alarmNotify.getAlarmId(), notifyType)) {
@Override
protected void onReturn(NetTaskNew task, String result) {
super.onReturn(task, result);
Log.i("notify12313131313", "feedback successfully!");
}
};
task.start();
// if(bundle!=null&& !TextUtils.isEmpty(msg))
// {
// String [] s = msg.split("说:");
// if(s[0].equals(((MyApplication)context.getApplicationContext()).getConfig().getName()))
// return;
// }
//维修工维保信息被拒绝
if (notifyType.equals(Constant.ACTION_MAIN_REJECT)) {
sendMainPlanRejectNotify(context);
}
//使用角色控制维修工和物业的登录冲突
String role = getRole(context);
//ChatActivity.isForeground() &&ChatActivity.isForeground()
if ("BAOXIU_NOTICE".equals(notifyType)||"BAOXIU_ASSIGN".equals(notifyType))
{
jumpToPage(context, alarmNotify, RepairListActivity.class, msg, msgId);
return;
}
else if ("TASK_FINISH".equals(notifyType)||"MAINT_NOTICE".equals(notifyType))
{
jumpToPage(context, alarmNotify, WorkOrderListActivity.class, msg, msgId);
}
else if("RESTART_LOCATION".equals(notifyType))
{
Intent it = new Intent();
it.setAction(Constant.START_LOCATION_SERVICE);
context.sendBroadcast(it);
}
if (role.equals(Constant.WORKER)) {
notifyWorker(context, alarmNotify, WorkerActivity.class, msg, msgId);
} else if (role.equals(Constant.PROPERTY)) {
notifyProperty(context, alarmNotify, AlarmTraceActivity.class, msg, msgId);
}
Log.e("push", "BaseFragmentActivity当前是否显示在聊天界面==>>>" + BaseFragmentActivity.isForeground()+ ChatActivity.isForeground()+chatMsgListener == null?"false":"true");
Log.e("push", "ChatActivity当前是否显示在聊天界面==>>>" + ChatActivity.isForeground());
if (BaseFragmentActivity.isForeground() && "CHAT".equals(notifyType)
&& chatMsgListener != null && ChatActivity.isForeground()) {
chatMsgListener.chatMsgListener(alarmNotify);
} else if ("CHAT".equals(notifyType)) {
jumpToPage(context, alarmNotify, ChatActivity.class, msg, msgId);
}
}
public interface onChatMsgListener {
void chatMsgListener(AlarmNotify alarmNotify);
}
private static onChatMsgListener chatMsgListener;
public static void setChatMsgListener(onChatMsgListener chatMsgListener) {
JPushMsgReceiver.chatMsgListener = chatMsgListener;
}
/**
* 初始化通知
*
* @param context
* @param intent
* @param notifyId
* @param msg
* @return
*/
private void sendNotify(Context context, Intent intent, String notifyId,
String msg) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setSmallIcon(R.drawable.logo);
builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.logo));
if (intent.getAction().equals(Constant.ACTION_ALARM_RECEIVED)
|| intent.getAction().equals(Constant.ACTION_ALARM_PROPERTY)) {
builder.setSound(Uri.parse("android.resource://" + context.getPackageName()
+ "/" + R.raw.alarm));
} else {
builder.setSound(Uri.parse("android.resource://" + context.getPackageName()
+ "/" + R.raw.message));
}
if(msg.contains("说:"))
{
String[] split = msg.split("说:");
builder.setTicker(msg);
builder.setContentTitle(split[0]);
builder.setContentText(split[1]);
}
else
{
builder.setTicker(msg);
builder.setContentTitle(msg);
builder.setContentText(msg);
}
int code = (int) (Long.parseLong(notifyId) % Integer.MAX_VALUE);
//使用code参数标记每次传递的intent 参数都不同
PendingIntent pendingIntent = PendingIntent.getActivity(context, code,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
builder.setAutoCancel(true);
final NotificationManager manager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
//同一个报警事件的推送事件使用相同的通知id
final int mId = Utils.getIntByStr(intent.getStringExtra("alarm_id"));
manager.notify(mId, builder.build());
// Notification notify = new Notification();
// notify.icon = R.drawable.logo;
// if (intent.getAction().equals(Constant.ACTION_ALARM_RECEIVED)
// || intent.getAction().equals(Constant.ACTION_ALARM_PROPERTY)) {
// notify.sound = Uri.parse("android.resource://" + context.getPackageName()
// + "/" + R.raw.alarm);
// } else {
// notify.sound = Uri.parse("android.resource://" + context.getPackageName()
// + "/" + R.raw.message);
// }
//
// int code = (int) (Long.parseLong(notifyId) % Integer.MAX_VALUE);
//
// //使用code参数标记每次传递的intent 参数都不同
// PendingIntent pendingIntent = PendingIntent.getActivity(context, code,
// intent, PendingIntent.FLAG_UPDATE_CURRENT);
//
// String[] split = msg.split("说:");
//
// notify.setLatestEventInfo(context, split[0], split[1], pendingIntent);
// notify.fullScreenIntent = pendingIntent;
//
// notify.flags = Notification.FLAG_AUTO_CANCEL;
//
// NotificationManager manager = (NotificationManager) context
// .getSystemService(Context.NOTIFICATION_SERVICE);
//
// //同一个报警事件的推送事件使用相同的通知id
// int mId = Utils.getIntByStr(intent.getStringExtra("alarm_id"));
// manager.notify(mId, notify);
}
/**
* 获取用户角色
*
* @param context
* @return
*/
private String getRole(Context context) {
SharedPreferences preferences = context.getSharedPreferences("config", Context.MODE_PRIVATE);
return preferences.getString("role", Constant.PROPERTY);
}
/**
* 获取用户id
*
* @param context
* @return
*/
private String getUserId(Context context) {
SharedPreferences preferences = context.getSharedPreferences("config", Context.MODE_PRIVATE);
return preferences.getString("user_id", "");
}
/**
* 发送通知,点击跳转到页面
*
* @param context
* @param alarmNotify
* @param cls
* @param msg
* @param msgId
*/
private void jumpToPage(Context context, AlarmNotify alarmNotify, Class<?> cls,
String msg, String msgId) {
Intent intent = new Intent(context, cls);
intent.setAction(alarmNotify.getNotifyType());
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("alarm_id", alarmNotify.getAlarmId());
intent.putExtra("msg", msg);
intent.putExtra("from", TAG);
sendNotify(context, intent, msgId, msg);
}
/**
* 当在前台时,处理接收到的推送消息
*
* @param context
* @param alarmNotify
* @param msg
*/
private void sendToPage(Context context, AlarmNotify alarmNotify, String msg) {
Intent intent = new Intent();
intent.setAction(addForeAction(alarmNotify.getNotifyType()));
intent.putExtra("alarm_id", alarmNotify.getAlarmId());
intent.putExtra("msg", msg);
intent.putExtra("from", TAG);
context.sendBroadcast(intent);
}
/**
* 通知维修工
*
* @param context
* @param alarmNotify
* @param cls
* @param msg
* @param msgId
*/
private void notifyWorker(Context context, AlarmNotify alarmNotify, Class<?> cls,
String msg, String msgId) {
//如果是报警信息,写入到数据库中,同时给服务器反馈,已经接收到报警信息
// String type = alarmNotify.getNotifyType();
// if (type.equals(Constant.ACTION_ALARM_RECEIVED)) {
// AlarmSqliteUtils.insertAlarm(context, getUserId(context), alarmNotify.getAlarmId());
// }
//
// //如果是指派结果信息,把此条报警相关的信息从sqlite中删除
// if (type.equals(Constant.ACTION_ALARM_ASSIGNED )
// || type.equals(Constant.ACTION_ALARM_UNASSIGNED)) {
// AlarmSqliteUtils.deleteAlarm(context, alarmNotify.getAlarmId());
// }
if (BaseFragmentActivity.isForeground()) {
sendToPage(context, alarmNotify, msg);
} else {
jumpToPage(context, alarmNotify, WorkerActivity.class, msg, msgId);
}
}
/**
* 通知物业
*
* @param context
* @param alarmNotify
* @param cls
* @param msg
* @param msgId
*/
private void notifyProperty(Context context, AlarmNotify alarmNotify, Class<?> cls,
String msg, String msgId) {
if (BaseFragmentActivity.isForeground()) {
sendToPage(context, alarmNotify, msg);
} else {
jumpToPage(context, alarmNotify, AlarmTraceActivity.class, msg, msgId);
}
}
/**
* 产生内部消息的action
*
* @param action
* @return
*/
private String addForeAction(String action) {
if (action.contains("_FORE")) {
return action;
}
return action + "_FORE";
}
private void sendMainPlanRejectNotify(Context context) {
Intent intent = new Intent(context, MyLiftActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(context)
.setAutoCancel(true)
.setSmallIcon(R.drawable.logo)
.setContentTitle("物业拒绝了您的维保计划")
.setContentText("物业拒绝了您的维保计划,点击查看详情")
.setContentIntent(pendingIntent)
.getNotification();
notification.defaults |= Notification.DEFAULT_SOUND;
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, notification);
}
/**
* 获取通知反馈的请求bean
*
* @param context
* @param alarmId
* @param notifyType
* @return
*/
private RequestBean getRequestBean(Context context, String alarmId, String notifyType) {
NotifyFeedbackRequest request = new NotifyFeedbackRequest();
NotifyFeedbackRequest.NotifyFeedbackReqBody body = request.new NotifyFeedbackReqBody();
RequestHead head = new RequestHead();
SharedPreferences preferences = context.getSharedPreferences("config", Context.MODE_PRIVATE);
head.setUserId(preferences.getString("user_id", ""));
head.setAccessToken(preferences.getString("token", ""));
body.setAlarmId(alarmId);
body.setType(notifyType);
body.setRole(preferences.getString("role", Constant.WORKER));
request.setHead(head);
request.setBody(body);
return request;
}
}
|
/*
* CPAchecker is a tool for configurable software verification.
* This file is part of CPAchecker.
*
* Copyright (C) 2007-2018 <NAME>
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* CPAchecker web page:
* http://cpachecker.sosy-lab.org
*/
package org.sosy_lab.cpachecker.util.slicing;
import java.util.Collection;
import org.sosy_lab.cpachecker.cfa.CFA;
import org.sosy_lab.cpachecker.cfa.model.CFAEdge;
import org.sosy_lab.cpachecker.core.Specification;
/**
* Interface for program slicers.
*
* <p>Classes implementing this interface provide means to get the {@link CFAEdge CFA edges} of a
* {@link CFA} that are relevant regarding a {@link Specification} or a set of slicing criteria.
* Slicing criteria are given as CFA edges.
*
* @see SlicerFactory
*/
public interface Slicer {
/** Returns the {@link Slice} of the given CFA that is relevant for the given specification. */
Slice getSlice(CFA pCfa, Specification pSpecification) throws InterruptedException;
/** Returns the {@link Slice} in the given CFA that is relevant for the given specification. */
Slice getSlice(CFA pCfa, Collection<CFAEdge> pSlicingCriteria) throws InterruptedException;
}
|
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {UtilityService} from '../utility/utility.service';
@Injectable()
export class ServerService {
serverURL = this.util.getServerUrl().local;
constructor(private http: HttpClient, private util: UtilityService) { }
uploadFileToServer(file){
let formData = new FormData();
formData.append(file.name, file);
let result = '';
return this.http.post(`${this.serverURL}/images/upload/`+localStorage.getItem('username'), formData);
}
uploadAvatarToServer(username, file){
let formData = new FormData();
formData.append(file.name, file);
let result = '';
return this.http.post(`${this.serverURL}/avatar/upload/`+ username, formData);
}
getUserAvatar(avatarName){
return this.http.get(`${this.serverURL}/avatar/get/` + avatarName ,{
responseType: 'blob',
headers: new HttpHeaders().append('Content-Type', 'application/json')
});
}
}
|
<reponame>tdm1223/Algorithm
// 9488. The n Days of Christmas
// 2021.09.05
// 수학
#include<iostream>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
unsigned long long n;
while (1)
{
cin >> n;
if (n == 0)
{
break;
}
cout << n * (n + 1) * (n + 2) / 6 << "\n";
}
return 0;
}
|
import requests
from bs4 import BeautifulSoup
def retrieve_data(url):
webpage_text = requests.get(url).text
webpage_soup = BeautifulSoup(webpage_text, 'html.parser')
data = webpage_soup.find_all('div', {'class': 'data'})
return data
|
source $stdenv/setup
set -o pipefail
objects=($objects)
symlinks=($symlinks)
suffices=($suffices)
mkdir root
# Needed for splash_helper, which gets run before init.
mkdir root/dev
mkdir root/sys
mkdir root/proc
for ((n = 0; n < ${#objects[*]}; n++)); do
object=${objects[$n]}
symlink=${symlinks[$n]}
suffix=${suffices[$n]}
if test "$suffix" = none; then suffix=; fi
mkdir -p $(dirname root/$symlink)
ln -s $object$suffix root/$symlink
done
# Get the paths in the closure of `object'.
storePaths=$(perl $pathsFromGraph closure-*)
# Paths in cpio archives *must* be relative, otherwise the kernel
# won't unpack 'em.
(cd root && cp -prd --parents $storePaths .)
# Put the closure in a gzipped cpio archive.
mkdir -p $out
for PREP in $prepend; do
cat $PREP >> $out/initrd
done
(cd root && find * -print0 | cpio -o -H newc --null | perl $cpioClean | $compressor >> $out/initrd)
if [ -n "$makeUInitrd" ]; then
mv $out/initrd $out/initrd.gz
mkimage -A arm -O linux -T ramdisk -C gzip -d $out/initrd.gz $out/initrd
fi
|
// Copyright (c) 2022 <NAME>. All Rights Reserved.
// https://github.com/cinar/indicatorts
import { deepStrictEqual } from 'assert';
import { mmax } from './mmax';
describe('Moving Max', () => {
it('should be able to compute max', () => {
const values = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
const expected = [10, 10, 10, 10, 9, 8, 7, 6, 5, 4];
const period = 4;
const actual = mmax(period, values);
deepStrictEqual(actual, expected);
});
});
|
<reponame>littlemole/MTL<filename>examples/helloworld/helloworld/id.cpp
#include "framework.h"
static void load_resource_ids()
{
mtl::gui().add({
{ 2, "IDC_MYICON" },
{ 101, "IDD_HELLOWORLD_DIALOG" },
{ 102, "IDS_APP_TITLE" },
{ 103, "IDD_ABOUTBOX" },
{ 104, "IDM_ABOUT" },
{ 105, "IDM_EXIT" },
{ 106, "IDI_HELLOWORLD" },
{ 107, "IDI_SMALL" },
{ 108, "IDI_JPEG" },
{ 109, "IDC_HELLOWORLD" },
{ 110, "IDR_MAINFRAME" },
{ 111, "IDM_FILE" },
{ 112, "IDM_HELP" },
{ 113, "IDM_MENU_A" },
{ 114, "IDM_MENU_B" },
{ 115, "IDM_MENU_C" },
{ 116, "IDM_MENU_REFRESH" },
{ 1000, "IDC_CHECK_LOVE" },
{ 1001, "IDC_LIST_LOVE" },
{ 1002, "IDC_COMBO1" },
{ 1003, "IDC_COMBO_LOVE" },
{ 1004, "IDC_BUTT" },
{ 1005, "IDC_LIST" },
{ -1, "IDC_STATIC" }
});
}
static int unused = [](){ load_resource_ids(); return 1; }();
|
<reponame>sarvgraphic/client
myApp.controllerProvider.register('headerController', function($document, $scope, userService,$stateParams,$location){
$scope.isRequired = function( val ) {
return !validate.isEmpty(val);
};
$scope.emailExist = function(val){
return new Promise(function(resolve, reject){
if(val != undefined){
var option = {
data: {
email : val
}
};
userService.existEmail(option).then(function(resp){
if(resp.result){
resolve(true);
} else {
reject(false);
}
}).catch(function(){
reject(false);
});
} else {
resolve(true);
}
});
};
$scope.hasMinLength = function( val, min ) {
if(min == undefined){
min = 6;
}
var constraints = {
from: {
length: {
minimum: min
}
}
};
return !validate({ from: val }, constraints);
};
$scope.isEmail = function( emailValue ) {
var constraints = {
from: {
email: true
}
};
return !validate({ from: emailValue }, constraints);
};
$scope.acceptTerms = {check: false};
$scope.isLogin = false;
$scope.create = function() {
async.auto({
startLoading: function( cb ) {
// loader.show("#signUpForm");
cb(null, true);
},
createUser: [ 'startLoading', function( cb, result ) {
var option = {
data: {
scope: 'website',
email: $scope.email,
password: $<PASSWORD>
}
};
userService.signUp(option).then(function( resp ) {
if( resp.result ) {
cb(null, resp.data);
} else {
cb(result.error);
}
}).catch(function( err ) {
cb(err);
});
} ],
updateUserStorage: [ 'createUser', function( cb, result ) {
var localDB = new db('website', 'public');
localDB.create();
localDB.set('userObj', result.createUser.user);
localDB.set('isLogin', true);
localDB.set('token', result.createUser.token);
} ]
}, function( err, results ) {
});
};
$scope.signIn = {};
$scope.login = function() {
async.auto({
startLoading: function( cb ) {
cb(null, true);
},
loginUser: [ 'startLoading', function( cb ) {
var option = {
data: {
scope: 'website',
password: $<PASSWORD>,
identifier: $scope.signIn.identifier
}
};
userService.login(option).then(function( resp ) {
console.log("resp", resp);
if( resp.result ) {
cb(null, resp.data);
} else {
cb(resp.error);
}
}).catch(function( error ) {
cb(error);
});
} ],
updateUserStorage: [ 'loginUser', function( cb, result ) {
var token = _.cloneDeep(result.loginUser.token);
_.unset(result.loginUser, 'token');
var localDB = new db('website', 'public');
localDB.create();
localDB.set('userObj', result.loginUser);
localDB.set('isLogin', true);
localDB.set('identifier', $scope.signIn.identifier);
localDB.set('token', token);
if($scope.rememberMe){
localDB.set('rememberMe', true);
} else {
localDB.set('rememberMe', false);
}
cb(null, true);
} ]
}, function( err, results ) {
if( err ) {
console.log("err", err);
} else {
$scope.isLogin = true;
$('#login-form').modal("hide");
}
$scope.$apply();
});
};
//$scope.getImageCategory = function() {
// async.auto({
// startLoading: function( cb ) {
// //loader.show("#image-category-list");
// cb(null, true);
// },
// getCategory: [ 'startLoading', function( cb, result ) {
// var option = {
// data: {
// scope: 'website'
// }
// };
// imageCategoryService.get_image_category(option).then(function( resp ) {
// if( resp.result ) {
// cb(null, resp.data);
// } else {
// cb(result.error);
// }
// }).catch(function( err ) {
// cb(err);
// });
// } ]
// }, function( err, results ) {
//
// if(err){
// console.log(err)
// }else{
// $scope.imageCategory = results.getCategory;
// //loader.hide("#image-category-list");
// $timeout(function(){
// $scope.$apply();
// })
// }
// });
//};
//
//$scope.getImageCategory();
//$scope.searchItem = '';
//$scope.setSearchParam = function(data){
// if(data == 'allImages'){
// $scope.searchParam = 'All Images';
// }else{
// $scope.searchParam = data;
// }
//
//
//
//};
//$scope.setSearchParam('allImages');
//
//console.log("$stateParams : ", $stateParams)
//$scope.search = function(){
// console.log("searchItem : ", $scope.searchItem)
// console.log("searchParam : ", $scope.searchParam, "#/search/"+$scope.searchItem)
//
// var urlData = {
// type : $scope.searchParam,
// query : $scope.searchItem
// };
// $location.path("/search/"+JSON.stringify(urlData))
//
//
//}
});
|
require_relative '../spec_helper'
RSpec.describe FastXML do
def conv_to_io(hash)
fh = StringIO.new
FastXML.hash2xml(hash, output: fh)
fh.string
end
it 'has a version number' do
expect(FastXML::VERSION).not_to be nil
end
describe '#configure' do
%i[output method root version encoding utf8 indent canonical use_attr
content xml_decl keep_root doc buf_size force_array force_content
merge_text attr text trim cdata comm max_depth].each do |attribute|
it { should respond_to attribute }
end
end
describe '#hash2xml' do
it 'with default options' do
expect(FastXML.hash2xml({ node1: [ 'value1', { node2: 'value2' } ] }))
.to eq(%{#{XML_DECL}\n<root><node1>value1</node1><node1><node2>value2</node2></node1></root>})
end
it 'when canonical = true' do
expect(FastXML.hash2xml({ node3: 'value3', node1: 'value1', node2: 'value2' }, canonical: true))
.to eq(%{#{XML_DECL}\n<root><node1>value1</node1><node2>value2</node2><node3>value3</node3></root>})
end
it 'when indent = 2' do
expect(FastXML.hash2xml({ node1: [ 'value1', { node2: 'value2' } ] }, indent: 2))
.to eq(<<-EOT)
#{XML_DECL}
<root>
<node1>value1</node1>
<node1>
<node2>value2</node2>
</node1>
</root>
EOT
end
it 'with string, float and integer' do
expect(FastXML.hash2xml({ node1: [ 'string', 1.22, 1 ] }))
.to eq(%{#{XML_DECL}\n<root><node1>string</node1><node1>1.22</node1><node1>1</node1></root>})
end
it 'when need to quote tag name' do
expect(FastXML.hash2xml({ 1 => 'value1' }))
.to eq(%{#{XML_DECL}\n<root><_1>value1</_1></root>})
end
it 'with lambda that returns a string' do
expect(FastXML.hash2xml({ node1: -> { 'value1' } }))
.to eq(%{#{XML_DECL}\n<root><node1>value1</node1></root>})
end
it 'with lambda that returns an array' do
expect(FastXML.hash2xml({ node1: -> { [ 'value1' ] } }))
.to eq(%{#{XML_DECL}\n<root><node1>value1</node1></root>})
end
it 'when need to escape' do
expect(FastXML.hash2xml({ node1: "< > & \r"}))
.to eq(%{#{XML_DECL}\n<root><node1>< > & </node1></root>})
end
it 'when trim = false' do
expect(FastXML.hash2xml({ node: " \t\ntest " }, trim: false))
.to eq(%{#{XML_DECL}\n<root><node> \t\ntest </node></root>})
end
it 'when trim = true' do
expect(FastXML.hash2xml({ node: " \t\ntest " }, trim: true))
.to eq(%{#{XML_DECL}\n<root><node>test</node></root>})
end
it 'when use_attr = true' do
expect(FastXML.hash2xml(
{
node1: 'value1"',
node2: 'value2&',
node3: { node31: 'value31' },
node4: [ { node41: 'value41' }, { node42: 'value42' } ],
node5: [ 51, 52, { node53: 'value53' } ],
node6: {},
node7: []
},
use_attr: true,
canonical: true,
indent: 2
)).to eq(<<-EOT)
#{XML_DECL}
<root node1="value1"" node2="value2&">
<node3 node31="value31"/>
<node4 node41="value41"/>
<node4 node42="value42"/>
<node5>51</node5>
<node5>52</node5>
<node5 node53="value53"/>
<node6/>
</root>
EOT
end
it 'with content' do
expect(FastXML.hash2xml(
{
content: 'content&1',
node2: [ 21, {
node22: "value22 < > & \" \t \n \r",
content: "content < > & \r"
} ],
},
use_attr: true,
canonical: true,
indent: 2,
content: 'content'
)).to eq(<<-EOT)
#{XML_DECL}
<root>
content&1
<node2>21</node2>
<node2 node22="value22 < > & " 	 ">
content < > &
</node2>
</root>
EOT
end
it 'with using enumerate' do
expect(FastXML.hash2xml({ enum: 3.times }, indent: 2)).to eq(<<-EOT)
#{XML_DECL}
<root>
<enum>0</enum>
<enum>1</enum>
<enum>2</enum>
</root>
EOT
end
it 'with cyrillic characters' do
expect(FastXML.hash2xml({ ключ: 'значение' }))
.to eq(%{#{XML_DECL}\n<root><ключ>значение</ключ></root>})
end
it 'with filehandle output' do
expect(conv_to_io({ node1: 'value1' }))
.to eq(%{#{XML_DECL}\n<root><node1>value1</node1></root>})
end
end
end
|
package model;
import java.util.Objects;
import org.apache.commons.validator.routines.EmailValidator;
public class Companion {
public static int TAM_MAX_CPF = 14;
public static int TAM_MAX_RG = 15;
public static int TAM_MAX_NAME = 50;
public static int TAM_MAX_SEX = 10;
public static int TAM_MAX_KINSHIP = 20;
public static int TAM_MAX_EMAIL = 50;
public static int TAM_MAX_PHONE = 16;
public static int TAM_MAX_MOTHER_ID = 14;
private String cpf;
private String rg;
private String name;
private String sex;
private String kinship;
private String email;
private String phone;
private String motherCpf;
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getRg() {
return rg;
}
private static boolean trimmedRgIsValid(String trimmedRg) {
for (int i = 0; i < trimmedRg.length(); i++) {
char ch = trimmedRg.charAt(i);
if (!Character.isLetterOrDigit(ch) && ch != ' ') {
return false;
}
}
return true;
}
public static String trimRg(String rg) throws ValorInvalidoException {
String trimmedRg = rg.replaceAll(" +", "");
if (trimmedRgIsValid(trimmedRg)) {
return trimmedRg;
} else {
throw new ValorInvalidoException("RG do acompanhante inválido: ele deve "
+ "conter apenas letras, números e espaços.");
}
}
public void setRg(String rg) throws ValorInvalidoException {
this.rg = trimRg(rg);
}
public String getName() {
return name;
}
private static boolean trimmedNameIsValid(String trimmedName) {
for (int i = 0; i < trimmedName.length(); i++) {
char ch = trimmedName.charAt(i);
if (!Character.isLetter(ch) && ch != ' ') {
return false;
}
}
return true;
}
public static String trimName(String name) throws ValorInvalidoException {
String trimmedName = name.trim().replaceAll(" +", " ");
if (trimmedNameIsValid(trimmedName)) {
return trimmedName;
} else {
throw new ValorInvalidoException("Nome do acompanhante inválido: "
+ "ele deve conter apenas letras e espaços");
}
}
public void setName(String name) throws ValorInvalidoException {
this.name = trimName(name);
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getKinship() {
return kinship;
}
private static boolean trimmedKinshipIsValid(String trimmedKinship) {
for (int i = 0; i < trimmedKinship.length(); i++) {
char ch = trimmedKinship.charAt(i);
if (!Character.isLetter(ch) && ch != ' ') {
return false;
}
}
return true;
}
public static String trimKinship(String kinship) throws ValorInvalidoException {
String trimmedKinship = kinship.replaceAll(" +", " ");
if (trimmedKinshipIsValid(trimmedKinship)) {
return trimmedKinship;
} else {
throw new ValorInvalidoException("Parentesco do acompanhante inválido: "
+ "ele deve conter apenas letras e espaços");
}
}
public void setKinship(String kinship) throws ValorInvalidoException {
this.kinship = trimKinship(kinship);
}
public String getEmail() {
return email;
}
public static String trimEmail(String email) throws ValorInvalidoException {
String repairedEmail = email.trim();
if (EmailValidator.getInstance().isValid(email)) {
return repairedEmail;
} else {
throw new ValorInvalidoException("Email do acompanhante inválido.");
}
}
public void setEmail(String email) throws ValorInvalidoException {
this.email = trimEmail(email);
}
public String getPhone() {
return phone;
}
private static boolean trimmedPhoneIsValid(String trimmedPhone) {
return trimmedPhone.matches("(\\(?\\d{2}\\)?\\s)?(\\d{4,5}\\-\\d{4})");
}
public static String formatPhone(String phone) throws ValorInvalidoException {
String trimmedPhone = phone.trim().replaceAll(" +", " ");
if (trimmedPhoneIsValid(trimmedPhone)) {
String[] phoneParts = phone.split(" ");
if (phoneParts.length > 1 && phoneParts[0].charAt(0) != '(') {
StringBuilder formattedPhone = new StringBuilder();
formattedPhone.append("(");
formattedPhone.append(phoneParts[0]);
formattedPhone.append(")");
formattedPhone.append(" ");
formattedPhone.append(phoneParts[1]);
return formattedPhone.toString();
} else {
return trimmedPhone;
}
} else {
throw new ValorInvalidoException("Telefone do acompanhante "
+ "inválido. Digite-o em um destes formatos:\n(xx) "
+ "xxxxx-xxxx\n(xx) xxxx-xxxx\nxx xxxxx-xxxx\nxx "
+ "xxxx-xxxx\nxxxxx-xxxx\nxxxx-xxxx");
}
}
public void setPhone(String phone) throws ValorInvalidoException {
this.phone = formatPhone(phone);
}
public void setMotherCpf(String motherCpf) {
this.motherCpf = motherCpf;
}
public String getMotherCpf() {
return motherCpf;
}
@Override
public int hashCode() {
int hash = 3;
hash = 83 * hash + Objects.hashCode(this.cpf);
hash = 83 * hash + Objects.hashCode(this.rg);
hash = 83 * hash + Objects.hashCode(this.name);
hash = 83 * hash + Objects.hashCode(this.sex);
hash = 83 * hash + Objects.hashCode(this.kinship);
hash = 83 * hash + Objects.hashCode(this.email);
hash = 83 * hash + Objects.hashCode(this.phone);
hash = 83 * hash + Objects.hashCode(this.motherCpf);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Companion other = (Companion) obj;
if (!Objects.equals(this.cpf, other.cpf)) {
return false;
}
if (!Objects.equals(this.rg, other.rg)) {
return false;
}
if (!Objects.equals(this.name, other.name)) {
return false;
}
if (!Objects.equals(this.sex, other.sex)) {
return false;
}
if (!Objects.equals(this.kinship, other.kinship)) {
return false;
}
if (!Objects.equals(this.email, other.email)) {
return false;
}
if (!Objects.equals(this.phone, other.phone)) {
return false;
}
if (!Objects.equals(this.motherCpf, other.motherCpf)) {
return false;
}
return true;
}
}
|
<gh_stars>0
#ifndef _MR_GL_FRAMEBUFFER_H_
#define _MR_GL_FRAMEBUFFER_H_
#include <vector>
#include <mobrend/framebuffer.h>
#include <mobrend/opengl/texture.h>
namespace mr
{
class GlFramebuffer : public Framebuffer
{
public:
struct GlAttachment
{
union
{
unsigned int renderObjectId;
GlTexture *texture;
};
Framebuffer::AttachmentType type;
bool isRenderbufferObject;
};
public:
GlFramebuffer(Framebuffer::CreateParams &createParams);
virtual ~GlFramebuffer() override;
virtual void Bind(FramebufferUsage usage) override;
virtual void Unbind(FramebufferUsage usage) override;
virtual void Clear(FramebufferUsage usage) override;
virtual Texture *GetTextureAttachment(uint32_t index) override;
private:
GlAttachment CreateAttachment(const Framebuffer::Attachment &specifications);
private:
static unsigned int GetFramebufferUsage(mr::FramebufferUsage usage);
static unsigned int GetAttachment(mr::Framebuffer::AttachmentType attachmentType);
static unsigned int GetAttachmentInternalFormat(Framebuffer::AttachmentType attachmentType);
static unsigned int GetBufferBit(Framebuffer::AttachmentType type);
private:
unsigned int framebufferId;
uint32_t width, height;
std::vector<GlAttachment> attachments;
};
} // namespace mr
#endif
|
#!/bin/bash
SERVICE=chapolin
# RABBITMQ
echo "export RABBIT_URL=\"amqp://$RABBITMQ_DEFAULT_USER:$RABBITMQ_DEFAULT_PASS@rabbitmq:$RABBITMQ_PORT\"" > /etc/profile.d/rabbit.sh
echo "export RABBIT_MANAGEMENT_LOGIN=$RABBITMQ_DEFAULT_USER" >> /etc/profile.d/rabbit.sh
echo "export RABBIT_MANAGEMENT_PASSWORD=$RABBITMQ_DEFAULT_PASS" >> /etc/profile.d/rabbit.sh
echo "export RABBIT_MANAGEMENT_URL=http://rabbitmq:15672/api" >> /etc/profile.d/rabbit.sh
source /etc/profile.d/rabbit.sh
# StackStorm
while ! echo > /dev/tcp/stackstorm/443; do sleep 1; done
limit=60 # timeout
count=0
while :; do
count=$[count+1]
TOKEN="$(curl -k -s -X POST -u $ST2_USER:$ST2_PASSWORD -H'Accept: */*' -H'content-type: application/json' --data-binary '{}' https://stackstorm/auth/tokens | python -c 'import sys, json; print json.load(sys.stdin)["token"]')"
[ "x${TOKEN}" != "x" ] && break || sleep 1
[ ${count} -ge ${limit} ] && break
done
echo "export STACKSTORM_LOGIN=$ST2_USER" > /etc/profile.d/stackstorm.sh
echo "export STACKSTORM_PASSWORD=$ST2_PASSWORD" >> /etc/profile.d/stackstorm.sh
echo "export STACKSTORM_API_URL=https://stackstorm/api/v1" >> /etc/profile.d/stackstorm.sh
echo "export STACKSTORM_AUTH_URL=https://stackstorm/auth/v1" >> /etc/profile.d/stackstorm.sh
source /etc/profile.d/stackstorm.sh
yum install -y openssh-clients
ssh -i /mnt/id_rsa -o "StrictHostKeyChecking=no" stanley@stackstorm "/usr/bin/st2ctl reload --register-all"
# RPM
yum install -y /mnt/jdk/*.rpm
yum install -y /mnt/dists/pepe-${SERVICE}-*el7.noarch.rpm
# START
PID_FILE="/opt/logs/pepe/${SERVICE}/pepe.pid"
JAVA_VMS="-Xms1024m"
JAVA_VMX="-Xmx1024m"
su -l -s /bin/bash pepe <<EOF
source /opt/pepe/${SERVICE}/scripts/pepe.sh || true; \
/usr/bin/java \
-server \
-XX:+UseParallelGC \
-XX:+PerfDisableSharedMem \
-Djavax.net.ssl.keyStore=/etc/pki/java/cacerts \
-Djavax.net.ssl.trustStore=/etc/pki/java/cacerts \
-Dcom.sun.management.jmxremote.port=9999 \
-Dcom.sun.management.jmxremote.authenticate=false \
-Dcom.sun.management.jmxremote.ssl=false \
-Dcom.sun.management.jmxremote=true \
-Dlogging.config=/mnt/src/main/resources/log4j2.xml \
-DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector \
${JAVA_VMS} \
${JAVA_VMX} \
-jar /opt/pepe/${SERVICE}/lib/pepe.jar
EOF
#EOF
|
module load cmake/3
module load aocc/3.2
module load python/3.9
. venv/bin/activate
export CC=clang
export CXX=clang++
# only required for 'python setup.py develop'
# because `pip install -e .` doesn't seem to use these vars...?
export LDSHARED="$CC -L$(python3-config --prefix)/lib -shared"
export LDCXXSHARED="$CXX -L$(python3-config --prefix)/lib -shared"
|
SELECT (@rownum:=@rownum+1) AS row_number, t.*
FROM table_name t, (SELECT @rownum:=0) r
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.